test_modules.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for twisted.python.modules, abstract access to imported or importable
  5. objects.
  6. """
  7. from __future__ import division, absolute_import
  8. import sys
  9. import itertools
  10. import compileall
  11. import zipfile
  12. import twisted
  13. from twisted.python import modules
  14. from twisted.python.compat import networkString
  15. from twisted.python.filepath import FilePath
  16. from twisted.python.reflect import namedAny
  17. from twisted.trial.unittest import TestCase
  18. from twisted.python.test.modules_helpers import TwistedModulesMixin
  19. from twisted.python.test.test_zippath import zipit
  20. class TwistedModulesTestCase(TwistedModulesMixin, TestCase):
  21. """
  22. Base class for L{modules} test cases.
  23. """
  24. def findByIteration(self, modname, where=modules, importPackages=False):
  25. """
  26. You don't ever actually want to do this, so it's not in the public
  27. API, but sometimes we want to compare the result of an iterative call
  28. with a lookup call and make sure they're the same for test purposes.
  29. """
  30. for modinfo in where.walkModules(importPackages=importPackages):
  31. if modinfo.name == modname:
  32. return modinfo
  33. self.fail("Unable to find module %r through iteration." % (modname,))
  34. class BasicTests(TwistedModulesTestCase):
  35. def test_namespacedPackages(self):
  36. """
  37. Duplicate packages are not yielded when iterating over namespace
  38. packages.
  39. """
  40. # Force pkgutil to be loaded already, since the probe package being
  41. # created depends on it, and the replaceSysPath call below will make
  42. # pretty much everything unimportable.
  43. __import__('pkgutil')
  44. namespaceBoilerplate = (
  45. b'import pkgutil; '
  46. b'__path__ = pkgutil.extend_path(__path__, __name__)')
  47. # Create two temporary directories with packages:
  48. #
  49. # entry:
  50. # test_package/
  51. # __init__.py
  52. # nested_package/
  53. # __init__.py
  54. # module.py
  55. #
  56. # anotherEntry:
  57. # test_package/
  58. # __init__.py
  59. # nested_package/
  60. # __init__.py
  61. # module2.py
  62. #
  63. # test_package and test_package.nested_package are namespace packages,
  64. # and when both of these are in sys.path, test_package.nested_package
  65. # should become a virtual package containing both "module" and
  66. # "module2"
  67. entry = self.pathEntryWithOnePackage()
  68. testPackagePath = entry.child('test_package')
  69. testPackagePath.child('__init__.py').setContent(namespaceBoilerplate)
  70. nestedEntry = testPackagePath.child('nested_package')
  71. nestedEntry.makedirs()
  72. nestedEntry.child('__init__.py').setContent(namespaceBoilerplate)
  73. nestedEntry.child('module.py').setContent(b'')
  74. anotherEntry = self.pathEntryWithOnePackage()
  75. anotherPackagePath = anotherEntry.child('test_package')
  76. anotherPackagePath.child('__init__.py').setContent(namespaceBoilerplate)
  77. anotherNestedEntry = anotherPackagePath.child('nested_package')
  78. anotherNestedEntry.makedirs()
  79. anotherNestedEntry.child('__init__.py').setContent(namespaceBoilerplate)
  80. anotherNestedEntry.child('module2.py').setContent(b'')
  81. self.replaceSysPath([entry.path, anotherEntry.path])
  82. module = modules.getModule('test_package')
  83. # We have to use importPackages=True in order to resolve the namespace
  84. # packages, so we remove the imported packages from sys.modules after
  85. # walking
  86. try:
  87. walkedNames = [
  88. mod.name for mod in module.walkModules(importPackages=True)]
  89. finally:
  90. for module in list(sys.modules.keys()):
  91. if module.startswith('test_package'):
  92. del sys.modules[module]
  93. expected = [
  94. 'test_package',
  95. 'test_package.nested_package',
  96. 'test_package.nested_package.module',
  97. 'test_package.nested_package.module2',
  98. ]
  99. self.assertEqual(walkedNames, expected)
  100. def test_unimportablePackageGetItem(self):
  101. """
  102. If a package has been explicitly forbidden from importing by setting a
  103. L{None} key in sys.modules under its name,
  104. L{modules.PythonPath.__getitem__} should still be able to retrieve an
  105. unloaded L{modules.PythonModule} for that package.
  106. """
  107. shouldNotLoad = []
  108. path = modules.PythonPath(sysPath=[self.pathEntryWithOnePackage().path],
  109. moduleLoader=shouldNotLoad.append,
  110. importerCache={},
  111. sysPathHooks={},
  112. moduleDict={'test_package': None})
  113. self.assertEqual(shouldNotLoad, [])
  114. self.assertFalse(path['test_package'].isLoaded())
  115. def test_unimportablePackageWalkModules(self):
  116. """
  117. If a package has been explicitly forbidden from importing by setting a
  118. L{None} key in sys.modules under its name, L{modules.walkModules} should
  119. still be able to retrieve an unloaded L{modules.PythonModule} for that
  120. package.
  121. """
  122. existentPath = self.pathEntryWithOnePackage()
  123. self.replaceSysPath([existentPath.path])
  124. self.replaceSysModules({"test_package": None})
  125. walked = list(modules.walkModules())
  126. self.assertEqual([m.name for m in walked],
  127. ["test_package"])
  128. self.assertFalse(walked[0].isLoaded())
  129. def test_nonexistentPaths(self):
  130. """
  131. Verify that L{modules.walkModules} ignores entries in sys.path which
  132. do not exist in the filesystem.
  133. """
  134. existentPath = self.pathEntryWithOnePackage()
  135. nonexistentPath = FilePath(self.mktemp())
  136. self.assertFalse(nonexistentPath.exists())
  137. self.replaceSysPath([existentPath.path])
  138. expected = [modules.getModule("test_package")]
  139. beforeModules = list(modules.walkModules())
  140. sys.path.append(nonexistentPath.path)
  141. afterModules = list(modules.walkModules())
  142. self.assertEqual(beforeModules, expected)
  143. self.assertEqual(afterModules, expected)
  144. def test_nonDirectoryPaths(self):
  145. """
  146. Verify that L{modules.walkModules} ignores entries in sys.path which
  147. refer to regular files in the filesystem.
  148. """
  149. existentPath = self.pathEntryWithOnePackage()
  150. nonDirectoryPath = FilePath(self.mktemp())
  151. self.assertFalse(nonDirectoryPath.exists())
  152. nonDirectoryPath.setContent(b"zip file or whatever\n")
  153. self.replaceSysPath([existentPath.path])
  154. beforeModules = list(modules.walkModules())
  155. sys.path.append(nonDirectoryPath.path)
  156. afterModules = list(modules.walkModules())
  157. self.assertEqual(beforeModules, afterModules)
  158. def test_twistedShowsUp(self):
  159. """
  160. Scrounge around in the top-level module namespace and make sure that
  161. Twisted shows up, and that the module thusly obtained is the same as
  162. the module that we find when we look for it explicitly by name.
  163. """
  164. self.assertEqual(modules.getModule('twisted'),
  165. self.findByIteration("twisted"))
  166. def test_dottedNames(self):
  167. """
  168. Verify that the walkModules APIs will give us back subpackages, not just
  169. subpackages.
  170. """
  171. self.assertEqual(
  172. modules.getModule('twisted.python'),
  173. self.findByIteration("twisted.python",
  174. where=modules.getModule('twisted')))
  175. def test_onlyTopModules(self):
  176. """
  177. Verify that the iterModules API will only return top-level modules and
  178. packages, not submodules or subpackages.
  179. """
  180. for module in modules.iterModules():
  181. self.assertFalse(
  182. '.' in module.name,
  183. "no nested modules should be returned from iterModules: %r"
  184. % (module.filePath))
  185. def test_loadPackagesAndModules(self):
  186. """
  187. Verify that we can locate and load packages, modules, submodules, and
  188. subpackages.
  189. """
  190. for n in ['os',
  191. 'twisted',
  192. 'twisted.python',
  193. 'twisted.python.reflect']:
  194. m = namedAny(n)
  195. self.failUnlessIdentical(
  196. modules.getModule(n).load(),
  197. m)
  198. self.failUnlessIdentical(
  199. self.findByIteration(n).load(),
  200. m)
  201. def test_pathEntriesOnPath(self):
  202. """
  203. Verify that path entries discovered via module loading are, in fact, on
  204. sys.path somewhere.
  205. """
  206. for n in ['os',
  207. 'twisted',
  208. 'twisted.python',
  209. 'twisted.python.reflect']:
  210. self.failUnlessIn(
  211. modules.getModule(n).pathEntry.filePath.path,
  212. sys.path)
  213. def test_alwaysPreferPy(self):
  214. """
  215. Verify that .py files will always be preferred to .pyc files, regardless of
  216. directory listing order.
  217. """
  218. mypath = FilePath(self.mktemp())
  219. mypath.createDirectory()
  220. pp = modules.PythonPath(sysPath=[mypath.path])
  221. originalSmartPath = pp._smartPath
  222. def _evilSmartPath(pathName):
  223. o = originalSmartPath(pathName)
  224. originalChildren = o.children
  225. def evilChildren():
  226. # normally this order is random; let's make sure it always
  227. # comes up .pyc-first.
  228. x = list(originalChildren())
  229. x.sort()
  230. x.reverse()
  231. return x
  232. o.children = evilChildren
  233. return o
  234. mypath.child("abcd.py").setContent(b'\n')
  235. compileall.compile_dir(mypath.path, quiet=True)
  236. # sanity check
  237. self.assertEqual(len(list(mypath.children())), 2)
  238. pp._smartPath = _evilSmartPath
  239. self.assertEqual(pp['abcd'].filePath,
  240. mypath.child('abcd.py'))
  241. def test_packageMissingPath(self):
  242. """
  243. A package can delete its __path__ for some reasons,
  244. C{modules.PythonPath} should be able to deal with it.
  245. """
  246. mypath = FilePath(self.mktemp())
  247. mypath.createDirectory()
  248. pp = modules.PythonPath(sysPath=[mypath.path])
  249. subpath = mypath.child("abcd")
  250. subpath.createDirectory()
  251. subpath.child("__init__.py").setContent(b'del __path__\n')
  252. sys.path.append(mypath.path)
  253. __import__("abcd")
  254. try:
  255. l = list(pp.walkModules())
  256. self.assertEqual(len(l), 1)
  257. self.assertEqual(l[0].name, 'abcd')
  258. finally:
  259. del sys.modules['abcd']
  260. sys.path.remove(mypath.path)
  261. class PathModificationTests(TwistedModulesTestCase):
  262. """
  263. These tests share setup/cleanup behavior of creating a dummy package and
  264. stuffing some code in it.
  265. """
  266. _serialnum = itertools.count() # used to generate serial numbers for
  267. # package names.
  268. def setUp(self):
  269. self.pathExtensionName = self.mktemp()
  270. self.pathExtension = FilePath(self.pathExtensionName)
  271. self.pathExtension.createDirectory()
  272. self.packageName = "pyspacetests%d" % (next(self._serialnum),)
  273. self.packagePath = self.pathExtension.child(self.packageName)
  274. self.packagePath.createDirectory()
  275. self.packagePath.child("__init__.py").setContent(b"")
  276. self.packagePath.child("a.py").setContent(b"")
  277. self.packagePath.child("b.py").setContent(b"")
  278. self.packagePath.child("c__init__.py").setContent(b"")
  279. self.pathSetUp = False
  280. def _setupSysPath(self):
  281. assert not self.pathSetUp
  282. self.pathSetUp = True
  283. sys.path.append(self.pathExtensionName)
  284. def _underUnderPathTest(self, doImport=True):
  285. moddir2 = self.mktemp()
  286. fpmd = FilePath(moddir2)
  287. fpmd.createDirectory()
  288. fpmd.child("foozle.py").setContent(b"x = 123\n")
  289. self.packagePath.child("__init__.py").setContent(
  290. networkString("__path__.append({0})\n".format(repr(moddir2))))
  291. # Cut here
  292. self._setupSysPath()
  293. modinfo = modules.getModule(self.packageName)
  294. self.assertEqual(
  295. self.findByIteration(self.packageName+".foozle", modinfo,
  296. importPackages=doImport),
  297. modinfo['foozle'])
  298. self.assertEqual(modinfo['foozle'].load().x, 123)
  299. def test_underUnderPathAlreadyImported(self):
  300. """
  301. Verify that iterModules will honor the __path__ of already-loaded packages.
  302. """
  303. self._underUnderPathTest()
  304. def _listModules(self):
  305. pkginfo = modules.getModule(self.packageName)
  306. nfni = [modinfo.name.split(".")[-1] for modinfo in
  307. pkginfo.iterModules()]
  308. nfni.sort()
  309. self.assertEqual(nfni, ['a', 'b', 'c__init__'])
  310. def test_listingModules(self):
  311. """
  312. Make sure the module list comes back as we expect from iterModules on a
  313. package, whether zipped or not.
  314. """
  315. self._setupSysPath()
  316. self._listModules()
  317. def test_listingModulesAlreadyImported(self):
  318. """
  319. Make sure the module list comes back as we expect from iterModules on a
  320. package, whether zipped or not, even if the package has already been
  321. imported.
  322. """
  323. self._setupSysPath()
  324. namedAny(self.packageName)
  325. self._listModules()
  326. def tearDown(self):
  327. # Intentionally using 'assert' here, this is not a test assertion, this
  328. # is just an "oh fuck what is going ON" assertion. -glyph
  329. if self.pathSetUp:
  330. HORK = "path cleanup failed: don't be surprised if other tests break"
  331. assert sys.path.pop() is self.pathExtensionName, HORK+", 1"
  332. assert self.pathExtensionName not in sys.path, HORK+", 2"
  333. class RebindingTests(PathModificationTests):
  334. """
  335. These tests verify that the default path interrogation API works properly
  336. even when sys.path has been rebound to a different object.
  337. """
  338. def _setupSysPath(self):
  339. assert not self.pathSetUp
  340. self.pathSetUp = True
  341. self.savedSysPath = sys.path
  342. sys.path = sys.path[:]
  343. sys.path.append(self.pathExtensionName)
  344. def tearDown(self):
  345. """
  346. Clean up sys.path by re-binding our original object.
  347. """
  348. if self.pathSetUp:
  349. sys.path = self.savedSysPath
  350. class ZipPathModificationTests(PathModificationTests):
  351. def _setupSysPath(self):
  352. assert not self.pathSetUp
  353. zipit(self.pathExtensionName, self.pathExtensionName+'.zip')
  354. self.pathExtensionName += '.zip'
  355. assert zipfile.is_zipfile(self.pathExtensionName)
  356. PathModificationTests._setupSysPath(self)
  357. class PythonPathTests(TestCase):
  358. """
  359. Tests for the class which provides the implementation for all of the
  360. public API of L{twisted.python.modules}, L{PythonPath}.
  361. """
  362. def test_unhandledImporter(self):
  363. """
  364. Make sure that the behavior when encountering an unknown importer
  365. type is not catastrophic failure.
  366. """
  367. class SecretImporter(object):
  368. pass
  369. def hook(name):
  370. return SecretImporter()
  371. syspath = ['example/path']
  372. sysmodules = {}
  373. syshooks = [hook]
  374. syscache = {}
  375. def sysloader(name):
  376. return None
  377. space = modules.PythonPath(
  378. syspath, sysmodules, syshooks, syscache, sysloader)
  379. entries = list(space.iterEntries())
  380. self.assertEqual(len(entries), 1)
  381. self.assertRaises(KeyError, lambda: entries[0]['module'])
  382. def test_inconsistentImporterCache(self):
  383. """
  384. If the path a module loaded with L{PythonPath.__getitem__} is not
  385. present in the path importer cache, a warning is emitted, but the
  386. L{PythonModule} is returned as usual.
  387. """
  388. space = modules.PythonPath([], sys.modules, [], {})
  389. thisModule = space[__name__]
  390. warnings = self.flushWarnings([self.test_inconsistentImporterCache])
  391. self.assertEqual(warnings[0]['category'], UserWarning)
  392. self.assertEqual(
  393. warnings[0]['message'],
  394. FilePath(twisted.__file__).parent().dirname() +
  395. " (for module " + __name__ + ") not in path importer cache "
  396. "(PEP 302 violation - check your local configuration).")
  397. self.assertEqual(len(warnings), 1)
  398. self.assertEqual(thisModule.name, __name__)
  399. def test_containsModule(self):
  400. """
  401. L{PythonPath} implements the C{in} operator so that when it is the
  402. right-hand argument and the name of a module which exists on that
  403. L{PythonPath} is the left-hand argument, the result is C{True}.
  404. """
  405. thePath = modules.PythonPath()
  406. self.assertIn('os', thePath)
  407. def test_doesntContainModule(self):
  408. """
  409. L{PythonPath} implements the C{in} operator so that when it is the
  410. right-hand argument and the name of a module which does not exist on
  411. that L{PythonPath} is the left-hand argument, the result is C{False}.
  412. """
  413. thePath = modules.PythonPath()
  414. self.assertNotIn('bogusModule', thePath)
  415. __all__ = ["BasicTests", "PathModificationTests", "RebindingTests",
  416. "ZipPathModificationTests", "PythonPathTests"]