SuperAPI AI 工具集

python-testing-patterns

编程与开发

查看项目

更新于 10-16 01:37

技能介绍

用途:该技能是一份 Python 测试策略指南,用于在编写单元测试、集成测试、搭建测试套件、实践 TDD、Mock 外部依赖、测试异步代码、实施属性测试以及配置 CI/CD 测试自动化时提供参考。

主要能力:涵盖测试发现规则(test_*.py 或 *test.py,函数以 test 开头)、fixture 及其作用域(function、class、module、session)与 conftest.py 共享、断言与 pytest.raises() 异常测试、测试组织(unit/、integration/、e2e/ 目录)、参数化、mock 与 patch、异步测试、属性测试(Hypothesis)、monkeypatch、覆盖率与集成测试等。内部按主题提供 references 参考文件,如 pytest-fundamentals.md、fixtures.md、parametrized-tests.md、mocking.md、async-testing.md、property-based-testing.md、monkeypatch.md、test-organization.md、coverage.md、integration-testing.md、best-practices.md。

使用方式:以 pytest 为运行入口,常用命令包括 pytest、pytest -v、pytest tests/unit/、pytest -k "test_user"、pytest -m unit;覆盖率命令如 pytest --cov=src --cov-report=term-missing、pytest --cov=src --cov-report=html、pytest --cov=src --cov-fail-under=80。可通过 pytest.ini 配置 testpaths、python_files、addopts、markers 等。典型模式包括 fixture 的 yield 清理、@pytest.mark.parametrize 多组用例、@patch 模拟外部调用、@pytest.mark.asyncio 异步测试、tmp_path 临时文件、自定义 marker 选择测试。

适用场景:Python 项目单元与集成测试、API/数据库/服务测试、异步与并发代码验证、TDD 流程、CI/CD 测试自动化、覆盖率度量与失败测试排查。

限制与注意事项:资料未提供安装命令、版本要求、收费信息或具体平台支持;文档提醒避免重复 setup、测试间顺序依赖、过度 mock、只测正常路径、测试过慢、忽略覆盖率盲区、命名含糊与缺少清理等常见问题。相关资源链接包括 pytest、unittest.mock、pytest-asyncio、pytest-cov、pytest-mock、Hypothesis、pytest-xdist、testcontainers 的官方文档。