source: test/mock_ftplib.py @ 1083:aa69703148f3

Last change on this file since 1083:aa69703148f3 was 1083:aa69703148f3, checked in by Stefan Schwarzer <sschwarzer@…>, 8 years ago
Use `super` instead of "classic" base class constructor call.
File size: 7.0 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, path, callback=None):
175        """Provide a callback function for processing each line of
176        a directory listing. Return nothing.
177        """
178        if DEBUG:
179            print 'dir: %s' % path
180        path = self._transform_path(path)
181        if not self.dir_contents.has_key(path):
182            raise ftplib.error_perm
183        dir_lines = self.dir_contents[path].split('\n')
184        for line in dir_lines:
185            if callback is None:
186                print line
187            else:
188                callback(line)
189
190    def voidresp(self):
191        assert self._transfercmds == 1
192        self._transfercmds = self._transfercmds - 1
193        return '2xx'
194
195    def transfercmd(self, cmd):
196        """
197        Return a `MockSocket` object whose `makefile` method will
198        return a mock file object.
199        """
200        if DEBUG:
201            print cmd
202        # Fail if attempting to read from/write to a directory
203        cmd, path = cmd.split()
204        path = self._remove_trailing_slash(path)
205        if self.dir_contents.has_key(path):
206            raise ftplib.error_perm
207        # Fail if path isn't available (this name is hard-coded here
208        #  and has to be used for the corresponding tests).
209        if (cmd, path) == ('RETR', 'notthere'):
210            raise ftplib.error_perm
211        assert self._transfercmds == 0
212        self._transfercmds = self._transfercmds + 1
213        return MockSocket(path, self.mock_file_content)
214
215    def close(self):
216        if not self.closed:
217            self.closed = 1
218            assert self._transfercmds == 0
219
Note: See TracBrowser for help on using the repository browser.