blob: 703b631c175b8a55eb3b47003acbe44d32f6b77e [file] [log] [blame]
Facundo Batista16ed5b42007-07-24 21:20:42 +00001import asyncore
Facundo Batista1bc8d632007-08-21 16:57:18 +00002import email.utils
Facundo Batista366d6262007-03-28 18:25:54 +00003import socket
Facundo Batista16ed5b42007-07-24 21:20:42 +00004import smtpd
Facundo Batista366d6262007-03-28 18:25:54 +00005import smtplib
Facundo Batista16ed5b42007-07-24 21:20:42 +00006import StringIO
7import sys
Facundo Batista366d6262007-03-28 18:25:54 +00008import time
Facundo Batista16ed5b42007-07-24 21:20:42 +00009import select
Facundo Batista366d6262007-03-28 18:25:54 +000010
Victor Stinner6a102812010-04-27 23:55:59 +000011import unittest
Facundo Batista366d6262007-03-28 18:25:54 +000012from test import test_support
13
Victor Stinner6a102812010-04-27 23:55:59 +000014try:
15 import threading
16except ImportError:
17 threading = None
18
Trent Nelsone41b0062008-04-08 23:47:30 +000019HOST = test_support.HOST
Facundo Batista366d6262007-03-28 18:25:54 +000020
Trent Nelsone41b0062008-04-08 23:47:30 +000021def server(evt, buf, serv):
Neal Norwitz75992ed2008-02-26 08:04:59 +000022 serv.listen(5)
23 evt.set()
Facundo Batista366d6262007-03-28 18:25:54 +000024 try:
25 conn, addr = serv.accept()
26 except socket.timeout:
27 pass
28 else:
Facundo Batista412b8b62007-08-01 23:18:36 +000029 n = 500
Facundo Batista16ed5b42007-07-24 21:20:42 +000030 while buf and n > 0:
31 r, w, e = select.select([], [conn], [])
32 if w:
33 sent = conn.send(buf)
34 buf = buf[sent:]
35
36 n -= 1
Facundo Batista16ed5b42007-07-24 21:20:42 +000037
Facundo Batista366d6262007-03-28 18:25:54 +000038 conn.close()
39 finally:
40 serv.close()
41 evt.set()
42
Victor Stinner6a102812010-04-27 23:55:59 +000043@unittest.skipUnless(threading, 'Threading required for this test.')
44class GeneralTests(unittest.TestCase):
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000045
Facundo Batista366d6262007-03-28 18:25:54 +000046 def setUp(self):
Antoine Pitroua763c062009-10-27 19:47:30 +000047 self._threads = test_support.threading_setup()
Facundo Batista366d6262007-03-28 18:25:54 +000048 self.evt = threading.Event()
Trent Nelsone41b0062008-04-08 23:47:30 +000049 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
50 self.sock.settimeout(15)
51 self.port = test_support.bind_port(self.sock)
52 servargs = (self.evt, "220 Hola mundo\n", self.sock)
Antoine Pitroua763c062009-10-27 19:47:30 +000053 self.thread = threading.Thread(target=server, args=servargs)
54 self.thread.start()
Neal Norwitz75992ed2008-02-26 08:04:59 +000055 self.evt.wait()
56 self.evt.clear()
Facundo Batista366d6262007-03-28 18:25:54 +000057
58 def tearDown(self):
59 self.evt.wait()
Antoine Pitroua763c062009-10-27 19:47:30 +000060 self.thread.join()
61 test_support.threading_cleanup(*self._threads)
Facundo Batista366d6262007-03-28 18:25:54 +000062
Facundo Batista16ed5b42007-07-24 21:20:42 +000063 def testBasic1(self):
Facundo Batista366d6262007-03-28 18:25:54 +000064 # connects
Trent Nelsone41b0062008-04-08 23:47:30 +000065 smtp = smtplib.SMTP(HOST, self.port)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000066 smtp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000067
Facundo Batista16ed5b42007-07-24 21:20:42 +000068 def testBasic2(self):
69 # connects, include port in host name
Trent Nelsone41b0062008-04-08 23:47:30 +000070 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000071 smtp.close()
Facundo Batista16ed5b42007-07-24 21:20:42 +000072
73 def testLocalHostName(self):
74 # check that supplied local_hostname is used
Trent Nelsone41b0062008-04-08 23:47:30 +000075 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Facundo Batista16ed5b42007-07-24 21:20:42 +000076 self.assertEqual(smtp.local_hostname, "testhost")
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000077 smtp.close()
Facundo Batista16ed5b42007-07-24 21:20:42 +000078
Facundo Batista366d6262007-03-28 18:25:54 +000079 def testTimeoutDefault(self):
Serhiy Storchaka79b6f172014-02-08 15:05:53 +020080 self.assertIsNone(socket.getdefaulttimeout())
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000081 socket.setdefaulttimeout(30)
82 try:
83 smtp = smtplib.SMTP(HOST, self.port)
84 finally:
85 socket.setdefaulttimeout(None)
Facundo Batista366d6262007-03-28 18:25:54 +000086 self.assertEqual(smtp.sock.gettimeout(), 30)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000087 smtp.close()
Facundo Batista366d6262007-03-28 18:25:54 +000088
89 def testTimeoutNone(self):
Serhiy Storchaka79b6f172014-02-08 15:05:53 +020090 self.assertIsNone(socket.getdefaulttimeout())
Facundo Batista366d6262007-03-28 18:25:54 +000091 socket.setdefaulttimeout(30)
92 try:
Trent Nelsone41b0062008-04-08 23:47:30 +000093 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Facundo Batista366d6262007-03-28 18:25:54 +000094 finally:
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000095 socket.setdefaulttimeout(None)
Serhiy Storchaka79b6f172014-02-08 15:05:53 +020096 self.assertIsNone(smtp.sock.gettimeout())
Facundo Batista4f1b1ed2008-05-29 16:39:26 +000097 smtp.close()
98
99 def testTimeoutValue(self):
100 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Facundo Batista366d6262007-03-28 18:25:54 +0000101 self.assertEqual(smtp.sock.gettimeout(), 30)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000102 smtp.close()
Facundo Batista366d6262007-03-28 18:25:54 +0000103
104
Facundo Batista1bc8d632007-08-21 16:57:18 +0000105# Test server thread using the specified SMTP server class
Trent Nelsone41b0062008-04-08 23:47:30 +0000106def debugging_server(serv, serv_evt, client_evt):
Neal Norwitz75992ed2008-02-26 08:04:59 +0000107 serv_evt.set()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000108
109 try:
Facundo Batista412b8b62007-08-01 23:18:36 +0000110 if hasattr(select, 'poll'):
111 poll_fun = asyncore.poll2
112 else:
113 poll_fun = asyncore.poll
114
115 n = 1000
116 while asyncore.socket_map and n > 0:
117 poll_fun(0.01, asyncore.socket_map)
118
119 # when the client conversation is finished, it will
120 # set client_evt, and it's then ok to kill the server
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000121 if client_evt.is_set():
Facundo Batista412b8b62007-08-01 23:18:36 +0000122 serv.close()
123 break
124
125 n -= 1
126
Facundo Batista16ed5b42007-07-24 21:20:42 +0000127 except socket.timeout:
128 pass
129 finally:
Benjamin Peterson0fbcf692008-06-11 17:27:50 +0000130 if not client_evt.is_set():
Neal Norwitz75992ed2008-02-26 08:04:59 +0000131 # allow some time for the client to read the result
132 time.sleep(0.5)
133 serv.close()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000134 asyncore.close_all()
Facundo Batista412b8b62007-08-01 23:18:36 +0000135 serv_evt.set()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000136
137MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
138MSG_END = '------------ END MESSAGE ------------\n'
139
Facundo Batista1bc8d632007-08-21 16:57:18 +0000140# NOTE: Some SMTP objects in the tests below are created with a non-default
141# local_hostname argument to the constructor, since (on some systems) the FQDN
142# lookup caused by the default local_hostname sometimes takes so long that the
Facundo Batista412b8b62007-08-01 23:18:36 +0000143# test server times out, causing the test to fail.
Facundo Batista1bc8d632007-08-21 16:57:18 +0000144
145# Test behavior of smtpd.DebuggingServer
Victor Stinner6a102812010-04-27 23:55:59 +0000146@unittest.skipUnless(threading, 'Threading required for this test.')
147class DebuggingServerTests(unittest.TestCase):
Facundo Batista16ed5b42007-07-24 21:20:42 +0000148
149 def setUp(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000150 # temporarily replace sys.stdout to capture DebuggingServer output
Facundo Batista16ed5b42007-07-24 21:20:42 +0000151 self.old_stdout = sys.stdout
152 self.output = StringIO.StringIO()
153 sys.stdout = self.output
154
Antoine Pitroua763c062009-10-27 19:47:30 +0000155 self._threads = test_support.threading_setup()
Facundo Batista412b8b62007-08-01 23:18:36 +0000156 self.serv_evt = threading.Event()
157 self.client_evt = threading.Event()
Antoine Pitrou54f9f832010-04-30 23:08:48 +0000158 # Pick a random unused port by passing 0 for the port number
159 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
160 # Keep a note of what port was assigned
161 self.port = self.serv.socket.getsockname()[1]
Trent Nelsone41b0062008-04-08 23:47:30 +0000162 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitroua763c062009-10-27 19:47:30 +0000163 self.thread = threading.Thread(target=debugging_server, args=serv_args)
164 self.thread.start()
Facundo Batista412b8b62007-08-01 23:18:36 +0000165
166 # wait until server thread has assigned a port number
Neal Norwitz75992ed2008-02-26 08:04:59 +0000167 self.serv_evt.wait()
168 self.serv_evt.clear()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000169
170 def tearDown(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000171 # indicate that the client is finished
172 self.client_evt.set()
173 # wait for the server thread to terminate
174 self.serv_evt.wait()
Antoine Pitroua763c062009-10-27 19:47:30 +0000175 self.thread.join()
176 test_support.threading_cleanup(*self._threads)
Facundo Batista412b8b62007-08-01 23:18:36 +0000177 # restore sys.stdout
Facundo Batista16ed5b42007-07-24 21:20:42 +0000178 sys.stdout = self.old_stdout
179
180 def testBasic(self):
181 # connect
Benjamin Peterson11222362016-12-01 23:58:38 -0800182 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista412b8b62007-08-01 23:18:36 +0000183 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000184
Facundo Batista1bc8d632007-08-21 16:57:18 +0000185 def testNOOP(self):
Benjamin Peterson11222362016-12-01 23:58:38 -0800186 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000187 expected = (250, 'Ok')
188 self.assertEqual(smtp.noop(), expected)
189 smtp.quit()
190
191 def testRSET(self):
Benjamin Peterson11222362016-12-01 23:58:38 -0800192 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000193 expected = (250, 'Ok')
194 self.assertEqual(smtp.rset(), expected)
195 smtp.quit()
196
197 def testNotImplemented(self):
198 # EHLO isn't implemented in DebuggingServer
Benjamin Peterson11222362016-12-01 23:58:38 -0800199 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista412b8b62007-08-01 23:18:36 +0000200 expected = (502, 'Error: command "EHLO" not implemented')
201 self.assertEqual(smtp.ehlo(), expected)
202 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000203
Facundo Batista1bc8d632007-08-21 16:57:18 +0000204 def testVRFY(self):
205 # VRFY isn't implemented in DebuggingServer
Benjamin Peterson11222362016-12-01 23:58:38 -0800206 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000207 expected = (502, 'Error: command "VRFY" not implemented')
208 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
209 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
210 smtp.quit()
211
212 def testSecondHELO(self):
213 # check that a second HELO returns a message that it's a duplicate
214 # (this behavior is specific to smtpd.SMTPChannel)
Benjamin Peterson11222362016-12-01 23:58:38 -0800215 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000216 smtp.helo()
217 expected = (503, 'Duplicate HELO/EHLO')
218 self.assertEqual(smtp.helo(), expected)
219 smtp.quit()
220
Facundo Batista16ed5b42007-07-24 21:20:42 +0000221 def testHELP(self):
Benjamin Peterson11222362016-12-01 23:58:38 -0800222 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000223 self.assertEqual(smtp.help(), 'Error: command "HELP" not implemented')
Facundo Batista412b8b62007-08-01 23:18:36 +0000224 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000225
226 def testSend(self):
227 # connect and send mail
228 m = 'A test message'
Benjamin Peterson11222362016-12-01 23:58:38 -0800229 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000230 smtp.sendmail('John', 'Sally', m)
Neal Norwitze39be532008-08-25 03:52:40 +0000231 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
232 # in asyncore. This sleep might help, but should really be fixed
233 # properly by using an Event variable.
234 time.sleep(0.01)
Facundo Batista412b8b62007-08-01 23:18:36 +0000235 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000236
Facundo Batista412b8b62007-08-01 23:18:36 +0000237 self.client_evt.set()
238 self.serv_evt.wait()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000239 self.output.flush()
240 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
241 self.assertEqual(self.output.getvalue(), mexpect)
242
243
Victor Stinner6a102812010-04-27 23:55:59 +0000244class NonConnectingTests(unittest.TestCase):
Neal Norwitz75992ed2008-02-26 08:04:59 +0000245
246 def testNotConnected(self):
247 # Test various operations on an unconnected SMTP object that
248 # should raise exceptions (at present the attempt in SMTP.send
249 # to reference the nonexistent 'sock' attribute of the SMTP object
250 # causes an AttributeError)
251 smtp = smtplib.SMTP()
252 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
253 self.assertRaises(smtplib.SMTPServerDisconnected,
254 smtp.send, 'test msg')
255
256 def testNonnumericPort(self):
257 # check that non-numeric port raises socket.error
258 self.assertRaises(socket.error, smtplib.SMTP,
259 "localhost", "bogus")
260 self.assertRaises(socket.error, smtplib.SMTP,
261 "localhost:bogus")
262
263
Facundo Batista1bc8d632007-08-21 16:57:18 +0000264# test response of client to a non-successful HELO message
Victor Stinner6a102812010-04-27 23:55:59 +0000265@unittest.skipUnless(threading, 'Threading required for this test.')
266class BadHELOServerTests(unittest.TestCase):
Facundo Batista16ed5b42007-07-24 21:20:42 +0000267
268 def setUp(self):
269 self.old_stdout = sys.stdout
270 self.output = StringIO.StringIO()
271 sys.stdout = self.output
272
Antoine Pitroua763c062009-10-27 19:47:30 +0000273 self._threads = test_support.threading_setup()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000274 self.evt = threading.Event()
Trent Nelsone41b0062008-04-08 23:47:30 +0000275 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
276 self.sock.settimeout(15)
277 self.port = test_support.bind_port(self.sock)
278 servargs = (self.evt, "199 no hello for you!\n", self.sock)
Antoine Pitroua763c062009-10-27 19:47:30 +0000279 self.thread = threading.Thread(target=server, args=servargs)
280 self.thread.start()
Neal Norwitz75992ed2008-02-26 08:04:59 +0000281 self.evt.wait()
282 self.evt.clear()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000283
284 def tearDown(self):
285 self.evt.wait()
Antoine Pitroua763c062009-10-27 19:47:30 +0000286 self.thread.join()
287 test_support.threading_cleanup(*self._threads)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000288 sys.stdout = self.old_stdout
289
290 def testFailingHELO(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000291 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Trent Nelsone41b0062008-04-08 23:47:30 +0000292 HOST, self.port, 'localhost', 3)
Facundo Batista366d6262007-03-28 18:25:54 +0000293
Facundo Batista1bc8d632007-08-21 16:57:18 +0000294
Benjamin Petersondabfc562014-12-05 20:05:18 -0500295@unittest.skipUnless(threading, 'Threading required for this test.')
296class TooLongLineTests(unittest.TestCase):
297 respdata = '250 OK' + ('.' * smtplib._MAXLINE * 2) + '\n'
298
299 def setUp(self):
300 self.old_stdout = sys.stdout
301 self.output = StringIO.StringIO()
302 sys.stdout = self.output
303
304 self.evt = threading.Event()
305 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
306 self.sock.settimeout(15)
307 self.port = test_support.bind_port(self.sock)
308 servargs = (self.evt, self.respdata, self.sock)
Victor Stinner14635182018-06-04 23:53:52 +0200309 self.thread = threading.Thread(target=server, args=servargs)
310 self.thread.start()
Benjamin Petersondabfc562014-12-05 20:05:18 -0500311 self.evt.wait()
312 self.evt.clear()
313
314 def tearDown(self):
315 self.evt.wait()
Victor Stinner14635182018-06-04 23:53:52 +0200316 self.thread.join()
Benjamin Petersondabfc562014-12-05 20:05:18 -0500317 sys.stdout = self.old_stdout
318
319 def testLineTooLong(self):
320 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
321 HOST, self.port, 'localhost', 3)
322
323
Facundo Batista1bc8d632007-08-21 16:57:18 +0000324sim_users = {'Mr.A@somewhere.com':'John A',
325 'Ms.B@somewhere.com':'Sally B',
326 'Mrs.C@somewhereesle.com':'Ruth C',
327 }
328
R. David Murray3724d6c2009-05-23 21:48:06 +0000329sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murray8de212b2009-05-28 18:49:23 +0000330sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
331 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
332sim_auth_credentials = {
333 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
334 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
335 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
336 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
337 }
338sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murray3724d6c2009-05-23 21:48:06 +0000339
Facundo Batista1bc8d632007-08-21 16:57:18 +0000340sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
341 'list-2':['Ms.B@somewhere.com',],
342 }
343
344# Simulated SMTP channel & server
345class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murray8de212b2009-05-28 18:49:23 +0000346
R. David Murray6b985442009-05-29 17:31:05 +0000347 def __init__(self, extra_features, *args, **kw):
348 self._extrafeatures = ''.join(
349 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murray8de212b2009-05-28 18:49:23 +0000350 smtpd.SMTPChannel.__init__(self, *args, **kw)
351
Facundo Batista1bc8d632007-08-21 16:57:18 +0000352 def smtp_EHLO(self, arg):
R. David Murray8de212b2009-05-28 18:49:23 +0000353 resp = ('250-testhost\r\n'
354 '250-EXPN\r\n'
355 '250-SIZE 20000000\r\n'
356 '250-STARTTLS\r\n'
357 '250-DELIVERBY\r\n')
358 resp = resp + self._extrafeatures + '250 HELP'
Facundo Batista1bc8d632007-08-21 16:57:18 +0000359 self.push(resp)
360
361 def smtp_VRFY(self, arg):
R David Murray95225952011-07-18 21:34:04 -0400362 # For max compatibility smtplib should be sending the raw address.
363 if arg in sim_users:
364 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Facundo Batista1bc8d632007-08-21 16:57:18 +0000365 else:
366 self.push('550 No such user: %s' % arg)
367
368 def smtp_EXPN(self, arg):
R David Murray95225952011-07-18 21:34:04 -0400369 list_name = arg.lower()
Facundo Batista1bc8d632007-08-21 16:57:18 +0000370 if list_name in sim_lists:
371 user_list = sim_lists[list_name]
372 for n, user_email in enumerate(user_list):
373 quoted_addr = smtplib.quoteaddr(user_email)
374 if n < len(user_list) - 1:
375 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
376 else:
377 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
378 else:
379 self.push('550 No access for you!')
380
R. David Murray3724d6c2009-05-23 21:48:06 +0000381 def smtp_AUTH(self, arg):
R. David Murray8de212b2009-05-28 18:49:23 +0000382 if arg.strip().lower()=='cram-md5':
383 self.push('334 {0}'.format(sim_cram_md5_challenge))
384 return
R. David Murray3724d6c2009-05-23 21:48:06 +0000385 mech, auth = arg.split()
R. David Murray8de212b2009-05-28 18:49:23 +0000386 mech = mech.lower()
387 if mech not in sim_auth_credentials:
R. David Murray3724d6c2009-05-23 21:48:06 +0000388 self.push('504 auth type unimplemented')
R. David Murray8de212b2009-05-28 18:49:23 +0000389 return
390 if mech == 'plain' and auth==sim_auth_credentials['plain']:
391 self.push('235 plain auth ok')
392 elif mech=='login' and auth==sim_auth_credentials['login']:
393 self.push('334 Password:')
394 else:
395 self.push('550 No access for you!')
R. David Murray3724d6c2009-05-23 21:48:06 +0000396
Giampaolo Rodolàe4499a82010-05-06 20:19:32 +0000397 def handle_error(self):
398 raise
399
Facundo Batista1bc8d632007-08-21 16:57:18 +0000400
401class SimSMTPServer(smtpd.SMTPServer):
R. David Murray8de212b2009-05-28 18:49:23 +0000402
R. David Murray6b985442009-05-29 17:31:05 +0000403 def __init__(self, *args, **kw):
404 self._extra_features = []
405 smtpd.SMTPServer.__init__(self, *args, **kw)
406
Facundo Batista1bc8d632007-08-21 16:57:18 +0000407 def handle_accept(self):
408 conn, addr = self.accept()
R. David Murray6b985442009-05-29 17:31:05 +0000409 self._SMTPchannel = SimSMTPChannel(self._extra_features,
410 self, conn, addr)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000411
412 def process_message(self, peer, mailfrom, rcpttos, data):
413 pass
414
R. David Murray8de212b2009-05-28 18:49:23 +0000415 def add_feature(self, feature):
R. David Murray6b985442009-05-29 17:31:05 +0000416 self._extra_features.append(feature)
R. David Murray8de212b2009-05-28 18:49:23 +0000417
Giampaolo Rodolàe4499a82010-05-06 20:19:32 +0000418 def handle_error(self):
419 raise
420
Facundo Batista1bc8d632007-08-21 16:57:18 +0000421
422# Test various SMTP & ESMTP commands/behaviors that require a simulated server
423# (i.e., something with more features than DebuggingServer)
Victor Stinner6a102812010-04-27 23:55:59 +0000424@unittest.skipUnless(threading, 'Threading required for this test.')
425class SMTPSimTests(unittest.TestCase):
Facundo Batista1bc8d632007-08-21 16:57:18 +0000426
427 def setUp(self):
Antoine Pitroua763c062009-10-27 19:47:30 +0000428 self._threads = test_support.threading_setup()
Facundo Batista1bc8d632007-08-21 16:57:18 +0000429 self.serv_evt = threading.Event()
430 self.client_evt = threading.Event()
Antoine Pitrou54f9f832010-04-30 23:08:48 +0000431 # Pick a random unused port by passing 0 for the port number
432 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
433 # Keep a note of what port was assigned
434 self.port = self.serv.socket.getsockname()[1]
Trent Nelsone41b0062008-04-08 23:47:30 +0000435 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitroua763c062009-10-27 19:47:30 +0000436 self.thread = threading.Thread(target=debugging_server, args=serv_args)
437 self.thread.start()
Facundo Batista1bc8d632007-08-21 16:57:18 +0000438
439 # wait until server thread has assigned a port number
Neal Norwitz75992ed2008-02-26 08:04:59 +0000440 self.serv_evt.wait()
441 self.serv_evt.clear()
Facundo Batista1bc8d632007-08-21 16:57:18 +0000442
443 def tearDown(self):
444 # indicate that the client is finished
445 self.client_evt.set()
446 # wait for the server thread to terminate
447 self.serv_evt.wait()
Antoine Pitroua763c062009-10-27 19:47:30 +0000448 self.thread.join()
449 test_support.threading_cleanup(*self._threads)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000450
451 def testBasic(self):
452 # smoke test
Trent Nelsone41b0062008-04-08 23:47:30 +0000453 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000454 smtp.quit()
455
456 def testEHLO(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000457 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000458
459 # no features should be present before the EHLO
460 self.assertEqual(smtp.esmtp_features, {})
461
462 # features expected from the test server
463 expected_features = {'expn':'',
464 'size': '20000000',
465 'starttls': '',
466 'deliverby': '',
467 'help': '',
468 }
469
470 smtp.ehlo()
471 self.assertEqual(smtp.esmtp_features, expected_features)
472 for k in expected_features:
473 self.assertTrue(smtp.has_extn(k))
474 self.assertFalse(smtp.has_extn('unsupported-feature'))
475 smtp.quit()
476
477 def testVRFY(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000478 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000479
480 for email, name in sim_users.items():
481 expected_known = (250, '%s %s' % (name, smtplib.quoteaddr(email)))
482 self.assertEqual(smtp.vrfy(email), expected_known)
483
484 u = 'nobody@nowhere.com'
R David Murray95225952011-07-18 21:34:04 -0400485 expected_unknown = (550, 'No such user: %s' % u)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000486 self.assertEqual(smtp.vrfy(u), expected_unknown)
487 smtp.quit()
488
489 def testEXPN(self):
Trent Nelsone41b0062008-04-08 23:47:30 +0000490 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000491
492 for listname, members in sim_lists.items():
493 users = []
494 for m in members:
495 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
496 expected_known = (250, '\n'.join(users))
497 self.assertEqual(smtp.expn(listname), expected_known)
498
499 u = 'PSU-Members-List'
500 expected_unknown = (550, 'No access for you!')
501 self.assertEqual(smtp.expn(u), expected_unknown)
502 smtp.quit()
503
R. David Murray8de212b2009-05-28 18:49:23 +0000504 def testAUTH_PLAIN(self):
R. David Murray8de212b2009-05-28 18:49:23 +0000505 self.serv.add_feature("AUTH PLAIN")
R. David Murray6b985442009-05-29 17:31:05 +0000506 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murray3724d6c2009-05-23 21:48:06 +0000507
R. David Murray8de212b2009-05-28 18:49:23 +0000508 expected_auth_ok = (235, b'plain auth ok')
R. David Murray3724d6c2009-05-23 21:48:06 +0000509 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Facundo Batista1bc8d632007-08-21 16:57:18 +0000510
R. David Murray8de212b2009-05-28 18:49:23 +0000511 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
512 # require a synchronous read to obtain the credentials...so instead smtpd
513 # sees the credential sent by smtplib's login method as an unknown command,
514 # which results in smtplib raising an auth error. Fortunately the error
515 # message contains the encoded credential, so we can partially check that it
516 # was generated correctly (partially, because the 'word' is uppercased in
517 # the error message).
518
519 def testAUTH_LOGIN(self):
R. David Murray8de212b2009-05-28 18:49:23 +0000520 self.serv.add_feature("AUTH LOGIN")
R. David Murray6b985442009-05-29 17:31:05 +0000521 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murray8de212b2009-05-28 18:49:23 +0000522 try: smtp.login(sim_auth[0], sim_auth[1])
523 except smtplib.SMTPAuthenticationError as err:
524 if sim_auth_login_password not in str(err):
525 raise "expected encoded password not found in error message"
526
527 def testAUTH_CRAM_MD5(self):
R. David Murray8de212b2009-05-28 18:49:23 +0000528 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray6b985442009-05-29 17:31:05 +0000529 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murray8de212b2009-05-28 18:49:23 +0000530
531 try: smtp.login(sim_auth[0], sim_auth[1])
532 except smtplib.SMTPAuthenticationError as err:
533 if sim_auth_credentials['cram-md5'] not in str(err):
534 raise "expected encoded credentials not found in error message"
535
536 #TODO: add tests for correct AUTH method fallback now that the
537 #test infrastructure can support it.
538
R David Murray7234e032014-08-30 16:56:49 -0400539 def test_quit_resets_greeting(self):
540 smtp = smtplib.SMTP(HOST, self.port,
541 local_hostname='localhost',
542 timeout=15)
543 code, message = smtp.ehlo()
544 self.assertEqual(code, 250)
545 self.assertIn('size', smtp.esmtp_features)
546 smtp.quit()
547 self.assertNotIn('size', smtp.esmtp_features)
548 smtp.connect(HOST, self.port)
549 self.assertNotIn('size', smtp.esmtp_features)
550 smtp.ehlo_or_helo_if_needed()
551 self.assertIn('size', smtp.esmtp_features)
552 smtp.quit()
553
Facundo Batista1bc8d632007-08-21 16:57:18 +0000554
Facundo Batista366d6262007-03-28 18:25:54 +0000555def test_main(verbose=None):
Facundo Batista412b8b62007-08-01 23:18:36 +0000556 test_support.run_unittest(GeneralTests, DebuggingServerTests,
Neal Norwitz75992ed2008-02-26 08:04:59 +0000557 NonConnectingTests,
Benjamin Petersondabfc562014-12-05 20:05:18 -0500558 BadHELOServerTests, SMTPSimTests,
559 TooLongLineTests)
Facundo Batista366d6262007-03-28 18:25:54 +0000560
561if __name__ == '__main__':
562 test_main()