Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recwarn: Fix module when re-emitting unmatched warnings #12898

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/11933.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix regression with :func:`pytest.warns` using wrong module when re-emitting unmatched warnings.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! 👍

8 changes: 7 additions & 1 deletion src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from pprint import pformat
import re
import sys
from types import TracebackType
from typing import Any
from typing import Callable
Expand Down Expand Up @@ -327,12 +328,17 @@ def found_str() -> str:
# Whether or not any warnings matched, we want to re-emit all unmatched warnings.
for w in self:
if not self.matches(w):
module = next(
k
for k, v in sys.modules.items()
if getattr(v, "__file__", None) == w.filename
)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably fallback to some string just in case something is very wrong and we cannot match the filename:

Suggested change
module = next(
k
for k, v in sys.modules.items()
if getattr(v, "__file__", None) == w.filename
)
module = next(
k
for k, v in sys.modules.items()
if getattr(v, "__file__", None) == w.filename,
None
)

I'm assuming None is a valid argument for module=.

warnings.warn_explicit(
message=w.message,
category=w.category,
filename=w.filename,
lineno=w.lineno,
module=w.__module__,
module=module,
source=w.source,
)

Expand Down
Loading