What pytest Does
- Auto-discovery — finds
test_*.pyfiles andtest_*functions - Assertion introspection — plain
assertwith detailed failure diffs - Fixtures — DI for test setup/teardown (function, class, module, session scope)
- Parametrize — run same test with multiple inputs
- Markers —
@pytest.mark.slow,@pytest.mark.skip, custom - Plugins — 1200+ on PyPI (pytest-cov, pytest-xdist, pytest-mock, pytest-asyncio)
- Conftest — shared fixtures across test directories
- Temporary directories —
tmp_pathfixture - Capture — stdout/stderr capture per test
- Parallel — via pytest-xdist
Comparison
| Framework | Style | Fixtures | Plugins |
|---|---|---|---|
| pytest | Function-based | DI (fixtures) | 1200+ |
| unittest | Class-based | setUp/tearDown | Limited |
| nose2 | Mixed | Limited | Some |
| doctest | Inline | None | None |
常见问题 FAQ
Q: pytest vs unittest? A: pytest 更简洁(无需 class)、assertion 更好(不用 assertEqual)、fixture DI 更强。Python 社区绝大多数新项目用 pytest。
Q: 怎么测异步代码?
A: pip install pytest-asyncio,然后 @pytest.mark.asyncio async def test_xxx() 即可 await 异步函数。
Q: fixture 的 scope? A: function(每个测试一次)、class、module、session(整个测试跑一次)。scope 越大,setup 开销越小但隔离越弱。
来源与致谢 Sources
- Docs: https://docs.pytest.org
- GitHub: https://github.com/pytest-dev/pytest
- License: MIT