前言
pytest是一个非常成熟的全功能的Python测试框架,官方文档是这么介绍的
Pytest is a framework that makes building simple and scalable tests easy. Tests are expressive and readable—no boilerplate code required. Get started in minutes with a small unit test or complex functional test for your application or library.
他的特点如下:
•简单灵活,容易上手•支持参数化•能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests)•pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等•测试用例的skip和xfail处理•可以很好的和jenkins集成•report框架----allure 也支持了pytest
安装
简单的介绍了下pytest ,我们就开始真正的接触和使用pytest 了,首先是他的安装,安装比较容易
pip install py
验证安装是否成功,
pytest --version
显示其安装版本号即为成功
pytest 运行
命名规则
对于单个测试方法(函数)来说 必须以test开头 对于测试类来说 以Test开头 ,且不能有__init__()方法 对于测试文件来说,必须满足test_ 开头 或 _test.py 结尾
运行方式
现有测试文件 test_demo.py ,内容如下:
import pytestdef test_01(func):print('test_01')assert 1def test_02(func):print("test_02")assert 1if __name__ == '__main__':pytest.main(['-s', 'test_1.py'])
•测试文件主函数运行
pytest.main(['-s', 'test_1.py'])运行结果如下:============================= test session starts ==============================platform darwin -- Python 3.7.3, pytest-6.0.1, py-1.9.0, pluggy-0.13.1rootdir: /Users/zhangcheng/Documents/project/7.18/test_pyplugins: allure-pytest-2.8.18collected 2 itemstest_1.pyin fixture before testcase......test_01.test_02Fin fixture after testcase......=================================== FAILURES ===================================___________________________________ test_02 ____________________________________func = Nonedef test_02(func):print("test_02")> assert 0E assert 0test_1.py:17: AssertionError=========================== short test summary info ============================FAILED test_1.py::test_02 - assert 0========================= 1 failed, 1 passed in 0.25s ==========================
•命令行模式下运行
pytest -s test_1.py
运行时 -s 是修饰符,有特定的含义,pytest 常用的修饰符如下:
•-v 用于显示每个测试函数的执行结果•-q 只显示整体测试结果•-s 用于显示测试函数中print()函数输出•-x, --exitfirst, exit instantly on first error or failed test•-h 帮助
-x 可以指定失败次数
pytest -x xx.py #遇到第一个失败时, 就会退出执行难
而当你想指定具体失败次数时,可以使用
pytest --maxfail=n xx.py
即出现第n次失败时,才退出。
通过上面的演示可以看出,pytest 相对于 unittest 使用起来更为简单,不用继承特定的类,可以直接使用。大家可以先尝试下,我们后续的文章会带大家进一步的深入了解pytest。
本文分享自微信公众号 - 工程师的自我修养之路(Engineer_Way)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
来源:oschina
链接:https://my.oschina.net/imyalost/blog/4682443