[英]How can I set session details in conftest.py for yield along with fixture in pytest?
我的目标是在conftest.py 文件中创建一个预测试和后测试,它将在我的测试套件中的每个测试用例之后运行。 即我试图在所有测试之前运行方法(login_page() 和 login()),在所有测试之后运行方法(logout()) 。
我试过使用下面的代码片段
@pytest.fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
yield driver
logout()
我观察到,虽然我的预测试 (login_page() 和 login()) 运行良好,但在所有测试用例之前,后测试 (logout()) 没有按预期工作,并且仅在我选择的所有测试之后运行案件被执行。
为了尝试不同的方法,我也尝试在conftest.py 中使用以下代码片段
@pytest.fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
@pytest.yield_fixture(scope="session", autouse=True)
def posttest():
logout()
上面的方法只是抛出了一些错误,并没有像这样启动测试。
我还在conftest.py文件中尝试了以下代码片段
@pytest.yield_fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
yield driver
logout()
我认为您真的很接近,并且您的问题来自使用"session"
范围,这是可能的更高范围(请参阅Pytest fixture scope 中的更多内容)。
使用"session"
意味着您的夹具在所有测试运行中都执行一次。 如果您在该夹具中使用yield
-ing,则yield
之前的内容将在所有测试之前执行(而不是在每个测试之前!),之后的内容将在所有测试运行后运行。
将其切换为"function"
将使夹具在每次测试之前/之后运行,这就是您想要的:
@pytest.fixture(scope="function", autouse=True)
def login_context(): # Renamed for clarity
login_page()
login()
yield driver # Not sure what this is?
logout()
注意这里的重命名: pretest
是误导性的,因为夹具的一部分实际上会在测试之后执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.