aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/internet/test/test_tcp.py
blob: 862cc25b4697e86ecd583f898d6195a29e41f80d (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
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for implementations of L{IReactorTCP} and the TCP parts of
L{IReactorSocket}.
"""

__metaclass__ = type

import socket, errno

from zope.interface import implements

from twisted.python.runtime import platform
from twisted.python.failure import Failure
from twisted.python import log

from twisted.trial.unittest import SkipTest, TestCase
from twisted.internet.test.reactormixins import ReactorBuilder, EndpointCreator
from twisted.internet.test.reactormixins import ConnectableProtocol
from twisted.internet.test.reactormixins import runProtocolsWithReactor
from twisted.internet.error import (
    ConnectionLost, UserError, ConnectionRefusedError, ConnectionDone,
    ConnectionAborted)
from twisted.internet.interfaces import (
    ILoggingContext, IConnector, IReactorFDSet, IReactorSocket, IReactorTCP)
from twisted.internet.address import IPv4Address, IPv6Address
from twisted.internet.defer import (
    Deferred, DeferredList, maybeDeferred, gatherResults)
from twisted.internet.endpoints import (
    TCP4ServerEndpoint, TCP4ClientEndpoint)
from twisted.internet.protocol import ServerFactory, ClientFactory, Protocol
from twisted.internet.interfaces import (
    IPushProducer, IPullProducer, IHalfCloseableProtocol)
from twisted.internet.tcp import Connection, Server, _resolveIPv6

from twisted.internet.test.connectionmixins import (
    LogObserverMixin, ConnectionTestsMixin, TCPClientTestsMixin, findFreePort)
from twisted.internet.test.test_core import ObjectModelIntegrationMixin
from twisted.test.test_tcp import MyClientFactory, MyServerFactory
from twisted.test.test_tcp import ClosingFactory, ClientStartStopFactory

try:
    from OpenSSL import SSL
except ImportError:
    useSSL = False
else:
    from twisted.internet.ssl import ClientContextFactory
    useSSL = True

try:
    socket.socket(socket.AF_INET6, socket.SOCK_STREAM).close()
except socket.error, e:
    ipv6Skip = str(e)
else:
    ipv6Skip = None



if platform.isWindows():
    from twisted.internet.test import _win32ifaces
    getLinkLocalIPv6Addresses = _win32ifaces.win32GetLinkLocalIPv6Addresses
else:
    try:
        from twisted.internet.test import _posixifaces
    except ImportError:
        getLinkLocalIPv6Addresses = lambda: []
    else:
        getLinkLocalIPv6Addresses = _posixifaces.posixGetLinkLocalIPv6Addresses



def getLinkLocalIPv6Address():
    """
    Find and return a configured link local IPv6 address including a scope
    identifier using the % separation syntax.  If the system has no link local
    IPv6 addresses, raise L{SkipTest} instead.

    @raise SkipTest: if no link local address can be found or if the
        C{netifaces} module is not available.

    @return: a C{str} giving the address
    """
    addresses = getLinkLocalIPv6Addresses()
    if addresses:
        return addresses[0]
    raise SkipTest("Link local IPv6 address unavailable")



def connect(client, (host, port)):
    if '%' in host or ':' in host:
        address = socket.getaddrinfo(host, port)[0][4]
    else:
        address = (host, port)
    client.connect(address)



class FakeSocket(object):
    """
    A fake for L{socket.socket} objects.

    @ivar data: A C{str} giving the data which will be returned from
        L{FakeSocket.recv}.

    @ivar sendBuffer: A C{list} of the objects passed to L{FakeSocket.send}.
    """
    def __init__(self, data):
        self.data = data
        self.sendBuffer = []

    def setblocking(self, blocking):
        self.blocking = blocking

    def recv(self, size):
        return self.data

    def send(self, bytes):
        """
        I{Send} all of C{bytes} by accumulating it into C{self.sendBuffer}.

        @return: The length of C{bytes}, indicating all the data has been
            accepted.
        """
        self.sendBuffer.append(bytes)
        return len(bytes)


    def shutdown(self, how):
        """
        Shutdown is not implemented.  The method is provided since real sockets
        have it and some code expects it.  No behavior of L{FakeSocket} is
        affected by a call to it.
        """


    def close(self):
        """
        Close is not implemented.  The method is provided since real sockets
        have it and some code expects it.  No behavior of L{FakeSocket} is
        affected by a call to it.
        """


    def setsockopt(self, *args):
        """
        Setsockopt is not implemented.  The method is provided since
        real sockets have it and some code expects it.  No behavior of
        L{FakeSocket} is affected by a call to it.
        """


    def fileno(self):
        """
        Return a fake file descriptor.  If actually used, this will have no
        connection to this L{FakeSocket} and will probably cause surprising
        results.
        """
        return 1



class TestFakeSocket(TestCase):
    """
    Test that the FakeSocket can be used by the doRead method of L{Connection}
    """

    def test_blocking(self):
        skt = FakeSocket("someData")
        skt.setblocking(0)
        self.assertEqual(skt.blocking, 0)


    def test_recv(self):
        skt = FakeSocket("someData")
        self.assertEqual(skt.recv(10), "someData")


    def test_send(self):
        """
        L{FakeSocket.send} accepts the entire string passed to it, adds it to
        its send buffer, and returns its length.
        """
        skt = FakeSocket("")
        count = skt.send("foo")
        self.assertEqual(count, 3)
        self.assertEqual(skt.sendBuffer, ["foo"])



class FakeProtocol(Protocol):
    """
    An L{IProtocol} that returns a value from its dataReceived method.
    """
    def dataReceived(self, data):
        """
        Return something other than C{None} to trigger a deprecation warning for
        that behavior.
        """
        return ()



class _FakeFDSetReactor(object):
    """
    A no-op implementation of L{IReactorFDSet}, which ignores all adds and
    removes.
    """
    implements(IReactorFDSet)

    addReader = addWriter = removeReader = removeWriter = (
        lambda self, desc: None)



class TCPServerTests(TestCase):
    """
    Whitebox tests for L{twisted.internet.tcp.Server}.
    """
    def setUp(self):
        self.reactor = _FakeFDSetReactor()
        class FakePort(object):
            _realPortNumber = 3
        self.skt = FakeSocket("")
        self.protocol = Protocol()
        self.server = Server(
            self.skt, self.protocol, ("", 0), FakePort(), None, self.reactor)


    def test_writeAfterDisconnect(self):
        """
        L{Server.write} discards bytes passed to it if called after it has lost
        its connection.
        """
        self.server.connectionLost(
            Failure(Exception("Simulated lost connection")))
        self.server.write("hello world")
        self.assertEqual(self.skt.sendBuffer, [])


    def test_writeAfteDisconnectAfterTLS(self):
        """
        L{Server.write} discards bytes passed to it if called after it has lost
        its connection when the connection had started TLS.
        """
        self.server.TLS = True
        self.test_writeAfterDisconnect()


    def test_writeSequenceAfterDisconnect(self):
        """
        L{Server.writeSequence} discards bytes passed to it if called after it
        has lost its connection.
        """
        self.server.connectionLost(
            Failure(Exception("Simulated lost connection")))
        self.server.writeSequence(["hello world"])
        self.assertEqual(self.skt.sendBuffer, [])


    def test_writeSequenceAfteDisconnectAfterTLS(self):
        """
        L{Server.writeSequence} discards bytes passed to it if called after it
        has lost its connection when the connection had started TLS.
        """
        self.server.TLS = True
        self.test_writeSequenceAfterDisconnect()



class TCPConnectionTests(TestCase):
    """
    Whitebox tests for L{twisted.internet.tcp.Connection}.
    """
    def test_doReadWarningIsRaised(self):
        """
        When an L{IProtocol} implementation that returns a value from its
        C{dataReceived} method, a deprecated warning is emitted.
        """
        skt = FakeSocket("someData")
        protocol = FakeProtocol()
        conn = Connection(skt, protocol)
        conn.doRead()
        warnings = self.flushWarnings([FakeProtocol.dataReceived])
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]["message"],
            "Returning a value other than None from "
            "twisted.internet.test.test_tcp.FakeProtocol.dataReceived "
            "is deprecated since Twisted 11.0.0.")
        self.assertEqual(len(warnings), 1)


    def test_noTLSBeforeStartTLS(self):
        """
        The C{TLS} attribute of a L{Connection} instance is C{False} before
        L{Connection.startTLS} is called.
        """
        skt = FakeSocket("")
        protocol = FakeProtocol()
        conn = Connection(skt, protocol)
        self.assertFalse(conn.TLS)


    def test_tlsAfterStartTLS(self):
        """
        The C{TLS} attribute of a L{Connection} instance is C{True} after
        L{Connection.startTLS} is called.
        """
        skt = FakeSocket("")
        protocol = FakeProtocol()
        conn = Connection(skt, protocol, reactor=_FakeFDSetReactor())
        conn._tlsClientDefault = True
        conn.startTLS(ClientContextFactory(), True)
        self.assertTrue(conn.TLS)
    if not useSSL:
        test_tlsAfterStartTLS.skip = "No SSL support available"



class TCPCreator(EndpointCreator):
    """
    Create IPv4 TCP endpoints for L{runProtocolsWithReactor}-based tests.
    """

    interface = "127.0.0.1"

    def server(self, reactor):
        """
        Create a server-side TCP endpoint.
        """
        return TCP4ServerEndpoint(reactor, 0, interface=self.interface)


    def client(self, reactor, serverAddress):
        """
        Create a client end point that will connect to the given address.

        @type serverAddress: L{IPv4Address}
        """
        return TCP4ClientEndpoint(reactor, self.interface, serverAddress.port)



class TCP6Creator(TCPCreator):
    """
    Create IPv6 TCP endpoints for
    C{ReactorBuilder.runProtocolsWithReactor}-based tests.

    The endpoint types in question here are still the TCP4 variety, since
    these simply pass through IPv6 address literals to the reactor, and we are
    only testing address literals, not name resolution (as name resolution has
    not yet been implemented).  See http://twistedmatrix.com/trac/ticket/4470
    for more specific information about new endpoint classes.  The naming is
    slightly misleading, but presumably if you're passing an IPv6 literal, you
    know what you're asking for.
    """
    def __init__(self):
        self.interface = getLinkLocalIPv6Address()



class TCPClientTestsBase(ReactorBuilder, ConnectionTestsMixin,
                         TCPClientTestsMixin):
    """
    Base class for builders defining tests related to L{IReactorTCP.connectTCP}.
    """
    requiredInterfaces = (IReactorTCP,)

    port = 1234

    @property
    def interface(self):
        """
        Return the interface attribute from the endpoints object.
        """
        return self.endpoints.interface



class TCP4ClientTestsBuilder(TCPClientTestsBase):
    """
    Builder configured with IPv4 parameters for tests related to
    L{IReactorTCP.connectTCP}.
    """
    fakeDomainName = 'some-fake.domain.example.com'
    family = socket.AF_INET
    addressClass = IPv4Address

    endpoints = TCPCreator()



class TCP6ClientTestsBuilder(TCPClientTestsBase):
    """
    Builder configured with IPv6 parameters for tests related to
    L{IReactorTCP.connectTCP}.
    """
    if ipv6Skip:
        skip = ipv6Skip

    family = socket.AF_INET6
    addressClass = IPv6Address

    def setUp(self):
        # Only create this object here, so that it won't be created if tests
        # are being skipped:
        self.endpoints = TCP6Creator()
        # This is used by test_addresses to test the distinction between the
        # resolved name and the name on the socket itself.  All the same
        # invariants should hold, but giving back an IPv6 address from a
        # resolver is not something the reactor can handle, so instead, we make
        # it so that the connect call for the IPv6 address test simply uses an
        # address literal.
        self.fakeDomainName = self.endpoints.interface



class TCPConnectorTestsBuilder(ReactorBuilder):
    """
    Tests for the L{IConnector} provider returned by L{IReactorTCP.connectTCP}.
    """
    requiredInterfaces = (IReactorTCP,)

    def test_connectorIdentity(self):
        """
        L{IReactorTCP.connectTCP} returns an object which provides
        L{IConnector}.  The destination of the connector is the address which
        was passed to C{connectTCP}.  The same connector object is passed to
        the factory's C{startedConnecting} method as to the factory's
        C{clientConnectionLost} method.
        """
        serverFactory = ClosingFactory()
        reactor = self.buildReactor()
        tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface)
        serverFactory.port = tcpPort
        portNumber = tcpPort.getHost().port

        seenConnectors = []
        seenFailures = []

        clientFactory = ClientStartStopFactory()
        clientFactory.clientConnectionLost = (
            lambda connector, reason: (seenConnectors.append(connector),
                                       seenFailures.append(reason)))
        clientFactory.startedConnecting = seenConnectors.append

        connector = reactor.connectTCP(self.interface, portNumber,
                                       clientFactory)
        self.assertTrue(IConnector.providedBy(connector))
        dest = connector.getDestination()
        self.assertEqual(dest.type, "TCP")
        self.assertEqual(dest.host, self.interface)
        self.assertEqual(dest.port, portNumber)

        clientFactory.whenStopped.addBoth(lambda _: reactor.stop())

        self.runReactor(reactor)

        seenFailures[0].trap(ConnectionDone)
        self.assertEqual(seenConnectors, [connector, connector])


    def test_userFail(self):
        """
        Calling L{IConnector.stopConnecting} in C{Factory.startedConnecting}
        results in C{Factory.clientConnectionFailed} being called with
        L{error.UserError} as the reason.
        """
        serverFactory = MyServerFactory()
        reactor = self.buildReactor()
        tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface)
        portNumber = tcpPort.getHost().port

        fatalErrors = []

        def startedConnecting(connector):
            try:
                connector.stopConnecting()
            except Exception:
                fatalErrors.append(Failure())
                reactor.stop()

        clientFactory = ClientStartStopFactory()
        clientFactory.startedConnecting = startedConnecting

        clientFactory.whenStopped.addBoth(lambda _: reactor.stop())

        reactor.callWhenRunning(lambda: reactor.connectTCP(self.interface,
                                                           portNumber,
                                                           clientFactory))

        self.runReactor(reactor)

        if fatalErrors:
            self.fail(fatalErrors[0].getTraceback())
        clientFactory.reason.trap(UserError)
        self.assertEqual(clientFactory.failed, 1)


    def test_reconnect(self):
        """
        Calling L{IConnector.connect} in C{Factory.clientConnectionLost} causes
        a new connection attempt to be made.
        """
        serverFactory = ClosingFactory()
        reactor = self.buildReactor()
        tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface)
        serverFactory.port = tcpPort
        portNumber = tcpPort.getHost().port

        clientFactory = MyClientFactory()

        def clientConnectionLost(connector, reason):
            connector.connect()
        clientFactory.clientConnectionLost = clientConnectionLost
        reactor.connectTCP(self.interface, portNumber, clientFactory)

        protocolMadeAndClosed = []
        def reconnectFailed(ignored):
            p = clientFactory.protocol
            protocolMadeAndClosed.append((p.made, p.closed))
            reactor.stop()

        clientFactory.failDeferred.addCallback(reconnectFailed)

        self.runReactor(reactor)

        clientFactory.reason.trap(ConnectionRefusedError)
        self.assertEqual(protocolMadeAndClosed, [(1, 1)])



class TCP4ConnectorTestsBuilder(TCPConnectorTestsBuilder):
    interface = '127.0.0.1'
    family = socket.AF_INET
    addressClass = IPv4Address



class TCP6ConnectorTestsBuilder(TCPConnectorTestsBuilder):
    family = socket.AF_INET6
    addressClass = IPv6Address

    if ipv6Skip:
        skip = ipv6Skip

    def setUp(self):
        self.interface = getLinkLocalIPv6Address()



def createTestSocket(test, addressFamily, socketType):
    """
    Create a socket for the duration of the given test.

    @param test: the test to add cleanup to.

    @param addressFamily: an C{AF_*} constant

    @param socketType: a C{SOCK_*} constant.

    @return: a socket object.
    """
    skt = socket.socket(addressFamily, socketType)
    test.addCleanup(skt.close)
    return skt



class StreamTransportTestsMixin(LogObserverMixin):
    """
    Mixin defining tests which apply to any port/connection based transport.
    """
    def test_startedListeningLogMessage(self):
        """
        When a port starts, a message including a description of the associated
        factory is logged.
        """
        loggedMessages = self.observe()
        reactor = self.buildReactor()
        class SomeFactory(ServerFactory):
            implements(ILoggingContext)
            def logPrefix(self):
                return "Crazy Factory"
        factory = SomeFactory()
        p = self.getListeningPort(reactor, factory)
        expectedMessage = self.getExpectedStartListeningLogMessage(
            p, "Crazy Factory")
        self.assertEqual((expectedMessage,), loggedMessages[0]['message'])


    def test_connectionLostLogMsg(self):
        """
        When a connection is lost, an informative message should be logged
        (see L{getExpectedConnectionLostLogMsg}): an address identifying
        the port and the fact that it was closed.
        """

        loggedMessages = []
        def logConnectionLostMsg(eventDict):
            loggedMessages.append(log.textFromEventDict(eventDict))

        reactor = self.buildReactor()
        p = self.getListeningPort(reactor, ServerFactory())
        expectedMessage = self.getExpectedConnectionLostLogMsg(p)
        log.addObserver(logConnectionLostMsg)

        def stopReactor(ignored):
            log.removeObserver(logConnectionLostMsg)
            reactor.stop()

        def doStopListening():
            log.addObserver(logConnectionLostMsg)
            maybeDeferred(p.stopListening).addCallback(stopReactor)

        reactor.callWhenRunning(doStopListening)
        reactor.run()

        self.assertIn(expectedMessage, loggedMessages)


    def test_allNewStyle(self):
        """
        The L{IListeningPort} object is an instance of a class with no
        classic classes in its hierarchy.
        """
        reactor = self.buildReactor()
        port = self.getListeningPort(reactor, ServerFactory())
        self.assertFullyNewStyle(port)


class ListenTCPMixin(object):
    """
    Mixin which uses L{IReactorTCP.listenTCP} to hand out listening TCP ports.
    """
    def getListeningPort(self, reactor, factory, port=0, interface=''):
        """
        Get a TCP port from a reactor.
        """
        return reactor.listenTCP(port, factory, interface=interface)



class SocketTCPMixin(object):
    """
    Mixin which uses L{IReactorSocket.adoptStreamPort} to hand out listening TCP
    ports.
    """
    def getListeningPort(self, reactor, factory, port=0, interface=''):
        """
        Get a TCP port from a reactor, wrapping an already-initialized file
        descriptor.
        """
        if IReactorSocket.providedBy(reactor):
            if ':' in interface:
                domain = socket.AF_INET6
                address = socket.getaddrinfo(interface, port)[0][4]
            else:
                domain = socket.AF_INET
                address = (interface, port)
            portSock = socket.socket(domain)
            portSock.bind(address)
            portSock.listen(3)
            portSock.setblocking(False)
            try:
                return reactor.adoptStreamPort(
                    portSock.fileno(), portSock.family, factory)
            finally:
                # The socket should still be open; fileno will raise if it is
                # not.
                portSock.fileno()
                # Now clean it up, because the rest of the test does not need
                # it.
                portSock.close()
        else:
            raise SkipTest("Reactor does not provide IReactorSocket")



class TCPPortTestsMixin(object):
    """
    Tests for L{IReactorTCP.listenTCP}
    """
    requiredInterfaces = (IReactorTCP,)

    def getExpectedStartListeningLogMessage(self, port, factory):
        """
        Get the message expected to be logged when a TCP port starts listening.
        """
        return "%s starting on %d" % (
            factory, port.getHost().port)


    def getExpectedConnectionLostLogMsg(self, port):
        """
        Get the expected connection lost message for a TCP port.
        """
        return "(TCP Port %s Closed)" % (port.getHost().port,)


    def test_portGetHostOnIPv4(self):
        """
        When no interface is passed to L{IReactorTCP.listenTCP}, the returned
        listening port listens on an IPv4 address.
        """
        reactor = self.buildReactor()
        port = self.getListeningPort(reactor, ServerFactory())
        address = port.getHost()
        self.assertIsInstance(address, IPv4Address)


    def test_portGetHostOnIPv6(self):
        """
        When listening on an IPv6 address, L{IListeningPort.getHost} returns
        an L{IPv6Address} with C{host} and C{port} attributes reflecting the
        address the port is bound to.
        """
        reactor = self.buildReactor()
        host, portNumber = findFreePort(
            family=socket.AF_INET6, interface='::1')[:2]
        port = self.getListeningPort(
            reactor, ServerFactory(), portNumber, host)
        address = port.getHost()
        self.assertIsInstance(address, IPv6Address)
        self.assertEqual('::1', address.host)
        self.assertEqual(portNumber, address.port)
    if ipv6Skip:
        test_portGetHostOnIPv6.skip = ipv6Skip


    def test_portGetHostOnIPv6ScopeID(self):
        """
        When a link-local IPv6 address including a scope identifier is passed as
        the C{interface} argument to L{IReactorTCP.listenTCP}, the resulting
        L{IListeningPort} reports its address as an L{IPv6Address} with a host
        value that includes the scope identifier.
        """
        linkLocal = getLinkLocalIPv6Address()
        reactor = self.buildReactor()
        port = self.getListeningPort(reactor, ServerFactory(), 0, linkLocal)
        address = port.getHost()
        self.assertIsInstance(address, IPv6Address)
        self.assertEqual(linkLocal, address.host)
    if ipv6Skip:
        test_portGetHostOnIPv6ScopeID.skip = ipv6Skip


    def _buildProtocolAddressTest(self, client, interface):
        """
        Connect C{client} to a server listening on C{interface} started with
        L{IReactorTCP.listenTCP} and return the address passed to the factory's
        C{buildProtocol} method.

        @param client: A C{SOCK_STREAM} L{socket.socket} created with an address
            family such that it will be able to connect to a server listening on
            C{interface}.

        @param interface: A C{str} giving an address for a server to listen on.
            This should almost certainly be the loopback address for some
            address family supported by L{IReactorTCP.listenTCP}.

        @return: Whatever object, probably an L{IAddress} provider, is passed to
            a server factory's C{buildProtocol} method when C{client}
            establishes a connection.
        """
        class ObserveAddress(ServerFactory):
            def buildProtocol(self, address):
                reactor.stop()
                self.observedAddress = address
                return Protocol()

        factory = ObserveAddress()
        reactor = self.buildReactor()
        port = self.getListeningPort(reactor, factory, 0, interface)
        client.setblocking(False)
        try:
            connect(client, (port.getHost().host, port.getHost().port))
        except socket.error, (errnum, message):
            self.assertIn(errnum, (errno.EINPROGRESS, errno.EWOULDBLOCK))

        self.runReactor(reactor)

        return factory.observedAddress


    def test_buildProtocolIPv4Address(self):
        """
        When a connection is accepted over IPv4, an L{IPv4Address} is passed
        to the factory's C{buildProtocol} method giving the peer's address.
        """
        interface = '127.0.0.1'
        client = createTestSocket(self, socket.AF_INET, socket.SOCK_STREAM)
        observedAddress = self._buildProtocolAddressTest(client, interface)
        self.assertEqual(
            IPv4Address('TCP', *client.getsockname()), observedAddress)


    def test_buildProtocolIPv6Address(self):
        """
        When a connection is accepted to an IPv6 address, an L{IPv6Address} is
        passed to the factory's C{buildProtocol} method giving the peer's
        address.
        """
        interface = '::1'
        client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM)
        observedAddress = self._buildProtocolAddressTest(client, interface)
        self.assertEqual(
            IPv6Address('TCP', *client.getsockname()[:2]), observedAddress)
    if ipv6Skip:
        test_buildProtocolIPv6Address.skip = ipv6Skip


    def test_buildProtocolIPv6AddressScopeID(self):
        """
        When a connection is accepted to a link-local IPv6 address, an
        L{IPv6Address} is passed to the factory's C{buildProtocol} method
        giving the peer's address, including a scope identifier.
        """
        interface = getLinkLocalIPv6Address()
        client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM)
        observedAddress = self._buildProtocolAddressTest(client, interface)
        self.assertEqual(
            IPv6Address('TCP', *client.getsockname()[:2]), observedAddress)
    if ipv6Skip:
        test_buildProtocolIPv6AddressScopeID.skip = ipv6Skip


    def _serverGetConnectionAddressTest(self, client, interface, which):
        """
        Connect C{client} to a server listening on C{interface} started with
        L{IReactorTCP.listenTCP} and return the address returned by one of the
        server transport's address lookup methods, C{getHost} or C{getPeer}.

        @param client: A C{SOCK_STREAM} L{socket.socket} created with an address
            family such that it will be able to connect to a server listening on
            C{interface}.

        @param interface: A C{str} giving an address for a server to listen on.
            This should almost certainly be the loopback address for some
            address family supported by L{IReactorTCP.listenTCP}.

        @param which: A C{str} equal to either C{"getHost"} or C{"getPeer"}
            determining which address will be returned.

        @return: Whatever object, probably an L{IAddress} provider, is returned
            from the method indicated by C{which}.
        """
        class ObserveAddress(Protocol):
            def makeConnection(self, transport):
                reactor.stop()
                self.factory.address = getattr(transport, which)()

        reactor = self.buildReactor()
        factory = ServerFactory()
        factory.protocol = ObserveAddress
        port = self.getListeningPort(reactor, factory, 0, interface)
        client.setblocking(False)
        try:
            connect(client, (port.getHost().host, port.getHost().port))
        except socket.error, (errnum, message):
            self.assertIn(errnum, (errno.EINPROGRESS, errno.EWOULDBLOCK))
        self.runReactor(reactor)
        return factory.address


    def test_serverGetHostOnIPv4(self):
        """
        When a connection is accepted over IPv4, the server
        L{ITransport.getHost} method returns an L{IPv4Address} giving the
        address on which the server accepted the connection.
        """
        interface = '127.0.0.1'
        client = createTestSocket(self, socket.AF_INET, socket.SOCK_STREAM)
        hostAddress = self._serverGetConnectionAddressTest(
            client, interface, 'getHost')
        self.assertEqual(
            IPv4Address('TCP', *client.getpeername()), hostAddress)


    def test_serverGetHostOnIPv6(self):
        """
        When a connection is accepted over IPv6, the server
        L{ITransport.getHost} method returns an L{IPv6Address} giving the
        address on which the server accepted the connection.
        """
        interface = '::1'
        client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM)
        hostAddress = self._serverGetConnectionAddressTest(
            client, interface, 'getHost')
        self.assertEqual(
            IPv6Address('TCP', *client.getpeername()[:2]), hostAddress)
    if ipv6Skip:
        test_serverGetHostOnIPv6.skip = ipv6Skip


    def test_serverGetHostOnIPv6ScopeID(self):
        """
        When a connection is accepted over IPv6, the server
        L{ITransport.getHost} method returns an L{IPv6Address} giving the
        address on which the server accepted the connection, including the scope
        identifier.
        """
        interface = getLinkLocalIPv6Address()
        client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM)
        hostAddress = self._serverGetConnectionAddressTest(
            client, interface, 'getHost')
        self.assertEqual(
            IPv6Address('TCP', *client.getpeername()[:2]), hostAddress)
    if ipv6Skip:
        test_serverGetHostOnIPv6ScopeID.skip = ipv6Skip


    def test_serverGetPeerOnIPv4(self):
        """
        When a connection is accepted over IPv4, the server
        L{ITransport.getPeer} method returns an L{IPv4Address} giving the
        address of the remote end of the connection.
        """
        interface = '127.0.0.1'
        client = createTestSocket(self, socket.AF_INET, socket.SOCK_STREAM)
        peerAddress = self._serverGetConnectionAddressTest(
            client, interface, 'getPeer')
        self.assertEqual(
            IPv4Address('TCP', *client.getsockname()), peerAddress)


    def test_serverGetPeerOnIPv6(self):
        """
        When a connection is accepted over IPv6, the server
        L{ITransport.getPeer} method returns an L{IPv6Address} giving the
        address on the remote end of the connection.
        """
        interface = '::1'
        client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM)
        peerAddress = self._serverGetConnectionAddressTest(
            client, interface, 'getPeer')
        self.assertEqual(
            IPv6Address('TCP', *client.getsockname()[:2]), peerAddress)
    if ipv6Skip:
        test_serverGetPeerOnIPv6.skip = ipv6Skip


    def test_serverGetPeerOnIPv6ScopeID(self):
        """
        When a connection is accepted over IPv6, the server
        L{ITransport.getPeer} method returns an L{IPv6Address} giving the
        address on the remote end of the connection, including the scope
        identifier.
        """
        interface = getLinkLocalIPv6Address()
        client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM)
        peerAddress = self._serverGetConnectionAddressTest(
            client, interface, 'getPeer')
        self.assertEqual(
            IPv6Address('TCP', *client.getsockname()[:2]), peerAddress)
    if ipv6Skip:
        test_serverGetPeerOnIPv6ScopeID.skip = ipv6Skip



class TCPPortTestsBuilder(ReactorBuilder, ListenTCPMixin, TCPPortTestsMixin,
                          ObjectModelIntegrationMixin,
                          StreamTransportTestsMixin):
    pass



class TCPFDPortTestsBuilder(ReactorBuilder, SocketTCPMixin, TCPPortTestsMixin,
                            ObjectModelIntegrationMixin,
                            StreamTransportTestsMixin):
    pass



class StopStartReadingProtocol(Protocol):
    """
    Protocol that pauses and resumes the transport a few times
    """

    def connectionMade(self):
        self.data = ''
        self.pauseResumeProducing(3)


    def pauseResumeProducing(self, counter):
        """
        Toggle transport read state, then count down.
        """
        self.transport.pauseProducing()
        self.transport.resumeProducing()
        if counter:
            self.factory.reactor.callLater(0,
                    self.pauseResumeProducing, counter - 1)
        else:
            self.factory.reactor.callLater(0,
                    self.factory.ready.callback, self)


    def dataReceived(self, data):
        log.msg('got data', len(data))
        self.data += data
        if len(self.data) == 4*4096:
            self.factory.stop.callback(self.data)



class TCPConnectionTestsBuilder(ReactorBuilder):
    """
    Builder defining tests relating to L{twisted.internet.tcp.Connection}.
    """
    requiredInterfaces = (IReactorTCP,)

    def test_stopStartReading(self):
        """
        This test verifies transport socket read state after multiple
        pause/resumeProducing calls.
        """
        sf = ServerFactory()
        reactor = sf.reactor = self.buildReactor()

        skippedReactors = ["Glib2Reactor", "Gtk2Reactor"]
        reactorClassName = reactor.__class__.__name__
        if reactorClassName in skippedReactors and platform.isWindows():
            raise SkipTest(
                "This test is broken on gtk/glib under Windows.")

        sf.protocol = StopStartReadingProtocol
        sf.ready = Deferred()
        sf.stop = Deferred()
        p = reactor.listenTCP(0, sf)
        port = p.getHost().port
        def proceed(protos, port):
            """
            Send several IOCPReactor's buffers' worth of data.
            """
            self.assertTrue(protos[0])
            self.assertTrue(protos[1])
            protos = protos[0][1], protos[1][1]
            protos[0].transport.write('x' * (2 * 4096) + 'y' * (2 * 4096))
            return (sf.stop.addCallback(cleanup, protos, port)
                           .addCallback(lambda ign: reactor.stop()))

        def cleanup(data, protos, port):
            """
            Make sure IOCPReactor didn't start several WSARecv operations
            that clobbered each other's results.
            """
            self.assertEqual(data, 'x'*(2*4096) + 'y'*(2*4096),
                                 'did not get the right data')
            return DeferredList([
                    maybeDeferred(protos[0].transport.loseConnection),
                    maybeDeferred(protos[1].transport.loseConnection),
                    maybeDeferred(port.stopListening)])

        cc = TCP4ClientEndpoint(reactor, '127.0.0.1', port)
        cf = ClientFactory()
        cf.protocol = Protocol
        d = DeferredList([cc.connect(cf), sf.ready]).addCallback(proceed, p)
        d.addErrback(log.err)
        self.runReactor(reactor)


    def test_connectionLostAfterPausedTransport(self):
        """
        Alice connects to Bob.  Alice writes some bytes and then shuts down the
        connection.  Bob receives the bytes from the connection and then pauses
        the transport object.  Shortly afterwards Bob resumes the transport
        object.  At that point, Bob is notified that the connection has been
        closed.

        This is no problem for most reactors.  The underlying event notification
        API will probably just remind them that the connection has been closed.
        It is a little tricky for win32eventreactor (MsgWaitForMultipleObjects).
        MsgWaitForMultipleObjects will only deliver the close notification once.
        The reactor needs to remember that notification until Bob resumes the
        transport.
        """
        class Pauser(ConnectableProtocol):
            def __init__(self):
                self.events = []

            def dataReceived(self, bytes):
                self.events.append("paused")
                self.transport.pauseProducing()
                self.reactor.callLater(0, self.resume)

            def resume(self):
                self.events.append("resumed")
                self.transport.resumeProducing()

            def connectionLost(self, reason):
                # This is the event you have been waiting for.
                self.events.append("lost")
                ConnectableProtocol.connectionLost(self, reason)

        class Client(ConnectableProtocol):
            def connectionMade(self):
                self.transport.write("some bytes for you")
                self.transport.loseConnection()

        pauser = Pauser()
        runProtocolsWithReactor(self, pauser, Client(), TCPCreator())
        self.assertEqual(pauser.events, ["paused", "resumed", "lost"])


    def test_doubleHalfClose(self):
        """
        If one side half-closes its connection, and then the other side of the
        connection calls C{loseWriteConnection}, and then C{loseConnection} in
        {writeConnectionLost}, the connection is closed correctly.

        This rather obscure case used to fail (see ticket #3037).
        """
        class ListenerProtocol(ConnectableProtocol):
            implements(IHalfCloseableProtocol)

            def readConnectionLost(self):
                self.transport.loseWriteConnection()

            def writeConnectionLost(self):
                self.transport.loseConnection()

        class Client(ConnectableProtocol):
            def connectionMade(self):
                self.transport.loseConnection()

        # If test fails, reactor won't stop and we'll hit timeout:
        runProtocolsWithReactor(
            self, ListenerProtocol(), Client(), TCPCreator())



class WriteSequenceTestsMixin(object):
    """
    Test for L{twisted.internet.abstract.FileDescriptor.writeSequence}.
    """
    requiredInterfaces = (IReactorTCP,)

    def setWriteBufferSize(self, transport, value):
        """
        Set the write buffer size for the given transport, mananing possible
        differences (ie, IOCP). Bug #4322 should remove the need of that hack.
        """
        if getattr(transport, "writeBufferSize", None) is not None:
            transport.writeBufferSize = value
        else:
            transport.bufferSize = value


    def test_writeSequeceWithoutWrite(self):
        """
        C{writeSequence} sends the data even if C{write} hasn't been called.
        """

        def connected(protocols):
            client, server, port = protocols

            def dataReceived(data):
                log.msg("data received: %r" % data)
                self.assertEqual(data, "Some sequence splitted")
                client.transport.loseConnection()

            server.dataReceived = dataReceived

            client.transport.writeSequence(["Some ", "sequence ", "splitted"])

        reactor = self.buildReactor()
        d = self.getConnectedClientAndServer(reactor, "127.0.0.1",
                                             socket.AF_INET)
        d.addCallback(connected)
        d.addErrback(log.err)
        self.runReactor(reactor)


    def test_writeSequenceWithUnicodeRaisesException(self):
        """
        C{writeSequence} with an element in the sequence of type unicode raises
        C{TypeError}.
        """

        def connected(protocols):
            client, server, port = protocols

            exc = self.assertRaises(
                TypeError,
                server.transport.writeSequence, [u"Unicode is not kosher"])

            self.assertEqual(str(exc), "Data must not be unicode")

            server.transport.loseConnection()

        reactor = self.buildReactor()
        d = self.getConnectedClientAndServer(reactor, "127.0.0.1",
                                             socket.AF_INET)
        d.addCallback(connected)
        d.addErrback(log.err)
        self.runReactor(reactor)


    def test_streamingProducer(self):
        """
        C{writeSequence} pauses its streaming producer if too much data is
        buffered, and then resumes it.
        """

        class SaveActionProducer(object):
            implements(IPushProducer)
            client = None
            server = None

            def __init__(self):
                self.actions = []

            def pauseProducing(self):
                self.actions.append("pause")

            def resumeProducing(self):
                self.actions.append("resume")
                # Unregister the producer so the connection can close
                self.client.transport.unregisterProducer()
                # This is why the code below waits for the server connection
                # first - so we have it to close here.  We close the server
                # side because win32evenreactor cannot reliably observe us
                # closing the client side (#5285).
                self.server.transport.loseConnection()

            def stopProducing(self):
                self.actions.append("stop")

        producer = SaveActionProducer()

        def connected(protocols):
            client, server = protocols[:2]
            producer.client = client
            producer.server = server
            # Register a streaming producer and verify that it gets paused
            # after it writes more than the local send buffer can hold.
            client.transport.registerProducer(producer, True)
            self.assertEqual(producer.actions, [])
            self.setWriteBufferSize(client.transport, 500)
            client.transport.writeSequence(["x" * 50] * 20)
            self.assertEqual(producer.actions, ["pause"])

        reactor = self.buildReactor()
        d = self.getConnectedClientAndServer(reactor, "127.0.0.1",
                                             socket.AF_INET)
        d.addCallback(connected)
        d.addErrback(log.err)
        self.runReactor(reactor)
        # After the send buffer gets a chance to empty out a bit, the producer
        # should be resumed.
        self.assertEqual(producer.actions, ["pause", "resume"])


    def test_nonStreamingProducer(self):
        """
        C{writeSequence} pauses its producer if too much data is buffered only
        if this is a streaming producer.
        """
        test = self

        class SaveActionProducer(object):
            implements(IPullProducer)
            client = None

            def __init__(self):
                self.actions = []

            def resumeProducing(self):
                self.actions.append("resume")
                if self.actions.count("resume") == 2:
                    self.client.transport.stopConsuming()
                else:
                    test.setWriteBufferSize(self.client.transport, 500)
                    self.client.transport.writeSequence(["x" * 50] * 20)

            def stopProducing(self):
                self.actions.append("stop")


        producer = SaveActionProducer()

        def connected(protocols):
            client = protocols[0]
            producer.client = client
            # Register a non-streaming producer and verify that it is resumed
            # immediately.
            client.transport.registerProducer(producer, False)
            self.assertEqual(producer.actions, ["resume"])

        reactor = self.buildReactor()
        d = self.getConnectedClientAndServer(reactor, "127.0.0.1",
                                             socket.AF_INET)
        d.addCallback(connected)
        d.addErrback(log.err)
        self.runReactor(reactor)
        # After the local send buffer empties out, the producer should be
        # resumed again.
        self.assertEqual(producer.actions, ["resume", "resume"])



class TCPTransportServerAddressTestMixin(object):
    """
    Test mixing for TCP server address building and log prefix.
    """

    def getConnectedClientAndServer(self, reactor, interface, addressFamily):
        """
        Helper method returnine a L{Deferred} firing with a tuple of a client
        protocol, a server protocol, and a running TCP port.
        """
        raise NotImplementedError()


    def _testServerAddress(self, interface, addressFamily, adressClass):
        """
        Helper method to test TCP server addresses on either IPv4 or IPv6.
        """

        def connected(protocols):
            client, server, port = protocols

            self.assertEqual(
                "<AccumulatingProtocol #%s on %s>" %
                    (server.transport.sessionno, port.getHost().port),
                str(server.transport))

            self.assertEqual(
                "AccumulatingProtocol,%s,%s" %
                    (server.transport.sessionno, interface),
                server.transport.logstr)

            [peerAddress] = server.factory.peerAddresses
            self.assertIsInstance(peerAddress, adressClass)
            self.assertEqual('TCP', peerAddress.type)
            self.assertEqual(interface, peerAddress.host)

            server.transport.loseConnection()

        reactor = self.buildReactor()
        d = self.getConnectedClientAndServer(reactor, interface, addressFamily)
        d.addCallback(connected)
        d.addErrback(log.err)
        self.runReactor(reactor)


    def test_serverAddressTCP4(self):
        """
        L{Server} instances have a string representation indicating on which
        port they're running, and the connected address is stored on the
        C{peerAddresses} attribute of the factory.
        """
        return self._testServerAddress("127.0.0.1", socket.AF_INET,
                                       IPv4Address)


    def test_serverAddressTCP6(self):
        """
        IPv6 L{Server} instances have a string representation indicating on
        which port they're running, and the connected address is stored on the
        C{peerAddresses} attribute of the factory.
        """
        return self._testServerAddress(getLinkLocalIPv6Address(),
                                       socket.AF_INET6, IPv6Address)

    if ipv6Skip:
        test_serverAddressTCP6.skip = ipv6Skip



class TCPTransportTestsBuilder(TCPTransportServerAddressTestMixin,
                               WriteSequenceTestsMixin, ReactorBuilder):
    """
    Test standard L{ITCPTransport}s built with C{listenTCP} and C{connectTCP}.
    """

    def getConnectedClientAndServer(self, reactor, interface, addressFamily):
        """
        Return a L{Deferred} firing with a L{MyClientFactory} and
        L{MyServerFactory} connected pair, and the listening C{Port}.
        """
        server = MyServerFactory()
        server.protocolConnectionMade = Deferred()
        server.protocolConnectionLost = Deferred()

        client = MyClientFactory()
        client.protocolConnectionMade = Deferred()
        client.protocolConnectionLost = Deferred()

        port = reactor.listenTCP(0, server, interface=interface)

        lostDeferred = gatherResults([client.protocolConnectionLost,
                                      server.protocolConnectionLost])
        def stop(result):
            reactor.stop()
            return result

        lostDeferred.addBoth(stop)

        startDeferred = gatherResults([client.protocolConnectionMade,
                                       server.protocolConnectionMade])

        deferred = Deferred()

        def start(protocols):
            client, server = protocols
            log.msg("client connected %s" % client)
            log.msg("server connected %s" % server)
            deferred.callback((client, server, port))

        startDeferred.addCallback(start)

        reactor.connectTCP(interface, port.getHost().port, client)

        return deferred



class AdoptStreamConnectionTestsBuilder(TCPTransportServerAddressTestMixin,
                                        WriteSequenceTestsMixin,
                                        ReactorBuilder):
    """
    Test server transports built using C{adoptStreamConnection}.
    """

    requiredInterfaces = (IReactorFDSet, IReactorSocket)

    def getConnectedClientAndServer(self, reactor, interface, addressFamily):
        """
        Return a L{Deferred} firing with a L{MyClientFactory} and
        L{MyServerFactory} connected pair, and the listening C{Port}. The
        particularity is that the server protocol has been obtained after doing
        a C{adoptStreamConnection} against the original server connection.
        """
        firstServer = MyServerFactory()
        firstServer.protocolConnectionMade = Deferred()

        server = MyServerFactory()
        server.protocolConnectionMade = Deferred()
        server.protocolConnectionLost = Deferred()

        client = MyClientFactory()
        client.protocolConnectionMade = Deferred()
        client.protocolConnectionLost = Deferred()

        port = reactor.listenTCP(0, firstServer, interface=interface)

        def firtServerConnected(proto):
            reactor.removeReader(proto.transport)
            reactor.removeWriter(proto.transport)
            reactor.adoptStreamConnection(
                proto.transport.fileno(), addressFamily, server)

        firstServer.protocolConnectionMade.addCallback(firtServerConnected)

        lostDeferred = gatherResults([client.protocolConnectionLost,
                                      server.protocolConnectionLost])
        def stop(result):
            if reactor.running:
                reactor.stop()
            return result

        lostDeferred.addBoth(stop)

        deferred = Deferred()
        deferred.addErrback(stop)

        startDeferred = gatherResults([client.protocolConnectionMade,
                                       server.protocolConnectionMade])
        def start(protocols):
            client, server = protocols
            log.msg("client connected %s" % client)
            log.msg("server connected %s" % server)
            deferred.callback((client, server, port))

        startDeferred.addCallback(start)

        reactor.connectTCP(interface, port.getHost().port, client)
        return deferred



globals().update(TCP4ClientTestsBuilder.makeTestCaseClasses())
globals().update(TCP6ClientTestsBuilder.makeTestCaseClasses())
globals().update(TCPPortTestsBuilder.makeTestCaseClasses())
globals().update(TCPFDPortTestsBuilder.makeTestCaseClasses())
globals().update(TCPConnectionTestsBuilder.makeTestCaseClasses())
globals().update(TCP4ConnectorTestsBuilder.makeTestCaseClasses())
globals().update(TCP6ConnectorTestsBuilder.makeTestCaseClasses())
globals().update(TCPTransportTestsBuilder.makeTestCaseClasses())
globals().update(AdoptStreamConnectionTestsBuilder.makeTestCaseClasses())



class ServerAbortsTwice(ConnectableProtocol):
    """
    Call abortConnection() twice.
    """

    def dataReceived(self, data):
        self.transport.abortConnection()
        self.transport.abortConnection()



class ServerAbortsThenLoses(ConnectableProtocol):
    """
    Call abortConnection() followed by loseConnection().
    """

    def dataReceived(self, data):
        self.transport.abortConnection()
        self.transport.loseConnection()



class AbortServerWritingProtocol(ConnectableProtocol):
    """
    Protocol that writes data upon connection.
    """

    def connectionMade(self):
        """
        Tell the client that the connection is set up and it's time to abort.
        """
        self.transport.write("ready")



class ReadAbortServerProtocol(AbortServerWritingProtocol):
    """
    Server that should never receive any data, except 'X's which are written
    by the other side of the connection before abortConnection, and so might
    possibly arrive.
    """

    def dataReceived(self, data):
        if data.replace('X', ''):
            raise Exception("Unexpectedly received data.")



class NoReadServer(ConnectableProtocol):
    """
    Stop reading immediately on connection.

    This simulates a lost connection that will cause the other side to time
    out, and therefore call abortConnection().
    """

    def connectionMade(self):
        self.transport.stopReading()



class EventualNoReadServer(ConnectableProtocol):
    """
    Like NoReadServer, except we Wait until some bytes have been delivered
    before stopping reading. This means TLS handshake has finished, where
    applicable.
    """

    gotData = False
    stoppedReading = False


    def dataReceived(self, data):
        if not self.gotData:
            self.gotData = True
            self.transport.registerProducer(self, False)
            self.transport.write("hello")


    def resumeProducing(self):
        if self.stoppedReading:
            return
        self.stoppedReading = True
        # We've written out the data:
        self.transport.stopReading()


    def pauseProducing(self):
        pass


    def stopProducing(self):
        pass



class BaseAbortingClient(ConnectableProtocol):
    """
    Base class for abort-testing clients.
    """
    inReactorMethod = False

    def connectionLost(self, reason):
        if self.inReactorMethod:
            raise RuntimeError("BUG: connectionLost was called re-entrantly!")
        ConnectableProtocol.connectionLost(self, reason)



class WritingButNotAbortingClient(BaseAbortingClient):
    """
    Write data, but don't abort.
    """

    def connectionMade(self):
        self.transport.write("hello")



class AbortingClient(BaseAbortingClient):
    """
    Call abortConnection() after writing some data.
    """

    def dataReceived(self, data):
        """
        Some data was received, so the connection is set up.
        """
        self.inReactorMethod = True
        self.writeAndAbort()
        self.inReactorMethod = False


    def writeAndAbort(self):
        # X is written before abortConnection, and so there is a chance it
        # might arrive. Y is written after, and so no Ys should ever be
        # delivered:
        self.transport.write("X" * 10000)
        self.transport.abortConnection()
        self.transport.write("Y" * 10000)



class AbortingTwiceClient(AbortingClient):
    """
    Call abortConnection() twice, after writing some data.
    """

    def writeAndAbort(self):
        AbortingClient.writeAndAbort(self)
        self.transport.abortConnection()



class AbortingThenLosingClient(AbortingClient):
    """
    Call abortConnection() and then loseConnection().
    """

    def writeAndAbort(self):
        AbortingClient.writeAndAbort(self)
        self.transport.loseConnection()



class ProducerAbortingClient(ConnectableProtocol):
    """
    Call abortConnection from doWrite, via resumeProducing.
    """

    inReactorMethod = True
    producerStopped = False

    def write(self):
        self.transport.write("lalala" * 127000)
        self.inRegisterProducer = True
        self.transport.registerProducer(self, False)
        self.inRegisterProducer = False


    def connectionMade(self):
        self.write()


    def resumeProducing(self):
        self.inReactorMethod = True
        if not self.inRegisterProducer:
            self.transport.abortConnection()
        self.inReactorMethod = False


    def stopProducing(self):
        self.producerStopped = True


    def connectionLost(self, reason):
        if not self.producerStopped:
            raise RuntimeError("BUG: stopProducing() was never called.")
        if self.inReactorMethod:
            raise RuntimeError("BUG: connectionLost called re-entrantly!")
        ConnectableProtocol.connectionLost(self, reason)



class StreamingProducerClient(ConnectableProtocol):
    """
    Call abortConnection() when the other side has stopped reading.

    In particular, we want to call abortConnection() only once our local
    socket hits a state where it is no longer writeable. This helps emulate
    the most common use case for abortConnection(), closing a connection after
    a timeout, with write buffers being full.

    Since it's very difficult to know when this actually happens, we just
    write a lot of data, and assume at that point no more writes will happen.
    """
    paused = False
    extraWrites = 0
    inReactorMethod = False

    def connectionMade(self):
        self.write()


    def write(self):
        """
        Write large amount to transport, then wait for a while for buffers to
        fill up.
        """
        self.transport.registerProducer(self, True)
        for i in range(100):
            self.transport.write("1234567890" * 32000)


    def resumeProducing(self):
        self.paused = False


    def stopProducing(self):
        pass


    def pauseProducing(self):
        """
        Called when local buffer fills up.

        The goal is to hit the point where the local file descriptor is not
        writeable (or the moral equivalent). The fact that pauseProducing has
        been called is not sufficient, since that can happen when Twisted's
        buffers fill up but OS hasn't gotten any writes yet. We want to be as
        close as possible to every buffer (including OS buffers) being full.

        So, we wait a bit more after this for Twisted to write out a few
        chunks, then abortConnection.
        """
        if self.paused:
            return
        self.paused = True
        # The amount we wait is arbitrary, we just want to make sure some
        # writes have happened and outgoing OS buffers filled up -- see
        # http://twistedmatrix.com/trac/ticket/5303 for details:
        self.reactor.callLater(0.01, self.doAbort)


    def doAbort(self):
        if not self.paused:
            log.err(RuntimeError("BUG: We should be paused a this point."))
        self.inReactorMethod = True
        self.transport.abortConnection()
        self.inReactorMethod = False


    def connectionLost(self, reason):
        # Tell server to start reading again so it knows to go away:
        self.otherProtocol.transport.startReading()
        ConnectableProtocol.connectionLost(self, reason)



class StreamingProducerClientLater(StreamingProducerClient):
    """
    Call abortConnection() from dataReceived, after bytes have been
    exchanged.
    """

    def connectionMade(self):
        self.transport.write("hello")
        self.gotData = False


    def dataReceived(self, data):
        if not self.gotData:
            self.gotData = True
            self.write()


class ProducerAbortingClientLater(ProducerAbortingClient):
    """
    Call abortConnection from doWrite, via resumeProducing.

    Try to do so after some bytes have already been exchanged, so we
    don't interrupt SSL handshake.
    """

    def connectionMade(self):
        # Override base class connectionMade().
        pass


    def dataReceived(self, data):
        self.write()



class DataReceivedRaisingClient(AbortingClient):
    """
    Call abortConnection(), and then throw exception, from dataReceived.
    """

    def dataReceived(self, data):
        self.transport.abortConnection()
        raise ZeroDivisionError("ONO")



class ResumeThrowsClient(ProducerAbortingClient):
    """
    Call abortConnection() and throw exception from resumeProducing().
    """

    def resumeProducing(self):
        if not self.inRegisterProducer:
            self.transport.abortConnection()
            raise ZeroDivisionError("ono!")


    def connectionLost(self, reason):
        # Base class assertion about stopProducing being called isn't valid;
        # if the we blew up in resumeProducing, consumers are justified in
        # giving up on the producer and not calling stopProducing.
        ConnectableProtocol.connectionLost(self, reason)



class AbortConnectionMixin(object):
    """
    Unit tests for L{ITransport.abortConnection}.
    """
    # Override in subclasses, should be a EndpointCreator instance:
    endpoints = None

    def runAbortTest(self, clientClass, serverClass,
                     clientConnectionLostReason=None):
        """
        A test runner utility function, which hooks up a matched pair of client
        and server protocols.

        We then run the reactor until both sides have disconnected, and then
        verify that the right exception resulted.
        """
        clientExpectedExceptions = (ConnectionAborted, ConnectionLost)
        serverExpectedExceptions = (ConnectionLost, ConnectionDone)
        # In TLS tests we may get SSL.Error instead of ConnectionLost,
        # since we're trashing the TLS protocol layer.
        if useSSL:
            clientExpectedExceptions = clientExpectedExceptions + (SSL.Error,)
            serverExpectedExceptions = serverExpectedExceptions + (SSL.Error,)

        client = clientClass()
        server = serverClass()
        client.otherProtocol = server
        server.otherProtocol = client
        reactor = runProtocolsWithReactor(self, server, client, self.endpoints)

        # Make sure everything was shutdown correctly:
        self.assertEqual(reactor.removeAll(), [])
        # The reactor always has a timeout added in runReactor():
        delayedCalls = reactor.getDelayedCalls()
        self.assertEqual(len(delayedCalls), 1, map(str, delayedCalls))

        if clientConnectionLostReason is not None:
            self.assertIsInstance(
                client.disconnectReason.value,
                (clientConnectionLostReason,) + clientExpectedExceptions)
        else:
            self.assertIsInstance(client.disconnectReason.value,
                                  clientExpectedExceptions)
        self.assertIsInstance(server.disconnectReason.value, serverExpectedExceptions)


    def test_dataReceivedAbort(self):
        """
        abortConnection() is called in dataReceived. The protocol should be
        disconnected, but connectionLost should not be called re-entrantly.
        """
        return self.runAbortTest(AbortingClient, ReadAbortServerProtocol)


    def test_clientAbortsConnectionTwice(self):
        """
        abortConnection() is called twice by client.

        No exception should be thrown, and the connection will be closed.
        """
        return self.runAbortTest(AbortingTwiceClient, ReadAbortServerProtocol)


    def test_clientAbortsConnectionThenLosesConnection(self):
        """
        Client calls abortConnection(), followed by loseConnection().

        No exception should be thrown, and the connection will be closed.
        """
        return self.runAbortTest(AbortingThenLosingClient,
                                 ReadAbortServerProtocol)


    def test_serverAbortsConnectionTwice(self):
        """
        abortConnection() is called twice by server.

        No exception should be thrown, and the connection will be closed.
        """
        return self.runAbortTest(WritingButNotAbortingClient, ServerAbortsTwice,
                                 clientConnectionLostReason=ConnectionLost)


    def test_serverAbortsConnectionThenLosesConnection(self):
        """
        Server calls abortConnection(), followed by loseConnection().

        No exception should be thrown, and the connection will be closed.
        """
        return self.runAbortTest(WritingButNotAbortingClient,
                                 ServerAbortsThenLoses,
                                 clientConnectionLostReason=ConnectionLost)


    def test_resumeProducingAbort(self):
        """
        abortConnection() is called in resumeProducing, before any bytes have
        been exchanged. The protocol should be disconnected, but
        connectionLost should not be called re-entrantly.
        """
        self.runAbortTest(ProducerAbortingClient,
                          ConnectableProtocol)


    def test_resumeProducingAbortLater(self):
        """
        abortConnection() is called in resumeProducing, after some
        bytes have been exchanged. The protocol should be disconnected.
        """
        return self.runAbortTest(ProducerAbortingClientLater,
                                 AbortServerWritingProtocol)


    def test_fullWriteBuffer(self):
        """
        abortConnection() triggered by the write buffer being full.

        In particular, the server side stops reading. This is supposed
        to simulate a realistic timeout scenario where the client
        notices the server is no longer accepting data.

        The protocol should be disconnected, but connectionLost should not be
        called re-entrantly.
        """
        self.runAbortTest(StreamingProducerClient,
                          NoReadServer)


    def test_fullWriteBufferAfterByteExchange(self):
        """
        abortConnection() is triggered by a write buffer being full.

        However, this buffer is filled after some bytes have been exchanged,
        allowing a TLS handshake if we're testing TLS. The connection will
        then be lost.
        """
        return self.runAbortTest(StreamingProducerClientLater,
                                 EventualNoReadServer)


    def test_dataReceivedThrows(self):
        """
        dataReceived calls abortConnection(), and then raises an exception.

        The connection will be lost, with the thrown exception
        (C{ZeroDivisionError}) as the reason on the client. The idea here is
        that bugs should not be masked by abortConnection, in particular
        unexpected exceptions.
        """
        self.runAbortTest(DataReceivedRaisingClient,
                          AbortServerWritingProtocol,
                          clientConnectionLostReason=ZeroDivisionError)
        errors = self.flushLoggedErrors(ZeroDivisionError)
        self.assertEqual(len(errors), 1)


    def test_resumeProducingThrows(self):
        """
        resumeProducing calls abortConnection(), and then raises an exception.

        The connection will be lost, with the thrown exception
        (C{ZeroDivisionError}) as the reason on the client. The idea here is
        that bugs should not be masked by abortConnection, in particular
        unexpected exceptions.
        """
        self.runAbortTest(ResumeThrowsClient,
                          ConnectableProtocol,
                          clientConnectionLostReason=ZeroDivisionError)
        errors = self.flushLoggedErrors(ZeroDivisionError)
        self.assertEqual(len(errors), 1)



class AbortConnectionTestCase(ReactorBuilder, AbortConnectionMixin):
    """
    TCP-specific L{AbortConnectionMixin} tests.
    """
    requiredInterfaces = (IReactorTCP,)

    endpoints = TCPCreator()

globals().update(AbortConnectionTestCase.makeTestCaseClasses())



class SimpleUtilityTestCase(TestCase):
    """
    Simple, direct tests for helpers within L{twisted.internet.tcp}.
    """
    if ipv6Skip:
        skip = ipv6Skip

    def test_resolveNumericHost(self):
        """
        L{_resolveIPv6} raises a L{socket.gaierror} (L{socket.EAI_NONAME}) when
        invoked with a non-numeric host.  (In other words, it is passing
        L{socket.AI_NUMERICHOST} to L{socket.getaddrinfo} and will not
        accidentally block if it receives bad input.)
        """
        err = self.assertRaises(socket.gaierror, _resolveIPv6, "localhost", 1)
        self.assertEqual(err.args[0], socket.EAI_NONAME)


    def test_resolveNumericService(self):
        """
        L{_resolveIPv6} raises a L{socket.gaierror} (L{socket.EAI_NONAME}) when
        invoked with a non-numeric port.  (In other words, it is passing
        L{socket.AI_NUMERICSERV} to L{socket.getaddrinfo} and will not
        accidentally block if it receives bad input.)
        """
        err = self.assertRaises(socket.gaierror, _resolveIPv6, "::1", "http")
        self.assertEqual(err.args[0], socket.EAI_NONAME)

    if platform.isWindows():
        test_resolveNumericService.skip = ("The AI_NUMERICSERV flag is not "
                                           "supported by Microsoft providers.")
        # http://msdn.microsoft.com/en-us/library/windows/desktop/ms738520.aspx


    def test_resolveIPv6(self):
        """
        L{_resolveIPv6} discovers the flow info and scope ID of an IPv6
        address.
        """
        result = _resolveIPv6("::1", 2)
        self.assertEqual(len(result), 4)
        # We can't say anything more useful about these than that they're
        # integers, because the whole point of getaddrinfo is that you can never
        # know a-priori know _anything_ about the network interfaces of the
        # computer that you're on and you have to ask it.
        self.assertIsInstance(result[2], int) # flow info
        self.assertIsInstance(result[3], int) # scope id
        # but, luckily, IP presentation format and what it means to be a port
        # number are a little better specified.
        self.assertEqual(result[:2], ("::1", 2))