用途:pytest 是 Python 的测试框架,用于编写和运行单元测试与集成测试,支持从简单函数测试到复杂依赖场景。
主要能力:fixture 系统实现依赖注入,支持 function、class、module、session 等作用域及 setup/teardown;parametrize 支持数据驱动测试与自定义 ID、间接参数化;断言内省无需 self.assertEqual;内置 skip、skipif、xfail 等标记并支持自定义标记;插件生态包括 pytest-cov、pytest-asyncio、pytest-mock、pytest-django;支持 async/await 与 pytest-xdist 并行执行;具备测试发现、组织与详细失败报告。
使用方式:安装命令为 pip install pytest;常用插件组合 pip install pytest pytest-cov pytest-asyncio pytest-mock;FastAPI 场景 pip install pytest httpx pytest-asyncio;Django 场景 pip install pytest pytest-django;异步数据库 pip install pytest-asyncio aiosqlite。运行方式包括 pytest、pytest -v、pytest -s、pytest test_math.py、pytest test_math.py::test_add,以及按标记运行 pytest -m unit、pytest -m "not slow"。FastAPI 可用 TestClient 或 httpx.AsyncClient 配合 @pytest.mark.asyncio;Django 需在 pytest.ini 配置 DJANGO_SETTINGS_MODULE 并使用 @pytest.mark.django_db。
适用场景:Python 项目单元测试、API 接口测试、Django 模型与视图测试、异步代码测试、需要 mock 外部依赖的测试。
限制:资料未提供具体版本兼容性、性能基准、收费或价格信息;部分示例依赖外部模块与数据库环境,需自行准备。