2

this sample code does work:

content of conftest.py

import pytest

env_globals = {"glb1": "g1",
               "glb2": "g2"}


@pytest.fixture(scope="session", autouse=True)
def init_globals():
    return env_globals

content of test_module.py

import pytest


class Test:

    @pytest.fixture(scope="class")
    def fixt(self, init_globals):
        payload = {
            "key1": init_globals['glb1'],
            "key2": init_globals['glb2']
        }
        return payload

    def test_something(self, fixt):
        assert len(fixt) == 2

my question is why do i still need to explicitly request the init_globals fixture in the test module, if in conftest it was already declared as (scope="session", autouse=True), i.e it should already be visible to anything in any test module in the project? if i just try def fixt(self) it gives me error "{NameError}name 'init_globals' is not defined"

tester11
  • 93
  • 7
  • 1
    Does this answer your question? [Access autouse fixture without having to add it to the method argument](https://stackoverflow.com/questions/37000463/access-autouse-fixture-without-having-to-add-it-to-the-method-argument) – D Malan Apr 25 '22 at 12:50
  • the link does state the exact same problem (and the second part of it, likewise, is inability to use @pytest.mark.usefixtures() syntax for such conftest fixtures either) but what is the current correct solution to this? – tester11 Apr 25 '22 at 13:08
  • 1
    There is no "solution" as you want to have it - read the comments under the first answer. The misunderstanding here is probably the `autouse` setting: it just means that the fixture is implicitely _applied_ to each test, not that it can be used inside the test. Fixtures can _only_ be used a arguments in tests and other fixtures. Making a fixture that just returns a value `autouse=True` is pointless - this is thought for fixtures with a side effect, e.g. setup and tear down logic. – MrBean Bremen Apr 25 '22 at 18:27
  • 1
    Here is [another related question](https://stackoverflow.com/questions/62916820/how-to-get-pytest-fixture-return-value-in-autouse-mode) you can check. – MrBean Bremen Apr 25 '22 at 18:28
  • 1
    thank you for the links and explanation! it is becoming more clear now, so an autouse fixture from conftest DOES get executed, but cannot be automatically referenced from test module unless listed in arguments, is that it? if you needed a global dict of constants accessible from any test module how would you implement it? – tester11 Apr 26 '22 at 09:33
  • Exactly right. If you need that global dict, just implement it as a global attribute or function, not as a fixture. As long as the global is read-only, it should not be a problem. – MrBean Bremen Apr 26 '22 at 17:47

0 Answers0