blob: 47563c806a9bcd8f8044f91c8f8af173a0d8195b [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 Pitrouf6fbf562013-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
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +020024TIMEOUT = 3
Benjamin Petersonbe17a112008-09-27 21:49:47 +000025# the dummy data returned by server over the data channel when
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020026# RETR, LIST, NLST, MLSD commands are issued
Benjamin Petersonbe17a112008-09-27 21:49:47 +000027RETR_DATA = 'abcde12345\r\n' * 1000
28LIST_DATA = 'foo\r\nbar\r\n'
29NLST_DATA = 'foo\r\nbar\r\n'
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020030MLSD_DATA = ("type=cdir;perm=el;unique==keVO1+ZF4; test\r\n"
31 "type=pdir;perm=e;unique==keVO1+d?3; ..\r\n"
32 "type=OS.unix=slink:/foobar;perm=;unique==keVO1+4G4; foobar\r\n"
33 "type=OS.unix=chr-13/29;perm=;unique==keVO1+5G4; device\r\n"
34 "type=OS.unix=blk-11/108;perm=;unique==keVO1+6G4; block\r\n"
35 "type=file;perm=awr;unique==keVO1+8G4; writable\r\n"
36 "type=dir;perm=cpmel;unique==keVO1+7G4; promiscuous\r\n"
37 "type=dir;perm=;unique==keVO1+1t2; no-exec\r\n"
38 "type=file;perm=r;unique==keVO1+EG4; two words\r\n"
39 "type=file;perm=r;unique==keVO1+IH4; leading space\r\n"
40 "type=file;perm=r;unique==keVO1+1G4; file1\r\n"
41 "type=dir;perm=cpmel;unique==keVO1+7G4; incoming\r\n"
42 "type=file;perm=r;unique==keVO1+1G4; file2\r\n"
43 "type=file;perm=r;unique==keVO1+1G4; file3\r\n"
44 "type=file;perm=r;unique==keVO1+1G4; file4\r\n")
Christian Heimes836baa52008-02-26 08:18:30 +000045
Christian Heimes836baa52008-02-26 08:18:30 +000046
Benjamin Petersonbe17a112008-09-27 21:49:47 +000047class DummyDTPHandler(asynchat.async_chat):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000048 dtp_conn_closed = False
Benjamin Petersonbe17a112008-09-27 21:49:47 +000049
50 def __init__(self, conn, baseclass):
51 asynchat.async_chat.__init__(self, conn)
52 self.baseclass = baseclass
53 self.baseclass.last_received_data = ''
54
55 def handle_read(self):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000056 self.baseclass.last_received_data += self.recv(1024).decode('ascii')
Benjamin Petersonbe17a112008-09-27 21:49:47 +000057
58 def handle_close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000059 # XXX: this method can be called many times in a row for a single
60 # connection, including in clear-text (non-TLS) mode.
61 # (behaviour witnessed with test_data_connection)
62 if not self.dtp_conn_closed:
63 self.baseclass.push('226 transfer complete')
64 self.close()
65 self.dtp_conn_closed = True
Benjamin Petersonbe17a112008-09-27 21:49:47 +000066
67 def push(self, what):
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020068 if self.baseclass.next_data is not None:
69 what = self.baseclass.next_data
70 self.baseclass.next_data = None
71 if not what:
72 return self.close_when_done()
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +000073 super(DummyDTPHandler, self).push(what.encode('ascii'))
Benjamin Petersonbe17a112008-09-27 21:49:47 +000074
Giampaolo Rodolàd930b632010-05-06 20:21:57 +000075 def handle_error(self):
76 raise
77
Benjamin Petersonbe17a112008-09-27 21:49:47 +000078
79class DummyFTPHandler(asynchat.async_chat):
80
Antoine Pitrouf988cd02009-11-17 20:21:14 +000081 dtp_handler = DummyDTPHandler
82
Benjamin Petersonbe17a112008-09-27 21:49:47 +000083 def __init__(self, conn):
84 asynchat.async_chat.__init__(self, conn)
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +020085 # tells the socket to handle urgent data inline (ABOR command)
86 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
Benjamin Petersonbe17a112008-09-27 21:49:47 +000087 self.set_terminator(b"\r\n")
88 self.in_buffer = []
89 self.dtp = None
90 self.last_received_cmd = None
91 self.last_received_data = ''
92 self.next_response = ''
Giampaolo Rodola'd78def92011-05-06 19:49:08 +020093 self.next_data = None
Antoine Pitrou648bcd72009-11-27 13:23:26 +000094 self.rest = None
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'0d4f08c2013-05-16 15:12:01 +0200129 s = socket.create_connection((ip, port), timeout=TIMEOUT)
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)
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200137 sock.settimeout(TIMEOUT)
Brett Cannon918e2d42010-10-29 23:26:25 +0000138 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'0d4f08c2013-05-16 15:12:01 +0200147 s = socket.create_connection((ip, port), timeout=TIMEOUT)
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)
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200155 sock.settimeout(TIMEOUT)
Brett Cannon918e2d42010-10-29 23:26:25 +0000156 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
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000224 self.dtp.push(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
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000246
247class DummyFTPServer(asyncore.dispatcher, threading.Thread):
248
249 handler = DummyFTPHandler
250
251 def __init__(self, address, af=socket.AF_INET):
252 threading.Thread.__init__(self)
253 asyncore.dispatcher.__init__(self)
254 self.create_socket(af, socket.SOCK_STREAM)
255 self.bind(address)
256 self.listen(5)
257 self.active = False
258 self.active_lock = threading.Lock()
259 self.host, self.port = self.socket.getsockname()[:2]
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000260 self.handler_instance = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000261
262 def start(self):
263 assert not self.active
264 self.__flag = threading.Event()
265 threading.Thread.start(self)
266 self.__flag.wait()
267
268 def run(self):
269 self.active = True
270 self.__flag.set()
271 while self.active and asyncore.socket_map:
272 self.active_lock.acquire()
273 asyncore.loop(timeout=0.1, count=1)
274 self.active_lock.release()
275 asyncore.close_all(ignore_all=True)
276
277 def stop(self):
278 assert self.active
279 self.active = False
280 self.join()
281
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000282 def handle_accepted(self, conn, addr):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000283 self.handler_instance = self.handler(conn)
Benjamin Petersond06e3b02008-09-28 21:00:42 +0000284
285 def handle_connect(self):
286 self.close()
287 handle_read = handle_connect
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000288
289 def writable(self):
290 return 0
291
292 def handle_error(self):
293 raise
294
295
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000296if ssl is not None:
297
298 CERTFILE = os.path.join(os.path.dirname(__file__), "keycert.pem")
299
300 class SSLConnection(asyncore.dispatcher):
301 """An asyncore.dispatcher subclass supporting TLS/SSL."""
302
303 _ssl_accepting = False
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000304 _ssl_closing = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000305
306 def secure_connection(self):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000307 socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
308 certfile=CERTFILE, server_side=True,
309 do_handshake_on_connect=False,
310 ssl_version=ssl.PROTOCOL_SSLv23)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200311 self.del_channel()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000312 self.set_socket(socket)
313 self._ssl_accepting = True
314
315 def _do_ssl_handshake(self):
316 try:
317 self.socket.do_handshake()
318 except ssl.SSLError as err:
319 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
320 ssl.SSL_ERROR_WANT_WRITE):
321 return
322 elif err.args[0] == ssl.SSL_ERROR_EOF:
323 return self.handle_close()
324 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +0200325 except OSError as err:
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000326 if err.args[0] == errno.ECONNABORTED:
327 return self.handle_close()
328 else:
329 self._ssl_accepting = False
330
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000331 def _do_ssl_shutdown(self):
332 self._ssl_closing = True
333 try:
334 self.socket = self.socket.unwrap()
335 except ssl.SSLError as err:
336 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
337 ssl.SSL_ERROR_WANT_WRITE):
338 return
Andrew Svetlov0832af62012-12-18 23:10:48 +0200339 except OSError as err:
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000340 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
341 # from OpenSSL's SSL_shutdown(), corresponding to a
342 # closed socket condition. See also:
343 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
344 pass
345 self._ssl_closing = False
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400346 if getattr(self, '_ccc', False) is False:
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200347 super(SSLConnection, self).close()
348 else:
349 pass
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000350
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000351 def handle_read_event(self):
352 if self._ssl_accepting:
353 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000354 elif self._ssl_closing:
355 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000356 else:
357 super(SSLConnection, self).handle_read_event()
358
359 def handle_write_event(self):
360 if self._ssl_accepting:
361 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000362 elif self._ssl_closing:
363 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000364 else:
365 super(SSLConnection, self).handle_write_event()
366
367 def send(self, data):
368 try:
369 return super(SSLConnection, self).send(data)
370 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000371 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
372 ssl.SSL_ERROR_WANT_READ,
373 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000374 return 0
375 raise
376
377 def recv(self, buffer_size):
378 try:
379 return super(SSLConnection, self).recv(buffer_size)
380 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000381 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
382 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000383 return b''
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000384 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
385 self.handle_close()
386 return b''
387 raise
388
389 def handle_error(self):
390 raise
391
392 def close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000393 if (isinstance(self.socket, ssl.SSLSocket) and
394 self.socket._sslobj is not None):
395 self._do_ssl_shutdown()
Benjamin Peterson1bd93a72010-10-31 19:58:07 +0000396 else:
397 super(SSLConnection, self).close()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000398
399
400 class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
401 """A DummyDTPHandler subclass supporting TLS/SSL."""
402
403 def __init__(self, conn, baseclass):
404 DummyDTPHandler.__init__(self, conn, baseclass)
405 if self.baseclass.secure_data_channel:
406 self.secure_connection()
407
408
409 class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
410 """A DummyFTPHandler subclass supporting TLS/SSL."""
411
412 dtp_handler = DummyTLS_DTPHandler
413
414 def __init__(self, conn):
415 DummyFTPHandler.__init__(self, conn)
416 self.secure_data_channel = False
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200417 self._ccc = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000418
419 def cmd_auth(self, line):
420 """Set up secure control channel."""
421 self.push('234 AUTH TLS successful')
422 self.secure_connection()
423
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200424 def cmd_ccc(self, line):
425 self.push('220 Reverting back to clear-text')
426 self._ccc = True
427 self._do_ssl_shutdown()
428
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000429 def cmd_pbsz(self, line):
430 """Negotiate size of buffer for secure data transfer.
431 For TLS/SSL the only valid value for the parameter is '0'.
432 Any other value is accepted but ignored.
433 """
434 self.push('200 PBSZ=0 successful.')
435
436 def cmd_prot(self, line):
437 """Setup un/secure data channel."""
438 arg = line.upper()
439 if arg == 'C':
440 self.push('200 Protection set to Clear')
441 self.secure_data_channel = False
442 elif arg == 'P':
443 self.push('200 Protection set to Private')
444 self.secure_data_channel = True
445 else:
446 self.push("502 Unrecognized PROT type (use C or P).")
447
448
449 class DummyTLS_FTPServer(DummyFTPServer):
450 handler = DummyTLS_FTPHandler
451
452
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000453class TestFTPClass(TestCase):
454
455 def setUp(self):
456 self.server = DummyFTPServer((HOST, 0))
457 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200458 self.client = ftplib.FTP(timeout=TIMEOUT)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000459 self.client.connect(self.server.host, self.server.port)
460
461 def tearDown(self):
462 self.client.close()
463 self.server.stop()
464
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100465 def check_data(self, received, expected):
466 self.assertEqual(len(received), len(expected))
467 self.assertEqual(received, expected)
468
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000469 def test_getwelcome(self):
470 self.assertEqual(self.client.getwelcome(), '220 welcome')
471
472 def test_sanitize(self):
473 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
474 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
475 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
476
477 def test_exceptions(self):
478 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
479 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
480 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
481 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
482 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
483
484 def test_all_errors(self):
485 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200486 ftplib.error_proto, ftplib.Error, OSError, EOFError)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000487 for x in exceptions:
488 try:
489 raise x('exception not included in all_errors set')
490 except ftplib.all_errors:
491 pass
492
493 def test_set_pasv(self):
494 # passive mode is supposed to be enabled by default
495 self.assertTrue(self.client.passiveserver)
496 self.client.set_pasv(True)
497 self.assertTrue(self.client.passiveserver)
498 self.client.set_pasv(False)
499 self.assertFalse(self.client.passiveserver)
500
501 def test_voidcmd(self):
502 self.client.voidcmd('echo 200')
503 self.client.voidcmd('echo 299')
504 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
505 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
506
507 def test_login(self):
508 self.client.login()
509
510 def test_acct(self):
511 self.client.acct('passwd')
512
513 def test_rename(self):
514 self.client.rename('a', 'b')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000515 self.server.handler_instance.next_response = '200'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000516 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
517
518 def test_delete(self):
519 self.client.delete('foo')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000520 self.server.handler_instance.next_response = '199'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000521 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
522
523 def test_size(self):
524 self.client.size('foo')
525
526 def test_mkd(self):
527 dir = self.client.mkd('/foo')
528 self.assertEqual(dir, '/foo')
529
530 def test_rmd(self):
531 self.client.rmd('foo')
532
Senthil Kumaran0d538602013-08-12 22:25:27 -0700533 def test_cwd(self):
534 dir = self.client.cwd('/foo')
535 self.assertEqual(dir, '250 cwd ok')
536
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000537 def test_pwd(self):
538 dir = self.client.pwd()
539 self.assertEqual(dir, 'pwd ok')
540
541 def test_quit(self):
542 self.assertEqual(self.client.quit(), '221 quit ok')
543 # Ensure the connection gets closed; sock attribute should be None
544 self.assertEqual(self.client.sock, None)
545
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200546 def test_abort(self):
547 self.client.abort()
548
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000549 def test_retrbinary(self):
550 def callback(data):
551 received.append(data.decode('ascii'))
552 received = []
553 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100554 self.check_data(''.join(received), RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000555
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000556 def test_retrbinary_rest(self):
557 def callback(data):
558 received.append(data.decode('ascii'))
559 for rest in (0, 10, 20):
560 received = []
561 self.client.retrbinary('retr', callback, rest=rest)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100562 self.check_data(''.join(received), RETR_DATA[rest:])
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000563
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000564 def test_retrlines(self):
565 received = []
566 self.client.retrlines('retr', received.append)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100567 self.check_data(''.join(received), RETR_DATA.replace('\r\n', ''))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000568
569 def test_storbinary(self):
570 f = io.BytesIO(RETR_DATA.encode('ascii'))
571 self.client.storbinary('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100572 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000573 # test new callback arg
574 flag = []
575 f.seek(0)
576 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
577 self.assertTrue(flag)
578
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000579 def test_storbinary_rest(self):
580 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
581 for r in (30, '30'):
582 f.seek(0)
583 self.client.storbinary('stor', f, rest=r)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000584 self.assertEqual(self.server.handler_instance.rest, str(r))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000585
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000586 def test_storlines(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000587 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
588 self.client.storlines('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100589 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000590 # test new callback arg
591 flag = []
592 f.seek(0)
593 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
594 self.assertTrue(flag)
595
Victor Stinnered3a3032013-04-02 22:13:27 +0200596 f = io.StringIO(RETR_DATA.replace('\r\n', '\n'))
597 # storlines() expects a binary file, not a text file
Florent Xicluna5f3fef32013-07-06 15:08:21 +0200598 with support.check_warnings(('', BytesWarning), quiet=True):
599 self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)
Victor Stinnered3a3032013-04-02 22:13:27 +0200600
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000601 def test_nlst(self):
602 self.client.nlst()
603 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
604
605 def test_dir(self):
606 l = []
607 self.client.dir(lambda x: l.append(x))
608 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
609
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200610 def test_mlsd(self):
611 list(self.client.mlsd())
612 list(self.client.mlsd(path='/'))
613 list(self.client.mlsd(path='/', facts=['size', 'type']))
614
615 ls = list(self.client.mlsd())
616 for name, facts in ls:
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200617 self.assertIsInstance(name, str)
618 self.assertIsInstance(facts, dict)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200619 self.assertTrue(name)
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200620 self.assertIn('type', facts)
621 self.assertIn('perm', facts)
622 self.assertIn('unique', facts)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200623
624 def set_data(data):
625 self.server.handler_instance.next_data = data
626
627 def test_entry(line, type=None, perm=None, unique=None, name=None):
628 type = 'type' if type is None else type
629 perm = 'perm' if perm is None else perm
630 unique = 'unique' if unique is None else unique
631 name = 'name' if name is None else name
632 set_data(line)
633 _name, facts = next(self.client.mlsd())
634 self.assertEqual(_name, name)
635 self.assertEqual(facts['type'], type)
636 self.assertEqual(facts['perm'], perm)
637 self.assertEqual(facts['unique'], unique)
638
639 # plain
640 test_entry('type=type;perm=perm;unique=unique; name\r\n')
641 # "=" in fact value
642 test_entry('type=ty=pe;perm=perm;unique=unique; name\r\n', type="ty=pe")
643 test_entry('type==type;perm=perm;unique=unique; name\r\n', type="=type")
644 test_entry('type=t=y=pe;perm=perm;unique=unique; name\r\n', type="t=y=pe")
645 test_entry('type=====;perm=perm;unique=unique; name\r\n', type="====")
646 # spaces in name
647 test_entry('type=type;perm=perm;unique=unique; na me\r\n', name="na me")
648 test_entry('type=type;perm=perm;unique=unique; name \r\n', name="name ")
649 test_entry('type=type;perm=perm;unique=unique; name\r\n', name=" name")
650 test_entry('type=type;perm=perm;unique=unique; n am e\r\n', name="n am e")
651 # ";" 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; ;;;;\r\n', name=";;;;")
656 # case sensitiveness
657 set_data('Type=type;TyPe=perm;UNIQUE=unique; name\r\n')
658 _name, facts = next(self.client.mlsd())
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200659 for x in facts:
660 self.assertTrue(x.islower())
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200661 # no data (directory empty)
662 set_data('')
663 self.assertRaises(StopIteration, next, self.client.mlsd())
664 set_data('')
665 for x in self.client.mlsd():
666 self.fail("unexpected data %s" % data)
667
Benjamin Peterson3a53fbb2008-09-27 22:04:16 +0000668 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000669 with self.client.makeport():
670 # IPv4 is in use, just make sure send_eprt has not been used
671 self.assertEqual(self.server.handler_instance.last_received_cmd,
672 'port')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000673
674 def test_makepasv(self):
675 host, port = self.client.makepasv()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200676 conn = socket.create_connection((host, port), timeout=TIMEOUT)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000677 conn.close()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000678 # IPv4 is in use, just make sure send_epsv has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000679 self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
680
681 def test_with_statement(self):
682 self.client.quit()
683
684 def is_client_connected():
685 if self.client.sock is None:
686 return False
687 try:
688 self.client.sendcmd('noop')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200689 except (OSError, EOFError):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000690 return False
691 return True
692
693 # base test
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200694 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000695 self.client.connect(self.server.host, self.server.port)
696 self.client.sendcmd('noop')
697 self.assertTrue(is_client_connected())
698 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
699 self.assertFalse(is_client_connected())
700
701 # QUIT sent inside the with block
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200702 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000703 self.client.connect(self.server.host, self.server.port)
704 self.client.sendcmd('noop')
705 self.client.quit()
706 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
707 self.assertFalse(is_client_connected())
708
709 # force a wrong response code to be sent on QUIT: error_perm
710 # is expected and the connection is supposed to be closed
711 try:
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200712 with ftplib.FTP(timeout=TIMEOUT) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000713 self.client.connect(self.server.host, self.server.port)
714 self.client.sendcmd('noop')
715 self.server.handler_instance.next_response = '550 error on quit'
716 except ftplib.error_perm as err:
717 self.assertEqual(str(err), '550 error on quit')
718 else:
719 self.fail('Exception not raised')
720 # needed to give the threaded server some time to set the attribute
721 # which otherwise would still be == 'noop'
722 time.sleep(0.1)
723 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
724 self.assertFalse(is_client_connected())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000725
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000726 def test_source_address(self):
727 self.client.quit()
728 port = support.find_unused_port()
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200729 try:
730 self.client.connect(self.server.host, self.server.port,
731 source_address=(HOST, port))
732 self.assertEqual(self.client.sock.getsockname()[1], port)
733 self.client.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200734 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200735 if e.errno == errno.EADDRINUSE:
736 self.skipTest("couldn't bind to port %d" % port)
737 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000738
739 def test_source_address_passive_connection(self):
740 port = support.find_unused_port()
741 self.client.source_address = (HOST, port)
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200742 try:
743 with self.client.transfercmd('list') as sock:
744 self.assertEqual(sock.getsockname()[1], port)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200745 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200746 if e.errno == errno.EADDRINUSE:
747 self.skipTest("couldn't bind to port %d" % port)
748 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000749
Giampaolo Rodolàbbc47822010-08-23 22:10:32 +0000750 def test_parse257(self):
751 self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
752 self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
753 self.assertEqual(ftplib.parse257('257 ""'), '')
754 self.assertEqual(ftplib.parse257('257 "" created'), '')
755 self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
756 # The 257 response is supposed to include the directory
757 # name and in case it contains embedded double-quotes
758 # they must be doubled (see RFC-959, chapter 7, appendix 2).
759 self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
760 self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
761
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000762
763class TestIPv6Environment(TestCase):
764
765 def setUp(self):
Antoine Pitrouf6fbf562013-08-22 00:39:46 +0200766 self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000767 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200768 self.client = ftplib.FTP(timeout=TIMEOUT)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000769 self.client.connect(self.server.host, self.server.port)
770
771 def tearDown(self):
772 self.client.close()
773 self.server.stop()
774
775 def test_af(self):
776 self.assertEqual(self.client.af, socket.AF_INET6)
777
778 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000779 with self.client.makeport():
780 self.assertEqual(self.server.handler_instance.last_received_cmd,
781 'eprt')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000782
783 def test_makepasv(self):
784 host, port = self.client.makepasv()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200785 conn = socket.create_connection((host, port), timeout=TIMEOUT)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000786 conn.close()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000787 self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000788
789 def test_transfer(self):
790 def retr():
791 def callback(data):
792 received.append(data.decode('ascii'))
793 received = []
794 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100795 self.assertEqual(len(''.join(received)), len(RETR_DATA))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000796 self.assertEqual(''.join(received), RETR_DATA)
797 self.client.set_pasv(True)
798 retr()
799 self.client.set_pasv(False)
800 retr()
801
802
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000803class TestTLS_FTPClassMixin(TestFTPClass):
804 """Repeat TestFTPClass tests starting the TLS layer for both control
805 and data connections first.
806 """
807
808 def setUp(self):
809 self.server = DummyTLS_FTPServer((HOST, 0))
810 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200811 self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000812 self.client.connect(self.server.host, self.server.port)
813 # enable TLS
814 self.client.auth()
815 self.client.prot_p()
816
817
818class TestTLS_FTPClass(TestCase):
819 """Specific TLS_FTP class tests."""
820
821 def setUp(self):
822 self.server = DummyTLS_FTPServer((HOST, 0))
823 self.server.start()
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200824 self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000825 self.client.connect(self.server.host, self.server.port)
826
827 def tearDown(self):
828 self.client.close()
829 self.server.stop()
830
831 def test_control_connection(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000832 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000833 self.client.auth()
Ezio Melottie9615932010-01-24 19:26:24 +0000834 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000835
836 def test_data_connection(self):
837 # clear text
Brett Cannon918e2d42010-10-29 23:26:25 +0000838 with self.client.transfercmd('list') as sock:
839 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000840 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000841
842 # secured, after PROT P
843 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000844 with self.client.transfercmd('list') as sock:
845 self.assertIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000846 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000847
848 # PROT C is issued, the connection must be in cleartext again
849 self.client.prot_c()
Brett Cannon918e2d42010-10-29 23:26:25 +0000850 with self.client.transfercmd('list') as sock:
851 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000852 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000853
854 def test_login(self):
855 # login() is supposed to implicitly secure the control connection
Ezio Melottie9615932010-01-24 19:26:24 +0000856 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000857 self.client.login()
Ezio Melottie9615932010-01-24 19:26:24 +0000858 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000859 # make sure that AUTH TLS doesn't get issued again
860 self.client.login()
861
862 def test_auth_issued_twice(self):
863 self.client.auth()
864 self.assertRaises(ValueError, self.client.auth)
865
866 def test_auth_ssl(self):
867 try:
868 self.client.ssl_version = ssl.PROTOCOL_SSLv3
869 self.client.auth()
870 self.assertRaises(ValueError, self.client.auth)
871 finally:
872 self.client.ssl_version = ssl.PROTOCOL_TLSv1
873
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000874 def test_context(self):
875 self.client.quit()
876 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
877 self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
878 context=ctx)
879 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
880 context=ctx)
881 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
882 keyfile=CERTFILE, context=ctx)
883
Giampaolo Rodola'0d4f08c2013-05-16 15:12:01 +0200884 self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000885 self.client.connect(self.server.host, self.server.port)
886 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
887 self.client.auth()
888 self.assertIs(self.client.sock.context, ctx)
889 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
890
891 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000892 with self.client.transfercmd('list') as sock:
893 self.assertIs(sock.context, ctx)
894 self.assertIsInstance(sock, ssl.SSLSocket)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000895
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200896 def test_ccc(self):
897 self.assertRaises(ValueError, self.client.ccc)
898 self.client.login(secure=True)
899 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
900 self.client.ccc()
901 self.assertRaises(ValueError, self.client.sock.unwrap)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200902
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000903
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000904class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000905
906 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000908 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100909 self.sock.settimeout(20)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000910 self.port = support.bind_port(self.sock)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100911 self.server_thread = threading.Thread(target=self.server)
912 self.server_thread.start()
Christian Heimes836baa52008-02-26 08:18:30 +0000913 # Wait for the server to be ready.
914 self.evt.wait()
915 self.evt.clear()
Antoine Pitrou08d02722012-12-19 20:44:02 +0100916 self.old_port = ftplib.FTP.port
Christian Heimes5e696852008-04-09 08:37:03 +0000917 ftplib.FTP.port = self.port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000918
919 def tearDown(self):
Antoine Pitrou08d02722012-12-19 20:44:02 +0100920 ftplib.FTP.port = self.old_port
921 self.server_thread.join()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000922
Antoine Pitrou08d02722012-12-19 20:44:02 +0100923 def server(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000924 # This method sets the evt 3 times:
925 # 1) when the connection is ready to be accepted.
926 # 2) when it is safe for the caller to close the connection
927 # 3) when we have closed the socket
Antoine Pitrou08d02722012-12-19 20:44:02 +0100928 self.sock.listen(5)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000929 # (1) Signal the caller that we are ready to accept the connection.
Antoine Pitrou08d02722012-12-19 20:44:02 +0100930 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000931 try:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100932 conn, addr = self.sock.accept()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000933 except socket.timeout:
934 pass
935 else:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100936 conn.sendall(b"1 Hola mundo\n")
937 conn.shutdown(socket.SHUT_WR)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000938 # (2) Signal the caller that it is safe to close the socket.
Antoine Pitrou08d02722012-12-19 20:44:02 +0100939 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000940 conn.close()
941 finally:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100942 self.sock.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000943
944 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000945 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000946 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000947 socket.setdefaulttimeout(30)
948 try:
Antoine Pitrouf6fbf562013-08-22 00:39:46 +0200949 ftp = ftplib.FTP(HOST)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000950 finally:
951 socket.setdefaulttimeout(None)
952 self.assertEqual(ftp.sock.gettimeout(), 30)
953 self.evt.wait()
954 ftp.close()
955
956 def testTimeoutNone(self):
957 # no timeout -- do not use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000958 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000959 socket.setdefaulttimeout(30)
960 try:
Antoine Pitrouf6fbf562013-08-22 00:39:46 +0200961 ftp = ftplib.FTP(HOST, timeout=None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000962 finally:
963 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000964 self.assertTrue(ftp.sock.gettimeout() is None)
Christian Heimes836baa52008-02-26 08:18:30 +0000965 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000966 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000967
968 def testTimeoutValue(self):
969 # a value
Christian Heimes5e696852008-04-09 08:37:03 +0000970 ftp = ftplib.FTP(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000971 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000972 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000973 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974
975 def testTimeoutConnect(self):
976 ftp = ftplib.FTP()
Christian Heimes5e696852008-04-09 08:37:03 +0000977 ftp.connect(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000978 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000979 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000980 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981
982 def testTimeoutDifferentOrder(self):
983 ftp = ftplib.FTP(timeout=30)
Christian Heimes5e696852008-04-09 08:37:03 +0000984 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000986 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000987 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000988
989 def testTimeoutDirectAccess(self):
990 ftp = ftplib.FTP()
991 ftp.timeout = 30
Christian Heimes5e696852008-04-09 08:37:03 +0000992 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000993 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000994 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000995 ftp.close()
996
997
R David Murray87632f12013-02-19 18:32:28 -0500998class TestNetrcDeprecation(TestCase):
999
1000 def test_deprecation(self):
1001 with support.temp_cwd(), support.EnvironmentVarGuard() as env:
1002 env['HOME'] = os.getcwd()
1003 open('.netrc', 'w').close()
1004 with self.assertWarns(DeprecationWarning):
1005 ftplib.Netrc()
1006
1007
1008
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001009def test_main():
R David Murray87632f12013-02-19 18:32:28 -05001010 tests = [TestFTPClass, TestTimeouts, TestNetrcDeprecation]
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +02001011 if support.IPV6_ENABLED:
Victor Stinnerc90e19d2011-05-01 01:23:03 +02001012 tests.append(TestIPv6Environment)
Antoine Pitrouf988cd02009-11-17 20:21:14 +00001013
1014 if ssl is not None:
1015 tests.extend([TestTLS_FTPClassMixin, TestTLS_FTPClass])
1016
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001017 thread_info = support.threading_setup()
1018 try:
1019 support.run_unittest(*tests)
1020 finally:
1021 support.threading_cleanup(*thread_info)
1022
Guido van Rossumd8faa362007-04-27 19:54:29 +00001023
1024if __name__ == '__main__':
1025 test_main()