文档
Pytest Hello World:第一个测试用例
目标
编写一个简单的数学函数,并用 pytest 测试它的各种情况,包括正常输入、边界值和异常。
完整代码
# math_utils.py — 被测试的模块
def divide(a: float, b: float) -> float:
"""安全除法,分母为零时抛出 ValueError"""
if b == 0:
raise ValueError("除数不能为零")
return a / b
def is_prime(n: int) -> bool:
"""判断是否为质数"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# test_math_utils.py — 测试文件(必须以 test_ 开头)
import pytest
from math_utils import divide, is_prime
# === 测试 divide 函数 ===
def test_divide_normal():
assert divide(10, 2) == 5.0
assert divide(7, 2) == 3.5
def test_divide_by_zero():
with pytest.raises(ValueError, match="除数不能为零"):
divide(1, 0)
# === 测试 is_prime 函数(参数化) ===
@pytest.mark.parametrize("n, expected", [
(1, False),
(2, True),
(3, True),
(4, False),
(17, True),
(100, False),
(97, True),
])
def test_is_prime(n, expected):
assert is_prime(n) == expected
运行步骤
pytest test_math_utils.py -v
预期输出
test_math_utils.py::test_divide_normal PASSED
test_math_utils.py::test_divide_by_zero PASSED
test_math_utils.py::test_is_prime[1-False] PASSED
test_math_utils.py::test_is_prime[2-True] PASSED
test_math_utils.py::test_is_prime[3-True] PASSED
test_math_utils.py::test_is_prime[4-False] PASSED
test_math_utils.py::test_is_prime[17-True] PASSED
test_math_utils.py::test_is_prime[100-False] PASSED
test_math_utils.py::test_is_prime[97-True] PASSED
======= 9 passed in 0.05s =======