ac8444bb41
- find_max_linear: 线性扫描 O(n)(原 find_max 重命名+alias兼容) - find_max_bubble: 冒泡排序 O(n²) - find_max_quickselect: 快速选择 partition O(n) avg - 37 个测试(7×3 参数化 + 9 一致性 + 7 原有)
64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
"""三种排序算法找最大值 — 单元测试"""
|
|
|
|
import pytest
|
|
|
|
from src.algorithms.find_max_linear import find_max_linear
|
|
from src.algorithms.find_max_bubble import find_max_bubble
|
|
from src.algorithms.find_max_quickselect import find_max_quickselect
|
|
|
|
ALL_ALGOS = [find_max_linear, find_max_bubble, find_max_quickselect]
|
|
|
|
|
|
# ── 通用测试(每种算法都跑) ──
|
|
|
|
@pytest.mark.parametrize("algo", ALL_ALGOS, ids=["linear", "bubble", "quickselect"])
|
|
class TestAllAlgorithms:
|
|
def test_normal_list(self, algo):
|
|
assert algo([3, 1, 4, 1, 5, 9, 2, 6]) == 9
|
|
|
|
def test_empty_list(self, algo):
|
|
assert algo([]) is None
|
|
|
|
def test_single_element(self, algo):
|
|
assert algo([42]) == 42
|
|
|
|
def test_negative_numbers(self, algo):
|
|
assert algo([-5, -1, -10, -3]) == -1
|
|
|
|
def test_floats(self, algo):
|
|
assert algo([1.5, 2.7, 0.3, 3.14]) == 3.14
|
|
|
|
def test_mixed_int_float(self, algo):
|
|
assert algo([1, 2.5, 3, 0.1]) == 3
|
|
|
|
def test_duplicate_max(self, algo):
|
|
assert algo([7, 7, 7]) == 7
|
|
|
|
|
|
# ── 一致性测试(同输入三法结果相同) ──
|
|
|
|
class TestConsistency:
|
|
@pytest.mark.parametrize("nums", [
|
|
[3, 1, 4, 1, 5, 9, 2, 6],
|
|
[-5, -1, -10, -3],
|
|
[1.5, 2.7, 0.3, 3.14],
|
|
[42],
|
|
[7, 7, 7],
|
|
[0, -0.0, 0.0],
|
|
[100, 200, 50, 150, 75],
|
|
])
|
|
def test_three_algorithms_same_result(self, nums):
|
|
results = [algo(nums) for algo in ALL_ALGOS]
|
|
assert all(r == results[0] for r in results), f"Inconsistent: {results}"
|
|
|
|
def test_empty_consistency(self):
|
|
results = [algo([]) for algo in ALL_ALGOS]
|
|
assert all(r is None for r in results)
|
|
|
|
def test_does_not_mutate_input(self):
|
|
original = [3, 1, 4, 1, 5, 9, 2, 6]
|
|
for algo in ALL_ALGOS:
|
|
nums = list(original)
|
|
algo(nums)
|
|
assert nums == original, f"{algo.__name__} mutated input"
|