blob: 7e8dce638b114ede8766f6ca248fedf84bf45df1 [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]
93 ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
94 self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
95 conn, addr = sock.accept()
96 self.dtp = DummyDTPHandler(conn, baseclass=self)
97
98 def cmd_eprt(self, arg):
99 af, ip, port = arg.split(arg[0])[1:-1]
100 port = int(port)
101 s = socket.create_connection((ip, port), timeout=2)
102 self.dtp = DummyDTPHandler(s, baseclass=self)
103 self.push('200 active data connection established')
104
105 def cmd_epsv(self, arg):
106 sock = socket.socket(socket.AF_INET6)
107 sock.bind((self.socket.getsockname()[0], 0))
108 sock.listen(5)
109 sock.settimeout(2)
110 port = sock.getsockname()[1]
111 self.push('229 entering extended passive mode (|||%d|)' %port)
112 conn, addr = sock.accept()
113 self.dtp = DummyDTPHandler(conn, baseclass=self)
114
115 def cmd_echo(self, arg):
116 # sends back the received string (used by the test suite)
117 self.push(arg)
118
119 def cmd_user(self, arg):
120 self.push('331 username ok')
121
122 def cmd_pass(self, arg):
123 self.push('230 password ok')
124
125 def cmd_acct(self, arg):
126 self.push('230 acct ok')
127
128 def cmd_rnfr(self, arg):
129 self.push('350 rnfr ok')
130
131 def cmd_rnto(self, arg):
132 self.push('250 rnto ok')
133
134 def cmd_dele(self, arg):
135 self.push('250 dele ok')
136
137 def cmd_cwd(self, arg):
138 self.push('250 cwd ok')
139
140 def cmd_size(self, arg):
141 self.push('250 1000')
142
143 def cmd_mkd(self, arg):
144 self.push('257 "%s"' %arg)
145
146 def cmd_rmd(self, arg):
147 self.push('250 rmd ok')
148
149 def cmd_pwd(self, arg):
150 self.push('257 "pwd ok"')
151
152 def cmd_type(self, arg):
153 self.push('200 type ok')
154
155 def cmd_quit(self, arg):
156 self.push('221 quit ok')
157 self.close()
158
159 def cmd_stor(self, arg):
160 self.push('125 stor ok')
161
162 def cmd_retr(self, arg):
163 self.push('125 retr ok')
164 self.dtp.push(RETR_DATA)
165 self.dtp.close_when_done()
166
167 def cmd_list(self, arg):
168 self.push('125 list ok')
169 self.dtp.push(LIST_DATA)
170 self.dtp.close_when_done()
171
172 def cmd_nlst(self, arg):
173 self.push('125 nlst ok')
174 self.dtp.push(NLST_DATA)
175 self.dtp.close_when_done()
176
177
178class DummyFTPServer(asyncore.dispatcher, threading.Thread):
179
180 handler = DummyFTPHandler
181
182 def __init__(self, address, af=socket.AF_INET):
183 threading.Thread.__init__(self)
184 asyncore.dispatcher.__init__(self)
185 self.create_socket(af, socket.SOCK_STREAM)
186 self.bind(address)
187 self.listen(5)
188 self.active = False
189 self.active_lock = threading.Lock()
190 self.host, self.port = self.socket.getsockname()[:2]
191
192 def start(self):
193 assert not self.active
194 self.__flag = threading.Event()
195 threading.Thread.start(self)
196 self.__flag.wait()
197
198 def run(self):
199 self.active = True
200 self.__flag.set()
201 while self.active and asyncore.socket_map:
202 self.active_lock.acquire()
203 asyncore.loop(timeout=0.1, count=1)
204 self.active_lock.release()
205 asyncore.close_all(ignore_all=True)
206
207 def stop(self):
208 assert self.active
209 self.active = False
210 self.join()
211
212 def handle_accept(self):
213 conn, addr = self.accept()
214 self.handler = self.handler(conn)
215
216 def writable(self):
217 return 0
218
219 def handle_error(self):
220 raise
221
222
223class TestFTPClass(TestCase):
224
225 def setUp(self):
226 self.server = DummyFTPServer((HOST, 0))
227 self.server.start()
228 self.client = ftplib.FTP(timeout=2)
229 self.client.connect(self.server.host, self.server.port)
230
231 def tearDown(self):
232 self.client.close()
233 self.server.stop()
234
235 def test_getwelcome(self):
236 self.assertEqual(self.client.getwelcome(), '220 welcome')
237
238 def test_sanitize(self):
239 self.assertEqual(self.client.sanitize('foo'), repr('foo'))
240 self.assertEqual(self.client.sanitize('pass 12345'), repr('pass *****'))
241 self.assertEqual(self.client.sanitize('PASS 12345'), repr('PASS *****'))
242
243 def test_exceptions(self):
244 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 400')
245 self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'echo 499')
246 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 500')
247 self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'echo 599')
248 self.assertRaises(ftplib.error_proto, self.client.sendcmd, 'echo 999')
249
250 def test_all_errors(self):
251 exceptions = (ftplib.error_reply, ftplib.error_temp, ftplib.error_perm,
252 ftplib.error_proto, ftplib.Error, IOError, EOFError)
253 for x in exceptions:
254 try:
255 raise x('exception not included in all_errors set')
256 except ftplib.all_errors:
257 pass
258
259 def test_set_pasv(self):
260 # passive mode is supposed to be enabled by default
261 self.assertTrue(self.client.passiveserver)
262 self.client.set_pasv(True)
263 self.assertTrue(self.client.passiveserver)
264 self.client.set_pasv(False)
265 self.assertFalse(self.client.passiveserver)
266
267 def test_voidcmd(self):
268 self.client.voidcmd('echo 200')
269 self.client.voidcmd('echo 299')
270 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 199')
271 self.assertRaises(ftplib.error_reply, self.client.voidcmd, 'echo 300')
272
273 def test_login(self):
274 self.client.login()
275
276 def test_acct(self):
277 self.client.acct('passwd')
278
279 def test_rename(self):
280 self.client.rename('a', 'b')
281 self.server.handler.next_response = '200'
282 self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
283
284 def test_delete(self):
285 self.client.delete('foo')
286 self.server.handler.next_response = '199'
287 self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
288
289 def test_size(self):
290 self.client.size('foo')
291
292 def test_mkd(self):
293 dir = self.client.mkd('/foo')
294 self.assertEqual(dir, '/foo')
295
296 def test_rmd(self):
297 self.client.rmd('foo')
298
299 def test_pwd(self):
300 dir = self.client.pwd()
301 self.assertEqual(dir, 'pwd ok')
302
303 def test_quit(self):
304 self.assertEqual(self.client.quit(), '221 quit ok')
305 # Ensure the connection gets closed; sock attribute should be None
306 self.assertEqual(self.client.sock, None)
307
308 def test_retrbinary(self):
309 received = []
310 self.client.retrbinary('retr', received.append)
311 self.assertEqual(''.join(received), RETR_DATA)
312
313 def test_retrlines(self):
314 received = []
315 self.client.retrlines('retr', received.append)
316 self.assertEqual(''.join(received), RETR_DATA.replace('\r\n', ''))
317
318 def test_storbinary(self):
319 f = StringIO.StringIO(RETR_DATA)
320 self.client.storbinary('stor', f)
321 self.assertEqual(self.server.handler.last_received_data, RETR_DATA)
322 # test new callback arg
323 flag = []
324 f.seek(0)
325 self.client.storbinary('stor', f, callback=lambda x: flag.append(None))
326 self.assertTrue(flag)
327
328 def test_storlines(self):
329 f = StringIO.StringIO(RETR_DATA.replace('\r\n', '\n'))
330 self.client.storlines('stor', f)
331 self.assertEqual(self.server.handler.last_received_data, RETR_DATA)
332 # test new callback arg
333 flag = []
334 f.seek(0)
335 self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
336 self.assertTrue(flag)
337
338 def test_nlst(self):
339 self.client.nlst()
340 self.assertEqual(self.client.nlst(), NLST_DATA.split('\r\n')[:-1])
341
342 def test_dir(self):
343 l = []
344 self.client.dir(lambda x: l.append(x))
345 self.assertEqual(''.join(l), LIST_DATA.replace('\r\n', ''))
346
347 def test_makeport(self):
348 self.client.makeport()
349 # IPv4 is in use, just make sure send_eprt has not been used
350 self.assertEqual(self.server.handler.last_received_cmd, 'port')
351
352 def test_makepasv(self):
353 host, port = self.client.makepasv()
354 conn = socket.create_connection((host, port), 2)
Facundo Batista93c33682007-03-30 13:00:35 +0000355 conn.close()
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000356 # IPv4 is in use, just make sure send_epsv has not been used
357 self.assertEqual(self.server.handler.last_received_cmd, 'pasv')
Facundo Batista3f100992007-03-26 20:56:09 +0000358
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000359
360class TestIPv6Environment(TestCase):
361
362 def setUp(self):
363 self.server = DummyFTPServer((HOST, 0), af=socket.AF_INET6)
364 self.server.start()
365 self.client = ftplib.FTP()
366 self.client.connect(self.server.host, self.server.port)
367
368 def tearDown(self):
369 self.client.close()
370 self.server.stop()
371
372 def test_af(self):
373 self.assertEqual(self.client.af, socket.AF_INET6)
374
375 def test_makeport(self):
376 self.client.makeport()
377 self.assertEqual(self.server.handler.last_received_cmd, 'eprt')
378
379 def test_makepasv(self):
380 host, port = self.client.makepasv()
381 conn = socket.create_connection((host, port), 2)
382 conn.close()
383 self.assertEqual(self.server.handler.last_received_cmd, 'epsv')
384
385 def test_transfer(self):
386 def retr():
387 received = []
388 self.client.retrbinary('retr', received.append)
389 self.assertEqual(''.join(received), RETR_DATA)
390 self.client.set_pasv(True)
391 retr()
392 self.client.set_pasv(False)
393 retr()
394
395
396class TestTimeouts(TestCase):
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000397
Facundo Batista3f100992007-03-26 20:56:09 +0000398 def setUp(self):
Facundo Batista3f100992007-03-26 20:56:09 +0000399 self.evt = threading.Event()
Trent Nelsone41b0062008-04-08 23:47:30 +0000400 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
401 self.sock.settimeout(3)
402 self.port = test_support.bind_port(self.sock)
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000403 threading.Thread(target=self.server, args=(self.evt,self.sock)).start()
Neal Norwitzb0917c12008-02-26 04:50:37 +0000404 # Wait for the server to be ready.
405 self.evt.wait()
406 self.evt.clear()
Trent Nelsone41b0062008-04-08 23:47:30 +0000407 ftplib.FTP.port = self.port
Facundo Batista3f100992007-03-26 20:56:09 +0000408
409 def tearDown(self):
410 self.evt.wait()
411
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000412 def server(self, evt, serv):
413 # This method sets the evt 3 times:
414 # 1) when the connection is ready to be accepted.
415 # 2) when it is safe for the caller to close the connection
416 # 3) when we have closed the socket
417 serv.listen(5)
418 # (1) Signal the caller that we are ready to accept the connection.
419 evt.set()
420 try:
421 conn, addr = serv.accept()
422 except socket.timeout:
423 pass
424 else:
425 conn.send("1 Hola mundo\n")
426 # (2) Signal the caller that it is safe to close the socket.
427 evt.set()
428 conn.close()
429 finally:
430 serv.close()
431 # (3) Signal the caller that we are done.
432 evt.set()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000433
Facundo Batista3f100992007-03-26 20:56:09 +0000434 def testTimeoutDefault(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000435 # default -- use global socket timeout
436 self.assert_(socket.getdefaulttimeout() is None)
437 socket.setdefaulttimeout(30)
438 try:
439 ftp = ftplib.FTP("localhost")
440 finally:
441 socket.setdefaulttimeout(None)
442 self.assertEqual(ftp.sock.gettimeout(), 30)
443 self.evt.wait()
444 ftp.close()
445
446 def testTimeoutNone(self):
447 # no timeout -- do not use global socket timeout
448 self.assert_(socket.getdefaulttimeout() is None)
449 socket.setdefaulttimeout(30)
450 try:
451 ftp = ftplib.FTP("localhost", timeout=None)
452 finally:
453 socket.setdefaulttimeout(None)
Facundo Batista3f100992007-03-26 20:56:09 +0000454 self.assertTrue(ftp.sock.gettimeout() is None)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000455 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000456 ftp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000457
Facundo Batista3f100992007-03-26 20:56:09 +0000458 def testTimeoutValue(self):
459 # a value
Trent Nelsone41b0062008-04-08 23:47:30 +0000460 ftp = ftplib.FTP(HOST, timeout=30)
Facundo Batista3f100992007-03-26 20:56:09 +0000461 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000462 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000463 ftp.close()
Facundo Batista3f100992007-03-26 20:56:09 +0000464
Facundo Batista93c33682007-03-30 13:00:35 +0000465 def testTimeoutConnect(self):
466 ftp = ftplib.FTP()
Trent Nelsone41b0062008-04-08 23:47:30 +0000467 ftp.connect(HOST, timeout=30)
Facundo Batista93c33682007-03-30 13:00:35 +0000468 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000469 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000470 ftp.close()
Facundo Batista93c33682007-03-30 13:00:35 +0000471
472 def testTimeoutDifferentOrder(self):
473 ftp = ftplib.FTP(timeout=30)
Trent Nelsone41b0062008-04-08 23:47:30 +0000474 ftp.connect(HOST)
Facundo Batista93c33682007-03-30 13:00:35 +0000475 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000476 self.evt.wait()
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000477 ftp.close()
Facundo Batista93c33682007-03-30 13:00:35 +0000478
479 def testTimeoutDirectAccess(self):
480 ftp = ftplib.FTP()
481 ftp.timeout = 30
Trent Nelsone41b0062008-04-08 23:47:30 +0000482 ftp.connect(HOST)
Facundo Batista93c33682007-03-30 13:00:35 +0000483 self.assertEqual(ftp.sock.gettimeout(), 30)
Neal Norwitzb0917c12008-02-26 04:50:37 +0000484 self.evt.wait()
Facundo Batista3f100992007-03-26 20:56:09 +0000485 ftp.close()
486
487
Benjamin Peterson3c0c4832008-09-27 02:49:54 +0000488def test_main():
489 tests = [TestFTPClass, TestTimeouts]
490 if socket.has_ipv6:
491 try:
492 DummyFTPServer((HOST, 0), af=socket.AF_INET6)
493 except socket.error:
494 pass
495 else:
496 tests.append(TestIPv6Environment)
497 thread_info = test_support.threading_setup()
498 try:
499 test_support.run_unittest(*tests)
500 finally:
501 test_support.threading_cleanup(*thread_info)
502
Facundo Batista3f100992007-03-26 20:56:09 +0000503
504if __name__ == '__main__':
505 test_main()