Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

test_modules.py 17KB

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