diff --git a/AUTHORS b/AUTHORS index f04403e2d5c..a5bd2e1835c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -239,6 +239,7 @@ James Bourbeau James Frost James V Jan Balster +Jania Hernández Dormuz Janne Vanhala Jason R. Coombs Javier Domingo Cansino diff --git a/changelog/15097.bugfix.rst b/changelog/15097.bugfix.rst new file mode 100644 index 00000000000..32a688bb5df --- /dev/null +++ b/changelog/15097.bugfix.rst @@ -0,0 +1 @@ +:meth:`pytest.WarningsRecorder.pop` now returns the first matching warning when the matches have unrelated categories, instead of the last one. diff --git a/src/_pytest/recwarn.py b/src/_pytest/recwarn.py index 3e36fc7d286..99e846d1127 100644 --- a/src/_pytest/recwarn.py +++ b/src/_pytest/recwarn.py @@ -213,17 +213,19 @@ def pop(self, cls: type[Warning] = Warning) -> warnings.WarningMessage: but not an instance of a child class of any other match. Raises ``AssertionError`` if there is no match. """ - best_idx: int | None = None + categories = {w.category for w in self._list if issubclass(w.category, cls)} + # Keep only the categories that are not a subclass of another match. + least_derived = { + category + for category in categories + if not any( + other is not category and issubclass(category, other) + for other in categories + ) + } 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) + if w.category in least_derived: + return self._list.pop(i) __tracebackhide__ = True raise AssertionError(f"{cls!r} not found in warning list") diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index d6de42a4c5c..ffce9b5b243 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -52,6 +52,9 @@ class ChildWarning(ParentWarning): class ChildOfChildWarning(ChildWarning): pass + class SiblingWarning(ParentWarning): + pass + @staticmethod def raise_warnings_from_list(_warnings: list[type[Warning]]): for warn in _warnings: @@ -82,6 +85,22 @@ def test_pop_finds_best_inexact_match(self): _warn = record.pop(self.ParentWarning) assert _warn.category is self.ChildWarning + def test_pop_unrelated_matches_returns_first(self): + with pytest.warns(self.ParentWarning) as record: + self.raise_warnings_from_list([self.ChildWarning, self.SiblingWarning]) + + _warn = record.pop(self.ParentWarning) + assert _warn.category is self.ChildWarning + + def test_pop_unrelated_matches_prefers_less_derived(self): + with pytest.warns(self.ParentWarning) as record: + self.raise_warnings_from_list( + [self.ChildOfChildWarning, self.SiblingWarning, self.ChildWarning] + ) + + _warn = record.pop(self.ParentWarning) + assert _warn.category is self.SiblingWarning + class TestWarningsRecorderChecker: def test_recording(self) -> None: