上一篇讲到fixture通过scope参数控制setup级别,既然有setup作为用例之前前的操作,用例执行完之后那肯定也有teardown操作。
这里用到fixture的teardown操作并不是独立的函数,用yield关键字呼唤teardown操作;
scope=“module”
1.fixture参数scope="module",module作用是整个.py文件都会生效,用例调用时,参数写上函数名称就行;
import pytest
@pytest.fixture(scope="module")
def login():
print("=================开始登陆login====================")
def test_01(login):
print("====================test_01================")
def test_02():
print("====================test_02================")
def test_03(login):
print("====================test_03================")
if __name__ == "__main__":
pytest.main(["-s","test_fix3.py"])
运行结果:
test_fix3.py::test_01 =================开始登陆login====================
PASSED [ 33%]====================test_01================
test_fix3.py::test_02 PASSED [ 66%]====================test_02================
test_fix3.py::test_03 PASSED [100%

本文详细探讨了pytest_fixture中的`yield`关键字如何实现teardown功能。通过`scope="module"`控制作用域,`yield`后的代码作为teardown在所有用例执行完毕后运行。即使在用例中遇到异常,`yield`后的代码仍然会被执行。此外,还介绍了`addfinalizer`方法,用于注册终结函数,确保测试资源的正确关闭,即使在fixture创建或获取时发生错误。
最低0.47元/天 解锁文章
356

被折叠的 条评论
为什么被折叠?



