pytest笔记2

一、allure2生成和查看报告

  1、安装插件:pip install allure-pytest

  2、下载allure2,解压后将allure2/bin加入环境变量中

  3、根据--alluredir参数生成allure报告:pytest 脚本名称.py --alluredir=report_path(报告路径)     访问allure本地路径,查看报告:allure serve report_path

    生成xml:pytest -q -s 脚本名称 --alluredir 报告路径       将xml生成html:allure generate xml路径 -o html指定路径

  4、清空以前的历史报告:allure generate xml路径 --clean -o html指定路径

二、pytest中fixtrue传参request

  1、用例中只有传一个fixture参数

#request传参.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
test_data=[{'user':'xw','pwd':'520'},{'user':'','pwd':'1314'}]
@pytest.fixture(scope="module")
def login(request):
    # 这一步是用来接收参数,此时有两个参数
    user=request.param['user']
    pwd=request.param['pwd']
    print('登陆账户为%s'%user)
    print('登陆密码为%s'%pwd)
    if user:
        return True
    else:
        return False
@pytest.mark.parametrize('login',test_data,indirect=True)
#indirect=True就是为了把login当成一个函数去执行,而不是一个参数
def test_01(login):
    a=login
    print('测试用例中login的返回值:%s' % a)
    assert a,"失败原因:账号为空"
if __name__ == '__main__':
    pytest.main(['-s','request传参.py'])

  运行结果  

C:UsersxwxxhAppDataLocalProgramsPythonPython37-32python.exe F:xwexamplepytestcase
equest传参.py
============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
rootdir: F:xwexamplepytestcase
plugins: html-2.1.1, metadata-1.10.0, rerunfailures-9.1.1
collected 2 items

request传参.py 登陆账户为xw
登陆密码为520
测试用例中login的返回值:True
.登陆账户为
登陆密码为1314
测试用例中login的返回值:False
F

================================== FAILURES ===================================
_______________________________ test_01[login1] _______________________________

login = False

    @pytest.mark.parametrize('login',test_data,indirect=True)
    #indirect=True就是为了把login当成一个函数去执行,而不是一个参数
    def test_01(login):
        a=login
        print('测试用例中login的返回值:%s' % a)
>       assert a,"失败原因:账号为空"
E       AssertionError: 失败原因:账号为空
E       assert False

request传参.py:21: AssertionError
=========================== short test summary info ===========================
FAILED request传参.py::test_01[login1] - AssertionError: 失败原因:账号为空
========================= 1 failed, 1 passed in 0.14s =========================

Process finished with exit code 0

2、用例中只有传多个个fixture参数

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
test_user=['xxx','yyy']
test_pwd=['123','456']
@pytest.fixture(scope='module')
def get_user(request):
    user=request.param
    return user
@pytest.fixture(scope='module')
def get_pwd(request):
    pwd=request.param
    return pwd
@pytest.mark.parametrize('get_user',test_user,indirect=True)
@pytest.mark.parametrize('get_pwd',test_pwd,indirect=True)
def test_01(get_user,get_pwd):
    user=get_user
    pwd=get_pwd
    print('%s--->%s'%(user,pwd))
if __name__ == '__main__':
    pytest.main(['-s','request_many.py'])

运行结果

C:UsersxwxxhAppDataLocalProgramsPythonPython37-32python.exe F:/xw/example/pytest/request_many.py
============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
rootdir: F:xwexamplepytest
plugins: html-2.1.1, metadata-1.10.0, rerunfailures-9.1.1
collected 4 items

request_many.py xxx--->123
.yyy--->123
.yyy--->456
.xxx--->456
.

============================== 4 passed in 0.03s ==============================

Process finished with exit code 0

 三、mark标记

  mark标记可用于单独指定执行某个用例

  1、注册标签名

  创建pytest.ini文件,在文件中添加标签名:  

[pytest]
markers =
    ontest:only execute this test.
   test
#ontest:标签名 #冒号后面为说明,可写也可以不写

  注:如果标签不注册的话,运行时会被警告  

2、打标签,在测试用例或者测试类前面加上:@pytest.mark.标签名  

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
def test_01():
    print('执行第一个用例')
@pytest.mark.ontest
def test_02():
    print('执行第二个用例')
def test_03():
    print('执行第三个用例')
if __name__ == '__main__':
    pytest.main(['-s','mark.py','-m=ontest'])

运行结果

C:UsersxwxxhAppDataLocalProgramsPythonPython37-32python.exe F:/xw/example/pytest/case/mark.py
============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
rootdir: F:xwexamplepytestcase, configfile: pytest.ini
plugins: html-2.1.1, metadata-1.10.0, rerunfailures-9.1.1
collected 3 items / 2 deselected / 1 selected

mark.py 执行第二个用例
.

======================= 1 passed, 2 deselected in 0.09s =======================

Process finished with exit code 0

3、给测试类打标签

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytest
#方式一 @pytest.mark.test
class Test1: def test_01(self): print('执行第1个用例')
#方式二
class Test2: pytestmark=[pytest.mark.test,pytest.mark.ontest]  #多个标签存在列表里面 def test_02(self): print('执行第2个用例')

四、pytest中--lf和--ff参数

  pytest --lf 脚本.py  只执行上次运行失败的用例

  pytest --ff 脚本.py  执行所有用例,但先执行上次运行失败的用例

五、pytest-html产生的报告中文乱码问题

  打开插件对应的py文件,基本都在Libsite-packagespytest_htmlplugin.py

  找到如下代码: 

class TestResult:
        def __init__(self, outcome, report, logfile, config):
            self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")

  将其改为:

    class TestResult:
        def __init__(self, outcome, report, logfile, config):
            #self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")
            self.test_id = report.nodeid

  然后再次运行,中文乱码问题就解决了!

六、pytest分布式执行

  分布式执行的插件为pytest-xdist,先用pip安装插件:pip install pytest-xdist

  分布式执行格式:pytest -n 5     #参数n后面跟数字,5为并行数量

七、重复执行用例

  重复执行用例的插件为pytest-repeat,先试用pip安装插件:pip install pytest-repeat

  格式:pytest --count =n 脚本.py    //n为重复的次数

原文地址:https://www.cnblogs.com/xwxxh/p/13903308.html