46
46
return lazy_import.ScopeReplacer.__call__(self, *args, **kwargs)
49
class InstrumentedImportReplacer(lazy_import.ImportReplacer):
52
def use_actions(actions):
53
InstrumentedImportReplacer.actions = actions
55
def _import(self, scope, name):
56
InstrumentedImportReplacer.actions.append(('_import', name))
57
return lazy_import.ImportReplacer._import(self, scope, name)
60
InstrumentedImportReplacer.actions.append('_replace')
61
return lazy_import.ScopeReplacer._replace(self)
63
def __getattribute__(self, attr):
64
InstrumentedImportReplacer.actions.append(('__getattribute__', attr))
65
return lazy_import.ScopeReplacer.__getattribute__(self, attr)
67
def __call__(self, *args, **kwargs):
68
InstrumentedImportReplacer.actions.append(('__call__', args, kwargs))
69
return lazy_import.ScopeReplacer.__call__(self, *args, **kwargs)
49
72
class TestClass(object):
50
73
"""Just a simple test class instrumented for the test cases"""
54
75
class_member = 'class_member'
211
232
self.create_modules()
212
233
base_path = self.test_dir + '/base'
236
InstrumentedImportReplacer.use_actions(self.actions)
238
original_import = __import__
239
def instrumented_import(mod, scope1, scope2, fromlist):
240
self.actions.append(('import', mod, fromlist))
241
return original_import(mod, scope1, scope2, fromlist)
244
if base_path in sys.path:
245
sys.path.remove(base_path)
246
__builtins__['__import__'] = original_import
247
self.addCleanup(cleanup)
214
248
sys.path.append(base_path)
216
sys.path.remove(base_path)
249
__builtins__['__import__'] = instrumented_import
218
251
def create_modules(self):
219
252
"""Create some random modules to be imported.
269
302
self.submod_name = submod_name
271
304
def test_basic_import(self):
272
root = __import__('.'.join([self.root_name, self.sub_name,
274
globals(), locals(), [])
305
sub_mod_path = '.'.join([self.root_name, self.sub_name,
307
root = __import__(sub_mod_path, globals(), locals(), [])
275
308
self.assertEqual(1, root.var1)
276
309
self.assertEqual(3, getattr(root, self.sub_name).var3)
277
310
self.assertEqual(4, getattr(getattr(root, self.sub_name),
278
311
self.submod_name).var4)
313
mod_path = '.'.join([self.root_name, self.mod_name])
314
root = __import__(mod_path, globals(), locals(), [])
315
self.assertEqual(2, getattr(root, self.mod_name).var2)
317
self.assertEqual([('import', sub_mod_path, []),
318
('import', mod_path, []),
321
def test_import_root(self):
325
# root1 shouldn't exist yet
328
self.fail('root1 was not supposed to exist yet')
330
# This should replicate 'import root-xxyyzz as root1'
331
InstrumentedImportReplacer(scope=globals(), name='root1',
332
module_path=self.root_name,
336
self.assertEqual(InstrumentedImportReplacer,
337
object.__getattribute__(root1, '__class__'))
338
self.assertEqual(1, root1.var1)
339
self.assertEqual('x', root1.func1('x'))
341
self.assertEqual([('__getattribute__', 'var1'),
343
('_import', 'root1'),
344
('import', self.root_name, []),