pytest四:fixture_yield 实现 teardown

既然有 setup 那就有 teardown,fixture 里面的 teardown 用 yield 来唤醒 teardown的执行

在所有用例执行完后执行:yield

import pytest

@pytest.fixture(scope='module')
def open():
print('打开浏览器=============')

yield
print('执行teardown!!!')
print('最后关闭浏览器')

def test_s1(open):
print('用例1111111')

def test_s2(open):
print('用例22222222')

def test_s3(open):
print('用例33333333')

if __name__=='__main__':
pytest.main()

yield 遇到异常

1、如果其中一个用例出现异常,不影响 yield 后面的 teardown 执行,运行结果互不影响,并且全部用例执行完之后,yield 呼唤 teardown操作

import pytest

@pytest.fixture(scope='module')
def open():
print(' 打开浏览器=============')

yield
print('执行teardown!!!')
print('最后关闭浏览器')

def test_s1(open):
print('用例1111111')

# 如果第一个用例异常了,不影响其他用的例执行
raise NameError # 模拟异常

def test_s2(open):
print('用例22222222')

def test_s3(open):
print('用例33333333')

if __name__=='__main__':
pytest.main()

2.如果在 setup 就异常了,那么是不会去执行 yield 后面的teardown 内容了

3.yield 也可以配合 with 语句使用,以下是官方文档给的案例

import smtplib
import pytest

@pytest.fixture(scope='module')
def smtp():
with smtplib.SMTP('smtp.gmail.com') as smtp:
yield smtp # provide the fixture value

addfinalizer 方法终结函数

1、除了 yield 可以实现 teardown,在 request-context 对象中注册addfinalizer 方法也可以实现终结函数。
2、yield 和 addfinalizer 方法都是在测试完成后呼叫相应的代码。但是 addfinalizer 不同的是:
  1.他可以注册多个终结函数。
  2.返些终结方法总是会被执行,无论在之前的 setup code 有没有抛出错误。这个方法对于正确关闭所有的 fixture 创建的资源非常便利,即使其一在创建或获取时失败

import smtplib
import pytest

@pytest.fixture(scope='module')
def smtp_connection(request):
smtp_connection = smtplib.SMTP('smtp.gmail.com', 587, timeout=5)
def fin():
print('teardown smtp_connection')
smtp_connection.close()
request.addfinalizer(fin)
return smtp_connection # provide the fixture value

原文地址:https://www.cnblogs.com/zhongyehai/p/9679823.html