Python自动化测试框架-pytest
Python自动化测试框架-pytest
源码: https://github.com/pytest-dev/pytest
文档: https://docs.pytest.org/en/8.2.x/
安装: pip install pytest
查看版本: pytest -V
简单样例
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
命令行执行pytest
可以看到执行结果
命名规范
- 测试模块: 文件以
test_
开头 - 测试类: 以
Test
开头 - 测试方法: 函数以
test
开头
# content of test_class.py
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
执行方式
# 帮助命令
pytest -h
# 测试单个文件
pytest test_mod.py
# 测试文件夹下的用例
pytest testing/
# 执行关键字表达式
# 执行 TestMyClass.test_something, 不执行 TestMyClass.test_method_simple
pytest -k 'MyClass and not method'
# 查看用例的print输出
pytest -s
常用功能
1.数据驱动测试
准备多组数据,在一条用例中测试
# content of test_expectation.py
import pytest
@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
assert eval(test_input) == expected
从文件中读取数据,如test_data.csv
文件
input,expected
1,True
-2,False
3,True
0,False
import pytest
import csv
def load_csv_data(file_path):
with open(file_path, 'r') as f:
reader = csv.reader(f)
next(reader) # 跳过标题行
return [(int(row[0]), row[1] == 'True') for row in reader]
@pytest.mark.parametrize("number,expected", load_csv_data('test_data.csv'))
def test_is_positive(number, expected):
assert (number > 0) == expected
2.fixture装饰器
在pytest中,@pytest.fixture
用于将一个函数标记为一个fixture。
Fixture是一种可以为测试函数提供可重复使用的初始化代码或者资源的机制。避免在每个测试函数中重复编写相同的初始化或清理代码,提高了代码的可维护性和可重复性.
import pytest
# 定义一个简单的fixture,返回一个值
@pytest.fixture
def setup():
print("\nSetup for test")
yield 10 # yield之后的代码作为清理操作
print("\nTeardown after test")
# 使用fixture
def test_fixture_example(setup):
assert setup == 10
3.生成测试报告
可以使用pytest-html
插件来生成包含详细信息的html报告
# 安装pytest-html
pip install pytest-html
# 运行并生成测试报告,文件保存在当前路径下
pytest --html=report.html
生成JUnit/XML格式的报告,通常用于与持续集成系统(如Jenkins)集成,使测试结果能够被轻松地解析和显示。
pytest --junitxml=report.xml
参考文档: https://blog.csdn.net/qadnkz/article/details/136333732
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2023-06-15 vim常用命令