一、fixture之yield实现teardown
pytest中fixture通过scope参数控制setup级别,setup作为用例之前的操作,teardown操作作为用例执行完之后的操作。
fixture的teardown操作并不是独立的函数,用yield关键字唤醒teardown操作。
scope=“module”
fixture参数scope=“module”,module作用是整个.py文件都会生效,用例调用时,参数写上函数名称就行。
import pytest
@pytest.fixture(scope="module")
def open():
print("打开浏览器,并且打开百度首页")
def test_s1(open):
print("用例1:搜索python-1")
def test_s2(open):
print("用例2:搜索python-2")
def test_s3(open):
print("用例3:搜索python-3")
if __name__ == "__main__":
pytest.main(["-s", "test_f1.py"])
import pytest
@pytest.fixture(scope="module")
def open():
print("打开浏览器,并且打开百度首页")
# test_s1不调用
def test_s1():
print("用例1:搜索python-1")
# test_s2调用open
def test_s2(open):
print("用例2:搜索python-2")
# test_s3不调用
def test_s3():
print("用例3:搜索python-3")
if __name__ == "__main__":
pytest.main(["-s", "test_f1.py"])
上述场景中,module级别的fixture只会在第一次调用前执行一次。
yield执行teardown
fixture里面用yield来唤醒teardown的执行。
import pytest
@pytest.fixture(scope="module")
def open():
print("打开浏览器,并且打开百度首页")
yield
print("执行teardown!")
print("最后关闭浏览器")
def test_s1(open):
print("用例1:搜索python-1")
def test_s2(open):
print("用例2:搜索python-2")
def test_s3(open):
print("用例3:搜索python-3")
if __name__ == "__main__":
pytest.main(["-s", "test_f1.py"])
yield执行时遇到异常
- 如果其中一个用例出现异常,不影响yield后面的teardown执行,运行结果互不影响,并且全部用例执行完之后,yield呼唤teardown操作。
import pytest
@pytest.fixture(scope="module")
def open():
print("打开浏览器,并且打开百度首页")
yield
print("执行teardown!")
print("最后关闭浏览器")
def test_s1(open):
print("用例1:搜索python-1")
# 如果第一个用例异常了,不影响其他的用例执行
# 模拟异常
raise NameError
def test_s2(open):
print("用例2:搜索python-2")
def test_s3(open):
print("用例3:搜索python-3")
if __name__ == "__main__":
pytest.main(["-s", "test_f1.py"])
-
如果在setup就异常了,那么是不会去执行yield后面的teardown内容。
-
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终结函数
除了yield可以实现teardown,在request-context对象中注册addfinalizer方法也可以实现终结函数。
# 官方文档案例
# content of conftest.py
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
yield和addfinalizer方法都是在测试完成后呼叫相应的代码。