Imported Upstream version 12.1.0
[contrib/python-twisted.git] / twisted / python / test / modules_helpers.py
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 Facilities for helping test code which interacts with L{twisted.python.modules},
6 or uses Python's own module system to load code.
7 """
8
9 import sys
10
11 from twisted.trial.unittest import TestCase
12 from twisted.python import modules
13 from twisted.python.filepath import FilePath
14
15 class TwistedModulesTestCase(TestCase):
16
17     def findByIteration(self, modname, where=modules, importPackages=False):
18         """
19         You don't ever actually want to do this, so it's not in the public API, but
20         sometimes we want to compare the result of an iterative call with a
21         lookup call and make sure they're the same for test purposes.
22         """
23         for modinfo in where.walkModules(importPackages=importPackages):
24             if modinfo.name == modname:
25                 return modinfo
26         self.fail("Unable to find module %r through iteration." % (modname,))
27
28
29     def replaceSysPath(self, sysPath):
30         """
31         Replace sys.path, for the duration of the test, with the given value.
32         """
33         originalSysPath = sys.path[:]
34         def cleanUpSysPath():
35             sys.path[:] = originalSysPath
36         self.addCleanup(cleanUpSysPath)
37         sys.path[:] = sysPath
38
39
40     def replaceSysModules(self, sysModules):
41         """
42         Replace sys.modules, for the duration of the test, with the given value.
43         """
44         originalSysModules = sys.modules.copy()
45         def cleanUpSysModules():
46             sys.modules.clear()
47             sys.modules.update(originalSysModules)
48         self.addCleanup(cleanUpSysModules)
49         sys.modules.clear()
50         sys.modules.update(sysModules)
51
52
53     def pathEntryWithOnePackage(self, pkgname="test_package"):
54         """
55         Generate a L{FilePath} with one package, named C{pkgname}, on it, and
56         return the L{FilePath} of the path entry.
57         """
58         entry = FilePath(self.mktemp())
59         pkg = entry.child("test_package")
60         pkg.makedirs()
61         pkg.child("__init__.py").setContent("")
62         return entry
63
64