0001 import os, sys, string, random, tempfile, unittest 0002 0003 from test.test_support import run_unittest 0004 0005 class TestImport(unittest.TestCase): 0006 0007 def __init__(self, *args, **kw): 0008 self.package_name = 'PACKAGE_' 0009 while sys.modules.has_key(self.package_name): 0010 self.package_name += random.choose(string.letters) 0011 self.module_name = self.package_name + '.foo' 0012 unittest.TestCase.__init__(self, *args, **kw) 0013 0014 def remove_modules(self): 0015 for module_name in (self.package_name, self.module_name): 0016 if sys.modules.has_key(module_name): 0017 del sys.modules[module_name] 0018 0019 def setUp(self): 0020 self.test_dir = tempfile.mkdtemp() 0021 sys.path.append(self.test_dir) 0022 self.package_dir = os.path.join(self.test_dir, 0023 self.package_name) 0024 os.mkdir(self.package_dir) 0025 open(os.path.join(self.package_dir, '__init__'+os.extsep+'py'), 'w') 0026 self.module_path = os.path.join(self.package_dir, 'foo'+os.extsep+'py') 0027 0028 def tearDown(self): 0029 for file in os.listdir(self.package_dir): 0030 os.remove(os.path.join(self.package_dir, file)) 0031 os.rmdir(self.package_dir) 0032 os.rmdir(self.test_dir) 0033 self.assertNotEqual(sys.path.count(self.test_dir), 0) 0034 sys.path.remove(self.test_dir) 0035 self.remove_modules() 0036 0037 def rewrite_file(self, contents): 0038 for extension in "co": 0039 compiled_path = self.module_path + extension 0040 if os.path.exists(compiled_path): 0041 os.remove(compiled_path) 0042 f = open(self.module_path, 'w') 0043 f.write(contents) 0044 f.close() 0045 0046 def test_package_import__semantics(self): 0047 0048 # Generate a couple of broken modules to try importing. 0049 0050 # ...try loading the module when there's a SyntaxError 0051 self.rewrite_file('for') 0052 try: __import__(self.module_name) 0053 except SyntaxError: pass 0054 else: raise RuntimeError, 'Failed to induce SyntaxError' 0055 self.assert_(not sys.modules.has_key(self.module_name) and 0056 not hasattr(sys.modules[self.package_name], 'foo')) 0057 0058 # ...make up a variable name that isn't bound in __builtins__ 0059 var = 'a' 0060 while var in dir(__builtins__): 0061 var += random.choose(string.letters) 0062 0063 # ...make a module that just contains that 0064 self.rewrite_file(var) 0065 0066 try: __import__(self.module_name) 0067 except NameError: pass 0068 else: raise RuntimeError, 'Failed to induce NameError.' 0069 0070 # ...now change the module so that the NameError doesn't 0071 # happen 0072 self.rewrite_file('%s = 1' % var) 0073 module = __import__(self.module_name).foo 0074 self.assertEqual(getattr(module, var), 1) 0075 0076 0077 def test_main(): 0078 run_unittest(TestImport) 0079 0080 0081 if __name__ == "__main__": 0082 test_main() 0083
Generated by PyXR 0.9.4