Debian Codegraph @

Lib/test/test___all__.py

raw
1 import unittest
2 from test import support
3 from test.support import warnings_helper
4 import os
5 import sys
6 import types
7
8
9 if support.check_sanitizer(address=True, memory=True):
10 SKIP_MODULES = frozenset((
11 # gh-90791: Tests involving libX11 can SEGFAULT on ASAN/MSAN builds.
12 # Skip modules, packages and tests using '_tkinter'.
13 '_tkinter',
14 'tkinter',
15 'test_tkinter',
16 'test_ttk',
17 'test_ttk_textonly',
18 'idlelib',
19 'test_idle',
20 ))
21 else:
22 SKIP_MODULES = ()
23
24
25 class NoAll(RuntimeError):
26 pass
27
28 class FailedImport(RuntimeError):
29 pass
30
31
32 class AllTest(unittest.TestCase):
33
34 def check_all(self, modname):
35 names = {}
36 with warnings_helper.check_warnings(
37 (f".*{modname}", DeprecationWarning),
38 (".* (module|package)", DeprecationWarning),
39 (".* (module|package)", PendingDeprecationWarning),
40 ("", ResourceWarning),
41 quiet=True):
42 try:
43 exec("import %s" % modname, names)
44 except:
45 # Silent fail here seems the best route since some modules
46 # may not be available or not initialize properly in all
47 # environments.
48 raise FailedImport(modname)
49 if not hasattr(sys.modules[modname], "__all__"):
50 raise NoAll(modname)
51 names = {}
52 with self.subTest(module=modname):
53 with warnings_helper.check_warnings(
54 ("", DeprecationWarning),
55 ("", ResourceWarning),
56 quiet=True):
57 try:
58 exec("from %s import *" % modname, names)
59 except Exception as e:
60 # Include the module name in the exception string
61 self.fail("__all__ failure in {}: {}: {}".format(
62 modname, e.__class__.__name__, e))
63 if "__builtins__" in names:
64 del names["__builtins__"]
65 if '__annotations__' in names:
66 del names['__annotations__']
67 if "__warningregistry__" in names:
68 del names["__warningregistry__"]
69 keys = set(names)
70 all_list = sys.modules[modname].__all__
71 all_set = set(all_list)
72 self.assertCountEqual(all_set, all_list, "in module {}".format(modname))
73 self.assertEqual(keys, all_set, "in module {}".format(modname))
74
75 def walk_modules(self, basedir, modpath):
76 for fn in sorted(os.listdir(basedir)):
77 path = os.path.join(basedir, fn)
78 if os.path.isdir(path):
79 if fn in SKIP_MODULES:
80 continue
81 pkg_init = os.path.join(path, '__init__.py')
82 if os.path.exists(pkg_init):
83 yield pkg_init, modpath + fn
84 for p, m in self.walk_modules(path, modpath + fn + "."):
85 yield p, m
86 continue
87
88 if fn == '__init__.py':
89 continue
90 if not fn.endswith('.py'):
91 continue
92 modname = fn.removesuffix('.py')
93 if modname in SKIP_MODULES:
94 continue
95 yield path, modpath + modname
96
97 def test_all(self):
98 # List of denied modules and packages
99 denylist = set([
100 # Will raise a SyntaxError when compiling the exec statement
101 '__future__',
102 ])
103
104 # In case _socket fails to build, make this test fail more gracefully
105 # than an AttributeError somewhere deep in concurrent.futures, email
106 # or unittest.
107 import _socket
108
109 ignored = []
110 failed_imports = []
111 lib_dir = os.path.dirname(os.path.dirname(__file__))
112 for path, modname in self.walk_modules(lib_dir, ""):
113 m = modname
114 denied = False
115 while m:
116 if m in denylist:
117 denied = True
118 break
119 m = m.rpartition('.')[0]
120 if denied:
121 continue
122 if support.verbose:
123 print(f"Check {modname}", flush=True)
124 try:
125 # This heuristic speeds up the process by removing, de facto,
126 # most test modules (and avoiding the auto-executing ones).
127 with open(path, "rb") as f:
128 if b"__all__" not in f.read():
129 raise NoAll(modname)
130 self.check_all(modname)
131 except NoAll:
132 ignored.append(modname)
133 except FailedImport:
134 failed_imports.append(modname)
135
136 if support.verbose:
137 print('Following modules have no __all__ and have been ignored:',
138 ignored)
139 print('Following modules failed to be imported:', failed_imports)
140
141
142 if __name__ == "__main__":
143 unittest.main()