153
def test_setattr_replaces(self):
154
"""ScopeReplacer can create an instance in local scope.
156
An object should appear in globals() by constructing a ScopeReplacer,
157
and it will be replaced with the real object upon the first request.
160
TestClass.use_actions(actions)
161
def factory(replacer, scope, name):
166
# test_obj6 shouldn't exist yet
169
self.fail('test_obj6 was not supposed to exist yet')
171
orig_globals = set(globals().keys())
173
lazy_import.ScopeReplacer(scope=globals(), name='test_obj6',
176
new_globals = set(globals().keys())
178
# We can't use isinstance() because that uses test_obj6.__class__
179
# and that goes through __getattribute__ which would activate
181
self.assertEqual(lazy_import.ScopeReplacer,
182
object.__getattribute__(test_obj6, '__class__'))
183
test_obj6.bar = 'test'
184
self.assertNotEqual(lazy_import.ScopeReplacer,
185
object.__getattribute__(test_obj6, '__class__'))
186
self.assertEqual('test', test_obj6.bar)
144
188
def test_replace_side_effects(self):
145
189
"""Creating a new object should only create one entry in globals.
326
370
self.assertRaises(errors.IllegalUseOfScopeReplacer,
327
371
getattr, test_obj3, 'foo')
330
self.assertEqual([('__getattribute__', 'foo'),
337
('__getattribute__', 'foo'),
373
self.assertEqual([('__getattribute__', 'foo'),
380
('__getattribute__', 'foo'),
384
def test_enable_proxying(self):
385
"""Test that we can allow ScopeReplacer to proxy."""
387
InstrumentedReplacer.use_actions(actions)
388
TestClass.use_actions(actions)
390
def factory(replacer, scope, name):
391
actions.append('factory')
397
# test_obj4 shouldn't exist yet
400
self.fail('test_obj4 was not supposed to exist yet')
402
lazy_import.ScopeReplacer._should_proxy = True
403
InstrumentedReplacer(scope=globals(), name='test_obj4',
406
self.assertEqual(InstrumentedReplacer,
407
object.__getattribute__(test_obj4, '__class__'))
408
test_obj5 = test_obj4
409
self.assertEqual(InstrumentedReplacer,
410
object.__getattribute__(test_obj4, '__class__'))
411
self.assertEqual(InstrumentedReplacer,
412
object.__getattribute__(test_obj5, '__class__'))
414
# The first use of the alternate variable causes test_obj2 to
416
self.assertEqual('foo', test_obj4.foo(1))
417
self.assertEqual(TestClass,
418
object.__getattribute__(test_obj4, '__class__'))
419
self.assertEqual(InstrumentedReplacer,
420
object.__getattribute__(test_obj5, '__class__'))
421
# We should be able to access test_obj4 attributes normally
422
self.assertEqual('foo', test_obj4.foo(2))
423
# because we enabled proxying, test_obj5 can access its members as well
424
self.assertEqual('foo', test_obj5.foo(3))
425
self.assertEqual('foo', test_obj5.foo(4))
427
# However, it cannot be replaced by the ScopeReplacer
428
self.assertEqual(InstrumentedReplacer,
429
object.__getattribute__(test_obj5, '__class__'))
431
self.assertEqual([('__getattribute__', 'foo'),
437
('__getattribute__', 'foo'),
439
('__getattribute__', 'foo'),