Skip to content

fix #10342: put location into warning exceptions #10343

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

Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 12 additions & 9 deletions src/_pytest/warning_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,15 @@ def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None:
filename = inspect.getfile(method)
module = method.__module__
mod_globals = method.__globals__

warnings.warn_explicit(
message,
type(message),
filename=filename,
module=module,
registry=mod_globals.setdefault("__warningregistry__", {}),
lineno=lineno,
)
try:
warnings.warn_explicit(
message,
type(message),
filename=filename,
module=module,
registry=mod_globals.setdefault("__warningregistry__", {}),
lineno=lineno,
)
except Warning as w:
# If warnings are errors (e.g. -Werror), location information gets lost, so we add it to the message.
raise type(w)(f"{w}\n at {filename}:{lineno}") from None
8 changes: 8 additions & 0 deletions testing/test_warning_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,11 @@ def test():
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["E pytest.PytestWarning: some warning"])


@pytest.mark.filterwarnings("error")
def test_warn_explicit_for_annotates_errors_with_location():
with pytest.raises(Warning, match="(?m)test\n at .*python_api.py:\\d+"):
warning_types.warn_explicit_for(
pytest.raises, warning_types.PytestWarning("test") # type: ignore
)