import unittest
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
class TestQuickSort(unittest.TestCase):
def test_empty_array(self):
self.assertEqual(quick_sort([]), [])
def test_single_element_array(self):
self.assertEqual(quick_sort([5]), [5])
def test_sorted_array(self):
self.assertEqual(quick_sort([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
def test_reverse_sorted_array(self):
self.assertEqual(quick_sort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5])
def test_unsorted_array(self):
self.assertEqual(quick_sort([3, 7, 8, 5, 2, 1, 9, 4, 6]), [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_array_with_duplicates(self):
self.assertEqual(quick_sort([3, 7, 8, 5, 2, 1, 9, 4, 6, 3, 7]), [1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 9])
if __name__ == '__main__':
unittest.main()
테스트 설명:
test_empty_array
: 함수가 빈 배열을 올바르게 처리하는지 확인합니다.
test_single_element_array
: 함수가 단일 요소가 있는 배열을 올바르게 처리하는지 확인합니다.
test_sorted_array
: 함수가 이미 정렬된 배열을 올바르게 정렬하는지 확인합니다.
test_reverse_sorted_array
: 함수가 역순으로 정렬된 배열을 올바르게 정렬하는지 확인합니다.
test_unsorted_array
: 함수가 정렬되지 않은 배열을 올바르게 정렬하는지 확인합니다.
test_array_with_duplicates
: 함수가 중복된 요소가 있는 배열을 올바르게 처리하는지 확인합니다.
테스트 실행:
테스트를 실행하려면 코드를 Python 파일로 저장하고(예: test_quick_sort.py
) 명령줄에서 실행하세요.
python test_quick_sort.py
그러면 테스트가 실행되고 결과가 출력됩니다. 모든 테스트를 통과하면 다음과 비슷한 출력이 표시됩니다.
....
----------------------------------------------------------------------
Ran 6 tests in 0.001s
OK