blob: e2b9b060f440e2a07d8293516062d4a0200a0de7 [file] [log] [blame]
Facundo Batista16ed5b42007-07-24 21:20:42 +00001import asyncore
Facundo Batista1bc8d632007-08-21 16:57:18 +00002import email.utils
Facundo Batista366d6262007-03-28 18:25:54 +00003import socket
4import threading
Facundo Batista16ed5b42007-07-24 21:20:42 +00005import smtpd
Facundo Batista366d6262007-03-28 18:25:54 +00006import smtplib
Facundo Batista16ed5b42007-07-24 21:20:42 +00007import StringIO
8import sys
Facundo Batista366d6262007-03-28 18:25:54 +00009import time
Facundo Batista16ed5b42007-07-24 21:20:42 +000010import select
Facundo Batista366d6262007-03-28 18:25:54 +000011
12from unittest import TestCase
13from test import test_support
14
Facundo Batista412b8b62007-08-01 23:18:36 +000015# PORT is used to communicate the port number assigned to the server
16# to the test client
Facundo Batista16ed5b42007-07-24 21:20:42 +000017HOST = "localhost"
Facundo Batista412b8b62007-08-01 23:18:36 +000018PORT = None
Facundo Batista366d6262007-03-28 18:25:54 +000019
Facundo Batista16ed5b42007-07-24 21:20:42 +000020def server(evt, buf):
Facundo Batista366d6262007-03-28 18:25:54 +000021 try:
Facundo Batista412b8b62007-08-01 23:18:36 +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)
Facundo Batista366d6262007-03-28 18:25:54 +000029 conn, addr = serv.accept()
30 except socket.timeout:
31 pass
32 else:
Facundo Batista412b8b62007-08-01 23:18:36 +000033 n = 500
Facundo Batista16ed5b42007-07-24 21:20:42 +000034 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
Facundo Batista366d6262007-03-28 18:25:54 +000043 conn.close()
44 finally:
45 serv.close()
Facundo Batista412b8b62007-08-01 23:18:36 +000046 PORT = None
Facundo Batista366d6262007-03-28 18:25:54 +000047 evt.set()
48
49class GeneralTests(TestCase):
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000050
Facundo Batista366d6262007-03-28 18:25:54 +000051 def setUp(self):
52 self.evt = threading.Event()
Facundo Batista16ed5b42007-07-24 21:20:42 +000053 servargs = (self.evt, "220 Hola mundo\n")
54 threading.Thread(target=server, args=servargs).start()
Facundo Batista412b8b62007-08-01 23:18:36 +000055
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)
Facundo Batista366d6262007-03-28 18:25:54 +000065
66 def tearDown(self):
67 self.evt.wait()
68
Facundo Batista16ed5b42007-07-24 21:20:42 +000069 def testBasic1(self):
Facundo Batista366d6262007-03-28 18:25:54 +000070 # connects
Facundo Batista16ed5b42007-07-24 21:20:42 +000071 smtp = smtplib.SMTP(HOST, PORT)
Facundo Batista366d6262007-03-28 18:25:54 +000072 smtp.sock.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000073
Facundo Batista16ed5b42007-07-24 21:20:42 +000074 def testBasic2(self):
75 # connects, include port in host name
76 smtp = smtplib.SMTP("%s:%s" % (HOST, PORT))
77 smtp.sock.close()
78
Facundo Batista1bc8d632007-08-21 16:57:18 +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
Facundo Batista16ed5b42007-07-24 21:20:42 +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):
Facundo Batista1bc8d632007-08-21 16:57:18 +000095 # check that non-numeric port raises socket.error
Facundo Batista412b8b62007-08-01 23:18:36 +000096 self.assertRaises(socket.error, smtplib.SMTP,
97 "localhost", "bogus")
Facundo Batista1bc8d632007-08-21 16:57:18 +000098 self.assertRaises(socket.error, smtplib.SMTP,
99 "localhost:bogus")
Facundo Batista16ed5b42007-07-24 21:20:42 +0000100
Facundo Batista366d6262007-03-28 18:25:54 +0000101 def testTimeoutDefault(self):
102 # default
Facundo Batista16ed5b42007-07-24 21:20:42 +0000103 smtp = smtplib.SMTP(HOST, PORT)
Facundo Batista366d6262007-03-28 18:25:54 +0000104 self.assertTrue(smtp.sock.gettimeout() is None)
105 smtp.sock.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000106
Facundo Batista366d6262007-03-28 18:25:54 +0000107 def testTimeoutValue(self):
108 # a value
Facundo Batista16ed5b42007-07-24 21:20:42 +0000109 smtp = smtplib.SMTP(HOST, PORT, timeout=30)
Facundo Batista366d6262007-03-28 18:25:54 +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:
Facundo Batista16ed5b42007-07-24 21:20:42 +0000118 smtp = smtplib.SMTP(HOST, PORT, timeout=None)
Facundo Batista366d6262007-03-28 18:25:54 +0000119 finally:
120 socket.setdefaulttimeout(previous)
121 self.assertEqual(smtp.sock.gettimeout(), 30)
122 smtp.sock.close()
123
124
Facundo Batista1bc8d632007-08-21 16:57:18 +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))
Facundo Batista412b8b62007-08-01 23:18:36 +0000128 global PORT
129 PORT = serv.getsockname()[1]
Facundo Batista16ed5b42007-07-24 21:20:42 +0000130
131 try:
Facundo Batista412b8b62007-08-01 23:18:36 +0000132 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
Facundo Batista16ed5b42007-07-24 21:20:42 +0000149 except socket.timeout:
150 pass
151 finally:
152 # allow some time for the client to read the result
153 time.sleep(0.5)
Facundo Batista412b8b62007-08-01 23:18:36 +0000154 serv.close()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000155 asyncore.close_all()
Facundo Batista412b8b62007-08-01 23:18:36 +0000156 PORT = None
157 time.sleep(0.5)
158 serv_evt.set()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000159
160MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
161MSG_END = '------------ END MESSAGE ------------\n'
162
Facundo Batista1bc8d632007-08-21 16:57:18 +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
Facundo Batista412b8b62007-08-01 23:18:36 +0000166# test server times out, causing the test to fail.
Facundo Batista1bc8d632007-08-21 16:57:18 +0000167
168# Test behavior of smtpd.DebuggingServer
Facundo Batista16ed5b42007-07-24 21:20:42 +0000169class DebuggingServerTests(TestCase):
170
171 def setUp(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000172 # temporarily replace sys.stdout to capture DebuggingServer output
Facundo Batista16ed5b42007-07-24 21:20:42 +0000173 self.old_stdout = sys.stdout
174 self.output = StringIO.StringIO()
175 sys.stdout = self.output
176
Facundo Batista412b8b62007-08-01 23:18:36 +0000177 self.serv_evt = threading.Event()
178 self.client_evt = threading.Event()
Facundo Batista1bc8d632007-08-21 16:57:18 +0000179 serv_args = (smtpd.DebuggingServer, self.serv_evt, self.client_evt)
Facundo Batista412b8b62007-08-01 23:18:36 +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)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000191
192 def tearDown(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000193 # 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
Facundo Batista16ed5b42007-07-24 21:20:42 +0000198 sys.stdout = self.old_stdout
199
200 def testBasic(self):
201 # connect
Facundo Batista412b8b62007-08-01 23:18:36 +0000202 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
203 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000204
Facundo Batista1bc8d632007-08-21 16:57:18 +0000205 def testNOOP(self):
206 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
207 expected = (250, '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, 'Ok')
214 self.assertEqual(smtp.rset(), expected)
215 smtp.quit()
216
217 def testNotImplemented(self):
218 # EHLO isn't implemented in DebuggingServer
Facundo Batista412b8b62007-08-01 23:18:36 +0000219 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
220 expected = (502, 'Error: command "EHLO" not implemented')
221 self.assertEqual(smtp.ehlo(), expected)
222 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000223
Facundo Batista1bc8d632007-08-21 16:57:18 +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, '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, 'Duplicate HELO/EHLO')
238 self.assertEqual(smtp.helo(), expected)
239 smtp.quit()
240
Facundo Batista16ed5b42007-07-24 21:20:42 +0000241 def testHELP(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000242 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000243 self.assertEqual(smtp.help(), 'Error: command "HELP" not implemented')
Facundo Batista412b8b62007-08-01 23:18:36 +0000244 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000245
246 def testSend(self):
247 # connect and send mail
248 m = 'A test message'
Facundo Batista412b8b62007-08-01 23:18:36 +0000249 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000250 smtp.sendmail('John', 'Sally', m)
Facundo Batista412b8b62007-08-01 23:18:36 +0000251 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000252
Facundo Batista412b8b62007-08-01 23:18:36 +0000253 self.client_evt.set()
254 self.serv_evt.wait()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000255 self.output.flush()
256 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
257 self.assertEqual(self.output.getvalue(), mexpect)
258
259
Facundo Batista1bc8d632007-08-21 16:57:18 +0000260# test response of client to a non-successful HELO message
Facundo Batista16ed5b42007-07-24 21:20:42 +0000261class BadHELOServerTests(TestCase):
262
263 def setUp(self):
264 self.old_stdout = sys.stdout
265 self.output = StringIO.StringIO()
266 sys.stdout = self.output
267
268 self.evt = threading.Event()
269 servargs = (self.evt, "199 no hello for you!\n")
270 threading.Thread(target=server, args=servargs).start()
Facundo Batista412b8b62007-08-01 23:18:36 +0000271
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)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000281
282 def tearDown(self):
283 self.evt.wait()
284 sys.stdout = self.old_stdout
285
286 def testFailingHELO(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000287 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
288 HOST, PORT, 'localhost', 3)
Facundo Batista366d6262007-03-28 18:25:54 +0000289
Facundo Batista1bc8d632007-08-21 16:57:18 +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, '%s %s' % (name, smtplib.quoteaddr(email)))
403 self.assertEqual(smtp.vrfy(email), expected_known)
404
405 u = 'nobody@nowhere.com'
406 expected_unknown = (550, 'No such user: %s' % smtplib.quoteaddr(u))
407 self.assertEqual(smtp.vrfy(u), expected_unknown)
408 smtp.quit()
409
410 def testEXPN(self):
411 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
412
413 for listname, members in sim_lists.items():
414 users = []
415 for m in members:
416 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
417 expected_known = (250, '\n'.join(users))
418 self.assertEqual(smtp.expn(listname), expected_known)
419
420 u = 'PSU-Members-List'
421 expected_unknown = (550, 'No access for you!')
422 self.assertEqual(smtp.expn(u), expected_unknown)
423 smtp.quit()
424
425
426
Facundo Batista366d6262007-03-28 18:25:54 +0000427def test_main(verbose=None):
Facundo Batista412b8b62007-08-01 23:18:36 +0000428 test_support.run_unittest(GeneralTests, DebuggingServerTests,
Facundo Batista1bc8d632007-08-21 16:57:18 +0000429 BadHELOServerTests, SMTPSimTests)
Facundo Batista366d6262007-03-28 18:25:54 +0000430
431if __name__ == '__main__':
432 test_main()