blob: 21592d744e3d827122b671ea64f314787b61a715 [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
Benjamin Petersonbe17a112008-09-27 21:49:47 +000021from test.support import HOST
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
Benjamin Petersonbe17a112008-09-27 21:49:47 +000094 self.push('220 welcome')
95
96 def collect_incoming_data(self, data):
97 self.in_buffer.append(data)
98
99 def found_terminator(self):
100 line = b''.join(self.in_buffer).decode('ascii')
101 self.in_buffer = []
102 if self.next_response:
103 self.push(self.next_response)
104 self.next_response = ''
105 cmd = line.split(' ')[0].lower()
106 self.last_received_cmd = cmd
107 space = line.find(' ')
108 if space != -1:
109 arg = line[space + 1:]
110 else:
111 arg = ""
112 if hasattr(self, 'cmd_' + cmd):
113 method = getattr(self, 'cmd_' + cmd)
114 method(arg)
115 else:
116 self.push('550 command "%s" not understood.' %cmd)
117
118 def handle_error(self):
119 raise
120
121 def push(self, data):
122 asynchat.async_chat.push(self, data.encode('ascii') + b'\r\n')
123
124 def cmd_port(self, arg):
125 addr = list(map(int, arg.split(',')))
126 ip = '%d.%d.%d.%d' %tuple(addr[:4])
127 port = (addr[4] * 256) + addr[5]
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200128 s = socket.create_connection((ip, port), timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000129 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000130 self.push('200 active data connection established')
131
132 def cmd_pasv(self, arg):
Brett Cannon918e2d42010-10-29 23:26:25 +0000133 with socket.socket() as sock:
134 sock.bind((self.socket.getsockname()[0], 0))
135 sock.listen(5)
136 sock.settimeout(10)
137 ip, port = sock.getsockname()[:2]
138 ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
139 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
140 conn, addr = sock.accept()
141 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000142
143 def cmd_eprt(self, arg):
144 af, ip, port = arg.split(arg[0])[1:-1]
145 port = int(port)
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200146 s = socket.create_connection((ip, port), timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000147 self.dtp = self.dtp_handler(s, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000148 self.push('200 active data connection established')
149
150 def cmd_epsv(self, arg):
Brett Cannon918e2d42010-10-29 23:26:25 +0000151 with socket.socket(socket.AF_INET6) as sock:
152 sock.bind((self.socket.getsockname()[0], 0))
153 sock.listen(5)
154 sock.settimeout(10)
155 port = sock.getsockname()[1]
156 self.push('229 entering extended passive mode (|||%d|)' %port)
157 conn, addr = sock.accept()
158 self.dtp = self.dtp_handler(conn, baseclass=self)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000159
160 def cmd_echo(self, arg):
161 # sends back the received string (used by the test suite)
162 self.push(arg)
163
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000164 def cmd_noop(self, arg):
165 self.push('200 noop ok')
166
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000167 def cmd_user(self, arg):
168 self.push('331 username ok')
169
170 def cmd_pass(self, arg):
171 self.push('230 password ok')
172
173 def cmd_acct(self, arg):
174 self.push('230 acct ok')
175
176 def cmd_rnfr(self, arg):
177 self.push('350 rnfr ok')
178
179 def cmd_rnto(self, arg):
180 self.push('250 rnto ok')
181
182 def cmd_dele(self, arg):
183 self.push('250 dele ok')
184
185 def cmd_cwd(self, arg):
186 self.push('250 cwd ok')
187
188 def cmd_size(self, arg):
189 self.push('250 1000')
190
191 def cmd_mkd(self, arg):
192 self.push('257 "%s"' %arg)
193
194 def cmd_rmd(self, arg):
195 self.push('250 rmd ok')
196
197 def cmd_pwd(self, arg):
198 self.push('257 "pwd ok"')
199
200 def cmd_type(self, arg):
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000201 self.push('200 type ok')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000202
203 def cmd_quit(self, arg):
204 self.push('221 quit ok')
205 self.close()
206
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200207 def cmd_abor(self, arg):
208 self.push('226 abor ok')
209
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000210 def cmd_stor(self, arg):
211 self.push('125 stor ok')
212
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000213 def cmd_rest(self, arg):
214 self.rest = arg
215 self.push('350 rest ok')
216
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000217 def cmd_retr(self, arg):
218 self.push('125 retr ok')
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000219 if self.rest is not None:
220 offset = int(self.rest)
221 else:
222 offset = 0
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000223 self.dtp.push(RETR_DATA[offset:])
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000224 self.dtp.close_when_done()
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000225 self.rest = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000226
227 def cmd_list(self, arg):
228 self.push('125 list ok')
229 self.dtp.push(LIST_DATA)
230 self.dtp.close_when_done()
231
232 def cmd_nlst(self, arg):
233 self.push('125 nlst ok')
234 self.dtp.push(NLST_DATA)
235 self.dtp.close_when_done()
236
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200237 def cmd_opts(self, arg):
238 self.push('200 opts ok')
239
240 def cmd_mlsd(self, arg):
241 self.push('125 mlsd ok')
242 self.dtp.push(MLSD_DATA)
243 self.dtp.close_when_done()
244
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000245
246class DummyFTPServer(asyncore.dispatcher, threading.Thread):
247
248 handler = DummyFTPHandler
249
250 def __init__(self, address, af=socket.AF_INET):
251 threading.Thread.__init__(self)
252 asyncore.dispatcher.__init__(self)
253 self.create_socket(af, socket.SOCK_STREAM)
254 self.bind(address)
255 self.listen(5)
256 self.active = False
257 self.active_lock = threading.Lock()
258 self.host, self.port = self.socket.getsockname()[:2]
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000259 self.handler_instance = None
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000260
261 def start(self):
262 assert not self.active
263 self.__flag = threading.Event()
264 threading.Thread.start(self)
265 self.__flag.wait()
266
267 def run(self):
268 self.active = True
269 self.__flag.set()
270 while self.active and asyncore.socket_map:
271 self.active_lock.acquire()
272 asyncore.loop(timeout=0.1, count=1)
273 self.active_lock.release()
274 asyncore.close_all(ignore_all=True)
275
276 def stop(self):
277 assert self.active
278 self.active = False
279 self.join()
280
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000281 def handle_accepted(self, conn, addr):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000282 self.handler_instance = self.handler(conn)
Benjamin Petersond06e3b02008-09-28 21:00:42 +0000283
284 def handle_connect(self):
285 self.close()
286 handle_read = handle_connect
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000287
288 def writable(self):
289 return 0
290
291 def handle_error(self):
292 raise
293
294
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000295if ssl is not None:
296
297 CERTFILE = os.path.join(os.path.dirname(__file__), "keycert.pem")
298
299 class SSLConnection(asyncore.dispatcher):
300 """An asyncore.dispatcher subclass supporting TLS/SSL."""
301
302 _ssl_accepting = False
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000303 _ssl_closing = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000304
305 def secure_connection(self):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000306 socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
307 certfile=CERTFILE, server_side=True,
308 do_handshake_on_connect=False,
309 ssl_version=ssl.PROTOCOL_SSLv23)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200310 self.del_channel()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000311 self.set_socket(socket)
312 self._ssl_accepting = True
313
314 def _do_ssl_handshake(self):
315 try:
316 self.socket.do_handshake()
317 except ssl.SSLError as err:
318 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
319 ssl.SSL_ERROR_WANT_WRITE):
320 return
321 elif err.args[0] == ssl.SSL_ERROR_EOF:
322 return self.handle_close()
323 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +0200324 except OSError as err:
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000325 if err.args[0] == errno.ECONNABORTED:
326 return self.handle_close()
327 else:
328 self._ssl_accepting = False
329
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000330 def _do_ssl_shutdown(self):
331 self._ssl_closing = True
332 try:
333 self.socket = self.socket.unwrap()
334 except ssl.SSLError as err:
335 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
336 ssl.SSL_ERROR_WANT_WRITE):
337 return
Andrew Svetlov0832af62012-12-18 23:10:48 +0200338 except OSError as err:
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000339 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
340 # from OpenSSL's SSL_shutdown(), corresponding to a
341 # closed socket condition. See also:
342 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
343 pass
344 self._ssl_closing = False
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400345 if getattr(self, '_ccc', False) is False:
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200346 super(SSLConnection, self).close()
347 else:
348 pass
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000349
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000350 def handle_read_event(self):
351 if self._ssl_accepting:
352 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000353 elif self._ssl_closing:
354 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000355 else:
356 super(SSLConnection, self).handle_read_event()
357
358 def handle_write_event(self):
359 if self._ssl_accepting:
360 self._do_ssl_handshake()
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000361 elif self._ssl_closing:
362 self._do_ssl_shutdown()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000363 else:
364 super(SSLConnection, self).handle_write_event()
365
366 def send(self, data):
367 try:
368 return super(SSLConnection, self).send(data)
369 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000370 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
371 ssl.SSL_ERROR_WANT_READ,
372 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000373 return 0
374 raise
375
376 def recv(self, buffer_size):
377 try:
378 return super(SSLConnection, self).recv(buffer_size)
379 except ssl.SSLError as err:
Antoine Pitrou5733c082010-03-22 14:49:10 +0000380 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
381 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000382 return b''
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000383 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
384 self.handle_close()
385 return b''
386 raise
387
388 def handle_error(self):
389 raise
390
391 def close(self):
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000392 if (isinstance(self.socket, ssl.SSLSocket) and
393 self.socket._sslobj is not None):
394 self._do_ssl_shutdown()
Benjamin Peterson1bd93a72010-10-31 19:58:07 +0000395 else:
396 super(SSLConnection, self).close()
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000397
398
399 class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
400 """A DummyDTPHandler subclass supporting TLS/SSL."""
401
402 def __init__(self, conn, baseclass):
403 DummyDTPHandler.__init__(self, conn, baseclass)
404 if self.baseclass.secure_data_channel:
405 self.secure_connection()
406
407
408 class DummyTLS_FTPHandler(SSLConnection, DummyFTPHandler):
409 """A DummyFTPHandler subclass supporting TLS/SSL."""
410
411 dtp_handler = DummyTLS_DTPHandler
412
413 def __init__(self, conn):
414 DummyFTPHandler.__init__(self, conn)
415 self.secure_data_channel = False
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200416 self._ccc = False
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000417
418 def cmd_auth(self, line):
419 """Set up secure control channel."""
420 self.push('234 AUTH TLS successful')
421 self.secure_connection()
422
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200423 def cmd_ccc(self, line):
424 self.push('220 Reverting back to clear-text')
425 self._ccc = True
426 self._do_ssl_shutdown()
427
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000428 def cmd_pbsz(self, line):
429 """Negotiate size of buffer for secure data transfer.
430 For TLS/SSL the only valid value for the parameter is '0'.
431 Any other value is accepted but ignored.
432 """
433 self.push('200 PBSZ=0 successful.')
434
435 def cmd_prot(self, line):
436 """Setup un/secure data channel."""
437 arg = line.upper()
438 if arg == 'C':
439 self.push('200 Protection set to Clear')
440 self.secure_data_channel = False
441 elif arg == 'P':
442 self.push('200 Protection set to Private')
443 self.secure_data_channel = True
444 else:
445 self.push("502 Unrecognized PROT type (use C or P).")
446
447
448 class DummyTLS_FTPServer(DummyFTPServer):
449 handler = DummyTLS_FTPHandler
450
451
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000452class TestFTPClass(TestCase):
453
454 def setUp(self):
455 self.server = DummyFTPServer((HOST, 0))
456 self.server.start()
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200457 self.client = ftplib.FTP(timeout=2)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000458 self.client.connect(self.server.host, self.server.port)
459
460 def tearDown(self):
461 self.client.close()
462 self.server.stop()
463
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100464 def check_data(self, received, expected):
465 self.assertEqual(len(received), len(expected))
466 self.assertEqual(received, expected)
467
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000468 def test_getwelcome(self):
469 self.assertEqual(self.client.getwelcome(), '220 welcome')
470
471 def test_sanitize(self):
472 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
473 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
474 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
475
476 def test_exceptions(self):
477 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
478 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
479 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
480 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
481 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
482
483 def test_all_errors(self):
484 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200485 ftplib.error_proto, ftplib.Error, OSError, EOFError)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000486 for x in exceptions:
487 try:
488 raise x('exception not included in all_errors set')
489 except ftplib.all_errors:
490 pass
491
492 def test_set_pasv(self):
493 # passive mode is supposed to be enabled by default
494 self.assertTrue(self.client.passiveserver)
495 self.client.set_pasv(True)
496 self.assertTrue(self.client.passiveserver)
497 self.client.set_pasv(False)
498 self.assertFalse(self.client.passiveserver)
499
500 def test_voidcmd(self):
501 self.client.voidcmd('echo 200')
502 self.client.voidcmd('echo 299')
503 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
504 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
505
506 def test_login(self):
507 self.client.login()
508
509 def test_acct(self):
510 self.client.acct('passwd')
511
512 def test_rename(self):
513 self.client.rename('a', 'b')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000514 self.server.handler_instance.next_response = '200'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000515 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
516
517 def test_delete(self):
518 self.client.delete('foo')
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000519 self.server.handler_instance.next_response = '199'
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000520 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
521
522 def test_size(self):
523 self.client.size('foo')
524
525 def test_mkd(self):
526 dir = self.client.mkd('/foo')
527 self.assertEqual(dir, '/foo')
528
529 def test_rmd(self):
530 self.client.rmd('foo')
531
532 def test_pwd(self):
533 dir = self.client.pwd()
534 self.assertEqual(dir, 'pwd ok')
535
536 def test_quit(self):
537 self.assertEqual(self.client.quit(), '221 quit ok')
538 # Ensure the connection gets closed; sock attribute should be None
539 self.assertEqual(self.client.sock, None)
540
Giampaolo Rodola'0b5c21f2011-05-07 19:03:47 +0200541 def test_abort(self):
542 self.client.abort()
543
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000544 def test_retrbinary(self):
545 def callback(data):
546 received.append(data.decode('ascii'))
547 received = []
548 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100549 self.check_data(''.join(received), RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000550
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000551 def test_retrbinary_rest(self):
552 def callback(data):
553 received.append(data.decode('ascii'))
554 for rest in (0, 10, 20):
555 received = []
556 self.client.retrbinary('retr', callback, rest=rest)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100557 self.check_data(''.join(received), RETR_DATA[rest:])
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000558
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000559 def test_retrlines(self):
560 received = []
561 self.client.retrlines('retr', received.append)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100562 self.check_data(''.join(received), RETR_DATA.replace('\r\n', ''))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000563
564 def test_storbinary(self):
565 f = io.BytesIO(RETR_DATA.encode('ascii'))
566 self.client.storbinary('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100567 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000568 # test new callback arg
569 flag = []
570 f.seek(0)
571 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
572 self.assertTrue(flag)
573
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000574 def test_storbinary_rest(self):
575 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
576 for r in (30, '30'):
577 f.seek(0)
578 self.client.storbinary('stor', f, rest=r)
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000579 self.assertEqual(self.server.handler_instance.rest, str(r))
Antoine Pitrou648bcd72009-11-27 13:23:26 +0000580
Giampaolo Rodolàf96482e2010-08-04 10:36:18 +0000581 def test_storlines(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000582 f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
583 self.client.storlines('stor', f)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100584 self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000585 # test new callback arg
586 flag = []
587 f.seek(0)
588 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
589 self.assertTrue(flag)
590
Victor Stinnered3a3032013-04-02 22:13:27 +0200591 f = io.StringIO(RETR_DATA.replace('\r\n', '\n'))
592 # storlines() expects a binary file, not a text file
593 self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)
594
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000595 def test_nlst(self):
596 self.client.nlst()
597 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
598
599 def test_dir(self):
600 l = []
601 self.client.dir(lambda x: l.append(x))
602 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
603
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200604 def test_mlsd(self):
605 list(self.client.mlsd())
606 list(self.client.mlsd(path='/'))
607 list(self.client.mlsd(path='/', facts=['size', 'type']))
608
609 ls = list(self.client.mlsd())
610 for name, facts in ls:
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200611 self.assertIsInstance(name, str)
612 self.assertIsInstance(facts, dict)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200613 self.assertTrue(name)
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200614 self.assertIn('type', facts)
615 self.assertIn('perm', facts)
616 self.assertIn('unique', facts)
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200617
618 def set_data(data):
619 self.server.handler_instance.next_data = data
620
621 def test_entry(line, type=None, perm=None, unique=None, name=None):
622 type = 'type' if type is None else type
623 perm = 'perm' if perm is None else perm
624 unique = 'unique' if unique is None else unique
625 name = 'name' if name is None else name
626 set_data(line)
627 _name, facts = next(self.client.mlsd())
628 self.assertEqual(_name, name)
629 self.assertEqual(facts['type'], type)
630 self.assertEqual(facts['perm'], perm)
631 self.assertEqual(facts['unique'], unique)
632
633 # plain
634 test_entry('type=type;perm=perm;unique=unique; name\r\n')
635 # "=" in fact value
636 test_entry('type=ty=pe;perm=perm;unique=unique; name\r\n', type="ty=pe")
637 test_entry('type==type;perm=perm;unique=unique; name\r\n', type="=type")
638 test_entry('type=t=y=pe;perm=perm;unique=unique; name\r\n', type="t=y=pe")
639 test_entry('type=====;perm=perm;unique=unique; name\r\n', type="====")
640 # spaces in name
641 test_entry('type=type;perm=perm;unique=unique; na me\r\n', name="na me")
642 test_entry('type=type;perm=perm;unique=unique; name \r\n', name="name ")
643 test_entry('type=type;perm=perm;unique=unique; name\r\n', name=" name")
644 test_entry('type=type;perm=perm;unique=unique; n am e\r\n', name="n am e")
645 # ";" in name
646 test_entry('type=type;perm=perm;unique=unique; na;me\r\n', name="na;me")
647 test_entry('type=type;perm=perm;unique=unique; ;name\r\n', name=";name")
648 test_entry('type=type;perm=perm;unique=unique; ;name;\r\n', name=";name;")
649 test_entry('type=type;perm=perm;unique=unique; ;;;;\r\n', name=";;;;")
650 # case sensitiveness
651 set_data('Type=type;TyPe=perm;UNIQUE=unique; name\r\n')
652 _name, facts = next(self.client.mlsd())
Giampaolo Rodola'a55efb32011-05-07 16:06:59 +0200653 for x in facts:
654 self.assertTrue(x.islower())
Giampaolo Rodola'd78def92011-05-06 19:49:08 +0200655 # no data (directory empty)
656 set_data('')
657 self.assertRaises(StopIteration, next, self.client.mlsd())
658 set_data('')
659 for x in self.client.mlsd():
660 self.fail("unexpected data %s" % data)
661
Benjamin Peterson3a53fbb2008-09-27 22:04:16 +0000662 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000663 with self.client.makeport():
664 # IPv4 is in use, just make sure send_eprt has not been used
665 self.assertEqual(self.server.handler_instance.last_received_cmd,
666 'port')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000667
668 def test_makepasv(self):
669 host, port = self.client.makepasv()
Antoine Pitroud778e562010-10-14 20:35:26 +0000670 conn = socket.create_connection((host, port), 10)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000671 conn.close()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000672 # IPv4 is in use, just make sure send_epsv has not been used
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000673 self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
674
675 def test_with_statement(self):
676 self.client.quit()
677
678 def is_client_connected():
679 if self.client.sock is None:
680 return False
681 try:
682 self.client.sendcmd('noop')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200683 except (OSError, EOFError):
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000684 return False
685 return True
686
687 # base test
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200688 with ftplib.FTP(timeout=2) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000689 self.client.connect(self.server.host, self.server.port)
690 self.client.sendcmd('noop')
691 self.assertTrue(is_client_connected())
692 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
693 self.assertFalse(is_client_connected())
694
695 # QUIT sent inside the with block
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200696 with ftplib.FTP(timeout=2) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000697 self.client.connect(self.server.host, self.server.port)
698 self.client.sendcmd('noop')
699 self.client.quit()
700 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
701 self.assertFalse(is_client_connected())
702
703 # force a wrong response code to be sent on QUIT: error_perm
704 # is expected and the connection is supposed to be closed
705 try:
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200706 with ftplib.FTP(timeout=2) as self.client:
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000707 self.client.connect(self.server.host, self.server.port)
708 self.client.sendcmd('noop')
709 self.server.handler_instance.next_response = '550 error on quit'
710 except ftplib.error_perm as err:
711 self.assertEqual(str(err), '550 error on quit')
712 else:
713 self.fail('Exception not raised')
714 # needed to give the threaded server some time to set the attribute
715 # which otherwise would still be == 'noop'
716 time.sleep(0.1)
717 self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit')
718 self.assertFalse(is_client_connected())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000719
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000720 def test_source_address(self):
721 self.client.quit()
722 port = support.find_unused_port()
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200723 try:
724 self.client.connect(self.server.host, self.server.port,
725 source_address=(HOST, port))
726 self.assertEqual(self.client.sock.getsockname()[1], port)
727 self.client.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200728 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200729 if e.errno == errno.EADDRINUSE:
730 self.skipTest("couldn't bind to port %d" % port)
731 raise
Giampaolo Rodolà396ff062011-02-28 19:19:51 +0000732
733 def test_source_address_passive_connection(self):
734 port = support.find_unused_port()
735 self.client.source_address = (HOST, port)
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200736 try:
737 with self.client.transfercmd('list') as sock:
738 self.assertEqual(sock.getsockname()[1], port)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200739 except OSError as e:
Antoine Pitrou6dca5272011-04-03 18:29:45 +0200740 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
Giampaolo Rodolàbbc47822010-08-23 22:10:32 +0000744 def test_parse257(self):
745 self.assertEqual(ftplib.parse257('257 "/foo/bar"'), '/foo/bar')
746 self.assertEqual(ftplib.parse257('257 "/foo/bar" created'), '/foo/bar')
747 self.assertEqual(ftplib.parse257('257 ""'), '')
748 self.assertEqual(ftplib.parse257('257 "" created'), '')
749 self.assertRaises(ftplib.error_reply, ftplib.parse257, '250 "/foo/bar"')
750 # The 257 response is supposed to include the directory
751 # name and in case it contains embedded double-quotes
752 # they must be doubled (see RFC-959, chapter 7, appendix 2).
753 self.assertEqual(ftplib.parse257('257 "/foo/b""ar"'), '/foo/b"ar')
754 self.assertEqual(ftplib.parse257('257 "/foo/b""ar" created'), '/foo/b"ar')
755
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000756
757class TestIPv6Environment(TestCase):
758
759 def setUp(self):
Victor Stinnerc90e19d2011-05-01 01:23:03 +0200760 self.server = DummyFTPServer(('::1', 0), af=socket.AF_INET6)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000761 self.server.start()
762 self.client = ftplib.FTP()
763 self.client.connect(self.server.host, self.server.port)
764
765 def tearDown(self):
766 self.client.close()
767 self.server.stop()
768
769 def test_af(self):
770 self.assertEqual(self.client.af, socket.AF_INET6)
771
772 def test_makeport(self):
Brett Cannon918e2d42010-10-29 23:26:25 +0000773 with self.client.makeport():
774 self.assertEqual(self.server.handler_instance.last_received_cmd,
775 'eprt')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000776
777 def test_makepasv(self):
778 host, port = self.client.makepasv()
Antoine Pitroud778e562010-10-14 20:35:26 +0000779 conn = socket.create_connection((host, port), 10)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000780 conn.close()
Giampaolo Rodolàbd576b72010-05-10 14:53:29 +0000781 self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000782
783 def test_transfer(self):
784 def retr():
785 def callback(data):
786 received.append(data.decode('ascii'))
787 received = []
788 self.client.retrbinary('retr', callback)
Giampaolo Rodola'8bc85852012-01-09 17:10:10 +0100789 self.assertEqual(len(''.join(received)), len(RETR_DATA))
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000790 self.assertEqual(''.join(received), RETR_DATA)
791 self.client.set_pasv(True)
792 retr()
793 self.client.set_pasv(False)
794 retr()
795
796
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000797class TestTLS_FTPClassMixin(TestFTPClass):
798 """Repeat TestFTPClass tests starting the TLS layer for both control
799 and data connections first.
800 """
801
802 def setUp(self):
803 self.server = DummyTLS_FTPServer((HOST, 0))
804 self.server.start()
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200805 self.client = ftplib.FTP_TLS(timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000806 self.client.connect(self.server.host, self.server.port)
807 # enable TLS
808 self.client.auth()
809 self.client.prot_p()
810
811
812class TestTLS_FTPClass(TestCase):
813 """Specific TLS_FTP class tests."""
814
815 def setUp(self):
816 self.server = DummyTLS_FTPServer((HOST, 0))
817 self.server.start()
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200818 self.client = ftplib.FTP_TLS(timeout=2)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000819 self.client.connect(self.server.host, self.server.port)
820
821 def tearDown(self):
822 self.client.close()
823 self.server.stop()
824
825 def test_control_connection(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000826 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000827 self.client.auth()
Ezio Melottie9615932010-01-24 19:26:24 +0000828 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000829
830 def test_data_connection(self):
831 # clear text
Brett Cannon918e2d42010-10-29 23:26:25 +0000832 with self.client.transfercmd('list') as sock:
833 self.assertNotIsInstance(sock, ssl.SSLSocket)
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000834 self.assertEqual(self.client.voidresp(), "226 transfer complete")
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000835
836 # secured, after PROT P
837 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000838 with self.client.transfercmd('list') as sock:
839 self.assertIsInstance(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 # PROT C is issued, the connection must be in cleartext again
843 self.client.prot_c()
Brett Cannon918e2d42010-10-29 23:26:25 +0000844 with self.client.transfercmd('list') as sock:
845 self.assertNotIsInstance(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 def test_login(self):
849 # login() is supposed to implicitly secure the control connection
Ezio Melottie9615932010-01-24 19:26:24 +0000850 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000851 self.client.login()
Ezio Melottie9615932010-01-24 19:26:24 +0000852 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000853 # make sure that AUTH TLS doesn't get issued again
854 self.client.login()
855
856 def test_auth_issued_twice(self):
857 self.client.auth()
858 self.assertRaises(ValueError, self.client.auth)
859
860 def test_auth_ssl(self):
861 try:
862 self.client.ssl_version = ssl.PROTOCOL_SSLv3
863 self.client.auth()
864 self.assertRaises(ValueError, self.client.auth)
865 finally:
866 self.client.ssl_version = ssl.PROTOCOL_TLSv1
867
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000868 def test_context(self):
869 self.client.quit()
870 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
871 self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
872 context=ctx)
873 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
874 context=ctx)
875 self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
876 keyfile=CERTFILE, context=ctx)
877
Giampaolo Rodola'842e5672011-05-07 18:47:31 +0200878 self.client = ftplib.FTP_TLS(context=ctx, timeout=2)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000879 self.client.connect(self.server.host, self.server.port)
880 self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
881 self.client.auth()
882 self.assertIs(self.client.sock.context, ctx)
883 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
884
885 self.client.prot_p()
Brett Cannon918e2d42010-10-29 23:26:25 +0000886 with self.client.transfercmd('list') as sock:
887 self.assertIs(sock.context, ctx)
888 self.assertIsInstance(sock, ssl.SSLSocket)
Giampaolo Rodolàa67299e2010-05-26 18:06:04 +0000889
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200890 def test_ccc(self):
891 self.assertRaises(ValueError, self.client.ccc)
892 self.client.login(secure=True)
893 self.assertIsInstance(self.client.sock, ssl.SSLSocket)
894 self.client.ccc()
895 self.assertRaises(ValueError, self.client.sock.unwrap)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +0200896
Antoine Pitrouf988cd02009-11-17 20:21:14 +0000897
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000898class TestTimeouts(TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899
900 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901 self.evt = threading.Event()
Christian Heimes5e696852008-04-09 08:37:03 +0000902 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100903 self.sock.settimeout(20)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000904 self.port = support.bind_port(self.sock)
Antoine Pitrou08d02722012-12-19 20:44:02 +0100905 self.server_thread = threading.Thread(target=self.server)
906 self.server_thread.start()
Christian Heimes836baa52008-02-26 08:18:30 +0000907 # Wait for the server to be ready.
908 self.evt.wait()
909 self.evt.clear()
Antoine Pitrou08d02722012-12-19 20:44:02 +0100910 self.old_port = ftplib.FTP.port
Christian Heimes5e696852008-04-09 08:37:03 +0000911 ftplib.FTP.port = self.port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000912
913 def tearDown(self):
Antoine Pitrou08d02722012-12-19 20:44:02 +0100914 ftplib.FTP.port = self.old_port
915 self.server_thread.join()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000916
Antoine Pitrou08d02722012-12-19 20:44:02 +0100917 def server(self):
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000918 # This method sets the evt 3 times:
919 # 1) when the connection is ready to be accepted.
920 # 2) when it is safe for the caller to close the connection
921 # 3) when we have closed the socket
Antoine Pitrou08d02722012-12-19 20:44:02 +0100922 self.sock.listen(5)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000923 # (1) Signal the caller that we are ready to accept the connection.
Antoine Pitrou08d02722012-12-19 20:44:02 +0100924 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000925 try:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100926 conn, addr = self.sock.accept()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000927 except socket.timeout:
928 pass
929 else:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100930 conn.sendall(b"1 Hola mundo\n")
931 conn.shutdown(socket.SHUT_WR)
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000932 # (2) Signal the caller that it is safe to close the socket.
Antoine Pitrou08d02722012-12-19 20:44:02 +0100933 self.evt.set()
Benjamin Petersonbe17a112008-09-27 21:49:47 +0000934 conn.close()
935 finally:
Antoine Pitrou08d02722012-12-19 20:44:02 +0100936 self.sock.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937
938 def testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000939 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000940 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000941 socket.setdefaulttimeout(30)
942 try:
943 ftp = ftplib.FTP("localhost")
944 finally:
945 socket.setdefaulttimeout(None)
946 self.assertEqual(ftp.sock.gettimeout(), 30)
947 self.evt.wait()
948 ftp.close()
949
950 def testTimeoutNone(self):
951 # no timeout -- do not use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000952 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000953 socket.setdefaulttimeout(30)
954 try:
955 ftp = ftplib.FTP("localhost", timeout=None)
956 finally:
957 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000958 self.assertTrue(ftp.sock.gettimeout() is None)
Christian Heimes836baa52008-02-26 08:18:30 +0000959 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000960 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000961
962 def testTimeoutValue(self):
963 # a value
Christian Heimes5e696852008-04-09 08:37:03 +0000964 ftp = ftplib.FTP(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000966 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000967 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968
969 def testTimeoutConnect(self):
970 ftp = ftplib.FTP()
Christian Heimes5e696852008-04-09 08:37:03 +0000971 ftp.connect(HOST, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000973 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000974 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000975
976 def testTimeoutDifferentOrder(self):
977 ftp = ftplib.FTP(timeout=30)
Christian Heimes5e696852008-04-09 08:37:03 +0000978 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000980 self.evt.wait()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000981 ftp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000982
983 def testTimeoutDirectAccess(self):
984 ftp = ftplib.FTP()
985 ftp.timeout = 30
Christian Heimes5e696852008-04-09 08:37:03 +0000986 ftp.connect(HOST)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000987 self.assertEqual(ftp.sock.gettimeout(), 30)
Christian Heimes836baa52008-02-26 08:18:30 +0000988 self.evt.wait()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989 ftp.close()
990
991
R David Murray87632f12013-02-19 18:32:28 -0500992class TestNetrcDeprecation(TestCase):
993
994 def test_deprecation(self):
995 with support.temp_cwd(), support.EnvironmentVarGuard() as env:
996 env['HOME'] = os.getcwd()
997 open('.netrc', 'w').close()
998 with self.assertWarns(DeprecationWarning):
999 ftplib.Netrc()
1000
1001
1002
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001003def test_main():
R David Murray87632f12013-02-19 18:32:28 -05001004 tests = [TestFTPClass, TestTimeouts, TestNetrcDeprecation]
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +02001005 if support.IPV6_ENABLED:
Victor Stinnerc90e19d2011-05-01 01:23:03 +02001006 tests.append(TestIPv6Environment)
Antoine Pitrouf988cd02009-11-17 20:21:14 +00001007
1008 if ssl is not None:
1009 tests.extend([TestTLS_FTPClassMixin, TestTLS_FTPClass])
1010
Benjamin Petersonbe17a112008-09-27 21:49:47 +00001011 thread_info = support.threading_setup()
1012 try:
1013 support.run_unittest(*tests)
1014 finally:
1015 support.threading_cleanup(*thread_info)
1016
Guido van Rossumd8faa362007-04-27 19:54:29 +00001017
1018if __name__ == '__main__':
1019 test_main()