测试固件fixture(三):调用fixture的两种方式及区别

方式一:

将fixture前置操作的函数名传入测试用例中。

方式二:

使用pytest.mark.usefixtures()装饰器。

usefixtures()传入字符串形式的前置操作函数名。

示例:

import pytest


@pytest.fixture()
def login():
    print("this is login")
    return "login fixture"


class Test1A:
    @pytest.mark.usefixtures("login")
    def test_1_b(self):
        print("this is test_1_b")

    def test_1_c(self):
        print("this is test_1_c")


@pytest.mark.usefixtures("login")
class Test2A:
    def test_2_b(self):
        print("this is test_2_b")

    def test_2_c(self):
        print("this is test_2_c")

执行结果:

test_1.py this is login
this is test_1_b
.this is test_1_c
.this is login
this is test_2_b
.this is login
this is test_2_c
.
================= 4 passed in 0.02s ====================

我们可以看到,被@pytest.mark.usefixtures(name='xxx')装饰的用例,执行了前置操作。若类被装饰,则类中的每一个用例都会执行前置操作。

 

区别(重点):

显示调用前置fixture,可以使用前置操作的函数名拿到返回值。而使用@pytest.mark.usefixtures()则无法拿到其返回值

posted @ 2022-02-22 19:46  Target_L  阅读(106)  评论(0)    收藏  举报