blob: 3a9de5b4b7096d5feb74ccdbf78a1ba4c93d1f64 [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()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000166 # Pick a random unused port by passing 0 for the port number
167 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
168 # Keep a note of what port was assigned
169 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000170 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000171 self.thread = threading.Thread(target=debugging_server, args=serv_args)
172 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000173
174 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000175 self.serv_evt.wait()
176 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000177
178 def tearDown(self):
179 # indicate that the client is finished
180 self.client_evt.set()
181 # wait for the server thread to terminate
182 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000183 self.thread.join()
184 support.threading_cleanup(*self._threads)
Guido van Rossum806c2462007-08-06 23:33:07 +0000185 # restore sys.stdout
186 sys.stdout = self.old_stdout
187
188 def testBasic(self):
189 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000190 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000191 smtp.quit()
192
Guido van Rossum04110fb2007-08-24 16:32:05 +0000193 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000194 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000195 expected = (250, b'Ok')
196 self.assertEqual(smtp.noop(), expected)
197 smtp.quit()
198
199 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000200 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000201 expected = (250, b'Ok')
202 self.assertEqual(smtp.rset(), expected)
203 smtp.quit()
204
205 def testNotImplemented(self):
206 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000207 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000208 expected = (502, b'Error: command "EHLO" not implemented')
209 self.assertEqual(smtp.ehlo(), expected)
210 smtp.quit()
211
Guido van Rossum04110fb2007-08-24 16:32:05 +0000212 def testVRFY(self):
213 # VRFY isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000214 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000215 expected = (502, b'Error: command "VRFY" not implemented')
216 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
217 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
218 smtp.quit()
219
220 def testSecondHELO(self):
221 # check that a second HELO returns a message that it's a duplicate
222 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000223 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000224 smtp.helo()
225 expected = (503, b'Duplicate HELO/EHLO')
226 self.assertEqual(smtp.helo(), expected)
227 smtp.quit()
228
Guido van Rossum806c2462007-08-06 23:33:07 +0000229 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000230 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000231 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
232 smtp.quit()
233
234 def testSend(self):
235 # connect and send mail
236 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000237 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000238 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000239 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
240 # in asyncore. This sleep might help, but should really be fixed
241 # properly by using an Event variable.
242 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000243 smtp.quit()
244
245 self.client_evt.set()
246 self.serv_evt.wait()
247 self.output.flush()
248 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
249 self.assertEqual(self.output.getvalue(), mexpect)
250
251
Victor Stinner45df8202010-04-28 22:31:17 +0000252class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000253
254 def testNotConnected(self):
255 # Test various operations on an unconnected SMTP object that
256 # should raise exceptions (at present the attempt in SMTP.send
257 # to reference the nonexistent 'sock' attribute of the SMTP object
258 # causes an AttributeError)
259 smtp = smtplib.SMTP()
260 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
261 self.assertRaises(smtplib.SMTPServerDisconnected,
262 smtp.send, 'test msg')
263
264 def testNonnumericPort(self):
265 # check that non-numeric port raises socket.error
266 self.assertRaises(socket.error, smtplib.SMTP,
267 "localhost", "bogus")
268 self.assertRaises(socket.error, smtplib.SMTP,
269 "localhost:bogus")
270
271
Guido van Rossum04110fb2007-08-24 16:32:05 +0000272# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000273@unittest.skipUnless(threading, 'Threading required for this test.')
274class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000275
276 def setUp(self):
277 self.old_stdout = sys.stdout
278 self.output = io.StringIO()
279 sys.stdout = self.output
280
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000281 self._threads = support.threading_setup()
Guido van Rossum806c2462007-08-06 23:33:07 +0000282 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000283 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
284 self.sock.settimeout(15)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000285 self.port = support.bind_port(self.sock)
Christian Heimes5e696852008-04-09 08:37:03 +0000286 servargs = (self.evt, b"199 no hello for you!\n", self.sock)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000287 self.thread = threading.Thread(target=server, args=servargs)
288 self.thread.start()
Christian Heimes380f7f22008-02-28 11:19:05 +0000289 self.evt.wait()
290 self.evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000291
292 def tearDown(self):
293 self.evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000294 self.thread.join()
295 support.threading_cleanup(*self._threads)
Guido van Rossum806c2462007-08-06 23:33:07 +0000296 sys.stdout = self.old_stdout
297
298 def testFailingHELO(self):
299 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000300 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301
Guido van Rossum04110fb2007-08-24 16:32:05 +0000302
303sim_users = {'Mr.A@somewhere.com':'John A',
304 'Ms.B@somewhere.com':'Sally B',
305 'Mrs.C@somewhereesle.com':'Ruth C',
306 }
307
R. David Murraycaa27b72009-05-23 18:49:56 +0000308sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000309sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
310 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
311sim_auth_credentials = {
312 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
313 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
314 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
315 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
316 }
317sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000318
Guido van Rossum04110fb2007-08-24 16:32:05 +0000319sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
320 'list-2':['Ms.B@somewhere.com',],
321 }
322
323# Simulated SMTP channel & server
324class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000325
R. David Murray23ddc0e2009-05-29 18:03:16 +0000326 def __init__(self, extra_features, *args, **kw):
327 self._extrafeatures = ''.join(
328 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000329 super(SimSMTPChannel, self).__init__(*args, **kw)
330
Guido van Rossum04110fb2007-08-24 16:32:05 +0000331 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000332 resp = ('250-testhost\r\n'
333 '250-EXPN\r\n'
334 '250-SIZE 20000000\r\n'
335 '250-STARTTLS\r\n'
336 '250-DELIVERBY\r\n')
337 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000338 self.push(resp)
339
340 def smtp_VRFY(self, arg):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000341 raw_addr = email.utils.parseaddr(arg)[1]
342 quoted_addr = smtplib.quoteaddr(arg)
343 if raw_addr in sim_users:
344 self.push('250 %s %s' % (sim_users[raw_addr], quoted_addr))
345 else:
346 self.push('550 No such user: %s' % arg)
347
348 def smtp_EXPN(self, arg):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000349 list_name = email.utils.parseaddr(arg)[1].lower()
350 if list_name in sim_lists:
351 user_list = sim_lists[list_name]
352 for n, user_email in enumerate(user_list):
353 quoted_addr = smtplib.quoteaddr(user_email)
354 if n < len(user_list) - 1:
355 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
356 else:
357 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
358 else:
359 self.push('550 No access for you!')
360
R. David Murraycaa27b72009-05-23 18:49:56 +0000361 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000362 if arg.strip().lower()=='cram-md5':
363 self.push('334 {}'.format(sim_cram_md5_challenge))
364 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000365 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000366 mech = mech.lower()
367 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000368 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000369 return
370 if mech == 'plain' and auth==sim_auth_credentials['plain']:
371 self.push('235 plain auth ok')
372 elif mech=='login' and auth==sim_auth_credentials['login']:
373 self.push('334 Password:')
374 else:
375 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000376
Guido van Rossum04110fb2007-08-24 16:32:05 +0000377
378class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000379
R. David Murray23ddc0e2009-05-29 18:03:16 +0000380 def __init__(self, *args, **kw):
381 self._extra_features = []
382 smtpd.SMTPServer.__init__(self, *args, **kw)
383
Guido van Rossum04110fb2007-08-24 16:32:05 +0000384 def handle_accept(self):
385 conn, addr = self.accept()
R. David Murray23ddc0e2009-05-29 18:03:16 +0000386 self._SMTPchannel = SimSMTPChannel(self._extra_features,
387 self, conn, addr)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000388
389 def process_message(self, peer, mailfrom, rcpttos, data):
390 pass
391
R. David Murrayfb123912009-05-28 18:19:00 +0000392 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000393 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000394
Guido van Rossum04110fb2007-08-24 16:32:05 +0000395
396# Test various SMTP & ESMTP commands/behaviors that require a simulated server
397# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000398@unittest.skipUnless(threading, 'Threading required for this test.')
399class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000400
401 def setUp(self):
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000402 self._threads = support.threading_setup()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000403 self.serv_evt = threading.Event()
404 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000405 # Pick a random unused port by passing 0 for the port number
406 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
407 # Keep a note of what port was assigned
408 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000409 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000410 self.thread = threading.Thread(target=debugging_server, args=serv_args)
411 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000412
413 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000414 self.serv_evt.wait()
415 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000416
417 def tearDown(self):
418 # indicate that the client is finished
419 self.client_evt.set()
420 # wait for the server thread to terminate
421 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000422 self.thread.join()
423 support.threading_cleanup(*self._threads)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000424
425 def testBasic(self):
426 # smoke test
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 smtp.quit()
429
430 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000431 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000432
433 # no features should be present before the EHLO
434 self.assertEqual(smtp.esmtp_features, {})
435
436 # features expected from the test server
437 expected_features = {'expn':'',
438 'size': '20000000',
439 'starttls': '',
440 'deliverby': '',
441 'help': '',
442 }
443
444 smtp.ehlo()
445 self.assertEqual(smtp.esmtp_features, expected_features)
446 for k in expected_features:
447 self.assertTrue(smtp.has_extn(k))
448 self.assertFalse(smtp.has_extn('unsupported-feature'))
449 smtp.quit()
450
451 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000452 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000453
454 for email, name in sim_users.items():
455 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000456 (name, smtplib.quoteaddr(email)),
457 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000458 self.assertEqual(smtp.vrfy(email), expected_known)
459
460 u = 'nobody@nowhere.com'
Thomas Wouters74e68c72007-08-31 00:20:14 +0000461 expected_unknown = (550, ('No such user: %s'
462 % smtplib.quoteaddr(u)).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000463 self.assertEqual(smtp.vrfy(u), expected_unknown)
464 smtp.quit()
465
466 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000467 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000468
469 for listname, members in sim_lists.items():
470 users = []
471 for m in members:
472 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000473 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000474 self.assertEqual(smtp.expn(listname), expected_known)
475
476 u = 'PSU-Members-List'
477 expected_unknown = (550, b'No access for you!')
478 self.assertEqual(smtp.expn(u), expected_unknown)
479 smtp.quit()
480
R. David Murrayfb123912009-05-28 18:19:00 +0000481 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000482 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000483 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000484
R. David Murrayfb123912009-05-28 18:19:00 +0000485 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000486 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000487
R. David Murrayfb123912009-05-28 18:19:00 +0000488 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
489 # require a synchronous read to obtain the credentials...so instead smtpd
490 # sees the credential sent by smtplib's login method as an unknown command,
491 # which results in smtplib raising an auth error. Fortunately the error
492 # message contains the encoded credential, so we can partially check that it
493 # was generated correctly (partially, because the 'word' is uppercased in
494 # the error message).
495
496 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000497 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000498 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000499 try: smtp.login(sim_auth[0], sim_auth[1])
500 except smtplib.SMTPAuthenticationError as err:
501 if sim_auth_login_password not in str(err):
502 raise "expected encoded password not found in error message"
503
504 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000505 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000506 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000507
508 try: smtp.login(sim_auth[0], sim_auth[1])
509 except smtplib.SMTPAuthenticationError as err:
510 if sim_auth_credentials['cram-md5'] not in str(err):
511 raise "expected encoded credentials not found in error message"
512
513 #TODO: add tests for correct AUTH method fallback now that the
514 #test infrastructure can support it.
515
Guido van Rossum04110fb2007-08-24 16:32:05 +0000516
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000518 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000519 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000520 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000521
522if __name__ == '__main__':
523 test_main()