diff --git a/changelog/9984.trivial.rst b/changelog/9984.trivial.rst new file mode 100644 index 000000000..cca817062 --- /dev/null +++ b/changelog/9984.trivial.rst @@ -0,0 +1,4 @@ +Improve the error message when we attempt to access a fixture that has been +torn down. +Add an additional sentence to the docstring explaining when it's not a good +idea to call getfixturevalue. diff --git a/src/_pytest/fixtures.py b/src/_pytest/fixtures.py index ee3e93f19..af5b449d0 100644 --- a/src/_pytest/fixtures.py +++ b/src/_pytest/fixtures.py @@ -548,11 +548,18 @@ class FixtureRequest: setup time, you may use this function to retrieve it inside a fixture or test function body. + This method can be used during the test setup phase or the test run + phase, but during the test teardown phase a fixture's value may not + be available. + :raises pytest.FixtureLookupError: If the given fixture could not be found. """ fixturedef = self._get_active_fixturedef(argname) - assert fixturedef.cached_result is not None + assert fixturedef.cached_result is not None, ( + f'The fixture value for "{argname}" is not available. ' + "This can happen when the fixture has already been torn down." + ) return fixturedef.cached_result[0] def _get_active_fixturedef(