pytest 调研报告 —— 上手 pytest 实现自动化测试
- 使用步骤
- 一、运行 pytest 测试 demo
- 二、如何在 pytest 运行的时候输出 print 信息,以及如何输出 Log 信息
- 三、返回优雅的 report 报告
- 四、默认的执行顺序,如何控制执行顺序
- 五、pytest 多线程和多进程实践
- and more 。。。
简介 / 前言
pytest是什么?
官方文档:https://docs.pytest.org/en/stable/
中文文档:https://learning-pytest.readthedocs.io/zh/latest/doc/intro/getting-started.html
pytest 是一个十分优秀的用于测试的模块,它是python的第三方测试框架,是基于unittest的扩展框架,比unittest更简洁,更高效。这篇文章主要概述我调研使用pytest的几个特殊的栗子。还有更多的内容我没有提到,我会在文章末尾给出一些优秀的blog供大家参考,当然还是要以官方文档为准。????
使用步骤
一、运行 pytest 测试 demo
项目目录
在test_01.py, test_02.py, test_03.py中都存入相同的数据。
def test_01():
print("here is test_01")
assert 1==1
def test_02():
print("here is test_02")
assert 2==2
def test_03():
print("here is test_03")
assert 3!=3
执行 pytest tests/
运行测试脚本
二、如何在 pytest 运行的时候输出 print 信息,以及如何输出 Log 信息
输出 print 信息
上个模块我们介绍了,test_01.py test_02.py test_03.py 都保存了关于 print
的内容。
我们是需要 将 pytest tests/
替换成 pytest -s tests/
即可,其中的 -s
参数帮助我们达到了目标
三、返回优雅的 report 报告
安装pytest-html
模块 – 当测试结束之后,他可以生成一个可视化的 report html。
pip install pytest-html
根据上述的例子,添加以下的内容即可实现功能。
pytest -s --html=report.html --self-contained-html tests/
四、默认的执行顺序,如何控制执行顺序
pip install pytest_ordering
安装完依赖之后,在test func上添加以下内容即可实现。
@pytest.mark.run(order=n)
1,被@pytest.mark.last装饰的,永远最后执行。
2,被装饰的用例优先于未被装饰的用例执行。
3,被装饰的用例之间,执行顺序按照order值的大小执行,值越小越先执行。
例如
tests/test.py
@pytest.mark.run(order=1)
def test_01():
print("here is test_01")
assert 1==1
@pytest.mark.run(order=3)
def test_02():
print("here is test_02")
assert 2==2
@pytest.mark.run(order=2)
def test_03():
print("here is test_03")
assert 3!=3
执行结果
可见,test03比test02先执行。
tips:@pytest.mark.run(order=n),可以“跨文件使用” – 以当前的Blog为例,当tests文件夹下有3个test.py文件,每个test.py文件又有三个test func,可以通过使用:
@pytest.mark.run(order=n)
来指定多个文件中的func的执行顺序。
五、pytest 多线程和多进程实践
以多个类文件为例,开启多线程之后他会按照设置好的顺序依次运行,当不同文件的函数运行顺序设置为相同时,会实现伪并行。
pytest-parallel 的功能比 pytest-xdist更加完善
pip install pytest-parallel
pip install pytest-xdist
1、pytest-parallel加了多线程处理后,最后执行时间是运行时间最长的线程的时间。
2、在windows下想用多进程的选pytst-xdist; 想用多线程的选pytest-parallel
and more 。。。
如果又更多关于 pytest 的分享,欢迎在评论区里分享哇。
总结
pytest是python中的一个优秀的测试模块。他方便又灵活。在实践过程中,我尝试将pytest和Jenkins结合,实现了自动化测试和报警。
关于作者
欢迎评论关注+点赞啊!