aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/mail/test/test_smtp.py
blob: 058bb8ec6cd171bc4232cd0707f275d671613856 (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
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Test cases for twisted.mail.smtp module.
"""

from zope.interface import implements

from twisted.python.util import LineLog
from twisted.trial import unittest, util
from twisted.protocols import basic, loopback
from twisted.mail import smtp
from twisted.internet import defer, protocol, reactor, interfaces
from twisted.internet import address, error, task
from twisted.test.proto_helpers import StringTransport

from twisted import cred
import twisted.cred.error
import twisted.cred.portal
import twisted.cred.checkers
import twisted.cred.credentials

from twisted.cred.portal import IRealm, Portal
from twisted.cred.checkers import ICredentialsChecker, AllowAnonymousAccess
from twisted.cred.credentials import IAnonymous
from twisted.cred.error import UnauthorizedLogin

from twisted.mail import imap4


try:
    from twisted.test.ssl_helpers import ClientTLSContext, ServerTLSContext
except ImportError:
    ClientTLSContext = ServerTLSContext = None

import re

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO


def spameater(*spam, **eggs):
    return None



class BrokenMessage(object):
    """
    L{BrokenMessage} is an L{IMessage} which raises an unexpected exception
    from its C{eomReceived} method.  This is useful for creating a server which
    can be used to test client retry behavior.
    """
    implements(smtp.IMessage)

    def __init__(self, user):
        pass


    def lineReceived(self, line):
        pass


    def eomReceived(self):
        raise RuntimeError("Some problem, delivery is failing.")


    def connectionLost(self):
        pass



class DummyMessage(object):
    """
    L{BrokenMessage} is an L{IMessage} which saves the message delivered to it
    to its domain object.

    @ivar domain: A L{DummyDomain} which will be used to store the message once
        it is received.
    """
    def __init__(self, domain, user):
        self.domain = domain
        self.user = user
        self.buffer = []


    def lineReceived(self, line):
        # Throw away the generated Received: header
        if not re.match('Received: From yyy.com \(\[.*\]\) by localhost;', line):
            self.buffer.append(line)


    def eomReceived(self):
        message = '\n'.join(self.buffer) + '\n'
        self.domain.messages[self.user.dest.local].append(message)
        deferred = defer.Deferred()
        deferred.callback("saved")
        return deferred



class DummyDomain(object):
    """
    L{DummyDomain} is an L{IDomain} which keeps track of messages delivered to
    it in memory.
    """
    def __init__(self, names):
        self.messages = {}
        for name in names:
            self.messages[name] = []


    def exists(self, user):
        if user.dest.local in self.messages:
            return defer.succeed(lambda: self.startMessage(user))
        return defer.fail(smtp.SMTPBadRcpt(user))


    def startMessage(self, user):
        return DummyMessage(self, user)



class SMTPTestCase(unittest.TestCase):

    messages = [('foo@bar.com', ['foo@baz.com', 'qux@baz.com'], '''\
Subject: urgent\015
\015
Someone set up us the bomb!\015
''')]

    mbox = {'foo': ['Subject: urgent\n\nSomeone set up us the bomb!\n']}

    def setUp(self):
        """
        Create an in-memory mail domain to which messages may be delivered by
        tests and create a factory and transport to do the delivering.
        """
        self.factory = smtp.SMTPFactory()
        self.factory.domains = {}
        self.factory.domains['baz.com'] = DummyDomain(['foo'])
        self.transport = StringTransport()


    def testMessages(self):
        from twisted.mail import protocols
        protocol =  protocols.DomainSMTP()
        protocol.service = self.factory
        protocol.factory = self.factory
        protocol.receivedHeader = spameater
        protocol.makeConnection(self.transport)
        protocol.lineReceived('HELO yyy.com')
        for message in self.messages:
            protocol.lineReceived('MAIL FROM:<%s>' % message[0])
            for target in message[1]:
                protocol.lineReceived('RCPT TO:<%s>' % target)
            protocol.lineReceived('DATA')
            protocol.dataReceived(message[2])
            protocol.lineReceived('.')
        protocol.lineReceived('QUIT')
        if self.mbox != self.factory.domains['baz.com'].messages:
            raise AssertionError(self.factory.domains['baz.com'].messages)
        protocol.setTimeout(None)

    testMessages.suppress = [util.suppress(message='DomainSMTP', category=DeprecationWarning)]

mail = '''\
Subject: hello

Goodbye
'''

class MyClient:
    def __init__(self, messageInfo=None):
        if messageInfo is None:
            messageInfo = (
                'moshez@foo.bar', ['moshez@foo.bar'], StringIO(mail))
        self._sender = messageInfo[0]
        self._recipient = messageInfo[1]
        self._data = messageInfo[2]


    def getMailFrom(self):
        return self._sender


    def getMailTo(self):
        return self._recipient


    def getMailData(self):
        return self._data


    def sendError(self, exc):
        self._error = exc


    def sentMail(self, code, resp, numOk, addresses, log):
        # Prevent another mail from being sent.
        self._sender = None
        self._recipient = None
        self._data = None



class MySMTPClient(MyClient, smtp.SMTPClient):
    def __init__(self, messageInfo=None):
        smtp.SMTPClient.__init__(self, 'foo.baz')
        MyClient.__init__(self, messageInfo)

class MyESMTPClient(MyClient, smtp.ESMTPClient):
    def __init__(self, secret = '', contextFactory = None):
        smtp.ESMTPClient.__init__(self, secret, contextFactory, 'foo.baz')
        MyClient.__init__(self)

class LoopbackMixin:
    def loopback(self, server, client):
        return loopback.loopbackTCP(server, client)

class LoopbackTestCase(LoopbackMixin):
    def testMessages(self):
        factory = smtp.SMTPFactory()
        factory.domains = {}
        factory.domains['foo.bar'] = DummyDomain(['moshez'])
        from twisted.mail.protocols import DomainSMTP
        protocol =  DomainSMTP()
        protocol.service = factory
        protocol.factory = factory
        clientProtocol = self.clientClass()
        return self.loopback(protocol, clientProtocol)
    testMessages.suppress = [util.suppress(message='DomainSMTP', category=DeprecationWarning)]

class LoopbackSMTPTestCase(LoopbackTestCase, unittest.TestCase):
    clientClass = MySMTPClient

class LoopbackESMTPTestCase(LoopbackTestCase, unittest.TestCase):
    clientClass = MyESMTPClient


class FakeSMTPServer(basic.LineReceiver):

    clientData = [
        '220 hello', '250 nice to meet you',
        '250 great', '250 great', '354 go on, lad'
    ]

    def connectionMade(self):
        self.buffer = []
        self.clientData = self.clientData[:]
        self.clientData.reverse()
        self.sendLine(self.clientData.pop())

    def lineReceived(self, line):
        self.buffer.append(line)
        if line == "QUIT":
            self.transport.write("221 see ya around\r\n")
            self.transport.loseConnection()
        elif line == ".":
            self.transport.write("250 gotcha\r\n")
        elif line == "RSET":
            self.transport.loseConnection()

        if self.clientData:
            self.sendLine(self.clientData.pop())


class SMTPClientTestCase(unittest.TestCase, LoopbackMixin):
    """
    Tests for L{smtp.SMTPClient}.
    """

    def test_timeoutConnection(self):
        """
        L{smtp.SMTPClient.timeoutConnection} calls the C{sendError} hook with a
        fatal L{SMTPTimeoutError} with the current line log.
        """
        error = []
        client = MySMTPClient()
        client.sendError = error.append
        client.makeConnection(StringTransport())
        client.lineReceived("220 hello")
        client.timeoutConnection()
        self.assertIsInstance(error[0], smtp.SMTPTimeoutError)
        self.assertTrue(error[0].isFatal)
        self.assertEqual(
            str(error[0]),
            "Timeout waiting for SMTP server response\n"
            "<<< 220 hello\n"
            ">>> HELO foo.baz\n")


    expected_output = [
        'HELO foo.baz', 'MAIL FROM:<moshez@foo.bar>',
        'RCPT TO:<moshez@foo.bar>', 'DATA',
        'Subject: hello', '', 'Goodbye', '.', 'RSET'
    ]

    def test_messages(self):
        """
        L{smtp.SMTPClient} sends I{HELO}, I{MAIL FROM}, I{RCPT TO}, and I{DATA}
        commands based on the return values of its C{getMailFrom},
        C{getMailTo}, and C{getMailData} methods.
        """
        client = MySMTPClient()
        server = FakeSMTPServer()
        d = self.loopback(server, client)
        d.addCallback(lambda x :
                      self.assertEqual(server.buffer, self.expected_output))
        return d


    def test_transferError(self):
        """
        If there is an error while producing the message body to the
        connection, the C{sendError} callback is invoked.
        """
        client = MySMTPClient(
            ('alice@example.com', ['bob@example.com'], StringIO("foo")))
        transport = StringTransport()
        client.makeConnection(transport)
        client.dataReceived(
            '220 Ok\r\n' # Greeting
            '250 Ok\r\n' # EHLO response
            '250 Ok\r\n' # MAIL FROM response
            '250 Ok\r\n' # RCPT TO response
            '354 Ok\r\n' # DATA response
            )

        # Sanity check - a pull producer should be registered now.
        self.assertNotIdentical(transport.producer, None)
        self.assertFalse(transport.streaming)

        # Now stop the producer prematurely, meaning the message was not sent.
        transport.producer.stopProducing()

        # The sendError hook should have been invoked as a result.
        self.assertIsInstance(client._error, Exception)


    def test_sendFatalError(self):
        """
        If L{smtp.SMTPClient.sendError} is called with an L{SMTPClientError}
        which is fatal, it disconnects its transport without writing anything
        more to it.
        """
        client = smtp.SMTPClient(None)
        transport = StringTransport()
        client.makeConnection(transport)
        client.sendError(smtp.SMTPClientError(123, "foo", isFatal=True))
        self.assertEqual(transport.value(), "")
        self.assertTrue(transport.disconnecting)


    def test_sendNonFatalError(self):
        """
        If L{smtp.SMTPClient.sendError} is called with an L{SMTPClientError}
        which is not fatal, it sends C{"QUIT"} and waits for the server to
        close the connection.
        """
        client = smtp.SMTPClient(None)
        transport = StringTransport()
        client.makeConnection(transport)
        client.sendError(smtp.SMTPClientError(123, "foo", isFatal=False))
        self.assertEqual(transport.value(), "QUIT\r\n")
        self.assertFalse(transport.disconnecting)


    def test_sendOtherError(self):
        """
        If L{smtp.SMTPClient.sendError} is called with an exception which is
        not an L{SMTPClientError}, it disconnects its transport without
        writing anything more to it.
        """
        client = smtp.SMTPClient(None)
        transport = StringTransport()
        client.makeConnection(transport)
        client.sendError(Exception("foo"))
        self.assertEqual(transport.value(), "")
        self.assertTrue(transport.disconnecting)



class DummySMTPMessage:

    def __init__(self, protocol, users):
        self.protocol = protocol
        self.users = users
        self.buffer = []

    def lineReceived(self, line):
        self.buffer.append(line)

    def eomReceived(self):
        message = '\n'.join(self.buffer) + '\n'
        helo, origin = self.users[0].helo[0], str(self.users[0].orig)
        recipients = []
        for user in self.users:
            recipients.append(str(user))
        self.protocol.message[tuple(recipients)] = (helo, origin, recipients, message)
        return defer.succeed("saved")



class DummyProto:
    def connectionMade(self):
        self.dummyMixinBase.connectionMade(self)
        self.message = {}

    def startMessage(self, users):
        return DummySMTPMessage(self, users)

    def receivedHeader(*spam):
        return None

    def validateTo(self, user):
        self.delivery = SimpleDelivery(None)
        return lambda: self.startMessage([user])

    def validateFrom(self, helo, origin):
        return origin



class DummySMTP(DummyProto, smtp.SMTP):
    dummyMixinBase = smtp.SMTP

class DummyESMTP(DummyProto, smtp.ESMTP):
    dummyMixinBase = smtp.ESMTP

class AnotherTestCase:
    serverClass = None
    clientClass = None

    messages = [ ('foo.com', 'moshez@foo.com', ['moshez@bar.com'],
                  'moshez@foo.com', ['moshez@bar.com'], '''\
From: Moshe
To: Moshe

Hi,
how are you?
'''),
                 ('foo.com', 'tttt@rrr.com', ['uuu@ooo', 'yyy@eee'],
                  'tttt@rrr.com', ['uuu@ooo', 'yyy@eee'], '''\
Subject: pass

..rrrr..
'''),
                 ('foo.com', '@this,@is,@ignored:foo@bar.com',
                  ['@ignore,@this,@too:bar@foo.com'],
                  'foo@bar.com', ['bar@foo.com'], '''\
Subject: apa
To: foo

123
.
456
'''),
              ]

    data = [
        ('', '220.*\r\n$', None, None),
        ('HELO foo.com\r\n', '250.*\r\n$', None, None),
        ('RSET\r\n', '250.*\r\n$', None, None),
        ]
    for helo_, from_, to_, realfrom, realto, msg in messages:
        data.append(('MAIL FROM:<%s>\r\n' % from_, '250.*\r\n',
                     None, None))
        for rcpt in to_:
            data.append(('RCPT TO:<%s>\r\n' % rcpt, '250.*\r\n',
                         None, None))

        data.append(('DATA\r\n','354.*\r\n',
                     msg, ('250.*\r\n',
                           (helo_, realfrom, realto, msg))))


    def test_buffer(self):
        """
        Exercise a lot of the SMTP client code.  This is a "shotgun" style unit
        test.  It does a lot of things and hopes that something will go really
        wrong if it is going to go wrong.  This test should be replaced with a
        suite of nicer tests.
        """
        transport = StringTransport()
        a = self.serverClass()
        class fooFactory:
            domain = 'foo.com'

        a.factory = fooFactory()
        a.makeConnection(transport)
        for (send, expect, msg, msgexpect) in self.data:
            if send:
                a.dataReceived(send)
            data = transport.value()
            transport.clear()
            if not re.match(expect, data):
                raise AssertionError, (send, expect, data)
            if data[:3] == '354':
                for line in msg.splitlines():
                    if line and line[0] == '.':
                        line = '.' + line
                    a.dataReceived(line + '\r\n')
                a.dataReceived('.\r\n')
                # Special case for DATA. Now we want a 250, and then
                # we compare the messages
                data = transport.value()
                transport.clear()
                resp, msgdata = msgexpect
                if not re.match(resp, data):
                    raise AssertionError, (resp, data)
                for recip in msgdata[2]:
                    expected = list(msgdata[:])
                    expected[2] = [recip]
                    self.assertEqual(
                        a.message[(recip,)],
                        tuple(expected)
                    )
        a.setTimeout(None)


class AnotherESMTPTestCase(AnotherTestCase, unittest.TestCase):
    serverClass = DummyESMTP
    clientClass = MyESMTPClient

class AnotherSMTPTestCase(AnotherTestCase, unittest.TestCase):
    serverClass = DummySMTP
    clientClass = MySMTPClient



class DummyChecker:
    implements(cred.checkers.ICredentialsChecker)

    users = {
        'testuser': 'testpassword'
    }

    credentialInterfaces = (cred.credentials.IUsernamePassword,
                            cred.credentials.IUsernameHashedPassword)

    def requestAvatarId(self, credentials):
        return defer.maybeDeferred(
            credentials.checkPassword, self.users[credentials.username]
        ).addCallback(self._cbCheck, credentials.username)

    def _cbCheck(self, result, username):
        if result:
            return username
        raise cred.error.UnauthorizedLogin()



class SimpleDelivery(object):
    """
    L{SimpleDelivery} is a message delivery factory with no interesting
    behavior.
    """
    implements(smtp.IMessageDelivery)

    def __init__(self, messageFactory):
        self._messageFactory = messageFactory


    def receivedHeader(self, helo, origin, recipients):
        return None


    def validateFrom(self, helo, origin):
        return origin


    def validateTo(self, user):
        return lambda: self._messageFactory(user)



class DummyRealm:
    def requestAvatar(self, avatarId, mind, *interfaces):
        return smtp.IMessageDelivery, SimpleDelivery(None), lambda: None



class AuthTestCase(unittest.TestCase, LoopbackMixin):
    def test_crammd5Auth(self):
        """
        L{ESMTPClient} can authenticate using the I{CRAM-MD5} SASL mechanism.

        @see: U{http://tools.ietf.org/html/rfc2195}
        """
        realm = DummyRealm()
        p = cred.portal.Portal(realm)
        p.registerChecker(DummyChecker())

        server = DummyESMTP({'CRAM-MD5': cred.credentials.CramMD5Credentials})
        server.portal = p
        client = MyESMTPClient('testpassword')

        cAuth = smtp.CramMD5ClientAuthenticator('testuser')
        client.registerAuthenticator(cAuth)

        d = self.loopback(server, client)
        d.addCallback(lambda x : self.assertEqual(server.authenticated, 1))
        return d


    def test_loginAuth(self):
        """
        L{ESMTPClient} can authenticate using the I{LOGIN} SASL mechanism.

        @see: U{http://sepp.oetiker.ch/sasl-2.1.19-ds/draft-murchison-sasl-login-00.txt}
        """
        realm = DummyRealm()
        p = cred.portal.Portal(realm)
        p.registerChecker(DummyChecker())

        server = DummyESMTP({'LOGIN': imap4.LOGINCredentials})
        server.portal = p
        client = MyESMTPClient('testpassword')

        cAuth = smtp.LOGINAuthenticator('testuser')
        client.registerAuthenticator(cAuth)

        d = self.loopback(server, client)
        d.addCallback(lambda x: self.assertTrue(server.authenticated))
        return d


    def test_loginAgainstWeirdServer(self):
        """
        When communicating with a server which implements the I{LOGIN} SASL
        mechanism using C{"Username:"} as the challenge (rather than C{"User
        Name\\0"}), L{ESMTPClient} can still authenticate successfully using
        the I{LOGIN} mechanism.
        """
        realm = DummyRealm()
        p = cred.portal.Portal(realm)
        p.registerChecker(DummyChecker())

        server = DummyESMTP({'LOGIN': smtp.LOGINCredentials})
        server.portal = p

        client = MyESMTPClient('testpassword')
        cAuth = smtp.LOGINAuthenticator('testuser')
        client.registerAuthenticator(cAuth)

        d = self.loopback(server, client)
        d.addCallback(lambda x: self.assertTrue(server.authenticated))
        return d



class SMTPHelperTestCase(unittest.TestCase):
    def testMessageID(self):
        d = {}
        for i in range(1000):
            m = smtp.messageid('testcase')
            self.failIf(m in d)
            d[m] = None

    def testQuoteAddr(self):
        cases = [
            ['user@host.name', '<user@host.name>'],
            ['"User Name" <user@host.name>', '<user@host.name>'],
            [smtp.Address('someguy@someplace'), '<someguy@someplace>'],
            ['', '<>'],
            [smtp.Address(''), '<>'],
        ]

        for (c, e) in cases:
            self.assertEqual(smtp.quoteaddr(c), e)

    def testUser(self):
        u = smtp.User('user@host', 'helo.host.name', None, None)
        self.assertEqual(str(u), 'user@host')

    def testXtextEncoding(self):
        cases = [
            ('Hello world', 'Hello+20world'),
            ('Hello+world', 'Hello+2Bworld'),
            ('\0\1\2\3\4\5', '+00+01+02+03+04+05'),
            ('e=mc2@example.com', 'e+3Dmc2@example.com')
        ]

        for (case, expected) in cases:
            self.assertEqual(smtp.xtext_encode(case), (expected, len(case)))
            self.assertEqual(case.encode('xtext'), expected)
            self.assertEqual(
                smtp.xtext_decode(expected), (case, len(expected)))
            self.assertEqual(expected.decode('xtext'), case)


    def test_encodeWithErrors(self):
        """
        Specifying an error policy to C{unicode.encode} with the
        I{xtext} codec should produce the same result as not
        specifying the error policy.
        """
        text = u'Hello world'
        self.assertEqual(
            smtp.xtext_encode(text, 'strict'),
            (text.encode('xtext'), len(text)))
        self.assertEqual(
            text.encode('xtext', 'strict'),
            text.encode('xtext'))


    def test_decodeWithErrors(self):
        """
        Similar to L{test_encodeWithErrors}, but for C{str.decode}.
        """
        bytes = 'Hello world'
        self.assertEqual(
            smtp.xtext_decode(bytes, 'strict'),
            (bytes.decode('xtext'), len(bytes)))
        self.assertEqual(
            bytes.decode('xtext', 'strict'),
            bytes.decode('xtext'))



class NoticeTLSClient(MyESMTPClient):
    tls = False

    def esmtpState_starttls(self, code, resp):
        MyESMTPClient.esmtpState_starttls(self, code, resp)
        self.tls = True

class TLSTestCase(unittest.TestCase, LoopbackMixin):
    def testTLS(self):
        clientCTX = ClientTLSContext()
        serverCTX = ServerTLSContext()

        client = NoticeTLSClient(contextFactory=clientCTX)
        server = DummyESMTP(contextFactory=serverCTX)

        def check(ignored):
            self.assertEqual(client.tls, True)
            self.assertEqual(server.startedTLS, True)

        return self.loopback(server, client).addCallback(check)

if ClientTLSContext is None:
    for case in (TLSTestCase,):
        case.skip = "OpenSSL not present"

if not interfaces.IReactorSSL.providedBy(reactor):
    for case in (TLSTestCase,):
        case.skip = "Reactor doesn't support SSL"

class EmptyLineTestCase(unittest.TestCase):
    def test_emptyLineSyntaxError(self):
        """
        If L{smtp.SMTP} receives an empty line, it responds with a 500 error
        response code and a message about a syntax error.
        """
        proto = smtp.SMTP()
        transport = StringTransport()
        proto.makeConnection(transport)
        proto.lineReceived('')
        proto.setTimeout(None)

        out = transport.value().splitlines()
        self.assertEqual(len(out), 2)
        self.failUnless(out[0].startswith('220'))
        self.assertEqual(out[1], "500 Error: bad syntax")



class TimeoutTestCase(unittest.TestCase, LoopbackMixin):
    """
    Check that SMTP client factories correctly use the timeout.
    """

    def _timeoutTest(self, onDone, clientFactory):
        """
        Connect the clientFactory, and check the timeout on the request.
        """
        clock = task.Clock()
        client = clientFactory.buildProtocol(
            address.IPv4Address('TCP', 'example.net', 25))
        client.callLater = clock.callLater
        t = StringTransport()
        client.makeConnection(t)
        t.protocol = client
        def check(ign):
            self.assertEqual(clock.seconds(), 0.5)
        d = self.assertFailure(onDone, smtp.SMTPTimeoutError
            ).addCallback(check)
        # The first call should not trigger the timeout
        clock.advance(0.1)
        # But this one should
        clock.advance(0.4)
        return d


    def test_SMTPClient(self):
        """
        Test timeout for L{smtp.SMTPSenderFactory}: the response L{Deferred}
        should be errback with a L{smtp.SMTPTimeoutError}.
        """
        onDone = defer.Deferred()
        clientFactory = smtp.SMTPSenderFactory(
            'source@address', 'recipient@address',
            StringIO("Message body"), onDone,
            retries=0, timeout=0.5)
        return self._timeoutTest(onDone, clientFactory)


    def test_ESMTPClient(self):
        """
        Test timeout for L{smtp.ESMTPSenderFactory}: the response L{Deferred}
        should be errback with a L{smtp.SMTPTimeoutError}.
        """
        onDone = defer.Deferred()
        clientFactory = smtp.ESMTPSenderFactory(
            'username', 'password',
            'source@address', 'recipient@address',
            StringIO("Message body"), onDone,
            retries=0, timeout=0.5)
        return self._timeoutTest(onDone, clientFactory)


    def test_resetTimeoutWhileSending(self):
        """
        The timeout is not allowed to expire after the server has accepted a
        DATA command and the client is actively sending data to it.
        """
        class SlowFile:
            """
            A file-like which returns one byte from each read call until the
            specified number of bytes have been returned.
            """
            def __init__(self, size):
                self._size = size

            def read(self, max=None):
                if self._size:
                    self._size -= 1
                    return 'x'
                return ''

        failed = []
        onDone = defer.Deferred()
        onDone.addErrback(failed.append)
        clientFactory = smtp.SMTPSenderFactory(
            'source@address', 'recipient@address',
            SlowFile(1), onDone, retries=0, timeout=3)
        clientFactory.domain = "example.org"
        clock = task.Clock()
        client = clientFactory.buildProtocol(
            address.IPv4Address('TCP', 'example.net', 25))
        client.callLater = clock.callLater
        transport = StringTransport()
        client.makeConnection(transport)

        client.dataReceived(
            "220 Ok\r\n" # Greet the client
            "250 Ok\r\n" # Respond to HELO
            "250 Ok\r\n" # Respond to MAIL FROM
            "250 Ok\r\n" # Respond to RCPT TO
            "354 Ok\r\n" # Respond to DATA
            )

        # Now the client is producing data to the server.  Any time
        # resumeProducing is called on the producer, the timeout should be
        # extended.  First, a sanity check.  This test is only written to
        # handle pull producers.
        self.assertNotIdentical(transport.producer, None)
        self.assertFalse(transport.streaming)

        # Now, allow 2 seconds (1 less than the timeout of 3 seconds) to
        # elapse.
        clock.advance(2)

        # The timeout has not expired, so the failure should not have happened.
        self.assertEqual(failed, [])

        # Let some bytes be produced, extending the timeout.  Then advance the
        # clock some more and verify that the timeout still hasn't happened.
        transport.producer.resumeProducing()
        clock.advance(2)
        self.assertEqual(failed, [])

        # The file has been completely produced - the next resume producing
        # finishes the upload, successfully.
        transport.producer.resumeProducing()
        client.dataReceived("250 Ok\r\n")
        self.assertEqual(failed, [])

        # Verify that the client actually did send the things expected.
        self.assertEqual(
            transport.value(),
            "HELO example.org\r\n"
            "MAIL FROM:<source@address>\r\n"
            "RCPT TO:<recipient@address>\r\n"
            "DATA\r\n"
            "x\r\n"
            ".\r\n"
            # This RSET is just an implementation detail.  It's nice, but this
            # test doesn't really care about it.
            "RSET\r\n")



class MultipleDeliveryFactorySMTPServerFactory(protocol.ServerFactory):
    """
    L{MultipleDeliveryFactorySMTPServerFactory} creates SMTP server protocol
    instances with message delivery factory objects supplied to it.  Each
    factory is used for one connection and then discarded.  Factories are used
    in the order they are supplied.
    """
    def __init__(self, messageFactories):
        self._messageFactories = messageFactories


    def buildProtocol(self, addr):
        p = protocol.ServerFactory.buildProtocol(self, addr)
        p.delivery = SimpleDelivery(self._messageFactories.pop(0))
        return p



class SMTPSenderFactoryRetryTestCase(unittest.TestCase):
    """
    Tests for the retry behavior of L{smtp.SMTPSenderFactory}.
    """
    def test_retryAfterDisconnect(self):
        """
        If the protocol created by L{SMTPSenderFactory} loses its connection
        before receiving confirmation of message delivery, it reconnects and
        tries to deliver the message again.
        """
        recipient = 'alice'
        message = "some message text"
        domain = DummyDomain([recipient])

        class CleanSMTP(smtp.SMTP):
            """
            An SMTP subclass which ensures that its transport will be
            disconnected before the test ends.
            """
            def makeConnection(innerSelf, transport):
                self.addCleanup(transport.loseConnection)
                smtp.SMTP.makeConnection(innerSelf, transport)

        # Create a server which will fail the first message deliver attempt to
        # it with a 500 and a disconnect, but which will accept a message
        # delivered over the 2nd connection to it.
        serverFactory = MultipleDeliveryFactorySMTPServerFactory([
                BrokenMessage,
                lambda user: DummyMessage(domain, user)])
        serverFactory.protocol = CleanSMTP
        serverPort = reactor.listenTCP(0, serverFactory, interface='127.0.0.1')
        serverHost = serverPort.getHost()
        self.addCleanup(serverPort.stopListening)

        # Set up a client to try to deliver a message to the above created
        # server.
        sentDeferred = defer.Deferred()
        clientFactory = smtp.SMTPSenderFactory(
            "bob@example.org", recipient + "@example.com",
            StringIO(message), sentDeferred)
        clientFactory.domain = "example.org"
        clientConnector = reactor.connectTCP(
            serverHost.host, serverHost.port, clientFactory)
        self.addCleanup(clientConnector.disconnect)

        def cbSent(ignored):
            """
            Verify that the message was successfully delivered and flush the
            error which caused the first attempt to fail.
            """
            self.assertEqual(
                domain.messages,
                {recipient: ["\n%s\n" % (message,)]})
            # Flush the RuntimeError that BrokenMessage caused to be logged.
            self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)
        sentDeferred.addCallback(cbSent)
        return sentDeferred



class SingletonRealm(object):
    """
    Trivial realm implementation which is constructed with an interface and an
    avatar and returns that avatar when asked for that interface.
    """
    implements(IRealm)

    def __init__(self, interface, avatar):
        self.interface = interface
        self.avatar = avatar


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



class NotImplementedDelivery(object):
    """
    Non-implementation of L{smtp.IMessageDelivery} which only has methods which
    raise L{NotImplementedError}.  Subclassed by various tests to provide the
    particular behavior being tested.
    """
    def validateFrom(self, helo, origin):
        raise NotImplementedError("This oughtn't be called in the course of this test.")


    def validateTo(self, user):
        raise NotImplementedError("This oughtn't be called in the course of this test.")


    def receivedHeader(self, helo, origin, recipients):
        raise NotImplementedError("This oughtn't be called in the course of this test.")



class SMTPServerTestCase(unittest.TestCase):
    """
    Test various behaviors of L{twisted.mail.smtp.SMTP} and
    L{twisted.mail.smtp.ESMTP}.
    """
    def testSMTPGreetingHost(self, serverClass=smtp.SMTP):
        """
        Test that the specified hostname shows up in the SMTP server's
        greeting.
        """
        s = serverClass()
        s.host = "example.com"
        t = StringTransport()
        s.makeConnection(t)
        s.connectionLost(error.ConnectionDone())
        self.assertIn("example.com", t.value())


    def testSMTPGreetingNotExtended(self):
        """
        Test that the string "ESMTP" does not appear in the SMTP server's
        greeting since that string strongly suggests the presence of support
        for various SMTP extensions which are not supported by L{smtp.SMTP}.
        """
        s = smtp.SMTP()
        t = StringTransport()
        s.makeConnection(t)
        s.connectionLost(error.ConnectionDone())
        self.assertNotIn("ESMTP", t.value())


    def testESMTPGreetingHost(self):
        """
        Similar to testSMTPGreetingHost, but for the L{smtp.ESMTP} class.
        """
        self.testSMTPGreetingHost(smtp.ESMTP)


    def testESMTPGreetingExtended(self):
        """
        Test that the string "ESMTP" does appear in the ESMTP server's
        greeting since L{smtp.ESMTP} does support the SMTP extensions which
        that advertises to the client.
        """
        s = smtp.ESMTP()
        t = StringTransport()
        s.makeConnection(t)
        s.connectionLost(error.ConnectionDone())
        self.assertIn("ESMTP", t.value())


    def test_acceptSenderAddress(self):
        """
        Test that a C{MAIL FROM} command with an acceptable address is
        responded to with the correct success code.
        """
        class AcceptanceDelivery(NotImplementedDelivery):
            """
            Delivery object which accepts all senders as valid.
            """
            def validateFrom(self, helo, origin):
                return origin

        realm = SingletonRealm(smtp.IMessageDelivery, AcceptanceDelivery())
        portal = Portal(realm, [AllowAnonymousAccess()])
        proto = smtp.SMTP()
        proto.portal = portal
        trans = StringTransport()
        proto.makeConnection(trans)

        # Deal with the necessary preliminaries
        proto.dataReceived('HELO example.com\r\n')
        trans.clear()

        # Try to specify our sender address
        proto.dataReceived('MAIL FROM:<alice@example.com>\r\n')

        # Clean up the protocol before doing anything that might raise an
        # exception.
        proto.connectionLost(error.ConnectionLost())

        # Make sure that we received exactly the correct response
        self.assertEqual(
            trans.value(),
            '250 Sender address accepted\r\n')


    def test_deliveryRejectedSenderAddress(self):
        """
        Test that a C{MAIL FROM} command with an address rejected by a
        L{smtp.IMessageDelivery} instance is responded to with the correct
        error code.
        """
        class RejectionDelivery(NotImplementedDelivery):
            """
            Delivery object which rejects all senders as invalid.
            """
            def validateFrom(self, helo, origin):
                raise smtp.SMTPBadSender(origin)

        realm = SingletonRealm(smtp.IMessageDelivery, RejectionDelivery())
        portal = Portal(realm, [AllowAnonymousAccess()])
        proto = smtp.SMTP()
        proto.portal = portal
        trans = StringTransport()
        proto.makeConnection(trans)

        # Deal with the necessary preliminaries
        proto.dataReceived('HELO example.com\r\n')
        trans.clear()

        # Try to specify our sender address
        proto.dataReceived('MAIL FROM:<alice@example.com>\r\n')

        # Clean up the protocol before doing anything that might raise an
        # exception.
        proto.connectionLost(error.ConnectionLost())

        # Make sure that we received exactly the correct response
        self.assertEqual(
            trans.value(),
            '550 Cannot receive from specified address '
            '<alice@example.com>: Sender not acceptable\r\n')


    def test_portalRejectedSenderAddress(self):
        """
        Test that a C{MAIL FROM} command with an address rejected by an
        L{smtp.SMTP} instance's portal is responded to with the correct error
        code.
        """
        class DisallowAnonymousAccess(object):
            """
            Checker for L{IAnonymous} which rejects authentication attempts.
            """
            implements(ICredentialsChecker)

            credentialInterfaces = (IAnonymous,)

            def requestAvatarId(self, credentials):
                return defer.fail(UnauthorizedLogin())

        realm = SingletonRealm(smtp.IMessageDelivery, NotImplementedDelivery())
        portal = Portal(realm, [DisallowAnonymousAccess()])
        proto = smtp.SMTP()
        proto.portal = portal
        trans = StringTransport()
        proto.makeConnection(trans)

        # Deal with the necessary preliminaries
        proto.dataReceived('HELO example.com\r\n')
        trans.clear()

        # Try to specify our sender address
        proto.dataReceived('MAIL FROM:<alice@example.com>\r\n')

        # Clean up the protocol before doing anything that might raise an
        # exception.
        proto.connectionLost(error.ConnectionLost())

        # Make sure that we received exactly the correct response
        self.assertEqual(
            trans.value(),
            '550 Cannot receive from specified address '
            '<alice@example.com>: Sender not acceptable\r\n')


    def test_portalRejectedAnonymousSender(self):
        """
        Test that a C{MAIL FROM} command issued without first authenticating
        when a portal has been configured to disallow anonymous logins is
        responded to with the correct error code.
        """
        realm = SingletonRealm(smtp.IMessageDelivery, NotImplementedDelivery())
        portal = Portal(realm, [])
        proto = smtp.SMTP()
        proto.portal = portal
        trans = StringTransport()
        proto.makeConnection(trans)

        # Deal with the necessary preliminaries
        proto.dataReceived('HELO example.com\r\n')
        trans.clear()

        # Try to specify our sender address
        proto.dataReceived('MAIL FROM:<alice@example.com>\r\n')

        # Clean up the protocol before doing anything that might raise an
        # exception.
        proto.connectionLost(error.ConnectionLost())

        # Make sure that we received exactly the correct response
        self.assertEqual(
            trans.value(),
            '550 Cannot receive from specified address '
            '<alice@example.com>: Unauthenticated senders not allowed\r\n')



class ESMTPAuthenticationTestCase(unittest.TestCase):
    def assertServerResponse(self, bytes, response):
        """
        Assert that when the given bytes are delivered to the ESMTP server
        instance, it responds with the indicated lines.

        @type bytes: str
        @type response: list of str
        """
        self.transport.clear()
        self.server.dataReceived(bytes)
        self.assertEqual(
            response,
            self.transport.value().splitlines())


    def assertServerAuthenticated(self, loginArgs, username="username", password="password"):
        """
        Assert that a login attempt has been made, that the credentials and
        interfaces passed to it are correct, and that when the login request
        is satisfied, a successful response is sent by the ESMTP server
        instance.

        @param loginArgs: A C{list} previously passed to L{portalFactory}.
        """
        d, credentials, mind, interfaces = loginArgs.pop()
        self.assertEqual(loginArgs, [])
        self.failUnless(twisted.cred.credentials.IUsernamePassword.providedBy(credentials))
        self.assertEqual(credentials.username, username)
        self.failUnless(credentials.checkPassword(password))
        self.assertIn(smtp.IMessageDeliveryFactory, interfaces)
        self.assertIn(smtp.IMessageDelivery, interfaces)
        d.callback((smtp.IMessageDeliveryFactory, None, lambda: None))

        self.assertEqual(
            ["235 Authentication successful."],
            self.transport.value().splitlines())


    def setUp(self):
        """
        Create an ESMTP instance attached to a StringTransport.
        """
        self.server = smtp.ESMTP({
                'LOGIN': imap4.LOGINCredentials})
        self.server.host = 'localhost'
        self.transport = StringTransport(
            peerAddress=address.IPv4Address('TCP', '127.0.0.1', 12345))
        self.server.makeConnection(self.transport)


    def tearDown(self):
        """
        Disconnect the ESMTP instance to clean up its timeout DelayedCall.
        """
        self.server.connectionLost(error.ConnectionDone())


    def portalFactory(self, loginList):
        class DummyPortal:
            def login(self, credentials, mind, *interfaces):
                d = defer.Deferred()
                loginList.append((d, credentials, mind, interfaces))
                return d
        return DummyPortal()


    def test_authenticationCapabilityAdvertised(self):
        """
        Test that AUTH is advertised to clients which issue an EHLO command.
        """
        self.transport.clear()
        self.server.dataReceived('EHLO\r\n')
        responseLines = self.transport.value().splitlines()
        self.assertEqual(
            responseLines[0],
            "250-localhost Hello 127.0.0.1, nice to meet you")
        self.assertEqual(
            responseLines[1],
            "250 AUTH LOGIN")
        self.assertEqual(len(responseLines), 2)


    def test_plainAuthentication(self):
        """
        Test that the LOGIN authentication mechanism can be used
        """
        loginArgs = []
        self.server.portal = self.portalFactory(loginArgs)

        self.server.dataReceived('EHLO\r\n')
        self.transport.clear()

        self.assertServerResponse(
            'AUTH LOGIN\r\n',
            ["334 " + "User Name\0".encode('base64').strip()])

        self.assertServerResponse(
            'username'.encode('base64') + '\r\n',
            ["334 " + "Password\0".encode('base64').strip()])

        self.assertServerResponse(
            'password'.encode('base64').strip() + '\r\n',
            [])

        self.assertServerAuthenticated(loginArgs)


    def test_plainAuthenticationEmptyPassword(self):
        """
        Test that giving an empty password for plain auth succeeds.
        """
        loginArgs = []
        self.server.portal = self.portalFactory(loginArgs)

        self.server.dataReceived('EHLO\r\n')
        self.transport.clear()

        self.assertServerResponse(
            'AUTH LOGIN\r\n',
            ["334 " + "User Name\0".encode('base64').strip()])

        self.assertServerResponse(
            'username'.encode('base64') + '\r\n',
            ["334 " + "Password\0".encode('base64').strip()])

        self.assertServerResponse('\r\n', [])
        self.assertServerAuthenticated(loginArgs, password='')


    def test_plainAuthenticationInitialResponse(self):
        """
        The response to the first challenge may be included on the AUTH command
        line.  Test that this is also supported.
        """
        loginArgs = []
        self.server.portal = self.portalFactory(loginArgs)

        self.server.dataReceived('EHLO\r\n')
        self.transport.clear()

        self.assertServerResponse(
            'AUTH LOGIN ' + "username".encode('base64').strip() + '\r\n',
            ["334 " + "Password\0".encode('base64').strip()])

        self.assertServerResponse(
            'password'.encode('base64').strip() + '\r\n',
            [])

        self.assertServerAuthenticated(loginArgs)


    def test_abortAuthentication(self):
        """
        Test that a challenge/response sequence can be aborted by the client.
        """
        loginArgs = []
        self.server.portal = self.portalFactory(loginArgs)

        self.server.dataReceived('EHLO\r\n')
        self.server.dataReceived('AUTH LOGIN\r\n')

        self.assertServerResponse(
            '*\r\n',
            ['501 Authentication aborted'])


    def test_invalidBase64EncodedResponse(self):
        """
        Test that a response which is not properly Base64 encoded results in
        the appropriate error code.
        """
        loginArgs = []
        self.server.portal = self.portalFactory(loginArgs)

        self.server.dataReceived('EHLO\r\n')
        self.server.dataReceived('AUTH LOGIN\r\n')

        self.assertServerResponse(
            'x\r\n',
            ['501 Syntax error in parameters or arguments'])

        self.assertEqual(loginArgs, [])


    def test_invalidBase64EncodedInitialResponse(self):
        """
        Like L{test_invalidBase64EncodedResponse} but for the case of an
        initial response included with the C{AUTH} command.
        """
        loginArgs = []
        self.server.portal = self.portalFactory(loginArgs)

        self.server.dataReceived('EHLO\r\n')
        self.assertServerResponse(
            'AUTH LOGIN x\r\n',
            ['501 Syntax error in parameters or arguments'])

        self.assertEqual(loginArgs, [])


    def test_unexpectedLoginFailure(self):
        """
        If the L{Deferred} returned by L{Portal.login} fires with an
        exception of any type other than L{UnauthorizedLogin}, the exception
        is logged and the client is informed that the authentication attempt
        has failed.
        """
        loginArgs = []
        self.server.portal = self.portalFactory(loginArgs)

        self.server.dataReceived('EHLO\r\n')
        self.transport.clear()

        self.assertServerResponse(
            'AUTH LOGIN ' + 'username'.encode('base64').strip() + '\r\n',
            ['334 ' + 'Password\0'.encode('base64').strip()])
        self.assertServerResponse(
            'password'.encode('base64').strip() + '\r\n',
            [])

        d, credentials, mind, interfaces = loginArgs.pop()
        d.errback(RuntimeError("Something wrong with the server"))

        self.assertEqual(
            '451 Requested action aborted: local error in processing\r\n',
            self.transport.value())

        self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)



class SMTPClientErrorTestCase(unittest.TestCase):
    """
    Tests for L{smtp.SMTPClientError}.
    """
    def test_str(self):
        """
        The string representation of a L{SMTPClientError} instance includes
        the response code and response string.
        """
        err = smtp.SMTPClientError(123, "some text")
        self.assertEqual(str(err), "123 some text")


    def test_strWithNegativeCode(self):
        """
        If the response code supplied to L{SMTPClientError} is negative, it
        is excluded from the string representation.
        """
        err = smtp.SMTPClientError(-1, "foo bar")
        self.assertEqual(str(err), "foo bar")


    def test_strWithLog(self):
        """
        If a line log is supplied to L{SMTPClientError}, its contents are
        included in the string representation of the exception instance.
        """
        log = LineLog(10)
        log.append("testlog")
        log.append("secondline")
        err = smtp.SMTPClientError(100, "test error", log=log.str())
        self.assertEqual(
            str(err),
            "100 test error\n"
            "testlog\n"
            "secondline\n")



class SenderMixinSentMailTests(unittest.TestCase):
    """
    Tests for L{smtp.SenderMixin.sentMail}, used in particular by
    L{smtp.SMTPSenderFactory} and L{smtp.ESMTPSenderFactory}.
    """
    def test_onlyLogFailedAddresses(self):
        """
        L{smtp.SenderMixin.sentMail} adds only the addresses with failing
        SMTP response codes to the log passed to the factory's errback.
        """
        onDone = self.assertFailure(defer.Deferred(), smtp.SMTPDeliveryError)
        onDone.addCallback(lambda e: self.assertEqual(
                e.log, "bob@example.com: 199 Error in sending.\n"))

        clientFactory = smtp.SMTPSenderFactory(
            'source@address', 'recipient@address',
            StringIO("Message body"), onDone,
            retries=0, timeout=0.5)

        client = clientFactory.buildProtocol(
            address.IPv4Address('TCP', 'example.net', 25))

        addresses = [("alice@example.com", 200, "No errors here!"),
                     ("bob@example.com", 199, "Error in sending.")]
        client.sentMail(199, "Test response", 1, addresses, client.log)

        return onDone