Python测试框架:pytest

匿名 (未验证) 提交于 2019-12-02 22:51:30

全功能Python测试框架:pytest

摘自:https://www.jianshu.com/p/932a4d9f78f8

image.png

pytest是一个非常成熟的全功能的Python测试框架,主要有以下几个特点:

  • 简单灵活,容易上手
  • 支持参数化
  • 能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests)
  • pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等
  • 测试用例的skip和xfail处理
  • 可以很好的和jenkins集成
  • report框架----allure 也支持了pytest

安装pytest:

pip install -U pytest 

验证安装的版本:

pytest --version 

几个pytest documentation中的例子:

例子1:

import pytest  # content of test_sample.py def func(x):     return x + 1 def test_answer():     assert func(3) == 5 

命令行切换到文件所在目录,执行测试(也可以直接在IDE中运行):


image.png

这个测试返回一个失败报告,因为func(3)不返回5。

例子2:
当需要编写多个测试样例的时候,我们可以将其放到一个测试类当中,如:

class TestClass:       def test_one(self):           x = "this"           assert 'h' in x          def test_two(self):           x = "hello"           assert hasattr(x, 'check')  

运行以上例子:


image.png

从测试结果中可以看到,该测试共执行了两个测试样例,一个失败一个成功。同样,我们也看到失败样例的详细信息,和执行过程中的中间结果。-q即-quiet,作用是减少冗长,具体就是不再展示pytest的版本信息。

如何编写pytest测试样例

通过上面2个实例,我们发现编写pytest测试样例非常简单,只需要按照下面的规则:

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试函数以test_开头
  • 断言使用基本的assert即可

运行模式

1.运行后生成测试报告(htmlReport)

安装pytest-html:

pip install -U pytest-html 

运行模式:

pytest --html=report.html 

报告效果:


image.png

在以上报告中可以清晰的看到测试结果和错误原因,定位问题很容易。

2.运行指定的case

例子代码:

class TestClassOne(object):     def test_one(self):         x = "this"         assert 't'in x      def test_two(self):         x = "hello"         assert hasattr(x, 'check')   class TestClassTwo(object):     def test_one(self):         x = "iphone"         assert 'p'in x      def test_two(self):         x = "apple"         assert hasattr(x, 'check') 

运行模式:

模式1:直接运行test_se.py文件中的所有cases:

pytest test_se.py 

模式2:运行test_se.py文件中的TestClassOne这个class下的两个cases:

pytest test_se.py::TestClassOne 

模式3:运行test_se.py文件中的TestClassTwo这个class下的test_one:

pytest test_se.py::TestClassTwo::test_one 

注意:定义class时,需要以T开头,不然pytest是不会去运行该class的。

3.多进程运行cases

安装pytest-xdist:

pip install -U pytest-xdist 

运行模式:

pytest test_se.py -n NUM 

其中NUM填写并发的进程数。

4.重试运行cases

安装pytest-rerunfailures:

pip install -U pytest-rerunfailures 

运行模式:

pytest test_se.py --reruns NUM 

NUM填写重试的次数。

5.显示print内容

运行模式:

pytest test_se.py -s 

pytest test_se.py -s -n 4 

学习网站:
pytest documentation
好用的Pytest单元测试框架(《51测试天地》四十九(下)- 44)
Pytest学习笔记
pytest单元测试框架

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!