source: test/mock_ftplib.py @ 1284:25228b207849

Last change on this file since 1284:25228b207849 was 1284:25228b207849, checked in by Stefan Schwarzer <sschwarzer@…>, 7 years ago
Added tests for string type handling for `chdir` and `listdir`. TODO: A bytes argument for `listdir` doesn't work yet. TODO: String type tests for `path.join` and `path.split*`.
File size: 8.6 KB
Line 
1# encoding: utf-8
2# Copyright (C) 2003-2013, Stefan Schwarzer <sschwarzer@sschwarzer.net>
3# See the file LICENSE for licensing terms.
4
5"""
6This module implements a mock version of the standard library's
7`ftplib.py` module. Some code is taken from there.
8
9Not all functionality is implemented, only what is needed to run the
10unit tests.
11"""
12
13from __future__ import unicode_literals
14
15import io
16import collections
17import ftplib
18import posixpath
19
20import ftputil.tool
21
22
23DEBUG = 0
24
25# Use a global dictionary of the form `{path: `MockFile` object, ...}`
26# to make "remote" mock files that were generated during a test
27# accessible. For example, this is used for testing the contents of a
28# file after an `FTPHost.upload` call.
29mock_files = {}
30
31def content_of(path):
32    """
33    Return the data stored in a mock remote file identified by `path`.
34    """
35    return mock_files[path].getvalue()
36
37
38class MockFile(io.BytesIO, object):
39    """
40    Mock class for the file objects _contained in_ `_FTPFile` objects
41    (not `_FTPFile` objects themselves!).
42
43    Contrary to `StringIO.StringIO` instances, `MockFile` objects can
44    be queried for their contents after they have been closed.
45    """
46    def __init__(self, path, content=b""):
47        global mock_files
48        mock_files[path] = self
49        self._super = super(MockFile, self)
50        self._super.__init__(content)
51
52    def getvalue(self):
53        if not self.closed:
54            return self._super.getvalue()
55        else:
56            return self._value_after_close
57
58    def close(self):
59        if not self.closed:
60            self._value_after_close = self._super.getvalue()
61        self._super.close()
62
63
64class MockSocket(object):
65    """
66    Mock class which is used to return something from
67    `MockSession.transfercmd`.
68    """
69    def __init__(self, path, mock_file_content=b""):
70        if DEBUG:
71            print("File content: *{0}*".format(mock_file_content))
72        self.file_path = path
73        self.mock_file_content = mock_file_content
74        self._timeout = 60
75
76    def makefile(self, mode):
77        return MockFile(self.file_path, self.mock_file_content)
78
79    def close(self):
80        pass
81
82    # Timeout-related methods are used in `FTPFile.close`.
83    def gettimeout(self):
84        return self._timeout
85
86    def settimeout(self, timeout):
87        self._timeout = timeout
88
89
90class MockSession(object):
91    """
92    Mock class which works like `ftplib.FTP` for the purpose of the
93    unit tests.
94    """
95    # Used by `MockSession.cwd` and `MockSession.pwd`
96    current_dir = '/home/sschwarzer'
97
98    # Used by `MockSession.dir`. This is a mapping from absolute path
99    # to the multi-line string that would show up in an FTP
100    # command-line client for this directory.
101    dir_contents = {}
102
103    # File content to be used (indirectly) with `transfercmd`.
104    mock_file_content = b''
105
106    def __init__(self, host='', user='', password=''):
107        self.closed = 0
108        # Count successful `transfercmd` invocations to ensure that
109        # each has a corresponding `voidresp`.
110        self._transfercmds = 0
111        # Dummy, only for getting/setting timeout in `_FTPFile.close`
112        self.sock = MockSocket("", "")
113
114    def voidcmd(self, cmd):
115        if DEBUG:
116            print(cmd)
117        if cmd == 'STAT':
118            return 'MockSession server awaiting your commands ;-)'
119        elif cmd.startswith('TYPE '):
120            return
121        elif cmd.startswith('SITE CHMOD'):
122            raise ftplib.error_perm("502 command not implemented")
123        else:
124            raise ftplib.error_perm
125
126    def pwd(self):
127        return self.current_dir
128
129    def _remove_trailing_slash(self, path):
130        if path != '/' and path.endswith('/'):
131            path = path[:-1]
132        return path
133
134    def _transform_path(self, path):
135        return posixpath.normpath(posixpath.join(self.pwd(), path))
136
137    def cwd(self, path):
138        path = ftputil.tool.as_unicode(path)
139        self.current_dir = self._transform_path(path)
140
141    def dir(self, *args):
142        """
143        Provide a callback function for processing each line of a
144        directory listing. Return nothing.
145        """
146        # The callback comes last in `ftplib.FTP.dir`.
147        if isinstance(args[-1], collections.Callable):
148            # Get `args[-1]` _before_ removing it in the line after.
149            callback = args[-1]
150            args = args[:-1]
151        else:
152            callback = None
153        # Everything before the path argument are options.
154        path = args[-1]
155        if DEBUG:
156            print("dir: {0}".format(path))
157        path = self._transform_path(path)
158        if path not in self.dir_contents:
159            raise ftplib.error_perm
160        dir_lines = self.dir_contents[path].split('\n')
161        for line in dir_lines:
162            if callback is None:
163                print(line)
164            else:
165                callback(line)
166
167    def voidresp(self):
168        assert self._transfercmds == 1
169        self._transfercmds = self._transfercmds - 1
170        return '2xx'
171
172    def transfercmd(self, cmd):
173        """
174        Return a `MockSocket` object whose `makefile` method will
175        return a mock file object.
176        """
177        if DEBUG:
178            print(cmd)
179        # Fail if attempting to read from/write to a directory.
180        cmd, path = cmd.split()
181        #  Normalize path for lookup.
182        path = self._remove_trailing_slash(path)
183        if path in self.dir_contents:
184            raise ftplib.error_perm
185        # Fail if path isn't available (this name is hard-coded here
186        # and has to be used for the corresponding tests).
187        if (cmd, path) == ('RETR', 'notthere'):
188            raise ftplib.error_perm
189        assert self._transfercmds == 0
190        self._transfercmds = self._transfercmds + 1
191        return MockSocket(path, self.mock_file_content)
192
193    def close(self):
194        if not self.closed:
195            self.closed = 1
196            assert self._transfercmds == 0
197
198
199class MockUnixFormatSession(MockSession):
200
201    dir_contents = {
202      '/': """\
203drwxr-xr-x   2 45854    200           512 May  4  2000 home""",
204
205      '/home': """\
206drwxr-sr-x   2 45854    200           512 May  4  2000 sschwarzer
207-rw-r--r--   1 45854    200          4605 Jan 19  1970 older
208-rw-r--r--   1 45854    200          4605 Jan 19  2020 newer
209lrwxrwxrwx   1 45854    200            21 Jan 19  2002 link -> sschwarzer/index.html
210lrwxrwxrwx   1 45854    200            15 Jan 19  2002 bad_link -> python/bad_link
211drwxr-sr-x   2 45854    200           512 May  4  2000 dir with spaces""",
212
213      '/home/python': """\
214lrwxrwxrwx   1 45854    200             7 Jan 19  2002 link_link -> ../link
215lrwxrwxrwx   1 45854    200            14 Jan 19  2002 bad_link -> /home/bad_link""",
216
217      '/home/sschwarzer': """\
218total 14
219drwxr-sr-x   2 45854    200           512 May  4  2000 chemeng
220drwxr-sr-x   2 45854    200           512 Jan  3 17:17 download
221drwxr-sr-x   2 45854    200           512 Jul 30 17:14 image
222-rw-r--r--   1 45854    200          4604 Jan 19 23:11 index.html
223drwxr-sr-x   2 45854    200           512 May 29  2000 os2
224lrwxrwxrwx   2 45854    200             6 May 29  2000 osup -> ../os2
225drwxr-sr-x   2 45854    200           512 May 25  2000 publications
226drwxr-sr-x   2 45854    200           512 Jan 20 16:12 python
227drwxr-sr-x   6 45854    200           512 Sep 20  1999 scios2""",
228
229      '/home/dir with spaces': """\
230total 1
231-rw-r--r--   1 45854    200          4604 Jan 19 23:11 file with spaces""",
232
233      '/home/file_name_test': """\
234drwxr-sr-x   2 45854    200           512 May 29  2000 ä
235-rw-r--r--   1 45854    200          4604 Jan 19 23:11 ö
236lrwxrwxrwx   2 45854    200             6 May 29  2000 ü -> ä""",
237
238      '/home/file_name_test/ä': """\
239-rw-r--r--   1 45854    200          4604 Jan 19 23:11 ö
240-rw-r--r--   1 45854    200          4604 Jan 19 23:11 o""",
241
242      # Fail when trying to write to this directory (the content isn't
243      # relevant).
244      'sschwarzer': "",
245    }
246
247
248class MockMSFormatSession(MockSession):
249
250    dir_contents = {
251      '/': """\
25210-23-01  03:25PM       <DIR>          home""",
253
254      '/home': """\
25510-23-01  03:25PM       <DIR>          msformat""",
256
257      '/home/msformat': """\
25810-23-01  03:25PM       <DIR>          WindowsXP
25912-07-01  02:05PM       <DIR>          XPLaunch
26007-17-00  02:08PM             12266720 abcd.exe
26107-17-00  02:08PM                89264 O2KKeys.exe""",
262
263      '/home/msformat/XPLaunch': """\
26410-23-01  03:25PM       <DIR>          WindowsXP
26512-07-01  02:05PM       <DIR>          XPLaunch
26612-07-01  02:05PM       <DIR>          empty
26707-17-00  02:08PM             12266720 abcd.exe
26807-17-00  02:08PM                89264 O2KKeys.exe""",
269
270      '/home/msformat/XPLaunch/empty': "total 0",
271    }
Note: See TracBrowser for help on using the repository browser.