fixture特性

二、fixture特性

1. fixture作为形参使用

import pytest

@pytest.fixture()
def myfunc():
    print("这是一个前置")
    yield 100 # 前后置分割线以及返回值
    print("这是一个后置")

def test_01(myfunc):
    print(myfunc+100)
    assert 0

输出

fixturetest.py:17: AssertionError
---------------------------- Captured stdout setup ----------------------------
这是一个前置
---------------------------- Captured stdout call -----------------------------
200
-------------------------- Captured stdout teardown ---------------------------
这是一个后置
============================== 1 failed in 0.17s ==============================

执行过程:

搜索到test_01测试用例,检查到有一个形参myfuncpytest搜索到和形参同名的一个fixture函数,调用执行函数并且将该函数的返回值作为test_01的实参传入。

2.  fixture:一个典型的依赖注入的实践

所谓的注入,也就是用例可以接收一个预处理的对象。即用例需要什么,我就给它什么,至于这个对象是如何产生如何实现的并不关心,只需要这个对象有效。

3. conftest.py:共享fixture实例

如果你想在多个测试模块中共享同一个fixture实例,那么你可以把这个fixture移动到conftest.py(文件名固定不可变)文件中。在测试模块中你不需要手动的导入它,pytest会自动发现,fixture的查找的顺序是:测试类、测试模块、conftest.py、最后是内置和第三方的插件,即如果在测试类和conftest.py中有一个同名的fixture时,该测试类(仅在运行该类时)的fixture会被有限调用

4. 共享测试数据

可以使用两个方法实现

1)使用fixture传值,具体请参考2.1节;

2)使用第三方插件pytest-datadirpytest-datafiles传递数据

datadir

#firstdemo.py 本模块名

# 读取全局变量内文件夹名字叫data的“hello.txt”文件
def test_read_global(shared_datadir):
    contents = (shared_datadir / 'hello.txt').read_text()
    assert contents == 'Hello World!\n'

# 读取和本模块同级的“spam.txt”文件
def test_read_module(datadir):
    contents = (datadir / 'spam.txt').read_text()
    assert contents == 'eggs\n'

1. 作用域:在跨类的、模块的或整个测试会话的用例中,共享fixture实例

fixture有五个级别,即scope参数可能的值都有:function(默认值)、classmodulepackage3.7版本及之后session他们的作用域分别为用例级、测试类级、模块级、包级、会话级。如使用了会话级的fixture,则整个会话内的测试用例都会共用这个fixture。如果同时使用了两个不同级别的fixture,则级别高的会把级别低的包裹起来,比如同时使用了测试类和用例级的fixture,则执行的顺序是:类的前置--用例1的前置--用例1的后置--用例2的前置--用例2的后置--类的后置

import pytest

@pytest.fixture()
def myfunc1():
    print("这是用例1的前置")
    yield
    print("这是用例1的后置")

@pytest.fixture()
def myfunc2():
    print("这是用例2的前置")
    yield
    print("这是用例2的后置")

@pytest.fixture(scope="class")
def myfunc3():
    print("这是类的前置")
    yield
    print("这是类的后置")

@pytest.mark.usefixtures("myfunc3")
class Test_fixture:

    @pytest.mark.usefixtures("myfunc1")
    def test_01(self):
        print("用例1")
        assert 0

    @pytest.mark.usefixtures("myfunc2")
    def test_02(self):
        print("用例2")
        assert 0

输出结果

fixturetest.py:33: AssertionError
---------------------------- Captured stdout setup ----------------------------
这是类的前置
这是用例1的前置
---------------------------- Captured stdout call -----------------------------
用例1
-------------------------- Captured stdout teardown ---------------------------
这是用例1的后置
____________________________ Test_fixture.test_02 _____________________________

self = <fixturetest.Test_fixture object at 0x000002218DC0A5F8>

    @pytest.mark.usefixtures("myfunc2")
    def test_02(self):
        print("用例2")
>       assert 0
E       assert 0

fixturetest.py:38: AssertionError
---------------------------- Captured stdout setup ----------------------------
这是用例2的前置
---------------------------- Captured stdout call -----------------------------
用例2
-------------------------- Captured stdout teardown ---------------------------
这是用例2的后置
这是类的后置
============================== 2 failed in 0.09s ==============================

 

6.工厂函数

如果你需要在一个测试用例中,多次使用同一个fixture实例,相对于直接返回数据,更好的方法是返回一个产生数据的工厂函数并且,对于工厂函数产生的数据,也可以在fixture中对其管理:

工厂函数的概念:一个函数(外部函数)内嵌另一个函数(内部函数),在调用外部函数的时候不会调用内部函数,只对其进行定义,内部函数作为外部函数的返回值返回。

x = 99
def f1():
    x = 88
    def f2(): # 工厂函数
        print(x)
    return f2

a = f1() # 调用f1时返回的是f2函数
print(a)
b = a()

 

输出

<function f1.<locals>.f2 at 0x0000027126AF5AE8>
88

fixture中使用工厂函数

import pytest
@pytest.fixture
def make_customer_record():

    # 记录生产的数据
    created_records = []

    # 工厂函数
    def _make_customer_record(name):
        # record = models.Customer(name=name, orders=[])
        created_records.append(name)
        print(created_records)
        return created_records

    yield _make_customer_record

    # 销毁数据
    print(created_records)
    for record in created_records:
        created_records.remove(record)
        print(created_records)
        print("这是后置")


def test_customer_records(make_customer_record):
    customer_1 = make_customer_record("Lisa")
    customer_2 = make_customer_record("Mike")
    customer_3 = make_customer_record("Meredith")
    assert 0

该实例的作用是:每调用一次fixture实例方法,就会往created_records中增加一条数据,待用例执行结束后,清除数据

7.fixtrue参数化

如果你需要在一系列的测试用例的执行中,每轮执行都使用同一个fixture,但是有不同的依赖场景,那么可以考虑对fixture进行参数化;这种方式适用于对多场景的功能模块进行详尽的测试

params参数中有几个参数,则该用例或该类就会被执行多少轮

 

@pytest.fixture(params=["前置1","前置2"])

# @pytest.fixture(params=[("a","b"),("c","d")])   传入参数组的形式
def myfunc1(request):
    data = request.param
    print(data)
    yield
    print("这是一个后置")

@pytest.mark.usefixtures("myfunc1")
def test_01():
    print("用例1")
    assert 0

输出结果为:

---------------------------- Captured stdout setup ----------------------------
前置1
---------------------------- Captured stdout call -----------------------------
用例1
-------------------------- Captured stdout teardown ---------------------------
这是一个后置
___________________________ test_01[\u524d\u7f6e2] ____________________________

    @pytest.mark.usefixtures("myfunc1")
    def test_01():
        print("用例1")
>       assert 0
E       assert 0

fixturetest.py:19: AssertionError
---------------------------- Captured stdout setup ----------------------------
前置2
---------------------------- Captured stdout call -----------------------------
用例1
-------------------------- Captured stdout teardown ---------------------------
这是一个后置
============================== 2 failed in 0.10s ==============================

可见该用例被执行了两次,并且每次的params参数不一样,应用场景举例:在ST环境和UAT环境分别全量执行用例,则可将环境参数放置params中,设置为会话级别的fixture

若要传输动态参数,可使用往params中传入函数的形式

@pytest.fixture(params=myfunc) # myfunc为函数名
def myfunc1(request):
    a = request.param # a = myfunc
    yield a()

 

8.在参数化的fixture中给用例打标签

方法1:在@pytest.fixture中使用pytest.param参数,用marks=标签的形式(针对前后置)

import pytest

@pytest.fixture(params=["前置1",pytest.param("前置2",marks=pytest.mark.demo)])
def myfunc1(request):
    data = request.param
    print(data)
    yield
    print("这是一个后置")

@pytest.mark.usefixtures("myfunc1")
def test_01():
    print("用例1")
    assert 0

if __name__ == '__main__':
    pytest.main(["-m","demo","fixturetest.py"])

这种写法的意思是:该用例执行两遍,入参分别为“前置1”和“前置2”,并且为pytest.param中的用例(每个参数对应一条用例)打上demo标签

输出结果为:

---------------------------- Captured stdout setup ----------------------------
前置2
---------------------------- Captured stdout call -----------------------------
<FixtureRequest for <Function test_01[\u524d\u7f6e2]>>
用例1
-------------------------- Captured stdout teardown ---------------------------
这是一个后置
======================= 1 failed, 1 deselected in 0.09s =======================

 

方法2:使用pytest.mark.parametrize(针对测试用例)达到同样的效果

@pytest.mark.parametrize("request",["内容1",pytest.param("内容2",marks=pytest.mark.demo)])
def test_01(request):
    print(request)
    print("用例1")
    assert 0


if __name__ == '__main__':
    pytest.main(["-m","demo","fixturetest.py"])

意思为:该用例执行两遍,入参分别为“内容1”和“内容2”,并且为pytest.param中的用例(每个参数对应一条用例)打上demo标签

输出结果为:

---------------------------- Captured stdout call -----------------------------
内容2
用例1
======================= 1 failed, 1 deselected in 0.10s =======================

9. fixture间的相互调用

1)同级别fixture调用:

被调用的fixture先被实例化,即被调用者会把调用者包裹

@pytest.fixture()
def myfunc1(myfunc2):
    print("用例前置1")
    print(myfunc2)
    yield
    print("这是用例1后置")

@pytest.fixture()
def myfunc2():
    print("用例前置2")
    yield "前置2返回值"
    print("这是用例2后置")

@pytest.mark.usefixtures("myfunc1")
def test_01():
    print("用例1")
    assert 0

输出结果为:

---------------------------- Captured stdout setup ----------------------------
用例前置2
用例前置1
前置2返回值
---------------------------- Captured stdout call -----------------------------
用例1
-------------------------- Captured stdout teardown ---------------------------
这是用例1后置
这是用例2后置
============================== 1 failed in 0.07s ==============================

可以看出,该例子是先执行了myfunc2(被调用者)的前置,再执行myfunc1(调用者)的前置,然后执行用例,再执行myfunc1的后置,最后是myfunc2的后置,即被调用者把调用者包裹

2)不同级别fixture的调用

由第一点特性可以知道,由于被调用者会先执行,所以被调用的作用域要比调用者的高或者同级,即类级别的fixture只能调用模块级的和会话级的,不能调用用例级的

@pytest.fixture()
def myfunc1(myfunc2):
    print("用例前置1")
    print(myfunc2)
    yield
    print("这是用例1后置")

@pytest.fixture(scope="class")
def myfunc2():
    print("前置")
    yield "前置返回值"
    print("后置")

class Test_01():

    @pytest.mark.usefixtures("myfunc1")
    def test_01(self):
        print("用例1")
        assert 0

    def test_02(self):
        print("用例2")
        assert 0

输出结果为:

---------------------------- Captured stdout setup ----------------------------
类前置
用例前置1
类前置返回值
---------------------------- Captured stdout call -----------------------------
用例1
-------------------------- Captured stdout teardown ---------------------------
这是用例1后置
_______________________________ Test_01.test_02 _______________________________

self = <fixturetest.Test_01 object at 0x0000017236BA57B8>

    def test_02(self):
        print("用例2")
>       assert 0
E       assert 0

fixturetest.py:32: AssertionError
---------------------------- Captured stdout call -----------------------------
用例2
-------------------------- Captured stdout teardown ---------------------------
类后置
============================== 2 failed in 0.11s ==============================

即类级别的fixture会先作用,同时要注意的是,类级别的fixture被用例级的fixture引用后,其本身的级别不变,还是类级别

10.在类、模块和项目级别上使用fixture实例

1)使用多个前置

@pytest.mark.usefixtures("myfunc1","myfunc2")

2)在类中使用前置

@pytest.mark.usefixtures("myfunc1")
class Test_01():

    def test_01(self):
        print("用例1")
        assert 0

3)在模块中使用前置

pytestmark = pytest.mark.usefixtures("myfunc1")

注:参数名pytestmark不可变

4)在项目中使用前置

# pytest.ini

[pytest]
usefixtures = cleandir

11.自动使用fixture

@pytest.fixture(autouse=True)

注意:使用自动使用fixture时,要注意作用域,比如在类里面声明的,作用域就是在类里面

class Test_01():
    @pytest.fixture(autouse=True)
    def myfunc1(self):
        print("前置1")
        yield
        print("后置1")

 

猜你喜欢

转载自www.cnblogs.com/handsomesuancaiyu/p/12116711.html