测试
- 作者仓库星标 2,412
- 许可证 NOASSERTION
- 作者仓库 debugpy
- 领域
- 文档
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 94 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @microsoft · NOASSERTION
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 即装即用
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
# Skill: pytest
Best practices for writing and organizing tests with pytest including fixtures, parametrize, and plugins.
## When to Use
Apply this skill when writing and organizing tests with pytest — fixtures, parametrize, markers, plugins, and test structure.
## Test Organization
- Place tests in a `tests/` directory mirroring the source structure.
- Name test files `test_<module>.py` and test functions `test_<behavior>()`.
- Group related tests in classes only when they share fixtures/setup.
## Fixtures
- Define fixtures at the narrowest scope needed (`function` > `class` > `module` > `session`).
- Use `conftest.py` for shared fixtures; put it at the appropriate directory level.
- Prefer factory fixtures over complex fixture inheritance.
- Use `yield` fixtures for setup/teardown; prefer `tmp_path` over `tempfile`.
## Parametrize
- Use `@pytest.mark.parametrize` for data-driven tests with multiple inputs.
- Give test IDs (`ids=...`) for readable test output.
- Combine `parametrize` with fixtures for cross-product testing.
## Assertions
- Use plain `assert` statements — pytest rewrites them for clear failure messages.
- Use `pytest.raises(ExceptionType, match=...)` for exception testing.
- Use `pytest.approx()` for floating-point comparisons.
## Plugins
- Common plugins: `pytest-cov`, `pytest-mock`, `pytest-asyncio`, `pytest-xdist`, `pytest-timeout`.
- Use `pytest-mock`'s `mocker` fixture over raw `unittest.mock.patch`.
## Pitfalls
- Don't use `session`-scoped fixtures for mutable state.
- Don't assert on implementation details — test observable behavior.
- Avoid test interdependence; each test should be runnable in isolation.
章节与文件索引
按说明文件中的顺序排列。
测试组织
赛程
参数化
断言
插件
文件/命令 -> tests/ · test_<module>.py · test_<behavior>() · function · class · module · session · conftest.py
内容校验值 -> b1c1f8e689f4
当前原文的自动摘译,尚未人工审校。
测试组织
将测试放在镜像源结构的
tests/目录中。将测试文件命名为test_<module>.py,将测试函数命名为test_<behavior>()。仅当共享固定装置/设置时,才将相关测试分组到类中。赛程
在所需的最窄范围内定义灯具 (
function>class>module>session)。使用conftest.py共享灯具;将其放在适当的目录级别。优先选择工厂固定装置而不是复杂的固定装置继承。使用yield夹具进行安装/拆卸;更喜欢tmp_path而不是tempfile。参数化
使用
@pytest.mark.parametrize进行具有多个输入的数据驱动测试。提供测试 ID (ids=...) 以获取可读的测试输出。将parametrize与夹具结合起来进行跨产品测试。断言
使用简单的
assert语句——pytest重写它们以获得清晰的失败消息。使用pytest.raises(ExceptionType, match=...)进行异常测试。使用pytest.approx()进行浮点比较。插件
常用插件:
pytest-cov、pytest-mock、pytest-asyncio、pytest-xdist、pytest-timeout。在原始的unittest.mock.patch上使用pytest-mock的mocker夹具。