Sushant Thakur
Sushant Thakur

Reputation: 3

Sessions Level Pytest Fixture

I want to create a suite setup for my Pytest framework.

I have created one fixture name suite setup, which return some values for test cases to consume.

@pytest.fixture(scope=session) def suite_setup(arg1, arg2 ...)

then i have 3 files test1.py, test2.py andtest3.py file where i have multiple test cases, I want my suite setup to be called once and then all the test cases of .py files should execute and then in the end suite_teardown should execute.

I want order like this

Suite_steup testcase1 testcase2 testcase..n suite_teardown

can you please help me with the sytax.

if i run -n 2, my session level fixture should get called only 2 times on different env

i have created conftest with fixture but i am not sure how to call session level fixture only once for all test cases and i want to use values returned by session level fixture in all test cases.

i tried calling scope level fixture in test parameter of test cases, but it gets called everytime a new test case starts

Upvotes: 0

Views: 766

Answers (1)

flakes
flakes

Reputation: 23584

A simple way can be to define the fixture as a context manager by using a yield instead of a standard return. This will easily allow you to specify setup and teardown logic.

You may also wish to use autouse=True to force it to always be run even if the fixture is not explicitly specified as a test argument.

In conftest.py you can add something along the lines of this:

@pytest.fixture(scope="session", autouse=True)
def session_fixture():
    fixture = do_setup()
    yield fixture
    do_teardown(fixture)

Upvotes: 2

Related Questions