Return variable from conftest to test class

2.2k Views Asked by At

I have the following scripts:

conftest.py:

import pytest
@pytest.fixture(scope="session")
def setup_env(request):
    # run some setup
    return("result")

test.py:

import pytest
@pytest.mark.usefixtures("setup_env")
class TestDirectoryInit(object):   
    def setup(cls):
        print("this is setup")
        ret=setup_env()
        print(ret)

    def test1():
        print("test1")

    def teardown(cls):
        print("this teardown")

I get the error:

    def setup(cls):
        print("this is setup")
>       ret=setup_env()
E       NameError: name 'setup_env' is not defined

In setup(), I want to get the return value "result" from setup_env() in conftest.py.

Could any expert guide me how to do it?

1

There are 1 best solutions below

0
MrName On

I believe that @pytest.mark.usefixtures is more meant for state alteration prior to the execution of each test. From the docs:

"Sometimes test functions do not directly need access to a fixture object."

https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects

Meaning that your fixture is running at the start of each test, but your functions do not have access to it.

When your tests need access to the object returned by your fixture, it should be already populated by name when placed in conftest.py and marked with @pytest.fixture. All you need to do is then delcare the name of the fixture as an argument to your test function, like so:

https://docs.pytest.org/en/latest/fixture.html#using-fixtures-from-classes-modules-or-projects

If you prefer to do this on a class or module level, you want to change the scope of your @pytest.fixture statement, like so:

https://docs.pytest.org/en/latest/fixture.html#sharing-a-fixture-across-tests-in-a-module-or-class-session

Sorry for so many links to the docs, but I think they have good examples. Hope that clears things up.