Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

unittest_manager.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. # Copyright (c) 2006, 2009-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  2. # Copyright (c) 2014-2016 Claudiu Popa <pcmanticore@gmail.com>
  3. # Copyright (c) 2014 Google, Inc.
  4. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  5. # For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
  6. import os
  7. import platform
  8. import site
  9. import sys
  10. import unittest
  11. import pkg_resources
  12. import six
  13. import astroid
  14. from astroid import exceptions
  15. from astroid import manager
  16. from astroid.tests import resources
  17. BUILTINS = six.moves.builtins.__name__
  18. def _get_file_from_object(obj):
  19. if platform.python_implementation() == 'Jython':
  20. return obj.__file__.split("$py.class")[0] + ".py"
  21. if sys.version_info >= (3, 4):
  22. return obj.__file__
  23. if not obj.__file__.endswith(".py"):
  24. return obj.__file__[:-1]
  25. return obj.__file__
  26. class AstroidManagerTest(resources.SysPathSetup,
  27. resources.AstroidCacheSetupMixin,
  28. unittest.TestCase):
  29. def setUp(self):
  30. super(AstroidManagerTest, self).setUp()
  31. self.manager = manager.AstroidManager()
  32. self.manager.clear_cache(self._builtins) # take care of borg
  33. def test_ast_from_file(self):
  34. filepath = unittest.__file__
  35. ast = self.manager.ast_from_file(filepath)
  36. self.assertEqual(ast.name, 'unittest')
  37. self.assertIn('unittest', self.manager.astroid_cache)
  38. def test_ast_from_file_cache(self):
  39. filepath = unittest.__file__
  40. self.manager.ast_from_file(filepath)
  41. ast = self.manager.ast_from_file('unhandledName', 'unittest')
  42. self.assertEqual(ast.name, 'unittest')
  43. self.assertIn('unittest', self.manager.astroid_cache)
  44. def test_ast_from_file_astro_builder(self):
  45. filepath = unittest.__file__
  46. ast = self.manager.ast_from_file(filepath, None, True, True)
  47. self.assertEqual(ast.name, 'unittest')
  48. self.assertIn('unittest', self.manager.astroid_cache)
  49. def test_ast_from_file_name_astro_builder_exception(self):
  50. self.assertRaises(exceptions.AstroidBuildingError,
  51. self.manager.ast_from_file, 'unhandledName')
  52. def test_do_not_expose_main(self):
  53. obj = self.manager.ast_from_module_name('__main__')
  54. self.assertEqual(obj.name, '__main__')
  55. self.assertEqual(obj.items(), [])
  56. def test_ast_from_module_name(self):
  57. ast = self.manager.ast_from_module_name('unittest')
  58. self.assertEqual(ast.name, 'unittest')
  59. self.assertIn('unittest', self.manager.astroid_cache)
  60. def test_ast_from_module_name_not_python_source(self):
  61. ast = self.manager.ast_from_module_name('time')
  62. self.assertEqual(ast.name, 'time')
  63. self.assertIn('time', self.manager.astroid_cache)
  64. self.assertEqual(ast.pure_python, False)
  65. def test_ast_from_module_name_astro_builder_exception(self):
  66. self.assertRaises(exceptions.AstroidBuildingError,
  67. self.manager.ast_from_module_name,
  68. 'unhandledModule')
  69. def _test_ast_from_old_namespace_package_protocol(self, root):
  70. origpath = sys.path[:]
  71. paths = [resources.find('data/path_{}_{}'.format(root, index))
  72. for index in range(1, 4)]
  73. sys.path.extend(paths)
  74. try:
  75. for name in ('foo', 'bar', 'baz'):
  76. module = self.manager.ast_from_module_name('package.' + name)
  77. self.assertIsInstance(module, astroid.Module)
  78. finally:
  79. sys.path = origpath
  80. def test_ast_from_namespace_pkgutil(self):
  81. self._test_ast_from_old_namespace_package_protocol('pkgutil')
  82. def test_ast_from_namespace_pkg_resources(self):
  83. self._test_ast_from_old_namespace_package_protocol('pkg_resources')
  84. @unittest.skipUnless(sys.version_info[:2] >= (3, 4), "Needs PEP 420 namespace protocol")
  85. def test_implicit_namespace_package(self):
  86. data_dir = os.path.dirname(resources.find('data/namespace_pep_420'))
  87. contribute = os.path.join(data_dir, 'contribute_to_namespace')
  88. for value in (data_dir, contribute):
  89. sys.path.insert(0, value)
  90. try:
  91. module = self.manager.ast_from_module_name('namespace_pep_420.module')
  92. self.assertIsInstance(module, astroid.Module)
  93. self.assertEqual(module.name, 'namespace_pep_420.module')
  94. var = next(module.igetattr('var'))
  95. self.assertIsInstance(var, astroid.Const)
  96. self.assertEqual(var.value, 42)
  97. finally:
  98. for _ in range(2):
  99. sys.path.pop(0)
  100. def test_namespace_package_pth_support(self):
  101. pth = 'foogle_fax-0.12.5-py2.7-nspkg.pth'
  102. site.addpackage(resources.RESOURCE_PATH, pth, [])
  103. pkg_resources._namespace_packages['foogle'] = [] # pylint: disable=no-member
  104. try:
  105. module = self.manager.ast_from_module_name('foogle.fax')
  106. submodule = next(module.igetattr('a'))
  107. value = next(submodule.igetattr('x'))
  108. self.assertIsInstance(value, astroid.Const)
  109. with self.assertRaises(exceptions.AstroidImportError):
  110. self.manager.ast_from_module_name('foogle.moogle')
  111. finally:
  112. del pkg_resources._namespace_packages['foogle'] # pylint: disable=no-member
  113. sys.modules.pop('foogle')
  114. def test_nested_namespace_import(self):
  115. pth = 'foogle_fax-0.12.5-py2.7-nspkg.pth'
  116. site.addpackage(resources.RESOURCE_PATH, pth, [])
  117. pkg_resources._namespace_packages['foogle'] = ['foogle.crank'] # pylint: disable=no-member
  118. pkg_resources._namespace_packages['foogle.crank'] = [] # pylint: disable=no-member
  119. try:
  120. self.manager.ast_from_module_name('foogle.crank')
  121. finally:
  122. del pkg_resources._namespace_packages['foogle'] # pylint: disable=no-member
  123. sys.modules.pop('foogle')
  124. def test_namespace_and_file_mismatch(self):
  125. filepath = unittest.__file__
  126. ast = self.manager.ast_from_file(filepath)
  127. self.assertEqual(ast.name, 'unittest')
  128. pth = 'foogle_fax-0.12.5-py2.7-nspkg.pth'
  129. site.addpackage(resources.RESOURCE_PATH, pth, [])
  130. pkg_resources._namespace_packages['foogle'] = [] # pylint: disable=no-member
  131. try:
  132. with self.assertRaises(exceptions.AstroidImportError):
  133. self.manager.ast_from_module_name('unittest.foogle.fax')
  134. finally:
  135. del pkg_resources._namespace_packages['foogle'] # pylint: disable=no-member
  136. sys.modules.pop('foogle')
  137. def _test_ast_from_zip(self, archive):
  138. origpath = sys.path[:]
  139. sys.modules.pop('mypypa', None)
  140. archive_path = resources.find(archive)
  141. sys.path.insert(0, archive_path)
  142. try:
  143. module = self.manager.ast_from_module_name('mypypa')
  144. self.assertEqual(module.name, 'mypypa')
  145. end = os.path.join(archive, 'mypypa')
  146. self.assertTrue(module.file.endswith(end),
  147. "%s doesn't endswith %s" % (module.file, end))
  148. finally:
  149. # remove the module, else after importing egg, we don't get the zip
  150. if 'mypypa' in self.manager.astroid_cache:
  151. del self.manager.astroid_cache['mypypa']
  152. del self.manager._mod_file_cache[('mypypa', None)]
  153. if archive_path in sys.path_importer_cache:
  154. del sys.path_importer_cache[archive_path]
  155. sys.path = origpath
  156. def test_ast_from_module_name_egg(self):
  157. self._test_ast_from_zip(
  158. os.path.sep.join(['data', os.path.normcase('MyPyPa-0.1.0-py2.5.egg')])
  159. )
  160. def test_ast_from_module_name_zip(self):
  161. self._test_ast_from_zip(
  162. os.path.sep.join(['data', os.path.normcase('MyPyPa-0.1.0-py2.5.zip')])
  163. )
  164. def test_zip_import_data(self):
  165. """check if zip_import_data works"""
  166. filepath = resources.find('data/MyPyPa-0.1.0-py2.5.zip/mypypa')
  167. ast = self.manager.zip_import_data(filepath)
  168. self.assertEqual(ast.name, 'mypypa')
  169. def test_zip_import_data_without_zipimport(self):
  170. """check if zip_import_data return None without zipimport"""
  171. self.assertEqual(self.manager.zip_import_data('path'), None)
  172. def test_file_from_module(self):
  173. """check if the unittest filepath is equals to the result of the method"""
  174. self.assertEqual(
  175. _get_file_from_object(unittest),
  176. # pylint: disable=no-member; can't infer the ModuleSpec
  177. self.manager.file_from_module_name('unittest', None).location)
  178. def test_file_from_module_name_astro_building_exception(self):
  179. """check if the method launch a exception with a wrong module name"""
  180. self.assertRaises(exceptions.AstroidBuildingError,
  181. self.manager.file_from_module_name, 'unhandledModule', None)
  182. def test_ast_from_module(self):
  183. ast = self.manager.ast_from_module(unittest)
  184. self.assertEqual(ast.pure_python, True)
  185. import time
  186. ast = self.manager.ast_from_module(time)
  187. self.assertEqual(ast.pure_python, False)
  188. def test_ast_from_module_cache(self):
  189. """check if the module is in the cache manager"""
  190. ast = self.manager.ast_from_module(unittest)
  191. self.assertEqual(ast.name, 'unittest')
  192. self.assertIn('unittest', self.manager.astroid_cache)
  193. def test_ast_from_class(self):
  194. ast = self.manager.ast_from_class(int)
  195. self.assertEqual(ast.name, 'int')
  196. self.assertEqual(ast.parent.frame().name, BUILTINS)
  197. ast = self.manager.ast_from_class(object)
  198. self.assertEqual(ast.name, 'object')
  199. self.assertEqual(ast.parent.frame().name, BUILTINS)
  200. self.assertIn('__setattr__', ast)
  201. def test_ast_from_class_with_module(self):
  202. """check if the method works with the module name"""
  203. ast = self.manager.ast_from_class(int, int.__module__)
  204. self.assertEqual(ast.name, 'int')
  205. self.assertEqual(ast.parent.frame().name, BUILTINS)
  206. ast = self.manager.ast_from_class(object, object.__module__)
  207. self.assertEqual(ast.name, 'object')
  208. self.assertEqual(ast.parent.frame().name, BUILTINS)
  209. self.assertIn('__setattr__', ast)
  210. def test_ast_from_class_attr_error(self):
  211. """give a wrong class at the ast_from_class method"""
  212. self.assertRaises(exceptions.AstroidBuildingError,
  213. self.manager.ast_from_class, None)
  214. def testFailedImportHooks(self):
  215. def hook(modname):
  216. if modname == 'foo.bar':
  217. return unittest
  218. else:
  219. raise exceptions.AstroidBuildingError()
  220. with self.assertRaises(exceptions.AstroidBuildingError):
  221. self.manager.ast_from_module_name('foo.bar')
  222. self.manager.register_failed_import_hook(hook)
  223. self.assertEqual(unittest, self.manager.ast_from_module_name('foo.bar'))
  224. with self.assertRaises(exceptions.AstroidBuildingError):
  225. self.manager.ast_from_module_name('foo.bar.baz')
  226. del self.manager._failed_import_hooks[0]
  227. class BorgAstroidManagerTC(unittest.TestCase):
  228. def test_borg(self):
  229. """test that the AstroidManager is really a borg, i.e. that two different
  230. instances has same cache"""
  231. first_manager = manager.AstroidManager()
  232. built = first_manager.ast_from_module_name(BUILTINS)
  233. second_manager = manager.AstroidManager()
  234. second_built = second_manager.ast_from_module_name(BUILTINS)
  235. self.assertIs(built, second_built)
  236. if __name__ == '__main__':
  237. unittest.main()