blob: 6b00b809c6a472a547dbc1f93ee30198af76f0ce [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
Guido van Rossum04110fb2007-08-24 16:32:05 +00002import email.utils
Guido van Rossumd8faa362007-04-27 19:54:29 +00003import socket
4import threading
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
8import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +00009import time
Guido van Rossum806c2462007-08-06 23:33:07 +000010import select
Guido van Rossumd8faa362007-04-27 19:54:29 +000011
12from unittest import TestCase
13from test import test_support
14
Guido van Rossum806c2462007-08-06 23:33:07 +000015# PORT is used to communicate the port number assigned to the server
16# to the test client
17HOST = "localhost"
18PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +000019
Guido van Rossum806c2462007-08-06 23:33:07 +000020def server(evt, buf):
Guido van Rossumd8faa362007-04-27 19:54:29 +000021 try:
Guido van Rossum806c2462007-08-06 23:33:07 +000022 serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
23 serv.settimeout(3)
24 serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
25 serv.bind(("", 0))
26 global PORT
27 PORT = serv.getsockname()[1]
28 serv.listen(5)
Guido van Rossumd8faa362007-04-27 19:54:29 +000029 conn, addr = serv.accept()
30 except socket.timeout:
31 pass
32 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000033 n = 500
34 while buf and n > 0:
35 r, w, e = select.select([], [conn], [])
36 if w:
37 sent = conn.send(buf)
38 buf = buf[sent:]
39
40 n -= 1
41 time.sleep(0.01)
42
Guido van Rossumd8faa362007-04-27 19:54:29 +000043 conn.close()
44 finally:
45 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000046 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +000047 evt.set()
48
49class GeneralTests(TestCase):
50
51 def setUp(self):
52 self.evt = threading.Event()
Guido van Rossum8a392d72007-11-21 22:09:45 +000053 servargs = (self.evt, b"220 Hola mundo\n")
Guido van Rossum806c2462007-08-06 23:33:07 +000054 threading.Thread(target=server, args=servargs).start()
55
56 # wait until server thread has assigned a port number
57 n = 500
58 while PORT is None and n > 0:
59 time.sleep(0.01)
60 n -= 1
61
62 # wait a little longer (sometimes connections are refused
63 # on slow machines without this additional wait)
64 time.sleep(0.5)
Guido van Rossumd8faa362007-04-27 19:54:29 +000065
66 def tearDown(self):
67 self.evt.wait()
68
Guido van Rossum806c2462007-08-06 23:33:07 +000069 def testBasic1(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +000070 # connects
Guido van Rossum806c2462007-08-06 23:33:07 +000071 smtp = smtplib.SMTP(HOST, PORT)
Guido van Rossumd8faa362007-04-27 19:54:29 +000072 smtp.sock.close()
73
Guido van Rossum806c2462007-08-06 23:33:07 +000074 def testBasic2(self):
75 # connects, include port in host name
76 smtp = smtplib.SMTP("%s:%s" % (HOST, PORT))
77 smtp.sock.close()
78
Guido van Rossum04110fb2007-08-24 16:32:05 +000079 def testNotConnected(self):
80 # Test various operations on an unconnected SMTP object that
81 # should raise exceptions (at present the attempt in SMTP.send
82 # to reference the nonexistent 'sock' attribute of the SMTP object
83 # causes an AttributeError)
84 smtp = smtplib.SMTP()
Christian Heimes90c3d9b2008-02-23 13:18:03 +000085 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
86 self.assertRaises(smtplib.SMTPServerDisconnected,
87 smtp.send, 'test msg')
Guido van Rossum04110fb2007-08-24 16:32:05 +000088
Guido van Rossum806c2462007-08-06 23:33:07 +000089 def testLocalHostName(self):
90 # check that supplied local_hostname is used
91 smtp = smtplib.SMTP(HOST, PORT, local_hostname="testhost")
92 self.assertEqual(smtp.local_hostname, "testhost")
93 smtp.sock.close()
94
95 def testNonnumericPort(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +000096 # check that non-numeric port raises socket.error
Guido van Rossum806c2462007-08-06 23:33:07 +000097 self.assertRaises(socket.error, smtplib.SMTP,
98 "localhost", "bogus")
Guido van Rossum04110fb2007-08-24 16:32:05 +000099 self.assertRaises(socket.error, smtplib.SMTP,
100 "localhost:bogus")
Guido van Rossum806c2462007-08-06 23:33:07 +0000101
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 def testTimeoutDefault(self):
103 # default
Guido van Rossum806c2462007-08-06 23:33:07 +0000104 smtp = smtplib.SMTP(HOST, PORT)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105 self.assertTrue(smtp.sock.gettimeout() is None)
106 smtp.sock.close()
107
108 def testTimeoutValue(self):
109 # a value
Guido van Rossum806c2462007-08-06 23:33:07 +0000110 smtp = smtplib.SMTP(HOST, PORT, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 self.assertEqual(smtp.sock.gettimeout(), 30)
112 smtp.sock.close()
113
114 def testTimeoutNone(self):
115 # None, having other default
116 previous = socket.getdefaulttimeout()
117 socket.setdefaulttimeout(30)
118 try:
Guido van Rossum806c2462007-08-06 23:33:07 +0000119 smtp = smtplib.SMTP(HOST, PORT, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120 finally:
121 socket.setdefaulttimeout(previous)
122 self.assertEqual(smtp.sock.gettimeout(), 30)
123 smtp.sock.close()
124
125
Guido van Rossum04110fb2007-08-24 16:32:05 +0000126# Test server thread using the specified SMTP server class
127def debugging_server(server_class, serv_evt, client_evt):
128 serv = server_class(("", 0), ('nowhere', -1))
Guido van Rossum806c2462007-08-06 23:33:07 +0000129 global PORT
130 PORT = serv.getsockname()[1]
131
132 try:
133 if hasattr(select, 'poll'):
134 poll_fun = asyncore.poll2
135 else:
136 poll_fun = asyncore.poll
137
138 n = 1000
139 while asyncore.socket_map and n > 0:
140 poll_fun(0.01, asyncore.socket_map)
141
142 # when the client conversation is finished, it will
143 # set client_evt, and it's then ok to kill the server
144 if client_evt.isSet():
145 serv.close()
146 break
147
148 n -= 1
149
150 except socket.timeout:
151 pass
152 finally:
153 # allow some time for the client to read the result
154 time.sleep(0.5)
155 serv.close()
156 asyncore.close_all()
157 PORT = None
158 time.sleep(0.5)
159 serv_evt.set()
160
161MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
162MSG_END = '------------ END MESSAGE ------------\n'
163
Guido van Rossum04110fb2007-08-24 16:32:05 +0000164# NOTE: Some SMTP objects in the tests below are created with a non-default
165# local_hostname argument to the constructor, since (on some systems) the FQDN
166# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000167# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000168
169# Test behavior of smtpd.DebuggingServer
Guido van Rossum806c2462007-08-06 23:33:07 +0000170class DebuggingServerTests(TestCase):
171
172 def setUp(self):
173 # temporarily replace sys.stdout to capture DebuggingServer output
174 self.old_stdout = sys.stdout
175 self.output = io.StringIO()
176 sys.stdout = self.output
177
178 self.serv_evt = threading.Event()
179 self.client_evt = threading.Event()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000180 serv_args = (smtpd.DebuggingServer, self.serv_evt, self.client_evt)
Guido van Rossum806c2462007-08-06 23:33:07 +0000181 threading.Thread(target=debugging_server, args=serv_args).start()
182
183 # wait until server thread has assigned a port number
184 n = 500
185 while PORT is None and n > 0:
186 time.sleep(0.01)
187 n -= 1
188
189 # wait a little longer (sometimes connections are refused
190 # on slow machines without this additional wait)
191 time.sleep(0.5)
192
193 def tearDown(self):
194 # indicate that the client is finished
195 self.client_evt.set()
196 # wait for the server thread to terminate
197 self.serv_evt.wait()
198 # restore sys.stdout
199 sys.stdout = self.old_stdout
200
201 def testBasic(self):
202 # connect
203 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
204 smtp.quit()
205
Guido van Rossum04110fb2007-08-24 16:32:05 +0000206 def testNOOP(self):
207 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
208 expected = (250, b'Ok')
209 self.assertEqual(smtp.noop(), expected)
210 smtp.quit()
211
212 def testRSET(self):
213 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
214 expected = (250, b'Ok')
215 self.assertEqual(smtp.rset(), expected)
216 smtp.quit()
217
218 def testNotImplemented(self):
219 # EHLO isn't implemented in DebuggingServer
Guido van Rossum806c2462007-08-06 23:33:07 +0000220 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
221 expected = (502, b'Error: command "EHLO" not implemented')
222 self.assertEqual(smtp.ehlo(), expected)
223 smtp.quit()
224
Guido van Rossum04110fb2007-08-24 16:32:05 +0000225 def testVRFY(self):
226 # VRFY isn't implemented in DebuggingServer
227 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
228 expected = (502, b'Error: command "VRFY" not implemented')
229 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
230 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
231 smtp.quit()
232
233 def testSecondHELO(self):
234 # check that a second HELO returns a message that it's a duplicate
235 # (this behavior is specific to smtpd.SMTPChannel)
236 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
237 smtp.helo()
238 expected = (503, b'Duplicate HELO/EHLO')
239 self.assertEqual(smtp.helo(), expected)
240 smtp.quit()
241
Guido van Rossum806c2462007-08-06 23:33:07 +0000242 def testHELP(self):
243 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
244 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
245 smtp.quit()
246
247 def testSend(self):
248 # connect and send mail
249 m = 'A test message'
250 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
251 smtp.sendmail('John', 'Sally', m)
252 smtp.quit()
253
254 self.client_evt.set()
255 self.serv_evt.wait()
256 self.output.flush()
257 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
258 self.assertEqual(self.output.getvalue(), mexpect)
259
260
Guido van Rossum04110fb2007-08-24 16:32:05 +0000261# test response of client to a non-successful HELO message
Guido van Rossum806c2462007-08-06 23:33:07 +0000262class BadHELOServerTests(TestCase):
263
264 def setUp(self):
265 self.old_stdout = sys.stdout
266 self.output = io.StringIO()
267 sys.stdout = self.output
268
269 self.evt = threading.Event()
270 servargs = (self.evt, b"199 no hello for you!\n")
271 threading.Thread(target=server, args=servargs).start()
272
273 # wait until server thread has assigned a port number
274 n = 500
275 while PORT is None and n > 0:
276 time.sleep(0.01)
277 n -= 1
278
279 # wait a little longer (sometimes connections are refused
280 # on slow machines without this additional wait)
281 time.sleep(0.5)
282
283 def tearDown(self):
284 self.evt.wait()
285 sys.stdout = self.old_stdout
286
287 def testFailingHELO(self):
288 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
289 HOST, PORT, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000290
Guido van Rossum04110fb2007-08-24 16:32:05 +0000291
292sim_users = {'Mr.A@somewhere.com':'John A',
293 'Ms.B@somewhere.com':'Sally B',
294 'Mrs.C@somewhereesle.com':'Ruth C',
295 }
296
297sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
298 'list-2':['Ms.B@somewhere.com',],
299 }
300
301# Simulated SMTP channel & server
302class SimSMTPChannel(smtpd.SMTPChannel):
303 def smtp_EHLO(self, arg):
304 resp = '250-testhost\r\n' \
305 '250-EXPN\r\n' \
306 '250-SIZE 20000000\r\n' \
307 '250-STARTTLS\r\n' \
308 '250-DELIVERBY\r\n' \
309 '250 HELP'
310 self.push(resp)
311
312 def smtp_VRFY(self, arg):
313# print '\nsmtp_VRFY(%r)\n' % arg
314
315 raw_addr = email.utils.parseaddr(arg)[1]
316 quoted_addr = smtplib.quoteaddr(arg)
317 if raw_addr in sim_users:
318 self.push('250 %s %s' % (sim_users[raw_addr], quoted_addr))
319 else:
320 self.push('550 No such user: %s' % arg)
321
322 def smtp_EXPN(self, arg):
323# print '\nsmtp_EXPN(%r)\n' % arg
324
325 list_name = email.utils.parseaddr(arg)[1].lower()
326 if list_name in sim_lists:
327 user_list = sim_lists[list_name]
328 for n, user_email in enumerate(user_list):
329 quoted_addr = smtplib.quoteaddr(user_email)
330 if n < len(user_list) - 1:
331 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
332 else:
333 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
334 else:
335 self.push('550 No access for you!')
336
337
338class SimSMTPServer(smtpd.SMTPServer):
339 def handle_accept(self):
340 conn, addr = self.accept()
341 channel = SimSMTPChannel(self, conn, addr)
342
343 def process_message(self, peer, mailfrom, rcpttos, data):
344 pass
345
346
347# Test various SMTP & ESMTP commands/behaviors that require a simulated server
348# (i.e., something with more features than DebuggingServer)
349class SMTPSimTests(TestCase):
350
351 def setUp(self):
352 self.serv_evt = threading.Event()
353 self.client_evt = threading.Event()
354 serv_args = (SimSMTPServer, self.serv_evt, self.client_evt)
355 threading.Thread(target=debugging_server, args=serv_args).start()
356
357 # wait until server thread has assigned a port number
358 n = 500
359 while PORT is None and n > 0:
360 time.sleep(0.01)
361 n -= 1
362
363 # wait a little longer (sometimes connections are refused
364 # on slow machines without this additional wait)
365 time.sleep(0.5)
366
367 def tearDown(self):
368 # indicate that the client is finished
369 self.client_evt.set()
370 # wait for the server thread to terminate
371 self.serv_evt.wait()
372
373 def testBasic(self):
374 # smoke test
375 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
376 smtp.quit()
377
378 def testEHLO(self):
379 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
380
381 # no features should be present before the EHLO
382 self.assertEqual(smtp.esmtp_features, {})
383
384 # features expected from the test server
385 expected_features = {'expn':'',
386 'size': '20000000',
387 'starttls': '',
388 'deliverby': '',
389 'help': '',
390 }
391
392 smtp.ehlo()
393 self.assertEqual(smtp.esmtp_features, expected_features)
394 for k in expected_features:
395 self.assertTrue(smtp.has_extn(k))
396 self.assertFalse(smtp.has_extn('unsupported-feature'))
397 smtp.quit()
398
399 def testVRFY(self):
400 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
401
402 for email, name in sim_users.items():
403 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000404 (name, smtplib.quoteaddr(email)),
405 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000406 self.assertEqual(smtp.vrfy(email), expected_known)
407
408 u = 'nobody@nowhere.com'
Thomas Wouters74e68c72007-08-31 00:20:14 +0000409 expected_unknown = (550, ('No such user: %s'
410 % smtplib.quoteaddr(u)).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000411 self.assertEqual(smtp.vrfy(u), expected_unknown)
412 smtp.quit()
413
414 def testEXPN(self):
415 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
416
417 for listname, members in sim_lists.items():
418 users = []
419 for m in members:
420 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000421 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000422 self.assertEqual(smtp.expn(listname), expected_known)
423
424 u = 'PSU-Members-List'
425 expected_unknown = (550, b'No access for you!')
426 self.assertEqual(smtp.expn(u), expected_unknown)
427 smtp.quit()
428
429
430
Guido van Rossumd8faa362007-04-27 19:54:29 +0000431def test_main(verbose=None):
Guido van Rossum806c2462007-08-06 23:33:07 +0000432 test_support.run_unittest(GeneralTests, DebuggingServerTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000433 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000434
435if __name__ == '__main__':
436 test_main()