Skip to content

Commit 24ef7c9

Browse files
Merge pull request #10343 from RonnyPfannschmidt/fix-10342-warn-explicit-add-location
fix #10342: put location into warning exceptions
2 parents c4981f5 + 7a15bad commit 24ef7c9

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

src/_pytest/warning_types.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -158,12 +158,15 @@ def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None:
158158
filename = inspect.getfile(method)
159159
module = method.__module__
160160
mod_globals = method.__globals__
161-
162-
warnings.warn_explicit(
163-
message,
164-
type(message),
165-
filename=filename,
166-
module=module,
167-
registry=mod_globals.setdefault("__warningregistry__", {}),
168-
lineno=lineno,
169-
)
161+
try:
162+
warnings.warn_explicit(
163+
message,
164+
type(message),
165+
filename=filename,
166+
module=module,
167+
registry=mod_globals.setdefault("__warningregistry__", {}),
168+
lineno=lineno,
169+
)
170+
except Warning as w:
171+
# If warnings are errors (e.g. -Werror), location information gets lost, so we add it to the message.
172+
raise type(w)(f"{w}\n at {filename}:{lineno}") from None

testing/test_warning_types.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,11 @@ def test():
3636
)
3737
result = pytester.runpytest()
3838
result.stdout.fnmatch_lines(["E pytest.PytestWarning: some warning"])
39+
40+
41+
@pytest.mark.filterwarnings("error")
42+
def test_warn_explicit_for_annotates_errors_with_location():
43+
with pytest.raises(Warning, match="(?m)test\n at .*python_api.py:\\d+"):
44+
warning_types.warn_explicit_for(
45+
pytest.raises, warning_types.PytestWarning("test") # type: ignore
46+
)

0 commit comments

Comments
 (0)