blob: 05d97ef4b7ebfc7c7f0876ede35a14efacb183a0 [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
180 self.serv_evt = threading.Event()
181 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000182 # Capture SMTPChannel debug output
183 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
184 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000185 # Pick a random unused port by passing 0 for the port number
186 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
187 # Keep a note of what port was assigned
188 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000189 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000190 self.thread = threading.Thread(target=debugging_server, args=serv_args)
191 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000192
193 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000194 self.serv_evt.wait()
195 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000196
197 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000198 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000199 # indicate that the client is finished
200 self.client_evt.set()
201 # wait for the server thread to terminate
202 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000203 self.thread.join()
Guido van Rossum806c2462007-08-06 23:33:07 +0000204 # restore sys.stdout
205 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000206 # restore DEBUGSTREAM
207 smtpd.DEBUGSTREAM.close()
208 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000209
210 def testBasic(self):
211 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000212 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000213 smtp.quit()
214
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800215 def testSourceAddress(self):
216 # connect
Senthil Kumaranb351a482011-07-31 09:14:17 +0800217 port = support.find_unused_port()
218 try:
219 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
220 timeout=3, source_address=('127.0.0.1', port))
221 self.assertEqual(smtp.source_address, ('127.0.0.1', port))
222 self.assertEqual(smtp.local_hostname, 'localhost')
223 smtp.quit()
224 except IOError as e:
225 if e.errno == errno.EADDRINUSE:
226 self.skipTest("couldn't bind to port %d" % port)
227 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800228
Guido van Rossum04110fb2007-08-24 16:32:05 +0000229 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000230 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000231 expected = (250, b'Ok')
232 self.assertEqual(smtp.noop(), expected)
233 smtp.quit()
234
235 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000236 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000237 expected = (250, b'Ok')
238 self.assertEqual(smtp.rset(), expected)
239 smtp.quit()
240
241 def testNotImplemented(self):
242 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000243 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000244 expected = (502, b'Error: command "EHLO" not implemented')
245 self.assertEqual(smtp.ehlo(), expected)
246 smtp.quit()
247
Guido van Rossum04110fb2007-08-24 16:32:05 +0000248 def testVRFY(self):
249 # VRFY isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000250 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000251 expected = (502, b'Error: command "VRFY" not implemented')
252 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
253 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
254 smtp.quit()
255
256 def testSecondHELO(self):
257 # check that a second HELO returns a message that it's a duplicate
258 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000259 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000260 smtp.helo()
261 expected = (503, b'Duplicate HELO/EHLO')
262 self.assertEqual(smtp.helo(), expected)
263 smtp.quit()
264
Guido van Rossum806c2462007-08-06 23:33:07 +0000265 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000266 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000267 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
268 smtp.quit()
269
270 def testSend(self):
271 # connect and send mail
272 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000273 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000274 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000275 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
276 # in asyncore. This sleep might help, but should really be fixed
277 # properly by using an Event variable.
278 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000279 smtp.quit()
280
281 self.client_evt.set()
282 self.serv_evt.wait()
283 self.output.flush()
284 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
285 self.assertEqual(self.output.getvalue(), mexpect)
286
R. David Murray7dff9e02010-11-08 17:15:13 +0000287 def testSendBinary(self):
288 m = b'A test message'
289 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
290 smtp.sendmail('John', 'Sally', m)
291 # XXX (see comment in testSend)
292 time.sleep(0.01)
293 smtp.quit()
294
295 self.client_evt.set()
296 self.serv_evt.wait()
297 self.output.flush()
298 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
299 self.assertEqual(self.output.getvalue(), mexpect)
300
R David Murray0f663d02011-06-09 15:05:57 -0400301 def testSendNeedingDotQuote(self):
302 # Issue 12283
303 m = '.A test\n.mes.sage.'
304 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
305 smtp.sendmail('John', 'Sally', m)
306 # XXX (see comment in testSend)
307 time.sleep(0.01)
308 smtp.quit()
309
310 self.client_evt.set()
311 self.serv_evt.wait()
312 self.output.flush()
313 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
314 self.assertEqual(self.output.getvalue(), mexpect)
315
R David Murray46346762011-07-18 21:38:54 -0400316 def testSendNullSender(self):
317 m = 'A test message'
318 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
319 smtp.sendmail('<>', 'Sally', m)
320 # XXX (see comment in testSend)
321 time.sleep(0.01)
322 smtp.quit()
323
324 self.client_evt.set()
325 self.serv_evt.wait()
326 self.output.flush()
327 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
328 self.assertEqual(self.output.getvalue(), mexpect)
329 debugout = smtpd.DEBUGSTREAM.getvalue()
330 sender = re.compile("^sender: <>$", re.MULTILINE)
331 self.assertRegex(debugout, sender)
332
R. David Murray7dff9e02010-11-08 17:15:13 +0000333 def testSendMessage(self):
334 m = email.mime.text.MIMEText('A test message')
335 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
336 smtp.send_message(m, from_addr='John', to_addrs='Sally')
337 # XXX (see comment in testSend)
338 time.sleep(0.01)
339 smtp.quit()
340
341 self.client_evt.set()
342 self.serv_evt.wait()
343 self.output.flush()
344 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400345 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000346 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
347 self.assertEqual(self.output.getvalue(), mexpect)
348
349 def testSendMessageWithAddresses(self):
350 m = email.mime.text.MIMEText('A test message')
351 m['From'] = 'foo@bar.com'
352 m['To'] = 'John'
353 m['CC'] = 'Sally, Fred'
354 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
355 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
356 smtp.send_message(m)
357 # XXX (see comment in testSend)
358 time.sleep(0.01)
359 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400360 # make sure the Bcc header is still in the message.
361 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
362 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000363
364 self.client_evt.set()
365 self.serv_evt.wait()
366 self.output.flush()
367 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400368 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400369 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000370 del m['Bcc']
371 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
372 self.assertEqual(self.output.getvalue(), mexpect)
373 debugout = smtpd.DEBUGSTREAM.getvalue()
374 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000375 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000376 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
377 'warped@silly.walks.com'):
378 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
379 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000380 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000381
382 def testSendMessageWithSomeAddresses(self):
383 # Make sure nothing breaks if not all of the three 'to' headers exist
384 m = email.mime.text.MIMEText('A test message')
385 m['From'] = 'foo@bar.com'
386 m['To'] = 'John, Dinsdale'
387 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
388 smtp.send_message(m)
389 # XXX (see comment in testSend)
390 time.sleep(0.01)
391 smtp.quit()
392
393 self.client_evt.set()
394 self.serv_evt.wait()
395 self.output.flush()
396 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400397 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000398 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
399 self.assertEqual(self.output.getvalue(), mexpect)
400 debugout = smtpd.DEBUGSTREAM.getvalue()
401 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000402 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000403 for addr in ('John', 'Dinsdale'):
404 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
405 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000406 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000407
R David Murrayac4e5ab2011-07-02 21:03:19 -0400408 def testSendMessageWithSpecifiedAddresses(self):
409 # Make sure addresses specified in call override those in message.
410 m = email.mime.text.MIMEText('A test message')
411 m['From'] = 'foo@bar.com'
412 m['To'] = 'John, Dinsdale'
413 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
414 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
415 # XXX (see comment in testSend)
416 time.sleep(0.01)
417 smtp.quit()
418
419 self.client_evt.set()
420 self.serv_evt.wait()
421 self.output.flush()
422 # Add the X-Peer header that DebuggingServer adds
423 m['X-Peer'] = socket.gethostbyname('localhost')
424 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
425 self.assertEqual(self.output.getvalue(), mexpect)
426 debugout = smtpd.DEBUGSTREAM.getvalue()
427 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
428 self.assertRegex(debugout, sender)
429 for addr in ('John', 'Dinsdale'):
430 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
431 re.MULTILINE)
432 self.assertNotRegex(debugout, to_addr)
433 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
434 self.assertRegex(debugout, recip)
435
436 def testSendMessageWithMultipleFrom(self):
437 # Sender overrides To
438 m = email.mime.text.MIMEText('A test message')
439 m['From'] = 'Bernard, Bianca'
440 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
441 m['To'] = 'John, Dinsdale'
442 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
443 smtp.send_message(m)
444 # XXX (see comment in testSend)
445 time.sleep(0.01)
446 smtp.quit()
447
448 self.client_evt.set()
449 self.serv_evt.wait()
450 self.output.flush()
451 # Add the X-Peer header that DebuggingServer adds
452 m['X-Peer'] = socket.gethostbyname('localhost')
453 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
454 self.assertEqual(self.output.getvalue(), mexpect)
455 debugout = smtpd.DEBUGSTREAM.getvalue()
456 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
457 self.assertRegex(debugout, sender)
458 for addr in ('John', 'Dinsdale'):
459 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
460 re.MULTILINE)
461 self.assertRegex(debugout, to_addr)
462
463 def testSendMessageResent(self):
464 m = email.mime.text.MIMEText('A test message')
465 m['From'] = 'foo@bar.com'
466 m['To'] = 'John'
467 m['CC'] = 'Sally, Fred'
468 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
469 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
470 m['Resent-From'] = 'holy@grail.net'
471 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
472 m['Resent-Bcc'] = 'doe@losthope.net'
473 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
474 smtp.send_message(m)
475 # XXX (see comment in testSend)
476 time.sleep(0.01)
477 smtp.quit()
478
479 self.client_evt.set()
480 self.serv_evt.wait()
481 self.output.flush()
482 # The Resent-Bcc headers are deleted before serialization.
483 del m['Bcc']
484 del m['Resent-Bcc']
485 # Add the X-Peer header that DebuggingServer adds
486 m['X-Peer'] = socket.gethostbyname('localhost')
487 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
488 self.assertEqual(self.output.getvalue(), mexpect)
489 debugout = smtpd.DEBUGSTREAM.getvalue()
490 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
491 self.assertRegex(debugout, sender)
492 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
493 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
494 re.MULTILINE)
495 self.assertRegex(debugout, to_addr)
496
497 def testSendMessageMultipleResentRaises(self):
498 m = email.mime.text.MIMEText('A test message')
499 m['From'] = 'foo@bar.com'
500 m['To'] = 'John'
501 m['CC'] = 'Sally, Fred'
502 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
503 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
504 m['Resent-From'] = 'holy@grail.net'
505 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
506 m['Resent-Bcc'] = 'doe@losthope.net'
507 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
508 m['Resent-To'] = 'holy@grail.net'
509 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
510 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
511 with self.assertRaises(ValueError):
512 smtp.send_message(m)
513 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000514
Victor Stinner45df8202010-04-28 22:31:17 +0000515class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000516
Richard Jones64b02de2010-08-03 06:39:33 +0000517 def setUp(self):
518 smtplib.socket = mock_socket
519
520 def tearDown(self):
521 smtplib.socket = socket
522
Christian Heimes380f7f22008-02-28 11:19:05 +0000523 def testNotConnected(self):
524 # Test various operations on an unconnected SMTP object that
525 # should raise exceptions (at present the attempt in SMTP.send
526 # to reference the nonexistent 'sock' attribute of the SMTP object
527 # causes an AttributeError)
528 smtp = smtplib.SMTP()
529 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
530 self.assertRaises(smtplib.SMTPServerDisconnected,
531 smtp.send, 'test msg')
532
533 def testNonnumericPort(self):
534 # check that non-numeric port raises socket.error
Richard Jones64b02de2010-08-03 06:39:33 +0000535 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000536 "localhost", "bogus")
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")
539
540
Guido van Rossum04110fb2007-08-24 16:32:05 +0000541# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000542@unittest.skipUnless(threading, 'Threading required for this test.')
543class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000544
545 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000546 smtplib.socket = mock_socket
547 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000548 self.old_stdout = sys.stdout
549 self.output = io.StringIO()
550 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000551 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000552
553 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000554 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000555 sys.stdout = self.old_stdout
556
557 def testFailingHELO(self):
558 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000559 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000560
Guido van Rossum04110fb2007-08-24 16:32:05 +0000561
562sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400563 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000564 'Mrs.C@somewhereesle.com':'Ruth C',
565 }
566
R. David Murraycaa27b72009-05-23 18:49:56 +0000567sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000568sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
569 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
570sim_auth_credentials = {
571 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
572 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
573 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
574 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
575 }
576sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000577
Guido van Rossum04110fb2007-08-24 16:32:05 +0000578sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400579 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000580 }
581
582# Simulated SMTP channel & server
583class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000584
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400585 # For testing failures in QUIT when using the context manager API.
586 quit_response = None
587
R. David Murray23ddc0e2009-05-29 18:03:16 +0000588 def __init__(self, extra_features, *args, **kw):
589 self._extrafeatures = ''.join(
590 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000591 super(SimSMTPChannel, self).__init__(*args, **kw)
592
Guido van Rossum04110fb2007-08-24 16:32:05 +0000593 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000594 resp = ('250-testhost\r\n'
595 '250-EXPN\r\n'
596 '250-SIZE 20000000\r\n'
597 '250-STARTTLS\r\n'
598 '250-DELIVERBY\r\n')
599 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000600 self.push(resp)
601
602 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400603 # For max compatibility smtplib should be sending the raw address.
604 if arg in sim_users:
605 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000606 else:
607 self.push('550 No such user: %s' % arg)
608
609 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400610 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000611 if list_name in sim_lists:
612 user_list = sim_lists[list_name]
613 for n, user_email in enumerate(user_list):
614 quoted_addr = smtplib.quoteaddr(user_email)
615 if n < len(user_list) - 1:
616 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
617 else:
618 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
619 else:
620 self.push('550 No access for you!')
621
R. David Murraycaa27b72009-05-23 18:49:56 +0000622 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000623 if arg.strip().lower()=='cram-md5':
624 self.push('334 {}'.format(sim_cram_md5_challenge))
625 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000626 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000627 mech = mech.lower()
628 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000629 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000630 return
631 if mech == 'plain' and auth==sim_auth_credentials['plain']:
632 self.push('235 plain auth ok')
633 elif mech=='login' and auth==sim_auth_credentials['login']:
634 self.push('334 Password:')
635 else:
636 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000637
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400638 def smtp_QUIT(self, arg):
639 # args is ignored
640 if self.quit_response is None:
641 super(SimSMTPChannel, self).smtp_QUIT(arg)
642 else:
643 self.push(self.quit_response)
644 self.close_when_done()
645
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000646 def handle_error(self):
647 raise
648
Guido van Rossum04110fb2007-08-24 16:32:05 +0000649
650class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000651
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400652 # For testing failures in QUIT when using the context manager API.
653 quit_response = None
654
R. David Murray23ddc0e2009-05-29 18:03:16 +0000655 def __init__(self, *args, **kw):
656 self._extra_features = []
657 smtpd.SMTPServer.__init__(self, *args, **kw)
658
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000659 def handle_accepted(self, conn, addr):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400660 self._SMTPchannel = SimSMTPChannel(
661 self._extra_features, self, conn, addr)
662 self._SMTPchannel.quit_response = self.quit_response
Guido van Rossum04110fb2007-08-24 16:32:05 +0000663
664 def process_message(self, peer, mailfrom, rcpttos, data):
665 pass
666
R. David Murrayfb123912009-05-28 18:19:00 +0000667 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000668 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000669
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000670 def handle_error(self):
671 raise
672
Guido van Rossum04110fb2007-08-24 16:32:05 +0000673
674# Test various SMTP & ESMTP commands/behaviors that require a simulated server
675# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000676@unittest.skipUnless(threading, 'Threading required for this test.')
677class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000678
679 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000680 self.real_getfqdn = socket.getfqdn
681 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000682 self.serv_evt = threading.Event()
683 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000684 # Pick a random unused port by passing 0 for the port number
685 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
686 # Keep a note of what port was assigned
687 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000688 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000689 self.thread = threading.Thread(target=debugging_server, args=serv_args)
690 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000691
692 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000693 self.serv_evt.wait()
694 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000695
696 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000697 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000698 # indicate that the client is finished
699 self.client_evt.set()
700 # wait for the server thread to terminate
701 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000702 self.thread.join()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000703
704 def testBasic(self):
705 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000706 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000707 smtp.quit()
708
709 def testEHLO(self):
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
712 # no features should be present before the EHLO
713 self.assertEqual(smtp.esmtp_features, {})
714
715 # features expected from the test server
716 expected_features = {'expn':'',
717 'size': '20000000',
718 'starttls': '',
719 'deliverby': '',
720 'help': '',
721 }
722
723 smtp.ehlo()
724 self.assertEqual(smtp.esmtp_features, expected_features)
725 for k in expected_features:
726 self.assertTrue(smtp.has_extn(k))
727 self.assertFalse(smtp.has_extn('unsupported-feature'))
728 smtp.quit()
729
730 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000731 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000732
733 for email, name in sim_users.items():
734 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000735 (name, smtplib.quoteaddr(email)),
736 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000737 self.assertEqual(smtp.vrfy(email), expected_known)
738
739 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400740 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000741 self.assertEqual(smtp.vrfy(u), expected_unknown)
742 smtp.quit()
743
744 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000745 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000746
747 for listname, members in sim_lists.items():
748 users = []
749 for m in members:
750 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000751 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000752 self.assertEqual(smtp.expn(listname), expected_known)
753
754 u = 'PSU-Members-List'
755 expected_unknown = (550, b'No access for you!')
756 self.assertEqual(smtp.expn(u), expected_unknown)
757 smtp.quit()
758
R. David Murrayfb123912009-05-28 18:19:00 +0000759 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000760 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000761 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000762
R. David Murrayfb123912009-05-28 18:19:00 +0000763 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000764 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Benjamin Petersond094efd2010-10-31 17:15:42 +0000765 smtp.close()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000766
R. David Murrayfb123912009-05-28 18:19:00 +0000767 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
768 # require a synchronous read to obtain the credentials...so instead smtpd
769 # sees the credential sent by smtplib's login method as an unknown command,
770 # which results in smtplib raising an auth error. Fortunately the error
771 # message contains the encoded credential, so we can partially check that it
772 # was generated correctly (partially, because the 'word' is uppercased in
773 # the error message).
774
775 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000776 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000777 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000778 try: smtp.login(sim_auth[0], sim_auth[1])
779 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000780 self.assertIn(sim_auth_login_password, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000781 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000782
783 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000784 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000785 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000786
787 try: smtp.login(sim_auth[0], sim_auth[1])
788 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000789 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000790 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000791
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400792 def test_with_statement(self):
793 with smtplib.SMTP(HOST, self.port) as smtp:
794 code, message = smtp.noop()
795 self.assertEqual(code, 250)
796 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
797 with smtplib.SMTP(HOST, self.port) as smtp:
798 smtp.close()
799 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
800
801 def test_with_statement_QUIT_failure(self):
802 self.serv.quit_response = '421 QUIT FAILED'
803 with self.assertRaises(smtplib.SMTPResponseException) as error:
804 with smtplib.SMTP(HOST, self.port) as smtp:
805 smtp.noop()
806 self.assertEqual(error.exception.smtp_code, 421)
807 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
808 # We don't need to clean up self.serv.quit_response because a new
809 # server is always instantiated in the setUp().
810
R. David Murrayfb123912009-05-28 18:19:00 +0000811 #TODO: add tests for correct AUTH method fallback now that the
812 #test infrastructure can support it.
813
Guido van Rossum04110fb2007-08-24 16:32:05 +0000814
Antoine Pitroud54fa552011-08-28 01:23:52 +0200815@support.reap_threads
Guido van Rossumd8faa362007-04-27 19:54:29 +0000816def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000817 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000818 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000819 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000820
821if __name__ == '__main__':
822 test_main()