--
:
--
:
--
第一阶段:pytest基础入门
最后更新于:
第一阶段:pytest基础入门
一、环境搭建
1.1 检查Python环境
1python --version
2# Python 3.9.101.2 安装pytest
1pip install pytest1.3 验证安装
1pytest --version
2# pytest 8.4.2二、核心概念
2.1 什么是pytest?
pytest是Python的一个成熟、功能丰富的测试框架,相比Python标准库的unittest,pytest更加简洁、灵活,支持自动发现测试用例。
2.2 pytest测试发现规则
pytest会自动查找符合以下规则的文件和函数:
| 类型 | 规则 | 示例 |
|---|---|---|
| 测试文件 | 文件名以test_开头或_test.py结尾 | test_example.py |
| 测试函数 | 函数名以test_开头 | def test_add(): |
| 测试类 | 类名以Test开头 | class TestCalculator: |
2.3 基本运行命令
1# 运行当前目录下所有测试
2pytest
3
4# 运行指定文件
5pytest test_example.py
6
7# 运行指定测试函数
8pytest test_example.py::test_add
9
10# 运行指定测试类中的方法
11pytest test_example.py::TestCalculator::test_add
12
13# 显示详细输出
14pytest -v
15
16# 显示更详细的输出(包括print内容)
17pytest -s
18
19# 失败时立即停止
20pytest -x
21
22# 指定并发数运行(需安装pytest-xdist)
23pytest -n 4三、项目结构
1pytest_project/
2├── src/ # 源代码目录
3│ └── calculator.py # 被测代码
4├── tests/ # 测试代码目录
5│ └── test_calculator.py # 测试用例
6└── pytest.ini # pytest配置文件四、配置文件pytest.ini
1[pytest]
2testpaths = tests # 指定测试文件搜索路径
3pythonpath = . # 添加Python模块搜索路径
4addopts = -v # 默认命令行参数五、示例代码
5.1 被测代码
1# src/calculator.py
2class Calculator:
3 def add(self, a, b):
4 return a + b
5
6 def subtract(self, a, b):
7 return a - b
8
9 def multiply(self, a, b):
10 return a * b
11
12 def divide(self, a, b):
13 if b == 0:
14 raise ValueError("Cannot divide by zero")
15 return a / b5.2 测试代码
1# tests/test_calculator.py
2from src.calculator import Calculator
3
4
5def test_add():
6 calc = Calculator()
7 result = calc.add(2, 3)
8 assert result == 5
9
10
11def test_subtract():
12 calc = Calculator()
13 result = calc.subtract(5, 2)
14 assert result == 3
15
16
17def test_multiply():
18 calc = Calculator()
19 result = calc.multiply(4, 5)
20 assert result == 20
21
22
23def test_divide():
24 calc = Calculator()
25 result = calc.divide(10, 2)
26 assert result == 5
27
28
29def test_divide_by_zero():
30 calc = Calculator()
31 with pytest.raises(ValueError, match="Cannot divide by zero"):
32 calc.divide(10, 0)六、易错点与注意事项
6.1 常见错误
- 测试函数命名错误:函数名不以
test_开头,导致pytest无法发现 - 模块导入错误:需要在
pytest.ini中设置pythonpath = . - 断言消息不明确:建议在断言中添加消息,如
assert result == 5, f"期望5,实际{result}"
6.2 最佳实践
- 测试文件放在
tests/目录下 - 被测代码放在
src/目录下 - 使用
pytest.ini统一配置测试参数 - 测试函数命名要清晰,描述测试目的
七、小结
本阶段学习了pytest的基础概念,包括:
- 环境搭建与配置
- 测试发现规则
- 基本运行命令
- 项目结构设计
- 断言系统使用
📡
👤
作者:
阿海
🌐
版权:
本站文章除特别声明外,均采用
CC BY-NC-SA 4.0
协议,转载请注明来自
阿海 Blog!
- 01JMeter界面详解 2026-07-11
- 02性能测试学习路线 2026-07-11
- 03JMeter线程组配置详解 2026-07-11