From 0e62861e847eeca1fb76bd63a03b1c5d5ef23206 Mon Sep 17 00:00:00 2001 From: Pete Baughman <99513503+petebman@users.noreply.github.com> Date: Mon, 23 May 2022 17:44:27 +0000 Subject: [PATCH] Improve error message in getfixturevalue --- changelog/9984.trivial.rst | 4 ++++ src/_pytest/fixtures.py | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 changelog/9984.trivial.rst 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(