测试固件fixture(四):后置teardown操作

前言:

一条测试用例的执行,可能需要前置操作,也可能需要对齐进行后置操作,fixture也可以进行后置操作。

 

一、如何实现teardown操作

通过yield关键字实现。

fixture装饰的函数中,yield有两个作用:1,返回(同return)。2,其后的代码提供teardown效果。

示例:

import pytest


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


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")


class Test2A:
    def test_2_b(self, login):
        print("this is test_2_b")
        print(login)

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

执行结果:

test_1.py this is login
this is test_1_b
.teardown
this is test_1_c
.this is login
this is test_2_b
login return
.teardown
this is test_2_c
.

=============== 4 passed in 0.02s ===============

从执行结果可以看出,test_2_b显示调用fixture后,拿到了其返回值(yield后的返回值),也执行了后置操作(teardown)。

 

二、关键点:

如果yield前面的代码,即setup部分已经抛出异常了,则不会执行yield后面的teardown内容。

如果测试用例抛出异常,yield后面的teardown内容还是会正常执行。

 

posted @ 2022-02-23 15:54  Target_L  阅读(78)  评论(0)    收藏  举报