From 14919c4bbbeca42a1822858ee31f928c0b2e35dd Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Thu, 6 Oct 2022 11:44:05 +0200 Subject: [PATCH 1/2] fix #10342: put location into warning exceptions as the warning systems own warn_explicit looses the information we add them explicitly to the warning exceptions --- src/_pytest/warning_types.py | 20 +++++++++++--------- testing/test_warning_types.py | 8 ++++++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/_pytest/warning_types.py b/src/_pytest/warning_types.py index 88a51399182..388949bed53 100644 --- a/src/_pytest/warning_types.py +++ b/src/_pytest/warning_types.py @@ -158,12 +158,14 @@ 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: + raise type(w)(f"{w}\n at {filename}:{lineno}") from None diff --git a/testing/test_warning_types.py b/testing/test_warning_types.py index b49cc68f9c6..5f69439ef3e 100644 --- a/testing/test_warning_types.py +++ b/testing/test_warning_types.py @@ -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 + ) From 7a15bad89b2a11923f06a5ac416303d77f48d05b Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Fri, 7 Oct 2022 12:46:40 +0200 Subject: [PATCH 2/2] Update src/_pytest/warning_types.py Co-authored-by: Florian Bruhin --- src/_pytest/warning_types.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/_pytest/warning_types.py b/src/_pytest/warning_types.py index 388949bed53..3be1648fe61 100644 --- a/src/_pytest/warning_types.py +++ b/src/_pytest/warning_types.py @@ -168,4 +168,5 @@ def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None: 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