1 import os
, sys
, string
, random
, tempfile
, unittest
3 from test
.test_support
import run_unittest
5 class TestImport(unittest
.TestCase
):
7 def __init__(self
, *args
, **kw
):
8 self
.package_name
= 'PACKAGE_'
9 while self
.package_name
in sys
.modules
:
10 self
.package_name
+= random
.choose(string
.letters
)
11 self
.module_name
= self
.package_name
+ '.foo'
12 unittest
.TestCase
.__init
__(self
, *args
, **kw
)
14 def remove_modules(self
):
15 for module_name
in (self
.package_name
, self
.module_name
):
16 if module_name
in sys
.modules
:
17 del sys
.modules
[module_name
]
20 self
.test_dir
= tempfile
.mkdtemp()
21 sys
.path
.append(self
.test_dir
)
22 self
.package_dir
= os
.path
.join(self
.test_dir
,
24 os
.mkdir(self
.package_dir
)
25 open(os
.path
.join(self
.package_dir
, '__init__'+os
.extsep
+'py'), 'w')
26 self
.module_path
= os
.path
.join(self
.package_dir
, 'foo'+os
.extsep
+'py')
29 for file in os
.listdir(self
.package_dir
):
30 os
.remove(os
.path
.join(self
.package_dir
, file))
31 os
.rmdir(self
.package_dir
)
32 os
.rmdir(self
.test_dir
)
33 self
.assertNotEqual(sys
.path
.count(self
.test_dir
), 0)
34 sys
.path
.remove(self
.test_dir
)
37 def rewrite_file(self
, contents
):
38 for extension
in "co":
39 compiled_path
= self
.module_path
+ extension
40 if os
.path
.exists(compiled_path
):
41 os
.remove(compiled_path
)
42 f
= open(self
.module_path
, 'w')
46 def test_package_import__semantics(self
):
48 # Generate a couple of broken modules to try importing.
50 # ...try loading the module when there's a SyntaxError
51 self
.rewrite_file('for')
52 try: __import__(self
.module_name
)
53 except SyntaxError: pass
54 else: raise RuntimeError, 'Failed to induce SyntaxError'
55 self
.assertNotIn(self
.module_name
, sys
.modules
)
56 self
.assertFalse(hasattr(sys
.modules
[self
.package_name
], 'foo'))
58 # ...make up a variable name that isn't bound in __builtins__
60 while var
in dir(__builtins__
):
61 var
+= random
.choose(string
.letters
)
63 # ...make a module that just contains that
64 self
.rewrite_file(var
)
66 try: __import__(self
.module_name
)
67 except NameError: pass
68 else: raise RuntimeError, 'Failed to induce NameError.'
70 # ...now change the module so that the NameError doesn't
72 self
.rewrite_file('%s = 1' % var
)
73 module
= __import__(self
.module_name
).foo
74 self
.assertEqual(getattr(module
, var
), 1)
78 run_unittest(TestImport
)
81 if __name__
== "__main__":