前提声明:
在pytest框架中,有如下约束:
- 所有的文件名都需要满足test_.py格式或_test.py格式;
- 在文件中,测试类以Test开头,并且不能带有init 方法(注意:定义class时,需要以T开头,不然pytest是不会去运行该class的)
- 在类中,可以包含一个或多个test_开头的函数。
此时,在执行pytest命令时,会自动从当前目录及子目录中寻找符合上述约束的测试函数来执行。
安装插件
pytest有很多强大的插件,例如:
pytest-xdist 多CPU 分发,多线程
pytest-rerunfailures 失败用例重跑
pytest-html 生成html测试报告
allure-pytest 生成测试报告
pytest-ordering 实现控制测试用例的顺序
安装方式:
法一:
如图所示,点击右上“+”号,搜素要安装的插件,点击“Install Package"即可安装成功;
法二:
依次在终端运行 pip install xxx
法三:
创建一个requirements.txt 的文档,然后通过 执行pip install -r requirements.txt
安装插件;注意,不要在该文件里写中文注释;
1、pytest-xdist
正常运行代码如下:
# test_case.py
from time import sleep
import pytest
class TestClass(object):
def test_one(self):
# assert 1 == 2
sleep(3)
print('just a test')
def test_two(self):
sleep(3)
assert 'h' in 'hello'
执行pytest -vs test_case.py
结果如下:
可以看到,这样顺序执行的话大概花费时间为6.09s
使用多线程,则花费时间会大大减少,执行 pytest -vs -n 2 test_case.py
,-n 2 即为两个线程同时执行,如图所示两个线程 gw0 和 gw1 ,时间为3.61s
2、pytest-rerunfailures
即:失败用例重跑
代码示例:
# test_case.py
import pytest
class TestClass(object):
def test_one(self):
assert 1 == 2
# sleep(3)
print('just a test')
def test_two(self):
# sleep(3)
assert 'h' in 'hello'
不使用–reruns,执行 pytest -vs test_case.py
,结果如下:
执行 pytest -vs test_case.py --reruns 2
.结果如下:
对比两张图片,可以看到test_one用例执行失败后,又重复执行了两次,第三次执行显示Failed,即 1failed, 2 return
3、pytest-html
执行方式:pytest --html=./report/report.html
代码同上,运行 pytest -vs -n 2 test_case.py --html=./report/res.html
,结果如图所示:
打开该文件中res.html,可以看到更加直观的运行结果
4、allure-pytest
执行方式:
生成allure所需要的测试结果文件
pytest test_case.py -n 2 -vs --alluredir ./res
执行allure serve res
,进入网页
代码示例:
# test_case.py
from operator import add
from time import sleep
import pytest
class TestClass(object):
def test_one(self):
# assert 1 == 2
sleep(3)
print('just a test')
def test_two(self):
sleep(3)
assert 'h' in 'hello'
# @pytest.mark.slow
def test_three(self):
assert 3 == 4
def test_four(self):
assert 3 < 5
# @pytest.mark.faster
def test_five(self):
assert add(1, 2) == 3
运行 pytest test_case.py -n 2 -vs --alluredir ./res
,生成allure所需要的测试结果文件:
显然这并不是我们需要的网页显示结果,需要再次执行allure serve res
,进入网页,可以看到一个色彩鲜明的图形化界面,比html好看一些,但是运行两行代码感Jio没有html好用~~
如果在执行这个命令时报错提示:allure不是内部或外部命令,也不是可运行的程序 或批处理文件,请移步 解决办法
5、pytest-ordering
pytest-ordering 插件后改变测试用例顺序
# test_case.py
from operator import add
from time import sleep
import pytest
class TestClass(object):
@pytest.mark.run(order=4)
def test_one(self):
print('11111111111111')
def test_two(self):
sleep(3)
assert 'h' in 'hello'
@pytest.mark.run(order=2)
def test_three(self):
print('33333333333')
assert 3 == 4
def test_four(self):
assert 3 < 5
# @pytest.mark.faster
@pytest.mark.run(order=1)
def test_five(self):
print('555555555555')
从结果可以看出,先按照order顺序执行,在按照函数顺序执行。