blob: 70654c50cd85608f03ff2c40ed67b8f7051309ad [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
219 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3,
220 source_address=('127.0.0.1', 19876))
221 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
222 self.assertEqual(smtp.local_hostname, 'localhost')
223 print(dir(smtp))
224 smtp.quit()
225
Guido van Rossum04110fb2007-08-24 16:32:05 +0000226 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000227 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000228 expected = (250, b'Ok')
229 self.assertEqual(smtp.noop(), expected)
230 smtp.quit()
231
232 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000233 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000234 expected = (250, b'Ok')
235 self.assertEqual(smtp.rset(), expected)
236 smtp.quit()
237
238 def testNotImplemented(self):
239 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000240 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000241 expected = (502, b'Error: command "EHLO" not implemented')
242 self.assertEqual(smtp.ehlo(), expected)
243 smtp.quit()
244
Guido van Rossum04110fb2007-08-24 16:32:05 +0000245 def testVRFY(self):
246 # VRFY isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000247 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000248 expected = (502, b'Error: command "VRFY" not implemented')
249 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
250 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
251 smtp.quit()
252
253 def testSecondHELO(self):
254 # check that a second HELO returns a message that it's a duplicate
255 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000256 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000257 smtp.helo()
258 expected = (503, b'Duplicate HELO/EHLO')
259 self.assertEqual(smtp.helo(), expected)
260 smtp.quit()
261
Guido van Rossum806c2462007-08-06 23:33:07 +0000262 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000263 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000264 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
265 smtp.quit()
266
267 def testSend(self):
268 # connect and send mail
269 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000270 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000271 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000272 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
273 # in asyncore. This sleep might help, but should really be fixed
274 # properly by using an Event variable.
275 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000276 smtp.quit()
277
278 self.client_evt.set()
279 self.serv_evt.wait()
280 self.output.flush()
281 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
282 self.assertEqual(self.output.getvalue(), mexpect)
283
R. David Murray7dff9e02010-11-08 17:15:13 +0000284 def testSendBinary(self):
285 m = b'A test message'
286 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
287 smtp.sendmail('John', 'Sally', m)
288 # XXX (see comment in testSend)
289 time.sleep(0.01)
290 smtp.quit()
291
292 self.client_evt.set()
293 self.serv_evt.wait()
294 self.output.flush()
295 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
296 self.assertEqual(self.output.getvalue(), mexpect)
297
R David Murray0f663d02011-06-09 15:05:57 -0400298 def testSendNeedingDotQuote(self):
299 # Issue 12283
300 m = '.A test\n.mes.sage.'
301 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
302 smtp.sendmail('John', 'Sally', m)
303 # XXX (see comment in testSend)
304 time.sleep(0.01)
305 smtp.quit()
306
307 self.client_evt.set()
308 self.serv_evt.wait()
309 self.output.flush()
310 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
311 self.assertEqual(self.output.getvalue(), mexpect)
312
R David Murray46346762011-07-18 21:38:54 -0400313 def testSendNullSender(self):
314 m = 'A test message'
315 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
316 smtp.sendmail('<>', 'Sally', m)
317 # XXX (see comment in testSend)
318 time.sleep(0.01)
319 smtp.quit()
320
321 self.client_evt.set()
322 self.serv_evt.wait()
323 self.output.flush()
324 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
325 self.assertEqual(self.output.getvalue(), mexpect)
326 debugout = smtpd.DEBUGSTREAM.getvalue()
327 sender = re.compile("^sender: <>$", re.MULTILINE)
328 self.assertRegex(debugout, sender)
329
R. David Murray7dff9e02010-11-08 17:15:13 +0000330 def testSendMessage(self):
331 m = email.mime.text.MIMEText('A test message')
332 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
333 smtp.send_message(m, from_addr='John', to_addrs='Sally')
334 # XXX (see comment in testSend)
335 time.sleep(0.01)
336 smtp.quit()
337
338 self.client_evt.set()
339 self.serv_evt.wait()
340 self.output.flush()
341 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400342 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000343 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
344 self.assertEqual(self.output.getvalue(), mexpect)
345
346 def testSendMessageWithAddresses(self):
347 m = email.mime.text.MIMEText('A test message')
348 m['From'] = 'foo@bar.com'
349 m['To'] = 'John'
350 m['CC'] = 'Sally, Fred'
351 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
352 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
353 smtp.send_message(m)
354 # XXX (see comment in testSend)
355 time.sleep(0.01)
356 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400357 # make sure the Bcc header is still in the message.
358 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
359 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000360
361 self.client_evt.set()
362 self.serv_evt.wait()
363 self.output.flush()
364 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400365 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400366 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000367 del m['Bcc']
368 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
369 self.assertEqual(self.output.getvalue(), mexpect)
370 debugout = smtpd.DEBUGSTREAM.getvalue()
371 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000372 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000373 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
374 'warped@silly.walks.com'):
375 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
376 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000377 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000378
379 def testSendMessageWithSomeAddresses(self):
380 # Make sure nothing breaks if not all of the three 'to' headers exist
381 m = email.mime.text.MIMEText('A test message')
382 m['From'] = 'foo@bar.com'
383 m['To'] = 'John, Dinsdale'
384 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
385 smtp.send_message(m)
386 # XXX (see comment in testSend)
387 time.sleep(0.01)
388 smtp.quit()
389
390 self.client_evt.set()
391 self.serv_evt.wait()
392 self.output.flush()
393 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400394 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000395 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
396 self.assertEqual(self.output.getvalue(), mexpect)
397 debugout = smtpd.DEBUGSTREAM.getvalue()
398 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000399 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000400 for addr in ('John', 'Dinsdale'):
401 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
402 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000403 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000404
R David Murrayac4e5ab2011-07-02 21:03:19 -0400405 def testSendMessageWithSpecifiedAddresses(self):
406 # Make sure addresses specified in call override those in message.
407 m = email.mime.text.MIMEText('A test message')
408 m['From'] = 'foo@bar.com'
409 m['To'] = 'John, Dinsdale'
410 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
411 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
412 # XXX (see comment in testSend)
413 time.sleep(0.01)
414 smtp.quit()
415
416 self.client_evt.set()
417 self.serv_evt.wait()
418 self.output.flush()
419 # Add the X-Peer header that DebuggingServer adds
420 m['X-Peer'] = socket.gethostbyname('localhost')
421 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
422 self.assertEqual(self.output.getvalue(), mexpect)
423 debugout = smtpd.DEBUGSTREAM.getvalue()
424 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
425 self.assertRegex(debugout, sender)
426 for addr in ('John', 'Dinsdale'):
427 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
428 re.MULTILINE)
429 self.assertNotRegex(debugout, to_addr)
430 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
431 self.assertRegex(debugout, recip)
432
433 def testSendMessageWithMultipleFrom(self):
434 # Sender overrides To
435 m = email.mime.text.MIMEText('A test message')
436 m['From'] = 'Bernard, Bianca'
437 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
438 m['To'] = 'John, Dinsdale'
439 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
440 smtp.send_message(m)
441 # XXX (see comment in testSend)
442 time.sleep(0.01)
443 smtp.quit()
444
445 self.client_evt.set()
446 self.serv_evt.wait()
447 self.output.flush()
448 # Add the X-Peer header that DebuggingServer adds
449 m['X-Peer'] = socket.gethostbyname('localhost')
450 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
451 self.assertEqual(self.output.getvalue(), mexpect)
452 debugout = smtpd.DEBUGSTREAM.getvalue()
453 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
454 self.assertRegex(debugout, sender)
455 for addr in ('John', 'Dinsdale'):
456 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
457 re.MULTILINE)
458 self.assertRegex(debugout, to_addr)
459
460 def testSendMessageResent(self):
461 m = email.mime.text.MIMEText('A test message')
462 m['From'] = 'foo@bar.com'
463 m['To'] = 'John'
464 m['CC'] = 'Sally, Fred'
465 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
466 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
467 m['Resent-From'] = 'holy@grail.net'
468 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
469 m['Resent-Bcc'] = 'doe@losthope.net'
470 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
471 smtp.send_message(m)
472 # XXX (see comment in testSend)
473 time.sleep(0.01)
474 smtp.quit()
475
476 self.client_evt.set()
477 self.serv_evt.wait()
478 self.output.flush()
479 # The Resent-Bcc headers are deleted before serialization.
480 del m['Bcc']
481 del m['Resent-Bcc']
482 # Add the X-Peer header that DebuggingServer adds
483 m['X-Peer'] = socket.gethostbyname('localhost')
484 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
485 self.assertEqual(self.output.getvalue(), mexpect)
486 debugout = smtpd.DEBUGSTREAM.getvalue()
487 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
488 self.assertRegex(debugout, sender)
489 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
490 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
491 re.MULTILINE)
492 self.assertRegex(debugout, to_addr)
493
494 def testSendMessageMultipleResentRaises(self):
495 m = email.mime.text.MIMEText('A test message')
496 m['From'] = 'foo@bar.com'
497 m['To'] = 'John'
498 m['CC'] = 'Sally, Fred'
499 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
500 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
501 m['Resent-From'] = 'holy@grail.net'
502 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
503 m['Resent-Bcc'] = 'doe@losthope.net'
504 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
505 m['Resent-To'] = 'holy@grail.net'
506 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
507 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
508 with self.assertRaises(ValueError):
509 smtp.send_message(m)
510 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000511
Victor Stinner45df8202010-04-28 22:31:17 +0000512class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000513
Richard Jones64b02de2010-08-03 06:39:33 +0000514 def setUp(self):
515 smtplib.socket = mock_socket
516
517 def tearDown(self):
518 smtplib.socket = socket
519
Christian Heimes380f7f22008-02-28 11:19:05 +0000520 def testNotConnected(self):
521 # Test various operations on an unconnected SMTP object that
522 # should raise exceptions (at present the attempt in SMTP.send
523 # to reference the nonexistent 'sock' attribute of the SMTP object
524 # causes an AttributeError)
525 smtp = smtplib.SMTP()
526 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
527 self.assertRaises(smtplib.SMTPServerDisconnected,
528 smtp.send, 'test msg')
529
530 def testNonnumericPort(self):
531 # check that non-numeric port raises socket.error
Richard Jones64b02de2010-08-03 06:39:33 +0000532 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000533 "localhost", "bogus")
Richard Jones64b02de2010-08-03 06:39:33 +0000534 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000535 "localhost:bogus")
536
537
Guido van Rossum04110fb2007-08-24 16:32:05 +0000538# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000539@unittest.skipUnless(threading, 'Threading required for this test.')
540class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000541
542 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000543 smtplib.socket = mock_socket
544 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000545 self.old_stdout = sys.stdout
546 self.output = io.StringIO()
547 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000548 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000549
550 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000551 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000552 sys.stdout = self.old_stdout
553
554 def testFailingHELO(self):
555 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000556 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000557
Guido van Rossum04110fb2007-08-24 16:32:05 +0000558
559sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400560 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000561 'Mrs.C@somewhereesle.com':'Ruth C',
562 }
563
R. David Murraycaa27b72009-05-23 18:49:56 +0000564sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000565sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
566 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
567sim_auth_credentials = {
568 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
569 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
570 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
571 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
572 }
573sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000574
Guido van Rossum04110fb2007-08-24 16:32:05 +0000575sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400576 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000577 }
578
579# Simulated SMTP channel & server
580class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000581
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400582 # For testing failures in QUIT when using the context manager API.
583 quit_response = None
584
R. David Murray23ddc0e2009-05-29 18:03:16 +0000585 def __init__(self, extra_features, *args, **kw):
586 self._extrafeatures = ''.join(
587 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000588 super(SimSMTPChannel, self).__init__(*args, **kw)
589
Guido van Rossum04110fb2007-08-24 16:32:05 +0000590 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000591 resp = ('250-testhost\r\n'
592 '250-EXPN\r\n'
593 '250-SIZE 20000000\r\n'
594 '250-STARTTLS\r\n'
595 '250-DELIVERBY\r\n')
596 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000597 self.push(resp)
598
599 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400600 # For max compatibility smtplib should be sending the raw address.
601 if arg in sim_users:
602 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000603 else:
604 self.push('550 No such user: %s' % arg)
605
606 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400607 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000608 if list_name in sim_lists:
609 user_list = sim_lists[list_name]
610 for n, user_email in enumerate(user_list):
611 quoted_addr = smtplib.quoteaddr(user_email)
612 if n < len(user_list) - 1:
613 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
614 else:
615 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
616 else:
617 self.push('550 No access for you!')
618
R. David Murraycaa27b72009-05-23 18:49:56 +0000619 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000620 if arg.strip().lower()=='cram-md5':
621 self.push('334 {}'.format(sim_cram_md5_challenge))
622 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000623 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000624 mech = mech.lower()
625 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000626 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000627 return
628 if mech == 'plain' and auth==sim_auth_credentials['plain']:
629 self.push('235 plain auth ok')
630 elif mech=='login' and auth==sim_auth_credentials['login']:
631 self.push('334 Password:')
632 else:
633 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000634
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400635 def smtp_QUIT(self, arg):
636 # args is ignored
637 if self.quit_response is None:
638 super(SimSMTPChannel, self).smtp_QUIT(arg)
639 else:
640 self.push(self.quit_response)
641 self.close_when_done()
642
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000643 def handle_error(self):
644 raise
645
Guido van Rossum04110fb2007-08-24 16:32:05 +0000646
647class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000648
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400649 # For testing failures in QUIT when using the context manager API.
650 quit_response = None
651
R. David Murray23ddc0e2009-05-29 18:03:16 +0000652 def __init__(self, *args, **kw):
653 self._extra_features = []
654 smtpd.SMTPServer.__init__(self, *args, **kw)
655
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000656 def handle_accepted(self, conn, addr):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400657 self._SMTPchannel = SimSMTPChannel(
658 self._extra_features, self, conn, addr)
659 self._SMTPchannel.quit_response = self.quit_response
Guido van Rossum04110fb2007-08-24 16:32:05 +0000660
661 def process_message(self, peer, mailfrom, rcpttos, data):
662 pass
663
R. David Murrayfb123912009-05-28 18:19:00 +0000664 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000665 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000666
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000667 def handle_error(self):
668 raise
669
Guido van Rossum04110fb2007-08-24 16:32:05 +0000670
671# Test various SMTP & ESMTP commands/behaviors that require a simulated server
672# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000673@unittest.skipUnless(threading, 'Threading required for this test.')
674class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000675
676 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000677 self.real_getfqdn = socket.getfqdn
678 socket.getfqdn = mock_socket.getfqdn
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000679 self._threads = support.threading_setup()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000680 self.serv_evt = threading.Event()
681 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000682 # Pick a random unused port by passing 0 for the port number
683 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
684 # Keep a note of what port was assigned
685 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000686 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000687 self.thread = threading.Thread(target=debugging_server, args=serv_args)
688 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000689
690 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000691 self.serv_evt.wait()
692 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000693
694 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000695 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000696 # indicate that the client is finished
697 self.client_evt.set()
698 # wait for the server thread to terminate
699 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000700 self.thread.join()
701 support.threading_cleanup(*self._threads)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000702
703 def testBasic(self):
704 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000705 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000706 smtp.quit()
707
708 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000709 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000710
711 # no features should be present before the EHLO
712 self.assertEqual(smtp.esmtp_features, {})
713
714 # features expected from the test server
715 expected_features = {'expn':'',
716 'size': '20000000',
717 'starttls': '',
718 'deliverby': '',
719 'help': '',
720 }
721
722 smtp.ehlo()
723 self.assertEqual(smtp.esmtp_features, expected_features)
724 for k in expected_features:
725 self.assertTrue(smtp.has_extn(k))
726 self.assertFalse(smtp.has_extn('unsupported-feature'))
727 smtp.quit()
728
729 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000730 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000731
732 for email, name in sim_users.items():
733 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000734 (name, smtplib.quoteaddr(email)),
735 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000736 self.assertEqual(smtp.vrfy(email), expected_known)
737
738 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400739 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000740 self.assertEqual(smtp.vrfy(u), expected_unknown)
741 smtp.quit()
742
743 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000744 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000745
746 for listname, members in sim_lists.items():
747 users = []
748 for m in members:
749 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000750 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000751 self.assertEqual(smtp.expn(listname), expected_known)
752
753 u = 'PSU-Members-List'
754 expected_unknown = (550, b'No access for you!')
755 self.assertEqual(smtp.expn(u), expected_unknown)
756 smtp.quit()
757
R. David Murrayfb123912009-05-28 18:19:00 +0000758 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000759 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000760 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000761
R. David Murrayfb123912009-05-28 18:19:00 +0000762 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000763 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Benjamin Petersond094efd2010-10-31 17:15:42 +0000764 smtp.close()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000765
R. David Murrayfb123912009-05-28 18:19:00 +0000766 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
767 # require a synchronous read to obtain the credentials...so instead smtpd
768 # sees the credential sent by smtplib's login method as an unknown command,
769 # which results in smtplib raising an auth error. Fortunately the error
770 # message contains the encoded credential, so we can partially check that it
771 # was generated correctly (partially, because the 'word' is uppercased in
772 # the error message).
773
774 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000775 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000776 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000777 try: smtp.login(sim_auth[0], sim_auth[1])
778 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000779 self.assertIn(sim_auth_login_password, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000780 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000781
782 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000783 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000784 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000785
786 try: smtp.login(sim_auth[0], sim_auth[1])
787 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000788 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000789 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000790
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400791 def test_with_statement(self):
792 with smtplib.SMTP(HOST, self.port) as smtp:
793 code, message = smtp.noop()
794 self.assertEqual(code, 250)
795 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
796 with smtplib.SMTP(HOST, self.port) as smtp:
797 smtp.close()
798 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
799
800 def test_with_statement_QUIT_failure(self):
801 self.serv.quit_response = '421 QUIT FAILED'
802 with self.assertRaises(smtplib.SMTPResponseException) as error:
803 with smtplib.SMTP(HOST, self.port) as smtp:
804 smtp.noop()
805 self.assertEqual(error.exception.smtp_code, 421)
806 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
807 # We don't need to clean up self.serv.quit_response because a new
808 # server is always instantiated in the setUp().
809
R. David Murrayfb123912009-05-28 18:19:00 +0000810 #TODO: add tests for correct AUTH method fallback now that the
811 #test infrastructure can support it.
812
Guido van Rossum04110fb2007-08-24 16:32:05 +0000813
Guido van Rossumd8faa362007-04-27 19:54:29 +0000814def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000815 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000816 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000817 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000818
819if __name__ == '__main__':
820 test_main()