Python测试框架之pytest高级用法之fixture(三)

前置条件:

1.文件路径:

Test_App
    - - test_abc.py
    - - pytest.ini

 2.pyetst.ini配置文件内容:

 
[pytest]
  命令行参数
 addopts = -s
 搜索文件名
 python_files = test*.py
  搜索的类名
 python_classes = Test*
搜索的函数名
 python_functions = test_*

  pytest之fixture

fixture修饰器来标记固定的工厂函数,在其他函数,模块,类或整个工程调用它时会被激活并优先执行,通常会被用于完成预置处理和重复操作。

方法:fixture(scope="function", params=None, autouse=False, ids=None, name=None)
常用参数:
scope:被标记方法的作用域  session>module>class>function
function" (default):作用于每个测试方法,每个test都运行一次
"class":作用于整个类,每个class的所有test只运行一次 一个类中可以有多个方法
"module":作用于整个模块,每个module的所有test只运行一次;每一个.py文件调用一次,该文件内又有多个function和class
"session:作用于整个session(慎用),每个session只运行一次;是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
params:(list类型)提供参数数据,供调用标记方法的函数使用;一个可选的参数列表,它将导致多个参数调用fixture功能和所有测试使用它。
autouse:是否自动运行,默认为False不运行,设置为True自动运行;如果True,则为所有测试激活fixture func可以看到它。如果为False则显示需要参考来激活fixture

ids:每个字符串id的列表,每个字符串对应于params这样他们就是测试ID的一部分。如果没有提供ID它们将从params自动生成;是给每一项params参数设置自定义名称用,意义不大。

 name:fixture的名称。这默认为装饰函数的名称。如果fixture在定义它的统一模块中使用,夹具的功能名称将被请求夹具的功能arg遮蔽,解决这个问题的一种方法时将装饰函数命    令"fixture_<fixturename>"然后使用"@pytest.fixture(name='<fixturename>')"。

  fixture第一个例子(通过参数引用)

class Test_ABC:
    @pytest.fixture()
    def before(self):
        print("------->before")
    def test_a(self,before): # ️ test_a方法传入了被fixture标识的函数,已变量的形式
        print("------->test_a")
        assert 1
if __name__ == '__main__':
    pytest.main(["-s  test_abc.py"])
         .

  

使用多个fixture

如果用例需要用到多个fixture的返回数据,fixture也可以返回一个元祖,list或字典,然后从里面取出对应数据。

import pytest
@pytest.fixture()
def test1():
    a = 'door'
    b = '123456'
    print('传出a,b')
    return (a, b)
def test_2(test1):
    u = test1[0]
    p = test1[1]
    assert u == 'door'
    assert p == '123456'
    print('元祖形式正确')
if __name__ == '__main__':
    pytest.main(['-s','test_abc.py'])

  

  当然也可以分成多个fixture,然后在用例中传多个fixture参数

import pytest
@pytest.fixture()
def test1():
    a = 'door'
    print('
传出a')
    return a
@pytest.fixture()
def test2():
    b = '123456'
    print('传出b')
    return b
def test_3(test1, test2):
    u = test1
    p = test2
    assert u == 'door'
    assert p == '123456'
    print('传入多个fixture参数正确')
if __name__ == '__main__':
    pytest.main(['-s','test_abc.py'])

  

 fixture第二个例子(通过函数引用)

import pytest
@pytest.fixture() # fixture标记的函数可以应用于测试类外部
def before():
    print("------->before")
@pytest.mark.usefixtures("before")#1.需要前面标记了before函数,这才可以用,所以需求before函数前面标记@pytest.fixture();2.前面标记了before函数,这不引用的话,执行后不执行before函数
                     比如在接口测试中有需要先登录的就可以使用这个用法
class Test_ABC: def setup(self): print("------->setup") def test_a(self): print("------->test_a") assert 1 if __name__ == '__main__': pytest.main(["-s","test_abc.py"])

  

 使用装饰器@pytest.mark.usefixtures()修饰需要运行的用例

import pytest
@pytest.fixture()
def test1():
    print('
开始执行function')
@pytest.mark.usefixtures('test1')
def test_a():
    print('---用例a执行---')
@pytest.mark.usefixtures('test1')
class Test_Case:
    def test_b(self):
        print('---用例b执行---')
    def test_c(self):
        print('---用例c执行---')
if __name__ == '__main__':
    pytest.main(['-s', 'test_abc.py'])

  

叠加usefixtures

如果一个方法或者一个class用例想要同时调用多个fixture,可以使用@pytest.mark.usefixture()进行叠加。注意叠加顺序,先执行的放底层,后执行的放上层。

import pytest
@pytest.fixture()
def test1():
    print('
开始执行function1')
@pytest.fixture()
def test2():
    print('
开始执行function2')
@pytest.mark.usefixtures('test1')
@pytest.mark.usefixtures('test2')
def test_a():
    print('---用例a执行---')
@pytest.mark.usefixtures('test2')
@pytest.mark.usefixtures('test1')
class Test_Case:
    def test_b(self):
        print('---用例b执行---')
    def test_c(self):
        print('---用例c执行---')
if __name__ == '__main__':
    pytest.main(['-s', 'test_abc.py'])

  

usefixtures与传fixture区别

 如果fixture有返回值,那么usefixture就无法获取到返回值,这个是装饰器usefixture与用例直接传fixture参数的区别。

当fixture需要用到return出来的参数时,只能讲参数名称直接当参数传入,不需要用到return出来的参数时,两种方式都可以。

 fixture第三个例子(默认设置为运行,作用域是function)

import pytest
@pytest.fixture(scope='function',autouse=True) # 作用域设置为function,自动运行
def before():
    print("------->before")
class Test_ABC:
    def setup(self):
        print("------->setup")
    def test_a(self):
        print("------->test_a")
        assert 1
    def test_b(self):
        print("------->test_b")
        assert 1
if __name__ == '__main__':
        pytest.main(["-s", "test_abc.py"])

  

 fixture第五个例子(设置作用域为class)

import pytest
@pytest.fixture(scope='class',autouse=True) # 作用域设置为class,自动运行
def before():
    print("------->before")
class Test_ABC:
    def setup(self):
        print("------->setup")
    def test_a(self):
        print("------->test_a")
        assert 1
    def test_b(self):
        print("------->test_b")
        assert 1
if __name__ == '__main__':
    pytest.main(["-s","test_abc.py"])

 fixture第六个例子(返回值)

import pytest
@pytest.fixture()
def need_data():
    return 2  # 返回数字2
class Test_ABC:
    def test_a(self, need_data):
        print("------->test_a")
        assert need_data != 3  # 拿到返回值做一次断言
if __name__ == '__main__':
    pytest.main(["-s",  "test_abc.py"])

 

import pytest
@pytest.fixture(params=[1, 2, 3])
def need_data(request):  # 传入参数request 系统封装参数
    return request.param  # 取列表中单个值,默认的取值方式
class Test_ABC:
    def test_a(self, need_data):
        print("------->test_a")
        assert need_data != 3  # 断言need_data不等于3
if __name__ == '__main__':
    pytest.main(["-s","test_abc.py"])

  发现结果运行了三次

fixture(设置作用域为module)

import pytest
@pytest.fixture(scope='module')
def test1():
    b = '男'
    print('传出了%s, 且在当前py文件下执行一次!!!' % b)
    return b
def test_3(test1):
    name = '男'
    print('找到name')
    assert test1 == name
class Test_Case:
    def test_4(self, test1):
        sex = '男'
        print('找到sex')
        assert test1 == sex
if __name__ == '__main__':
    pytest.main(["-s","test_abc.py"])

  

 fixture(设置作用域为session)

fixture为session级别是可以跨.py模块调用的,也就是当我们有多个.py文件的用例的时候,如果多个用例只需调用一次fixture,那就可以设置为scope="session",并且写到conftest.py文件里。

conftest.py文件名称时固定的,pytest会自动识别该文件。放到项目的根目录下就可以全局调用了,如果放到某个package下,那就在改package内有效。

import pytest
# conftest.py

@pytest.fixture(scope='session')
def test1():
    a='door'
    print('获取到%s' % a)
    return a

  

import pytest
# abc.py

def test3(test1):
    b = 'pen'
    print('找到b')
    assert test1 == b


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

  

import pytest
# abc1.py

class Test_Case:

    def test_4(self, test1):
        a = 'door'
        print('找到a')
        assert test1 == a

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

  如果需要同时执行两个py文件,可以在cmd中在文件py文件所在目录下执行命令:pytest -s test_abc.py test_abc.py 

conftest.py的作用范围

一个工程下可以建多个conftest.py的文件,一般在工程根目录下设置的conftest文件起到全局作用。在不同子目录下也可以放conftest.py的文件,作用范围只能在改层级以及以下目录生效。

 1.conftest在不同的层级间的作用域不一样

 2.conftest是不能跨模块调用的(这里没有使用模块调用)

 fixture自动使用autouse=True

当用例很多的时候,每次都传这个参数,会很麻烦。fixture里面有个参数autouse,默认是False没开启的,可以设置为True开启自动使用fixture功能,这样用例就不用每次都去传参了

平常写自动化用例会写一些前置的fixture操作,用例需要用到就直接传该函数的参数名称就行了。当用例很多的时候,每次都传这个参数,会比较麻烦。
fixture里面有个参数autouse,默认是Fasle没开启的,可以设置为True开启自动使用fixture功能,这样用例就不用每次都去传参了
设置autouse=True
autouse设置为True,自动调用fixture功能
start设置scope为module级别,在当前.py用例模块只执行一次,autouse=True自动使用[图片]open_home设置scope为function级别,
每个用例前都调用一次,自动使用

autouse设置为True,自动调用fixture功能

import pytest
@pytest.fixture(scope='module', autouse=True)
def test1():
    print('
开始执行module')
@pytest.fixture(scope='class', autouse=True)
def test2():
    print('
开始执行class')
@pytest.fixture(scope='function', autouse=True)
def test3():
    print('
开始执行function')
def test_a():
    print('---用例a执行---')
def test_d():
    print('---用例d执行---')
class Test_Case:
    def test_b(self):
        print('---用例b执行---')
    def test_c(self):
        print('---用例c执行---')
if __name__ == '__main__':
    pytest.main(['-s', 'test_abc.py'])

  

 结果可以看到scope=class时也作用于class外的函数

fixture 之 params 使用示例

request 是pytest的内置 fixture ,主要用于传递参数

Fixture参数之params参数实现参数化:(可以为list和tuple,或者字典列表,字典元祖等)

import pytest
 
def read_yaml():
    return ['1','2','3']
 
@pytest.fixture(params=read_yaml())
def get_param(request):
    return request.param
 
def test_01(get_param):
    print('测试用例:'+get_param)
 
if __name__ == '__main__':
    pytest.main(['-s','test_abc.py'])
执行结果:

============================= test session starts =============================
platform win32 -- Python 3.5.2, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: E:PycharmProjectslianxi, configfile: pytest.ini
plugins: forked-1.3.0, html-1.22.1, metadata-1.8.0, rerunfailures-9.1, xdist-2.1.0
collected 3 items

test_abc.py 测试用例:1
.测试用例:2
.测试用例:3
.

------ generated html file: file://E:PycharmProjectslianxi eport.html ------
============================== 3 passed in 0.13s ==============================

  

注意:

1.此例中test01方法被执行了三次,分别使用的数据为'1','2','3',此结果类似于ddt数据驱动的功能。特别注意:这里的request参数名是固定的,然后request.param的param没有s。

2.可以把return request.param改成yield request.param,yield也是返回的意思,它和return的区别在于return返回后后面不能接代码,但是yield返回后,后面还可以接代码。

原文地址:https://www.cnblogs.com/wxcx/p/13779826.html