简体   繁体   English

如何在 conftest.py 中设置会话详细信息以获取收益以及 pytest 中的夹具?

[英]How can I set session details in conftest.py for yield along with fixture in pytest?

My aim is to create a pretest and post test in conftest.py file which will run after each test case in my test suite.我的目标是在conftest.py 文件中创建一个预测试和后测试,它将在我的测试套件中的每个测试用例之后运行。 ie I was trying to run the methods (login_page() and login()) before all tests and the methods (logout()) after all tests.即我试图在所有测试之前运行方法(login_page() 和 login()),在所有测试之后运行方法(logout())

I have tried using the below code snippet我试过使用下面的代码片段

@pytest.fixture(scope="session", autouse=True)
def pretest():
    login_page()
    login()
    yield driver
    logout()

I have observed that, while my pre-tests (login_page() & login()) are running perfectly, before all test cases, post-tests (logout()) are not working as intended and was running only after all my selected test cases were executed.我观察到,虽然我的预测试 (login_page() 和 login()) 运行良好,但在所有测试用例之前,后测试 (logout()) 没有按预期工作,并且在我选择的所有测试之后运行案件被执行。

To try a different approach, I had tried using the below code snippet in conftest.py as well为了尝试不同的方法,我也尝试在conftest.py 中使用以下代码片段

@pytest.fixture(scope="session", autouse=True)
def pretest():
    login_page()
    login()
@pytest.yield_fixture(scope="session", autouse=True)
def posttest():
    logout()

The above method was simply throwing some errors and was not launching the test as such.上面的方法只是抛出了一些错误,并没有像这样启动测试。

I had also tried the below code snippet in conftest.py file我还在conftest.py文件中尝试了以下代码片段

@pytest.yield_fixture(scope="session", autouse=True)
def pretest():
    login_page()
    login()
    yield driver
    logout()

I think that you're really close, and your issue comes from using the "session" scope, which is the higher possible scope (see more in Pytest fixture scope ).我认为您真的很接近,并且您的问题来自使用"session"范围,这是可能的更高范围(请参阅Pytest fixture scope 中的更多内容)。

Using "session" means your fixture is executed once for all the test run.使用"session"意味着您的夹具在所有测试运行中都执行一次。 If you're yield -ing in that fixture, what comes before the yield will be executed before all tests (not before each test!), and what comes after will run after all tests have run.如果您在该夹具中使用yield -ing,则yield之前的内容将在所有测试之前执行(而不是在每个测试之前!),之后的内容将在所有测试运行后运行。

Switching this to "function" instead will make the fixture run before/after each test instead, which is what you want:将其切换为"function"将使夹具在每次测试之前/之后运行,这就是您想要的:

@pytest.fixture(scope="function", autouse=True)
def login_context():  # Renamed for clarity
    login_page()
    login()
    yield driver  # Not sure what this is?
    logout()

Note the rename here: pretest is misleasing because part of the fixture will actually be executed after the test.注意这里的重命名: pretest是误导性的,因为夹具的一部分实际上会在测试之后执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM