Python 单元测试 pytest 与 Mock 使用指南
pytest 是 Python 最流行的测试框架,简洁且功能强大。
1. 基本测试
def add(a, b):
return a + b
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0运行 pytest 即可自动发现 test_*.py 文件。
2. 参数化测试
import pytest
@pytest.mark.parametrize('a,b,expected', [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0)
])
def test_add_param(a, b, expected):
assert add(a, b) == expected3. 使用 Mock 模拟依赖
from unittest.mock import Mock
def test_user_service():
mock_db = Mock()
mock_db.get_user.return_value = {'id': 1, 'name': 'Alice'}
service = UserService(mock_db)
assert service.get_user_name(1) == 'Alice'4. 夹具(Fixtures)
@pytest.fixture
def sample_data():
return {'name': 'test', 'value': 42}
def test_fixture(sample_data):
assert sample_data['value'] == 425. 覆盖率和报告
pytest --cov=. --cov-report=html单元测试是代码质量的基石,pytest 是首选工具。
