I encountered this error because my scope was too high.
TLDR: Verify that your scopes are correct, and if needed, set the child to a lower scope – or create a new fixture from the parent in the child scope. scope="module"
was the culprit for me. I set to a lower scope - "function"
and it worked.
Story time:
Here's what I was trying to do (oversimplified):
1. Test a class which uses pytest's temporary directory:
import dataclasses
@dataclasses.dataclass
class Storage:
directory: str
def test_my_class(tmpdir):
"""Ensure Storage object can be instantiated"""
s = Storage(directory=tmpdir)
assert s.directory == str(tmpdir)
💡 However, I was writing dozens of tests, and I did not want to instantiate dozens of storage class objects.
2. Instead, I created this fixture:
@pytest.fixture()
def my_storage(tmpdir) -> Storage:
return Storage(directory=tmpdir)
def test_my_class(my_storage, tmpdir):
"""Ensure Storage object can be instantiated"""
assert my_storage.directory == tmpdir
💡 But I wanted the scope to be on the module level.
3. Setting scope to module level causes error:
@pytest.fixture(scope="module")
def my_storage(tmpdir) -> Storage:
return Storage(directory=tmpdir)
ScopeMismatch: You tried to access the function scoped fixture tmpdir with a module scoped request object, involved factories:
4. Easy solution = Set scope to function (default):
@pytest.fixture(scope="function")
def my_storage(tmpdir) -> Storage:
return Storage(directory=tmpdir)
This works. But what if I needed the fixture on the module level?
5. Hard solution = Create a temporary directory as a fixture, in the designated scope:
@pytest.fixture(scope="module")
def my_tmpdir(tmpdir_factory):
return tmpdir_factory.mktemp("data")
@pytest.fixture(scope="module")
def my_storage(my_tmpdir) -> Storage:
return Storage(directory=my_tmpdir)
def test_my_class(my_storage, my_tmpdir):
"""Ensure Storage object can be instantiated"""
assert my_storage.directory == my_tmpdir
file-1
fixture_1
is not decorated with@pytest.fixture
2) it has the same name asfile-2
fixture_1
3) it is returning a generator function, do you really want it? – Shifra