source: test/mock_ftplib.py @ 1096:34fde55180be

Last change on this file since 1096:34fde55180be was 1096:34fde55180be, checked in by Stefan Schwarzer <sschwarzer@…>, 8 years ago
If the server's `LIST` command accepts the `-a` option, use it. The option will be used for all subsequent directory requests. With some servers, this makes the server send directory lines where the file or directory entry starts with a dot. However, there's no _guarantee_ that such entries will be displayed even if the `-a` option is used. Note that the fact that the FTP server doesn't complain about the `-a` option means the option has an effect. I did an experiment and tried arbitrary "options" with `LIST`, but neither gave an error message, but just a directory listing as without the `-a` option.
File size: 7.2 KB
Line 
1# Copyright (C) 2003-2009, Stefan Schwarzer <sschwarzer@sschwarzer.net>
2# See the file LICENSE for licensing terms.
3
4"""
5This module implements a mock version of the standard library's
6`ftplib.py` module. Some code is taken from there.
7
8Not all functionality is implemented, only that what is used to
9run the unit tests.
10"""
11
12import ftplib
13import posixpath
14import StringIO
15
16DEBUG = 0
17
18# Use a global dictionary of the form `{path: mock_file, ...}` to
19#  make "volatile" mock files accessible. This is used for testing
20#  the contents of a file after an `FTPHost.upload` call.
21mock_files = {}
22
23def content_of(path):
24    return mock_files[path].getvalue()
25
26
27class MockFile(StringIO.StringIO, object):
28    """
29    Mock class for the file objects _contained in_ `_FTPFile` objects
30    (not `_FTPFile` objects themselves!).
31
32    Contrary to `StringIO.StringIO` instances, `MockFile` objects can
33    be queried for their contents after they have been closed.
34    """
35    def __init__(self, path, content=''):
36        global mock_files
37        mock_files[path] = self
38        super(MockFile, self).__init__(content)
39
40    def getvalue(self):
41        if not self.closed:
42            return super(MockFile, self).getvalue()
43        else:
44            return self._value_after_close
45
46    def close(self):
47        if not self.closed:
48            self._value_after_close = super(MockFile, self).getvalue()
49        super(MockFile, self).close()
50
51
52class MockSocket(object):
53    """
54    Mock class which is used to return something from
55    `MockSession.transfercmd`.
56    """
57    def __init__(self, path, mock_file_content=''):
58        if DEBUG:
59            print 'File content: *%s*' % mock_file_content
60        self.file_path = path
61        self.mock_file_content = mock_file_content
62        self._timeout = 60
63
64    def makefile(self, mode):
65        return MockFile(self.file_path, self.mock_file_content)
66
67    def close(self):
68        pass
69
70    def gettimeout(self):
71        return self._timeout
72
73    def settimeout(self, timeout):
74        self._timeout = timeout
75
76
77class MockSession(object):
78    """
79    Mock class which works like `ftplib.FTP` for the purpose of the
80    unit tests.
81    """
82    # Used by `MockSession.cwd` and `MockSession.pwd`
83    current_dir = '/home/sschwarzer'
84
85    # Used by `MockSession.dir`
86    dir_contents = {
87      '/': """\
88drwxr-xr-x   2 45854    200           512 May  4  2000 home""",
89
90      '/home': """\
91drwxr-sr-x   2 45854    200           512 May  4  2000 sschwarzer
92-rw-r--r--   1 45854    200          4605 Jan 19  1970 older
93-rw-r--r--   1 45854    200          4605 Jan 19  2020 newer
94lrwxrwxrwx   1 45854    200            21 Jan 19  2002 link -> sschwarzer/index.html
95lrwxrwxrwx   1 45854    200            15 Jan 19  2002 bad_link -> python/bad_link""",
96
97      '/home/python': """\
98lrwxrwxrwx   1 45854    200             7 Jan 19  2002 link_link -> ../link
99lrwxrwxrwx   1 45854    200            14 Jan 19  2002 bad_link -> /home/bad_link""",
100
101      '/home/sschwarzer': """\
102total 14
103drwxr-sr-x   2 45854    200           512 May  4  2000 chemeng
104drwxr-sr-x   2 45854    200           512 Jan  3 17:17 download
105drwxr-sr-x   2 45854    200           512 Jul 30 17:14 image
106-rw-r--r--   1 45854    200          4604 Jan 19 23:11 index.html
107drwxr-sr-x   2 45854    200           512 May 29  2000 os2
108lrwxrwxrwx   2 45854    200             6 May 29  2000 osup -> ../os2
109drwxr-sr-x   2 45854    200           512 May 25  2000 publications
110drwxr-sr-x   2 45854    200           512 Jan 20 16:12 python
111drwxr-sr-x   6 45854    200           512 Sep 20  1999 scios2""",
112
113      '/home/dir with spaces': """\
114total 1
115-rw-r--r--   1 45854    200          4604 Jan 19 23:11 file with spaces""",
116
117      # Fail when trying to write to this directory (the content isn't
118      #  relevant).
119      'sschwarzer': "",
120
121      '/home/msformat': """\
12210-23-01  03:25PM       <DIR>          WindowsXP
12312-07-01  02:05PM       <DIR>          XPLaunch
12407-17-00  02:08PM             12266720 abcd.exe
12507-17-00  02:08PM                89264 O2KKeys.exe""",
126
127      '/home/msformat/XPLaunch': """\
12810-23-01  03:25PM       <DIR>          WindowsXP
12912-07-01  02:05PM       <DIR>          XPLaunch
13012-07-01  02:05PM       <DIR>          empty
13107-17-00  02:08PM             12266720 abcd.exe
13207-17-00  02:08PM                89264 O2KKeys.exe""",
133
134      '/home/msformat/XPLaunch/empty': "total 0",
135    }
136
137    # File content to be used (indirectly) with `transfercmd`.
138    mock_file_content = ''
139
140    def __init__(self, host='', user='', password=''):
141        self.closed = 0
142        # Count successful `transfercmd` invocations to ensure that
143        #  each has a corresponding `voidresp`.
144        self._transfercmds = 0
145        # Dummy, only for getting/setting timeout in `_FTPFile.close`
146        self.sock = MockSocket("", "")
147
148    def voidcmd(self, cmd):
149        if DEBUG:
150            print cmd
151        if cmd == 'STAT':
152            return 'MockSession server awaiting your commands ;-)'
153        elif cmd.startswith('TYPE '):
154            return
155        elif cmd.startswith('SITE CHMOD'):
156            raise ftplib.error_perm("502 command not implemented")
157        else:
158            raise ftplib.error_perm
159
160    def pwd(self):
161        return self.current_dir
162
163    def _remove_trailing_slash(self, path):
164        if path != '/' and path.endswith('/'):
165            path = path[:-1]
166        return path
167
168    def _transform_path(self, path):
169        return posixpath.normpath(posixpath.join(self.pwd(), path))
170
171    def cwd(self, path):
172        self.current_dir = self._transform_path(path)
173
174    def dir(self, *args):
175        """Provide a callback function for processing each line of
176        a directory listing. Return nothing.
177        """
178        if callable(args[-1]):
179            callback = args[-1]
180            args = args[:-1]
181        else:
182            callback = None
183        # Everything before the path argument are options.
184        path = args[-1]
185        if DEBUG:
186            print 'dir: %s' % path
187        path = self._transform_path(path)
188        if not self.dir_contents.has_key(path):
189            raise ftplib.error_perm
190        dir_lines = self.dir_contents[path].split('\n')
191        for line in dir_lines:
192            if callback is None:
193                print line
194            else:
195                callback(line)
196
197    def voidresp(self):
198        assert self._transfercmds == 1
199        self._transfercmds = self._transfercmds - 1
200        return '2xx'
201
202    def transfercmd(self, cmd):
203        """
204        Return a `MockSocket` object whose `makefile` method will
205        return a mock file object.
206        """
207        if DEBUG:
208            print cmd
209        # Fail if attempting to read from/write to a directory
210        cmd, path = cmd.split()
211        path = self._remove_trailing_slash(path)
212        if self.dir_contents.has_key(path):
213            raise ftplib.error_perm
214        # Fail if path isn't available (this name is hard-coded here
215        #  and has to be used for the corresponding tests).
216        if (cmd, path) == ('RETR', 'notthere'):
217            raise ftplib.error_perm
218        assert self._transfercmds == 0
219        self._transfercmds = self._transfercmds + 1
220        return MockSocket(path, self.mock_file_content)
221
222    def close(self):
223        if not self.closed:
224            self.closed = 1
225            assert self._transfercmds == 0
226
Note: See TracBrowser for help on using the repository browser.