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?
I believe that
@pytest.mark.usefixturesis 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.pyand 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
scopeof your@pytest.fixturestatement, 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.