系统学习 测试与质量四阶段学习路径:从单元与接口测试,到端到端、性能、契约和 CI 门禁

pytest 的安装、用例发现、断言、筛选、参数化、标记与 CI 集成入门

适用场景

已有 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 打乱顺序以暴露用例依赖。

常用示例

1. 最小可运行用例

# 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

2. 参数化与标记

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"

3. 精准重跑与 CI 报告

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 和失败日志。

易错点

相关条目

参考链接

读完自测

  1. pytest -k 和 pytest -m 分别按什么筛选用例?
  2. 为什么 async def 测试只加 @pytest.mark.asyncio 还不够?
  3. monkeypatch 修改导入后的名字时,应该补丁哪个位置?
答案
  1. -k 按用例名表达式筛选,-m 按已注册的标记筛选。
  2. 还需要安装并启用 pytest-asyncio,或在配置中设置 asyncio_mode = "auto"。
  3. 补丁使用该名字的模块,例如 app.DEBUG,而不是原始定义模块 config.DEBUG。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令