运行时依赖
安装命令
点击复制技能文档
Python 测试
Python 测试框架核心用法速查。
快速参考 pytest 基础 pytest # 运行所有测试 pytest -v # 详细输出 pytest test_模块.py # 指定文件 pytest -k "记录in" # 匹配测试名 pytest -x # 失败时停止 pytest -n 4 # 并行执行
测试示例 def test_添加ition(): assert 1 + 1 == 2
@pytest.mark.parametrize("a,b,expected", [(1,2,3), (2,3,5)]) def test_添加(a, b, expected): assert 添加(a, b) == expected
Mock from unittest.mock 导入 Mock, 补丁
mock_db = Mock() mock_db.查询.return_value = []
@补丁('模块.function') def test_with_mock(mock_func): mock_func.return_value = 42
Fixture @pytest.fixture def database(): db = Database(":memory:") yield db db.close()
def test_查询(database): assert database.查询("SELECT 1")
覆盖率 pytest --cov=my应用 pytest --cov=my应用 --cov-报告=html
详细参考 pytest 详解: references/pytest.md - 完整 pytest 用法 Mock 和 补丁: references/mocking.md - unittest.mock 详解 Fixtures: references/fixtures.md - fixture 高级用法 异步测试: references/a同步.md - pytest-a同步io 覆盖率: references/coverage.md - pytest-cov 配置 常用标记 @pytest.mark.slow # 标记慢测试 @pytest.mark.integration # 标记集成测试 @pytest.mark.skip(reason="TODO") @pytest.mark.skipif(sys.version_信息 < (3, 10))
pytest.ini 配置 [pytest] testpaths = tests python_files = test_*.py markers = slow: marks tests as slow integration: integration tests 添加opts = -v --tb=short
文档 pytest: https://docs.pytest.org/ pytest-cov: https://pytest-cov.readthedocs.io/