已有 Python 函数或服务,想用最少的样板代码写单元测试、接口测试和回归测试。pytest 能直接运行普通 assert,支持按名称、标记和失败历史筛选用例,也适合放进 GitHub Actions、GitLab CI 等流水线。
python -m pip install -U pytest
python -m pytest --version
优先用 python -m pytest,它会使用当前解释器,避免 pytest 命令指向另一个虚拟环境。默认发现规则是:文件名为 test_*.py 或 *_test.py,函数名为 test_*,类名为 Test* 且不能有 __init__,类中的方法名为 test_*。
项目根目录可用 pyproject.toml 固定范围和标记:
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
markers = [
"slow: 运行时间较长的用例",
"integration: 需要外部服务的用例",
]
测试里直接写 assert,失败时 pytest 会重写断言并展示中间值。常用辅助函数有 pytest.raises、pytest.approx 和 pytest.warns。
常用命令行参数:-q 精简输出,-v 显示每个用例,-x 第一个失败就停止,-k "login and not slow" 按用例名表达式筛选,-m "not slow" 按标记筛选,--lf 只重跑上次失败的用例,--ff 先跑失败用例,--co 只收集不执行。
@pytest.mark.parametrize 把一组输入展开成多个独立用例;多个参数化装饰器会做笛卡尔积。自定义标记要先注册,否则会出现 PytestUnknownMarkWarning。
常用插件:pytest-cov 统计覆盖率,pytest-xdist 用 -n auto 并行执行,pytest-asyncio 测试 async def,pytest-mock 提供 mocker,pytest-randomly 打乱顺序以暴露用例依赖。
# test_math.py
def add(a, b):
return a + b
def test_add():
assert add(1, 2) == 3
def test_add_negative():
assert add(-1, 1) == 0
python -m pytest -q test_math.py
import pytest
@pytest.mark.parametrize("raw, expected", [
(" 42 ", 42),
("0", 0),
("-7", -7),
])
def test_parse_int(raw, expected):
assert int(raw.strip()) == expected
@pytest.mark.slow
def test_large_payload():
assert len(list(range(100_000))) == 100_000
python -m pytest -q -k "parse and not large"
python -m pytest -q -m "not slow"
python -m pytest -q --lf
python -m pytest -q --maxfail=1 \
--junitxml=reports/junit.xml \
--cov=src --cov-report=xml
--junitxml 供 CI 展示用例结果,--cov 需要先安装 pytest-cov;流水线里至少保留 JUnit XML 和失败日志。
session 后只初始化一次;被多个用例修改的可变对象会互相污染。共享连接可以放宽作用域,共享数据应每次重置或改用 factory。async def test_xxx 而不安装和标记 pytest-asyncio,用例可能被跳过或直接报错;也可在配置里设置 asyncio_mode = "auto"。from config import DEBUG 之后,DEBUG 已绑定到当前模块;要打补丁的目标应是使用处,例如 app.DEBUG,而不是 config.DEBUG。test_*.py 则不会被收集。-k 不是正则:它按子串和 and、or、not 表达式匹配,写复杂正则不会生效。--lf 掩盖全量问题:本地重跑失败用例很快,但 CI 仍应跑全量;缓存目录 .pytest_cache 缺失时会退化为全量。-n auto 后 fixture 不共享:每个 worker 有独立进程,session fixture 也会各建一份;数据库和端口要按 worker 隔离。python -O 运行时 assert 会被移除,测试命令不要加 -O。pytest -k 和 pytest -m 分别按什么筛选用例?async def 测试只加 @pytest.mark.asyncio 还不够?monkeypatch 修改导入后的名字时,应该补丁哪个位置?-k 按用例名表达式筛选,-m 按已注册的标记筛选。pytest-asyncio,或在配置中设置 asyncio_mode = "auto"。app.DEBUG,而不是原始定义模块 config.DEBUG。
小程序版
微信扫码,随时查命令