blob: e0dcc86cada9f5bd78cf22dcf5cd74c5b623f8b8 [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 Rossum806c2462007-08-06 23:33:07 +000053 servargs = (self.evt, "220 Hola mundo\n")
54 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()
85 self.assertRaises(AttributeError, smtp.ehlo)
86 self.assertRaises(AttributeError, smtp.send, 'test msg')
87
Guido van Rossum806c2462007-08-06 23:33:07 +000088 def testLocalHostName(self):
89 # check that supplied local_hostname is used
90 smtp = smtplib.SMTP(HOST, PORT, local_hostname="testhost")
91 self.assertEqual(smtp.local_hostname, "testhost")
92 smtp.sock.close()
93
94 def testNonnumericPort(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +000095 # check that non-numeric port raises socket.error
Guido van Rossum806c2462007-08-06 23:33:07 +000096 self.assertRaises(socket.error, smtplib.SMTP,
97 "localhost", "bogus")
Guido van Rossum04110fb2007-08-24 16:32:05 +000098 self.assertRaises(socket.error, smtplib.SMTP,
99 "localhost:bogus")
Guido van Rossum806c2462007-08-06 23:33:07 +0000100
Guido van Rossumd8faa362007-04-27 19:54:29 +0000101 def testTimeoutDefault(self):
102 # default
Guido van Rossum806c2462007-08-06 23:33:07 +0000103 smtp = smtplib.SMTP(HOST, PORT)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000104 self.assertTrue(smtp.sock.gettimeout() is None)
105 smtp.sock.close()
106
107 def testTimeoutValue(self):
108 # a value
Guido van Rossum806c2462007-08-06 23:33:07 +0000109 smtp = smtplib.SMTP(HOST, PORT, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000110 self.assertEqual(smtp.sock.gettimeout(), 30)
111 smtp.sock.close()
112
113 def testTimeoutNone(self):
114 # None, having other default
115 previous = socket.getdefaulttimeout()
116 socket.setdefaulttimeout(30)
117 try:
Guido van Rossum806c2462007-08-06 23:33:07 +0000118 smtp = smtplib.SMTP(HOST, PORT, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000119 finally:
120 socket.setdefaulttimeout(previous)
121 self.assertEqual(smtp.sock.gettimeout(), 30)
122 smtp.sock.close()
123
124
Guido van Rossum04110fb2007-08-24 16:32:05 +0000125# Test server thread using the specified SMTP server class
126def debugging_server(server_class, serv_evt, client_evt):
127 serv = server_class(("", 0), ('nowhere', -1))
Guido van Rossum806c2462007-08-06 23:33:07 +0000128 global PORT
129 PORT = serv.getsockname()[1]
130
131 try:
132 if hasattr(select, 'poll'):
133 poll_fun = asyncore.poll2
134 else:
135 poll_fun = asyncore.poll
136
137 n = 1000
138 while asyncore.socket_map and n > 0:
139 poll_fun(0.01, asyncore.socket_map)
140
141 # when the client conversation is finished, it will
142 # set client_evt, and it's then ok to kill the server
143 if client_evt.isSet():
144 serv.close()
145 break
146
147 n -= 1
148
149 except socket.timeout:
150 pass
151 finally:
152 # allow some time for the client to read the result
153 time.sleep(0.5)
154 serv.close()
155 asyncore.close_all()
156 PORT = None
157 time.sleep(0.5)
158 serv_evt.set()
159
160MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
161MSG_END = '------------ END MESSAGE ------------\n'
162
Guido van Rossum04110fb2007-08-24 16:32:05 +0000163# NOTE: Some SMTP objects in the tests below are created with a non-default
164# local_hostname argument to the constructor, since (on some systems) the FQDN
165# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000166# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000167
168# Test behavior of smtpd.DebuggingServer
Guido van Rossum806c2462007-08-06 23:33:07 +0000169class DebuggingServerTests(TestCase):
170
171 def setUp(self):
172 # temporarily replace sys.stdout to capture DebuggingServer output
173 self.old_stdout = sys.stdout
174 self.output = io.StringIO()
175 sys.stdout = self.output
176
177 self.serv_evt = threading.Event()
178 self.client_evt = threading.Event()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000179 serv_args = (smtpd.DebuggingServer, self.serv_evt, self.client_evt)
Guido van Rossum806c2462007-08-06 23:33:07 +0000180 threading.Thread(target=debugging_server, args=serv_args).start()
181
182 # wait until server thread has assigned a port number
183 n = 500
184 while PORT is None and n > 0:
185 time.sleep(0.01)
186 n -= 1
187
188 # wait a little longer (sometimes connections are refused
189 # on slow machines without this additional wait)
190 time.sleep(0.5)
191
192 def tearDown(self):
193 # indicate that the client is finished
194 self.client_evt.set()
195 # wait for the server thread to terminate
196 self.serv_evt.wait()
197 # restore sys.stdout
198 sys.stdout = self.old_stdout
199
200 def testBasic(self):
201 # connect
202 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
203 smtp.quit()
204
Guido van Rossum04110fb2007-08-24 16:32:05 +0000205 def testNOOP(self):
206 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
207 expected = (250, b'Ok')
208 self.assertEqual(smtp.noop(), expected)
209 smtp.quit()
210
211 def testRSET(self):
212 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
213 expected = (250, b'Ok')
214 self.assertEqual(smtp.rset(), expected)
215 smtp.quit()
216
217 def testNotImplemented(self):
218 # EHLO isn't implemented in DebuggingServer
Guido van Rossum806c2462007-08-06 23:33:07 +0000219 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
220 expected = (502, b'Error: command "EHLO" not implemented')
221 self.assertEqual(smtp.ehlo(), expected)
222 smtp.quit()
223
Guido van Rossum04110fb2007-08-24 16:32:05 +0000224 def testVRFY(self):
225 # VRFY isn't implemented in DebuggingServer
226 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
227 expected = (502, b'Error: command "VRFY" not implemented')
228 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
229 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
230 smtp.quit()
231
232 def testSecondHELO(self):
233 # check that a second HELO returns a message that it's a duplicate
234 # (this behavior is specific to smtpd.SMTPChannel)
235 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
236 smtp.helo()
237 expected = (503, b'Duplicate HELO/EHLO')
238 self.assertEqual(smtp.helo(), expected)
239 smtp.quit()
240
Guido van Rossum806c2462007-08-06 23:33:07 +0000241 def testHELP(self):
242 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
243 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
244 smtp.quit()
245
246 def testSend(self):
247 # connect and send mail
248 m = 'A test message'
249 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
250 smtp.sendmail('John', 'Sally', m)
251 smtp.quit()
252
253 self.client_evt.set()
254 self.serv_evt.wait()
255 self.output.flush()
256 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
257 self.assertEqual(self.output.getvalue(), mexpect)
258
259
Guido van Rossum04110fb2007-08-24 16:32:05 +0000260# test response of client to a non-successful HELO message
Guido van Rossum806c2462007-08-06 23:33:07 +0000261class BadHELOServerTests(TestCase):
262
263 def setUp(self):
264 self.old_stdout = sys.stdout
265 self.output = io.StringIO()
266 sys.stdout = self.output
267
268 self.evt = threading.Event()
269 servargs = (self.evt, b"199 no hello for you!\n")
270 threading.Thread(target=server, args=servargs).start()
271
272 # wait until server thread has assigned a port number
273 n = 500
274 while PORT is None and n > 0:
275 time.sleep(0.01)
276 n -= 1
277
278 # wait a little longer (sometimes connections are refused
279 # on slow machines without this additional wait)
280 time.sleep(0.5)
281
282 def tearDown(self):
283 self.evt.wait()
284 sys.stdout = self.old_stdout
285
286 def testFailingHELO(self):
287 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
288 HOST, PORT, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289
Guido van Rossum04110fb2007-08-24 16:32:05 +0000290
291sim_users = {'Mr.A@somewhere.com':'John A',
292 'Ms.B@somewhere.com':'Sally B',
293 'Mrs.C@somewhereesle.com':'Ruth C',
294 }
295
296sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
297 'list-2':['Ms.B@somewhere.com',],
298 }
299
300# Simulated SMTP channel & server
301class SimSMTPChannel(smtpd.SMTPChannel):
302 def smtp_EHLO(self, arg):
303 resp = '250-testhost\r\n' \
304 '250-EXPN\r\n' \
305 '250-SIZE 20000000\r\n' \
306 '250-STARTTLS\r\n' \
307 '250-DELIVERBY\r\n' \
308 '250 HELP'
309 self.push(resp)
310
311 def smtp_VRFY(self, arg):
312# print '\nsmtp_VRFY(%r)\n' % arg
313
314 raw_addr = email.utils.parseaddr(arg)[1]
315 quoted_addr = smtplib.quoteaddr(arg)
316 if raw_addr in sim_users:
317 self.push('250 %s %s' % (sim_users[raw_addr], quoted_addr))
318 else:
319 self.push('550 No such user: %s' % arg)
320
321 def smtp_EXPN(self, arg):
322# print '\nsmtp_EXPN(%r)\n' % arg
323
324 list_name = email.utils.parseaddr(arg)[1].lower()
325 if list_name in sim_lists:
326 user_list = sim_lists[list_name]
327 for n, user_email in enumerate(user_list):
328 quoted_addr = smtplib.quoteaddr(user_email)
329 if n < len(user_list) - 1:
330 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
331 else:
332 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
333 else:
334 self.push('550 No access for you!')
335
336
337class SimSMTPServer(smtpd.SMTPServer):
338 def handle_accept(self):
339 conn, addr = self.accept()
340 channel = SimSMTPChannel(self, conn, addr)
341
342 def process_message(self, peer, mailfrom, rcpttos, data):
343 pass
344
345
346# Test various SMTP & ESMTP commands/behaviors that require a simulated server
347# (i.e., something with more features than DebuggingServer)
348class SMTPSimTests(TestCase):
349
350 def setUp(self):
351 self.serv_evt = threading.Event()
352 self.client_evt = threading.Event()
353 serv_args = (SimSMTPServer, self.serv_evt, self.client_evt)
354 threading.Thread(target=debugging_server, args=serv_args).start()
355
356 # wait until server thread has assigned a port number
357 n = 500
358 while PORT is None and n > 0:
359 time.sleep(0.01)
360 n -= 1
361
362 # wait a little longer (sometimes connections are refused
363 # on slow machines without this additional wait)
364 time.sleep(0.5)
365
366 def tearDown(self):
367 # indicate that the client is finished
368 self.client_evt.set()
369 # wait for the server thread to terminate
370 self.serv_evt.wait()
371
372 def testBasic(self):
373 # smoke test
374 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
375 smtp.quit()
376
377 def testEHLO(self):
378 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
379
380 # no features should be present before the EHLO
381 self.assertEqual(smtp.esmtp_features, {})
382
383 # features expected from the test server
384 expected_features = {'expn':'',
385 'size': '20000000',
386 'starttls': '',
387 'deliverby': '',
388 'help': '',
389 }
390
391 smtp.ehlo()
392 self.assertEqual(smtp.esmtp_features, expected_features)
393 for k in expected_features:
394 self.assertTrue(smtp.has_extn(k))
395 self.assertFalse(smtp.has_extn('unsupported-feature'))
396 smtp.quit()
397
398 def testVRFY(self):
399 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
400
401 for email, name in sim_users.items():
402 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000403 (name, smtplib.quoteaddr(email)),
404 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000405 self.assertEqual(smtp.vrfy(email), expected_known)
406
407 u = 'nobody@nowhere.com'
408 expected_unknown = (550, bytes('No such user: %s'
409 % smtplib.quoteaddr(u)))
410 self.assertEqual(smtp.vrfy(u), expected_unknown)
411 smtp.quit()
412
413 def testEXPN(self):
414 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
415
416 for listname, members in sim_lists.items():
417 users = []
418 for m in members:
419 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000420 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000421 self.assertEqual(smtp.expn(listname), expected_known)
422
423 u = 'PSU-Members-List'
424 expected_unknown = (550, b'No access for you!')
425 self.assertEqual(smtp.expn(u), expected_unknown)
426 smtp.quit()
427
428
429
Guido van Rossumd8faa362007-04-27 19:54:29 +0000430def test_main(verbose=None):
Guido van Rossum806c2462007-08-06 23:33:07 +0000431 test_support.run_unittest(GeneralTests, DebuggingServerTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000432 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000433
434if __name__ == '__main__':
435 test_main()