目录/第 64 章 · pytest 测试
第 64 章 / 70 · 工程 · 测试与第三方

pytest 测试

pytest / 断言 / fixture / parametrize / raises / 测试发现

先介绍1 个 demo6 个任务答案可展开

一、本章介绍

pytest 是最流行的 Python 测试框架:不用写类,直接定义以 test_ 开头的函数,用 assert 断言即可。fixture 准备测试数据,@pytest.mark.parametrize 一次跑多组参数,pytest.raises 验证是否抛出指定异常。

这一章用可以直接运行的方式讲解这些核心用法,所有示例都不依赖 pytest 命令(会展示等价的可运行结果),并说明真实项目中如何用 pytest 命令自动发现测试。

本章要点

  • test_ 命名约定与 assert
  • fixture 准备数据
  • parametrize 参数化
  • raises 验证异常
  • pytest 命令与测试发现
  • 直接调用测试函数验证

二、先看 demo

下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。

案例

先看一个完整例子

介绍 · 逐行注释
import pytest

# 1) 最简单的测试函数:assert 断言
def add(a, b):
    return a + b

def test_add():
    assert add(1, 2) == 3
    assert add(0, 0) == 0

# 直接调用测试函数(等价于 pytest 执行时的断言)
test_add()
print("assert 通过", True)

# 2) fixture:准备测试数据
@pytest.fixture
def sample():
    return [1, 2, 3]

def test_sum(sample):
    assert sum(sample) == 6

# fixture 函数本身被包装,用 __wrapped__ 拿到原函数手动调用
test_sum(sample.__wrapped__())
print("fixture 通过", True)

# 3) parametrize:多组参数(这里手动遍历等价效果)
cases = [(1, 1, 2), (2, 3, 5), (10, -10, 0)]
results = [add(a, b) == c for a, b, c in cases]
print("参数化全部通过", all(results))

# 4) raises:验证异常
def divide(a, b):
    return a / b

try:
    with pytest.raises(ZeroDivisionError):
        divide(1, 0)
    print("raises 通过", True)
except Exception as e:
    print("raises 失败", e)

# 5) 测试类名以 Test 开头
class TestMath:
    def test_mul(self):
        assert 2 * 3 == 6
TestMath().test_mul()
print("测试类通过", True)
运行结果
assert 通过 True
fixture 通过 True
参数化全部通过 True
raises 通过 True
测试类通过 True

要点:pytest 的核心就是 assert 断言 + test_ 前缀的自动发现。真实项目里运行 pytest 命令会自动收集并执行所有 test_ 函数;本页用直接调用函数的方式让你在无命令行环境下也能看懂断言过程。fixture 用 @pytest.fixture 定义,测试函数通过参数名注入。

三、6 个任务(自己先写,再看答案)

难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。

任务 1

assert 断言

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 test_ 命名约定与 assert、fixture 准备数据、parametrize 参数化。先对照要求自己写一遍,卡住了再展开答案。

写一个测试函数断言 2+3==5,并直接调用

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
def test_a():
    assert 2+3==5
test_a(); print("ok")
运行结果
ok
任务 2

测试多组数据

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 test_ 命名约定与 assert、fixture 准备数据、parametrize 参数化。先对照要求自己写一遍,卡住了再展开答案。

用 assert 循环验证 1~5 的平方

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
def f(n): return n*n
for i in range(1,6):
    assert f(i)==i*i
print("all ok")
运行结果
all ok
任务 3

fixture 准备数据

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 test_ 命名约定与 assert、fixture 准备数据、parametrize 参数化。先对照要求自己写一遍,卡住了再展开答案。

用 pytest.fixture 定义返回 [1,2,3] 并通过 __wrapped__ 调用

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import pytest
@pytest.fixture
def data(): return [1,2,3]
print(sum(data.__wrapped__()))
运行结果
6
任务 4

raises 验证异常

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 test_ 命名约定与 assert、fixture 准备数据、parametrize 参数化。先对照要求自己写一遍,卡住了再展开答案。

用 pytest.raises 验证 1/0 抛 ZeroDivisionError

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import pytest
with pytest.raises(ZeroDivisionError):
    1/0
print("ok")
运行结果
ok
任务 5

测试类

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 test_ 命名约定与 assert、fixture 准备数据、parametrize 参数化。先对照要求自己写一遍,卡住了再展开答案。

定义 TestX 类含 test_ 方法并直接调用

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
class TestX:
    def test_a(self): assert True
TestX().test_a(); print("ok")
运行结果
ok
任务 6

断言列表相等

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 test_ 命名约定与 assert、fixture 准备数据、parametrize 参数化。先对照要求自己写一遍,卡住了再展开答案。

用 assert 判断两个列表相等并打印结果

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
def test_l():
    assert [1,2]==[1,2]
test_l(); print("ok")
运行结果
ok