blob: d36ab0e82b90649f35c7c747d9f3258a7a895b74 [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
Guido van Rossum04110fb2007-08-24 16:32:05 +00002import email.utils
Guido van Rossumd8faa362007-04-27 19:54:29 +00003import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00004import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +00005import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +00006import io
7import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +00008import time
Guido van Rossum806c2462007-08-06 23:33:07 +00009import select
Guido van Rossumd8faa362007-04-27 19:54:29 +000010
Victor Stinner45df8202010-04-28 22:31:17 +000011import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
Guido van Rossumd8faa362007-04-27 19:54:29 +000013
Victor Stinner45df8202010-04-28 22:31:17 +000014try:
15 import threading
16except ImportError:
17 threading = None
18
Benjamin Petersonee8712c2008-05-20 21:35:26 +000019HOST = support.HOST
Guido van Rossumd8faa362007-04-27 19:54:29 +000020
Josiah Carlsond74900e2008-07-07 04:15:08 +000021if sys.platform == 'darwin':
22 # select.poll returns a select.POLLHUP at the end of the tests
23 # on darwin, so just ignore it
24 def handle_expt(self):
25 pass
26 smtpd.SMTPChannel.handle_expt = handle_expt
27
28
Christian Heimes5e696852008-04-09 08:37:03 +000029def server(evt, buf, serv):
Christian Heimes380f7f22008-02-28 11:19:05 +000030 serv.listen(5)
31 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000032 try:
33 conn, addr = serv.accept()
34 except socket.timeout:
35 pass
36 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000037 n = 500
38 while buf and n > 0:
39 r, w, e = select.select([], [conn], [])
40 if w:
41 sent = conn.send(buf)
42 buf = buf[sent:]
43
44 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000045
Guido van Rossumd8faa362007-04-27 19:54:29 +000046 conn.close()
47 finally:
48 serv.close()
49 evt.set()
50
Victor Stinner45df8202010-04-28 22:31:17 +000051@unittest.skipUnless(threading, 'Threading required for this test.')
52class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000053
54 def setUp(self):
Antoine Pitrouc3d47722009-10-27 19:49:45 +000055 self._threads = support.threading_setup()
Guido van Rossumd8faa362007-04-27 19:54:29 +000056 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +000057 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
58 self.sock.settimeout(15)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000059 self.port = support.bind_port(self.sock)
Christian Heimes5e696852008-04-09 08:37:03 +000060 servargs = (self.evt, b"220 Hola mundo\n", self.sock)
Antoine Pitrouc3d47722009-10-27 19:49:45 +000061 self.thread = threading.Thread(target=server, args=servargs)
62 self.thread.start()
Christian Heimes380f7f22008-02-28 11:19:05 +000063 self.evt.wait()
64 self.evt.clear()
Guido van Rossumd8faa362007-04-27 19:54:29 +000065
66 def tearDown(self):
67 self.evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +000068 self.thread.join()
69 support.threading_cleanup(*self._threads)
Guido van Rossumd8faa362007-04-27 19:54:29 +000070
Guido van Rossum806c2462007-08-06 23:33:07 +000071 def testBasic1(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +000072 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000073 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000074 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000075
Guido van Rossum806c2462007-08-06 23:33:07 +000076 def testBasic2(self):
77 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000078 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000079 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000080
81 def testLocalHostName(self):
82 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000083 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000084 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000085 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000086
Guido van Rossumd8faa362007-04-27 19:54:29 +000087 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +000088 self.assertTrue(socket.getdefaulttimeout() is None)
89 socket.setdefaulttimeout(30)
90 try:
91 smtp = smtplib.SMTP(HOST, self.port)
92 finally:
93 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +000094 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +000095 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000096
97 def testTimeoutNone(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +000098 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +000099 socket.setdefaulttimeout(30)
100 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000101 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000103 socket.setdefaulttimeout(None)
104 self.assertTrue(smtp.sock.gettimeout() is None)
105 smtp.close()
106
107 def testTimeoutValue(self):
108 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000110 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111
112
Guido van Rossum04110fb2007-08-24 16:32:05 +0000113# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000114def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000115 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000116
117 try:
118 if hasattr(select, 'poll'):
119 poll_fun = asyncore.poll2
120 else:
121 poll_fun = asyncore.poll
122
123 n = 1000
124 while asyncore.socket_map and n > 0:
125 poll_fun(0.01, asyncore.socket_map)
126
127 # when the client conversation is finished, it will
128 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000129 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000130 serv.close()
131 break
132
133 n -= 1
134
135 except socket.timeout:
136 pass
137 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000138 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000139 # allow some time for the client to read the result
140 time.sleep(0.5)
141 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000142 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000143 serv_evt.set()
144
145MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
146MSG_END = '------------ END MESSAGE ------------\n'
147
Guido van Rossum04110fb2007-08-24 16:32:05 +0000148# NOTE: Some SMTP objects in the tests below are created with a non-default
149# local_hostname argument to the constructor, since (on some systems) the FQDN
150# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000151# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000152
153# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000154@unittest.skipUnless(threading, 'Threading required for this test.')
155class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000156
157 def setUp(self):
158 # temporarily replace sys.stdout to capture DebuggingServer output
159 self.old_stdout = sys.stdout
160 self.output = io.StringIO()
161 sys.stdout = self.output
162
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000163 self._threads = support.threading_setup()
Guido van Rossum806c2462007-08-06 23:33:07 +0000164 self.serv_evt = threading.Event()
165 self.client_evt = threading.Event()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000166 self.port = support.find_unused_port()
Christian Heimes5e696852008-04-09 08:37:03 +0000167 self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1))
168 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000169 self.thread = threading.Thread(target=debugging_server, args=serv_args)
170 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000171
172 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000173 self.serv_evt.wait()
174 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000175
176 def tearDown(self):
177 # indicate that the client is finished
178 self.client_evt.set()
179 # wait for the server thread to terminate
180 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000181 self.thread.join()
182 support.threading_cleanup(*self._threads)
Guido van Rossum806c2462007-08-06 23:33:07 +0000183 # restore sys.stdout
184 sys.stdout = self.old_stdout
185
186 def testBasic(self):
187 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000188 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000189 smtp.quit()
190
Guido van Rossum04110fb2007-08-24 16:32:05 +0000191 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000192 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000193 expected = (250, b'Ok')
194 self.assertEqual(smtp.noop(), expected)
195 smtp.quit()
196
197 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000198 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000199 expected = (250, b'Ok')
200 self.assertEqual(smtp.rset(), expected)
201 smtp.quit()
202
203 def testNotImplemented(self):
204 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000205 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000206 expected = (502, b'Error: command "EHLO" not implemented')
207 self.assertEqual(smtp.ehlo(), expected)
208 smtp.quit()
209
Guido van Rossum04110fb2007-08-24 16:32:05 +0000210 def testVRFY(self):
211 # VRFY isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000212 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000213 expected = (502, b'Error: command "VRFY" not implemented')
214 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
215 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
216 smtp.quit()
217
218 def testSecondHELO(self):
219 # check that a second HELO returns a message that it's a duplicate
220 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000221 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000222 smtp.helo()
223 expected = (503, b'Duplicate HELO/EHLO')
224 self.assertEqual(smtp.helo(), expected)
225 smtp.quit()
226
Guido van Rossum806c2462007-08-06 23:33:07 +0000227 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000228 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000229 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
230 smtp.quit()
231
232 def testSend(self):
233 # connect and send mail
234 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000235 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000236 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000237 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
238 # in asyncore. This sleep might help, but should really be fixed
239 # properly by using an Event variable.
240 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000241 smtp.quit()
242
243 self.client_evt.set()
244 self.serv_evt.wait()
245 self.output.flush()
246 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
247 self.assertEqual(self.output.getvalue(), mexpect)
248
249
Victor Stinner45df8202010-04-28 22:31:17 +0000250class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000251
252 def testNotConnected(self):
253 # Test various operations on an unconnected SMTP object that
254 # should raise exceptions (at present the attempt in SMTP.send
255 # to reference the nonexistent 'sock' attribute of the SMTP object
256 # causes an AttributeError)
257 smtp = smtplib.SMTP()
258 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
259 self.assertRaises(smtplib.SMTPServerDisconnected,
260 smtp.send, 'test msg')
261
262 def testNonnumericPort(self):
263 # check that non-numeric port raises socket.error
264 self.assertRaises(socket.error, smtplib.SMTP,
265 "localhost", "bogus")
266 self.assertRaises(socket.error, smtplib.SMTP,
267 "localhost:bogus")
268
269
Guido van Rossum04110fb2007-08-24 16:32:05 +0000270# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000271@unittest.skipUnless(threading, 'Threading required for this test.')
272class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000273
274 def setUp(self):
275 self.old_stdout = sys.stdout
276 self.output = io.StringIO()
277 sys.stdout = self.output
278
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000279 self._threads = support.threading_setup()
Guido van Rossum806c2462007-08-06 23:33:07 +0000280 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000281 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
282 self.sock.settimeout(15)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000283 self.port = support.bind_port(self.sock)
Christian Heimes5e696852008-04-09 08:37:03 +0000284 servargs = (self.evt, b"199 no hello for you!\n", self.sock)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000285 self.thread = threading.Thread(target=server, args=servargs)
286 self.thread.start()
Christian Heimes380f7f22008-02-28 11:19:05 +0000287 self.evt.wait()
288 self.evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000289
290 def tearDown(self):
291 self.evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000292 self.thread.join()
293 support.threading_cleanup(*self._threads)
Guido van Rossum806c2462007-08-06 23:33:07 +0000294 sys.stdout = self.old_stdout
295
296 def testFailingHELO(self):
297 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000298 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000299
Guido van Rossum04110fb2007-08-24 16:32:05 +0000300
301sim_users = {'Mr.A@somewhere.com':'John A',
302 'Ms.B@somewhere.com':'Sally B',
303 'Mrs.C@somewhereesle.com':'Ruth C',
304 }
305
R. David Murraycaa27b72009-05-23 18:49:56 +0000306sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000307sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
308 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
309sim_auth_credentials = {
310 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
311 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
312 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
313 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
314 }
315sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000316
Guido van Rossum04110fb2007-08-24 16:32:05 +0000317sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
318 'list-2':['Ms.B@somewhere.com',],
319 }
320
321# Simulated SMTP channel & server
322class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000323
R. David Murray23ddc0e2009-05-29 18:03:16 +0000324 def __init__(self, extra_features, *args, **kw):
325 self._extrafeatures = ''.join(
326 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000327 super(SimSMTPChannel, self).__init__(*args, **kw)
328
Guido van Rossum04110fb2007-08-24 16:32:05 +0000329 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000330 resp = ('250-testhost\r\n'
331 '250-EXPN\r\n'
332 '250-SIZE 20000000\r\n'
333 '250-STARTTLS\r\n'
334 '250-DELIVERBY\r\n')
335 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000336 self.push(resp)
337
338 def smtp_VRFY(self, arg):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000339 raw_addr = email.utils.parseaddr(arg)[1]
340 quoted_addr = smtplib.quoteaddr(arg)
341 if raw_addr in sim_users:
342 self.push('250 %s %s' % (sim_users[raw_addr], quoted_addr))
343 else:
344 self.push('550 No such user: %s' % arg)
345
346 def smtp_EXPN(self, arg):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000347 list_name = email.utils.parseaddr(arg)[1].lower()
348 if list_name in sim_lists:
349 user_list = sim_lists[list_name]
350 for n, user_email in enumerate(user_list):
351 quoted_addr = smtplib.quoteaddr(user_email)
352 if n < len(user_list) - 1:
353 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
354 else:
355 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
356 else:
357 self.push('550 No access for you!')
358
R. David Murraycaa27b72009-05-23 18:49:56 +0000359 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000360 if arg.strip().lower()=='cram-md5':
361 self.push('334 {}'.format(sim_cram_md5_challenge))
362 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000363 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000364 mech = mech.lower()
365 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000366 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000367 return
368 if mech == 'plain' and auth==sim_auth_credentials['plain']:
369 self.push('235 plain auth ok')
370 elif mech=='login' and auth==sim_auth_credentials['login']:
371 self.push('334 Password:')
372 else:
373 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000374
Guido van Rossum04110fb2007-08-24 16:32:05 +0000375
376class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000377
R. David Murray23ddc0e2009-05-29 18:03:16 +0000378 def __init__(self, *args, **kw):
379 self._extra_features = []
380 smtpd.SMTPServer.__init__(self, *args, **kw)
381
Guido van Rossum04110fb2007-08-24 16:32:05 +0000382 def handle_accept(self):
383 conn, addr = self.accept()
R. David Murray23ddc0e2009-05-29 18:03:16 +0000384 self._SMTPchannel = SimSMTPChannel(self._extra_features,
385 self, conn, addr)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000386
387 def process_message(self, peer, mailfrom, rcpttos, data):
388 pass
389
R. David Murrayfb123912009-05-28 18:19:00 +0000390 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000391 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000392
Guido van Rossum04110fb2007-08-24 16:32:05 +0000393
394# Test various SMTP & ESMTP commands/behaviors that require a simulated server
395# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000396@unittest.skipUnless(threading, 'Threading required for this test.')
397class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000398
399 def setUp(self):
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000400 self._threads = support.threading_setup()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000401 self.serv_evt = threading.Event()
402 self.client_evt = threading.Event()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000403 self.port = support.find_unused_port()
Christian Heimes5e696852008-04-09 08:37:03 +0000404 self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1))
405 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000406 self.thread = threading.Thread(target=debugging_server, args=serv_args)
407 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000408
409 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000410 self.serv_evt.wait()
411 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000412
413 def tearDown(self):
414 # indicate that the client is finished
415 self.client_evt.set()
416 # wait for the server thread to terminate
417 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000418 self.thread.join()
419 support.threading_cleanup(*self._threads)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000420
421 def testBasic(self):
422 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000423 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000424 smtp.quit()
425
426 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000427 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000428
429 # no features should be present before the EHLO
430 self.assertEqual(smtp.esmtp_features, {})
431
432 # features expected from the test server
433 expected_features = {'expn':'',
434 'size': '20000000',
435 'starttls': '',
436 'deliverby': '',
437 'help': '',
438 }
439
440 smtp.ehlo()
441 self.assertEqual(smtp.esmtp_features, expected_features)
442 for k in expected_features:
443 self.assertTrue(smtp.has_extn(k))
444 self.assertFalse(smtp.has_extn('unsupported-feature'))
445 smtp.quit()
446
447 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000448 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000449
450 for email, name in sim_users.items():
451 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000452 (name, smtplib.quoteaddr(email)),
453 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000454 self.assertEqual(smtp.vrfy(email), expected_known)
455
456 u = 'nobody@nowhere.com'
Thomas Wouters74e68c72007-08-31 00:20:14 +0000457 expected_unknown = (550, ('No such user: %s'
458 % smtplib.quoteaddr(u)).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000459 self.assertEqual(smtp.vrfy(u), expected_unknown)
460 smtp.quit()
461
462 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000463 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000464
465 for listname, members in sim_lists.items():
466 users = []
467 for m in members:
468 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000469 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000470 self.assertEqual(smtp.expn(listname), expected_known)
471
472 u = 'PSU-Members-List'
473 expected_unknown = (550, b'No access for you!')
474 self.assertEqual(smtp.expn(u), expected_unknown)
475 smtp.quit()
476
R. David Murrayfb123912009-05-28 18:19:00 +0000477 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000478 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000479 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000480
R. David Murrayfb123912009-05-28 18:19:00 +0000481 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000482 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000483
R. David Murrayfb123912009-05-28 18:19:00 +0000484 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
485 # require a synchronous read to obtain the credentials...so instead smtpd
486 # sees the credential sent by smtplib's login method as an unknown command,
487 # which results in smtplib raising an auth error. Fortunately the error
488 # message contains the encoded credential, so we can partially check that it
489 # was generated correctly (partially, because the 'word' is uppercased in
490 # the error message).
491
492 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000493 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000494 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000495 try: smtp.login(sim_auth[0], sim_auth[1])
496 except smtplib.SMTPAuthenticationError as err:
497 if sim_auth_login_password not in str(err):
498 raise "expected encoded password not found in error message"
499
500 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000501 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000502 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000503
504 try: smtp.login(sim_auth[0], sim_auth[1])
505 except smtplib.SMTPAuthenticationError as err:
506 if sim_auth_credentials['cram-md5'] not in str(err):
507 raise "expected encoded credentials not found in error message"
508
509 #TODO: add tests for correct AUTH method fallback now that the
510 #test infrastructure can support it.
511
Guido van Rossum04110fb2007-08-24 16:32:05 +0000512
Guido van Rossumd8faa362007-04-27 19:54:29 +0000513def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000514 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000515 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000516 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517
518if __name__ == '__main__':
519 test_main()