Debian Codegraph @

Lib/test/test_pyclbr.py

raw
1 '''
2 Test cases for pyclbr.py
3 Nick Mathewson
4 '''
5
6 import sys
7 from textwrap import dedent
8 from types import FunctionType, MethodType, BuiltinFunctionType
9 import pyclbr
10 from unittest import TestCase, main as unittest_main
11 from test.test_importlib import util as test_importlib_util
12 import warnings
13 from test.support.testcase import ExtraAssertions
14
15
16 StaticMethodType = type(staticmethod(lambda: None))
17 ClassMethodType = type(classmethod(lambda c: None))
18
19 # Here we test the python class browser code.
20 #
21 # The main function in this suite, 'testModule', compares the output
22 # of pyclbr with the introspected members of a module. Because pyclbr
23 # is imperfect (as designed), testModule is called with a set of
24 # members to ignore.
25
26 class PyclbrTest(TestCase, ExtraAssertions):
27
28 def assertListEq(self, l1, l2, ignore):
29 ''' succeed iff {l1} - {ignore} == {l2} - {ignore} '''
30 missing = (set(l1) ^ set(l2)) - set(ignore)
31 if missing:
32 print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr)
33 self.fail("%r missing" % missing.pop())
34
35 def assertHaskey(self, obj, key, ignore):
36 ''' succeed iff key in obj or key in ignore. '''
37 if key in ignore: return
38 if key not in obj:
39 print("***",key, file=sys.stderr)
40 self.assertIn(key, obj)
41
42 def assertEqualsOrIgnored(self, a, b, ignore):
43 ''' succeed iff a == b or a in ignore or b in ignore '''
44 if a not in ignore and b not in ignore:
45 self.assertEqual(a, b)
46
47 def checkModule(self, moduleName, module=None, ignore=()):
48 ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds
49 to the actual module object, module. Any identifiers in
50 ignore are ignored. If no module is provided, the appropriate
51 module is loaded with __import__.'''
52
53 ignore = set(ignore) | set(['object'])
54
55 if module is None:
56 # Import it.
57 # ('<silly>' is to work around an API silliness in __import__)
58 module = __import__(moduleName, globals(), {}, ['<silly>'])
59
60 dict = pyclbr.readmodule_ex(moduleName)
61
62 def ismethod(oclass, obj, name):
63 classdict = oclass.__dict__
64 if isinstance(obj, MethodType):
65 # could be a classmethod
66 if (not isinstance(classdict[name], ClassMethodType) or
67 obj.__self__ is not oclass):
68 return False
69 elif not isinstance(obj, FunctionType):
70 return False
71
72 objname = obj.__name__
73 if objname.startswith("__") and not objname.endswith("__"):
74 if stripped_typename := oclass.__name__.lstrip('_'):
75 objname = f"_{stripped_typename}{objname}"
76 return objname == name
77
78 # Make sure the toplevel functions and classes are the same.
79 for name, value in dict.items():
80 if name in ignore:
81 continue
82 self.assertHasAttr(module, name, ignore)
83 py_item = getattr(module, name)
84 if isinstance(value, pyclbr.Function):
85 self.assertIsInstance(py_item, (FunctionType, BuiltinFunctionType))
86 if py_item.__module__ != moduleName:
87 continue # skip functions that came from somewhere else
88 self.assertEqual(py_item.__module__, value.module)
89 else:
90 self.assertIsInstance(py_item, type)
91 if py_item.__module__ != moduleName:
92 continue # skip classes that came from somewhere else
93
94 real_bases = [base.__name__ for base in py_item.__bases__]
95 pyclbr_bases = [ getattr(base, 'name', base)
96 for base in value.super ]
97
98 try:
99 self.assertListEq(real_bases, pyclbr_bases, ignore)
100 except:
101 print("class=%s" % py_item, file=sys.stderr)
102 raise
103
104 actualMethods = []
105 for m in py_item.__dict__.keys():
106 if ismethod(py_item, getattr(py_item, m), m):
107 actualMethods.append(m)
108
109 if stripped_typename := name.lstrip('_'):
110 foundMethods = []
111 for m in value.methods.keys():
112 if m.startswith('__') and not m.endswith('__'):
113 foundMethods.append(f"_{stripped_typename}{m}")
114 else:
115 foundMethods.append(m)
116 else:
117 foundMethods = list(value.methods.keys())
118
119 try:
120 self.assertListEq(foundMethods, actualMethods, ignore)
121 self.assertEqual(py_item.__module__, value.module)
122
123 self.assertEqualsOrIgnored(py_item.__name__, value.name,
124 ignore)
125 # can't check file or lineno
126 except:
127 print("class=%s" % py_item, file=sys.stderr)
128 raise
129
130 # Now check for missing stuff.
131 def defined_in(item, module):
132 if isinstance(item, type):
133 return item.__module__ == module.__name__
134 if isinstance(item, FunctionType):
135 return item.__globals__ is module.__dict__
136 return False
137 for name in dir(module):
138 item = getattr(module, name)
139 if isinstance(item, (type, FunctionType)):
140 if defined_in(item, module):
141 self.assertHaskey(dict, name, ignore)
142
143 def test_easy(self):
144 self.checkModule('pyclbr')
145 # XXX: Metaclasses are not supported
146 # self.checkModule('ast')
147 self.checkModule('doctest', ignore=("TestResults", "_SpoofOut",
148 "DocTestCase", '_DocTestSuite'))
149 self.checkModule('difflib', ignore=("Match",))
150
151 def test_cases(self):
152 # see test.pyclbr_input for the rationale behind the ignored symbols
153 self.checkModule('test.pyclbr_input', ignore=['om', 'f'])
154
155 def test_nested(self):
156 mb = pyclbr
157 # Set arguments for descriptor creation and _creat_tree call.
158 m, p, f, t, i = 'test', '', 'test.py', {}, None
159 source = dedent("""\
160 def f0():
161 def f1(a,b,c):
162 def f2(a=1, b=2, c=3): pass
163 return f1(a,b,d)
164 class c1: pass
165 class C0:
166 "Test class."
167 def F1():
168 "Method."
169 return 'return'
170 class C1():
171 class C2:
172 "Class nested within nested class."
173 def F3(): return 1+1
174
175 """)
176 actual = mb._create_tree(m, p, f, source, t, i)
177
178 # Create descriptors, linked together, and expected dict.
179 f0 = mb.Function(m, 'f0', f, 1, end_lineno=5)
180 f1 = mb._nest_function(f0, 'f1', 2, 4)
181 f2 = mb._nest_function(f1, 'f2', 3, 3)
182 c1 = mb._nest_class(f0, 'c1', 5, 5)
183 C0 = mb.Class(m, 'C0', None, f, 6, end_lineno=14)
184 F1 = mb._nest_function(C0, 'F1', 8, 10)
185 C1 = mb._nest_class(C0, 'C1', 11, 14)
186 C2 = mb._nest_class(C1, 'C2', 12, 14)
187 F3 = mb._nest_function(C2, 'F3', 14, 14)
188 expected = {'f0':f0, 'C0':C0}
189
190 def compare(parent1, children1, parent2, children2):
191 """Return equality of tree pairs.
192
193 Each parent,children pair define a tree. The parents are
194 assumed equal. Comparing the children dictionaries as such
195 does not work due to comparison by identity and double
196 linkage. We separate comparing string and number attributes
197 from comparing the children of input children.
198 """
199 self.assertEqual(children1.keys(), children2.keys())
200 for ob in children1.values():
201 self.assertIs(ob.parent, parent1)
202 for ob in children2.values():
203 self.assertIs(ob.parent, parent2)
204 for key in children1.keys():
205 o1, o2 = children1[key], children2[key]
206 t1 = type(o1), o1.name, o1.file, o1.module, o1.lineno, o1.end_lineno
207 t2 = type(o2), o2.name, o2.file, o2.module, o2.lineno, o2.end_lineno
208 self.assertEqual(t1, t2)
209 if type(o1) is mb.Class:
210 self.assertEqual(o1.methods, o2.methods)
211 # Skip superclasses for now as not part of example
212 compare(o1, o1.children, o2, o2.children)
213
214 compare(None, actual, None, expected)
215
216 def test_others(self):
217 cm = self.checkModule
218
219 # These were once some of the longest modules.
220 cm('random', ignore=('Random',)) # from _random import Random as CoreGenerator
221 cm('pickle', ignore=('partial', 'PickleBuffer'))
222 with warnings.catch_warnings():
223 warnings.simplefilter('ignore', DeprecationWarning)
224 cm('sre_parse', ignore=('dump', 'groups', 'pos')) # from sre_constants import *; property
225 cm(
226 'pdb',
227 # pyclbr does not handle elegantly `typing` or properties
228 ignore=('Union', '_ModuleTarget', '_ScriptTarget', '_ZipTarget', 'rlcompleter'),
229 )
230 cm('pydoc', ignore=('input', 'output',)) # properties
231
232 # Tests for modules inside packages
233 cm('email.parser')
234 cm('test.test_pyclbr')
235
236
237 class ReadmoduleTests(TestCase):
238
239 def setUp(self):
240 self._modules = pyclbr._modules.copy()
241
242 def tearDown(self):
243 pyclbr._modules = self._modules
244
245
246 def test_dotted_name_not_a_package(self):
247 # test ImportError is raised when the first part of a dotted name is
248 # not a package.
249 #
250 # Issue #14798.
251 self.assertRaises(ImportError, pyclbr.readmodule_ex, 'asyncio.foo')
252
253 def test_module_has_no_spec(self):
254 module_name = "doesnotexist"
255 assert module_name not in pyclbr._modules
256 with test_importlib_util.uncache(module_name):
257 with self.assertRaises(ModuleNotFoundError):
258 pyclbr.readmodule_ex(module_name)
259
260
261 if __name__ == "__main__":
262 unittest_main()