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_plugin.py 25KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. # Copyright (c) 2005 Divmod, Inc.
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Tests for Twisted plugin system.
  6. """
  7. import compileall
  8. import errno
  9. import functools
  10. import os
  11. import sys
  12. import time
  13. from importlib import invalidate_caches as invalidateImportCaches
  14. from typing import Callable
  15. from zope.interface import Interface
  16. from twisted import plugin
  17. from twisted.python.filepath import FilePath
  18. from twisted.python.log import addObserver, removeObserver, textFromEventDict
  19. from twisted.trial import unittest
  20. class ITestPlugin(Interface):
  21. """
  22. A plugin for use by the plugin system's unit tests.
  23. Do not use this.
  24. """
  25. class ITestPlugin2(Interface):
  26. """
  27. See L{ITestPlugin}.
  28. """
  29. class PluginTests(unittest.TestCase):
  30. """
  31. Tests which verify the behavior of the current, active Twisted plugins
  32. directory.
  33. """
  34. def setUp(self):
  35. """
  36. Save C{sys.path} and C{sys.modules}, and create a package for tests.
  37. """
  38. self.originalPath = sys.path[:]
  39. self.savedModules = sys.modules.copy()
  40. self.root = FilePath(self.mktemp())
  41. self.root.createDirectory()
  42. self.package = self.root.child("mypackage")
  43. self.package.createDirectory()
  44. self.package.child("__init__.py").setContent(b"")
  45. FilePath(__file__).sibling("plugin_basic.py").copyTo(
  46. self.package.child("testplugin.py")
  47. )
  48. self.originalPlugin = "testplugin"
  49. sys.path.insert(0, self.root.path)
  50. import mypackage # type: ignore[import]
  51. self.module = mypackage
  52. def tearDown(self):
  53. """
  54. Restore C{sys.path} and C{sys.modules} to their original values.
  55. """
  56. sys.path[:] = self.originalPath
  57. sys.modules.clear()
  58. sys.modules.update(self.savedModules)
  59. def _unimportPythonModule(self, module, deleteSource=False):
  60. modulePath = module.__name__.split(".")
  61. packageName = ".".join(modulePath[:-1])
  62. moduleName = modulePath[-1]
  63. delattr(sys.modules[packageName], moduleName)
  64. del sys.modules[module.__name__]
  65. for ext in ["c", "o"] + (deleteSource and [""] or []):
  66. try:
  67. os.remove(module.__file__ + ext)
  68. except OSError as ose:
  69. if ose.errno != errno.ENOENT:
  70. raise
  71. def _clearCache(self):
  72. """
  73. Remove the plugins B{droping.cache} file.
  74. """
  75. self.package.child("dropin.cache").remove()
  76. def _withCacheness(meth: Callable):
  77. """
  78. This is a paranoid test wrapper, that calls C{meth} 2 times, clear the
  79. cache, and calls it 2 other times. It's supposed to ensure that the
  80. plugin system behaves correctly no matter what the state of the cache
  81. is.
  82. """
  83. @functools.wraps(meth)
  84. def wrapped(self):
  85. meth(self)
  86. meth(self)
  87. self._clearCache()
  88. meth(self)
  89. meth(self)
  90. return wrapped
  91. @_withCacheness
  92. def test_cache(self):
  93. """
  94. Check that the cache returned by L{plugin.getCache} hold the plugin
  95. B{testplugin}, and that this plugin has the properties we expect:
  96. provide L{TestPlugin}, has the good name and description, and can be
  97. loaded successfully.
  98. """
  99. cache = plugin.getCache(self.module)
  100. dropin = cache[self.originalPlugin]
  101. self.assertEqual(dropin.moduleName, f"mypackage.{self.originalPlugin}")
  102. self.assertIn("I'm a test drop-in.", dropin.description)
  103. # Note, not the preferred way to get a plugin by its interface.
  104. p1 = [p for p in dropin.plugins if ITestPlugin in p.provided][0]
  105. self.assertIs(p1.dropin, dropin)
  106. self.assertEqual(p1.name, "TestPlugin")
  107. # Check the content of the description comes from the plugin module
  108. # docstring
  109. self.assertEqual(
  110. p1.description.strip(), "A plugin used solely for testing purposes."
  111. )
  112. self.assertEqual(p1.provided, [ITestPlugin, plugin.IPlugin])
  113. realPlugin = p1.load()
  114. # The plugin should match the class present in sys.modules
  115. self.assertIs(
  116. realPlugin,
  117. sys.modules[f"mypackage.{self.originalPlugin}"].TestPlugin,
  118. )
  119. # And it should also match if we import it classicly
  120. import mypackage.testplugin as tp # type: ignore[import]
  121. self.assertIs(realPlugin, tp.TestPlugin)
  122. def test_cacheRepr(self):
  123. """
  124. L{CachedPlugin} has a helpful C{repr} which contains relevant
  125. information about it.
  126. """
  127. cachedDropin = plugin.getCache(self.module)[self.originalPlugin]
  128. cachedPlugin = list(p for p in cachedDropin.plugins if p.name == "TestPlugin")[
  129. 0
  130. ]
  131. self.assertEqual(
  132. repr(cachedPlugin),
  133. "<CachedPlugin 'TestPlugin'/'mypackage.testplugin' "
  134. "(provides 'ITestPlugin, IPlugin')>",
  135. )
  136. @_withCacheness
  137. def test_plugins(self):
  138. """
  139. L{plugin.getPlugins} should return the list of plugins matching the
  140. specified interface (here, L{ITestPlugin2}), and these plugins
  141. should be instances of classes with a C{test} method, to be sure
  142. L{plugin.getPlugins} load classes correctly.
  143. """
  144. plugins = list(plugin.getPlugins(ITestPlugin2, self.module))
  145. self.assertEqual(len(plugins), 2)
  146. names = ["AnotherTestPlugin", "ThirdTestPlugin"]
  147. for p in plugins:
  148. names.remove(p.__name__)
  149. p.test()
  150. @_withCacheness
  151. def test_detectNewFiles(self):
  152. """
  153. Check that L{plugin.getPlugins} is able to detect plugins added at
  154. runtime.
  155. """
  156. FilePath(__file__).sibling("plugin_extra1.py").copyTo(
  157. self.package.child("pluginextra.py")
  158. )
  159. try:
  160. # Check that the current situation is clean
  161. self.failIfIn("mypackage.pluginextra", sys.modules)
  162. self.assertFalse(
  163. hasattr(sys.modules["mypackage"], "pluginextra"),
  164. "mypackage still has pluginextra module",
  165. )
  166. plgs = list(plugin.getPlugins(ITestPlugin, self.module))
  167. # We should find 2 plugins: the one in testplugin, and the one in
  168. # pluginextra
  169. self.assertEqual(len(plgs), 2)
  170. names = ["TestPlugin", "FourthTestPlugin"]
  171. for p in plgs:
  172. names.remove(p.__name__)
  173. p.test1()
  174. finally:
  175. self._unimportPythonModule(sys.modules["mypackage.pluginextra"], True)
  176. @_withCacheness
  177. def test_detectFilesChanged(self):
  178. """
  179. Check that if the content of a plugin change, L{plugin.getPlugins} is
  180. able to detect the new plugins added.
  181. """
  182. FilePath(__file__).sibling("plugin_extra1.py").copyTo(
  183. self.package.child("pluginextra.py")
  184. )
  185. try:
  186. plgs = list(plugin.getPlugins(ITestPlugin, self.module))
  187. # Sanity check
  188. self.assertEqual(len(plgs), 2)
  189. FilePath(__file__).sibling("plugin_extra2.py").copyTo(
  190. self.package.child("pluginextra.py")
  191. )
  192. # Fake out Python.
  193. self._unimportPythonModule(sys.modules["mypackage.pluginextra"])
  194. # Make sure additions are noticed
  195. plgs = list(plugin.getPlugins(ITestPlugin, self.module))
  196. self.assertEqual(len(plgs), 3)
  197. names = ["TestPlugin", "FourthTestPlugin", "FifthTestPlugin"]
  198. for p in plgs:
  199. names.remove(p.__name__)
  200. p.test1()
  201. finally:
  202. self._unimportPythonModule(sys.modules["mypackage.pluginextra"], True)
  203. @_withCacheness
  204. def test_detectFilesRemoved(self):
  205. """
  206. Check that when a dropin file is removed, L{plugin.getPlugins} doesn't
  207. return it anymore.
  208. """
  209. FilePath(__file__).sibling("plugin_extra1.py").copyTo(
  210. self.package.child("pluginextra.py")
  211. )
  212. try:
  213. # Generate a cache with pluginextra in it.
  214. list(plugin.getPlugins(ITestPlugin, self.module))
  215. finally:
  216. self._unimportPythonModule(sys.modules["mypackage.pluginextra"], True)
  217. plgs = list(plugin.getPlugins(ITestPlugin, self.module))
  218. self.assertEqual(1, len(plgs))
  219. @_withCacheness
  220. def test_nonexistentPathEntry(self):
  221. """
  222. Test that getCache skips over any entries in a plugin package's
  223. C{__path__} which do not exist.
  224. """
  225. path = self.mktemp()
  226. self.assertFalse(os.path.exists(path))
  227. # Add the test directory to the plugins path
  228. self.module.__path__.append(path)
  229. try:
  230. plgs = list(plugin.getPlugins(ITestPlugin, self.module))
  231. self.assertEqual(len(plgs), 1)
  232. finally:
  233. self.module.__path__.remove(path)
  234. @_withCacheness
  235. def test_nonDirectoryChildEntry(self):
  236. """
  237. Test that getCache skips over any entries in a plugin package's
  238. C{__path__} which refer to children of paths which are not directories.
  239. """
  240. path = FilePath(self.mktemp())
  241. self.assertFalse(path.exists())
  242. path.touch()
  243. child = path.child("test_package").path
  244. self.module.__path__.append(child)
  245. try:
  246. plgs = list(plugin.getPlugins(ITestPlugin, self.module))
  247. self.assertEqual(len(plgs), 1)
  248. finally:
  249. self.module.__path__.remove(child)
  250. def test_deployedMode(self):
  251. """
  252. The C{dropin.cache} file may not be writable: the cache should still be
  253. attainable, but an error should be logged to show that the cache
  254. couldn't be updated.
  255. """
  256. # Generate the cache
  257. plugin.getCache(self.module)
  258. cachepath = self.package.child("dropin.cache")
  259. # Add a new plugin
  260. FilePath(__file__).sibling("plugin_extra1.py").copyTo(
  261. self.package.child("pluginextra.py")
  262. )
  263. invalidateImportCaches()
  264. os.chmod(self.package.path, 0o500)
  265. # Change the right of dropin.cache too for windows
  266. os.chmod(cachepath.path, 0o400)
  267. self.addCleanup(os.chmod, self.package.path, 0o700)
  268. self.addCleanup(os.chmod, cachepath.path, 0o700)
  269. # Start observing log events to see the warning
  270. events = []
  271. addObserver(events.append)
  272. self.addCleanup(removeObserver, events.append)
  273. cache = plugin.getCache(self.module)
  274. # The new plugin should be reported
  275. self.assertIn("pluginextra", cache)
  276. self.assertIn(self.originalPlugin, cache)
  277. # Make sure something was logged about the cache.
  278. expected = "Unable to write to plugin cache %s: error number %d" % (
  279. cachepath.path,
  280. errno.EPERM,
  281. )
  282. for event in events:
  283. if expected in textFromEventDict(event):
  284. break
  285. else:
  286. self.fail(
  287. "Did not observe unwriteable cache warning in log "
  288. "events: %r" % (events,)
  289. )
  290. # This is something like the Twisted plugins file.
  291. pluginInitFile = b"""
  292. from twisted.plugin import pluginPackagePaths
  293. __path__.extend(pluginPackagePaths(__name__))
  294. __all__ = []
  295. """
  296. def pluginFileContents(name):
  297. return (
  298. (
  299. "from zope.interface import provider\n"
  300. "from twisted.plugin import IPlugin\n"
  301. "from twisted.test.test_plugin import ITestPlugin\n"
  302. "\n"
  303. "@provider(IPlugin, ITestPlugin)\n"
  304. "class {}:\n"
  305. " pass\n"
  306. )
  307. .format(name)
  308. .encode("ascii")
  309. )
  310. def _createPluginDummy(entrypath, pluginContent, real, pluginModule):
  311. """
  312. Create a plugindummy package.
  313. """
  314. entrypath.createDirectory()
  315. pkg = entrypath.child("plugindummy")
  316. pkg.createDirectory()
  317. if real:
  318. pkg.child("__init__.py").setContent(b"")
  319. plugs = pkg.child("plugins")
  320. plugs.createDirectory()
  321. if real:
  322. plugs.child("__init__.py").setContent(pluginInitFile)
  323. plugs.child(pluginModule + ".py").setContent(pluginContent)
  324. return plugs
  325. class DeveloperSetupTests(unittest.TestCase):
  326. """
  327. These tests verify things about the plugin system without actually
  328. interacting with the deployed 'twisted.plugins' package, instead creating a
  329. temporary package.
  330. """
  331. def setUp(self):
  332. """
  333. Create a complex environment with multiple entries on sys.path, akin to
  334. a developer's environment who has a development (trunk) checkout of
  335. Twisted, a system installed version of Twisted (for their operating
  336. system's tools) and a project which provides Twisted plugins.
  337. """
  338. self.savedPath = sys.path[:]
  339. self.savedModules = sys.modules.copy()
  340. self.fakeRoot = FilePath(self.mktemp())
  341. self.fakeRoot.createDirectory()
  342. self.systemPath = self.fakeRoot.child("system_path")
  343. self.devPath = self.fakeRoot.child("development_path")
  344. self.appPath = self.fakeRoot.child("application_path")
  345. self.systemPackage = _createPluginDummy(
  346. self.systemPath, pluginFileContents("system"), True, "plugindummy_builtin"
  347. )
  348. self.devPackage = _createPluginDummy(
  349. self.devPath, pluginFileContents("dev"), True, "plugindummy_builtin"
  350. )
  351. self.appPackage = _createPluginDummy(
  352. self.appPath, pluginFileContents("app"), False, "plugindummy_app"
  353. )
  354. # Now we're going to do the system installation.
  355. sys.path.extend([x.path for x in [self.systemPath, self.appPath]])
  356. # Run all the way through the plugins list to cause the
  357. # L{plugin.getPlugins} generator to write cache files for the system
  358. # installation.
  359. self.getAllPlugins()
  360. self.sysplug = self.systemPath.child("plugindummy").child("plugins")
  361. self.syscache = self.sysplug.child("dropin.cache")
  362. # Make sure there's a nice big difference in modification times so that
  363. # we won't re-build the system cache.
  364. now = time.time()
  365. os.utime(self.sysplug.child("plugindummy_builtin.py").path, (now - 5000,) * 2)
  366. os.utime(self.syscache.path, (now - 2000,) * 2)
  367. # For extra realism, let's make sure that the system path is no longer
  368. # writable.
  369. self.lockSystem()
  370. self.resetEnvironment()
  371. def lockSystem(self):
  372. """
  373. Lock the system directories, as if they were unwritable by this user.
  374. """
  375. os.chmod(self.sysplug.path, 0o555)
  376. os.chmod(self.syscache.path, 0o555)
  377. def unlockSystem(self):
  378. """
  379. Unlock the system directories, as if they were writable by this user.
  380. """
  381. os.chmod(self.sysplug.path, 0o777)
  382. os.chmod(self.syscache.path, 0o777)
  383. def getAllPlugins(self):
  384. """
  385. Get all the plugins loadable from our dummy package, and return their
  386. short names.
  387. """
  388. # Import the module we just added to our path. (Local scope because
  389. # this package doesn't exist outside of this test.)
  390. import plugindummy.plugins # type: ignore[import]
  391. x = list(plugin.getPlugins(ITestPlugin, plugindummy.plugins))
  392. return [plug.__name__ for plug in x]
  393. def resetEnvironment(self):
  394. """
  395. Change the environment to what it should be just as the test is
  396. starting.
  397. """
  398. self.unsetEnvironment()
  399. sys.path.extend([x.path for x in [self.devPath, self.systemPath, self.appPath]])
  400. def unsetEnvironment(self):
  401. """
  402. Change the Python environment back to what it was before the test was
  403. started.
  404. """
  405. invalidateImportCaches()
  406. sys.modules.clear()
  407. sys.modules.update(self.savedModules)
  408. sys.path[:] = self.savedPath
  409. def tearDown(self):
  410. """
  411. Reset the Python environment to what it was before this test ran, and
  412. restore permissions on files which were marked read-only so that the
  413. directory may be cleanly cleaned up.
  414. """
  415. self.unsetEnvironment()
  416. # Normally we wouldn't "clean up" the filesystem like this (leaving
  417. # things for post-test inspection), but if we left the permissions the
  418. # way they were, we'd be leaving files around that the buildbots
  419. # couldn't delete, and that would be bad.
  420. self.unlockSystem()
  421. def test_developmentPluginAvailability(self):
  422. """
  423. Plugins added in the development path should be loadable, even when
  424. the (now non-importable) system path contains its own idea of the
  425. list of plugins for a package. Inversely, plugins added in the
  426. system path should not be available.
  427. """
  428. # Run 3 times: uncached, cached, and then cached again to make sure we
  429. # didn't overwrite / corrupt the cache on the cached try.
  430. for x in range(3):
  431. names = self.getAllPlugins()
  432. names.sort()
  433. self.assertEqual(names, ["app", "dev"])
  434. def test_freshPyReplacesStalePyc(self):
  435. """
  436. Verify that if a stale .pyc file on the PYTHONPATH is replaced by a
  437. fresh .py file, the plugins in the new .py are picked up rather than
  438. the stale .pyc, even if the .pyc is still around.
  439. """
  440. mypath = self.appPackage.child("stale.py")
  441. mypath.setContent(pluginFileContents("one"))
  442. # Make it super stale
  443. x = time.time() - 1000
  444. os.utime(mypath.path, (x, x))
  445. pyc = mypath.sibling("stale.pyc")
  446. # compile it
  447. # On python 3, don't use the __pycache__ directory; the intention
  448. # of scanning for .pyc files is for configurations where you want
  449. # to intentionally include them, which means we _don't_ scan for
  450. # them inside cache directories.
  451. extra = dict(legacy=True)
  452. compileall.compile_dir(self.appPackage.path, quiet=1, **extra)
  453. os.utime(pyc.path, (x, x))
  454. # Eliminate the other option.
  455. mypath.remove()
  456. # Make sure it's the .pyc path getting cached.
  457. self.resetEnvironment()
  458. # Sanity check.
  459. self.assertIn("one", self.getAllPlugins())
  460. self.failIfIn("two", self.getAllPlugins())
  461. self.resetEnvironment()
  462. mypath.setContent(pluginFileContents("two"))
  463. self.failIfIn("one", self.getAllPlugins())
  464. self.assertIn("two", self.getAllPlugins())
  465. def test_newPluginsOnReadOnlyPath(self):
  466. """
  467. Verify that a failure to write the dropin.cache file on a read-only
  468. path will not affect the list of plugins returned.
  469. Note: this test should pass on both Linux and Windows, but may not
  470. provide useful coverage on Windows due to the different meaning of
  471. "read-only directory".
  472. """
  473. self.unlockSystem()
  474. self.sysplug.child("newstuff.py").setContent(pluginFileContents("one"))
  475. self.lockSystem()
  476. # Take the developer path out, so that the system plugins are actually
  477. # examined.
  478. sys.path.remove(self.devPath.path)
  479. # Start observing log events to see the warning
  480. events = []
  481. addObserver(events.append)
  482. self.addCleanup(removeObserver, events.append)
  483. self.assertIn("one", self.getAllPlugins())
  484. # Make sure something was logged about the cache.
  485. expected = "Unable to write to plugin cache %s: error number %d" % (
  486. self.syscache.path,
  487. errno.EPERM,
  488. )
  489. for event in events:
  490. if expected in textFromEventDict(event):
  491. break
  492. else:
  493. self.fail(
  494. "Did not observe unwriteable cache warning in log "
  495. "events: %r" % (events,)
  496. )
  497. class AdjacentPackageTests(unittest.TestCase):
  498. """
  499. Tests for the behavior of the plugin system when there are multiple
  500. installed copies of the package containing the plugins being loaded.
  501. """
  502. def setUp(self):
  503. """
  504. Save the elements of C{sys.path} and the items of C{sys.modules}.
  505. """
  506. self.originalPath = sys.path[:]
  507. self.savedModules = sys.modules.copy()
  508. def tearDown(self):
  509. """
  510. Restore C{sys.path} and C{sys.modules} to their original values.
  511. """
  512. sys.path[:] = self.originalPath
  513. sys.modules.clear()
  514. sys.modules.update(self.savedModules)
  515. def createDummyPackage(self, root, name, pluginName):
  516. """
  517. Create a directory containing a Python package named I{dummy} with a
  518. I{plugins} subpackage.
  519. @type root: L{FilePath}
  520. @param root: The directory in which to create the hierarchy.
  521. @type name: C{str}
  522. @param name: The name of the directory to create which will contain
  523. the package.
  524. @type pluginName: C{str}
  525. @param pluginName: The name of a module to create in the
  526. I{dummy.plugins} package.
  527. @rtype: L{FilePath}
  528. @return: The directory which was created to contain the I{dummy}
  529. package.
  530. """
  531. directory = root.child(name)
  532. package = directory.child("dummy")
  533. package.makedirs()
  534. package.child("__init__.py").setContent(b"")
  535. plugins = package.child("plugins")
  536. plugins.makedirs()
  537. plugins.child("__init__.py").setContent(pluginInitFile)
  538. pluginModule = plugins.child(pluginName + ".py")
  539. pluginModule.setContent(pluginFileContents(name))
  540. return directory
  541. def test_hiddenPackageSamePluginModuleNameObscured(self):
  542. """
  543. Only plugins from the first package in sys.path should be returned by
  544. getPlugins in the case where there are two Python packages by the same
  545. name installed, each with a plugin module by a single name.
  546. """
  547. root = FilePath(self.mktemp())
  548. root.makedirs()
  549. firstDirectory = self.createDummyPackage(root, "first", "someplugin")
  550. secondDirectory = self.createDummyPackage(root, "second", "someplugin")
  551. sys.path.append(firstDirectory.path)
  552. sys.path.append(secondDirectory.path)
  553. import dummy.plugins # type: ignore[import]
  554. plugins = list(plugin.getPlugins(ITestPlugin, dummy.plugins))
  555. self.assertEqual(["first"], [p.__name__ for p in plugins])
  556. def test_hiddenPackageDifferentPluginModuleNameObscured(self):
  557. """
  558. Plugins from the first package in sys.path should be returned by
  559. getPlugins in the case where there are two Python packages by the same
  560. name installed, each with a plugin module by a different name.
  561. """
  562. root = FilePath(self.mktemp())
  563. root.makedirs()
  564. firstDirectory = self.createDummyPackage(root, "first", "thisplugin")
  565. secondDirectory = self.createDummyPackage(root, "second", "thatplugin")
  566. sys.path.append(firstDirectory.path)
  567. sys.path.append(secondDirectory.path)
  568. import dummy.plugins
  569. plugins = list(plugin.getPlugins(ITestPlugin, dummy.plugins))
  570. self.assertEqual(["first"], [p.__name__ for p in plugins])
  571. class PackagePathTests(unittest.TestCase):
  572. """
  573. Tests for L{plugin.pluginPackagePaths} which constructs search paths for
  574. plugin packages.
  575. """
  576. def setUp(self):
  577. """
  578. Save the elements of C{sys.path}.
  579. """
  580. self.originalPath = sys.path[:]
  581. def tearDown(self):
  582. """
  583. Restore C{sys.path} to its original value.
  584. """
  585. sys.path[:] = self.originalPath
  586. def test_pluginDirectories(self):
  587. """
  588. L{plugin.pluginPackagePaths} should return a list containing each
  589. directory in C{sys.path} with a suffix based on the supplied package
  590. name.
  591. """
  592. foo = FilePath("foo")
  593. bar = FilePath("bar")
  594. sys.path = [foo.path, bar.path]
  595. self.assertEqual(
  596. plugin.pluginPackagePaths("dummy.plugins"),
  597. [
  598. foo.child("dummy").child("plugins").path,
  599. bar.child("dummy").child("plugins").path,
  600. ],
  601. )
  602. def test_pluginPackagesExcluded(self):
  603. """
  604. L{plugin.pluginPackagePaths} should exclude directories which are
  605. Python packages. The only allowed plugin package (the only one
  606. associated with a I{dummy} package which Python will allow to be
  607. imported) will already be known to the caller of
  608. L{plugin.pluginPackagePaths} and will most commonly already be in
  609. the C{__path__} they are about to mutate.
  610. """
  611. root = FilePath(self.mktemp())
  612. foo = root.child("foo").child("dummy").child("plugins")
  613. foo.makedirs()
  614. foo.child("__init__.py").setContent(b"")
  615. sys.path = [root.child("foo").path, root.child("bar").path]
  616. self.assertEqual(
  617. plugin.pluginPackagePaths("dummy.plugins"),
  618. [root.child("bar").child("dummy").child("plugins").path],
  619. )