生成快速排序单元测试

为给定 Python 函数生成单元测试。

在对 Cloud 控制台使用不同参数值时,或通过直接调用 Vertex AI API,您可以直接查询模型,并测试返回的结果。

提示自由格式

为以下 quick_sort 函数创建单元测试。

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)

响应

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()

测试说明

  1. test_empty_array:检查函数是否正确处理空数组。
  2. test_single_element_array:检查函数是否正确处理具有单个元素的数组。
  3. test_sorted_array:检查函数是否对已排序的数组正确排序。
  4. test_reverse_sorted_array:检查函数是否对反向排序的数组正确排序。
  5. test_unsorted_array:检查函数是否对未排序的数组正确排序。
  6. test_array_with_duplicates:检查函数是否正确处理具有重复元素的数组。

运行测试

如要运行测试,请将代码保存为 Python 文件(例如,test_quick_sort.py),然后从命令行运行该文件:

python test_quick_sort.py

系统将执行测试并输出结果。如果所有测试都通过,您应该会看到类似如下内容的输出:

....
----------------------------------------------------------------------
Ran 6 tests in 0.001s

OK
型号: gemini-1.5-flash-001
温度: 1
输出令牌数量上限: 8192
TopK: 40
TopP: 0.95