如何为新人写 pytest 入门模板并自动化检查?
解读
面试官想知道两件事:
- 你能否把“零样板代码”的 pytest 真正落地成“新人 5 分钟能跑通”的模板,而不是丢一堆官方链接。
- 你能否把“质量门禁”前移,让本地+CI 都能自动拦截不合格用例,体现工程化思维。
国内真实场景下,新人常踩的坑包括:不会装包、路径含中文、断言乱用 print、fixtures 与 mark 混用、覆盖率虚高、CI 镜像慢。模板必须一次性解决这些痛点,并给出可复制的“自检命令”,让 HR/面试官当场能跑。
知识点
- 最小可运行结构:遵循
<project>/tests/目录规范、conftest.py集中管理 fixtures、__init__.py留空避免包名冲突。 - 依赖锁定:国内源加速 +
requirements-test.txt+python -m pip install -r …保证可复现。 - 零样板断言:原生
assert即可,但禁止裸print,统一使用capsys或caplog检查。 - 参数化与标记:用
@pytest.mark.parametrize与自定义 mark(如slow)做分级,配套pytest.ini过滤。 - 覆盖率真门槛:
pytest-cov设置--cov-fail-under=80,且通过.coveragercOmit 掉tests/目录与venv/防止虚高。 - 自动化检查脚本:
- 本地:
tox单命令跑 3 套环境(lint、test、cov)。 - CI:GitHub Actions / Gitee Go 国内镜像,缓存
~/.cache/pip,job 并行。
- 本地:
- 统一代码风格:
black、isort、flake8在pre-commit阶段强制,钩子失败直接阻断提交。 - 自描述文档:
README.md给出“三步跑通”命令,并嵌入徽章(CI/cov),让面试官一眼看到结果。
答案
下面给出可直接克隆的“pytest-boilerplate”最小仓库,新人按顺序执行三条命令即可通过自动化检查。
-
目录结构
project/
├─ src/
│ └─ calculator.py
├─ tests/
│ ├─ init.py
│ ├─ conftest.py
│ ├─ test_calculator.py
│ └─ test_with_fixture.py
├─ .github/workflows/ci.yml
├─ tox.ini
├─ pytest.ini
├─ .coveragerc
├─ .pre-commit-config.yaml
├─ requirements-test.txt
└─ README.md -
核心文件示例
src/calculator.py
def add(a: int, b: int) -> int:
return a + b
tests/test_calculator.py
import pytest
from src.calculator import add
@pytest.mark.parametrize("x,y,expected", [(1, 2, 3), (0, 0, 0), (-1, 1, 0)])
def test_add(x, y, expected):
assert add(x, y) == expected
tests/conftest.py
import pytest
@pytest.fixture(scope="session")
def db_conn():
# 模拟重量级资源
yield "fake_connection"
print("teardown db")
pytest.ini
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts = -ra -q --strict-markers --cov=src --cov-report=term-missing
markers =
slow: marks tests as slow (deselect with '-m "not slow"')
.coveragerc
[run]
source = src
omit = */tests/*,*/venv/*,*/site-packages/*
[report]
fail_under = 80
tox.ini(国内源加速)
[tox]
envlist = py38,lint
[testenv]
deps = -rrequirements-test.txt
commands = pytest {posargs}
[testenv:lint]
deps = pre-commit
commands = pre-commit run --all-files
.pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
.github/workflows/ci.yml(Gitee Go 只需换触发器)
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: "3.8"
cache: pip
- run: pip install tox
- run: tox
README.md(关键三步)
## 三步跑通
1. git clone <repo>
2. python -m pip install -r requirements-test.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
3. tox
如果看到绿色 PASSED 与 coverage ≥ 80%,即通过。
- 自动化检查命令
本地:tox# 同时跑测试、覆盖率、lint
CI:推送后自动触发,PR 页面实时展示结果,未达 80% 或 lint 失败则红叉阻断合并。
拓展思考
- 分层测试:模板可再拆
tests/unit/与tests/integration/目录,在tox中定义posargs实现tox -e integration只跑集成用例,避免本地耗时。 - 动态生成测试数据:结合
hypothesis做基于属性的测试,把@given与 fixtures 混用,考察候选人对“测试可维护性”的理解。 - 并行与资源隔离:使用
pytest-xdist的--numprocesses=auto并配合filelock实现 session 级共享数据库容器,既提速又避免冲突。 - 质量门禁再升级:把
mypy --strict、bandit、safety check也纳入tox的quality环境,形成“静态+动态+安全”三位一体,面试时可展示徽章墙,瞬间拉开与普通候选人的差距。