blob: 46861836182cc5f787906bb6f3b2026838316a6d [file] [log] [blame]
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001"""Test script for ftplib module."""
2
Antoine Pitrouf988cd02009-11-17 20:21:14 +00003# Modified by Giampaolo Rodola' to test FTP class, IPv6 and TLS
4# environment
Benjamin Petersonbe17a112008-09-27 21:49:47 +00005
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import ftplib
Benjamin Petersonbe17a112008-09-27 21:49:47 +00007import asyncore
8import asynchat
9import socket
10import io
Antoine Pitrouf988cd02009-11-17 20:21:14 +000011import errno
12import os
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +000013import time
Antoine Pitrouf988cd02009-11-17 20:21:14 +000014try:
15 import ssl
16except ImportError:
17 ssl = None
Guido van Rossumd8faa362007-04-27 19:54:29 +000018
19from unittest import TestCase
Benjamin Petersonee8712c2008-05-20 21:35:26 +000020from test import support
Antoine Pitrou1e440cf2013-08-22 00:39:46 +020021from test.support import HOST, HOSTv6
Victor Stinner45df8202010-04-28 22:31:17 +000022threading = support.import_module('threading')
Guido van Rossumd8faa362007-04-27 19:54:29 +000023
Benjamin Petersonbe17a112008-09-27 21:49:47 +000024# the dummy data returned by server over the data channel when
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020025# RETR, LIST, NLST, MLSD commands are issued
Benjamin Petersonbe17a112008-09-27 21:49:47 +000026RETR_DATA = 'abcde12345\r\n' * 1000
27LIST_DATA = 'foo\r\nbar\r\n'
28NLST_DATA = 'foo\r\nbar\r\n'
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020029MLSD_DATA = ("type=cdir;perm=el;unique==keVO1+ZF4; test\r\n"
30 "type=pdir;perm=e;unique==keVO1+d?3; ..\r\n"
31 "type=OS.unix=slink:/foobar;perm=;unique==keVO1+4G4; foobar\r\n"
32 "type=OS.unix=chr-13/29;perm=;unique==keVO1+5G4; device\r\n"
33 "type=OS.unix=blk-11/108;perm=;unique==keVO1+6G4; block\r\n"
34 "type=file;perm=awr;unique==keVO1+8G4; writable\r\n"
35 "type=dir;perm=cpmel;unique==keVO1+7G4; promiscuous\r\n"
36 "type=dir;perm=;unique==keVO1+1t2; no-exec\r\n"
37 "type=file;perm=r;unique==keVO1+EG4; two words\r\n"
38 "type=file;perm=r;unique==keVO1+IH4; leading space\r\n"
39 "type=file;perm=r;unique==keVO1+1G4; file1\r\n"
40 "type=dir;perm=cpmel;unique==keVO1+7G4; incoming\r\n"
41 "type=file;perm=r;unique==keVO1+1G4; file2\r\n"
42 "type=file;perm=r;unique==keVO1+1G4; file3\r\n"
43 "type=file;perm=r;unique==keVO1+1G4; file4\r\n")
Christian Heimes836baa52008-02-26 08:18:30 +000044
Christian Heimes836baa52008-02-26 08:18:30 +000045
Benjamin Petersonbe17a112008-09-27 21:49:47 +000046class DummyDTPHandler(asynchat.async_chat):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000047 dtp_conn_closed = False
Benjamin Petersonbe17a112008-09-27 21:49:47 +000048
49 def __init__(self, conn, baseclass):
50 asynchat.async_chat.__init__(self, conn)
51 self.baseclass = baseclass
52 self.baseclass.last_received_data = ''
53
54 def handle_read(self):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000055 self.baseclass.last_received_data += self.recv(1024).decode('ascii')
Benjamin Petersonbe17a112008-09-27 21:49:47 +000056
57 def handle_close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000058 # XXX: this method can be called many times in a row for a single
59 # connection, including in clear-text (non-TLS) mode.
60 # (behaviour witnessed with test_data_connection)
61 if not self.dtp_conn_closed:
62 self.baseclass.push('226 transfer complete')
63 self.close()
64 self.dtp_conn_closed = True
Benjamin Petersonbe17a112008-09-27 21:49:47 +000065
66 def push(self, what):
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020067 if self.baseclass.next_data is not None:
68 what = self.baseclass.next_data
69 self.baseclass.next_data = None
70 if not what:
71 return self.close_when_done()
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000072 super(DummyDTPHandler, self).push(what.encode('ascii'))
Benjamin Petersonbe17a112008-09-27 21:49:47 +000073
Giampaolo Rodolàd930b632010-05-06 20:21:57 +000074 def handle_error(self):
75 raise
76
Benjamin Petersonbe17a112008-09-27 21:49:47 +000077
78class DummyFTPHandler(asynchat.async_chat):
79
Antoine Pitrouf988cd02009-11-17 20:21:14 +000080 dtp_handler = DummyDTPHandler
81
Benjamin Petersonbe17a112008-09-27 21:49:47 +000082 def __init__(self, conn):
83 asynchat.async_chat.__init__(self, conn)
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +020084 # tells the socket to handle urgent data inline (ABOR command)
85 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
Benjamin Petersonbe17a112008-09-27 21:49:47 +000086 self.set_terminator(b"\r\n")
87 self.in_buffer = []
88 self.dtp = None
89 self.last_received_cmd = None
90 self.last_received_data = ''
91 self.next_response = ''
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020092 self.next_data = None
Antoine Pitrou648bcd72009-11-27 13:23:26 +000093 self.rest = None
Serhiy Storchakac30b1782013-10-20 16:58:27 +030094 self.next_retr_data = RETR_DATA
Benjamin Petersonbe17a112008-09-27 21:49:47 +000095 self.push('220 welcome')
96
97 def collect_incoming_data(self, data):
98 self.in_buffer.append(data)
99
100 def found_terminator(self):
101 line = b''.join(self.in_buffer).decode('ascii')
102 self.in_buffer = []
103 if self.next_response:
104 self.push(self.next_response)
105 self.next_response = ''
106 cmd = line.split(' ')[0].lower()
107 self.last_received_cmd = cmd
108 space = line.find(' ')
109 if space != -1:
110 arg = line[space + 1:]
111 else:
112 arg = ""
113 if hasattr(self, 'cmd_' + cmd):
114 method = getattr(self, 'cmd_' + cmd)
115 method(arg)
116 else:
117 self.push('550 command "%s" not understood.' %cmd)
118
119 def handle_error(self):
120 raise
121
122 def push(self, data):
123 asynchat.async_chat.push(self, data.encode('ascii') + b'\r\n')
124
125 def cmd_port(self, arg):
126 addr = list(map(int, arg.split(',')))
127 ip = '%d.%d.%d.%d' %tuple(addr[:4])
128 port = (addr[4] * 256) + addr[5]
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200129 s = socket.create_connection((ip, port), timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000130 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000131 self.push('200 active data connection established')
132
133 def cmd_pasv(self, arg):
Brett Cannon918e2d42010-10-29 23:26:25 +0000134 with socket.socket() as sock:
135 sock.bind((self.socket.getsockname()[0], 0))
136 sock.listen(5)
137 sock.settimeout(10)
138 ip, port = sock.getsockname()[:2]
139 ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
140 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
141 conn, addr = sock.accept()
142 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000143
144 def cmd_eprt(self, arg):
145 af, ip, port = arg.split(arg[0])[1:-1]
146 port = int(port)
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200147 s = socket.create_connection((ip, port), timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000148 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000149 self.push('200 active data connection established')
150
151 def cmd_epsv(self, arg):
Brett Cannon918e2d42010-10-29 23:26:25 +0000152 with socket.socket(socket.AF_INET6) as sock:
153 sock.bind((self.socket.getsockname()[0], 0))
154 sock.listen(5)
155 sock.settimeout(10)
156 port = sock.getsockname()[1]
157 self.push('229 entering extended passive mode (|||%d|)' %port)
158 conn, addr = sock.accept()
159 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000160
161 def cmd_echo(self, arg):
162 # sends back the received string (used by the test suite)
163 self.push(arg)
164
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000165 def cmd_noop(self, arg):
166 self.push('200 noop ok')
167
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000168 def cmd_user(self, arg):
169 self.push('331 username ok')
170
171 def cmd_pass(self, arg):
172 self.push('230 password ok')
173
174 def cmd_acct(self, arg):
175 self.push('230 acct ok')
176
177 def cmd_rnfr(self, arg):
178 self.push('350 rnfr ok')
179
180 def cmd_rnto(self, arg):
181 self.push('250 rnto ok')
182
183 def cmd_dele(self, arg):
184 self.push('250 dele ok')
185
186 def cmd_cwd(self, arg):
187 self.push('250 cwd ok')
188
189 def cmd_size(self, arg):
190 self.push('250 1000')
191
192 def cmd_mkd(self, arg):
193 self.push('257 "%s"' %arg)
194
195 def cmd_rmd(self, arg):
196 self.push('250 rmd ok')
197
198 def cmd_pwd(self, arg):
199 self.push('257 "pwd ok"')
200
201 def cmd_type(self, arg):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000202 self.push('200 type ok')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000203
204 def cmd_quit(self, arg):
205 self.push('221 quit ok')
206 self.close()
207
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200208 def cmd_abor(self, arg):
209 self.push('226 abor ok')
210
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000211 def cmd_stor(self, arg):
212 self.push('125 stor ok')
213
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000214 def cmd_rest(self, arg):
215 self.rest = arg
216 self.push('350 rest ok')
217
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000218 def cmd_retr(self, arg):
219 self.push('125 retr ok')
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000220 if self.rest is not None:
221 offset = int(self.rest)
222 else:
223 offset = 0
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300224 self.dtp.push(self.next_retr_data[offset:])
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000225 self.dtp.close_when_done()
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000226 self.rest = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000227
228 def cmd_list(self, arg):
229 self.push('125 list ok')
230 self.dtp.push(LIST_DATA)
231 self.dtp.close_when_done()
232
233 def cmd_nlst(self, arg):
234 self.push('125 nlst ok')
235 self.dtp.push(NLST_DATA)
236 self.dtp.close_when_done()
237
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200238 def cmd_opts(self, arg):
239 self.push('200 opts ok')
240
241 def cmd_mlsd(self, arg):
242 self.push('125 mlsd ok')
243 self.dtp.push(MLSD_DATA)
244 self.dtp.close_when_done()
245
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300246 def cmd_setlongretr(self, arg):
247 # For testing. Next RETR will return long line.
248 self.next_retr_data = 'x' * int(arg)
249 self.push('125 setlongretr ok')
250
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000251
252class DummyFTPServer(asyncore.dispatcher, threading.Thread):
253
254 handler = DummyFTPHandler
255
256 def __init__(self, address, af=socket.AF_INET):
257 threading.Thread.__init__(self)
258 asyncore.dispatcher.__init__(self)
259 self.create_socket(af, socket.SOCK_STREAM)
260 self.bind(address)
261 self.listen(5)
262 self.active = False
263 self.active_lock = threading.Lock()
264 self.host, self.port = self.socket.getsockname()[:2]
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000265 self.handler_instance = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000266
267 def start(self):
268 assert not self.active
269 self.__flag = threading.Event()
270 threading.Thread.start(self)
271 self.__flag.wait()
272
273 def run(self):
274 self.active = True
275 self.__flag.set()
276 while self.active and asyncore.socket_map:
277 self.active_lock.acquire()
278 asyncore.loop(timeout=0.1, count=1)
279 self.active_lock.release()
280 asyncore.close_all(ignore_all=True)
281
282 def stop(self):
283 assert self.active
284 self.active = False
285 self.join()
286
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000287 def handle_accepted(self, conn, addr):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000288 self.handler_instance = self.handler(conn)
Benjamin Petersond06e3b02008-09-28 21:00:42 +0000289
290 def handle_connect(self):
291 self.close()
292 handle_read = handle_connect
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000293
294 def writable(self):
295 return 0
296
297 def handle_error(self):
298 raise
299
300
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000301if ssl is not None:
302
303 CERTFILE = os.path.join(os.path.dirname(__file__), "keycert.pem")
304
305 class SSLConnection(asyncore.dispatcher):
306 """An asyncore.dispatcher subclass supporting TLS/SSL."""
307
308 _ssl_accepting = False
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000309 _ssl_closing = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000310
311 def secure_connection(self):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000312 socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
313 certfile=CERTFILE, server_side=True,
314 do_handshake_on_connect=False,
315 ssl_version=ssl.PROTOCOL_SSLv23)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200316 self.del_channel()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000317 self.set_socket(socket)
318 self._ssl_accepting = True
319
320 def _do_ssl_handshake(self):
321 try:
322 self.socket.do_handshake()
323 except ssl.SSLError as err:
324 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
325 ssl.SSL_ERROR_WANT_WRITE):
326 return
327 elif err.args[0] == ssl.SSL_ERROR_EOF:
328 return self.handle_close()
329 raise
330 except socket.error as err:
331 if err.args[0] == errno.ECONNABORTED:
332 return self.handle_close()
333 else:
334 self._ssl_accepting = False
335
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000336 def _do_ssl_shutdown(self):
337 self._ssl_closing = True
338 try:
339 self.socket = self.socket.unwrap()
340 except ssl.SSLError as err:
341 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
342 ssl.SSL_ERROR_WANT_WRITE):
343 return
344 except socket.error as err:
345 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
346 # from OpenSSL's SSL_shutdown(), corresponding to a
347 # closed socket condition. See also:
348 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
349 pass
350 self._ssl_closing = False
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400351 if getattr(self, '_ccc', False) is False:
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200352 super(SSLConnection, self).close()
353 else:
354 pass
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000355
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000356 def handle_read_event(self):
357 if self._ssl_accepting:
358 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000359 elif self._ssl_closing:
360 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000361 else:
362 super(SSLConnection, self).handle_read_event()
363
364 def handle_write_event(self):
365 if self._ssl_accepting:
366 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000367 elif self._ssl_closing:
368 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000369 else:
370 super(SSLConnection, self).handle_write_event()
371
372 def send(self, data):
373 try:
374 return super(SSLConnection, self).send(data)
375 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000376 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
377 ssl.SSL_ERROR_WANT_READ,
378 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000379 return 0
380 raise
381
382 def recv(self, buffer_size):
383 try:
384 return super(SSLConnection, self).recv(buffer_size)
385 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000386 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
387 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000388 return b''
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000389 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
390 self.handle_close()
391 return b''
392 raise
393
394 def handle_error(self):
395 raise
396
397 def close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000398 if (isinstance(self.socket, ssl.SSLSocket) and
399 self.socket._sslobj is not None):
400 self._do_ssl_shutdown()
Benjamin Peterson1bd93a72010-10-31 19:58:07 +0000401 else:
402 super(SSLConnection, self).close()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000403
404
405 class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
406 """A DummyDTPHandler subclass supporting TLS/SSL."""
407
408 def __init__(self, conn, baseclass):
409 DummyDTPHandler.__init__(self, conn, baseclass)
410 if self.baseclass.secure_data_channel:
411 self.secure_connection()
412
413
414 class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
415 """A DummyFTPHandler subclass supporting TLS/SSL."""
416
417 dtp_handler = DummyTLS_DTPHandler
418
419 def __init__(self, conn):
420 DummyFTPHandler.__init__(self, conn)
421 self.secure_data_channel = False
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200422 self._ccc = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000423
424 def cmd_auth(self, line):
425 """Set up secure control channel."""
426 self.push('234 AUTH TLS successful')
427 self.secure_connection()
428
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200429 def cmd_ccc(self, line):
430 self.push('220 Reverting back to clear-text')
431 self._ccc = True
432 self._do_ssl_shutdown()
433
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000434 def cmd_pbsz(self, line):
435 """Negotiate size of buffer for secure data transfer.
436 For TLS/SSL the only valid value for the parameter is '0'.
437 Any other value is accepted but ignored.
438 """
439 self.push('200 PBSZ=0 successful.')
440
441 def cmd_prot(self, line):
442 """Setup un/secure data channel."""
443 arg = line.upper()
444 if arg == 'C':
445 self.push('200 Protection set to Clear')
446 self.secure_data_channel = False
447 elif arg == 'P':
448 self.push('200 Protection set to Private')
449 self.secure_data_channel = True
450 else:
451 self.push("502 Unrecognized PROT type (use C or P).")
452
453
454 class DummyTLS_FTPServer(DummyFTPServer):
455 handler = DummyTLS_FTPHandler
456
457
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000458class TestFTPClass(TestCase):
459
460 def setUp(self):
461 self.server = DummyFTPServer((HOST, 0))
462 self.server.start()
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200463 self.client = ftplib.FTP(timeout=2)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000464 self.client.connect(self.server.host, self.server.port)
465
466 def tearDown(self):
467 self.client.close()
468 self.server.stop()
469
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100470 def check_data(self, received, expected):
471 self.assertEqual(len(received), len(expected))
472 self.assertEqual(received, expected)
473
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000474 def test_getwelcome(self):
475 self.assertEqual(self.client.getwelcome(), '220 welcome')
476
477 def test_sanitize(self):
478 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
479 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
480 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
481
482 def test_exceptions(self):
483 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
484 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
485 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
486 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
487 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
488
489 def test_all_errors(self):
490 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
491 ftplib.error_proto, ftplib.Error, IOError, EOFError)
492 for x in exceptions:
493 try:
494 raise x('exception not included in all_errors set')
495 except ftplib.all_errors:
496 pass
497
498 def test_set_pasv(self):
499 # passive mode is supposed to be enabled by default
500 self.assertTrue(self.client.passiveserver)
501 self.client.set_pasv(True)
502 self.assertTrue(self.client.passiveserver)
503 self.client.set_pasv(False)
504 self.assertFalse(self.client.passiveserver)
505
506 def test_voidcmd(self):
507 self.client.voidcmd('echo 200')
508 self.client.voidcmd('echo 299')
509 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
510 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
511
512 def test_login(self):
513 self.client.login()
514
515 def test_acct(self):
516 self.client.acct('passwd')
517
518 def test_rename(self):
519 self.client.rename('a', 'b')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000520 self.server.handler_instance.next_response = '200'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000521 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
522
523 def test_delete(self):
524 self.client.delete('foo')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000525 self.server.handler_instance.next_response = '199'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000526 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
527
528 def test_size(self):
529 self.client.size('foo')
530
531 def test_mkd(self):
532 dir = self.client.mkd('/foo')
533 self.assertEqual(dir, '/foo')
534
535 def test_rmd(self):
536 self.client.rmd('foo')
537
Senthil Kumaran0d538602013-08-12 22:25:27 -0700538 def test_cwd(self):
539 dir = self.client.cwd('/foo')
540 self.assertEqual(dir, '250 cwd ok')
541
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000542 def test_pwd(self):
543 dir = self.client.pwd()
544 self.assertEqual(dir, 'pwd ok')
545
546 def test_quit(self):
547 self.assertEqual(self.client.quit(), '221 quit ok')
548 # Ensure the connection gets closed; sock attribute should be None
549 self.assertEqual(self.client.sock, None)
550
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200551 def test_abort(self):
552 self.client.abort()
553
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000554 def test_retrbinary(self):
555 def callback(data):
556 received.append(data.decode('ascii'))
557 received = []
558 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100559 self.check_data(''.join(received), RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000560
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000561 def test_retrbinary_rest(self):
562 def callback(data):
563 received.append(data.decode('ascii'))
564 for rest in (0, 10, 20):
565 received = []
566 self.client.retrbinary('retr', callback, rest=rest)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100567 self.check_data(''.join(received), RETR_DATA[rest:])
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000568
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000569 def test_retrlines(self):
570 received = []
571 self.client.retrlines('retr', received.append)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100572 self.check_data(''.join(received), RETR_DATA.replace('\r\n', ''))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000573
574 def test_storbinary(self):
575 f = io.BytesIO(RETR_DATA.encode('ascii'))
576 self.client.storbinary('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100577 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000578 # test new callback arg
579 flag = []
580 f.seek(0)
581 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
582 self.assertTrue(flag)
583
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000584 def test_storbinary_rest(self):
585 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
586 for r in (30, '30'):
587 f.seek(0)
588 self.client.storbinary('stor', f, rest=r)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000589 self.assertEqual(self.server.handler_instance.rest, str(r))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000590
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000591 def test_storlines(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000592 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
593 self.client.storlines('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100594 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000595 # test new callback arg
596 flag = []
597 f.seek(0)
598 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
599 self.assertTrue(flag)
600
Victor Stinnered3a3032013-04-02 22:13:27 +0200601 f = io.StringIO(RETR_DATA.replace('\r\n', '\n'))
602 # storlines() expects a binary file, not a text file
Florent Xicluna5f3fef32013-07-06 15:08:21 +0200603 with support.check_warnings(('', BytesWarning), quiet=True):
604 self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)
Victor Stinnered3a3032013-04-02 22:13:27 +0200605
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000606 def test_nlst(self):
607 self.client.nlst()
608 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
609
610 def test_dir(self):
611 l = []
612 self.client.dir(lambda x: l.append(x))
613 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
614
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200615 def test_mlsd(self):
616 list(self.client.mlsd())
617 list(self.client.mlsd(path='/'))
618 list(self.client.mlsd(path='/', facts=['size', 'type']))
619
620 ls = list(self.client.mlsd())
621 for name, facts in ls:
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200622 self.assertIsInstance(name, str)
623 self.assertIsInstance(facts, dict)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200624 self.assertTrue(name)
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200625 self.assertIn('type', facts)
626 self.assertIn('perm', facts)
627 self.assertIn('unique', facts)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200628
629 def set_data(data):
630 self.server.handler_instance.next_data = data
631
632 def test_entry(line, type=None, perm=None, unique=None, name=None):
633 type = 'type' if type is None else type
634 perm = 'perm' if perm is None else perm
635 unique = 'unique' if unique is None else unique
636 name = 'name' if name is None else name
637 set_data(line)
638 _name, facts = next(self.client.mlsd())
639 self.assertEqual(_name, name)
640 self.assertEqual(facts['type'], type)
641 self.assertEqual(facts['perm'], perm)
642 self.assertEqual(facts['unique'], unique)
643
644 # plain
645 test_entry('type=type;perm=perm;unique=unique; name\r\n')
646 # "=" in fact value
647 test_entry('type=ty=pe;perm=perm;unique=unique; name\r\n', type="ty=pe")
648 test_entry('type==type;perm=perm;unique=unique; name\r\n', type="=type")
649 test_entry('type=t=y=pe;perm=perm;unique=unique; name\r\n', type="t=y=pe")
650 test_entry('type=====;perm=perm;unique=unique; name\r\n', type="====")
651 # spaces in name
652 test_entry('type=type;perm=perm;unique=unique; na me\r\n', name="na me")
653 test_entry('type=type;perm=perm;unique=unique; name \r\n', name="name ")
654 test_entry('type=type;perm=perm;unique=unique; name\r\n', name=" name")
655 test_entry('type=type;perm=perm;unique=unique; n am e\r\n', name="n am e")
656 # ";" in name
657 test_entry('type=type;perm=perm;unique=unique; na;me\r\n', name="na;me")
658 test_entry('type=type;perm=perm;unique=unique; ;name\r\n', name=";name")
659 test_entry('type=type;perm=perm;unique=unique; ;name;\r\n', name=";name;")
660 test_entry('type=type;perm=perm;unique=unique; ;;;;\r\n', name=";;;;")
661 # case sensitiveness
662 set_data('Type=type;TyPe=perm;UNIQUE=unique; name\r\n')
663 _name, facts = next(self.client.mlsd())
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200664 for x in facts:
665 self.assertTrue(x.islower())
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200666 # no data (directory empty)
667 set_data('')
668 self.assertRaises(StopIteration, next, self.client.mlsd())
669 set_data('')
670 for x in self.client.mlsd():
671 self.fail("unexpected data %s" % data)
672
Benjamin Peterson3a53fbb2008-09-27 22:04:16 +0000673 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000674 with self.client.makeport():
675 # IPv4 is in use, just make sure send_eprt has not been used
676 self.assertEqual(self.server.handler_instance.last_received_cmd,
677 'port')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000678
679 def test_makepasv(self):
680 host, port = self.client.makepasv()
Antoine Pitroud778e562010-10-14 20:35:26 +0000681 conn = socket.create_connection((host, port), 10)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000682 conn.close()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000683 # IPv4 is in use, just make sure send_epsv has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000684 self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
685
686 def test_with_statement(self):
687 self.client.quit()
688
689 def is_client_connected():
690 if self.client.sock is None:
691 return False
692 try:
693 self.client.sendcmd('noop')
694 except (socket.error, EOFError):
695 return False
696 return True
697
698 # base test
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200699 with ftplib.FTP(timeout=2) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000700 self.client.connect(self.server.host, self.server.port)
701 self.client.sendcmd('noop')
702 self.assertTrue(is_client_connected())
703 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
704 self.assertFalse(is_client_connected())
705
706 # QUIT sent inside the with block
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200707 with ftplib.FTP(timeout=2) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000708 self.client.connect(self.server.host, self.server.port)
709 self.client.sendcmd('noop')
710 self.client.quit()
711 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
712 self.assertFalse(is_client_connected())
713
714 # force a wrong response code to be sent on QUIT: error_perm
715 # is expected and the connection is supposed to be closed
716 try:
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200717 with ftplib.FTP(timeout=2) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000718 self.client.connect(self.server.host, self.server.port)
719 self.client.sendcmd('noop')
720 self.server.handler_instance.next_response = '550 error on quit'
721 except ftplib.error_perm as err:
722 self.assertEqual(str(err), '550 error on quit')
723 else:
724 self.fail('Exception not raised')
725 # needed to give the threaded server some time to set the attribute
726 # which otherwise would still be == 'noop'
727 time.sleep(0.1)
728 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
729 self.assertFalse(is_client_connected())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000730
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000731 def test_source_address(self):
732 self.client.quit()
733 port = support.find_unused_port()
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200734 try:
735 self.client.connect(self.server.host, self.server.port,
736 source_address=(HOST, port))
737 self.assertEqual(self.client.sock.getsockname()[1], port)
738 self.client.quit()
739 except IOError as e:
740 if e.errno == errno.EADDRINUSE:
741 self.skipTest("couldn't bind to port %d" % port)
742 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000743
744 def test_source_address_passive_connection(self):
745 port = support.find_unused_port()
746 self.client.source_address = (HOST, port)
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200747 try:
748 with self.client.transfercmd('list') as sock:
749 self.assertEqual(sock.getsockname()[1], port)
750 except IOError as e:
751 if e.errno == errno.EADDRINUSE:
752 self.skipTest("couldn't bind to port %d" % port)
753 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000754
Giampaolo Rodolàbbc47822010-08-23 22:10:32 +0000755 def test_parse257(self):
756 self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
757 self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
758 self.assertEqual(ftplib.parse257('257 ""'), '')
759 self.assertEqual(ftplib.parse257('257 "" created'), '')
760 self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
761 # The 257 response is supposed to include the directory
762 # name and in case it contains embedded double-quotes
763 # they must be doubled (see RFC-959, chapter 7, appendix 2).
764 self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
765 self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
766
Serhiy Storchakac30b1782013-10-20 16:58:27 +0300767 def test_line_too_long(self):
768 self.assertRaises(ftplib.Error, self.client.sendcmd,
769 'x' * self.client.maxline * 2)
770
771 def test_retrlines_too_long(self):
772 self.client.sendcmd('SETLONGRETR %d' % (self.client.maxline * 2))
773 received = []
774 self.assertRaises(ftplib.Error,
775 self.client.retrlines, 'retr', received.append)
776
777 def test_storlines_too_long(self):
778 f = io.BytesIO(b'x' * self.client.maxline * 2)
779 self.assertRaises(ftplib.Error, self.client.storlines, 'stor', f)
780
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000781
782class TestIPv6Environment(TestCase):
783
784 def setUp(self):
Antoine Pitrou1e440cf2013-08-22 00:39:46 +0200785 self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000786 self.server.start()
787 self.client = ftplib.FTP()
788 self.client.connect(self.server.host, self.server.port)
789
790 def tearDown(self):
791 self.client.close()
792 self.server.stop()
793
794 def test_af(self):
795 self.assertEqual(self.client.af, socket.AF_INET6)
796
797 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000798 with self.client.makeport():
799 self.assertEqual(self.server.handler_instance.last_received_cmd,
800 'eprt')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000801
802 def test_makepasv(self):
803 host, port = self.client.makepasv()
Antoine Pitroud778e562010-10-14 20:35:26 +0000804 conn = socket.create_connection((host, port), 10)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000805 conn.close()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000806 self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000807
808 def test_transfer(self):
809 def retr():
810 def callback(data):
811 received.append(data.decode('ascii'))
812 received = []
813 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100814 self.assertEqual(len(''.join(received)), len(RETR_DATA))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000815 self.assertEqual(''.join(received), RETR_DATA)
816 self.client.set_pasv(True)
817 retr()
818 self.client.set_pasv(False)
819 retr()
820
821
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000822class TestTLS_FTPClassMixin(TestFTPClass):
823 """Repeat TestFTPClass tests starting the TLS layer for both control
824 and data connections first.
825 """
826
827 def setUp(self):
828 self.server = DummyTLS_FTPServer((HOST, 0))
829 self.server.start()
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200830 self.client = ftplib.FTP_TLS(timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000831 self.client.connect(self.server.host, self.server.port)
832 # enable TLS
833 self.client.auth()
834 self.client.prot_p()
835
836
837class TestTLS_FTPClass(TestCase):
838 """Specific TLS_FTP class tests."""
839
840 def setUp(self):
841 self.server = DummyTLS_FTPServer((HOST, 0))
842 self.server.start()
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200843 self.client = ftplib.FTP_TLS(timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000844 self.client.connect(self.server.host, self.server.port)
845
846 def tearDown(self):
847 self.client.close()
848 self.server.stop()
849
850 def test_control_connection(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000851 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000852 self.client.auth()
Ezio Melottie9615932010-01-24 19:26:24 +0000853 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000854
855 def test_data_connection(self):
856 # clear text
Brett Cannon918e2d42010-10-29 23:26:25 +0000857 with self.client.transfercmd('list') as sock:
858 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000859 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000860
861 # secured, after PROT P
862 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000863 with self.client.transfercmd('list') as sock:
864 self.assertIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000865 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000866
867 # PROT C is issued, the connection must be in cleartext again
868 self.client.prot_c()
Brett Cannon918e2d42010-10-29 23:26:25 +0000869 with self.client.transfercmd('list') as sock:
870 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000871 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000872
873 def test_login(self):
874 # login() is supposed to implicitly secure the control connection
Ezio Melottie9615932010-01-24 19:26:24 +0000875 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000876 self.client.login()
Ezio Melottie9615932010-01-24 19:26:24 +0000877 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000878 # make sure that AUTH TLS doesn't get issued again
879 self.client.login()
880
881 def test_auth_issued_twice(self):
882 self.client.auth()
883 self.assertRaises(ValueError, self.client.auth)
884
885 def test_auth_ssl(self):
886 try:
887 self.client.ssl_version = ssl.PROTOCOL_SSLv3
888 self.client.auth()
889 self.assertRaises(ValueError, self.client.auth)
890 finally:
891 self.client.ssl_version = ssl.PROTOCOL_TLSv1
892
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000893 def test_context(self):
894 self.client.quit()
895 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
896 self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
897 context=ctx)
898 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
899 context=ctx)
900 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
901 keyfile=CERTFILE, context=ctx)
902
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200903 self.client = ftplib.FTP_TLS(context=ctx, timeout=2)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000904 self.client.connect(self.server.host, self.server.port)
905 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
906 self.client.auth()
907 self.assertIs(self.client.sock.context, ctx)
908 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
909
910 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000911 with self.client.transfercmd('list') as sock:
912 self.assertIs(sock.context, ctx)
913 self.assertIsInstance(sock, ssl.SSLSocket)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000914
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200915 def test_ccc(self):
916 self.assertRaises(ValueError, self.client.ccc)
917 self.client.login(secure=True)
918 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
919 self.client.ccc()
920 self.assertRaises(ValueError, self.client.sock.unwrap)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200921
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000922
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000923class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000924
925 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000926 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000927 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100928 self.sock.settimeout(20)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000929 self.port = support.bind_port(self.sock)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100930 self.server_thread = threading.Thread(target=self.server)
931 self.server_thread.start()
Christian Heimes836baa52008-02-26 08:18:30 +0000932 # Wait for the server to be ready.
933 self.evt.wait()
934 self.evt.clear()
Antoine Pitrou08d02722012-12-19 20:44:02 +0100935 self.old_port = ftplib.FTP.port
Christian Heimes5e696852008-04-09 08:37:03 +0000936 ftplib.FTP.port = self.port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937
938 def tearDown(self):
Antoine Pitrou08d02722012-12-19 20:44:02 +0100939 ftplib.FTP.port = self.old_port
940 self.server_thread.join()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941
Antoine Pitrou08d02722012-12-19 20:44:02 +0100942 def server(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000943 # This method sets the evt 3 times:
944 # 1) when the connection is ready to be accepted.
945 # 2) when it is safe for the caller to close the connection
946 # 3) when we have closed the socket
Antoine Pitrou08d02722012-12-19 20:44:02 +0100947 self.sock.listen(5)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000948 # (1) Signal the caller that we are ready to accept the connection.
Antoine Pitrou08d02722012-12-19 20:44:02 +0100949 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000950 try:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100951 conn, addr = self.sock.accept()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000952 except socket.timeout:
953 pass
954 else:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100955 conn.sendall(b"1 Hola mundo\n")
956 conn.shutdown(socket.SHUT_WR)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000957 # (2) Signal the caller that it is safe to close the socket.
Antoine Pitrou08d02722012-12-19 20:44:02 +0100958 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000959 conn.close()
960 finally:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100961 self.sock.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000962
963 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000964 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000965 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000966 socket.setdefaulttimeout(30)
967 try:
Antoine Pitrou1e440cf2013-08-22 00:39:46 +0200968 ftp = ftplib.FTP(HOST)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000969 finally:
970 socket.setdefaulttimeout(None)
971 self.assertEqual(ftp.sock.gettimeout(), 30)
972 self.evt.wait()
973 ftp.close()
974
975 def testTimeoutNone(self):
976 # no timeout -- do not use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000977 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000978 socket.setdefaulttimeout(30)
979 try:
Antoine Pitrou1e440cf2013-08-22 00:39:46 +0200980 ftp = ftplib.FTP(HOST, timeout=None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000981 finally:
982 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 self.assertTrue(ftp.sock.gettimeout() is None)
Christian Heimes836baa52008-02-26 08:18:30 +0000984 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000985 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000986
987 def testTimeoutValue(self):
988 # a value
Christian Heimes5e696852008-04-09 08:37:03 +0000989 ftp = ftplib.FTP(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000991 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000992 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000993
994 def testTimeoutConnect(self):
995 ftp = ftplib.FTP()
Christian Heimes5e696852008-04-09 08:37:03 +0000996 ftp.connect(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000997 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000998 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000999 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001000
1001 def testTimeoutDifferentOrder(self):
1002 ftp = ftplib.FTP(timeout=30)
Christian Heimes5e696852008-04-09 08:37:03 +00001003 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001004 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001005 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +00001006 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001007
1008 def testTimeoutDirectAccess(self):
1009 ftp = ftplib.FTP()
1010 ftp.timeout = 30
Christian Heimes5e696852008-04-09 08:37:03 +00001011 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001012 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +00001013 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014 ftp.close()
1015
1016
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001017def test_main():
1018 tests = [TestFTPClass, TestTimeouts]
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +02001019 if support.IPV6_ENABLED:
Victor Stinnerc90e19d2011-05-01 01:23:03 +02001020 tests.append(TestIPv6Environment)
Antoine Pitrouf988cd02009-11-17 20:21:14 +00001021
1022 if ssl is not None:
1023 tests.extend([TestTLS_FTPClassMixin, TestTLS_FTPClass])
1024
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001025 thread_info = support.threading_setup()
1026 try:
1027 support.run_unittest(*tests)
1028 finally:
1029 support.threading_cleanup(*thread_info)
1030
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031
1032if __name__ == '__main__':
1033 test_main()