Create unit tests for the following quick_sort function.
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)
Response
Of course. Here are unit tests for the quick_sort function using Python's built-in unittest framework.
The Code to Test
First, let's place the function in a file, for example, sorter.py .
sorter.py
def quick_sort(arr):
"""
Sorts a list of comparable elements using the Quick Sort algorithm.
Note: This implementation is simple for demonstration and not optimized.
It creates new lists in memory for partitions.
"""
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)
The Unit Tests
Now, we'll create a separate file for our tests, for example, test_sorter.py . This file will import the quick_sort function and define a series of test cases to validate its behavior.
The tests cover:
- Edge Cases: Empty lists and single-element lists.
- Standard Cases: A typical unsorted list with positive integers.
- Data Variations: Lists with negative numbers, floats, and duplicates.
- Challenging Cases: Lists that are already sorted or in reverse order.
- Immutability: A test to ensure the original list is not modified.
- Other Data Types: A test with strings to ensure it works with other comparable types.
test_sorter.py
import unittest
from sorter import quick_sort
class TestQuickSort(unittest.TestCase):
def test_empty_list(self):
"""Test sorting an empty list, which should result in an empty list."""
self.assertEqual(quick_sort([]), [])
def test_single_element_list(self):
"""Test sorting a list with a single element."""
self.assertEqual(quick_sort([42]), [42])
def test_already_sorted_list(self):
"""Test a list that is already sorted."""
self.assertEqual(quick_sort([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
def test_reverse_sorted_list(self):
"""Test a list that is sorted in reverse order."""
self.assertEqual(quick_sort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5])
def test_random_integers(self):
"""Test a typical unsorted list of integers."""
arr = [3, 6, 8, 10, 1, 2, 1]
self.assertEqual(quick_sort(arr), [1, 1, 2, 3, 6, 8, 10])
def test_with_negative_numbers(self):
"""Test a list containing negative numbers."""
arr = [-3, 6, -8, 10, 1, -2, 0]
self.assertEqual(quick_sort(arr), [-8, -3, -2, 0, 1, 6, 10])
def test_with_duplicates(self):
"""Test a list with duplicate elements."""
arr = [5, 2, 8, 2, 5, 1, 8]
self.assertEqual(quick_sort(arr), [1, 2, 2, 5, 5, 8, 8])
def test_all_elements_are_the_same(self):
"""Test a list where all elements are identical."""
self.assertEqual(quick_sort([7, 7, 7, 7, 7]), [7, 7, 7, 7, 7])
def test_with_floats(self):
"""Test a list containing floating-point numbers."""
arr = [3.14, 1.0, -2.5, 0.5, 2.71]
self.assertEqual(quick_sort(arr), [-2.5, 0.5, 1.0, 2.71, 3.14])
def test_with_strings(self):
"""Test a list of strings."""
arr = ["banana", "apple", "cherry", "date", "apple"]
self.assertEqual(quick_sort(arr), ["apple", "apple", "banana", "cherry", "date"])
def test_original_list_is_unchanged(self):
"""Test that the function does not modify the original list (immutability)."""
original_list = [3, 1, 4, 1, 5, 9]
# Create a copy to compare against after the function call
list_copy = original_list[:]
quick_sort(original_list)
# Verify the original list is the same as its copy
self.assertEqual(original_list, list_copy)
# This allows the test to be run from the command line
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
How to Run the Tests
- Save the two files (
sorter.py and test_sorter.py ) in the same directory.
- Open your terminal or command prompt and navigate to that directory.
Run the test file using the following command:
python -m unittest test_sorter.py
Or, for more detailed output:
python -m unittest -v test_sorter.py
Expected Output
If all tests pass, you will see output similar to this:
............
----------------------------------------------------------------------
Ran 12 tests in 0.001s
OK
Each dot (. ) represents a test that passed successfully. If a test fails, unittest will provide a detailed traceback showing the assertion that failed, the expected value, and the actual value received from the function.
|
Model: |
gemini-2.5-pro |
Temperature: |
0.2 |
Max output tokens: |
8192 |
TopK: |
40.0 |
TopP: |
0.95 |
|