Debian Codegraph @

Lib/test/test_poplib.py

raw
1 """Test script for poplib module."""
2
3 # Modified by Giampaolo Rodola' to give poplib.POP3 and poplib.POP3_SSL
4 # a real test suite
5
6 import poplib
7 import socket
8 import os
9 import errno
10 import threading
11
12 import unittest
13 from unittest import TestCase, skipUnless
14 from test import support as test_support
15 from test.support import hashlib_helper
16 from test.support import socket_helper
17 from test.support import threading_helper
18 from test.support import asynchat
19 from test.support import asyncore
20 from test.support.testcase import ExtraAssertions
21
22
23 test_support.requires_working_socket(module=True)
24
25 HOST = socket_helper.HOST
26 PORT = 0
27
28 SUPPORTS_SSL = False
29 if hasattr(poplib, 'POP3_SSL'):
30 import ssl
31
32 SUPPORTS_SSL = True
33 CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "certdata", "keycert3.pem")
34 CAFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "certdata", "pycacert.pem")
35
36 requires_ssl = skipUnless(SUPPORTS_SSL, 'SSL not supported')
37
38 # the dummy data returned by server when LIST and RETR commands are issued
39 LIST_RESP = b'1 1\r\n2 2\r\n3 3\r\n4 4\r\n5 5\r\n.\r\n'
40 RETR_RESP = b"""From: [email protected]\
41 \r\nContent-Type: text/plain\r\n\
42 MIME-Version: 1.0\r\n\
43 Subject: Dummy\r\n\
44 \r\n\
45 line1\r\n\
46 line2\r\n\
47 line3\r\n\
48 .\r\n"""
49
50
51 class DummyPOP3Handler(asynchat.async_chat):
52
53 CAPAS = {'UIDL': [], 'IMPLEMENTATION': ['python-testlib-pop-server']}
54 enable_UTF8 = False
55
56 def __init__(self, conn):
57 asynchat.async_chat.__init__(self, conn)
58 self.set_terminator(b"\r\n")
59 self.in_buffer = []
60 self.push('+OK dummy pop3 server ready. <timestamp>')
61 self.tls_active = False
62 self.tls_starting = False
63
64 def collect_incoming_data(self, data):
65 self.in_buffer.append(data)
66
67 def found_terminator(self):
68 line = b''.join(self.in_buffer)
69 line = str(line, 'ISO-8859-1')
70 self.in_buffer = []
71 cmd = line.split(' ')[0].lower()
72 space = line.find(' ')
73 if space != -1:
74 arg = line[space + 1:]
75 else:
76 arg = ""
77 if hasattr(self, 'cmd_' + cmd):
78 method = getattr(self, 'cmd_' + cmd)
79 method(arg)
80 else:
81 self.push('-ERR unrecognized POP3 command "%s".' %cmd)
82
83 def handle_error(self):
84 raise
85
86 def push(self, data):
87 asynchat.async_chat.push(self, data.encode("ISO-8859-1") + b'\r\n')
88
89 def cmd_echo(self, arg):
90 # sends back the received string (used by the test suite)
91 self.push(arg)
92
93 def cmd_user(self, arg):
94 if arg != "guido":
95 self.push("-ERR no such user")
96 self.push('+OK password required')
97
98 def cmd_pass(self, arg):
99 if arg != "python":
100 self.push("-ERR wrong password")
101 self.push('+OK 10 messages')
102
103 def cmd_stat(self, arg):
104 self.push('+OK 10 100')
105
106 def cmd_list(self, arg):
107 if arg:
108 self.push('+OK %s %s' % (arg, arg))
109 else:
110 self.push('+OK')
111 asynchat.async_chat.push(self, LIST_RESP)
112
113 cmd_uidl = cmd_list
114
115 def cmd_retr(self, arg):
116 self.push('+OK %s bytes' %len(RETR_RESP))
117 asynchat.async_chat.push(self, RETR_RESP)
118
119 cmd_top = cmd_retr
120
121 def cmd_dele(self, arg):
122 self.push('+OK message marked for deletion.')
123
124 def cmd_noop(self, arg):
125 self.push('+OK done nothing.')
126
127 def cmd_rpop(self, arg):
128 self.push('+OK done nothing.')
129
130 def cmd_apop(self, arg):
131 self.push('+OK done nothing.')
132
133 def cmd_quit(self, arg):
134 self.push('+OK closing.')
135 self.close_when_done()
136
137 def _get_capas(self):
138 _capas = dict(self.CAPAS)
139 if not self.tls_active and SUPPORTS_SSL:
140 _capas['STLS'] = []
141 return _capas
142
143 def cmd_capa(self, arg):
144 self.push('+OK Capability list follows')
145 if self._get_capas():
146 for cap, params in self._get_capas().items():
147 _ln = [cap]
148 if params:
149 _ln.extend(params)
150 self.push(' '.join(_ln))
151 self.push('.')
152
153 def cmd_utf8(self, arg):
154 self.push('+OK I know RFC6856'
155 if self.enable_UTF8
156 else '-ERR What is UTF8?!')
157
158 if SUPPORTS_SSL:
159
160 def cmd_stls(self, arg):
161 if self.tls_active is False:
162 self.push('+OK Begin TLS negotiation')
163 context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
164 context.load_cert_chain(CERTFILE)
165 tls_sock = context.wrap_socket(self.socket,
166 server_side=True,
167 do_handshake_on_connect=False,
168 suppress_ragged_eofs=False)
169 self.del_channel()
170 self.set_socket(tls_sock)
171 self.tls_active = True
172 self.tls_starting = True
173 self.in_buffer = []
174 self._do_tls_handshake()
175 else:
176 self.push('-ERR Command not permitted when TLS active')
177
178 def _do_tls_handshake(self):
179 try:
180 self.socket.do_handshake()
181 except ssl.SSLError as err:
182 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
183 ssl.SSL_ERROR_WANT_WRITE):
184 return
185 elif err.args[0] == ssl.SSL_ERROR_EOF:
186 return self.handle_close()
187 # TODO: SSLError does not expose alert information
188 elif ("SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1] or
189 "SSLV3_ALERT_CERTIFICATE_UNKNOWN" in err.args[1]):
190 return self.handle_close()
191 raise
192 except OSError as err:
193 if err.args[0] == errno.ECONNABORTED:
194 return self.handle_close()
195 else:
196 self.tls_active = True
197 self.tls_starting = False
198
199 def handle_read(self):
200 if self.tls_starting:
201 self._do_tls_handshake()
202 else:
203 try:
204 asynchat.async_chat.handle_read(self)
205 except ssl.SSLEOFError:
206 self.handle_close()
207
208 class DummyPOP3Server(asyncore.dispatcher, threading.Thread):
209
210 handler = DummyPOP3Handler
211
212 def __init__(self, address, af=socket.AF_INET):
213 threading.Thread.__init__(self)
214 asyncore.dispatcher.__init__(self)
215 self.daemon = True
216 self.create_socket(af, socket.SOCK_STREAM)
217 self.bind(address)
218 self.listen(5)
219 self.active = False
220 self.active_lock = threading.Lock()
221 self.host, self.port = self.socket.getsockname()[:2]
222 self.handler_instance = None
223
224 def start(self):
225 assert not self.active
226 self.__flag = threading.Event()
227 threading.Thread.start(self)
228 self.__flag.wait()
229
230 def run(self):
231 self.active = True
232 self.__flag.set()
233 try:
234 while self.active and asyncore.socket_map:
235 with self.active_lock:
236 asyncore.loop(timeout=0.1, count=1)
237 finally:
238 asyncore.close_all(ignore_all=True)
239
240 def stop(self):
241 assert self.active
242 self.active = False
243 self.join()
244
245 def handle_accepted(self, conn, addr):
246 self.handler_instance = self.handler(conn)
247
248 def handle_connect(self):
249 self.close()
250 handle_read = handle_connect
251
252 def writable(self):
253 return 0
254
255 def handle_error(self):
256 raise
257
258
259 class TestPOP3Class(TestCase, ExtraAssertions):
260 def assertOK(self, resp):
261 self.assertStartsWith(resp, b"+OK")
262
263 def setUp(self):
264 self.server = DummyPOP3Server((HOST, PORT))
265 self.server.start()
266 self.client = poplib.POP3(self.server.host, self.server.port,
267 timeout=test_support.LOOPBACK_TIMEOUT)
268
269 def tearDown(self):
270 self.client.close()
271 self.server.stop()
272 # Explicitly clear the attribute to prevent dangling thread
273 self.server = None
274
275 def test_getwelcome(self):
276 self.assertEqual(self.client.getwelcome(),
277 b'+OK dummy pop3 server ready. <timestamp>')
278
279 def test_exceptions(self):
280 self.assertRaises(poplib.error_proto, self.client._shortcmd, 'echo -err')
281
282 def test_user(self):
283 self.assertOK(self.client.user('guido'))
284 self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
285
286 def test_pass_(self):
287 self.assertOK(self.client.pass_('python'))
288 self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
289
290 def test_stat(self):
291 self.assertEqual(self.client.stat(), (10, 100))
292
293 original_shortcmd = self.client._shortcmd
294 def mock_shortcmd_invalid_format(cmd):
295 if cmd == 'STAT':
296 return b'+OK'
297 return original_shortcmd(cmd)
298
299 self.client._shortcmd = mock_shortcmd_invalid_format
300 with self.assertRaises(poplib.error_proto):
301 self.client.stat()
302
303 def mock_shortcmd_invalid_data(cmd):
304 if cmd == 'STAT':
305 return b'+OK abc def'
306 return original_shortcmd(cmd)
307
308 self.client._shortcmd = mock_shortcmd_invalid_data
309 with self.assertRaises(poplib.error_proto):
310 self.client.stat()
311
312 def mock_shortcmd_extra_fields(cmd):
313 if cmd == 'STAT':
314 return b'+OK 1 2 3 4 5'
315 return original_shortcmd(cmd)
316
317 self.client._shortcmd = mock_shortcmd_extra_fields
318
319 result = self.client.stat()
320 self.assertEqual(result, (1, 2))
321
322 self.client._shortcmd = original_shortcmd
323
324 def test_list(self):
325 self.assertEqual(self.client.list()[1:],
326 ([b'1 1', b'2 2', b'3 3', b'4 4', b'5 5'],
327 25))
328 self.assertEndsWith(self.client.list('1'), b"OK 1 1")
329
330 def test_retr(self):
331 expected = (b'+OK 116 bytes',
332 [b'From: [email protected]', b'Content-Type: text/plain',
333 b'MIME-Version: 1.0', b'Subject: Dummy',
334 b'', b'line1', b'line2', b'line3'],
335 113)
336 foo = self.client.retr('foo')
337 self.assertEqual(foo, expected)
338
339 def test_too_long_lines(self):
340 self.assertRaises(poplib.error_proto, self.client._shortcmd,
341 'echo +%s' % ((poplib._MAXLINE + 10) * 'a'))
342
343 def test_dele(self):
344 self.assertOK(self.client.dele('foo'))
345
346 def test_noop(self):
347 self.assertOK(self.client.noop())
348
349 def test_rpop(self):
350 self.assertOK(self.client.rpop('foo'))
351
352 @hashlib_helper.requires_hashdigest('md5', openssl=True)
353 def test_apop_normal(self):
354 self.assertOK(self.client.apop('foo', 'dummypassword'))
355
356 @hashlib_helper.requires_hashdigest('md5', openssl=True)
357 def test_apop_REDOS(self):
358 # Replace welcome with very long evil welcome.
359 # NB The upper bound on welcome length is currently 2048.
360 # At this length, evil input makes each apop call take
361 # on the order of milliseconds instead of microseconds.
362 evil_welcome = b'+OK' + (b'<' * 1000000)
363 with test_support.swap_attr(self.client, 'welcome', evil_welcome):
364 # The evil welcome is invalid, so apop should throw.
365 self.assertRaises(poplib.error_proto, self.client.apop, 'a', 'kb')
366
367 def test_top(self):
368 expected = (b'+OK 116 bytes',
369 [b'From: [email protected]', b'Content-Type: text/plain',
370 b'MIME-Version: 1.0', b'Subject: Dummy', b'',
371 b'line1', b'line2', b'line3'],
372 113)
373 self.assertEqual(self.client.top(1, 1), expected)
374
375 def test_uidl(self):
376 self.client.uidl()
377 self.client.uidl('foo')
378
379 def test_utf8_raises_if_unsupported(self):
380 self.server.handler.enable_UTF8 = False
381 self.assertRaises(poplib.error_proto, self.client.utf8)
382
383 def test_utf8(self):
384 self.server.handler.enable_UTF8 = True
385 expected = b'+OK I know RFC6856'
386 result = self.client.utf8()
387 self.assertEqual(result, expected)
388
389 def test_capa(self):
390 capa = self.client.capa()
391 self.assertTrue('IMPLEMENTATION' in capa.keys())
392
393 def test_quit(self):
394 resp = self.client.quit()
395 self.assertTrue(resp)
396 self.assertIsNone(self.client.sock)
397 self.assertIsNone(self.client.file)
398
399 @requires_ssl
400 def test_stls_capa(self):
401 capa = self.client.capa()
402 self.assertTrue('STLS' in capa.keys())
403
404 @requires_ssl
405 def test_stls(self):
406 expected = b'+OK Begin TLS negotiation'
407 resp = self.client.stls()
408 self.assertEqual(resp, expected)
409
410 @requires_ssl
411 def test_stls_context(self):
412 expected = b'+OK Begin TLS negotiation'
413 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
414 ctx.load_verify_locations(CAFILE)
415 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
416 self.assertEqual(ctx.check_hostname, True)
417 with self.assertRaises(ssl.CertificateError):
418 resp = self.client.stls(context=ctx)
419 self.client = poplib.POP3("localhost", self.server.port,
420 timeout=test_support.LOOPBACK_TIMEOUT)
421 resp = self.client.stls(context=ctx)
422 self.assertEqual(resp, expected)
423
424
425 if SUPPORTS_SSL:
426 from test.test_ftplib import SSLConnection
427
428 class DummyPOP3_SSLHandler(SSLConnection, DummyPOP3Handler):
429
430 def __init__(self, conn):
431 asynchat.async_chat.__init__(self, conn)
432 self.secure_connection()
433 self.set_terminator(b"\r\n")
434 self.in_buffer = []
435 self.push('+OK dummy pop3 server ready. <timestamp>')
436 self.tls_active = True
437 self.tls_starting = False
438
439
440 @requires_ssl
441 class TestPOP3_SSLClass(TestPOP3Class):
442 # repeat previous tests by using poplib.POP3_SSL
443
444 def setUp(self):
445 self.server = DummyPOP3Server((HOST, PORT))
446 self.server.handler = DummyPOP3_SSLHandler
447 self.server.start()
448 self.client = poplib.POP3_SSL(self.server.host, self.server.port)
449
450 def test__all__(self):
451 self.assertIn('POP3_SSL', poplib.__all__)
452
453 def test_context(self):
454 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
455 ctx.check_hostname = False
456 ctx.verify_mode = ssl.CERT_NONE
457
458 self.client.quit()
459 self.client = poplib.POP3_SSL(self.server.host, self.server.port,
460 context=ctx)
461 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
462 self.assertIs(self.client.sock.context, ctx)
463 self.assertStartsWith(self.client.noop(), b'+OK')
464
465 def test_stls(self):
466 self.assertRaises(poplib.error_proto, self.client.stls)
467
468 test_stls_context = test_stls
469
470 def test_stls_capa(self):
471 capa = self.client.capa()
472 self.assertFalse('STLS' in capa.keys())
473
474
475 @requires_ssl
476 class TestPOP3_TLSClass(TestPOP3Class):
477 # repeat previous tests by using poplib.POP3.stls()
478
479 def setUp(self):
480 self.server = DummyPOP3Server((HOST, PORT))
481 self.server.start()
482 self.client = poplib.POP3(self.server.host, self.server.port,
483 timeout=test_support.LOOPBACK_TIMEOUT)
484 self.client.stls()
485
486 def tearDown(self):
487 if self.client.file is not None and self.client.sock is not None:
488 try:
489 self.client.quit()
490 except poplib.error_proto:
491 # happens in the test_too_long_lines case; the overlong
492 # response will be treated as response to QUIT and raise
493 # this exception
494 self.client.close()
495 self.server.stop()
496 # Explicitly clear the attribute to prevent dangling thread
497 self.server = None
498
499 def test_stls(self):
500 self.assertRaises(poplib.error_proto, self.client.stls)
501
502 test_stls_context = test_stls
503
504 def test_stls_capa(self):
505 capa = self.client.capa()
506 self.assertFalse(b'STLS' in capa.keys())
507
508
509 class TestTimeouts(TestCase):
510
511 def setUp(self):
512 self.evt = threading.Event()
513 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
514 self.sock.settimeout(60) # Safety net. Look issue 11812
515 self.port = socket_helper.bind_port(self.sock)
516 self.thread = threading.Thread(target=self.server, args=(self.evt, self.sock))
517 self.thread.daemon = True
518 self.thread.start()
519 self.evt.wait()
520
521 def tearDown(self):
522 self.thread.join()
523 # Explicitly clear the attribute to prevent dangling thread
524 self.thread = None
525
526 def server(self, evt, serv):
527 serv.listen()
528 evt.set()
529 try:
530 conn, addr = serv.accept()
531 conn.send(b"+ Hola mundo\n")
532 conn.close()
533 except TimeoutError:
534 pass
535 finally:
536 serv.close()
537
538 def testTimeoutDefault(self):
539 self.assertIsNone(socket.getdefaulttimeout())
540 socket.setdefaulttimeout(test_support.LOOPBACK_TIMEOUT)
541 try:
542 pop = poplib.POP3(HOST, self.port)
543 finally:
544 socket.setdefaulttimeout(None)
545 self.assertEqual(pop.sock.gettimeout(), test_support.LOOPBACK_TIMEOUT)
546 pop.close()
547
548 def testTimeoutNone(self):
549 self.assertIsNone(socket.getdefaulttimeout())
550 socket.setdefaulttimeout(30)
551 try:
552 pop = poplib.POP3(HOST, self.port, timeout=None)
553 finally:
554 socket.setdefaulttimeout(None)
555 self.assertIsNone(pop.sock.gettimeout())
556 pop.close()
557
558 def testTimeoutValue(self):
559 pop = poplib.POP3(HOST, self.port, timeout=test_support.LOOPBACK_TIMEOUT)
560 self.assertEqual(pop.sock.gettimeout(), test_support.LOOPBACK_TIMEOUT)
561 pop.close()
562 with self.assertRaises(ValueError):
563 poplib.POP3(HOST, self.port, timeout=0)
564
565
566 def setUpModule():
567 thread_info = threading_helper.threading_setup()
568 unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info)
569
570
571 if __name__ == '__main__':
572 unittest.main()