单元测试 pytest
测试能在改代码时及时发现问题。pytest 是最流行的 Python 测试框架,写法简单。
$ pip install pytest
被测试的代码 calc.py:
def divide(a, b):
if b == 0:
raise ValueError("除数不能为 0")
return a / b
测试文件 test_calc.py(文件名以 test_ 开头):
import pytest
from calc import divide
def test_divide():
assert divide(10, 2) == 5
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(1, 0)
运行:
$ pytest -q
.. [100%]
2 passed in 0.01s
参数化
同一个逻辑测试多组数据:
@pytest.mark.parametrize("a, b, expected", [
(6, 3, 2),
(1, 4, 0.25),
(-8, 2, -4),
])
def test_divide_cases(a, b, expected):
assert divide(a, b) == expected
fixture
用 fixture 准备测试数据,多个测试可以共用:
@pytest.fixture
def sample_users():
return [{"name": "a", "age": 18}, {"name": "b", "age": 30}]
def test_adults(sample_users):
assert len([u for u in sample_users if u["age"] >= 18]) == 2练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 为函数 is_leap(year) 编写参数化测试,覆盖 1900、2000、2024、2025 四种情况。
查看参考答案
import pytest
def is_leap(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
@pytest.mark.parametrize("year, expected", [
(1900, False), (2000, True), (2024, True), (2025, False),
])
def test_is_leap(year, expected):
assert is_leap(year) == expected