PYTHON MINI PROJECTS / CHAPTER 15
第 15 章 给代码写测试(pytest)CHAPTER 15 · 让改动有底气
目标:从三行测试开始,掌握参数化、fixture、异常测试,并借测试做一次重构。
本章内容与知识点
写好代码还要能证明它是对的。本章从三行 pytest 测试开始,掌握参数化一次测多组、fixture 准备数据、pytest.raises 测异常和 xfail 标记,最后借测试驱动一次重构。 动手前先在项目目录激活 venv 并 pip install pytest。
基础
三行测试pytest -q / -v指定测试
参数化
@parametrize多组数据
夹具
@fixturescopetmp_path
异常与重构
pytest.raisesxfail借测试重构
本章知识点覆盖对照
| 知识点 | 落在哪个项目 | 你要做到的程度 |
|---|---|---|
| 为什么写测试 / 三行测试 | 案例 | 会写 test_ 函数与 assert |
| pytest -q / -v / 指定测试 | 案例 | 会跑单个测试与查看详细输出 |
| @pytest.mark.parametrize | 任务 1 | 能把多组输入写成参数表 |
| @pytest.fixture / scope / tmp_path | 任务 2 | 会自己定义夹具并用内置夹具 |
| pytest.raises / xfail | 任务 3 | 会测异常与标记已知问题 |
| 借测试做重构 | 任务 3 | 知道测试全绿才敢改实现 |
案例
第一个 pytest(跟着敲)
介绍 · 三行测试新建目录,写两个文件。业务代码 calc.py:
# calc.py —— 被测试的业务代码
def add(a, b):
"""两数相加。"""
return a + b
def divide(a, b):
"""除数为 0 时抛 ValueError。"""
if b == 0:
raise ValueError("除数不能为 0")
return a / b
测试文件 test_calc.py(文件名必须以 test_ 开头):
# test_calc.py —— 测试文件
from calc import add
def test_add():
assert add(1, 2) == 3在 PowerShell 里运行:
pytest -q pytest -v # 看每个测试的名字 pytest test_calc.py::test_add # 只跑一个测试
. 1 passed in 0.01s
- 把
assert add(1, 2) == 4改成错的,跑一次,读一遍失败信息(左边是实际值,右边是期望值)。 - 理解:测试函数以
test_开头,用assert断言,pytest 自动发现。
任务 1
一次测好几组输入
自己敲 · @pytest.mark.parametrize解题提示:本题主要用到 为什么写测试、三行测试、pytest -q。先对照要求自己敲一遍,卡住了再展开答案。
写 test_param.py,测试案例 的 add 和 divide:
- 用
@pytest.mark.parametrize("a,b,expected", [...5组...])测 add,覆盖正数、负数、0、小数。 - 用参数化测 divide 的三组正常输入。
- 运行
pytest -v,确认每个参数组合算一个独立测试。 - 注释说明:参数化避免复制粘贴多份测试函数。
参考答案(先自己敲,再看)
# test_param.py —— 参数化测试
import pytest
from calc import add, divide
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0),
(2.5, 1.5, 4.0),
(100, -50, 50),
])
def test_add_many(a, b, expected):
assert add(a, b) == expected
@pytest.mark.parametrize("a, b, expected", [
(10, 2, 5.0),
(9, 3, 3.0),
(1, 4, 0.25),
])
def test_divide_ok(a, b, expected):
assert divide(a, b) == expected
# 一组参数就是一个独立测试:失败时能直接看到是哪组数据出问题。8 passed in 0.02s
任务 2
用 fixture 准备"现场"
自己敲 · @pytest.fixture / tmp_path解题提示:本题主要用到 @pytest.fixture、tmp_path。先对照要求自己敲一遍,卡住了再展开答案。
写 test_fixture.py,为"带文件的计算"准备数据:
- 用
@pytest.fixture定义numbers(),返回[1,2,3,4,5]。 - 写测试
test_sum(numbers)断言sum(numbers) == 15。 - 用 pytest 内置
tmp_pathfixture 写一个临时文件,再读回来断言内容一致。 - 用
@pytest.fixture(scope="module")定义一个只初始化一次的字典。 - 运行
pytest -v,观察 fixture 在测试前被执行。
参考答案(先自己敲,再看)
# test_fixture.py —— 夹具练习
import pytest
@pytest.fixture
def numbers():
return [1, 2, 3, 4, 5]
@pytest.fixture(scope="module")
def config():
return {"mode": "test", "retries": 3}
def test_sum(numbers):
assert sum(numbers) == 15
def test_len(numbers, config):
assert len(numbers) == 5
assert config["mode"] == "test"
def test_tmp_file(tmp_path):
p = tmp_path / "data.txt"
p.write_text("hello", encoding="utf-8")
assert p.read_text(encoding="utf-8") == "hello"3 passed in 0.03s
tmp_path 是 pytest 自带的夹具,会自动创建临时目录并在测试后清理,非常适合文件相关测试。任务 3
测"应该报错"的情况 + 借测试重构
自己敲 · pytest.raises / 重构解题提示:本题主要用到 pytest.raises、重构。先对照要求自己敲一遍,卡住了再展开答案。
写 test_raises.py:
- 用
with pytest.raises(ValueError):断言divide(1, 0)会抛错。 - 用
excinfo.value检查异常消息里含"除数"两个字。 - 写
@pytest.mark.xfail标记一个"已知还没实现"的功能测试。 - 重构
calc.py的divide:把校验抽成check_nonzero(b),重跑全部测试确保不退化。 - 注释总结:测试是重构的安全网。
参考答案(先自己敲,再看)
# test_raises.py —— 异常测试
import pytest
from calc import divide
def test_divide_by_zero():
with pytest.raises(ValueError) as excinfo:
divide(1, 0)
assert "除数" in str(excinfo.value)
@pytest.mark.xfail(reason="乘法功能还没实现")
def test_multiply_not_ready():
from calc import multiply
assert multiply(2, 3) == 6
# 重构后的 calc.py 片段:
# def check_nonzero(b):
# if b == 0:
# raise ValueError("除数不能为 0")
#
# def divide(a, b):
# check_nonzero(b)
# return a / b
# 测试全绿才说明重构没有改变外部行为。1 passed, 1 xfailed in 0.02s
任务 4
参数化测试:一次测多组输入
自己敲 · @pytest.mark.parametrize解题提示:本题主要用到 parametrize、assert、pytest -q。先对照要求自己敲一遍,卡住了再展开答案。
写一个 test_parametrize.py,用 @pytest.mark.parametrize 一次测试多组输入。
- 定义被测函数
def is_even(n): return n % 2 == 0。 - 用
@pytest.mark.parametrize("n, want", [(0, True), (3, False), (8, True)])提供三组数据。 - 测试函数里
assert is_even(n) == want。 - 运行
pytest -q test_parametrize.py,看到 3 个用例全部通过。
提示:参数化让同一段测试逻辑跑多组数据,避免复制粘贴三份测试。
关于输出:这是 pytest 命令的输出(不是 Python 直接运行的结果),需先 pip install pytest。
参考答案(先自己敲,再看)
# test_parametrize.py —— 参数化测试
import pytest
def is_even(n):
return n % 2 == 0
@pytest.mark.parametrize("n, want", [
(0, True),
(3, False),
(8, True),
])
def test_is_even(n, want):
assert is_even(n) == want... [100%] 3 passed in 0.01s
任务 5
用fixture准备数据
自己敲 · @pytest.fixture解题提示:本题主要用到 fixture、assert、pytest -q。先对照要求自己敲一遍,卡住了再展开答案。
写一个 test_fixture.py,用 fixture 给多个测试准备同一份数据。
- 定义
@pytest.fixture装饰的scores(),返回[78, 92, 88]。 - 写两个测试:一个断言
len(scores) == 3,一个断言max(scores) == 92。 - 测试函数把
scores作为参数接收。 - 运行
pytest -q test_fixture.py。
提示:fixture 是"可复用的测试准备",pytest 会自动把返回值传给同名参数。
关于输出:这是 pytest 命令的输出,需先安装 pytest。
参考答案(先自己敲,再看)
# test_fixture.py —— 用 fixture 准备数据
import pytest
@pytest.fixture
def scores():
return [78, 92, 88]
def test_count(scores):
assert len(scores) == 3
def test_max(scores):
assert max(scores) == 92.. [100%] 2 passed in 0.01s