测试思维与pytest基础

Python 自动化测试 · 第1篇 · 基础入门

写代码不写测试,就像开车不系安全带——平时觉得没事,出事就是大事。这篇文章带你建立测试思维,掌握pytest这个Python最流行的测试框架,从"不想写测试"到"停不下来"。

📋 本文目录

01 为什么要做测试?Bug修复成本曲线
02 测试金字塔:单元、集成、端到端
03 unittest vs pytest 对比
04 pytest安装与基础用法
05 assert断言与参数化测试
06 fixture与测试组织
07 实战:计算器模块完整单元测试

一、为什么要做测试?

很多初学者觉得写测试是"浪费时间"——代码能跑不就行了吗?但现实是,没有测试的代码就像没有质检的产品,你不知道它什么时候会出问题。

软件工程中有一个经典结论:Bug发现得越晚,修复成本越高。IBM的研究报告显示:

📊 Bug修复成本(相对于需求阶段)

需求阶段
1x
设计阶段
5x
编码阶段
10x
测试阶段
20x
上线之后
100x 💀

上线后修复Bug的成本是需求阶段的100倍!这就是为什么我们要在编码阶段就写测试——把问题消灭在萌芽状态。

二、测试金字塔

软件测试有多种类型,经典的"测试金字塔"模型告诉我们如何合理分配测试比例:

E2E 测试(少量)
模拟完整用户流程,成本高、速度慢
集成测试(适量)
测试模块间交互,如API+数据库
单元测试(大量)
测试单个函数/方法,速度快、成本低

单元测试是金字塔的基石——它测试的是最小可验证单元(通常是一个函数或方法)。单元测试跑得极快(毫秒级),写起来简单,是性价比最高的测试类型。

💡 小贴士:什么是"最小可验证单元"?

一个做加法的 add(a, b) 函数就是一个最小单元。一个处理用户注册的 register_user() 方法也是。关键是:它应该只测一件事。

三、unittest vs pytest 对比

Python有两个主流测试框架,我们来看看它们的区别:

特性 unittest pytest
安装方式 内置,无需安装 pip install pytest
测试写法 必须继承TestCase类 普通函数即可
断言方式 self.assertEqual()等方法 直接 assert 语句
fixture机制 setUp/tearDown @pytest.fixture 装饰器
参数化 subTest,写法繁琐 @pytest.mark.parametrize 简洁
插件生态 较少 丰富(1000+插件)
失败信息 信息不够详细 详细的差异对比

结论很明确:pytest是当前Python测试的主流选择。它更简洁、更灵活、生态更丰富。后续内容我们以pytest为主。

四、pytest安装与基础用法

首先安装pytest:

Bash 安装命令
pip install pytest
pytest --version   # 验证安装

pytest的核心规则很简单:

✅ 测试文件以 test_ 开头或 _test 结尾
✅ 测试函数以 test_ 开头
✅ 测试类以 Test 开头(不能有 __init__)
✅ 使用 assert 进行断言

来看最简单的测试:

Python test_hello.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# test_hello.py - 最简单的pytest测试
# 被测试的函数
def greet(name):
return f"你好,{name}!欢迎学习Python"
# 测试函数:以test_开头
def test_greet_returns_string():
"""测试greet返回的是字符串"""
result = greet("小明")
assert isinstance(result, str)
def test_greet_contains_name():
"""测试返回值包含传入的名字"""
result = greet("小红")
assert "小红" in result
def test_greet_not_empty():
"""测试返回值不为空"""
result = greet("小华")
assert result != ""
assert len(result) > 0

运行测试只需一个命令:

Bash 运行测试
pytest test_hello.py -v

# 输出:
# test_hello.py::test_greet_returns_string PASSED
# test_hello.py::test_greet_contains_name  PASSED
# test_hello.py::test_greet_not_empty      PASSED
# 3 passed in 0.02s

五、assert断言与参数化测试

pytest使用Python内置的 assert 语句做断言,不需要记各种 assertEqual、assertIn 方法。

常用断言形式

assert x == y — 等于
assert x != y — 不等于
assert x is True — 为真
assert x is None — 为空
assert item in list — 包含
assert isinstance(x, cls) — 类型检查
pytest.raises(ExcType) — 异常断言
Python test_assert_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# test_assert_demo.py
import pytest
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
def test_divide_normal():
assert divide(10, 2) == 5.0
assert divide(7, 3) == pytest.approx(2.333, abs=0.01)
def test_divide_returns_float():
assert isinstance(divide(1, 2), float)
def test_divide_by_zero():
# 断言抛出指定异常
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
assert "除数不能为零" in str(exc_info.value)
def test_divide_negative():
assert divide(-10, 2) == -5.0
assert divide(-10, -2) == 5.0

参数化测试:一次测多组数据

不用写一堆重复测试函数,@pytest.mark.parametrize 让你用一份测试逻辑跑多组数据:

Python 参数化示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 参数化测试 - 一组逻辑,多组数据
import pytest
def is_even(n):
return n % 2 == 0
@pytest.mark.parametrize("input_val, expected", [
(2, True),
(3, False),
(0, True),
(-4, True),
(-7, False),
(100, True),
])
def test_is_even(input_val, expected):
"""测试偶数判断:6组数据自动跑6次"""
assert is_even(input_val) == expected

⚠️ 常见错误:参数化装饰器的参数名要对应

装饰器中的字符串 "input_val, expected" 必须与函数参数名完全一致。名字不匹配会报 fixture not found 错误,这是初学者最常踩的坑。

六、fixture与测试组织

fixture是pytest最强大的功能之一——它负责在测试前准备数据、在测试后清理资源。比unittest的setUp/tearDown灵活得多。

Python fixture示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# conftest.py 或测试文件中定义fixture
import pytest
@pytest.fixture
def sample_users():
"""提供一个测试用的用户列表"""
return [
{"name": "Alice", "age": 25, "role": "admin"},
{"name": "Bob", "age": 30, "role": "user"},
{"name": "Charlie", "age": 17, "role": "user"},
]
@pytest.fixture
def db_connection():
"""模拟数据库连接(带清理)"""
conn = {"status": "connected"} # 模拟建立连接
yield conn # 将conn传给测试
conn["status"] = "closed" # 测试结束后清理
# 使用fixture:函数参数名 = fixture名
def test_user_count(sample_users):
assert len(sample_users) == 3
def test_admin_exists(sample_users):
roles = [u["role"] for u in sample_users]
assert "admin" in roles
def test_db_is_connected(db_connection):
assert db_connection["status"] == "connected"

注意 yield 关键字:它让fixture变成了"准备+清理"的两段式。yield之前是准备,yield之后是清理。这和生成器语法一样,但在这里它控制的是测试的生命周期。

conftest.py:共享fixture

把fixture放在 conftest.py 文件中,同目录下所有测试文件都能使用,无需import:

推荐的项目结构:
my_project/
  ├── src/
  │   └── calculator.py
  ├── tests/
  │   ├── conftest.py      # 共享fixture
  │   ├── test_add.py
  │   ├── test_subtract.py
  │   └── test_multiply.py
  └── requirements.txt

七、实战:计算器模块完整单元测试

让我们为一个计算器模块编写完整的测试套件。先定义被测试的代码:

Python calculator.py - 被测模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# calculator.py
class Calculator:
"""简易计算器"""
def __init__(self):
self.history = []
def add(self, a, b):
result = a + b
self.history.append(f"{a} + {b} = {result}")
return result
def subtract(self, a, b):
result = a - b
self.history.append(f"{a} - {b} = {result}")
return result
def multiply(self, a, b):
result = a * b
self.history.append(f"{a} * {b} = {result}")
return result
def divide(self, a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
result = a / b
self.history.append(f"{a} / {b} = {result}")
return result
def get_history(self):
return self.history.copy()
def clear_history(self):
self.history.clear()

接下来是完整的测试文件:

Python test_calculator.py - 完整测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# test_calculator.py
import pytest
from calculator import Calculator
# ---- Fixture ----
@pytest.fixture
def calc():
"""每个测试获得一个全新的Calculator实例"""
return Calculator()
# ---- 加法测试 ----
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
(1.5, 2.5, 4.0),
(-3, -7, -10),
])
def test_add(calc, a, b, expected):
assert calc.add(a, b) == expected
# ---- 减法测试 ----
@pytest.mark.parametrize("a, b, expected", [
(5, 3, 2),
(0, 0, 0),
(3, 5, -2),
])
def test_subtract(calc, a, b, expected):
assert calc.subtract(a, b) == expected
# ---- 乘法测试 ----
def test_multiply(calc):
assert calc.multiply(3, 4) == 12
assert calc.multiply(0, 100) == 0
assert calc.multiply(-2, 3) == -6
# ---- 除法测试(含异常) ----
def test_divide(calc):
assert calc.divide(10, 2) == 5.0
assert calc.divide(7, 3) == pytest.approx(2.333, abs=0.01)
def test_divide_by_zero(calc):
with pytest.raises(ValueError):
calc.divide(1, 0)
# ---- 历史记录测试 ----
def test_history_records_operations(calc):
calc.add(1, 2)
calc.multiply(3, 4)
history = calc.get_history()
assert len(history) == 2
assert "1 + 2 = 3" in history[0]
def test_clear_history(calc):
calc.add(1, 1)
calc.clear_history()
assert calc.get_history() == []
def test_each_test_gets_fresh_calc(calc):
"""验证fixture为每个测试创建新实例"""
assert calc.get_history() == []

💡 小贴士:pytest.approx 处理浮点数

浮点数比较有精度问题(0.1 + 0.2 != 0.3),用 pytest.approx(expected, abs=0.01) 做近似比较,这是测试中处理浮点数的标准做法。

常见踩坑记录

⚠️ 坑1:测试函数名没以test_开头

pytest不会运行不以 test_ 开头的函数。如果你发现测试"没跑",先检查命名。

⚠️ 坑2:assert 比较浮点数

直接 assert 0.1 + 0.2 == 0.3 会失败!浮点数要用 pytest.approx()。

⚠️ 坑3:fixture有副作用

如果fixture返回可变对象(如列表、字典),且没有在测试结束后清理,可能导致测试间相互影响。使用 yield + 清理代码来避免。

📝 知识回顾

✦ Bug修复成本随开发阶段指数增长,越早测试越省钱
✦ 测试金字塔:大量单元测试 > 适量集成测试 > 少量E2E测试
✦ pytest比unittest更简洁:普通函数 + assert + fixture
✦ 测试命名:文件/函数以 test_ 开头,类以 Test 开头
✦ 参数化:@pytest.mark.parametrize 避免重复代码
✦ fixture:用 @pytest.fixture 装饰器准备测试数据,yield 控制生命周期

下一篇预告

接口自动化测试:Requests + unittest

学会了单元测试,接下来挑战真实世界的API测试!下篇将带你用Requests库对REST API进行自动化测试,掌握接口测试用例设计、数据驱动和测试报告生成。

Python 自动化测试 · 第2篇 →
相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书