Hello lad
Hello lad

Reputation: 18790

Can not use autouse fixture to import module

I have a test module has one autouse fixture

import pytest

@pytest.fixture(autouse=True):
def set_env_config(monkeypatch):
    palladium_config =   os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), 'config.py')
    monkeypatch.setenv('PALLADIUM_CONFIG', palladium_config)
    from A import B

and in every followed test within this test module class B is needed, but this importation can not be achieved for any tests.

In the other way, I patch only the environment variable only

@pytest.fixture(autouse=True):
def set_env_config(monkeypatch):
    palladium_config =   os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), 'config.py')
    monkeypatch.setenv('PALLADIUM_CONFIG', palladium_config)

and import the class B in every test case, it succeeded.

Why is that? why can't I import class within autouse fixture?

Upvotes: 1

Views: 439

Answers (1)

Frank T
Frank T

Reputation: 9046

I am guessing that you are expecting something like the following:

@pytest.fixture(autouse=True)
def do_an_import():
    from A import B

def test_foo():
    assert B.do_my_thing() == 'foo'

That doesn't work, while doing the following does what you want:

def test_foo():
    from A import B
    assert B.do_my_thing() == 'foo'

Unfortunately doing an import in the fixture (the first example) will add B into that fixture function's namespace, but not the test function's namespace.

Similarly, this wouldn't work for the same reason:

@pytest.fixture
def not_an_autouse_fixture():
    from A import B

def test_foo(not_an_autouse_fixture):
    assert B.do_my_thing() == 'foo'

B is being imported into the fixture's namespace, which is different from the test's namespace. You could instead do:

@pytest.fixture
def Cls():
    from A import B
    return B

def test_foo(Cls):
    assert Cls.do_my_thing() == 'foo'

or you could import it at the top level of your module like:

from A import B

def test_foo(B):
    assert B.do_my_thing() == 'foo'

Upvotes: 0

Related Questions