0001 import sys 0002 import imp 0003 import os 0004 import unittest 0005 from test import test_support 0006 0007 0008 test_src = """\ 0009 def get_name(): 0010 return __name__ 0011 def get_file(): 0012 return __file__ 0013 """ 0014 0015 reload_src = test_src+"""\ 0016 reloaded = True 0017 """ 0018 0019 test_co = compile(test_src, "<???>", "exec") 0020 reload_co = compile(reload_src, "<???>", "exec") 0021 0022 test_path = "!!!_test_!!!" 0023 0024 0025 class ImportTracker: 0026 """Importer that only tracks attempted imports.""" 0027 def __init__(self): 0028 self.imports = [] 0029 def find_module(self, fullname, path=None): 0030 self.imports.append(fullname) 0031 return None 0032 0033 0034 class TestImporter: 0035 0036 modules = { 0037 "hooktestmodule": (False, test_co), 0038 "hooktestpackage": (True, test_co), 0039 "hooktestpackage.sub": (True, test_co), 0040 "hooktestpackage.sub.subber": (False, test_co), 0041 "reloadmodule": (False, test_co), 0042 } 0043 0044 def __init__(self, path=test_path): 0045 if path != test_path: 0046 # if out class is on sys.path_hooks, we must raise 0047 # ImportError for any path item that we can't handle. 0048 raise ImportError 0049 self.path = path 0050 0051 def _get__path__(self): 0052 raise NotImplementedError 0053 0054 def find_module(self, fullname, path=None): 0055 if fullname in self.modules: 0056 return self 0057 else: 0058 return None 0059 0060 def load_module(self, fullname): 0061 ispkg, code = self.modules[fullname] 0062 mod = sys.modules.setdefault(fullname,imp.new_module(fullname)) 0063 mod.__file__ = "<%s>" % self.__class__.__name__ 0064 mod.__loader__ = self 0065 if ispkg: 0066 mod.__path__ = self._get__path__() 0067 exec code in mod.__dict__ 0068 return mod 0069 0070 0071 class MetaImporter(TestImporter): 0072 def _get__path__(self): 0073 return [] 0074 0075 class PathImporter(TestImporter): 0076 def _get__path__(self): 0077 return [self.path] 0078 0079 0080 class ImportBlocker: 0081 """Place an ImportBlocker instance on sys.meta_path and you 0082 can be sure the modules you specified can't be imported, even 0083 if it's a builtin.""" 0084 def __init__(self, *namestoblock): 0085 self.namestoblock = dict.fromkeys(namestoblock) 0086 def find_module(self, fullname, path=None): 0087 if fullname in self.namestoblock: 0088 return self 0089 return None 0090 def load_module(self, fullname): 0091 raise ImportError, "I dare you" 0092 0093 0094 class ImpWrapper: 0095 0096 def __init__(self, path=None): 0097 if path is not None and not os.path.isdir(path): 0098 raise ImportError 0099 self.path = path 0100 0101 def find_module(self, fullname, path=None): 0102 subname = fullname.split(".")[-1] 0103 if subname != fullname and self.path is None: 0104 return None 0105 if self.path is None: 0106 path = None 0107 else: 0108 path = [self.path] 0109 try: 0110 file, filename, stuff = imp.find_module(subname, path) 0111 except ImportError: 0112 return None 0113 return ImpLoader(file, filename, stuff) 0114 0115 0116 class ImpLoader: 0117 0118 def __init__(self, file, filename, stuff): 0119 self.file = file 0120 self.filename = filename 0121 self.stuff = stuff 0122 0123 def load_module(self, fullname): 0124 mod = imp.load_module(fullname, self.file, self.filename, self.stuff) 0125 if self.file: 0126 self.file.close() 0127 mod.__loader__ = self # for introspection 0128 return mod 0129 0130 0131 class ImportHooksBaseTestCase(unittest.TestCase): 0132 0133 def setUp(self): 0134 self.path = sys.path[:] 0135 self.meta_path = sys.meta_path[:] 0136 self.path_hooks = sys.path_hooks[:] 0137 sys.path_importer_cache.clear() 0138 self.tracker = ImportTracker() 0139 sys.meta_path.insert(0, self.tracker) 0140 0141 def tearDown(self): 0142 sys.path[:] = self.path 0143 sys.meta_path[:] = self.meta_path 0144 sys.path_hooks[:] = self.path_hooks 0145 sys.path_importer_cache.clear() 0146 for fullname in self.tracker.imports: 0147 if fullname in sys.modules: 0148 del sys.modules[fullname] 0149 0150 0151 class ImportHooksTestCase(ImportHooksBaseTestCase): 0152 0153 def doTestImports(self, importer=None): 0154 import hooktestmodule 0155 import hooktestpackage 0156 import hooktestpackage.sub 0157 import hooktestpackage.sub.subber 0158 self.assertEqual(hooktestmodule.get_name(), 0159 "hooktestmodule") 0160 self.assertEqual(hooktestpackage.get_name(), 0161 "hooktestpackage") 0162 self.assertEqual(hooktestpackage.sub.get_name(), 0163 "hooktestpackage.sub") 0164 self.assertEqual(hooktestpackage.sub.subber.get_name(), 0165 "hooktestpackage.sub.subber") 0166 if importer: 0167 self.assertEqual(hooktestmodule.__loader__, importer) 0168 self.assertEqual(hooktestpackage.__loader__, importer) 0169 self.assertEqual(hooktestpackage.sub.__loader__, importer) 0170 self.assertEqual(hooktestpackage.sub.subber.__loader__, importer) 0171 0172 TestImporter.modules['reloadmodule'] = (False, test_co) 0173 import reloadmodule 0174 self.failIf(hasattr(reloadmodule,'reloaded')) 0175 0176 TestImporter.modules['reloadmodule'] = (False, reload_co) 0177 reload(reloadmodule) 0178 self.failUnless(hasattr(reloadmodule,'reloaded')) 0179 0180 def testMetaPath(self): 0181 i = MetaImporter() 0182 sys.meta_path.append(i) 0183 self.doTestImports(i) 0184 0185 def testPathHook(self): 0186 sys.path_hooks.append(PathImporter) 0187 sys.path.append(test_path) 0188 self.doTestImports() 0189 0190 def testBlocker(self): 0191 mname = "exceptions" # an arbitrary harmless builtin module 0192 if mname in sys.modules: 0193 del sys.modules[mname] 0194 sys.meta_path.append(ImportBlocker(mname)) 0195 try: 0196 __import__(mname) 0197 except ImportError: 0198 pass 0199 else: 0200 self.fail("'%s' was not supposed to be importable" % mname) 0201 0202 def testImpWrapper(self): 0203 i = ImpWrapper() 0204 sys.meta_path.append(i) 0205 sys.path_hooks.append(ImpWrapper) 0206 mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc") 0207 for mname in mnames: 0208 parent = mname.split(".")[0] 0209 for n in sys.modules.keys(): 0210 if n.startswith(parent): 0211 del sys.modules[n] 0212 for mname in mnames: 0213 m = __import__(mname, globals(), locals(), ["__dummy__"]) 0214 m.__loader__ # to make sure we actually handled the import 0215 0216 def test_main(): 0217 test_support.run_unittest(ImportHooksTestCase) 0218 0219 if __name__ == "__main__": 0220 test_main() 0221
Generated by PyXR 0.9.4