202
206
class TestImportReplacer(TestCaseInTempDir):
203
207
"""Test the ability to have a lazily imported module or object"""
210
TestCaseInTempDir.setUp(self)
211
self.create_modules()
212
base_path = self.test_dir + '/base'
214
sys.path.append(base_path)
216
sys.path.remove(base_path)
218
def create_modules(self):
219
"""Create some random modules to be imported.
221
Each entry has a random suffix, and the full names are saved
223
These are setup as follows:
224
base/ <= used to ensure not in default search path
226
__init__.py <= This will contain var1, func1
227
mod-XXX.py <= This will contain var2, func2
229
__init__.py <= Contains var3, func3
230
submod-XXX.py <= contains var4, func4
232
rand_suffix = osutils.rand_chars(4)
233
root_name = 'root_' + rand_suffix
234
mod_name = 'mod_' + rand_suffix
235
sub_name = 'sub_' + rand_suffix
236
submod_name = 'submod_' + rand_suffix
238
root_path = osutils.pathjoin('base', root_name)
240
root_init = osutils.pathjoin(root_path, '__init__.py')
241
f = open(osutils.pathjoin(root_path, '__init__.py'), 'wb')
243
f.write('var1 = 1\ndef func1(a):\n return a\n')
246
mod_path = osutils.pathjoin(root_path, mod_name + '.py')
247
f = open(mod_path, 'wb')
249
f.write('var2 = 2\ndef func2(a):\n return a\n')
253
sub_path = osutils.pathjoin(root_path, sub_name)
255
f = open(osutils.pathjoin(sub_path, '__init__.py'), 'wb')
257
f.write('var3 = 3\ndef func3(a):\n return a\n')
260
submod_path = osutils.pathjoin(sub_path, submod_name + '.py')
261
f = open(submod_path, 'wb')
263
f.write('var4 = 4\ndef func4(a):\n return a\n')
266
self.root_name = root_name
267
self.mod_name = mod_name
268
self.sub_name = sub_name
269
self.submod_name = submod_name
271
def test_basic_import(self):
272
root = __import__('.'.join([self.root_name, self.sub_name,
274
globals(), locals(), [])
275
self.assertEqual(1, root.var1)
276
self.assertEqual(3, getattr(root, self.sub_name).var3)
277
self.assertEqual(4, getattr(getattr(root, self.sub_name),
278
self.submod_name).var4)