本文共 1339 字,大约阅读时间需要 4 分钟。
Pytest 是一个成熟的全功能 Python 测试框架,广泛应用于单元测试、功能测试以及自动化测试等领域。以下将从安装、基础使用、运行参数以及配置等方面详细介绍 Pytest 的使用方法。
安装 Pytest 及其常用插件,可以通过以下步骤完成:
安装依赖
将以下内容写入require-install.txt 文件:pytestpytest-htmlpytest-xdistpytest-rerunfailures
在命令提示符下运行:
pip install -r require-install.txt
验证安装结果:
pytest --version
如果出现版本冲突,可以降低 Python 或 Pytest 版本。
示例环境配置
作者推荐的环境为:函数测试
定义测试函数,命名为test_ 开头:import pytestdef test_01(): print('测试用例一')类测试
测试类需以Test 开头,且不包含 __init__ 方法:class TestCase: def test_03(self): print('测试用例三') def defg(self): print('测试用例四')运行方式
if __name__ == '__main__': pytest.main(['-s', 'pytest-demo.py'])
pytest pytest-demo.py
-s:启用打印输出。:::指定测试用例。--html=./report.html:生成 HTML 测试报告(需安装 pytest-html)。--maxfail=1:允许 1 个失败后停止测试。-n=2:使用多线程运行测试(需安装 pytest-xdist)。--reruns=2:重试失败的测试用例(需安装 pytest-rerunfailures)。Pytest 的 pytest.ini 文件位于项目根目录下,配置方式如下:
[pytest]addopts = -s --html=./report.htmltestpaths = ../pytestprojectpython_files = test*.pypython_classes = Test*python_functions = test*
示例配置:
[pytest]addopts = -s --html=./report.htmltestpaths = ..python_files = test_*.pypython_classes = Test*
Pytest 是一个强大的测试框架,支持灵活的配置和丰富的插件扩展。通过合理的测试用例编写和配置文件设置,可以实现高效的测试自动化。希望本文能为您的测试工作提供帮助,祝您测试顺利!
转载地址:http://ynafk.baihongyu.com/