bpo-34624: Allow regex for module passed via -W or PYTHONWARNINGS by coldfix · Pull Request #9358 · python/cpython · GitHub
Skip to content
Closed
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
8 changes: 5 additions & 3 deletions Doc/library/warnings.rst
20 changes: 20 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1157,6 +1157,26 @@ def test_envvar_and_command_line(self):
self.assertEqual(stdout,
b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")

def test_module_regex(self):
WARN_NOWHERE = 'True'
WARN_IN_MAIN = "import warnings; warnings.warn('__main__ warning');"
WARN_IN_SUBMOD = "import test.test_warnings.data.submodule_warning;"
# Check the warning is ignored by default:
assert_python_ok("-c", WARN_IN_MAIN, PYTHONWARNINGS="")
assert_python_ok("-c", WARN_IN_MAIN, PYTHONWARNINGS="ignore")
assert_python_ok("-c", WARN_IN_SUBMOD, PYTHONWARNINGS="")
assert_python_ok("-c", WARN_IN_SUBMOD, PYTHONWARNINGS="ignore")
# The submodule warning is still ignored because the pattern selects
# only to the package itself, not the submodule:
assert_python_ok("-c", WARN_IN_SUBMOD, PYTHONWARNINGS="error:::test")
# Warnings can be enabled by using wildcard regex:
assert_python_ok("-c", WARN_NOWHERE, PYTHONWARNINGS="error:::.*")
assert_python_failure("-c", WARN_IN_MAIN, PYTHONWARNINGS="error:::.*")
assert_python_failure("-c", WARN_IN_SUBMOD, PYTHONWARNINGS="error:::.*")
# Warning from submodule is raised using a more specific pattern:
assert_python_failure("-c", WARN_IN_SUBMOD,
PYTHONWARNINGS=r"error:::test.test_warnings(\..*)?")

def test_conflicting_envvar_and_command_line(self):
rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
"import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_warnings/data/submodule_warning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import warnings

warnings.warn('submodule warning', DeprecationWarning)
6 changes: 1 addition & 5 deletions Lib/warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,12 +220,8 @@ def _setoption(arg):
for s in parts]
action = _getaction(action)
category = _getcategory(category)
if message or module:
import re
if message:
message = re.escape(message)
if module:
module = re.escape(module) + r'\Z'
module = r'\A(' + module + r')\Z'
if lineno:
try:
lineno = int(lineno)
Expand Down