Search code examples
pythonpytest

How to share object from fixture to all tests using pytest?


What is the best way to define an object in a fixture with session scope and autouse=True, so it will be available to all tests?

@pytest.fixture(scope='session', autouse=True)
def setup_func(request):
    obj = SomeObj()

Next thing, I want some magic that previously created obj will appear in each test context without the need of each test to define the setup_func fixture.

def test_one():
   obj.do_something_fancy()

Solution

  • My recommendation would to add the fixture to conftest.py and make sure to return the object you want to produce from the fixture.

    As noted, this makes "autouse" kind of useless.

    In the root directory for your tests, add the fixture to a file named conftest.py:

    @pytest.fixture(scope='session', autouse=True)
    def someobj(request):
        return SomeObj()
    

    Any test file beneath the root file will have access to this fixture (for example test_foo.py):

    def test_foo(someobj):
        assert isinstance(someobj, SomeObj)
    

    Another approach, would be to use a global variable defined in the same test or imported from a module.

    For example in conftest.py:

    someobj = None
    @pytest.fixture(scope='session', autouse=True)
    def prep_someobj(request):
        someobj = SomeObj()
    

    Then in your test:

    from . import conftest
    
    def test_foo():
        assert isinstance(conftest.someobj, SomeObj)
    

    In my opinion this is less readable and more cumbersome than the first method.