blob: 933523b93045b6069fcc2c7a14a09f551252ded6 [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()
Facundo Batista16609332008-02-23 12:27:17 +000085 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
86 self.assertRaises(smtplib.SMTPServerDisconnected,
87 smtp.send, 'test msg')
Facundo Batista1bc8d632007-08-21 16:57:18 +000088
Facundo Batista16ed5b42007-07-24 21:20:42 +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):
Facundo Batista1bc8d632007-08-21 16:57:18 +000096 # check that non-numeric port raises socket.error
Facundo Batista412b8b62007-08-01 23:18:36 +000097 self.assertRaises(socket.error, smtplib.SMTP,
98 "localhost", "bogus")
Facundo Batista1bc8d632007-08-21 16:57:18 +000099 self.assertRaises(socket.error, smtplib.SMTP,
100 "localhost:bogus")
Facundo Batista16ed5b42007-07-24 21:20:42 +0000101
Facundo Batista366d6262007-03-28 18:25:54 +0000102 def testTimeoutDefault(self):
103 # default
Facundo Batista16ed5b42007-07-24 21:20:42 +0000104 smtp = smtplib.SMTP(HOST, PORT)
Facundo Batista366d6262007-03-28 18:25:54 +0000105 self.assertTrue(smtp.sock.gettimeout() is None)
106 smtp.sock.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000107
Facundo Batista366d6262007-03-28 18:25:54 +0000108 def testTimeoutValue(self):
109 # a value
Facundo Batista16ed5b42007-07-24 21:20:42 +0000110 smtp = smtplib.SMTP(HOST, PORT, timeout=30)
Facundo Batista366d6262007-03-28 18:25:54 +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:
Facundo Batista16ed5b42007-07-24 21:20:42 +0000119 smtp = smtplib.SMTP(HOST, PORT, timeout=None)
Facundo Batista366d6262007-03-28 18:25:54 +0000120 finally:
121 socket.setdefaulttimeout(previous)
122 self.assertEqual(smtp.sock.gettimeout(), 30)
123 smtp.sock.close()
124
125
Facundo Batista1bc8d632007-08-21 16:57:18 +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))
Facundo Batista412b8b62007-08-01 23:18:36 +0000129 global PORT
130 PORT = serv.getsockname()[1]
Facundo Batista16ed5b42007-07-24 21:20:42 +0000131
132 try:
Facundo Batista412b8b62007-08-01 23:18:36 +0000133 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
Facundo Batista16ed5b42007-07-24 21:20:42 +0000150 except socket.timeout:
151 pass
152 finally:
153 # allow some time for the client to read the result
154 time.sleep(0.5)
Facundo Batista412b8b62007-08-01 23:18:36 +0000155 serv.close()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000156 asyncore.close_all()
Facundo Batista412b8b62007-08-01 23:18:36 +0000157 PORT = None
158 time.sleep(0.5)
159 serv_evt.set()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000160
161MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
162MSG_END = '------------ END MESSAGE ------------\n'
163
Facundo Batista1bc8d632007-08-21 16:57:18 +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
Facundo Batista412b8b62007-08-01 23:18:36 +0000167# test server times out, causing the test to fail.
Facundo Batista1bc8d632007-08-21 16:57:18 +0000168
169# Test behavior of smtpd.DebuggingServer
Facundo Batista16ed5b42007-07-24 21:20:42 +0000170class DebuggingServerTests(TestCase):
171
172 def setUp(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000173 # temporarily replace sys.stdout to capture DebuggingServer output
Facundo Batista16ed5b42007-07-24 21:20:42 +0000174 self.old_stdout = sys.stdout
175 self.output = StringIO.StringIO()
176 sys.stdout = self.output
177
Facundo Batista412b8b62007-08-01 23:18:36 +0000178 self.serv_evt = threading.Event()
179 self.client_evt = threading.Event()
Facundo Batista1bc8d632007-08-21 16:57:18 +0000180 serv_args = (smtpd.DebuggingServer, self.serv_evt, self.client_evt)
Facundo Batista412b8b62007-08-01 23:18:36 +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)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000192
193 def tearDown(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000194 # 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
Facundo Batista16ed5b42007-07-24 21:20:42 +0000199 sys.stdout = self.old_stdout
200
201 def testBasic(self):
202 # connect
Facundo Batista412b8b62007-08-01 23:18:36 +0000203 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
204 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000205
Facundo Batista1bc8d632007-08-21 16:57:18 +0000206 def testNOOP(self):
207 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
208 expected = (250, '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, 'Ok')
215 self.assertEqual(smtp.rset(), expected)
216 smtp.quit()
217
218 def testNotImplemented(self):
219 # EHLO isn't implemented in DebuggingServer
Facundo Batista412b8b62007-08-01 23:18:36 +0000220 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
221 expected = (502, 'Error: command "EHLO" not implemented')
222 self.assertEqual(smtp.ehlo(), expected)
223 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000224
Facundo Batista1bc8d632007-08-21 16:57:18 +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, '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, 'Duplicate HELO/EHLO')
239 self.assertEqual(smtp.helo(), expected)
240 smtp.quit()
241
Facundo Batista16ed5b42007-07-24 21:20:42 +0000242 def testHELP(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000243 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000244 self.assertEqual(smtp.help(), 'Error: command "HELP" not implemented')
Facundo Batista412b8b62007-08-01 23:18:36 +0000245 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000246
247 def testSend(self):
248 # connect and send mail
249 m = 'A test message'
Facundo Batista412b8b62007-08-01 23:18:36 +0000250 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000251 smtp.sendmail('John', 'Sally', m)
Facundo Batista412b8b62007-08-01 23:18:36 +0000252 smtp.quit()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000253
Facundo Batista412b8b62007-08-01 23:18:36 +0000254 self.client_evt.set()
255 self.serv_evt.wait()
Facundo Batista16ed5b42007-07-24 21:20:42 +0000256 self.output.flush()
257 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
258 self.assertEqual(self.output.getvalue(), mexpect)
259
260
Facundo Batista1bc8d632007-08-21 16:57:18 +0000261# test response of client to a non-successful HELO message
Facundo Batista16ed5b42007-07-24 21:20:42 +0000262class BadHELOServerTests(TestCase):
263
264 def setUp(self):
265 self.old_stdout = sys.stdout
266 self.output = StringIO.StringIO()
267 sys.stdout = self.output
268
269 self.evt = threading.Event()
270 servargs = (self.evt, "199 no hello for you!\n")
271 threading.Thread(target=server, args=servargs).start()
Facundo Batista412b8b62007-08-01 23:18:36 +0000272
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)
Facundo Batista16ed5b42007-07-24 21:20:42 +0000282
283 def tearDown(self):
284 self.evt.wait()
285 sys.stdout = self.old_stdout
286
287 def testFailingHELO(self):
Facundo Batista412b8b62007-08-01 23:18:36 +0000288 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
289 HOST, PORT, 'localhost', 3)
Facundo Batista366d6262007-03-28 18:25:54 +0000290
Facundo Batista1bc8d632007-08-21 16:57:18 +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, '%s %s' % (name, smtplib.quoteaddr(email)))
404 self.assertEqual(smtp.vrfy(email), expected_known)
405
406 u = 'nobody@nowhere.com'
407 expected_unknown = (550, 'No such user: %s' % smtplib.quoteaddr(u))
408 self.assertEqual(smtp.vrfy(u), expected_unknown)
409 smtp.quit()
410
411 def testEXPN(self):
412 smtp = smtplib.SMTP(HOST, PORT, local_hostname='localhost', timeout=3)
413
414 for listname, members in sim_lists.items():
415 users = []
416 for m in members:
417 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
418 expected_known = (250, '\n'.join(users))
419 self.assertEqual(smtp.expn(listname), expected_known)
420
421 u = 'PSU-Members-List'
422 expected_unknown = (550, 'No access for you!')
423 self.assertEqual(smtp.expn(u), expected_unknown)
424 smtp.quit()
425
426
427
Facundo Batista366d6262007-03-28 18:25:54 +0000428def test_main(verbose=None):
Facundo Batista412b8b62007-08-01 23:18:36 +0000429 test_support.run_unittest(GeneralTests, DebuggingServerTests,
Facundo Batista1bc8d632007-08-21 16:57:18 +0000430 BadHELOServerTests, SMTPSimTests)
Facundo Batista366d6262007-03-28 18:25:54 +0000431
432if __name__ == '__main__':
433 test_main()