blob: bbedbbdb10a10484e9bfaf5632e4a54db1e5ad74 [file] [log] [blame]
Christian Heimesd3956292008-11-05 19:48:27 +00001"""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
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import poplib
Christian Heimesd3956292008-11-05 19:48:27 +00007import asyncore
8import asynchat
9import socket
10import os
Antoine Pitroud3f8ab82010-04-24 21:26:44 +000011import errno
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020012import threading
Guido van Rossumd8faa362007-04-27 19:54:29 +000013
Serhiy Storchaka43767632013-11-03 21:31:38 +020014from unittest import TestCase, skipUnless
Christian Heimesd3956292008-11-05 19:48:27 +000015from test import support as test_support
Guido van Rossumd8faa362007-04-27 19:54:29 +000016
Christian Heimesd3956292008-11-05 19:48:27 +000017HOST = test_support.HOST
18PORT = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +000019
Antoine Pitrou8618d742012-11-23 20:13:48 +010020SUPPORTS_SSL = False
21if hasattr(poplib, 'POP3_SSL'):
22 import ssl
23
24 SUPPORTS_SSL = True
Christian Heimes1bc70682013-12-02 20:10:50 +010025 CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert3.pem")
26 CAFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "pycacert.pem")
Christian Heimese8a257c2013-12-15 21:44:43 +010027
Serhiy Storchaka43767632013-11-03 21:31:38 +020028requires_ssl = skipUnless(SUPPORTS_SSL, 'SSL not supported')
Antoine Pitrou8618d742012-11-23 20:13:48 +010029
Christian Heimesd3956292008-11-05 19:48:27 +000030# the dummy data returned by server when LIST and RETR commands are issued
31LIST_RESP = b'1 1\r\n2 2\r\n3 3\r\n4 4\r\n5 5\r\n.\r\n'
32RETR_RESP = b"""From: postmaster@python.org\
33\r\nContent-Type: text/plain\r\n\
34MIME-Version: 1.0\r\n\
35Subject: Dummy\r\n\
36\r\n\
37line1\r\n\
38line2\r\n\
39line3\r\n\
40.\r\n"""
Guido van Rossumd8faa362007-04-27 19:54:29 +000041
Christian Heimesd3956292008-11-05 19:48:27 +000042
43class DummyPOP3Handler(asynchat.async_chat):
44
Antoine Pitrou25cee192012-11-23 20:07:39 +010045 CAPAS = {'UIDL': [], 'IMPLEMENTATION': ['python-testlib-pop-server']}
R David Murrayb8cd3e42015-05-16 15:05:53 -040046 enable_UTF8 = False
Antoine Pitrou25cee192012-11-23 20:07:39 +010047
Christian Heimesd3956292008-11-05 19:48:27 +000048 def __init__(self, conn):
49 asynchat.async_chat.__init__(self, conn)
50 self.set_terminator(b"\r\n")
51 self.in_buffer = []
Mark Dickinsonea1158f2009-08-06 16:06:25 +000052 self.push('+OK dummy pop3 server ready. <timestamp>')
Antoine Pitrou8618d742012-11-23 20:13:48 +010053 self.tls_active = False
54 self.tls_starting = False
Christian Heimesd3956292008-11-05 19:48:27 +000055
56 def collect_incoming_data(self, data):
57 self.in_buffer.append(data)
58
59 def found_terminator(self):
60 line = b''.join(self.in_buffer)
61 line = str(line, 'ISO-8859-1')
62 self.in_buffer = []
63 cmd = line.split(' ')[0].lower()
64 space = line.find(' ')
65 if space != -1:
66 arg = line[space + 1:]
67 else:
68 arg = ""
69 if hasattr(self, 'cmd_' + cmd):
70 method = getattr(self, 'cmd_' + cmd)
71 method(arg)
72 else:
73 self.push('-ERR unrecognized POP3 command "%s".' %cmd)
74
75 def handle_error(self):
76 raise
77
78 def push(self, data):
79 asynchat.async_chat.push(self, data.encode("ISO-8859-1") + b'\r\n')
80
81 def cmd_echo(self, arg):
82 # sends back the received string (used by the test suite)
83 self.push(arg)
84
85 def cmd_user(self, arg):
86 if arg != "guido":
87 self.push("-ERR no such user")
88 self.push('+OK password required')
89
90 def cmd_pass(self, arg):
91 if arg != "python":
92 self.push("-ERR wrong password")
93 self.push('+OK 10 messages')
94
95 def cmd_stat(self, arg):
96 self.push('+OK 10 100')
97
98 def cmd_list(self, arg):
99 if arg:
Georg Brandl7e27abb2013-10-27 07:23:53 +0100100 self.push('+OK %s %s' % (arg, arg))
Christian Heimesd3956292008-11-05 19:48:27 +0000101 else:
102 self.push('+OK')
103 asynchat.async_chat.push(self, LIST_RESP)
104
105 cmd_uidl = cmd_list
106
107 def cmd_retr(self, arg):
108 self.push('+OK %s bytes' %len(RETR_RESP))
109 asynchat.async_chat.push(self, RETR_RESP)
110
111 cmd_top = cmd_retr
112
113 def cmd_dele(self, arg):
114 self.push('+OK message marked for deletion.')
115
116 def cmd_noop(self, arg):
117 self.push('+OK done nothing.')
118
119 def cmd_rpop(self, arg):
120 self.push('+OK done nothing.')
121
Mark Dickinsonea1158f2009-08-06 16:06:25 +0000122 def cmd_apop(self, arg):
123 self.push('+OK done nothing.')
124
Giampaolo Rodolà95bcb932011-02-25 22:28:24 +0000125 def cmd_quit(self, arg):
126 self.push('+OK closing.')
127 self.close_when_done()
128
Antoine Pitrou8618d742012-11-23 20:13:48 +0100129 def _get_capas(self):
130 _capas = dict(self.CAPAS)
131 if not self.tls_active and SUPPORTS_SSL:
132 _capas['STLS'] = []
133 return _capas
134
Antoine Pitrou25cee192012-11-23 20:07:39 +0100135 def cmd_capa(self, arg):
136 self.push('+OK Capability list follows')
Antoine Pitrou8618d742012-11-23 20:13:48 +0100137 if self._get_capas():
138 for cap, params in self._get_capas().items():
Antoine Pitrou25cee192012-11-23 20:07:39 +0100139 _ln = [cap]
140 if params:
141 _ln.extend(params)
142 self.push(' '.join(_ln))
143 self.push('.')
144
R David Murrayb8cd3e42015-05-16 15:05:53 -0400145 def cmd_utf8(self, arg):
146 self.push('+OK I know RFC6856'
147 if self.enable_UTF8
148 else '-ERR What is UTF8?!')
149
Antoine Pitrou8618d742012-11-23 20:13:48 +0100150 if SUPPORTS_SSL:
151
152 def cmd_stls(self, arg):
153 if self.tls_active is False:
154 self.push('+OK Begin TLS negotiation')
Christian Heimesd0486372016-09-10 23:23:33 +0200155 context = ssl.SSLContext()
Miss Islington (bot)2614ed42018-02-27 00:17:49 -0800156 # TODO: fix TLSv1.3 support
157 context.options |= ssl.OP_NO_TLSv1_3
Christian Heimesd0486372016-09-10 23:23:33 +0200158 context.load_cert_chain(CERTFILE)
159 tls_sock = context.wrap_socket(self.socket,
160 server_side=True,
161 do_handshake_on_connect=False,
162 suppress_ragged_eofs=False)
Antoine Pitrou8618d742012-11-23 20:13:48 +0100163 self.del_channel()
164 self.set_socket(tls_sock)
165 self.tls_active = True
166 self.tls_starting = True
167 self.in_buffer = []
168 self._do_tls_handshake()
169 else:
170 self.push('-ERR Command not permitted when TLS active')
171
172 def _do_tls_handshake(self):
173 try:
174 self.socket.do_handshake()
175 except ssl.SSLError as err:
176 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
177 ssl.SSL_ERROR_WANT_WRITE):
178 return
179 elif err.args[0] == ssl.SSL_ERROR_EOF:
180 return self.handle_close()
Christian Heimes61d478c2018-01-27 15:51:38 +0100181 # TODO: SSLError does not expose alert information
Miss Islington (bot)8965d752018-05-17 05:49:01 -0700182 elif ("SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1] or
183 "SSLV3_ALERT_CERTIFICATE_UNKNOWN" in err.args[1]):
Christian Heimes61d478c2018-01-27 15:51:38 +0100184 return self.handle_close()
Antoine Pitrou8618d742012-11-23 20:13:48 +0100185 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +0200186 except OSError as err:
Antoine Pitrou8618d742012-11-23 20:13:48 +0100187 if err.args[0] == errno.ECONNABORTED:
188 return self.handle_close()
189 else:
190 self.tls_active = True
191 self.tls_starting = False
192
193 def handle_read(self):
194 if self.tls_starting:
195 self._do_tls_handshake()
196 else:
197 try:
198 asynchat.async_chat.handle_read(self)
199 except ssl.SSLEOFError:
200 self.handle_close()
Christian Heimesd3956292008-11-05 19:48:27 +0000201
202class DummyPOP3Server(asyncore.dispatcher, threading.Thread):
203
204 handler = DummyPOP3Handler
205
206 def __init__(self, address, af=socket.AF_INET):
207 threading.Thread.__init__(self)
208 asyncore.dispatcher.__init__(self)
209 self.create_socket(af, socket.SOCK_STREAM)
210 self.bind(address)
211 self.listen(5)
212 self.active = False
213 self.active_lock = threading.Lock()
214 self.host, self.port = self.socket.getsockname()[:2]
Giampaolo Rodolà42382fe2010-08-17 16:09:53 +0000215 self.handler_instance = None
Christian Heimesd3956292008-11-05 19:48:27 +0000216
217 def start(self):
218 assert not self.active
219 self.__flag = threading.Event()
220 threading.Thread.start(self)
221 self.__flag.wait()
222
223 def run(self):
224 self.active = True
225 self.__flag.set()
Miss Islington (bot)8965d752018-05-17 05:49:01 -0700226 try:
227 while self.active and asyncore.socket_map:
228 with self.active_lock:
229 asyncore.loop(timeout=0.1, count=1)
230 finally:
231 asyncore.close_all(ignore_all=True)
Christian Heimesd3956292008-11-05 19:48:27 +0000232
233 def stop(self):
234 assert self.active
235 self.active = False
236 self.join()
237
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000238 def handle_accepted(self, conn, addr):
Giampaolo Rodolà42382fe2010-08-17 16:09:53 +0000239 self.handler_instance = self.handler(conn)
Christian Heimesd3956292008-11-05 19:48:27 +0000240
241 def handle_connect(self):
242 self.close()
243 handle_read = handle_connect
244
245 def writable(self):
246 return 0
247
248 def handle_error(self):
249 raise
250
251
252class TestPOP3Class(TestCase):
253 def assertOK(self, resp):
254 self.assertTrue(resp.startswith(b"+OK"))
255
256 def setUp(self):
257 self.server = DummyPOP3Server((HOST, PORT))
258 self.server.start()
Giampaolo Rodolà95bcb932011-02-25 22:28:24 +0000259 self.client = poplib.POP3(self.server.host, self.server.port, timeout=3)
Christian Heimesd3956292008-11-05 19:48:27 +0000260
261 def tearDown(self):
Giampaolo Rodolà95bcb932011-02-25 22:28:24 +0000262 self.client.close()
Christian Heimesd3956292008-11-05 19:48:27 +0000263 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700264 # Explicitly clear the attribute to prevent dangling thread
265 self.server = None
Christian Heimesd3956292008-11-05 19:48:27 +0000266
267 def test_getwelcome(self):
Mark Dickinsonea1158f2009-08-06 16:06:25 +0000268 self.assertEqual(self.client.getwelcome(),
269 b'+OK dummy pop3 server ready. <timestamp>')
Christian Heimesd3956292008-11-05 19:48:27 +0000270
271 def test_exceptions(self):
272 self.assertRaises(poplib.error_proto, self.client._shortcmd, 'echo -err')
273
274 def test_user(self):
275 self.assertOK(self.client.user('guido'))
276 self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
277
278 def test_pass_(self):
279 self.assertOK(self.client.pass_('python'))
280 self.assertRaises(poplib.error_proto, self.client.user, 'invalid')
281
282 def test_stat(self):
283 self.assertEqual(self.client.stat(), (10, 100))
284
285 def test_list(self):
286 self.assertEqual(self.client.list()[1:],
287 ([b'1 1', b'2 2', b'3 3', b'4 4', b'5 5'],
288 25))
289 self.assertTrue(self.client.list('1').endswith(b"OK 1 1"))
290
291 def test_retr(self):
292 expected = (b'+OK 116 bytes',
293 [b'From: postmaster@python.org', b'Content-Type: text/plain',
294 b'MIME-Version: 1.0', b'Subject: Dummy',
295 b'', b'line1', b'line2', b'line3'],
296 113)
297 foo = self.client.retr('foo')
298 self.assertEqual(foo, expected)
299
Georg Brandl7e27abb2013-10-27 07:23:53 +0100300 def test_too_long_lines(self):
301 self.assertRaises(poplib.error_proto, self.client._shortcmd,
302 'echo +%s' % ((poplib._MAXLINE + 10) * 'a'))
303
Christian Heimesd3956292008-11-05 19:48:27 +0000304 def test_dele(self):
305 self.assertOK(self.client.dele('foo'))
306
307 def test_noop(self):
308 self.assertOK(self.client.noop())
309
310 def test_rpop(self):
311 self.assertOK(self.client.rpop('foo'))
312
Miss Islington (bot)0902a2d2018-03-03 21:55:07 -0800313 def test_apop_normal(self):
Mark Dickinsonea1158f2009-08-06 16:06:25 +0000314 self.assertOK(self.client.apop('foo', 'dummypassword'))
315
Miss Islington (bot)0902a2d2018-03-03 21:55:07 -0800316 def test_apop_REDOS(self):
317 # Replace welcome with very long evil welcome.
318 # NB The upper bound on welcome length is currently 2048.
319 # At this length, evil input makes each apop call take
320 # on the order of milliseconds instead of microseconds.
321 evil_welcome = b'+OK' + (b'<' * 1000000)
322 with test_support.swap_attr(self.client, 'welcome', evil_welcome):
323 # The evil welcome is invalid, so apop should throw.
324 self.assertRaises(poplib.error_proto, self.client.apop, 'a', 'kb')
325
Christian Heimesd3956292008-11-05 19:48:27 +0000326 def test_top(self):
327 expected = (b'+OK 116 bytes',
328 [b'From: postmaster@python.org', b'Content-Type: text/plain',
329 b'MIME-Version: 1.0', b'Subject: Dummy', b'',
330 b'line1', b'line2', b'line3'],
331 113)
332 self.assertEqual(self.client.top(1, 1), expected)
333
334 def test_uidl(self):
335 self.client.uidl()
336 self.client.uidl('foo')
337
R David Murrayb8cd3e42015-05-16 15:05:53 -0400338 def test_utf8_raises_if_unsupported(self):
339 self.server.handler.enable_UTF8 = False
340 self.assertRaises(poplib.error_proto, self.client.utf8)
341
342 def test_utf8(self):
343 self.server.handler.enable_UTF8 = True
344 expected = b'+OK I know RFC6856'
345 result = self.client.utf8()
346 self.assertEqual(result, expected)
347
Antoine Pitrou25cee192012-11-23 20:07:39 +0100348 def test_capa(self):
349 capa = self.client.capa()
350 self.assertTrue('IMPLEMENTATION' in capa.keys())
351
Giampaolo Rodolà95bcb932011-02-25 22:28:24 +0000352 def test_quit(self):
353 resp = self.client.quit()
354 self.assertTrue(resp)
355 self.assertIsNone(self.client.sock)
356 self.assertIsNone(self.client.file)
357
Serhiy Storchaka43767632013-11-03 21:31:38 +0200358 @requires_ssl
359 def test_stls_capa(self):
360 capa = self.client.capa()
361 self.assertTrue('STLS' in capa.keys())
Christian Heimesd3956292008-11-05 19:48:27 +0000362
Serhiy Storchaka43767632013-11-03 21:31:38 +0200363 @requires_ssl
364 def test_stls(self):
365 expected = b'+OK Begin TLS negotiation'
366 resp = self.client.stls()
367 self.assertEqual(resp, expected)
Christian Heimesd3956292008-11-05 19:48:27 +0000368
Serhiy Storchaka43767632013-11-03 21:31:38 +0200369 @requires_ssl
370 def test_stls_context(self):
371 expected = b'+OK Begin TLS negotiation'
Christian Heimesa170fa12017-09-15 20:27:30 +0200372 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Miss Islington (bot)2614ed42018-02-27 00:17:49 -0800373 # TODO: fix TLSv1.3 support
374 ctx.options |= ssl.OP_NO_TLSv1_3
Christian Heimes1bc70682013-12-02 20:10:50 +0100375 ctx.load_verify_locations(CAFILE)
Christian Heimesa170fa12017-09-15 20:27:30 +0200376 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
377 self.assertEqual(ctx.check_hostname, True)
Christian Heimes1bc70682013-12-02 20:10:50 +0100378 with self.assertRaises(ssl.CertificateError):
379 resp = self.client.stls(context=ctx)
380 self.client = poplib.POP3("localhost", self.server.port, timeout=3)
Serhiy Storchaka43767632013-11-03 21:31:38 +0200381 resp = self.client.stls(context=ctx)
382 self.assertEqual(resp, expected)
Antoine Pitrou8618d742012-11-23 20:13:48 +0100383
384
385if SUPPORTS_SSL:
Antoine Pitrou3f73e4c2014-04-29 10:27:09 +0200386 from test.test_ftplib import SSLConnection
Christian Heimesd3956292008-11-05 19:48:27 +0000387
Antoine Pitrou3f73e4c2014-04-29 10:27:09 +0200388 class DummyPOP3_SSLHandler(SSLConnection, DummyPOP3Handler):
Christian Heimesd3956292008-11-05 19:48:27 +0000389
390 def __init__(self, conn):
391 asynchat.async_chat.__init__(self, conn)
Antoine Pitrou3f73e4c2014-04-29 10:27:09 +0200392 self.secure_connection()
Christian Heimesd3956292008-11-05 19:48:27 +0000393 self.set_terminator(b"\r\n")
394 self.in_buffer = []
Mark Dickinsonea1158f2009-08-06 16:06:25 +0000395 self.push('+OK dummy pop3 server ready. <timestamp>')
Antoine Pitrou3f73e4c2014-04-29 10:27:09 +0200396 self.tls_active = True
397 self.tls_starting = False
Christian Heimesd3956292008-11-05 19:48:27 +0000398
Giampaolo Rodolà95bcb932011-02-25 22:28:24 +0000399
Serhiy Storchaka43767632013-11-03 21:31:38 +0200400@requires_ssl
401class TestPOP3_SSLClass(TestPOP3Class):
402 # repeat previous tests by using poplib.POP3_SSL
Christian Heimesd3956292008-11-05 19:48:27 +0000403
Serhiy Storchaka43767632013-11-03 21:31:38 +0200404 def setUp(self):
405 self.server = DummyPOP3Server((HOST, PORT))
406 self.server.handler = DummyPOP3_SSLHandler
407 self.server.start()
408 self.client = poplib.POP3_SSL(self.server.host, self.server.port)
Christian Heimesd3956292008-11-05 19:48:27 +0000409
Serhiy Storchaka43767632013-11-03 21:31:38 +0200410 def test__all__(self):
411 self.assertIn('POP3_SSL', poplib.__all__)
Christian Heimesd3956292008-11-05 19:48:27 +0000412
Serhiy Storchaka43767632013-11-03 21:31:38 +0200413 def test_context(self):
Christian Heimesa170fa12017-09-15 20:27:30 +0200414 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Miss Islington (bot)2614ed42018-02-27 00:17:49 -0800415 # TODO: fix TLSv1.3 support
416 ctx.options |= ssl.OP_NO_TLSv1_3
Christian Heimesa170fa12017-09-15 20:27:30 +0200417 ctx.check_hostname = False
418 ctx.verify_mode = ssl.CERT_NONE
Serhiy Storchaka43767632013-11-03 21:31:38 +0200419 self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
420 self.server.port, keyfile=CERTFILE, context=ctx)
421 self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
422 self.server.port, certfile=CERTFILE, context=ctx)
423 self.assertRaises(ValueError, poplib.POP3_SSL, self.server.host,
424 self.server.port, keyfile=CERTFILE,
425 certfile=CERTFILE, context=ctx)
Giampaolo Rodolà42382fe2010-08-17 16:09:53 +0000426
Serhiy Storchaka43767632013-11-03 21:31:38 +0200427 self.client.quit()
428 self.client = poplib.POP3_SSL(self.server.host, self.server.port,
429 context=ctx)
430 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
431 self.assertIs(self.client.sock.context, ctx)
432 self.assertTrue(self.client.noop().startswith(b'+OK'))
Giampaolo Rodolà42382fe2010-08-17 16:09:53 +0000433
Serhiy Storchaka43767632013-11-03 21:31:38 +0200434 def test_stls(self):
435 self.assertRaises(poplib.error_proto, self.client.stls)
Antoine Pitrou8618d742012-11-23 20:13:48 +0100436
Serhiy Storchaka43767632013-11-03 21:31:38 +0200437 test_stls_context = test_stls
Antoine Pitrou8618d742012-11-23 20:13:48 +0100438
Serhiy Storchaka43767632013-11-03 21:31:38 +0200439 def test_stls_capa(self):
440 capa = self.client.capa()
441 self.assertFalse('STLS' in capa.keys())
Antoine Pitrou8618d742012-11-23 20:13:48 +0100442
443
Serhiy Storchaka43767632013-11-03 21:31:38 +0200444@requires_ssl
445class TestPOP3_TLSClass(TestPOP3Class):
446 # repeat previous tests by using poplib.POP3.stls()
Antoine Pitrou8618d742012-11-23 20:13:48 +0100447
Serhiy Storchaka43767632013-11-03 21:31:38 +0200448 def setUp(self):
449 self.server = DummyPOP3Server((HOST, PORT))
450 self.server.start()
451 self.client = poplib.POP3(self.server.host, self.server.port, timeout=3)
452 self.client.stls()
Antoine Pitrou8618d742012-11-23 20:13:48 +0100453
Serhiy Storchaka43767632013-11-03 21:31:38 +0200454 def tearDown(self):
455 if self.client.file is not None and self.client.sock is not None:
456 try:
457 self.client.quit()
458 except poplib.error_proto:
459 # happens in the test_too_long_lines case; the overlong
460 # response will be treated as response to QUIT and raise
461 # this exception
Victor Stinner28dd6de2013-12-09 01:15:10 +0100462 self.client.close()
Serhiy Storchaka43767632013-11-03 21:31:38 +0200463 self.server.stop()
Victor Stinnerd403a292017-09-13 03:58:25 -0700464 # Explicitly clear the attribute to prevent dangling thread
465 self.server = None
Antoine Pitrou8618d742012-11-23 20:13:48 +0100466
Serhiy Storchaka43767632013-11-03 21:31:38 +0200467 def test_stls(self):
468 self.assertRaises(poplib.error_proto, self.client.stls)
Antoine Pitrou8618d742012-11-23 20:13:48 +0100469
Serhiy Storchaka43767632013-11-03 21:31:38 +0200470 test_stls_context = test_stls
Antoine Pitrou8618d742012-11-23 20:13:48 +0100471
Serhiy Storchaka43767632013-11-03 21:31:38 +0200472 def test_stls_capa(self):
473 capa = self.client.capa()
474 self.assertFalse(b'STLS' in capa.keys())
Antoine Pitrou8618d742012-11-23 20:13:48 +0100475
Christian Heimesd3956292008-11-05 19:48:27 +0000476
477class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478
479 def setUp(self):
480 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000481 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Charles-François Natali83ef2542011-12-14 19:28:56 +0100482 self.sock.settimeout(60) # Safety net. Look issue 11812
Christian Heimesd3956292008-11-05 19:48:27 +0000483 self.port = test_support.bind_port(self.sock)
Charles-François Natali83ef2542011-12-14 19:28:56 +0100484 self.thread = threading.Thread(target=self.server, args=(self.evt,self.sock))
485 self.thread.setDaemon(True)
486 self.thread.start()
487 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488
489 def tearDown(self):
Charles-François Natali83ef2542011-12-14 19:28:56 +0100490 self.thread.join()
Victor Stinnerd403a292017-09-13 03:58:25 -0700491 # Explicitly clear the attribute to prevent dangling thread
492 self.thread = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000493
Christian Heimesd3956292008-11-05 19:48:27 +0000494 def server(self, evt, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +0100495 serv.listen()
Charles-François Natali83ef2542011-12-14 19:28:56 +0100496 evt.set()
Christian Heimesd3956292008-11-05 19:48:27 +0000497 try:
498 conn, addr = serv.accept()
Christian Heimesd3956292008-11-05 19:48:27 +0000499 conn.send(b"+ Hola mundo\n")
500 conn.close()
Charles-François Natali83ef2542011-12-14 19:28:56 +0100501 except socket.timeout:
502 pass
Christian Heimesd3956292008-11-05 19:48:27 +0000503 finally:
504 serv.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505
506 def testTimeoutDefault(self):
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200507 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000508 socket.setdefaulttimeout(30)
509 try:
Charles-François Natali83ef2542011-12-14 19:28:56 +0100510 pop = poplib.POP3(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000511 finally:
512 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000513 self.assertEqual(pop.sock.gettimeout(), 30)
Victor Stinnerd165e142017-09-13 05:53:10 -0700514 pop.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000515
516 def testTimeoutNone(self):
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200517 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 socket.setdefaulttimeout(30)
519 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000520 pop = poplib.POP3(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000521 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000522 socket.setdefaulttimeout(None)
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200523 self.assertIsNone(pop.sock.gettimeout())
Victor Stinnerd165e142017-09-13 05:53:10 -0700524 pop.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525
Georg Brandlf78e02b2008-06-10 17:40:04 +0000526 def testTimeoutValue(self):
Charles-François Natali83ef2542011-12-14 19:28:56 +0100527 pop = poplib.POP3(HOST, self.port, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000528 self.assertEqual(pop.sock.gettimeout(), 30)
Victor Stinnerd165e142017-09-13 05:53:10 -0700529 pop.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530
531
Christian Heimesd3956292008-11-05 19:48:27 +0000532def test_main():
Serhiy Storchaka43767632013-11-03 21:31:38 +0200533 tests = [TestPOP3Class, TestTimeouts,
534 TestPOP3_SSLClass, TestPOP3_TLSClass]
Christian Heimesd3956292008-11-05 19:48:27 +0000535 thread_info = test_support.threading_setup()
536 try:
537 test_support.run_unittest(*tests)
538 finally:
539 test_support.threading_cleanup(*thread_info)
540
Guido van Rossumd8faa362007-04-27 19:54:29 +0000541
542if __name__ == '__main__':
543 test_main()