pytest初始化与清除fixture(二)

参考链接:https://blog.csdn.net/qq_42610167/article/details/116795260?spm=1001.2014.3001.5502  (较详细)

 

@pytest.fixture用法

1.导入pytest模块:import pytest

2.调用装饰器函数:@pytest.fixture(callable_or_scope=None,*args,scope='function',params=None,autouse=False,ids=None,name=None)

scope=function(默认值),表示作用于每一个测试用例

scope=class,表示每一个类调用一次,一个类中可以有多个方法

scope=moudle,表示每一个.py文件调用一次

scope=session,表示多个文件调用一次

autouse=True,表示每个测试用例都会执行初始化清除操作  (autouse=True自动调用,无需传仍何参数,作用范围跟着scope走(谨慎使用),20230203实践操作过,见下面代码)

 

import pytest

@pytest.fixture(scope="class",autouse=True)
def before():
    print("this is setup")
    yield
    after()

# '''以下是初始化配套清除操作的第二种写法,代替yield'''
# @pytest.fixture(autouse=True)
# def before(request):
#     print("this is setup")
#     request.addfinalizer(after())

def after():
    print("this is teardown")

class Test001():
    def test_001(self):
        print("this is test_001()")
class Test002():
    def test_002(self):
        print("this is test_002()")

if __name__=="__main__":
    pytest.main(['-s',"test_0203.py"])



执行结果:
D:\tool\python\python.exe D:/work/Test/Interface_Test/test_0203.py
============================= test session starts =============================
platform win32 -- Python 3.10.3, pytest-7.1.2, pluggy-1.0.0
rootdir: D:\work\Test\Interface_Test
plugins: allure-pytest-2.9.45, html-3.2.0, metadata-2.0.4, ordering-0.6
collected 2 items

test_0203.py this is setup
this is test_001()
.this is teardown
this is setup
this is test_002()
.this is teardown


============================== 2 passed in 0.01s ==============================

 

以上结论:定义了初始化清除函数的范围是作用于类,自动调用,在执行脚本时两个类都执行了一遍初始化清除操作。

 

import pytest

@pytest.fixture(autouse=True)
def before():
    print("this is setup")
    yield
    after()

'''以下是初始化配套清除操作的第二种写法,代替yield'''
@pytest.fixture(autouse=True)
def before(request):
    print("this is setup")
    request.addfinalizer(after())

def after(): 
    print("this is teardown") 

def test_001(): 
    print("this is test_001()") 

def test_002(): 
    print("this is test_002()") 

C:\Users\cale\checkapi\test>pytest -s test_gy.py
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 2 items

test_gy.py this is setup
this is test_001()
.this is teardown
this is setup
this is test_002()
.this is teardown

 

 autouse=False(默认值),不会作用于每个测试用例,哪些测试用例要执行初始化清除操作需在测试用例里面传入对应的参数

from api.compare_result import CompareResult
from api.gy import gy_v4
import pytest

class TestSuite():
    def test_gy1(self,start):
        '''start:调用start()方法作为该测试用例的初始化清除方法'''
        inputxml1 = 'C:/Users/cale/checkapi/data/input/gyopt.xml'
        outputxml1 = 'C:/Users/cale/checkapi/data/output/gyopt.xml'
        cmpr=CompareResult()
        cmpr.compareXML(gy_v4,inputxml1,outputxml1)

    @pytest.fixture(autouse=False)
    def start(self):
        '''调用fixture()装饰器,将此方法装饰成初始化清除方法'''
        print("执行测试套件前会先执行此方法")
        yield
        self.end()

    def end(self):
        print('执行完测试套件后会执行此方法')

执行结果:
test_gy.py 执行测试套件前会先执行此方法
.<?xml version="1.0" encoding="UTF-8"?>
<root><result><base><hospital_code>H0003</hospital_code><event_no></event_no><patient_id>004026990100aa</patient_id><source>门诊</source></base><btnStatus></btnStatus><invoke_result><invoke_status>0</invoke_status><invoke_message>调用失败</invoke_message></invoke_result><message><recipe_id></recipe_id><infos><info><info_id>1585813554277</info_id><recipe_item_id></recipe_item_id><group_no></group_no><drug_id></drug_id><drug_name></drug_name><error_info>干预异常!</error_info><advice></advice><source></source><rt></rt><source_id></source_id><severity></severity><message_id></message_id><type></type><analysis_type></analysis_type><analysis_result_type></analysis_result_type><info_type>0</info_type></info></infos></message></result></root>
比标准出参多出来的节点如下>>>>>>>>>>>>>>>>>
没有多余的节点
比标准出参少的节点如下>>>>>>>>>>>>>>>>>
没有缺少的节点
与标准出参类型不一致的节点如下>>>>>>>>>>>>>>>>>
节点名称:event_no            ,标准出参类型:str                 ,实际出参类型:<class 'NoneType'>
节点名称:source              ,标准出参类型:str                 ,实际出参类型:<class 'NoneType'>
执行完测试套件后会执行此方法
                                                             [100%]

============================== 1 passed in 1.71s ==============================

用fixture decorator调用fixture(autouse=False的情况下)

import pytest

@pytest.fixture(autouse=True)
def before():
    print("this is setup")
    yield
    after()

def after():
    print("this is teardown")

class TestSuite():
    @pytest.mark.usefixtures("before")
    def test_003(self):
        print("test_003()")

    @pytest.mark.usefixtures("before")
    def test_004(self):
        print("test_004()")

@pytest.mark.usefixtures("before")
class TestSuite2():
    def test_004(self):
        print("test_004()")

    def test_005(self):
        print("test_005()")

C:\Users\cale\checkapi\test>pytest -s test_gy.py
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 4 items

test_gy.py this is setup
test_003()
.this is teardown
this is setup
test_004()
.this is teardown
this is setup
test_004()
.this is teardown
this is setup
test_005()
.this is teardown

用autos调用fixture (autouse=True的情况下)

import pytest

@pytest.fixture(scope='module',autouse=True)
def mod_header(request):
    print("module:%s"%(request.module.__name__))

@pytest.fixture(scope='function',autouse=True)
def func_header(request):
    print("function:%s"%(request.function.__name__))

def test_006():
    print("test_006")

def test_007():
    print("test_007")

运行结果:

C:\Users\cale\checkapi\test>pytest test_gy.py -s
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 2 items

test_gy.py module:test_gy
function:test_006
test_006
.function:test_007
test_007
.

================================================== 2 passed in 0.12s ==================================================

 以上mod_header()函数运行了一次,在所有测试用例执行前运行了一次;func_header()运行了两次,每个测试用例执行前都会运行一次

fixture返回值的使用

import pytest

@pytest.fixture(params=[1,2])
def test_data(request):
    return request.param

def test_not_2(test_data):
    print("test_data:%s"%(test_data))
    assert test_data!=2

运行结果:

C:\Users\cale\checkapi\test>pytest test_gy.py -s
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 2 items

test_gy.py test_data:1
.test_data:2
F

====================================================== FAILURES =======================================================
____________________________________________________ test_not_2[2] ____________________________________________________

test_data = 2

def test_not_2(test_data):
print("test_data:%s"%(test_data))
> assert test_data!=2
E assert 2 != 2

test_gy.py:49: AssertionError
============================================= 1 failed, 1 passed in 0.47s =============================================

可以看到test_not_2这个测试用例执行了两次,test_data函数中params这个变量传了几个参数,测试用例就会运行几次

 

 

链接:https://www.jianshu.com/p/54b0f4016300

目录下的初始化(session):https://blog.csdn.net/qq_36502272/article/details/100776789

posted @ 2020-04-07 11:01  pple  阅读(523)  评论(0编辑  收藏  举报
以终为始,你期待的那天不会太遥远。