blob: 969ff1519d530c4fc8e0ea8e2945d4e7fc8c1cf2 [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
R. David Murray7dff9e02010-11-08 17:15:13 +00002import email.mime.text
Guido van Rossum04110fb2007-08-24 16:32:05 +00003import email.utils
Guido van Rossumd8faa362007-04-27 19:54:29 +00004import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00005import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +00007import io
R. David Murray7dff9e02010-11-08 17:15:13 +00008import re
Guido van Rossum806c2462007-08-06 23:33:07 +00009import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import time
Guido van Rossum806c2462007-08-06 23:33:07 +000011import select
Guido van Rossumd8faa362007-04-27 19:54:29 +000012
Victor Stinner45df8202010-04-28 22:31:17 +000013import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000014from test import support, mock_socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000015
Victor Stinner45df8202010-04-28 22:31:17 +000016try:
17 import threading
18except ImportError:
19 threading = None
20
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021HOST = support.HOST
Guido van Rossumd8faa362007-04-27 19:54:29 +000022
Josiah Carlsond74900e2008-07-07 04:15:08 +000023if sys.platform == 'darwin':
24 # select.poll returns a select.POLLHUP at the end of the tests
25 # on darwin, so just ignore it
26 def handle_expt(self):
27 pass
28 smtpd.SMTPChannel.handle_expt = handle_expt
29
30
Christian Heimes5e696852008-04-09 08:37:03 +000031def server(evt, buf, serv):
Christian Heimes380f7f22008-02-28 11:19:05 +000032 serv.listen(5)
33 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000034 try:
35 conn, addr = serv.accept()
36 except socket.timeout:
37 pass
38 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000039 n = 500
40 while buf and n > 0:
41 r, w, e = select.select([], [conn], [])
42 if w:
43 sent = conn.send(buf)
44 buf = buf[sent:]
45
46 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000047
Guido van Rossumd8faa362007-04-27 19:54:29 +000048 conn.close()
49 finally:
50 serv.close()
51 evt.set()
52
Victor Stinner45df8202010-04-28 22:31:17 +000053class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000054
55 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000056 smtplib.socket = mock_socket
57 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000058
59 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000060 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000061
R. David Murray7dff9e02010-11-08 17:15:13 +000062 # This method is no longer used but is retained for backward compatibility,
63 # so test to make sure it still works.
64 def testQuoteData(self):
65 teststr = "abc\n.jkl\rfoo\r\n..blue"
66 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
67 self.assertEqual(expected, smtplib.quotedata(teststr))
68
Guido van Rossum806c2462007-08-06 23:33:07 +000069 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000070 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000071 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000072 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000073 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000074
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080075 def testSourceAddress(self):
76 mock_socket.reply_with(b"220 Hola mundo")
77 # connects
78 smtp = smtplib.SMTP(HOST, self.port,
79 source_address=('127.0.0.1',19876))
80 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
81 smtp.close()
82
Guido van Rossum806c2462007-08-06 23:33:07 +000083 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000084 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000085 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000086 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000087 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000088
89 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000090 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000091 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000092 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000093 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000094 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000095
Guido van Rossumd8faa362007-04-27 19:54:29 +000096 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000097 mock_socket.reply_with(b"220 Hola mundo")
Richard Jones64b02de2010-08-03 06:39:33 +000098 self.assertTrue(mock_socket.getdefaulttimeout() is None)
99 mock_socket.setdefaulttimeout(30)
100 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000101 try:
102 smtp = smtplib.SMTP(HOST, self.port)
103 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000104 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000106 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107
108 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000109 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000110 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 socket.setdefaulttimeout(30)
112 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000113 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000115 socket.setdefaulttimeout(None)
116 self.assertTrue(smtp.sock.gettimeout() is None)
117 smtp.close()
118
119 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000120 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000121 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000122 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000123 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124
125
Guido van Rossum04110fb2007-08-24 16:32:05 +0000126# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000127def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000128 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000129
130 try:
131 if hasattr(select, 'poll'):
132 poll_fun = asyncore.poll2
133 else:
134 poll_fun = asyncore.poll
135
136 n = 1000
137 while asyncore.socket_map and n > 0:
138 poll_fun(0.01, asyncore.socket_map)
139
140 # when the client conversation is finished, it will
141 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000142 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000143 serv.close()
144 break
145
146 n -= 1
147
148 except socket.timeout:
149 pass
150 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000151 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000152 # allow some time for the client to read the result
153 time.sleep(0.5)
154 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000155 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000156 serv_evt.set()
157
158MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
159MSG_END = '------------ END MESSAGE ------------\n'
160
Guido van Rossum04110fb2007-08-24 16:32:05 +0000161# NOTE: Some SMTP objects in the tests below are created with a non-default
162# local_hostname argument to the constructor, since (on some systems) the FQDN
163# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000164# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000165
166# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000167@unittest.skipUnless(threading, 'Threading required for this test.')
168class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000169
R. David Murray7dff9e02010-11-08 17:15:13 +0000170 maxDiff = None
171
Guido van Rossum806c2462007-08-06 23:33:07 +0000172 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000173 self.real_getfqdn = socket.getfqdn
174 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000175 # temporarily replace sys.stdout to capture DebuggingServer output
176 self.old_stdout = sys.stdout
177 self.output = io.StringIO()
178 sys.stdout = self.output
179
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000180 self._threads = support.threading_setup()
Guido van Rossum806c2462007-08-06 23:33:07 +0000181 self.serv_evt = threading.Event()
182 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000183 # Capture SMTPChannel debug output
184 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
185 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000186 # Pick a random unused port by passing 0 for the port number
187 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
188 # Keep a note of what port was assigned
189 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000190 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000191 self.thread = threading.Thread(target=debugging_server, args=serv_args)
192 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000193
194 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000195 self.serv_evt.wait()
196 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000197
198 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000199 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000200 # indicate that the client is finished
201 self.client_evt.set()
202 # wait for the server thread to terminate
203 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000204 self.thread.join()
205 support.threading_cleanup(*self._threads)
Guido van Rossum806c2462007-08-06 23:33:07 +0000206 # restore sys.stdout
207 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000208 # restore DEBUGSTREAM
209 smtpd.DEBUGSTREAM.close()
210 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000211
212 def testBasic(self):
213 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000214 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000215 smtp.quit()
216
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800217 def testSourceAddress(self):
218 # connect
Senthil Kumaranb351a482011-07-31 09:14:17 +0800219 port = support.find_unused_port()
220 try:
221 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
222 timeout=3, source_address=('127.0.0.1', port))
223 self.assertEqual(smtp.source_address, ('127.0.0.1', port))
224 self.assertEqual(smtp.local_hostname, 'localhost')
225 smtp.quit()
226 except IOError as e:
227 if e.errno == errno.EADDRINUSE:
228 self.skipTest("couldn't bind to port %d" % port)
229 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800230
Guido van Rossum04110fb2007-08-24 16:32:05 +0000231 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000232 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000233 expected = (250, b'Ok')
234 self.assertEqual(smtp.noop(), expected)
235 smtp.quit()
236
237 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000238 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000239 expected = (250, b'Ok')
240 self.assertEqual(smtp.rset(), expected)
241 smtp.quit()
242
243 def testNotImplemented(self):
244 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000245 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000246 expected = (502, b'Error: command "EHLO" not implemented')
247 self.assertEqual(smtp.ehlo(), expected)
248 smtp.quit()
249
Guido van Rossum04110fb2007-08-24 16:32:05 +0000250 def testVRFY(self):
251 # VRFY isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000252 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000253 expected = (502, b'Error: command "VRFY" not implemented')
254 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
255 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
256 smtp.quit()
257
258 def testSecondHELO(self):
259 # check that a second HELO returns a message that it's a duplicate
260 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000261 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000262 smtp.helo()
263 expected = (503, b'Duplicate HELO/EHLO')
264 self.assertEqual(smtp.helo(), expected)
265 smtp.quit()
266
Guido van Rossum806c2462007-08-06 23:33:07 +0000267 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000268 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000269 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
270 smtp.quit()
271
272 def testSend(self):
273 # connect and send mail
274 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000275 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000276 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000277 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
278 # in asyncore. This sleep might help, but should really be fixed
279 # properly by using an Event variable.
280 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000281 smtp.quit()
282
283 self.client_evt.set()
284 self.serv_evt.wait()
285 self.output.flush()
286 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
287 self.assertEqual(self.output.getvalue(), mexpect)
288
R. David Murray7dff9e02010-11-08 17:15:13 +0000289 def testSendBinary(self):
290 m = b'A test message'
291 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
292 smtp.sendmail('John', 'Sally', m)
293 # XXX (see comment in testSend)
294 time.sleep(0.01)
295 smtp.quit()
296
297 self.client_evt.set()
298 self.serv_evt.wait()
299 self.output.flush()
300 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
301 self.assertEqual(self.output.getvalue(), mexpect)
302
R David Murray0f663d02011-06-09 15:05:57 -0400303 def testSendNeedingDotQuote(self):
304 # Issue 12283
305 m = '.A test\n.mes.sage.'
306 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
307 smtp.sendmail('John', 'Sally', m)
308 # XXX (see comment in testSend)
309 time.sleep(0.01)
310 smtp.quit()
311
312 self.client_evt.set()
313 self.serv_evt.wait()
314 self.output.flush()
315 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
316 self.assertEqual(self.output.getvalue(), mexpect)
317
R David Murray46346762011-07-18 21:38:54 -0400318 def testSendNullSender(self):
319 m = 'A test message'
320 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
321 smtp.sendmail('<>', 'Sally', m)
322 # XXX (see comment in testSend)
323 time.sleep(0.01)
324 smtp.quit()
325
326 self.client_evt.set()
327 self.serv_evt.wait()
328 self.output.flush()
329 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
330 self.assertEqual(self.output.getvalue(), mexpect)
331 debugout = smtpd.DEBUGSTREAM.getvalue()
332 sender = re.compile("^sender: <>$", re.MULTILINE)
333 self.assertRegex(debugout, sender)
334
R. David Murray7dff9e02010-11-08 17:15:13 +0000335 def testSendMessage(self):
336 m = email.mime.text.MIMEText('A test message')
337 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
338 smtp.send_message(m, from_addr='John', to_addrs='Sally')
339 # XXX (see comment in testSend)
340 time.sleep(0.01)
341 smtp.quit()
342
343 self.client_evt.set()
344 self.serv_evt.wait()
345 self.output.flush()
346 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400347 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000348 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
349 self.assertEqual(self.output.getvalue(), mexpect)
350
351 def testSendMessageWithAddresses(self):
352 m = email.mime.text.MIMEText('A test message')
353 m['From'] = 'foo@bar.com'
354 m['To'] = 'John'
355 m['CC'] = 'Sally, Fred'
356 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
357 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
358 smtp.send_message(m)
359 # XXX (see comment in testSend)
360 time.sleep(0.01)
361 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400362 # make sure the Bcc header is still in the message.
363 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
364 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000365
366 self.client_evt.set()
367 self.serv_evt.wait()
368 self.output.flush()
369 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400370 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400371 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000372 del m['Bcc']
373 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
374 self.assertEqual(self.output.getvalue(), mexpect)
375 debugout = smtpd.DEBUGSTREAM.getvalue()
376 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000377 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000378 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
379 'warped@silly.walks.com'):
380 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
381 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000382 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000383
384 def testSendMessageWithSomeAddresses(self):
385 # Make sure nothing breaks if not all of the three 'to' headers exist
386 m = email.mime.text.MIMEText('A test message')
387 m['From'] = 'foo@bar.com'
388 m['To'] = 'John, Dinsdale'
389 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
390 smtp.send_message(m)
391 # XXX (see comment in testSend)
392 time.sleep(0.01)
393 smtp.quit()
394
395 self.client_evt.set()
396 self.serv_evt.wait()
397 self.output.flush()
398 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400399 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000400 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
401 self.assertEqual(self.output.getvalue(), mexpect)
402 debugout = smtpd.DEBUGSTREAM.getvalue()
403 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000404 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000405 for addr in ('John', 'Dinsdale'):
406 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
407 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000408 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000409
R David Murrayac4e5ab2011-07-02 21:03:19 -0400410 def testSendMessageWithSpecifiedAddresses(self):
411 # Make sure addresses specified in call override those in message.
412 m = email.mime.text.MIMEText('A test message')
413 m['From'] = 'foo@bar.com'
414 m['To'] = 'John, Dinsdale'
415 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
416 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
417 # XXX (see comment in testSend)
418 time.sleep(0.01)
419 smtp.quit()
420
421 self.client_evt.set()
422 self.serv_evt.wait()
423 self.output.flush()
424 # Add the X-Peer header that DebuggingServer adds
425 m['X-Peer'] = socket.gethostbyname('localhost')
426 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
427 self.assertEqual(self.output.getvalue(), mexpect)
428 debugout = smtpd.DEBUGSTREAM.getvalue()
429 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
430 self.assertRegex(debugout, sender)
431 for addr in ('John', 'Dinsdale'):
432 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
433 re.MULTILINE)
434 self.assertNotRegex(debugout, to_addr)
435 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
436 self.assertRegex(debugout, recip)
437
438 def testSendMessageWithMultipleFrom(self):
439 # Sender overrides To
440 m = email.mime.text.MIMEText('A test message')
441 m['From'] = 'Bernard, Bianca'
442 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
443 m['To'] = 'John, Dinsdale'
444 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
445 smtp.send_message(m)
446 # XXX (see comment in testSend)
447 time.sleep(0.01)
448 smtp.quit()
449
450 self.client_evt.set()
451 self.serv_evt.wait()
452 self.output.flush()
453 # Add the X-Peer header that DebuggingServer adds
454 m['X-Peer'] = socket.gethostbyname('localhost')
455 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
456 self.assertEqual(self.output.getvalue(), mexpect)
457 debugout = smtpd.DEBUGSTREAM.getvalue()
458 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
459 self.assertRegex(debugout, sender)
460 for addr in ('John', 'Dinsdale'):
461 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
462 re.MULTILINE)
463 self.assertRegex(debugout, to_addr)
464
465 def testSendMessageResent(self):
466 m = email.mime.text.MIMEText('A test message')
467 m['From'] = 'foo@bar.com'
468 m['To'] = 'John'
469 m['CC'] = 'Sally, Fred'
470 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
471 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
472 m['Resent-From'] = 'holy@grail.net'
473 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
474 m['Resent-Bcc'] = 'doe@losthope.net'
475 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
476 smtp.send_message(m)
477 # XXX (see comment in testSend)
478 time.sleep(0.01)
479 smtp.quit()
480
481 self.client_evt.set()
482 self.serv_evt.wait()
483 self.output.flush()
484 # The Resent-Bcc headers are deleted before serialization.
485 del m['Bcc']
486 del m['Resent-Bcc']
487 # Add the X-Peer header that DebuggingServer adds
488 m['X-Peer'] = socket.gethostbyname('localhost')
489 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
490 self.assertEqual(self.output.getvalue(), mexpect)
491 debugout = smtpd.DEBUGSTREAM.getvalue()
492 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
493 self.assertRegex(debugout, sender)
494 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
495 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
496 re.MULTILINE)
497 self.assertRegex(debugout, to_addr)
498
499 def testSendMessageMultipleResentRaises(self):
500 m = email.mime.text.MIMEText('A test message')
501 m['From'] = 'foo@bar.com'
502 m['To'] = 'John'
503 m['CC'] = 'Sally, Fred'
504 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
505 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
506 m['Resent-From'] = 'holy@grail.net'
507 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
508 m['Resent-Bcc'] = 'doe@losthope.net'
509 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
510 m['Resent-To'] = 'holy@grail.net'
511 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
512 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
513 with self.assertRaises(ValueError):
514 smtp.send_message(m)
515 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000516
Victor Stinner45df8202010-04-28 22:31:17 +0000517class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000518
Richard Jones64b02de2010-08-03 06:39:33 +0000519 def setUp(self):
520 smtplib.socket = mock_socket
521
522 def tearDown(self):
523 smtplib.socket = socket
524
Christian Heimes380f7f22008-02-28 11:19:05 +0000525 def testNotConnected(self):
526 # Test various operations on an unconnected SMTP object that
527 # should raise exceptions (at present the attempt in SMTP.send
528 # to reference the nonexistent 'sock' attribute of the SMTP object
529 # causes an AttributeError)
530 smtp = smtplib.SMTP()
531 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
532 self.assertRaises(smtplib.SMTPServerDisconnected,
533 smtp.send, 'test msg')
534
535 def testNonnumericPort(self):
536 # check that non-numeric port raises socket.error
Richard Jones64b02de2010-08-03 06:39:33 +0000537 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000538 "localhost", "bogus")
Richard Jones64b02de2010-08-03 06:39:33 +0000539 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000540 "localhost:bogus")
541
542
Guido van Rossum04110fb2007-08-24 16:32:05 +0000543# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000544@unittest.skipUnless(threading, 'Threading required for this test.')
545class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000546
547 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000548 smtplib.socket = mock_socket
549 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000550 self.old_stdout = sys.stdout
551 self.output = io.StringIO()
552 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000553 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000554
555 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000556 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000557 sys.stdout = self.old_stdout
558
559 def testFailingHELO(self):
560 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000561 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562
Guido van Rossum04110fb2007-08-24 16:32:05 +0000563
564sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400565 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000566 'Mrs.C@somewhereesle.com':'Ruth C',
567 }
568
R. David Murraycaa27b72009-05-23 18:49:56 +0000569sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000570sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
571 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
572sim_auth_credentials = {
573 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
574 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
575 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
576 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
577 }
578sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000579
Guido van Rossum04110fb2007-08-24 16:32:05 +0000580sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400581 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000582 }
583
584# Simulated SMTP channel & server
585class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000586
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400587 # For testing failures in QUIT when using the context manager API.
588 quit_response = None
589
R. David Murray23ddc0e2009-05-29 18:03:16 +0000590 def __init__(self, extra_features, *args, **kw):
591 self._extrafeatures = ''.join(
592 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000593 super(SimSMTPChannel, self).__init__(*args, **kw)
594
Guido van Rossum04110fb2007-08-24 16:32:05 +0000595 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000596 resp = ('250-testhost\r\n'
597 '250-EXPN\r\n'
598 '250-SIZE 20000000\r\n'
599 '250-STARTTLS\r\n'
600 '250-DELIVERBY\r\n')
601 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000602 self.push(resp)
603
604 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400605 # For max compatibility smtplib should be sending the raw address.
606 if arg in sim_users:
607 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000608 else:
609 self.push('550 No such user: %s' % arg)
610
611 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400612 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000613 if list_name in sim_lists:
614 user_list = sim_lists[list_name]
615 for n, user_email in enumerate(user_list):
616 quoted_addr = smtplib.quoteaddr(user_email)
617 if n < len(user_list) - 1:
618 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
619 else:
620 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
621 else:
622 self.push('550 No access for you!')
623
R. David Murraycaa27b72009-05-23 18:49:56 +0000624 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000625 if arg.strip().lower()=='cram-md5':
626 self.push('334 {}'.format(sim_cram_md5_challenge))
627 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000628 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000629 mech = mech.lower()
630 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000631 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000632 return
633 if mech == 'plain' and auth==sim_auth_credentials['plain']:
634 self.push('235 plain auth ok')
635 elif mech=='login' and auth==sim_auth_credentials['login']:
636 self.push('334 Password:')
637 else:
638 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000639
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400640 def smtp_QUIT(self, arg):
641 # args is ignored
642 if self.quit_response is None:
643 super(SimSMTPChannel, self).smtp_QUIT(arg)
644 else:
645 self.push(self.quit_response)
646 self.close_when_done()
647
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000648 def handle_error(self):
649 raise
650
Guido van Rossum04110fb2007-08-24 16:32:05 +0000651
652class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000653
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400654 # For testing failures in QUIT when using the context manager API.
655 quit_response = None
656
R. David Murray23ddc0e2009-05-29 18:03:16 +0000657 def __init__(self, *args, **kw):
658 self._extra_features = []
659 smtpd.SMTPServer.__init__(self, *args, **kw)
660
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000661 def handle_accepted(self, conn, addr):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400662 self._SMTPchannel = SimSMTPChannel(
663 self._extra_features, self, conn, addr)
664 self._SMTPchannel.quit_response = self.quit_response
Guido van Rossum04110fb2007-08-24 16:32:05 +0000665
666 def process_message(self, peer, mailfrom, rcpttos, data):
667 pass
668
R. David Murrayfb123912009-05-28 18:19:00 +0000669 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000670 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000671
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000672 def handle_error(self):
673 raise
674
Guido van Rossum04110fb2007-08-24 16:32:05 +0000675
676# Test various SMTP & ESMTP commands/behaviors that require a simulated server
677# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000678@unittest.skipUnless(threading, 'Threading required for this test.')
679class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000680
681 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000682 self.real_getfqdn = socket.getfqdn
683 socket.getfqdn = mock_socket.getfqdn
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000684 self._threads = support.threading_setup()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000685 self.serv_evt = threading.Event()
686 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000687 # Pick a random unused port by passing 0 for the port number
688 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
689 # Keep a note of what port was assigned
690 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000691 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000692 self.thread = threading.Thread(target=debugging_server, args=serv_args)
693 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000694
695 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000696 self.serv_evt.wait()
697 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000698
699 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000700 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000701 # indicate that the client is finished
702 self.client_evt.set()
703 # wait for the server thread to terminate
704 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000705 self.thread.join()
706 support.threading_cleanup(*self._threads)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000707
708 def testBasic(self):
709 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000710 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000711 smtp.quit()
712
713 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000714 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000715
716 # no features should be present before the EHLO
717 self.assertEqual(smtp.esmtp_features, {})
718
719 # features expected from the test server
720 expected_features = {'expn':'',
721 'size': '20000000',
722 'starttls': '',
723 'deliverby': '',
724 'help': '',
725 }
726
727 smtp.ehlo()
728 self.assertEqual(smtp.esmtp_features, expected_features)
729 for k in expected_features:
730 self.assertTrue(smtp.has_extn(k))
731 self.assertFalse(smtp.has_extn('unsupported-feature'))
732 smtp.quit()
733
734 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000735 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000736
737 for email, name in sim_users.items():
738 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000739 (name, smtplib.quoteaddr(email)),
740 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000741 self.assertEqual(smtp.vrfy(email), expected_known)
742
743 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400744 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000745 self.assertEqual(smtp.vrfy(u), expected_unknown)
746 smtp.quit()
747
748 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000749 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000750
751 for listname, members in sim_lists.items():
752 users = []
753 for m in members:
754 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000755 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000756 self.assertEqual(smtp.expn(listname), expected_known)
757
758 u = 'PSU-Members-List'
759 expected_unknown = (550, b'No access for you!')
760 self.assertEqual(smtp.expn(u), expected_unknown)
761 smtp.quit()
762
R. David Murrayfb123912009-05-28 18:19:00 +0000763 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000764 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000765 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000766
R. David Murrayfb123912009-05-28 18:19:00 +0000767 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000768 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Benjamin Petersond094efd2010-10-31 17:15:42 +0000769 smtp.close()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000770
R. David Murrayfb123912009-05-28 18:19:00 +0000771 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
772 # require a synchronous read to obtain the credentials...so instead smtpd
773 # sees the credential sent by smtplib's login method as an unknown command,
774 # which results in smtplib raising an auth error. Fortunately the error
775 # message contains the encoded credential, so we can partially check that it
776 # was generated correctly (partially, because the 'word' is uppercased in
777 # the error message).
778
779 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000780 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000781 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000782 try: smtp.login(sim_auth[0], sim_auth[1])
783 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000784 self.assertIn(sim_auth_login_password, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000785 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000786
787 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000788 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000789 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000790
791 try: smtp.login(sim_auth[0], sim_auth[1])
792 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000793 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000794 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000795
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400796 def test_with_statement(self):
797 with smtplib.SMTP(HOST, self.port) as smtp:
798 code, message = smtp.noop()
799 self.assertEqual(code, 250)
800 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
801 with smtplib.SMTP(HOST, self.port) as smtp:
802 smtp.close()
803 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
804
805 def test_with_statement_QUIT_failure(self):
806 self.serv.quit_response = '421 QUIT FAILED'
807 with self.assertRaises(smtplib.SMTPResponseException) as error:
808 with smtplib.SMTP(HOST, self.port) as smtp:
809 smtp.noop()
810 self.assertEqual(error.exception.smtp_code, 421)
811 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
812 # We don't need to clean up self.serv.quit_response because a new
813 # server is always instantiated in the setUp().
814
R. David Murrayfb123912009-05-28 18:19:00 +0000815 #TODO: add tests for correct AUTH method fallback now that the
816 #test infrastructure can support it.
817
Guido van Rossum04110fb2007-08-24 16:32:05 +0000818
Guido van Rossumd8faa362007-04-27 19:54:29 +0000819def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000820 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000821 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000822 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000823
824if __name__ == '__main__':
825 test_main()