source: test/mock_ftplib.py @ 1140:3bdcd99a54de

Last change on this file since 1140:3bdcd99a54de was 1140:3bdcd99a54de, checked in by Stefan Schwarzer <sschwarzer@…>, 7 years ago
Extracted `MockUnixSession` corresponding to `MockMSFormatSession`. Also, a few tests had to be adapted as a consequence.
File size: 7.7 KB
Line 
1# Copyright (C) 2003-2012, 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`. This is a mapping from absolute path
86    # to the multi-line string that would show up in an FTP
87    # command-line client for this directory.
88    dir_contents = {}
89
90    # File content to be used (indirectly) with `transfercmd`.
91    mock_file_content = ''
92
93    def __init__(self, host='', user='', password=''):
94        self.closed = 0
95        # Count successful `transfercmd` invocations to ensure that
96        # each has a corresponding `voidresp`.
97        self._transfercmds = 0
98        # Dummy, only for getting/setting timeout in `_FTPFile.close`
99        self.sock = MockSocket("", "")
100
101    def voidcmd(self, cmd):
102        if DEBUG:
103            print cmd
104        if cmd == 'STAT':
105            return 'MockSession server awaiting your commands ;-)'
106        elif cmd.startswith('TYPE '):
107            return
108        elif cmd.startswith('SITE CHMOD'):
109            raise ftplib.error_perm("502 command not implemented")
110        else:
111            raise ftplib.error_perm
112
113    def pwd(self):
114        return self.current_dir
115
116    def _remove_trailing_slash(self, path):
117        if path != '/' and path.endswith('/'):
118            path = path[:-1]
119        return path
120
121    def _transform_path(self, path):
122        return posixpath.normpath(posixpath.join(self.pwd(), path))
123
124    def cwd(self, path):
125        self.current_dir = self._transform_path(path)
126
127    def dir(self, *args):
128        """Provide a callback function for processing each line of
129        a directory listing. Return nothing.
130        """
131        if callable(args[-1]):
132            callback = args[-1]
133            args = args[:-1]
134        else:
135            callback = None
136        # Everything before the path argument are options.
137        path = args[-1]
138        if DEBUG:
139            print 'dir: %s' % path
140        path = self._transform_path(path)
141        if not self.dir_contents.has_key(path):
142            raise ftplib.error_perm
143        dir_lines = self.dir_contents[path].split('\n')
144        for line in dir_lines:
145            if callback is None:
146                print line
147            else:
148                callback(line)
149
150    def voidresp(self):
151        assert self._transfercmds == 1
152        self._transfercmds = self._transfercmds - 1
153        return '2xx'
154
155    def transfercmd(self, cmd):
156        """
157        Return a `MockSocket` object whose `makefile` method will
158        return a mock file object.
159        """
160        if DEBUG:
161            print cmd
162        # Fail if attempting to read from/write to a directory
163        cmd, path = cmd.split()
164        path = self._remove_trailing_slash(path)
165        if self.dir_contents.has_key(path):
166            raise ftplib.error_perm
167        # Fail if path isn't available (this name is hard-coded here
168        # and has to be used for the corresponding tests).
169        if (cmd, path) == ('RETR', 'notthere'):
170            raise ftplib.error_perm
171        assert self._transfercmds == 0
172        self._transfercmds = self._transfercmds + 1
173        return MockSocket(path, self.mock_file_content)
174
175    def close(self):
176        if not self.closed:
177            self.closed = 1
178            assert self._transfercmds == 0
179
180
181class MockUnixSession(MockSession):
182
183    dir_contents = {
184      '/': """\
185drwxr-xr-x   2 45854    200           512 May  4  2000 home""",
186
187      '/home': """\
188drwxr-sr-x   2 45854    200           512 May  4  2000 sschwarzer
189-rw-r--r--   1 45854    200          4605 Jan 19  1970 older
190-rw-r--r--   1 45854    200          4605 Jan 19  2020 newer
191lrwxrwxrwx   1 45854    200            21 Jan 19  2002 link -> sschwarzer/index.html
192lrwxrwxrwx   1 45854    200            15 Jan 19  2002 bad_link -> python/bad_link
193drwxr-sr-x   2 45854    200           512 May  4  2000 dir with spaces""",
194
195      '/home/python': """\
196lrwxrwxrwx   1 45854    200             7 Jan 19  2002 link_link -> ../link
197lrwxrwxrwx   1 45854    200            14 Jan 19  2002 bad_link -> /home/bad_link""",
198
199      '/home/sschwarzer': """\
200total 14
201drwxr-sr-x   2 45854    200           512 May  4  2000 chemeng
202drwxr-sr-x   2 45854    200           512 Jan  3 17:17 download
203drwxr-sr-x   2 45854    200           512 Jul 30 17:14 image
204-rw-r--r--   1 45854    200          4604 Jan 19 23:11 index.html
205drwxr-sr-x   2 45854    200           512 May 29  2000 os2
206lrwxrwxrwx   2 45854    200             6 May 29  2000 osup -> ../os2
207drwxr-sr-x   2 45854    200           512 May 25  2000 publications
208drwxr-sr-x   2 45854    200           512 Jan 20 16:12 python
209drwxr-sr-x   6 45854    200           512 Sep 20  1999 scios2""",
210
211      '/home/dir with spaces': """\
212total 1
213-rw-r--r--   1 45854    200          4604 Jan 19 23:11 file with spaces""",
214
215      # Fail when trying to write to this directory (the content isn't
216      # relevant).
217      'sschwarzer': "",
218    }
219
220
221class MockMSFormatSession(MockSession):
222
223    dir_contents = {
224      '/': """\
22510-23-01  03:25PM       <DIR>          home""",
226
227      '/home': """\
22810-23-01  03:25PM       <DIR>          msformat""",
229
230      '/home/msformat': """\
23110-23-01  03:25PM       <DIR>          WindowsXP
23212-07-01  02:05PM       <DIR>          XPLaunch
23307-17-00  02:08PM             12266720 abcd.exe
23407-17-00  02:08PM                89264 O2KKeys.exe""",
235
236      '/home/msformat/XPLaunch': """\
23710-23-01  03:25PM       <DIR>          WindowsXP
23812-07-01  02:05PM       <DIR>          XPLaunch
23912-07-01  02:05PM       <DIR>          empty
24007-17-00  02:08PM             12266720 abcd.exe
24107-17-00  02:08PM                89264 O2KKeys.exe""",
242
243      '/home/msformat/XPLaunch/empty': "total 0",
244    }
Note: See TracBrowser for help on using the repository browser.