01. pytest 基础
pytest 是 Python 最流行的测试框架,语法简洁,功能强大。测试文件和函数以 test_ 开头。
python
# test_calculator.py
from calculator import add, divide
import pytest
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_divide():
assert divide(10, 2) == 5.0
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(10, 0)02. Fixture 与参数化
Fixture 用于准备测试环境和数据。参数化测试可以用一组用例测试多种输入。
python
import pytest
@pytest.fixture
def sample_data():
return {"name": "Alice", "age": 25}
def test_data_name(sample_data):
assert sample_data["name"] == "Alice"
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_double(input, expected):
assert input * 2 == expected知识测验
第 1/5 题正确 0
pytest 测试文件的命名规则是什么?