简体   繁体   中英

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. ie I was trying to run the methods (login_page() and login()) before all tests and the methods (logout()) after all tests.

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.

To try a different approach, I had tried using the below code snippet in conftest.py as well

@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

@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 ).

Using "session" means your fixture is executed once for all the test run. 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.

Switching this to "function" instead will make the fixture run before/after each test instead, which is what you want:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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