From e34a22d5795bab420cef4aa3f0108bfbefc837a2 Mon Sep 17 00:00:00 2001 From: ikappaki Date: Sat, 17 May 2025 13:30:41 +0100 Subject: [PATCH] Replace `:` with `;` in the assertion rewrite warning message so it can be filtered using standard Python warning filters. --- changelog/5473.improvement.rst | 1 + src/_pytest/assertion/rewrite.py | 2 +- testing/test_assertrewrite.py | 18 +++++++++++++++++- 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 changelog/5473.improvement.rst diff --git a/changelog/5473.improvement.rst b/changelog/5473.improvement.rst new file mode 100644 index 00000000000..1b9ab006d49 --- /dev/null +++ b/changelog/5473.improvement.rst @@ -0,0 +1 @@ +Replace `:` with `;` in the assertion rewrite warning message so it can be filtered using standard Python warning filters before calling :func:`pytest.main`. diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 2e606d1903a..c4782c7c5a8 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -281,7 +281,7 @@ def _warn_already_imported(self, name: str) -> None: self.config.issue_config_time_warning( PytestAssertRewriteWarning( - f"Module already imported so cannot be rewritten: {name}" + f"Module already imported so cannot be rewritten; {name}" ), stacklevel=5, ) diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 02d1c3e52ff..e2e448fe5e6 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -1197,7 +1197,23 @@ def test_rewrite_warning(self, pytester: Pytester) -> None: ) # needs to be a subprocess because pytester explicitly disables this warning result = pytester.runpytest_subprocess() - result.stdout.fnmatch_lines(["*Module already imported*: _pytest"]) + result.stdout.fnmatch_lines(["*Module already imported*; _pytest"]) + + def test_rewrite_warning_ignore(self, pytester: Pytester) -> None: + pytester.makeconftest( + """ + import pytest + pytest.register_assert_rewrite("_pytest") + """ + ) + # needs to be a subprocess because pytester explicitly disables this warning + result = pytester.runpytest_subprocess( + "-W", + "ignore:Module already imported so cannot be rewritten; _pytest:pytest.PytestAssertRewriteWarning", + ) + # Previously, when the message pattern used to contain an extra `:`, an error was raised. + assert not result.stderr.str().strip() + result.stdout.no_fnmatch_line("*Module already imported*; _pytest") def test_rewrite_module_imported_from_conftest(self, pytester: Pytester) -> None: pytester.makeconftest(