aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/test/test_pb.py
blob: 4616708f093016e18e2520ffef48cf5f18f4274d (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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for Perspective Broker module.

TODO: update protocol level tests to use new connection API, leaving
only specific tests for old API.
"""

# issue1195 TODOs: replace pump.pump() with something involving Deferreds.
# Clean up warning suppression.

import sys, os, time, gc, weakref

from cStringIO import StringIO
from zope.interface import implements, Interface

from twisted.trial import unittest
from twisted.spread import pb, util, publish, jelly
from twisted.internet import protocol, main, reactor
from twisted.internet.error import ConnectionRefusedError
from twisted.internet.defer import Deferred, gatherResults, succeed
from twisted.protocols.policies import WrappingFactory
from twisted.python import failure, log
from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
from twisted.cred import portal, checkers, credentials


class Dummy(pb.Viewable):
    def view_doNothing(self, user):
        if isinstance(user, DummyPerspective):
            return 'hello world!'
        else:
            return 'goodbye, cruel world!'


class DummyPerspective(pb.Avatar):
    """
    An L{IPerspective} avatar which will be used in some tests.
    """
    def perspective_getDummyViewPoint(self):
        return Dummy()



class DummyRealm(object):
    implements(portal.IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        for iface in interfaces:
            if iface is pb.IPerspective:
                return iface, DummyPerspective(avatarId), lambda: None


class IOPump:
    """
    Utility to pump data between clients and servers for protocol testing.

    Perhaps this is a utility worthy of being in protocol.py?
    """
    def __init__(self, client, server, clientIO, serverIO):
        self.client = client
        self.server = server
        self.clientIO = clientIO
        self.serverIO = serverIO


    def flush(self):
        """
        Pump until there is no more input or output or until L{stop} is called.
        This does not run any timers, so don't use it with any code that calls
        reactor.callLater.
        """
        # failsafe timeout
        self._stop = False
        timeout = time.time() + 5
        while not self._stop and self.pump():
            if time.time() > timeout:
                return


    def stop(self):
        """
        Stop a running L{flush} operation, even if data remains to be
        transferred.
        """
        self._stop = True


    def pump(self):
        """
        Move data back and forth.

        Returns whether any data was moved.
        """
        self.clientIO.seek(0)
        self.serverIO.seek(0)
        cData = self.clientIO.read()
        sData = self.serverIO.read()
        self.clientIO.seek(0)
        self.serverIO.seek(0)
        self.clientIO.truncate()
        self.serverIO.truncate()
        self.client.transport._checkProducer()
        self.server.transport._checkProducer()
        for byte in cData:
            self.server.dataReceived(byte)
        for byte in sData:
            self.client.dataReceived(byte)
        if cData or sData:
            return 1
        else:
            return 0



def connectedServerAndClient(realm=None):
    """
    Connect a client and server L{Broker} together with an L{IOPump}

    @param realm: realm to use, defaulting to a L{DummyRealm}

    @returns: a 3-tuple (client, server, pump).
    """
    realm = realm or DummyRealm()
    clientBroker = pb.Broker()
    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(guest='guest')
    factory = pb.PBServerFactory(portal.Portal(realm, [checker]))
    serverBroker = factory.buildProtocol(('127.0.0.1',))

    clientTransport = StringIO()
    serverTransport = StringIO()
    clientBroker.makeConnection(protocol.FileWrapper(clientTransport))
    serverBroker.makeConnection(protocol.FileWrapper(serverTransport))
    pump = IOPump(clientBroker, serverBroker, clientTransport, serverTransport)
    # Challenge-response authentication:
    pump.flush()
    return clientBroker, serverBroker, pump


class SimpleRemote(pb.Referenceable):
    def remote_thunk(self, arg):
        self.arg = arg
        return arg + 1

    def remote_knuth(self, arg):
        raise Exception()


class NestedRemote(pb.Referenceable):
    def remote_getSimple(self):
        return SimpleRemote()


class SimpleCopy(pb.Copyable):
    def __init__(self):
        self.x = 1
        self.y = {"Hello":"World"}
        self.z = ['test']


class SimpleLocalCopy(pb.RemoteCopy):
    pass

pb.setUnjellyableForClass(SimpleCopy, SimpleLocalCopy)


class SimpleFactoryCopy(pb.Copyable):
    """
    @cvar allIDs: hold every created instances of this class.
    @type allIDs: C{dict}
    """
    allIDs = {}
    def __init__(self, id):
        self.id = id
        SimpleFactoryCopy.allIDs[id] = self


def createFactoryCopy(state):
    """
    Factory of L{SimpleFactoryCopy}, getting a created instance given the
    C{id} found in C{state}.
    """
    stateId = state.get("id", None)
    if stateId is None:
        raise RuntimeError("factory copy state has no 'id' member %s" %
                           (repr(state),))
    if not stateId in SimpleFactoryCopy.allIDs:
        raise RuntimeError("factory class has no ID: %s" %
                           (SimpleFactoryCopy.allIDs,))
    inst = SimpleFactoryCopy.allIDs[stateId]
    if not inst:
        raise RuntimeError("factory method found no object with id")
    return inst

pb.setUnjellyableFactoryForClass(SimpleFactoryCopy, createFactoryCopy)


class NestedCopy(pb.Referenceable):
    def remote_getCopy(self):
        return SimpleCopy()

    def remote_getFactory(self, value):
        return SimpleFactoryCopy(value)



class SimpleCache(pb.Cacheable):
    def __init___(self):
        self.x = 1
        self.y = {"Hello":"World"}
        self.z = ['test']


class NestedComplicatedCache(pb.Referenceable):
    def __init__(self):
        self.c = VeryVeryComplicatedCacheable()

    def remote_getCache(self):
        return self.c


class VeryVeryComplicatedCacheable(pb.Cacheable):
    def __init__(self):
        self.x = 1
        self.y = 2
        self.foo = 3

    def setFoo4(self):
        self.foo = 4
        self.observer.callRemote('foo',4)

    def getStateToCacheAndObserveFor(self, perspective, observer):
        self.observer = observer
        return {"x": self.x,
                "y": self.y,
                "foo": self.foo}

    def stoppedObserving(self, perspective, observer):
        log.msg("stopped observing")
        observer.callRemote("end")
        if observer == self.observer:
            self.observer = None


class RatherBaroqueCache(pb.RemoteCache):
    def observe_foo(self, newFoo):
        self.foo = newFoo

    def observe_end(self):
        log.msg("the end of things")

pb.setUnjellyableForClass(VeryVeryComplicatedCacheable, RatherBaroqueCache)


class SimpleLocalCache(pb.RemoteCache):
    def setCopyableState(self, state):
        self.__dict__.update(state)

    def checkMethod(self):
        return self.check

    def checkSelf(self):
        return self

    def check(self):
        return 1

pb.setUnjellyableForClass(SimpleCache, SimpleLocalCache)


class NestedCache(pb.Referenceable):
    def __init__(self):
        self.x = SimpleCache()

    def remote_getCache(self):
        return [self.x,self.x]

    def remote_putCache(self, cache):
        return (self.x is cache)


class Observable(pb.Referenceable):
    def __init__(self):
        self.observers = []

    def remote_observe(self, obs):
        self.observers.append(obs)

    def remote_unobserve(self, obs):
        self.observers.remove(obs)

    def notify(self, obj):
        for observer in self.observers:
            observer.callRemote('notify', self, obj)


class DeferredRemote(pb.Referenceable):
    def __init__(self):
        self.run = 0

    def runMe(self, arg):
        self.run = arg
        return arg + 1

    def dontRunMe(self, arg):
        assert 0, "shouldn't have been run!"

    def remote_doItLater(self):
        """
        Return a L{Deferred} to be fired on client side. When fired,
        C{self.runMe} is called.
        """
        d = Deferred()
        d.addCallbacks(self.runMe, self.dontRunMe)
        self.d = d
        return d


class Observer(pb.Referenceable):
    notified = 0
    obj = None
    def remote_notify(self, other, obj):
        self.obj = obj
        self.notified = self.notified + 1
        other.callRemote('unobserve',self)


class NewStyleCopy(pb.Copyable, pb.RemoteCopy, object):
    def __init__(self, s):
        self.s = s
pb.setUnjellyableForClass(NewStyleCopy, NewStyleCopy)


class NewStyleCopy2(pb.Copyable, pb.RemoteCopy, object):
    allocated = 0
    initialized = 0
    value = 1

    def __new__(self):
        NewStyleCopy2.allocated += 1
        inst = object.__new__(self)
        inst.value = 2
        return inst

    def __init__(self):
        NewStyleCopy2.initialized += 1

pb.setUnjellyableForClass(NewStyleCopy2, NewStyleCopy2)


class NewStyleCacheCopy(pb.Cacheable, pb.RemoteCache, object):
    def getStateToCacheAndObserveFor(self, perspective, observer):
        return self.__dict__

pb.setUnjellyableForClass(NewStyleCacheCopy, NewStyleCacheCopy)


class Echoer(pb.Root):
    def remote_echo(self, st):
        return st


class CachedReturner(pb.Root):
    def __init__(self, cache):
        self.cache = cache
    def remote_giveMeCache(self, st):
        return self.cache


class NewStyleTestCase(unittest.TestCase):
    def setUp(self):
        """
        Create a pb server using L{Echoer} protocol and connect a client to it.
        """
        self.serverFactory = pb.PBServerFactory(Echoer())
        self.wrapper = WrappingFactory(self.serverFactory)
        self.server = reactor.listenTCP(0, self.wrapper)
        clientFactory = pb.PBClientFactory()
        reactor.connectTCP("localhost", self.server.getHost().port,
                           clientFactory)
        def gotRoot(ref):
            self.ref = ref
        return clientFactory.getRootObject().addCallback(gotRoot)


    def tearDown(self):
        """
        Close client and server connections, reset values of L{NewStyleCopy2}
        class variables.
        """
        NewStyleCopy2.allocated = 0
        NewStyleCopy2.initialized = 0
        NewStyleCopy2.value = 1
        self.ref.broker.transport.loseConnection()
        # Disconnect any server-side connections too.
        for proto in self.wrapper.protocols:
            proto.transport.loseConnection()
        return self.server.stopListening()

    def test_newStyle(self):
        """
        Create a new style object, send it over the wire, and check the result.
        """
        orig = NewStyleCopy("value")
        d = self.ref.callRemote("echo", orig)
        def cb(res):
            self.failUnless(isinstance(res, NewStyleCopy))
            self.assertEqual(res.s, "value")
            self.failIf(res is orig) # no cheating :)
        d.addCallback(cb)
        return d

    def test_alloc(self):
        """
        Send a new style object and check the number of allocations.
        """
        orig = NewStyleCopy2()
        self.assertEqual(NewStyleCopy2.allocated, 1)
        self.assertEqual(NewStyleCopy2.initialized, 1)
        d = self.ref.callRemote("echo", orig)
        def cb(res):
            # receiving the response creates a third one on the way back
            self.failUnless(isinstance(res, NewStyleCopy2))
            self.assertEqual(res.value, 2)
            self.assertEqual(NewStyleCopy2.allocated, 3)
            self.assertEqual(NewStyleCopy2.initialized, 1)
            self.failIf(res is orig) # no cheating :)
        # sending the object creates a second one on the far side
        d.addCallback(cb)
        return d



class ConnectionNotifyServerFactory(pb.PBServerFactory):
    """
    A server factory which stores the last connection and fires a
    L{Deferred} on connection made. This factory can handle only one
    client connection.

    @ivar protocolInstance: the last protocol instance.
    @type protocolInstance: C{pb.Broker}

    @ivar connectionMade: the deferred fired upon connection.
    @type connectionMade: C{Deferred}
    """
    protocolInstance = None

    def __init__(self, root):
        """
        Initialize the factory.
        """
        pb.PBServerFactory.__init__(self, root)
        self.connectionMade = Deferred()


    def clientConnectionMade(self, protocol):
        """
        Store the protocol and fire the connection deferred.
        """
        self.protocolInstance = protocol
        d, self.connectionMade = self.connectionMade, None
        if d is not None:
            d.callback(None)



class NewStyleCachedTestCase(unittest.TestCase):
    def setUp(self):
        """
        Create a pb server using L{CachedReturner} protocol and connect a
        client to it.
        """
        self.orig = NewStyleCacheCopy()
        self.orig.s = "value"
        self.server = reactor.listenTCP(0,
            ConnectionNotifyServerFactory(CachedReturner(self.orig)))
        clientFactory = pb.PBClientFactory()
        reactor.connectTCP("localhost", self.server.getHost().port,
                           clientFactory)
        def gotRoot(ref):
            self.ref = ref
        d1 = clientFactory.getRootObject().addCallback(gotRoot)
        d2 = self.server.factory.connectionMade
        return gatherResults([d1, d2])


    def tearDown(self):
        """
        Close client and server connections.
        """
        self.server.factory.protocolInstance.transport.loseConnection()
        self.ref.broker.transport.loseConnection()
        return self.server.stopListening()


    def test_newStyleCache(self):
        """
        A new-style cacheable object can be retrieved and re-retrieved over a
        single connection.  The value of an attribute of the cacheable can be
        accessed on the receiving side.
        """
        d = self.ref.callRemote("giveMeCache", self.orig)
        def cb(res, again):
            self.assertIsInstance(res, NewStyleCacheCopy)
            self.assertEqual("value", res.s)
            # no cheating :)
            self.assertNotIdentical(self.orig, res)

            if again:
                # Save a reference so it stays alive for the rest of this test
                self.res = res
                # And ask for it again to exercise the special re-jelly logic in
                # Cacheable.
                return self.ref.callRemote("giveMeCache", self.orig)
        d.addCallback(cb, True)
        d.addCallback(cb, False)
        return d



class BrokerTestCase(unittest.TestCase):
    thunkResult = None

    def tearDown(self):
        try:
            # from RemotePublished.getFileName
            os.unlink('None-None-TESTING.pub')
        except OSError:
            pass

    def thunkErrorBad(self, error):
        self.fail("This should cause a return value, not %s" % (error,))

    def thunkResultGood(self, result):
        self.thunkResult = result

    def thunkErrorGood(self, tb):
        pass

    def thunkResultBad(self, result):
        self.fail("This should cause an error, not %s" % (result,))

    def test_reference(self):
        c, s, pump = connectedServerAndClient()

        class X(pb.Referenceable):
            def remote_catch(self,arg):
                self.caught = arg

        class Y(pb.Referenceable):
            def remote_throw(self, a, b):
                a.callRemote('catch', b)

        s.setNameForLocal("y", Y())
        y = c.remoteForName("y")
        x = X()
        z = X()
        y.callRemote('throw', x, z)
        pump.pump()
        pump.pump()
        pump.pump()
        self.assertIdentical(x.caught, z, "X should have caught Z")

        # make sure references to remote methods are equals
        self.assertEqual(y.remoteMethod('throw'), y.remoteMethod('throw'))

    def test_result(self):
        c, s, pump = connectedServerAndClient()
        for x, y in (c, s), (s, c):
            # test reflexivity
            foo = SimpleRemote()
            x.setNameForLocal("foo", foo)
            bar = y.remoteForName("foo")
            self.expectedThunkResult = 8
            bar.callRemote('thunk',self.expectedThunkResult - 1
                ).addCallbacks(self.thunkResultGood, self.thunkErrorBad)
            # Send question.
            pump.pump()
            # Send response.
            pump.pump()
            # Shouldn't require any more pumping than that...
            self.assertEqual(self.thunkResult, self.expectedThunkResult,
                              "result wasn't received.")

    def refcountResult(self, result):
        self.nestedRemote = result

    def test_tooManyRefs(self):
        l = []
        e = []
        c, s, pump = connectedServerAndClient()
        foo = NestedRemote()
        s.setNameForLocal("foo", foo)
        x = c.remoteForName("foo")
        for igno in xrange(pb.MAX_BROKER_REFS + 10):
            if s.transport.closed or c.transport.closed:
                break
            x.callRemote("getSimple").addCallbacks(l.append, e.append)
            pump.pump()
        expected = (pb.MAX_BROKER_REFS - 1)
        self.assertTrue(s.transport.closed, "transport was not closed")
        self.assertEqual(len(l), expected,
                          "expected %s got %s" % (expected, len(l)))

    def test_copy(self):
        c, s, pump = connectedServerAndClient()
        foo = NestedCopy()
        s.setNameForLocal("foo", foo)
        x = c.remoteForName("foo")
        x.callRemote('getCopy'
            ).addCallbacks(self.thunkResultGood, self.thunkErrorBad)
        pump.pump()
        pump.pump()
        self.assertEqual(self.thunkResult.x, 1)
        self.assertEqual(self.thunkResult.y['Hello'], 'World')
        self.assertEqual(self.thunkResult.z[0], 'test')

    def test_observe(self):
        c, s, pump = connectedServerAndClient()

        # this is really testing the comparison between remote objects, to make
        # sure that you can *UN*observe when you have an observer architecture.
        a = Observable()
        b = Observer()
        s.setNameForLocal("a", a)
        ra = c.remoteForName("a")
        ra.callRemote('observe',b)
        pump.pump()
        a.notify(1)
        pump.pump()
        pump.pump()
        a.notify(10)
        pump.pump()
        pump.pump()
        self.assertNotIdentical(b.obj, None, "didn't notify")
        self.assertEqual(b.obj, 1, 'notified too much')

    def test_defer(self):
        c, s, pump = connectedServerAndClient()
        d = DeferredRemote()
        s.setNameForLocal("d", d)
        e = c.remoteForName("d")
        pump.pump(); pump.pump()
        results = []
        e.callRemote('doItLater').addCallback(results.append)
        pump.pump(); pump.pump()
        self.assertFalse(d.run, "Deferred method run too early.")
        d.d.callback(5)
        self.assertEqual(d.run, 5, "Deferred method run too late.")
        pump.pump(); pump.pump()
        self.assertEqual(results[0], 6, "Incorrect result.")


    def test_refcount(self):
        c, s, pump = connectedServerAndClient()
        foo = NestedRemote()
        s.setNameForLocal("foo", foo)
        bar = c.remoteForName("foo")
        bar.callRemote('getSimple'
            ).addCallbacks(self.refcountResult, self.thunkErrorBad)

        # send question
        pump.pump()
        # send response
        pump.pump()

        # delving into internal structures here, because GC is sort of
        # inherently internal.
        rluid = self.nestedRemote.luid
        self.assertIn(rluid, s.localObjects)
        del self.nestedRemote
        # nudge the gc
        if sys.hexversion >= 0x2000000:
            gc.collect()
        # try to nudge the GC even if we can't really
        pump.pump()
        pump.pump()
        pump.pump()
        self.assertNotIn(rluid, s.localObjects)

    def test_cache(self):
        c, s, pump = connectedServerAndClient()
        obj = NestedCache()
        obj2 = NestedComplicatedCache()
        vcc = obj2.c
        s.setNameForLocal("obj", obj)
        s.setNameForLocal("xxx", obj2)
        o2 = c.remoteForName("obj")
        o3 = c.remoteForName("xxx")
        coll = []
        o2.callRemote("getCache"
            ).addCallback(coll.append).addErrback(coll.append)
        o2.callRemote("getCache"
            ).addCallback(coll.append).addErrback(coll.append)
        complex = []
        o3.callRemote("getCache").addCallback(complex.append)
        o3.callRemote("getCache").addCallback(complex.append)
        pump.flush()
        # `worst things first'
        self.assertEqual(complex[0].x, 1)
        self.assertEqual(complex[0].y, 2)
        self.assertEqual(complex[0].foo, 3)

        vcc.setFoo4()
        pump.flush()
        self.assertEqual(complex[0].foo, 4)
        self.assertEqual(len(coll), 2)
        cp = coll[0][0]
        self.assertIdentical(cp.checkMethod().im_self, cp,
                             "potential refcounting issue")
        self.assertIdentical(cp.checkSelf(), cp,
                             "other potential refcounting issue")
        col2 = []
        o2.callRemote('putCache',cp).addCallback(col2.append)
        pump.flush()
        # The objects were the same (testing lcache identity)
        self.assertTrue(col2[0])
        # test equality of references to methods
        self.assertEqual(o2.remoteMethod("getCache"),
                          o2.remoteMethod("getCache"))

        # now, refcounting (similiar to testRefCount)
        luid = cp.luid
        baroqueLuid = complex[0].luid
        self.assertIn(luid, s.remotelyCachedObjects,
                      "remote cache doesn't have it")
        del coll
        del cp
        pump.flush()
        del complex
        del col2
        # extra nudge...
        pump.flush()
        # del vcc.observer
        # nudge the gc
        if sys.hexversion >= 0x2000000:
            gc.collect()
        # try to nudge the GC even if we can't really
        pump.flush()
        # The GC is done with it.
        self.assertNotIn(luid, s.remotelyCachedObjects,
                         "Server still had it after GC")
        self.assertNotIn(luid, c.locallyCachedObjects,
                         "Client still had it after GC")
        self.assertNotIn(baroqueLuid, s.remotelyCachedObjects,
                         "Server still had complex after GC")
        self.assertNotIn(baroqueLuid, c.locallyCachedObjects,
                         "Client still had complex after GC")
        self.assertIdentical(vcc.observer, None, "observer was not removed")

    def test_publishable(self):
        try:
            os.unlink('None-None-TESTING.pub') # from RemotePublished.getFileName
        except OSError:
            pass # Sometimes it's not there.
        c, s, pump = connectedServerAndClient()
        foo = GetPublisher()
        # foo.pub.timestamp = 1.0
        s.setNameForLocal("foo", foo)
        bar = c.remoteForName("foo")
        accum = []
        bar.callRemote('getPub').addCallbacks(accum.append, self.thunkErrorBad)
        pump.flush()
        obj = accum.pop()
        self.assertEqual(obj.activateCalled, 1)
        self.assertEqual(obj.isActivated, 1)
        self.assertEqual(obj.yayIGotPublished, 1)
        # timestamp's dirty, we don't have a cache file
        self.assertEqual(obj._wasCleanWhenLoaded, 0)
        c, s, pump = connectedServerAndClient()
        s.setNameForLocal("foo", foo)
        bar = c.remoteForName("foo")
        bar.callRemote('getPub').addCallbacks(accum.append, self.thunkErrorBad)
        pump.flush()
        obj = accum.pop()
        # timestamp's clean, our cache file is up-to-date
        self.assertEqual(obj._wasCleanWhenLoaded, 1)

    def gotCopy(self, val):
        self.thunkResult = val.id


    def test_factoryCopy(self):
        c, s, pump = connectedServerAndClient()
        ID = 99
        obj = NestedCopy()
        s.setNameForLocal("foo", obj)
        x = c.remoteForName("foo")
        x.callRemote('getFactory', ID
            ).addCallbacks(self.gotCopy, self.thunkResultBad)
        pump.pump()
        pump.pump()
        pump.pump()
        self.assertEqual(self.thunkResult, ID,
            "ID not correct on factory object %s" % (self.thunkResult,))


bigString = "helloworld" * 50

callbackArgs = None
callbackKeyword = None

def finishedCallback(*args, **kw):
    global callbackArgs, callbackKeyword
    callbackArgs = args
    callbackKeyword = kw


class Pagerizer(pb.Referenceable):
    def __init__(self, callback, *args, **kw):
        self.callback, self.args, self.kw = callback, args, kw

    def remote_getPages(self, collector):
        util.StringPager(collector, bigString, 100,
                         self.callback, *self.args, **self.kw)
        self.args = self.kw = None


class FilePagerizer(pb.Referenceable):
    pager = None

    def __init__(self, filename, callback, *args, **kw):
        self.filename = filename
        self.callback, self.args, self.kw = callback, args, kw

    def remote_getPages(self, collector):
        self.pager = util.FilePager(collector, file(self.filename),
                                    self.callback, *self.args, **self.kw)
        self.args = self.kw = None



class PagingTestCase(unittest.TestCase):
    """
    Test pb objects sending data by pages.
    """

    def setUp(self):
        """
        Create a file used to test L{util.FilePager}.
        """
        self.filename = self.mktemp()
        fd = file(self.filename, 'w')
        fd.write(bigString)
        fd.close()


    def test_pagingWithCallback(self):
        """
        Test L{util.StringPager}, passing a callback to fire when all pages
        are sent.
        """
        c, s, pump = connectedServerAndClient()
        s.setNameForLocal("foo", Pagerizer(finishedCallback, 'hello', value=10))
        x = c.remoteForName("foo")
        l = []
        util.getAllPages(x, "getPages").addCallback(l.append)
        while not l:
            pump.pump()
        self.assertEqual(''.join(l[0]), bigString,
                          "Pages received not equal to pages sent!")
        self.assertEqual(callbackArgs, ('hello',),
                          "Completed callback not invoked")
        self.assertEqual(callbackKeyword, {'value': 10},
                          "Completed callback not invoked")


    def test_pagingWithoutCallback(self):
        """
        Test L{util.StringPager} without a callback.
        """
        c, s, pump = connectedServerAndClient()
        s.setNameForLocal("foo", Pagerizer(None))
        x = c.remoteForName("foo")
        l = []
        util.getAllPages(x, "getPages").addCallback(l.append)
        while not l:
            pump.pump()
        self.assertEqual(''.join(l[0]), bigString,
                          "Pages received not equal to pages sent!")


    def test_emptyFilePaging(self):
        """
        Test L{util.FilePager}, sending an empty file.
        """
        filenameEmpty = self.mktemp()
        fd = file(filenameEmpty, 'w')
        fd.close()
        c, s, pump = connectedServerAndClient()
        pagerizer = FilePagerizer(filenameEmpty, None)
        s.setNameForLocal("bar", pagerizer)
        x = c.remoteForName("bar")
        l = []
        util.getAllPages(x, "getPages").addCallback(l.append)
        ttl = 10
        while not l and ttl > 0:
            pump.pump()
            ttl -= 1
        if not ttl:
            self.fail('getAllPages timed out')
        self.assertEqual(''.join(l[0]), '',
                          "Pages received not equal to pages sent!")


    def test_filePagingWithCallback(self):
        """
        Test L{util.FilePager}, passing a callback to fire when all pages
        are sent, and verify that the pager doesn't keep chunks in memory.
        """
        c, s, pump = connectedServerAndClient()
        pagerizer = FilePagerizer(self.filename, finishedCallback,
                                  'frodo', value = 9)
        s.setNameForLocal("bar", pagerizer)
        x = c.remoteForName("bar")
        l = []
        util.getAllPages(x, "getPages").addCallback(l.append)
        while not l:
            pump.pump()
        self.assertEqual(''.join(l[0]), bigString,
                          "Pages received not equal to pages sent!")
        self.assertEqual(callbackArgs, ('frodo',),
                          "Completed callback not invoked")
        self.assertEqual(callbackKeyword, {'value': 9},
                          "Completed callback not invoked")
        self.assertEqual(pagerizer.pager.chunks, [])


    def test_filePagingWithoutCallback(self):
        """
        Test L{util.FilePager} without a callback.
        """
        c, s, pump = connectedServerAndClient()
        pagerizer = FilePagerizer(self.filename, None)
        s.setNameForLocal("bar", pagerizer)
        x = c.remoteForName("bar")
        l = []
        util.getAllPages(x, "getPages").addCallback(l.append)
        while not l:
            pump.pump()
        self.assertEqual(''.join(l[0]), bigString,
                          "Pages received not equal to pages sent!")
        self.assertEqual(pagerizer.pager.chunks, [])



class DumbPublishable(publish.Publishable):
    def getStateToPublish(self):
        return {"yayIGotPublished": 1}


class DumbPub(publish.RemotePublished):
    def activated(self):
        self.activateCalled = 1


class GetPublisher(pb.Referenceable):
    def __init__(self):
        self.pub = DumbPublishable("TESTING")

    def remote_getPub(self):
        return self.pub


pb.setUnjellyableForClass(DumbPublishable, DumbPub)

class DisconnectionTestCase(unittest.TestCase):
    """
    Test disconnection callbacks.
    """

    def error(self, *args):
        raise RuntimeError("I shouldn't have been called: %s" % (args,))


    def gotDisconnected(self):
        """
        Called on broker disconnect.
        """
        self.gotCallback = 1

    def objectDisconnected(self, o):
        """
        Called on RemoteReference disconnect.
        """
        self.assertEqual(o, self.remoteObject)
        self.objectCallback = 1

    def test_badSerialization(self):
        c, s, pump = connectedServerAndClient()
        pump.pump()
        s.setNameForLocal("o", BadCopySet())
        g = c.remoteForName("o")
        l = []
        g.callRemote("setBadCopy", BadCopyable()).addErrback(l.append)
        pump.flush()
        self.assertEqual(len(l), 1)

    def test_disconnection(self):
        c, s, pump = connectedServerAndClient()
        pump.pump()
        s.setNameForLocal("o", SimpleRemote())

        # get a client reference to server object
        r = c.remoteForName("o")
        pump.pump()
        pump.pump()
        pump.pump()

        # register and then unregister disconnect callbacks
        # making sure they get unregistered
        c.notifyOnDisconnect(self.error)
        self.assertIn(self.error, c.disconnects)
        c.dontNotifyOnDisconnect(self.error)
        self.assertNotIn(self.error, c.disconnects)

        r.notifyOnDisconnect(self.error)
        self.assertIn(r._disconnected, c.disconnects)
        self.assertIn(self.error, r.disconnectCallbacks)
        r.dontNotifyOnDisconnect(self.error)
        self.assertNotIn(r._disconnected, c.disconnects)
        self.assertNotIn(self.error, r.disconnectCallbacks)

        # register disconnect callbacks
        c.notifyOnDisconnect(self.gotDisconnected)
        r.notifyOnDisconnect(self.objectDisconnected)
        self.remoteObject = r

        # disconnect
        c.connectionLost(failure.Failure(main.CONNECTION_DONE))
        self.assertTrue(self.gotCallback)
        self.assertTrue(self.objectCallback)


class FreakOut(Exception):
    pass


class BadCopyable(pb.Copyable):
    def getStateToCopyFor(self, p):
        raise FreakOut()


class BadCopySet(pb.Referenceable):
    def remote_setBadCopy(self, bc):
        return None


class LocalRemoteTest(util.LocalAsRemote):
    reportAllTracebacks = 0

    def sync_add1(self, x):
        return x + 1

    def async_add(self, x=0, y=1):
        return x + y

    def async_fail(self):
        raise RuntimeError()



class MyPerspective(pb.Avatar):
    """
    @ivar loggedIn: set to C{True} when the avatar is logged in.
    @type loggedIn: C{bool}

    @ivar loggedOut: set to C{True} when the avatar is logged out.
    @type loggedOut: C{bool}
    """
    implements(pb.IPerspective)

    loggedIn = loggedOut = False

    def __init__(self, avatarId):
        self.avatarId = avatarId


    def perspective_getAvatarId(self):
        """
        Return the avatar identifier which was used to access this avatar.
        """
        return self.avatarId


    def perspective_getViewPoint(self):
        return MyView()


    def perspective_add(self, a, b):
        """
        Add the given objects and return the result.  This is a method
        unavailable on L{Echoer}, so it can only be invoked by authenticated
        users who received their avatar from L{TestRealm}.
        """
        return a + b


    def logout(self):
        self.loggedOut = True



class TestRealm(object):
    """
    A realm which repeatedly gives out a single instance of L{MyPerspective}
    for non-anonymous logins and which gives out a new instance of L{Echoer}
    for each anonymous login.

    @ivar lastPerspective: The L{MyPerspective} most recently created and
        returned from C{requestAvatar}.

    @ivar perspectiveFactory: A one-argument callable which will be used to
        create avatars to be returned from C{requestAvatar}.
    """
    perspectiveFactory = MyPerspective

    lastPerspective = None

    def requestAvatar(self, avatarId, mind, interface):
        """
        Verify that the mind and interface supplied have the expected values
        (this should really be done somewhere else, like inside a test method)
        and return an avatar appropriate for the given identifier.
        """
        assert interface == pb.IPerspective
        assert mind == "BRAINS!"
        if avatarId is checkers.ANONYMOUS:
            return pb.IPerspective, Echoer(), lambda: None
        else:
            self.lastPerspective = self.perspectiveFactory(avatarId)
            self.lastPerspective.loggedIn = True
            return (
                pb.IPerspective, self.lastPerspective,
                self.lastPerspective.logout)



class MyView(pb.Viewable):

    def view_check(self, user):
        return isinstance(user, MyPerspective)



class LeakyRealm(TestRealm):
    """
    A realm which hangs onto a reference to the mind object in its logout
    function.
    """
    def __init__(self, mindEater):
        """
        Create a L{LeakyRealm}.

        @param mindEater: a callable that will be called with the C{mind}
        object when it is available
        """
        self._mindEater = mindEater


    def requestAvatar(self, avatarId, mind, interface):
        self._mindEater(mind)
        persp = self.perspectiveFactory(avatarId)
        return (pb.IPerspective, persp, lambda : (mind, persp.logout()))



class NewCredLeakTests(unittest.TestCase):
    """
    Tests to try to trigger memory leaks.
    """
    def test_logoutLeak(self):
        """
        The server does not leak a reference when the client disconnects
        suddenly, even if the cred logout function forms a reference cycle with
        the perspective.
        """
        # keep a weak reference to the mind object, which we can verify later
        # evaluates to None, thereby ensuring the reference leak is fixed.
        self.mindRef = None
        def setMindRef(mind):
            self.mindRef = weakref.ref(mind)

        clientBroker, serverBroker, pump = connectedServerAndClient(
                LeakyRealm(setMindRef))

        # log in from the client
        connectionBroken = []
        root = clientBroker.remoteForName("root")
        d = root.callRemote("login", 'guest')
        def cbResponse((challenge, challenger)):
            mind = SimpleRemote()
            return challenger.callRemote("respond",
                    pb.respond(challenge, 'guest'), mind)
        d.addCallback(cbResponse)
        def connectionLost(_):
            pump.stop() # don't try to pump data anymore - it won't work
            connectionBroken.append(1)
            serverBroker.connectionLost(failure.Failure(RuntimeError("boom")))
        d.addCallback(connectionLost)

        # flush out the response and connectionLost
        pump.flush()
        self.assertEqual(connectionBroken, [1])

        # and check for lingering references - requestAvatar sets mindRef
        # to a weakref to the mind; this object should be gc'd, and thus
        # the ref should return None
        gc.collect()
        self.assertEqual(self.mindRef(), None)



class NewCredTestCase(unittest.TestCase):
    """
    Tests related to the L{twisted.cred} support in PB.
    """
    def setUp(self):
        """
        Create a portal with no checkers and wrap it around a simple test
        realm.  Set up a PB server on a TCP port which serves perspectives
        using that portal.
        """
        self.realm = TestRealm()
        self.portal = portal.Portal(self.realm)
        self.factory = ConnectionNotifyServerFactory(self.portal)
        self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
        self.portno = self.port.getHost().port


    def tearDown(self):
        """
        Shut down the TCP port created by L{setUp}.
        """
        return self.port.stopListening()


    def getFactoryAndRootObject(self, clientFactory=pb.PBClientFactory):
        """
        Create a connection to the test server.

        @param clientFactory: the factory class used to create the connection.

        @return: a tuple (C{factory}, C{deferred}), where factory is an
            instance of C{clientFactory} and C{deferred} the L{Deferred} firing
            with the PB root object.
        """
        factory = clientFactory()
        rootObjDeferred = factory.getRootObject()
        connector = reactor.connectTCP('127.0.0.1', self.portno, factory)
        self.addCleanup(connector.disconnect)
        return factory, rootObjDeferred


    def test_getRootObject(self):
        """
        Assert only that L{PBClientFactory.getRootObject}'s Deferred fires with
        a L{RemoteReference}.
        """
        factory, rootObjDeferred = self.getFactoryAndRootObject()

        def gotRootObject(rootObj):
            self.assertIsInstance(rootObj, pb.RemoteReference)
            disconnectedDeferred = Deferred()
            rootObj.notifyOnDisconnect(disconnectedDeferred.callback)
            factory.disconnect()
            return disconnectedDeferred

        return rootObjDeferred.addCallback(gotRootObject)


    def test_deadReferenceError(self):
        """
        Test that when a connection is lost, calling a method on a
        RemoteReference obtained from it raises DeadReferenceError.
        """
        factory, rootObjDeferred = self.getFactoryAndRootObject()

        def gotRootObject(rootObj):
            disconnectedDeferred = Deferred()
            rootObj.notifyOnDisconnect(disconnectedDeferred.callback)

            def lostConnection(ign):
                self.assertRaises(
                    pb.DeadReferenceError,
                    rootObj.callRemote, 'method')

            disconnectedDeferred.addCallback(lostConnection)
            factory.disconnect()
            return disconnectedDeferred

        return rootObjDeferred.addCallback(gotRootObject)


    def test_clientConnectionLost(self):
        """
        Test that if the L{reconnecting} flag is passed with a True value then
        a remote call made from a disconnection notification callback gets a
        result successfully.
        """
        class ReconnectOnce(pb.PBClientFactory):
            reconnectedAlready = False
            def clientConnectionLost(self, connector, reason):
                reconnecting = not self.reconnectedAlready
                self.reconnectedAlready = True
                if reconnecting:
                    connector.connect()
                return pb.PBClientFactory.clientConnectionLost(
                    self, connector, reason, reconnecting)

        factory, rootObjDeferred = self.getFactoryAndRootObject(ReconnectOnce)

        def gotRootObject(rootObj):
            self.assertIsInstance(rootObj, pb.RemoteReference)

            d = Deferred()
            rootObj.notifyOnDisconnect(d.callback)
            factory.disconnect()

            def disconnected(ign):
                d = factory.getRootObject()

                def gotAnotherRootObject(anotherRootObj):
                    self.assertIsInstance(anotherRootObj, pb.RemoteReference)

                    d = Deferred()
                    anotherRootObj.notifyOnDisconnect(d.callback)
                    factory.disconnect()
                    return d
                return d.addCallback(gotAnotherRootObject)
            return d.addCallback(disconnected)
        return rootObjDeferred.addCallback(gotRootObject)


    def test_immediateClose(self):
        """
        Test that if a Broker loses its connection without receiving any bytes,
        it doesn't raise any exceptions or log any errors.
        """
        serverProto = self.factory.buildProtocol(('127.0.0.1', 12345))
        serverProto.makeConnection(protocol.FileWrapper(StringIO()))
        serverProto.connectionLost(failure.Failure(main.CONNECTION_DONE))


    def test_loginConnectionRefused(self):
        """
        L{PBClientFactory.login} returns a L{Deferred} which is errbacked
        with the L{ConnectionRefusedError} if the underlying connection is
        refused.
        """
        clientFactory = pb.PBClientFactory()
        loginDeferred = clientFactory.login(
            credentials.UsernamePassword("foo", "bar"))
        clientFactory.clientConnectionFailed(
            None,
            failure.Failure(
                ConnectionRefusedError("Test simulated refused connection")))
        return self.assertFailure(loginDeferred, ConnectionRefusedError)


    def _disconnect(self, ignore, factory):
        """
        Helper method disconnecting the given client factory and returning a
        C{Deferred} that will fire when the server connection has noticed the
        disconnection.
        """
        disconnectedDeferred = Deferred()
        self.factory.protocolInstance.notifyOnDisconnect(
            lambda: disconnectedDeferred.callback(None))
        factory.disconnect()
        return disconnectedDeferred


    def test_loginLogout(self):
        """
        Test that login can be performed with IUsernamePassword credentials and
        that when the connection is dropped the avatar is logged out.
        """
        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
        factory = pb.PBClientFactory()
        creds = credentials.UsernamePassword("user", "pass")

        # NOTE: real code probably won't need anything where we have the
        # "BRAINS!" argument, passing None is fine. We just do it here to
        # test that it is being passed. It is used to give additional info to
        # the realm to aid perspective creation, if you don't need that,
        # ignore it.
        mind = "BRAINS!"

        d = factory.login(creds, mind)
        def cbLogin(perspective):
            self.assertTrue(self.realm.lastPerspective.loggedIn)
            self.assertIsInstance(perspective, pb.RemoteReference)
            return self._disconnect(None, factory)
        d.addCallback(cbLogin)

        def cbLogout(ignored):
            self.assertTrue(self.realm.lastPerspective.loggedOut)
        d.addCallback(cbLogout)

        connector = reactor.connectTCP("127.0.0.1", self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_logoutAfterDecref(self):
        """
        If a L{RemoteReference} to an L{IPerspective} avatar is decrefed and
        there remain no other references to the avatar on the server, the
        avatar is garbage collected and the logout method called.
        """
        loggedOut = Deferred()

        class EventPerspective(pb.Avatar):
            """
            An avatar which fires a Deferred when it is logged out.
            """
            def __init__(self, avatarId):
                pass

            def logout(self):
                loggedOut.callback(None)

        self.realm.perspectiveFactory = EventPerspective

        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(foo='bar'))
        factory = pb.PBClientFactory()
        d = factory.login(
            credentials.UsernamePassword('foo', 'bar'), "BRAINS!")
        def cbLoggedIn(avatar):
            # Just wait for the logout to happen, as it should since the
            # reference to the avatar will shortly no longer exists.
            return loggedOut
        d.addCallback(cbLoggedIn)
        def cbLoggedOut(ignored):
            # Verify that the server broker's _localCleanup dict isn't growing
            # without bound.
            self.assertEqual(self.factory.protocolInstance._localCleanup, {})
        d.addCallback(cbLoggedOut)
        d.addCallback(self._disconnect, factory)
        connector = reactor.connectTCP("127.0.0.1", self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_concurrentLogin(self):
        """
        Two different correct login attempts can be made on the same root
        object at the same time and produce two different resulting avatars.
        """
        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(
                foo='bar', baz='quux'))
        factory = pb.PBClientFactory()

        firstLogin = factory.login(
            credentials.UsernamePassword('foo', 'bar'), "BRAINS!")
        secondLogin = factory.login(
            credentials.UsernamePassword('baz', 'quux'), "BRAINS!")
        d = gatherResults([firstLogin, secondLogin])
        def cbLoggedIn((first, second)):
            return gatherResults([
                    first.callRemote('getAvatarId'),
                    second.callRemote('getAvatarId')])
        d.addCallback(cbLoggedIn)
        def cbAvatarIds((first, second)):
            self.assertEqual(first, 'foo')
            self.assertEqual(second, 'baz')
        d.addCallback(cbAvatarIds)
        d.addCallback(self._disconnect, factory)

        connector = reactor.connectTCP('127.0.0.1', self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_badUsernamePasswordLogin(self):
        """
        Test that a login attempt with an invalid user or invalid password
        fails in the appropriate way.
        """
        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
        factory = pb.PBClientFactory()

        firstLogin = factory.login(
            credentials.UsernamePassword('nosuchuser', 'pass'))
        secondLogin = factory.login(
            credentials.UsernamePassword('user', 'wrongpass'))

        self.assertFailure(firstLogin, UnauthorizedLogin)
        self.assertFailure(secondLogin, UnauthorizedLogin)
        d = gatherResults([firstLogin, secondLogin])

        def cleanup(ignore):
            errors = self.flushLoggedErrors(UnauthorizedLogin)
            self.assertEqual(len(errors), 2)
            return self._disconnect(None, factory)
        d.addCallback(cleanup)

        connector = reactor.connectTCP("127.0.0.1", self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_anonymousLogin(self):
        """
        Verify that a PB server using a portal configured with an checker which
        allows IAnonymous credentials can be logged into using IAnonymous
        credentials.
        """
        self.portal.registerChecker(checkers.AllowAnonymousAccess())
        factory = pb.PBClientFactory()
        d = factory.login(credentials.Anonymous(), "BRAINS!")

        def cbLoggedIn(perspective):
            return perspective.callRemote('echo', 123)
        d.addCallback(cbLoggedIn)

        d.addCallback(self.assertEqual, 123)

        d.addCallback(self._disconnect, factory)

        connector = reactor.connectTCP("127.0.0.1", self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_anonymousLoginNotPermitted(self):
        """
        Verify that without an anonymous checker set up, anonymous login is
        rejected.
        """
        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
        factory = pb.PBClientFactory()
        d = factory.login(credentials.Anonymous(), "BRAINS!")
        self.assertFailure(d, UnhandledCredentials)

        def cleanup(ignore):
            errors = self.flushLoggedErrors(UnhandledCredentials)
            self.assertEqual(len(errors), 1)
            return self._disconnect(None, factory)
        d.addCallback(cleanup)

        connector = reactor.connectTCP('127.0.0.1', self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_anonymousLoginWithMultipleCheckers(self):
        """
        Like L{test_anonymousLogin} but against a portal with a checker for
        both IAnonymous and IUsernamePassword.
        """
        self.portal.registerChecker(checkers.AllowAnonymousAccess())
        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
        factory = pb.PBClientFactory()
        d = factory.login(credentials.Anonymous(), "BRAINS!")

        def cbLogin(perspective):
            return perspective.callRemote('echo', 123)
        d.addCallback(cbLogin)

        d.addCallback(self.assertEqual, 123)

        d.addCallback(self._disconnect, factory)

        connector = reactor.connectTCP('127.0.0.1', self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_authenticatedLoginWithMultipleCheckers(self):
        """
        Like L{test_anonymousLoginWithMultipleCheckers} but check that
        username/password authentication works.
        """
        self.portal.registerChecker(checkers.AllowAnonymousAccess())
        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
        factory = pb.PBClientFactory()
        d = factory.login(
            credentials.UsernamePassword('user', 'pass'), "BRAINS!")

        def cbLogin(perspective):
            return perspective.callRemote('add', 100, 23)
        d.addCallback(cbLogin)

        d.addCallback(self.assertEqual, 123)

        d.addCallback(self._disconnect, factory)

        connector = reactor.connectTCP('127.0.0.1', self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d


    def test_view(self):
        """
        Verify that a viewpoint can be retrieved after authenticating with
        cred.
        """
        self.portal.registerChecker(
            checkers.InMemoryUsernamePasswordDatabaseDontUse(user='pass'))
        factory = pb.PBClientFactory()
        d = factory.login(
            credentials.UsernamePassword("user", "pass"), "BRAINS!")

        def cbLogin(perspective):
            return perspective.callRemote("getViewPoint")
        d.addCallback(cbLogin)

        def cbView(viewpoint):
            return viewpoint.callRemote("check")
        d.addCallback(cbView)

        d.addCallback(self.assertTrue)

        d.addCallback(self._disconnect, factory)

        connector = reactor.connectTCP("127.0.0.1", self.portno, factory)
        self.addCleanup(connector.disconnect)
        return d



class NonSubclassingPerspective:
    implements(pb.IPerspective)

    def __init__(self, avatarId):
        pass

    # IPerspective implementation
    def perspectiveMessageReceived(self, broker, message, args, kwargs):
        args = broker.unserialize(args, self)
        kwargs = broker.unserialize(kwargs, self)
        return broker.serialize((message, args, kwargs))

    # Methods required by TestRealm
    def logout(self):
        self.loggedOut = True



class NSPTestCase(unittest.TestCase):
    """
    Tests for authentication against a realm where the L{IPerspective}
    implementation is not a subclass of L{Avatar}.
    """
    def setUp(self):
        self.realm = TestRealm()
        self.realm.perspectiveFactory = NonSubclassingPerspective
        self.portal = portal.Portal(self.realm)
        self.checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser("user", "pass")
        self.portal.registerChecker(self.checker)
        self.factory = WrappingFactory(pb.PBServerFactory(self.portal))
        self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1")
        self.addCleanup(self.port.stopListening)
        self.portno = self.port.getHost().port


    def test_NSP(self):
        """
        An L{IPerspective} implementation which does not subclass
        L{Avatar} can expose remote methods for the client to call.
        """
        factory = pb.PBClientFactory()
        d = factory.login(credentials.UsernamePassword('user', 'pass'),
                          "BRAINS!")
        reactor.connectTCP('127.0.0.1', self.portno, factory)
        d.addCallback(lambda p: p.callRemote('ANYTHING', 'here', bar='baz'))
        d.addCallback(self.assertEqual,
                      ('ANYTHING', ('here',), {'bar': 'baz'}))
        def cleanup(ignored):
            factory.disconnect()
            for p in self.factory.protocols:
                p.transport.loseConnection()
        d.addCallback(cleanup)
        return d



class IForwarded(Interface):
    """
    Interface used for testing L{util.LocalAsyncForwarder}.
    """

    def forwardMe():
        """
        Simple synchronous method.
        """

    def forwardDeferred():
        """
        Simple asynchronous method.
        """


class Forwarded:
    """
    Test implementation of L{IForwarded}.

    @ivar forwarded: set if C{forwardMe} is called.
    @type forwarded: C{bool}
    @ivar unforwarded: set if C{dontForwardMe} is called.
    @type unforwarded: C{bool}
    """
    implements(IForwarded)
    forwarded = False
    unforwarded = False

    def forwardMe(self):
        """
        Set a local flag to test afterwards.
        """
        self.forwarded = True

    def dontForwardMe(self):
        """
        Set a local flag to test afterwards. This should not be called as it's
        not in the interface.
        """
        self.unforwarded = True

    def forwardDeferred(self):
        """
        Asynchronously return C{True}.
        """
        return succeed(True)


class SpreadUtilTestCase(unittest.TestCase):
    """
    Tests for L{twisted.spread.util}.
    """

    def test_sync(self):
        """
        Call a synchronous method of a L{util.LocalAsRemote} object and check
        the result.
        """
        o = LocalRemoteTest()
        self.assertEqual(o.callRemote("add1", 2), 3)

    def test_async(self):
        """
        Call an asynchronous method of a L{util.LocalAsRemote} object and check
        the result.
        """
        o = LocalRemoteTest()
        o = LocalRemoteTest()
        d = o.callRemote("add", 2, y=4)
        self.assertIsInstance(d, Deferred)
        d.addCallback(self.assertEqual, 6)
        return d

    def test_asyncFail(self):
        """
        Test a asynchronous failure on a remote method call.
        """
        o = LocalRemoteTest()
        d = o.callRemote("fail")
        def eb(f):
            self.assertTrue(isinstance(f, failure.Failure))
            f.trap(RuntimeError)
        d.addCallbacks(lambda res: self.fail("supposed to fail"), eb)
        return d

    def test_remoteMethod(self):
        """
        Test the C{remoteMethod} facility of L{util.LocalAsRemote}.
        """
        o = LocalRemoteTest()
        m = o.remoteMethod("add1")
        self.assertEqual(m(3), 4)

    def test_localAsyncForwarder(self):
        """
        Test a call to L{util.LocalAsyncForwarder} using L{Forwarded} local
        object.
        """
        f = Forwarded()
        lf = util.LocalAsyncForwarder(f, IForwarded)
        lf.callRemote("forwardMe")
        self.assertTrue(f.forwarded)
        lf.callRemote("dontForwardMe")
        self.assertFalse(f.unforwarded)
        rr = lf.callRemote("forwardDeferred")
        l = []
        rr.addCallback(l.append)
        self.assertEqual(l[0], 1)



class PBWithSecurityOptionsTest(unittest.TestCase):
    """
    Test security customization.
    """

    def test_clientDefaultSecurityOptions(self):
        """
        By default, client broker should use C{jelly.globalSecurity} as
        security settings.
        """
        factory = pb.PBClientFactory()
        broker = factory.buildProtocol(None)
        self.assertIdentical(broker.security, jelly.globalSecurity)


    def test_serverDefaultSecurityOptions(self):
        """
        By default, server broker should use C{jelly.globalSecurity} as
        security settings.
        """
        factory = pb.PBServerFactory(Echoer())
        broker = factory.buildProtocol(None)
        self.assertIdentical(broker.security, jelly.globalSecurity)


    def test_clientSecurityCustomization(self):
        """
        Check that the security settings are passed from the client factory to
        the broker object.
        """
        security = jelly.SecurityOptions()
        factory = pb.PBClientFactory(security=security)
        broker = factory.buildProtocol(None)
        self.assertIdentical(broker.security, security)


    def test_serverSecurityCustomization(self):
        """
        Check that the security settings are passed from the server factory to
        the broker object.
        """
        security = jelly.SecurityOptions()
        factory = pb.PBServerFactory(Echoer(), security=security)
        broker = factory.buildProtocol(None)
        self.assertIdentical(broker.security, security)