blob: 1c2ceeb87282ee5345ebdfd72f7fea38d9e08d23 [file] [log] [blame]
Benjamin Peterson3c0c4832008-09-27 02:49:54 +00001"""Test script for ftplib module."""
2
3# Modified by Giampaolo Rodola' to test FTP class and IPv6 environment
4
Facundo Batista3f100992007-03-26 20:56:09 +00005import ftplib
Benjamin Peterson3c0c4832008-09-27 02:49:54 +00006import threading
7import asyncore
8import asynchat
9import socket
10import StringIO
Facundo Batista3f100992007-03-26 20:56:09 +000011
12from unittest import TestCase
13from test import test_support
Benjamin Peterson3c0c4832008-09-27 02:49:54 +000014from test.test_support import HOST
Facundo Batista3f100992007-03-26 20:56:09 +000015
Neal Norwitzb0917c12008-02-26 04:50:37 +000016
Benjamin Peterson3c0c4832008-09-27 02:49:54 +000017# the dummy data returned by server over the data channel when
18# RETR, LIST and NLST commands are issued
19RETR_DATA = 'abcde12345\r\n' * 1000
20LIST_DATA = 'foo\r\nbar\r\n'
21NLST_DATA = 'foo\r\nbar\r\n'
22
23
24class DummyDTPHandler(asynchat.async_chat):
25
26 def __init__(self, conn, baseclass):
27 asynchat.async_chat.__init__(self, conn)
28 self.baseclass = baseclass
29 self.baseclass.last_received_data = ''
30
31 def handle_read(self):
32 self.baseclass.last_received_data += self.recv(1024)
33
34 def handle_close(self):
35 self.baseclass.push('226 transfer complete')
36 self.close()
37
38
39class DummyFTPHandler(asynchat.async_chat):
40
41 def __init__(self, conn):
42 asynchat.async_chat.__init__(self, conn)
43 self.set_terminator("\r\n")
44 self.in_buffer = []
45 self.dtp = None
46 self.last_received_cmd = None
47 self.last_received_data = ''
48 self.next_response = ''
49 self.push('220 welcome')
50
51 def collect_incoming_data(self, data):
52 self.in_buffer.append(data)
53
54 def found_terminator(self):
55 line = ''.join(self.in_buffer)
56 self.in_buffer = []
57 if self.next_response:
58 self.push(self.next_response)
59 self.next_response = ''
60 cmd = line.split(' ')[0].lower()
61 self.last_received_cmd = cmd
62 space = line.find(' ')
63 if space != -1:
64 arg = line[space + 1:]
65 else:
66 arg = ""
67 if hasattr(self, 'cmd_' + cmd):
68 method = getattr(self, 'cmd_' + cmd)
69 method(arg)
70 else:
71 self.push('550 command "%s" not understood.' %cmd)
72
73 def handle_error(self):
74 raise
75
76 def push(self, data):
77 asynchat.async_chat.push(self, data + '\r\n')
78
79 def cmd_port(self, arg):
80 addr = map(int, arg.split(','))
81 ip = '%d.%d.%d.%d' %tuple(addr[:4])
82 port = (addr[4] * 256) + addr[5]
83 s = socket.create_connection((ip, port), timeout=2)
84 self.dtp = DummyDTPHandler(s, baseclass=self)
85 self.push('200 active data connection established')
86
87 def cmd_pasv(self, arg):
88 sock = socket.socket()
89 sock.bind((self.socket.getsockname()[0], 0))
90 sock.listen(5)
91 sock.settimeout(2)
92 ip, port = sock.getsockname()[:2]
Ezio Melotti3efafd72010-08-02 18:40:55 +000093 ip = ip.replace('.', ',')
94 p1, p2 = divmod(port, 256)
Benjamin Peterson3c0c4832008-09-27 02:49:54 +000095 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
96 conn, addr = sock.accept()
97 self.dtp = DummyDTPHandler(conn, baseclass=self)
98
99 def cmd_eprt(self, arg):
100 af, ip, port = arg.split(arg[0])[1:-1]
101 port = int(port)
102 s = socket.create_connection((ip, port), timeout=2)
103 self.dtp = DummyDTPHandler(s, baseclass=self)
104 self.push('200 active data connection established')
105
106 def cmd_epsv(self, arg):
107 sock = socket.socket(socket.AF_INET6)
108 sock.bind((self.socket.getsockname()[0], 0))
109 sock.listen(5)
110 sock.settimeout(2)
111 port = sock.getsockname()[1]
112 self.push('229 entering extended passive mode (|||%d|)' %port)
113 conn, addr = sock.accept()
114 self.dtp = DummyDTPHandler(conn, baseclass=self)
115
116 def cmd_echo(self, arg):
117 # sends back the received string (used by the test suite)
118 self.push(arg)
119
120 def cmd_user(self, arg):
121 self.push('331 username ok')
122
123 def cmd_pass(self, arg):
124 self.push('230 password ok')
125
126 def cmd_acct(self, arg):
127 self.push('230 acct ok')
128
129 def cmd_rnfr(self, arg):
130 self.push('350 rnfr ok')
131
132 def cmd_rnto(self, arg):
133 self.push('250 rnto ok')
134
135 def cmd_dele(self, arg):
136 self.push('250 dele ok')
137
138 def cmd_cwd(self, arg):
139 self.push('250 cwd ok')
140
141 def cmd_size(self, arg):
142 self.push('250 1000')
143
144 def cmd_mkd(self, arg):
145 self.push('257 "%s"' %arg)
146
147 def cmd_rmd(self, arg):
148 self.push('250 rmd ok')
149
150 def cmd_pwd(self, arg):
151 self.push('257 "pwd ok"')
152
153 def cmd_type(self, arg):
154 self.push('200 type ok')
155
156 def cmd_quit(self, arg):
157 self.push('221 quit ok')
158 self.close()
159
160 def cmd_stor(self, arg):
161 self.push('125 stor ok')
162
163 def cmd_retr(self, arg):
164 self.push('125 retr ok')
165 self.dtp.push(RETR_DATA)
166 self.dtp.close_when_done()
167
168 def cmd_list(self, arg):
169 self.push('125 list ok')
170 self.dtp.push(LIST_DATA)
171 self.dtp.close_when_done()
172
173 def cmd_nlst(self, arg):
174 self.push('125 nlst ok')
175 self.dtp.push(NLST_DATA)
176 self.dtp.close_when_done()
177
178
179class DummyFTPServer(asyncore.dispatcher, threading.Thread):
180
181 handler = DummyFTPHandler
182
183 def __init__(self, address, af=socket.AF_INET):
184 threading.Thread.__init__(self)
185 asyncore.dispatcher.__init__(self)
186 self.create_socket(af, socket.SOCK_STREAM)
187 self.bind(address)
188 self.listen(5)
189 self.active = False
190 self.active_lock = threading.Lock()
191 self.host, self.port = self.socket.getsockname()[:2]
192
193 def start(self):
194 assert not self.active
195 self.__flag = threading.Event()
196 threading.Thread.start(self)
197 self.__flag.wait()
198
199 def run(self):
200 self.active = True
201 self.__flag.set()
202 while self.active and asyncore.socket_map:
203 self.active_lock.acquire()
204 asyncore.loop(timeout=0.1, count=1)
205 self.active_lock.release()
206 asyncore.close_all(ignore_all=True)
207
208 def stop(self):
209 assert self.active
210 self.active = False
211 self.join()
212
213 def handle_accept(self):
214 conn, addr = self.accept()
215 self.handler = self.handler(conn)
Benjamin Petersone14267b2008-09-28 20:57:21 +0000216 self.close()
217
218 def handle_connect(self):
219 self.close()
220 handle_read = handle_connect
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000221
222 def writable(self):
223 return 0
224
225 def handle_error(self):
226 raise
227
228
229class TestFTPClass(TestCase):
230
231 def setUp(self):
232 self.server = DummyFTPServer((HOST, 0))
233 self.server.start()
234 self.client = ftplib.FTP(timeout=2)
235 self.client.connect(self.server.host, self.server.port)
236
237 def tearDown(self):
238 self.client.close()
239 self.server.stop()
240
241 def test_getwelcome(self):
242 self.assertEqual(self.client.getwelcome(), '220 welcome')
243
244 def test_sanitize(self):
245 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
246 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
247 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
248
249 def test_exceptions(self):
250 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
251 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
252 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
253 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
254 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
255
256 def test_all_errors(self):
257 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
258 ftplib.error_proto, ftplib.Error, IOError, EOFError)
259 for x in exceptions:
260 try:
261 raise x('exception not included in all_errors set')
262 except ftplib.all_errors:
263 pass
264
265 def test_set_pasv(self):
266 # passive mode is supposed to be enabled by default
267 self.assertTrue(self.client.passiveserver)
268 self.client.set_pasv(True)
269 self.assertTrue(self.client.passiveserver)
270 self.client.set_pasv(False)
271 self.assertFalse(self.client.passiveserver)
272
273 def test_voidcmd(self):
274 self.client.voidcmd('echo 200')
275 self.client.voidcmd('echo 299')
276 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
277 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
278
279 def test_login(self):
280 self.client.login()
281
282 def test_acct(self):
283 self.client.acct('passwd')
284
285 def test_rename(self):
286 self.client.rename('a', 'b')
287 self.server.handler.next_response = '200'
288 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
289
290 def test_delete(self):
291 self.client.delete('foo')
292 self.server.handler.next_response = '199'
293 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
294
295 def test_size(self):
296 self.client.size('foo')
297
298 def test_mkd(self):
299 dir = self.client.mkd('/foo')
300 self.assertEqual(dir, '/foo')
301
302 def test_rmd(self):
303 self.client.rmd('foo')
304
305 def test_pwd(self):
306 dir = self.client.pwd()
307 self.assertEqual(dir, 'pwd ok')
308
309 def test_quit(self):
310 self.assertEqual(self.client.quit(), '221 quit ok')
311 # Ensure the connection gets closed; sock attribute should be None
312 self.assertEqual(self.client.sock, None)
313
314 def test_retrbinary(self):
315 received = []
316 self.client.retrbinary('retr', received.append)
317 self.assertEqual(''.join(received), RETR_DATA)
318
319 def test_retrlines(self):
320 received = []
321 self.client.retrlines('retr', received.append)
322 self.assertEqual(''.join(received), RETR_DATA.replace('\r\n', ''))
323
324 def test_storbinary(self):
325 f = StringIO.StringIO(RETR_DATA)
326 self.client.storbinary('stor', f)
327 self.assertEqual(self.server.handler.last_received_data, RETR_DATA)
328 # test new callback arg
329 flag = []
330 f.seek(0)
331 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
332 self.assertTrue(flag)
333
334 def test_storlines(self):
335 f = StringIO.StringIO(RETR_DATA.replace('\r\n', '\n'))
336 self.client.storlines('stor', f)
337 self.assertEqual(self.server.handler.last_received_data, RETR_DATA)
338 # test new callback arg
339 flag = []
340 f.seek(0)
341 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
342 self.assertTrue(flag)
343
344 def test_nlst(self):
345 self.client.nlst()
346 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
347
348 def test_dir(self):
349 l = []
350 self.client.dir(lambda x: l.append(x))
351 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
352
353 def test_makeport(self):
354 self.client.makeport()
355 # IPv4 is in use, just make sure send_eprt has not been used
356 self.assertEqual(self.server.handler.last_received_cmd, 'port')
357
358 def test_makepasv(self):
359 host, port = self.client.makepasv()
360 conn = socket.create_connection((host, port), 2)
Facundo Batista93c33682007-03-30 13:00:35 +0000361 conn.close()
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000362 # IPv4 is in use, just make sure send_epsv has not been used
363 self.assertEqual(self.server.handler.last_received_cmd, 'pasv')
Facundo Batista3f100992007-03-26 20:56:09 +0000364
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000365
366class TestIPv6Environment(TestCase):
367
368 def setUp(self):
369 self.server = DummyFTPServer((HOST, 0), af=socket.AF_INET6)
370 self.server.start()
371 self.client = ftplib.FTP()
372 self.client.connect(self.server.host, self.server.port)
373
374 def tearDown(self):
375 self.client.close()
376 self.server.stop()
377
378 def test_af(self):
379 self.assertEqual(self.client.af, socket.AF_INET6)
380
381 def test_makeport(self):
382 self.client.makeport()
383 self.assertEqual(self.server.handler.last_received_cmd, 'eprt')
384
385 def test_makepasv(self):
386 host, port = self.client.makepasv()
387 conn = socket.create_connection((host, port), 2)
388 conn.close()
389 self.assertEqual(self.server.handler.last_received_cmd, 'epsv')
390
391 def test_transfer(self):
392 def retr():
393 received = []
394 self.client.retrbinary('retr', received.append)
395 self.assertEqual(''.join(received), RETR_DATA)
396 self.client.set_pasv(True)
397 retr()
398 self.client.set_pasv(False)
399 retr()
400
401
402class TestTimeouts(TestCase):
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000403
Facundo Batista3f100992007-03-26 20:56:09 +0000404 def setUp(self):
Facundo Batista3f100992007-03-26 20:56:09 +0000405 self.evt = threading.Event()
Trent Nelsone41b0062008-04-08 23:47:30 +0000406 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
407 self.sock.settimeout(3)
408 self.port = test_support.bind_port(self.sock)
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000409 threading.Thread(target=self.server, args=(self.evt,self.sock)).start()
Neal Norwitzb0917c12008-02-26 04:50:37 +0000410 # Wait for the server to be ready.
411 self.evt.wait()
412 self.evt.clear()
Trent Nelsone41b0062008-04-08 23:47:30 +0000413 ftplib.FTP.port = self.port
Facundo Batista3f100992007-03-26 20:56:09 +0000414
415 def tearDown(self):
416 self.evt.wait()
417
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000418 def server(self, evt, serv):
419 # This method sets the evt 3 times:
420 # 1) when the connection is ready to be accepted.
421 # 2) when it is safe for the caller to close the connection
422 # 3) when we have closed the socket
423 serv.listen(5)
424 # (1) Signal the caller that we are ready to accept the connection.
425 evt.set()
426 try:
427 conn, addr = serv.accept()
428 except socket.timeout:
429 pass
430 else:
431 conn.send("1 Hola mundo\n")
432 # (2) Signal the caller that it is safe to close the socket.
433 evt.set()
434 conn.close()
435 finally:
436 serv.close()
437 # (3) Signal the caller that we are done.
438 evt.set()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000439
Facundo Batista3f100992007-03-26 20:56:09 +0000440 def testTimeoutDefault(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000441 # default -- use global socket timeout
442 self.assert_(socket.getdefaulttimeout() is None)
443 socket.setdefaulttimeout(30)
444 try:
445 ftp = ftplib.FTP("localhost")
446 finally:
447 socket.setdefaulttimeout(None)
448 self.assertEqual(ftp.sock.gettimeout(), 30)
449 self.evt.wait()
450 ftp.close()
451
452 def testTimeoutNone(self):
453 # no timeout -- do not use global socket timeout
454 self.assert_(socket.getdefaulttimeout() is None)
455 socket.setdefaulttimeout(30)
456 try:
457 ftp = ftplib.FTP("localhost", timeout=None)
458 finally:
459 socket.setdefaulttimeout(None)
Facundo Batista3f100992007-03-26 20:56:09 +0000460 self.assertTrue(ftp.sock.gettimeout() is None)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000461 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000462 ftp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000463
Facundo Batista3f100992007-03-26 20:56:09 +0000464 def testTimeoutValue(self):
465 # a value
Trent Nelsone41b0062008-04-08 23:47:30 +0000466 ftp = ftplib.FTP(HOST, timeout=30)
Facundo Batista3f100992007-03-26 20:56:09 +0000467 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000468 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000469 ftp.close()
Facundo Batista3f100992007-03-26 20:56:09 +0000470
Facundo Batista93c33682007-03-30 13:00:35 +0000471 def testTimeoutConnect(self):
472 ftp = ftplib.FTP()
Trent Nelsone41b0062008-04-08 23:47:30 +0000473 ftp.connect(HOST, timeout=30)
Facundo Batista93c33682007-03-30 13:00:35 +0000474 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000475 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000476 ftp.close()
Facundo Batista93c33682007-03-30 13:00:35 +0000477
478 def testTimeoutDifferentOrder(self):
479 ftp = ftplib.FTP(timeout=30)
Trent Nelsone41b0062008-04-08 23:47:30 +0000480 ftp.connect(HOST)
Facundo Batista93c33682007-03-30 13:00:35 +0000481 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000482 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000483 ftp.close()
Facundo Batista93c33682007-03-30 13:00:35 +0000484
485 def testTimeoutDirectAccess(self):
486 ftp = ftplib.FTP()
487 ftp.timeout = 30
Trent Nelsone41b0062008-04-08 23:47:30 +0000488 ftp.connect(HOST)
Facundo Batista93c33682007-03-30 13:00:35 +0000489 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000490 self.evt.wait()
Facundo Batista3f100992007-03-26 20:56:09 +0000491 ftp.close()
492
493
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000494def test_main():
495 tests = [TestFTPClass, TestTimeouts]
496 if socket.has_ipv6:
497 try:
498 DummyFTPServer((HOST, 0), af=socket.AF_INET6)
499 except socket.error:
500 pass
501 else:
502 tests.append(TestIPv6Environment)
503 thread_info = test_support.threading_setup()
504 try:
505 test_support.run_unittest(*tests)
506 finally:
507 test_support.threading_cleanup(*thread_info)
508
Facundo Batista3f100992007-03-26 20:56:09 +0000509
510if __name__ == '__main__':
511 test_main()