test_pyclbr.py 10 KB

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