gh-135801: Improve filtering by module in warn_explicit() without module argument (GH-140151)

* Try to match the module name pattern with module names constructed
  starting from different parent directories of the filename.
  E.g., for "/path/to/package/module" try to match with
  "path.to.package.module", "to.package.module", "package.module" and
  "module".
* Ignore trailing "/__init__.py".
* Ignore trailing ".pyw" on Windows.
* Keep matching with the full filename (without optional ".py" extension)
  for compatibility.
* Only ignore the case of the ".py" extension on Windows.
This commit is contained in:
Serhiy Storchaka 2025-10-30 15:55:39 +02:00 committed by GitHub
parent efc37ba49e
commit 6826166280
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 243 additions and 73 deletions

View file

@ -5,6 +5,7 @@
import re
import textwrap
import symtable
import warnings
import unittest
from test import support
@ -586,6 +587,20 @@ def test__symtable_refleak(self):
# check error path when 'compile_type' AC conversion failed
self.assertRaises(TypeError, symtable.symtable, '', mortal_str, 1)
def test_filter_syntax_warnings_by_module(self):
filename = support.findfile('test_import/data/syntax_warnings.py')
with open(filename, 'rb') as f:
source = f.read()
module_re = r'test\.test_import\.data\.syntax_warnings\z'
with warnings.catch_warnings(record=True) as wlog:
warnings.simplefilter('error')
warnings.filterwarnings('always', module=module_re)
symtable.symtable(source, filename, 'exec')
self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10])
for wm in wlog:
self.assertEqual(wm.filename, filename)
self.assertIs(wm.category, SyntaxWarning)
class ComprehensionTests(unittest.TestCase):
def get_identifiers_recursive(self, st, res):