Python 自动化测试框架全面解析
测试是软件质量保障的基础环节,但手动重复执行测试既耗时又极易出错。自动化测试借助机器批量、高频地运行测试任务,而自动化测试框架则是对测试代码的封装,将通用能力抽象出来。其核心优势十分明显:测试效率显著提升,代码复用性极高,重复劳动大幅减少;测试覆盖范围广泛,能同时执行大量场景;最关键的是无需人工持续盯防,错误率自然随之降低。

Pytest 框架深度介绍
Pytest 是什么
Pytest 是 Python 生态中极受欢迎的测试框架,支持编写和执行多种类型的软件测试:单元测试、集成测试、端到端测试、功能测试均能胜任。虽然它最常应用于 API 测试,但同样适用于数据库、UI 及其他组件的测试。它内置了参数化测试、fixture(固定装置)、断言重写、并行执行等实用功能。安装非常简便,只需执行 pip install -U pytest,安装完成后使用 pytest --version 确认版本即可。

它的优点可快速归纳如下:
- 同时执行多个测试用例,有效缩短整体执行时间
- 可在执行过程中灵活跳过某个测试方法
- 完全免费且开源
- 学习曲线平滑,上手迅速
使用 Pytest 开展 Python 自动化测试
Pytest 的安装步骤
直接通过 pip 命令安装:
pip install -U pytest
安装完成后,在终端输入 pytest --version,若显示版本号则代表安装成功。
Pytest 用例编写规范要点
Pytest 对文件、类和方法命名有明确约定,遵循这些规则才能被框架自动识别:
- 测试文件必须以
test_开头或以_test结尾 - Pytest 运行时会自动查找这类文件作为测试文件
- 测试类名需要以
Test开头,且不能包含__init__方法,否则会触发ytestCollectionWarning: cannot collect test class 'TestXXX'警告 - 测试方法名必须以
test_开头 - 断言直接使用 Python 原生的
assert语句
运行命令的灵活用法
通过 -k 参数可以灵活筛选需要执行的用例:
pytest -k "类名"
pytest -k "方法名"
pytest -k "类名 and not 方法名"
运行模式详解
Pytest 支持不同粒度的运行方式:既可以只运行某个模块,也可以精确到模块下的某个具体方法。
pytest 文件名.py
pytest 文件名.py::类名
pytest 文件名.py::类名::方法名
实际示例演示
编写一段测试代码作为演示。我们需要创建一个以 test_ 开头的 .py 文件。
在一个test开头的py文件里面,编写一下脚本:
def setup_module():
print('\n 这是setup_module方法,只执行一次,当有多个测试类的时候使用')
def teardown_module():
print('这是 teardown_module方法,只执行一次,当有多个测试类的时候使用')
def teardown_module():
print('这是 teardown_module方法,只执行一次,当有多个测试类的时候使用')
def setup_function():
print('这是 setup_function方法,只执行一次,当有多个测试类的时候使用')
def teardown_function():
print('这是 teardown_function方法,只执行一次,当有多个测试类的时候使用')
def test_five():
print('this is test_five method')
def test_six():
print('this is test_six method')
class TestPytest01:
def setup_class(self):
print('调用了setup_class1方法')
def teardown_class(self):
print('调用了teardown_class1方法')
def setup_method(self):
print('执行测试方法前的setup1操作')
def teardown_method(self):
print('执行测试方法后的teardown1操作')
def test_one(self):
print('this is test_one method')
def test_two(self):
print('this is test_two method')
def setup(self):
print('this is setup 方法')
def teardown(self):
print('this is teardown 方法')
class TestPytest02:
def setup_class(self):
print('调用了setup_class2方法')
def teardown_class(self):
print('调用了teardown_class2方法')
def setup_method(self):
print('执行测试方法前的setup2操作')
def teardown_method(self):
print('执行测试方法后的teardown2操作')
def test_three(self):
print('this is test_three method')
def test_four(self):
print('this is test_four method')
运行后得到的结果截图如下:

控制测试用例的执行顺序
如果需要自定义测试用例的执行顺序,可以借助 pytest-order 插件,配合 @pytest.mark.run(order=num) 装饰器来实现。
pip install pytest-ordering
编写一段代码进行验证:
import pytest
class TestPytest:
@pytest.mark.run(order=-2)
def test_03(self):
print('test_03')
@pytest.mark.run(order=-3)
def test_01(self):
print('test_01')
@pytest.mark.run(order=4)
def test_02(self):
print('test_02')
执行结果如下:

