aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_components.py
blob: c4c1b451b6f439faaca84a98819f89a5c2925d69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.


"""
Test cases for Twisted component architecture.
"""

from zope.interface import Interface, implements, Attribute
from zope.interface.adapter import AdapterRegistry

from twisted.trial import unittest
from twisted.python import components
from twisted.python.components import _addHook, _removeHook, proxyForInterface


class InterfacesTestCase(unittest.TestCase):
    """Test interfaces."""

class Compo(components.Componentized):
    num = 0
    def inc(self):
        self.num = self.num + 1
        return self.num

class IAdept(Interface):
    def adaptorFunc():
        raise NotImplementedError()

class IElapsed(Interface):
    def elapsedFunc():
        """
        1!
        """

class Adept(components.Adapter):
    implements(IAdept)
    def __init__(self, orig):
        self.original = orig
        self.num = 0
    def adaptorFunc(self):
        self.num = self.num + 1
        return self.num, self.original.inc()

class Elapsed(components.Adapter):
    implements(IElapsed)
    def elapsedFunc(self):
        return 1

class AComp(components.Componentized):
    pass
class BComp(AComp):
    pass
class CComp(BComp):
    pass

class ITest(Interface):
    pass
class ITest2(Interface):
    pass
class ITest3(Interface):
    pass
class ITest4(Interface):
    pass
class Test(components.Adapter):
    implements(ITest, ITest3, ITest4)
    def __init__(self, orig):
        pass
class Test2:
    implements(ITest2)
    temporaryAdapter = 1
    def __init__(self, orig):
        pass



class RegistryUsingMixin(object):
    """
    Mixin for test cases which modify the global registry somehow.
    """
    def setUp(self):
        """
        Configure L{twisted.python.components.registerAdapter} to mutate an
        alternate registry to improve test isolation.
        """
        # Create a brand new, empty registry and put it onto the components
        # module where registerAdapter will use it.  Also ensure that it goes
        # away at the end of the test.
        scratchRegistry = AdapterRegistry()
        self.patch(components, 'globalRegistry', scratchRegistry)
        # Hook the new registry up to the adapter lookup system and ensure that
        # association is also discarded after the test.
        hook = _addHook(scratchRegistry)
        self.addCleanup(_removeHook, hook)



class ComponentizedTestCase(unittest.TestCase, RegistryUsingMixin):
    """
    Simple test case for caching in Componentized.
    """
    def setUp(self):
        RegistryUsingMixin.setUp(self)

        components.registerAdapter(Test, AComp, ITest)
        components.registerAdapter(Test, AComp, ITest3)
        components.registerAdapter(Test2, AComp, ITest2)


    def testComponentized(self):
        components.registerAdapter(Adept, Compo, IAdept)
        components.registerAdapter(Elapsed, Compo, IElapsed)

        c = Compo()
        assert c.getComponent(IAdept).adaptorFunc() == (1, 1)
        assert c.getComponent(IAdept).adaptorFunc() == (2, 2)
        assert IElapsed(IAdept(c)).elapsedFunc() == 1

    def testInheritanceAdaptation(self):
        c = CComp()
        co1 = c.getComponent(ITest)
        co2 = c.getComponent(ITest)
        co3 = c.getComponent(ITest2)
        co4 = c.getComponent(ITest2)
        assert co1 is co2
        assert co3 is not co4
        c.removeComponent(co1)
        co5 = c.getComponent(ITest)
        co6 = c.getComponent(ITest)
        assert co5 is co6
        assert co1 is not co5

    def testMultiAdapter(self):
        c = CComp()
        co1 = c.getComponent(ITest)
        co2 = c.getComponent(ITest2)
        co3 = c.getComponent(ITest3)
        co4 = c.getComponent(ITest4)
        self.assertIdentical(None, co4)
        self.assertIdentical(co1, co3)


    def test_getComponentDefaults(self):
        """
        Test that a default value specified to Componentized.getComponent if
        there is no component for the requested interface.
        """
        componentized = components.Componentized()
        default = object()
        self.assertIdentical(
            componentized.getComponent(ITest, default),
            default)
        self.assertIdentical(
            componentized.getComponent(ITest, default=default),
            default)
        self.assertIdentical(
            componentized.getComponent(ITest),
            None)



class AdapterTestCase(unittest.TestCase):
    """Test adapters."""

    def testAdapterGetComponent(self):
        o = object()
        a = Adept(o)
        self.assertRaises(components.CannotAdapt, ITest, a)
        self.assertEqual(ITest(a, None), None)



class IMeta(Interface):
    pass

class MetaAdder(components.Adapter):
    implements(IMeta)
    def add(self, num):
        return self.original.num + num

class BackwardsAdder(components.Adapter):
    implements(IMeta)
    def add(self, num):
        return self.original.num - num

class MetaNumber:
    def __init__(self, num):
        self.num = num

class FakeAdder:
    def add(self, num):
        return num + 5

class FakeNumber:
    num = 3

class ComponentNumber(components.Componentized):
    def __init__(self):
        self.num = 0
        components.Componentized.__init__(self)

class ComponentMeta(components.Adapter):
    implements(IMeta)
    def __init__(self, original):
        components.Adapter.__init__(self, original)
        self.num = self.original.num

class ComponentAdder(ComponentMeta):
    def add(self, num):
        self.num += num
        return self.num

class ComponentDoubler(ComponentMeta):
    def add(self, num):
        self.num += (num * 2)
        return self.original.num

class IAttrX(Interface):
    def x():
        pass

class IAttrXX(Interface):
    def xx():
        pass

class Xcellent:
    implements(IAttrX)
    def x(self):
        return 'x!'

class DoubleXAdapter:
    num = 42
    def __init__(self, original):
        self.original = original
    def xx(self):
        return (self.original.x(), self.original.x())
    def __cmp__(self, other):
        return cmp(self.num, other.num)


class TestMetaInterface(RegistryUsingMixin, unittest.TestCase):
    def testBasic(self):
        components.registerAdapter(MetaAdder, MetaNumber, IMeta)
        n = MetaNumber(1)
        self.assertEqual(IMeta(n).add(1), 2)

    def testComponentizedInteraction(self):
        components.registerAdapter(ComponentAdder, ComponentNumber, IMeta)
        c = ComponentNumber()
        IMeta(c).add(1)
        IMeta(c).add(1)
        self.assertEqual(IMeta(c).add(1), 3)

    def testAdapterWithCmp(self):
        # Make sure that a __cmp__ on an adapter doesn't break anything
        components.registerAdapter(DoubleXAdapter, IAttrX, IAttrXX)
        xx = IAttrXX(Xcellent())
        self.assertEqual(('x!', 'x!'), xx.xx())


class RegistrationTestCase(RegistryUsingMixin, unittest.TestCase):
    """
    Tests for adapter registration.
    """
    def _registerAdapterForClassOrInterface(self, original):
        """
        Register an adapter with L{components.registerAdapter} for the given
        class or interface and verify that the adapter can be looked up with
        L{components.getAdapterFactory}.
        """
        adapter = lambda o: None
        components.registerAdapter(adapter, original, ITest)
        self.assertIdentical(
            components.getAdapterFactory(original, ITest, None),
            adapter)


    def test_registerAdapterForClass(self):
        """
        Test that an adapter from a class can be registered and then looked
        up.
        """
        class TheOriginal(object):
            pass
        return self._registerAdapterForClassOrInterface(TheOriginal)


    def test_registerAdapterForInterface(self):
        """
        Test that an adapter from an interface can be registered and then
        looked up.
        """
        return self._registerAdapterForClassOrInterface(ITest2)


    def _duplicateAdapterForClassOrInterface(self, original):
        """
        Verify that L{components.registerAdapter} raises L{ValueError} if the
        from-type/interface and to-interface pair is not unique.
        """
        firstAdapter = lambda o: False
        secondAdapter = lambda o: True
        components.registerAdapter(firstAdapter, original, ITest)
        self.assertRaises(
            ValueError,
            components.registerAdapter,
            secondAdapter, original, ITest)
        # Make sure that the original adapter is still around as well
        self.assertIdentical(
            components.getAdapterFactory(original, ITest, None),
            firstAdapter)


    def test_duplicateAdapterForClass(self):
        """
        Test that attempting to register a second adapter from a class
        raises the appropriate exception.
        """
        class TheOriginal(object):
            pass
        return self._duplicateAdapterForClassOrInterface(TheOriginal)


    def test_duplicateAdapterForInterface(self):
        """
        Test that attempting to register a second adapter from an interface
        raises the appropriate exception.
        """
        return self._duplicateAdapterForClassOrInterface(ITest2)


    def _duplicateAdapterForClassOrInterfaceAllowed(self, original):
        """
        Verify that when C{components.ALLOW_DUPLICATES} is set to C{True}, new
        adapter registrations for a particular from-type/interface and
        to-interface pair replace older registrations.
        """
        firstAdapter = lambda o: False
        secondAdapter = lambda o: True
        class TheInterface(Interface):
            pass
        components.registerAdapter(firstAdapter, original, TheInterface)
        components.ALLOW_DUPLICATES = True
        try:
            components.registerAdapter(secondAdapter, original, TheInterface)
            self.assertIdentical(
                components.getAdapterFactory(original, TheInterface, None),
                secondAdapter)
        finally:
            components.ALLOW_DUPLICATES = False

        # It should be rejected again at this point
        self.assertRaises(
            ValueError,
            components.registerAdapter,
            firstAdapter, original, TheInterface)

        self.assertIdentical(
            components.getAdapterFactory(original, TheInterface, None),
            secondAdapter)


    def test_duplicateAdapterForClassAllowed(self):
        """
        Test that when L{components.ALLOW_DUPLICATES} is set to a true
        value, duplicate registrations from classes are allowed to override
        the original registration.
        """
        class TheOriginal(object):
            pass
        return self._duplicateAdapterForClassOrInterfaceAllowed(TheOriginal)


    def test_duplicateAdapterForInterfaceAllowed(self):
        """
        Test that when L{components.ALLOW_DUPLICATES} is set to a true
        value, duplicate registrations from interfaces are allowed to
        override the original registration.
        """
        class TheOriginal(Interface):
            pass
        return self._duplicateAdapterForClassOrInterfaceAllowed(TheOriginal)


    def _multipleInterfacesForClassOrInterface(self, original):
        """
        Verify that an adapter can be registered for multiple to-interfaces at a
        time.
        """
        adapter = lambda o: None
        components.registerAdapter(adapter, original, ITest, ITest2)
        self.assertIdentical(
            components.getAdapterFactory(original, ITest, None), adapter)
        self.assertIdentical(
            components.getAdapterFactory(original, ITest2, None), adapter)


    def test_multipleInterfacesForClass(self):
        """
        Test the registration of an adapter from a class to several
        interfaces at once.
        """
        class TheOriginal(object):
            pass
        return self._multipleInterfacesForClassOrInterface(TheOriginal)


    def test_multipleInterfacesForInterface(self):
        """
        Test the registration of an adapter from an interface to several
        interfaces at once.
        """
        return self._multipleInterfacesForClassOrInterface(ITest3)


    def _subclassAdapterRegistrationForClassOrInterface(self, original):
        """
        Verify that a new adapter can be registered for a particular
        to-interface from a subclass of a type or interface which already has an
        adapter registered to that interface and that the subclass adapter takes
        precedence over the base class adapter.
        """
        firstAdapter = lambda o: True
        secondAdapter = lambda o: False
        class TheSubclass(original):
            pass
        components.registerAdapter(firstAdapter, original, ITest)
        components.registerAdapter(secondAdapter, TheSubclass, ITest)
        self.assertIdentical(
            components.getAdapterFactory(original, ITest, None),
            firstAdapter)
        self.assertIdentical(
            components.getAdapterFactory(TheSubclass, ITest, None),
            secondAdapter)


    def test_subclassAdapterRegistrationForClass(self):
        """
        Test that an adapter to a particular interface can be registered
        from both a class and its subclass.
        """
        class TheOriginal(object):
            pass
        return self._subclassAdapterRegistrationForClassOrInterface(TheOriginal)


    def test_subclassAdapterRegistrationForInterface(self):
        """
        Test that an adapter to a particular interface can be registered
        from both an interface and its subclass.
        """
        return self._subclassAdapterRegistrationForClassOrInterface(ITest2)



class IProxiedInterface(Interface):
    """
    An interface class for use by L{proxyForInterface}.
    """

    ifaceAttribute = Attribute("""
        An example declared attribute, which should be proxied.""")

    def yay(*a, **kw):
        """
        A sample method which should be proxied.
        """

class IProxiedSubInterface(IProxiedInterface):
    """
    An interface that derives from another for use with L{proxyForInterface}.
    """

    def boo(self):
        """
        A different sample method which should be proxied.
        """



class Yayable(object):
    """
    A provider of L{IProxiedInterface} which increments a counter for
    every call to C{yay}.

    @ivar yays: The number of times C{yay} has been called.
    """
    implements(IProxiedInterface)

    def __init__(self):
        self.yays = 0
        self.yayArgs = []

    def yay(self, *a, **kw):
        """
        Increment C{self.yays}.
        """
        self.yays += 1
        self.yayArgs.append((a, kw))
        return self.yays


class Booable(object):
    """
    An implementation of IProxiedSubInterface
    """
    implements(IProxiedSubInterface)
    yayed = False
    booed = False
    def yay(self):
        """
        Mark the fact that 'yay' has been called.
        """
        self.yayed = True


    def boo(self):
        """
        Mark the fact that 'boo' has been called.1
        """
        self.booed = True



class IMultipleMethods(Interface):
    """
    An interface with multiple methods.
    """

    def methodOne():
        """
        The first method. Should return 1.
        """

    def methodTwo():
        """
        The second method. Should return 2.
        """



class MultipleMethodImplementor(object):
    """
    A precise implementation of L{IMultipleMethods}.
    """

    def methodOne(self):
        """
        @return: 1
        """
        return 1


    def methodTwo(self):
        """
        @return: 2
        """
        return 2



class ProxyForInterfaceTests(unittest.TestCase):
    """
    Tests for L{proxyForInterface}.
    """

    def test_original(self):
        """
        Proxy objects should have an C{original} attribute which refers to the
        original object passed to the constructor.
        """
        original = object()
        proxy = proxyForInterface(IProxiedInterface)(original)
        self.assertIdentical(proxy.original, original)


    def test_proxyMethod(self):
        """
        The class created from L{proxyForInterface} passes methods on an
        interface to the object which is passed to its constructor.
        """
        klass = proxyForInterface(IProxiedInterface)
        yayable = Yayable()
        proxy = klass(yayable)
        proxy.yay()
        self.assertEqual(proxy.yay(), 2)
        self.assertEqual(yayable.yays, 2)


    def test_proxyAttribute(self):
        """
        Proxy objects should proxy declared attributes, but not other
        attributes.
        """
        yayable = Yayable()
        yayable.ifaceAttribute = object()
        proxy = proxyForInterface(IProxiedInterface)(yayable)
        self.assertIdentical(proxy.ifaceAttribute, yayable.ifaceAttribute)
        self.assertRaises(AttributeError, lambda: proxy.yays)


    def test_proxySetAttribute(self):
        """
        The attributes that proxy objects proxy should be assignable and affect
        the original object.
        """
        yayable = Yayable()
        proxy = proxyForInterface(IProxiedInterface)(yayable)
        thingy = object()
        proxy.ifaceAttribute = thingy
        self.assertIdentical(yayable.ifaceAttribute, thingy)


    def test_proxyDeleteAttribute(self):
        """
        The attributes that proxy objects proxy should be deletable and affect
        the original object.
        """
        yayable = Yayable()
        yayable.ifaceAttribute = None
        proxy = proxyForInterface(IProxiedInterface)(yayable)
        del proxy.ifaceAttribute
        self.assertFalse(hasattr(yayable, 'ifaceAttribute'))


    def test_multipleMethods(self):
        """
        [Regression test] The proxy should send its method calls to the correct
        method, not the incorrect one.
        """
        multi = MultipleMethodImplementor()
        proxy = proxyForInterface(IMultipleMethods)(multi)
        self.assertEqual(proxy.methodOne(), 1)
        self.assertEqual(proxy.methodTwo(), 2)


    def test_subclassing(self):
        """
        It is possible to subclass the result of L{proxyForInterface}.
        """

        class SpecializedProxy(proxyForInterface(IProxiedInterface)):
            """
            A specialized proxy which can decrement the number of yays.
            """
            def boo(self):
                """
                Decrement the number of yays.
                """
                self.original.yays -= 1

        yayable = Yayable()
        special = SpecializedProxy(yayable)
        self.assertEqual(yayable.yays, 0)
        special.boo()
        self.assertEqual(yayable.yays, -1)


    def test_proxyName(self):
        """
        The name of a proxy class indicates which interface it proxies.
        """
        proxy = proxyForInterface(IProxiedInterface)
        self.assertEqual(
            proxy.__name__,
            "(Proxy for "
            "twisted.python.test.test_components.IProxiedInterface)")


    def test_implements(self):
        """
        The resulting proxy implements the interface that it proxies.
        """
        proxy = proxyForInterface(IProxiedInterface)
        self.assertTrue(IProxiedInterface.implementedBy(proxy))


    def test_proxyDescriptorGet(self):
        """
        _ProxyDescriptor's __get__ method should return the appropriate
        attribute of its argument's 'original' attribute if it is invoked with
        an object.  If it is invoked with None, it should return a false
        class-method emulator instead.

        For some reason, Python's documentation recommends to define
        descriptors' __get__ methods with the 'type' parameter as optional,
        despite the fact that Python itself never actually calls the descriptor
        that way.  This is probably do to support 'foo.__get__(bar)' as an
        idiom.  Let's make sure that the behavior is correct.  Since we don't
        actually use the 'type' argument at all, this test calls it the
        idiomatic way to ensure that signature works; test_proxyInheritance
        verifies the how-Python-actually-calls-it signature.
        """
        class Sample:
            called = False
            def hello(self):
                self.called = True
        fakeProxy = Sample()
        testObject = Sample()
        fakeProxy.original = testObject
        pd = components._ProxyDescriptor("hello", "original")
        self.assertEqual(pd.__get__(fakeProxy), testObject.hello)
        fakeClassMethod = pd.__get__(None)
        fakeClassMethod(fakeProxy)
        self.failUnless(testObject.called)


    def test_proxyInheritance(self):
        """
        Subclasses of the class returned from L{proxyForInterface} should be
        able to upcall methods by reference to their superclass, as any normal
        Python class can.
        """
        class YayableWrapper(proxyForInterface(IProxiedInterface)):
            """
            This class does not override any functionality.
            """

        class EnhancedWrapper(YayableWrapper):
            """
            This class overrides the 'yay' method.
            """
            wrappedYays = 1
            def yay(self, *a, **k):
                self.wrappedYays += 1
                return YayableWrapper.yay(self, *a, **k) + 7

        yayable = Yayable()
        wrapper = EnhancedWrapper(yayable)
        self.assertEqual(wrapper.yay(3, 4, x=5, y=6), 8)
        self.assertEqual(yayable.yayArgs,
                          [((3, 4), dict(x=5, y=6))])


    def test_interfaceInheritance(self):
        """
        Proxies of subinterfaces generated with proxyForInterface should allow
        access to attributes of both the child and the base interfaces.
        """
        proxyClass = proxyForInterface(IProxiedSubInterface)
        booable = Booable()
        proxy = proxyClass(booable)
        proxy.yay()
        proxy.boo()
        self.failUnless(booable.yayed)
        self.failUnless(booable.booed)


    def test_attributeCustomization(self):
        """
        The original attribute name can be customized via the
        C{originalAttribute} argument of L{proxyForInterface}: the attribute
        should change, but the methods of the original object should still be
        callable, and the attributes still accessible.
        """
        yayable = Yayable()
        yayable.ifaceAttribute = object()
        proxy = proxyForInterface(
            IProxiedInterface, originalAttribute='foo')(yayable)
        self.assertIdentical(proxy.foo, yayable)

        # Check the behavior
        self.assertEqual(proxy.yay(), 1)
        self.assertIdentical(proxy.ifaceAttribute, yayable.ifaceAttribute)
        thingy = object()
        proxy.ifaceAttribute = thingy
        self.assertIdentical(yayable.ifaceAttribute, thingy)
        del proxy.ifaceAttribute
        self.assertFalse(hasattr(yayable, 'ifaceAttribute'))