blob: 18dde2f4406525269c205de1699374e249f024f6 [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
Ross Lagerwall86407432012-03-29 18:08:48 +020012import errno
Guido van Rossumd8faa362007-04-27 19:54:29 +000013
Victor Stinner45df8202010-04-28 22:31:17 +000014import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000015from test import support, mock_socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000016
Victor Stinner45df8202010-04-28 22:31:17 +000017try:
18 import threading
19except ImportError:
20 threading = None
21
Benjamin Petersonee8712c2008-05-20 21:35:26 +000022HOST = support.HOST
Guido van Rossumd8faa362007-04-27 19:54:29 +000023
Josiah Carlsond74900e2008-07-07 04:15:08 +000024if sys.platform == 'darwin':
25 # select.poll returns a select.POLLHUP at the end of the tests
26 # on darwin, so just ignore it
27 def handle_expt(self):
28 pass
29 smtpd.SMTPChannel.handle_expt = handle_expt
30
31
Christian Heimes5e696852008-04-09 08:37:03 +000032def server(evt, buf, serv):
Christian Heimes380f7f22008-02-28 11:19:05 +000033 serv.listen(5)
34 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000035 try:
36 conn, addr = serv.accept()
37 except socket.timeout:
38 pass
39 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000040 n = 500
41 while buf and n > 0:
42 r, w, e = select.select([], [conn], [])
43 if w:
44 sent = conn.send(buf)
45 buf = buf[sent:]
46
47 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000048
Guido van Rossumd8faa362007-04-27 19:54:29 +000049 conn.close()
50 finally:
51 serv.close()
52 evt.set()
53
Victor Stinner45df8202010-04-28 22:31:17 +000054class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000055
56 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000057 smtplib.socket = mock_socket
58 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000059
60 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000061 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000062
R. David Murray7dff9e02010-11-08 17:15:13 +000063 # This method is no longer used but is retained for backward compatibility,
64 # so test to make sure it still works.
65 def testQuoteData(self):
66 teststr = "abc\n.jkl\rfoo\r\n..blue"
67 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
68 self.assertEqual(expected, smtplib.quotedata(teststr))
69
Guido van Rossum806c2462007-08-06 23:33:07 +000070 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000071 mock_socket.reply_with(b"220 Hola mundo")
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
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080076 def testSourceAddress(self):
77 mock_socket.reply_with(b"220 Hola mundo")
78 # connects
79 smtp = smtplib.SMTP(HOST, self.port,
80 source_address=('127.0.0.1',19876))
81 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
82 smtp.close()
83
Guido van Rossum806c2462007-08-06 23:33:07 +000084 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000085 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000086 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000087 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000088 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000089
90 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000091 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000092 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000093 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000094 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000095 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000096
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000098 mock_socket.reply_with(b"220 Hola mundo")
Richard Jones64b02de2010-08-03 06:39:33 +000099 self.assertTrue(mock_socket.getdefaulttimeout() is None)
100 mock_socket.setdefaulttimeout(30)
101 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000102 try:
103 smtp = smtplib.SMTP(HOST, self.port)
104 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000105 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000107 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108
109 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000110 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000111 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 socket.setdefaulttimeout(30)
113 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000114 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000116 socket.setdefaulttimeout(None)
117 self.assertTrue(smtp.sock.gettimeout() is None)
118 smtp.close()
119
120 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000121 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000122 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000124 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125
126
Guido van Rossum04110fb2007-08-24 16:32:05 +0000127# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000128def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000129 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000130
131 try:
132 if hasattr(select, 'poll'):
133 poll_fun = asyncore.poll2
134 else:
135 poll_fun = asyncore.poll
136
137 n = 1000
138 while asyncore.socket_map and n > 0:
139 poll_fun(0.01, asyncore.socket_map)
140
141 # when the client conversation is finished, it will
142 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000143 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000144 serv.close()
145 break
146
147 n -= 1
148
149 except socket.timeout:
150 pass
151 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000152 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000153 # allow some time for the client to read the result
154 time.sleep(0.5)
155 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000156 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000157 serv_evt.set()
158
159MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
160MSG_END = '------------ END MESSAGE ------------\n'
161
Guido van Rossum04110fb2007-08-24 16:32:05 +0000162# NOTE: Some SMTP objects in the tests below are created with a non-default
163# local_hostname argument to the constructor, since (on some systems) the FQDN
164# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000165# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000166
167# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000168@unittest.skipUnless(threading, 'Threading required for this test.')
169class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000170
R. David Murray7dff9e02010-11-08 17:15:13 +0000171 maxDiff = None
172
Guido van Rossum806c2462007-08-06 23:33:07 +0000173 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000174 self.real_getfqdn = socket.getfqdn
175 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000176 # temporarily replace sys.stdout to capture DebuggingServer output
177 self.old_stdout = sys.stdout
178 self.output = io.StringIO()
179 sys.stdout = self.output
180
181 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()
Guido van Rossum806c2462007-08-06 23:33:07 +0000205 # restore sys.stdout
206 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000207 # restore DEBUGSTREAM
208 smtpd.DEBUGSTREAM.close()
209 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000210
211 def testBasic(self):
212 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000213 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000214 smtp.quit()
215
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800216 def testSourceAddress(self):
217 # connect
Senthil Kumaranb351a482011-07-31 09:14:17 +0800218 port = support.find_unused_port()
219 try:
220 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
221 timeout=3, source_address=('127.0.0.1', port))
222 self.assertEqual(smtp.source_address, ('127.0.0.1', port))
223 self.assertEqual(smtp.local_hostname, 'localhost')
224 smtp.quit()
225 except IOError as e:
226 if e.errno == errno.EADDRINUSE:
227 self.skipTest("couldn't bind to port %d" % port)
228 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800229
Guido van Rossum04110fb2007-08-24 16:32:05 +0000230 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000231 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000232 expected = (250, b'Ok')
233 self.assertEqual(smtp.noop(), expected)
234 smtp.quit()
235
236 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000237 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000238 expected = (250, b'Ok')
239 self.assertEqual(smtp.rset(), expected)
240 smtp.quit()
241
242 def testNotImplemented(self):
243 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000244 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000245 expected = (502, b'Error: command "EHLO" not implemented')
246 self.assertEqual(smtp.ehlo(), expected)
247 smtp.quit()
248
Guido van Rossum04110fb2007-08-24 16:32:05 +0000249 def testVRFY(self):
250 # VRFY isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000251 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000252 expected = (502, b'Error: command "VRFY" not implemented')
253 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
254 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
255 smtp.quit()
256
257 def testSecondHELO(self):
258 # check that a second HELO returns a message that it's a duplicate
259 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000260 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000261 smtp.helo()
262 expected = (503, b'Duplicate HELO/EHLO')
263 self.assertEqual(smtp.helo(), expected)
264 smtp.quit()
265
Guido van Rossum806c2462007-08-06 23:33:07 +0000266 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000267 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000268 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
269 smtp.quit()
270
271 def testSend(self):
272 # connect and send mail
273 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000274 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000275 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000276 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
277 # in asyncore. This sleep might help, but should really be fixed
278 # properly by using an Event variable.
279 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000280 smtp.quit()
281
282 self.client_evt.set()
283 self.serv_evt.wait()
284 self.output.flush()
285 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
286 self.assertEqual(self.output.getvalue(), mexpect)
287
R. David Murray7dff9e02010-11-08 17:15:13 +0000288 def testSendBinary(self):
289 m = b'A test message'
290 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
291 smtp.sendmail('John', 'Sally', m)
292 # XXX (see comment in testSend)
293 time.sleep(0.01)
294 smtp.quit()
295
296 self.client_evt.set()
297 self.serv_evt.wait()
298 self.output.flush()
299 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
300 self.assertEqual(self.output.getvalue(), mexpect)
301
R David Murray0f663d02011-06-09 15:05:57 -0400302 def testSendNeedingDotQuote(self):
303 # Issue 12283
304 m = '.A test\n.mes.sage.'
305 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
306 smtp.sendmail('John', 'Sally', m)
307 # XXX (see comment in testSend)
308 time.sleep(0.01)
309 smtp.quit()
310
311 self.client_evt.set()
312 self.serv_evt.wait()
313 self.output.flush()
314 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
315 self.assertEqual(self.output.getvalue(), mexpect)
316
R David Murray46346762011-07-18 21:38:54 -0400317 def testSendNullSender(self):
318 m = 'A test message'
319 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
320 smtp.sendmail('<>', 'Sally', m)
321 # XXX (see comment in testSend)
322 time.sleep(0.01)
323 smtp.quit()
324
325 self.client_evt.set()
326 self.serv_evt.wait()
327 self.output.flush()
328 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
329 self.assertEqual(self.output.getvalue(), mexpect)
330 debugout = smtpd.DEBUGSTREAM.getvalue()
331 sender = re.compile("^sender: <>$", re.MULTILINE)
332 self.assertRegex(debugout, sender)
333
R. David Murray7dff9e02010-11-08 17:15:13 +0000334 def testSendMessage(self):
335 m = email.mime.text.MIMEText('A test message')
336 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
337 smtp.send_message(m, from_addr='John', to_addrs='Sally')
338 # XXX (see comment in testSend)
339 time.sleep(0.01)
340 smtp.quit()
341
342 self.client_evt.set()
343 self.serv_evt.wait()
344 self.output.flush()
345 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400346 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000347 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
348 self.assertEqual(self.output.getvalue(), mexpect)
349
350 def testSendMessageWithAddresses(self):
351 m = email.mime.text.MIMEText('A test message')
352 m['From'] = 'foo@bar.com'
353 m['To'] = 'John'
354 m['CC'] = 'Sally, Fred'
355 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
356 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
357 smtp.send_message(m)
358 # XXX (see comment in testSend)
359 time.sleep(0.01)
360 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400361 # make sure the Bcc header is still in the message.
362 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
363 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000364
365 self.client_evt.set()
366 self.serv_evt.wait()
367 self.output.flush()
368 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400369 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400370 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000371 del m['Bcc']
372 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
373 self.assertEqual(self.output.getvalue(), mexpect)
374 debugout = smtpd.DEBUGSTREAM.getvalue()
375 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000376 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000377 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
378 'warped@silly.walks.com'):
379 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
380 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000381 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000382
383 def testSendMessageWithSomeAddresses(self):
384 # Make sure nothing breaks if not all of the three 'to' headers exist
385 m = email.mime.text.MIMEText('A test message')
386 m['From'] = 'foo@bar.com'
387 m['To'] = 'John, Dinsdale'
388 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
389 smtp.send_message(m)
390 # XXX (see comment in testSend)
391 time.sleep(0.01)
392 smtp.quit()
393
394 self.client_evt.set()
395 self.serv_evt.wait()
396 self.output.flush()
397 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400398 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000399 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
400 self.assertEqual(self.output.getvalue(), mexpect)
401 debugout = smtpd.DEBUGSTREAM.getvalue()
402 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000403 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000404 for addr in ('John', 'Dinsdale'):
405 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
406 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000407 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000408
R David Murrayac4e5ab2011-07-02 21:03:19 -0400409 def testSendMessageWithSpecifiedAddresses(self):
410 # Make sure addresses specified in call override those in message.
411 m = email.mime.text.MIMEText('A test message')
412 m['From'] = 'foo@bar.com'
413 m['To'] = 'John, Dinsdale'
414 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
415 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
416 # XXX (see comment in testSend)
417 time.sleep(0.01)
418 smtp.quit()
419
420 self.client_evt.set()
421 self.serv_evt.wait()
422 self.output.flush()
423 # Add the X-Peer header that DebuggingServer adds
424 m['X-Peer'] = socket.gethostbyname('localhost')
425 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
426 self.assertEqual(self.output.getvalue(), mexpect)
427 debugout = smtpd.DEBUGSTREAM.getvalue()
428 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
429 self.assertRegex(debugout, sender)
430 for addr in ('John', 'Dinsdale'):
431 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
432 re.MULTILINE)
433 self.assertNotRegex(debugout, to_addr)
434 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
435 self.assertRegex(debugout, recip)
436
437 def testSendMessageWithMultipleFrom(self):
438 # Sender overrides To
439 m = email.mime.text.MIMEText('A test message')
440 m['From'] = 'Bernard, Bianca'
441 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
442 m['To'] = 'John, Dinsdale'
443 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
444 smtp.send_message(m)
445 # XXX (see comment in testSend)
446 time.sleep(0.01)
447 smtp.quit()
448
449 self.client_evt.set()
450 self.serv_evt.wait()
451 self.output.flush()
452 # Add the X-Peer header that DebuggingServer adds
453 m['X-Peer'] = socket.gethostbyname('localhost')
454 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
455 self.assertEqual(self.output.getvalue(), mexpect)
456 debugout = smtpd.DEBUGSTREAM.getvalue()
457 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
458 self.assertRegex(debugout, sender)
459 for addr in ('John', 'Dinsdale'):
460 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
461 re.MULTILINE)
462 self.assertRegex(debugout, to_addr)
463
464 def testSendMessageResent(self):
465 m = email.mime.text.MIMEText('A test message')
466 m['From'] = 'foo@bar.com'
467 m['To'] = 'John'
468 m['CC'] = 'Sally, Fred'
469 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
470 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
471 m['Resent-From'] = 'holy@grail.net'
472 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
473 m['Resent-Bcc'] = 'doe@losthope.net'
474 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
475 smtp.send_message(m)
476 # XXX (see comment in testSend)
477 time.sleep(0.01)
478 smtp.quit()
479
480 self.client_evt.set()
481 self.serv_evt.wait()
482 self.output.flush()
483 # The Resent-Bcc headers are deleted before serialization.
484 del m['Bcc']
485 del m['Resent-Bcc']
486 # Add the X-Peer header that DebuggingServer adds
487 m['X-Peer'] = socket.gethostbyname('localhost')
488 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
489 self.assertEqual(self.output.getvalue(), mexpect)
490 debugout = smtpd.DEBUGSTREAM.getvalue()
491 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
492 self.assertRegex(debugout, sender)
493 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
494 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
495 re.MULTILINE)
496 self.assertRegex(debugout, to_addr)
497
498 def testSendMessageMultipleResentRaises(self):
499 m = email.mime.text.MIMEText('A test message')
500 m['From'] = 'foo@bar.com'
501 m['To'] = 'John'
502 m['CC'] = 'Sally, Fred'
503 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
504 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
505 m['Resent-From'] = 'holy@grail.net'
506 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
507 m['Resent-Bcc'] = 'doe@losthope.net'
508 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
509 m['Resent-To'] = 'holy@grail.net'
510 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
511 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
512 with self.assertRaises(ValueError):
513 smtp.send_message(m)
514 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000515
Victor Stinner45df8202010-04-28 22:31:17 +0000516class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000517
Richard Jones64b02de2010-08-03 06:39:33 +0000518 def setUp(self):
519 smtplib.socket = mock_socket
520
521 def tearDown(self):
522 smtplib.socket = socket
523
Christian Heimes380f7f22008-02-28 11:19:05 +0000524 def testNotConnected(self):
525 # Test various operations on an unconnected SMTP object that
526 # should raise exceptions (at present the attempt in SMTP.send
527 # to reference the nonexistent 'sock' attribute of the SMTP object
528 # causes an AttributeError)
529 smtp = smtplib.SMTP()
530 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
531 self.assertRaises(smtplib.SMTPServerDisconnected,
532 smtp.send, 'test msg')
533
534 def testNonnumericPort(self):
535 # check that non-numeric port raises socket.error
Richard Jones64b02de2010-08-03 06:39:33 +0000536 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000537 "localhost", "bogus")
Richard Jones64b02de2010-08-03 06:39:33 +0000538 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000539 "localhost:bogus")
540
541
Guido van Rossum04110fb2007-08-24 16:32:05 +0000542# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000543@unittest.skipUnless(threading, 'Threading required for this test.')
544class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000545
546 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000547 smtplib.socket = mock_socket
548 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000549 self.old_stdout = sys.stdout
550 self.output = io.StringIO()
551 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000552 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000553
554 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000555 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000556 sys.stdout = self.old_stdout
557
558 def testFailingHELO(self):
559 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000560 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561
Guido van Rossum04110fb2007-08-24 16:32:05 +0000562
563sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400564 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000565 'Mrs.C@somewhereesle.com':'Ruth C',
566 }
567
R. David Murraycaa27b72009-05-23 18:49:56 +0000568sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000569sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
570 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
571sim_auth_credentials = {
572 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
573 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
574 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
575 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
576 }
577sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000578
Guido van Rossum04110fb2007-08-24 16:32:05 +0000579sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400580 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000581 }
582
583# Simulated SMTP channel & server
584class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000585
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400586 # For testing failures in QUIT when using the context manager API.
587 quit_response = None
588
R. David Murray23ddc0e2009-05-29 18:03:16 +0000589 def __init__(self, extra_features, *args, **kw):
590 self._extrafeatures = ''.join(
591 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000592 super(SimSMTPChannel, self).__init__(*args, **kw)
593
Guido van Rossum04110fb2007-08-24 16:32:05 +0000594 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000595 resp = ('250-testhost\r\n'
596 '250-EXPN\r\n'
597 '250-SIZE 20000000\r\n'
598 '250-STARTTLS\r\n'
599 '250-DELIVERBY\r\n')
600 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000601 self.push(resp)
602
603 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400604 # For max compatibility smtplib should be sending the raw address.
605 if arg in sim_users:
606 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000607 else:
608 self.push('550 No such user: %s' % arg)
609
610 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400611 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000612 if list_name in sim_lists:
613 user_list = sim_lists[list_name]
614 for n, user_email in enumerate(user_list):
615 quoted_addr = smtplib.quoteaddr(user_email)
616 if n < len(user_list) - 1:
617 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
618 else:
619 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
620 else:
621 self.push('550 No access for you!')
622
R. David Murraycaa27b72009-05-23 18:49:56 +0000623 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000624 if arg.strip().lower()=='cram-md5':
625 self.push('334 {}'.format(sim_cram_md5_challenge))
626 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000627 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000628 mech = mech.lower()
629 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000630 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000631 return
632 if mech == 'plain' and auth==sim_auth_credentials['plain']:
633 self.push('235 plain auth ok')
634 elif mech=='login' and auth==sim_auth_credentials['login']:
635 self.push('334 Password:')
636 else:
637 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000638
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400639 def smtp_QUIT(self, arg):
640 # args is ignored
641 if self.quit_response is None:
642 super(SimSMTPChannel, self).smtp_QUIT(arg)
643 else:
644 self.push(self.quit_response)
645 self.close_when_done()
646
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000647 def handle_error(self):
648 raise
649
Guido van Rossum04110fb2007-08-24 16:32:05 +0000650
651class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000652
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400653 # For testing failures in QUIT when using the context manager API.
654 quit_response = None
655
R. David Murray23ddc0e2009-05-29 18:03:16 +0000656 def __init__(self, *args, **kw):
657 self._extra_features = []
658 smtpd.SMTPServer.__init__(self, *args, **kw)
659
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000660 def handle_accepted(self, conn, addr):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400661 self._SMTPchannel = SimSMTPChannel(
662 self._extra_features, self, conn, addr)
663 self._SMTPchannel.quit_response = self.quit_response
Guido van Rossum04110fb2007-08-24 16:32:05 +0000664
665 def process_message(self, peer, mailfrom, rcpttos, data):
666 pass
667
R. David Murrayfb123912009-05-28 18:19:00 +0000668 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000669 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000670
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000671 def handle_error(self):
672 raise
673
Guido van Rossum04110fb2007-08-24 16:32:05 +0000674
675# Test various SMTP & ESMTP commands/behaviors that require a simulated server
676# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000677@unittest.skipUnless(threading, 'Threading required for this test.')
678class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000679
680 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000681 self.real_getfqdn = socket.getfqdn
682 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000683 self.serv_evt = threading.Event()
684 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000685 # Pick a random unused port by passing 0 for the port number
686 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
687 # Keep a note of what port was assigned
688 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000689 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000690 self.thread = threading.Thread(target=debugging_server, args=serv_args)
691 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000692
693 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000694 self.serv_evt.wait()
695 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000696
697 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000698 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000699 # indicate that the client is finished
700 self.client_evt.set()
701 # wait for the server thread to terminate
702 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000703 self.thread.join()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000704
705 def testBasic(self):
706 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000707 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000708 smtp.quit()
709
710 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000711 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000712
713 # no features should be present before the EHLO
714 self.assertEqual(smtp.esmtp_features, {})
715
716 # features expected from the test server
717 expected_features = {'expn':'',
718 'size': '20000000',
719 'starttls': '',
720 'deliverby': '',
721 'help': '',
722 }
723
724 smtp.ehlo()
725 self.assertEqual(smtp.esmtp_features, expected_features)
726 for k in expected_features:
727 self.assertTrue(smtp.has_extn(k))
728 self.assertFalse(smtp.has_extn('unsupported-feature'))
729 smtp.quit()
730
731 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000732 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000733
734 for email, name in sim_users.items():
735 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000736 (name, smtplib.quoteaddr(email)),
737 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000738 self.assertEqual(smtp.vrfy(email), expected_known)
739
740 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400741 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000742 self.assertEqual(smtp.vrfy(u), expected_unknown)
743 smtp.quit()
744
745 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000746 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000747
748 for listname, members in sim_lists.items():
749 users = []
750 for m in members:
751 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000752 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000753 self.assertEqual(smtp.expn(listname), expected_known)
754
755 u = 'PSU-Members-List'
756 expected_unknown = (550, b'No access for you!')
757 self.assertEqual(smtp.expn(u), expected_unknown)
758 smtp.quit()
759
R. David Murrayfb123912009-05-28 18:19:00 +0000760 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000761 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000762 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000763
R. David Murrayfb123912009-05-28 18:19:00 +0000764 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000765 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Benjamin Petersond094efd2010-10-31 17:15:42 +0000766 smtp.close()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000767
R. David Murrayfb123912009-05-28 18:19:00 +0000768 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
769 # require a synchronous read to obtain the credentials...so instead smtpd
770 # sees the credential sent by smtplib's login method as an unknown command,
771 # which results in smtplib raising an auth error. Fortunately the error
772 # message contains the encoded credential, so we can partially check that it
773 # was generated correctly (partially, because the 'word' is uppercased in
774 # the error message).
775
776 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000777 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000778 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000779 try: smtp.login(sim_auth[0], sim_auth[1])
780 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000781 self.assertIn(sim_auth_login_password, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000782 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000783
784 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000785 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000786 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000787
788 try: smtp.login(sim_auth[0], sim_auth[1])
789 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000790 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000791 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000792
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400793 def test_with_statement(self):
794 with smtplib.SMTP(HOST, self.port) as smtp:
795 code, message = smtp.noop()
796 self.assertEqual(code, 250)
797 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
798 with smtplib.SMTP(HOST, self.port) as smtp:
799 smtp.close()
800 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
801
802 def test_with_statement_QUIT_failure(self):
803 self.serv.quit_response = '421 QUIT FAILED'
804 with self.assertRaises(smtplib.SMTPResponseException) as error:
805 with smtplib.SMTP(HOST, self.port) as smtp:
806 smtp.noop()
807 self.assertEqual(error.exception.smtp_code, 421)
808 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
809 # We don't need to clean up self.serv.quit_response because a new
810 # server is always instantiated in the setUp().
811
R. David Murrayfb123912009-05-28 18:19:00 +0000812 #TODO: add tests for correct AUTH method fallback now that the
813 #test infrastructure can support it.
814
Guido van Rossum04110fb2007-08-24 16:32:05 +0000815
Antoine Pitroud54fa552011-08-28 01:23:52 +0200816@support.reap_threads
Guido van Rossumd8faa362007-04-27 19:54:29 +0000817def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000818 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000819 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000820 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000821
822if __name__ == '__main__':
823 test_main()