2

## 【python內建模組- unitest】單元測試

``````import unittest

class Test(unittest.TestCase):

def test_method1(self):
pass

def test_method2(self):
pass

...

if __name__ == '__main__':
unittest.main()
``````

# 自己寫的例子

``````import unittest
import random

def partition(arr, front, end):
pivot = arr[end]
idx = front-1
for j in range(front,end):
if arr[j]<pivot:
idx+=1
arr[idx],arr[j]=arr[j],arr[idx]
arr[idx+1],arr[end]=arr[end],arr[idx+1]
return idx+1;

# 原地修改陣列
def quickSort(arr, front=0, end=None):
if end==None:
end=len(arr)-1
if front<end:
pivot = partition(arr, front, end);
quickSort(arr, front, pivot-1);
quickSort(arr, pivot+1, end);
return arr

class Test(unittest.TestCase):

def test_fixDatas(self):
arr = [52,30,6,20,13]
self.assertEqual(quickSort(arr), [6,13,20,30,52])

def test_quickSort(self):
for i in range(100):
arr = [random.randint(-10000,10000) for i in range(1000)]
copy = arr[:]
self.assertEqual(quickSort(arr), sorted(copy))

if __name__ == '__main__':
unittest.main()
``````

assertEqual()是一種斷言，