modules_helpers.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Facilities for helping test code which interacts with Python's module system
  5. to load code.
  6. """
  7. from __future__ import division, absolute_import
  8. import sys
  9. from twisted.python.filepath import FilePath
  10. class TwistedModulesMixin(object):
  11. """
  12. A mixin for C{twisted.trial.unittest.SynchronousTestCase} providing useful
  13. methods for manipulating Python's module system.
  14. """
  15. def replaceSysPath(self, sysPath):
  16. """
  17. Replace sys.path, for the duration of the test, with the given value.
  18. """
  19. originalSysPath = sys.path[:]
  20. def cleanUpSysPath():
  21. sys.path[:] = originalSysPath
  22. self.addCleanup(cleanUpSysPath)
  23. sys.path[:] = sysPath
  24. def replaceSysModules(self, sysModules):
  25. """
  26. Replace sys.modules, for the duration of the test, with the given value.
  27. """
  28. originalSysModules = sys.modules.copy()
  29. def cleanUpSysModules():
  30. sys.modules.clear()
  31. sys.modules.update(originalSysModules)
  32. self.addCleanup(cleanUpSysModules)
  33. sys.modules.clear()
  34. sys.modules.update(sysModules)
  35. def pathEntryWithOnePackage(self, pkgname="test_package"):
  36. """
  37. Generate a L{FilePath} with one package, named C{pkgname}, on it, and
  38. return the L{FilePath} of the path entry.
  39. """
  40. entry = FilePath(self.mktemp())
  41. pkg = entry.child("test_package")
  42. pkg.makedirs()
  43. pkg.child("__init__.py").setContent(b"")
  44. return entry