pytest-dev/pytest · error · AssertionError

{cls!r} not found in warning list

Error message

{cls!r} not found in warning list

What it means

WarningsRecorder.pop raises AssertionError when no recorded warning matches the requested class (or a subclass). It searches the recorded list and fails if nothing matches.

Source

Thrown at src/_pytest/recwarn.py:228

    def pop(self, cls: type[Warning] = Warning) -> warnings.WarningMessage:
        """Pop the first recorded warning which is an instance of ``cls``,
        but not an instance of a child class of any other match.
        Raises ``AssertionError`` if there is no match.
        """
        best_idx: int | None = None
        for i, w in enumerate(self._list):
            if w.category == cls:
                return self._list.pop(i)  # exact match, stop looking
            if issubclass(w.category, cls) and (
                best_idx is None
                or not issubclass(w.category, self._list[best_idx].category)
            ):
                best_idx = i
        if best_idx is not None:
            return self._list.pop(best_idx)
        __tracebackhide__ = True
        raise AssertionError(f"{cls!r} not found in warning list")

    def clear(self) -> None:
        """Clear the list of recorded warnings."""
        self._list[:] = []

    # Type ignored because we basically want the `catch_warnings` generic type
    # parameter to be ourselves but that is not possible(?).
    def __enter__(self) -> Self:  # type: ignore[override]
        if self._entered:
            __tracebackhide__ = True
            raise RuntimeError(f"Cannot enter {self!r} twice")
        _list = super().__enter__()
        # record=True means it's None.
        assert _list is not None
        self._list = _list
        warnings.simplefilter("always")
        return self

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Ensure the code under test actually emits a warning of the requested category.
  2. Check recwarn.list (or iterate) before popping to confirm a matching warning exists.
  3. Prefer pytest.warns(ExpectedCategory) context manager over manual pop for clearer failure messages.
  4. Verify the warning category — pop matches by exact class first, then by most-specific subclass.

Example fix

// before
recwarn.pop(RuntimeWarning)  # may raise
// after
matches = [w for w in recwarn.list if issubclass(w.category, RuntimeWarning)]
assert matches, 'no RuntimeWarning emitted'
recwarn.pop(RuntimeWarning)
Defensive patterns

Strategy: try-catch

Validate before calling

matches = [w for w in recwarn.list if issubclass(w.category, cls)]
if not matches:
    pytest.fail(f'no {cls.__name__} warning was recorded')
recwarn.pop(cls)

Try / catch

try:
    recwarn.pop(RuntimeWarning)
except AssertionError:
    pytest.fail('expected a RuntimeWarning that was not emitted')

Prevention

When it happens

Trigger: Calling recwarn.pop(RuntimeWarning) when no RuntimeWarning (or subclass) was emitted during the test. Hits recwarn.py:228.

Common situations: The code under test didn't emit the expected warning; pop is called before the warning-emitting code ran; the warning category differs from what was expected.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/b90cdefc6a9095d8.json. Report an issue: GitHub.