source: test/mock_ftplib.py @ 1436:4f26ad9b5427

Last change on this file since 1436:4f26ad9b5427 was 1436:4f26ad9b5427, checked in by Stefan Schwarzer <sschwarzer@…>, 6 years ago
Added empty line before constructor.
File size: 8.9 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
47    def __init__(self, path, content=b""):
48        global mock_files
49        mock_files[path] = self
50        self._super = super(MockFile, self)
51        self._super.__init__(content)
52
53    def getvalue(self):
54        if not self.closed:
55            return self._super.getvalue()
56        else:
57            return self._value_after_close
58
59    def close(self):
60        if not self.closed:
61            self._value_after_close = self._super.getvalue()
62        self._super.close()
63
64
65class MockSocket(object):
66    """
67    Mock class which is used to return something from
68    `MockSession.transfercmd`.
69    """
70    def __init__(self, path, mock_file_content=b""):
71        if DEBUG:
72            print("File content: *{0}*".format(mock_file_content))
73        self.file_path = path
74        self.mock_file_content = mock_file_content
75        self._timeout = 60
76
77    def makefile(self, mode):
78        return MockFile(self.file_path, self.mock_file_content)
79
80    def close(self):
81        pass
82
83    # Timeout-related methods are used in `FTPFile.close`.
84    def gettimeout(self):
85        return self._timeout
86
87    def settimeout(self, timeout):
88        self._timeout = timeout
89
90
91class MockSession(object):
92    """
93    Mock class which works like `ftplib.FTP` for the purpose of the
94    unit tests.
95    """
96    # Used by `MockSession.cwd` and `MockSession.pwd`
97    current_dir = "/home/sschwarzer"
98
99    # Used by `MockSession.dir`. This is a mapping from absolute path
100    # to the multi-line string that would show up in an FTP
101    # command-line client for this directory.
102    dir_contents = {}
103
104    # File content to be used (indirectly) with `transfercmd`.
105    mock_file_content = b""
106
107    def __init__(self, host="", user="", password=""):
108        self.closed = 0
109        # Count successful `transfercmd` invocations to ensure that
110        # each has a corresponding `voidresp`.
111        self._transfercmds = 0
112        # Dummy, only for getting/setting timeout in `FTPFile.close`
113        self.sock = MockSocket("", "")
114
115    def voidcmd(self, cmd):
116        if DEBUG:
117            print(cmd)
118        if cmd == "STAT":
119            return "MockSession server awaiting your commands ;-)"
120        elif cmd.startswith("TYPE "):
121            return
122        elif cmd.startswith("SITE CHMOD"):
123            raise ftplib.error_perm("502 command not implemented")
124        else:
125            raise ftplib.error_perm
126
127    def pwd(self):
128        return self.current_dir
129
130    def _remove_trailing_slash(self, path):
131        if path != "/" and path.endswith("/"):
132            path = path[:-1]
133        return path
134
135    def _transform_path(self, path):
136        return posixpath.normpath(posixpath.join(self.pwd(), path))
137
138    def cwd(self, path):
139        path = ftputil.tool.as_unicode(path)
140        self.current_dir = self._transform_path(path)
141
142    def _ignore_arguments(self, *args, **kwargs):
143        pass
144
145    delete = mkd = rename = rmd = _ignore_arguments
146
147    def dir(self, *args):
148        """
149        Provide a callback function for processing each line of a
150        directory listing. Return nothing.
151        """
152        # The callback comes last in `ftplib.FTP.dir`.
153        if isinstance(args[-1], collections.Callable):
154            # Get `args[-1]` _before_ removing it in the line after.
155            callback = args[-1]
156            args = args[:-1]
157        else:
158            callback = None
159        # Everything before the path argument are options.
160        path = args[-1]
161        if DEBUG:
162            print("dir: {0}".format(path))
163        path = self._transform_path(path)
164        if path not in self.dir_contents:
165            raise ftplib.error_perm
166        dir_lines = self.dir_contents[path].split("\n")
167        for line in dir_lines:
168            if callback is None:
169                print(line)
170            else:
171                callback(line)
172
173    def voidresp(self):
174        assert self._transfercmds == 1
175        self._transfercmds = self._transfercmds - 1
176        return "2xx"
177
178    def transfercmd(self, cmd):
179        """
180        Return a `MockSocket` object whose `makefile` method will
181        return a mock file object.
182        """
183        if DEBUG:
184            print(cmd)
185        # Fail if attempting to read from/write to a directory.
186        cmd, path = cmd.split()
187        #  Normalize path for lookup.
188        path = self._remove_trailing_slash(path)
189        if path in self.dir_contents:
190            raise ftplib.error_perm
191        # Fail if path isn't available (this name is hard-coded here
192        # and has to be used for the corresponding tests).
193        if (cmd, path) == ("RETR", "notthere"):
194            raise ftplib.error_perm
195        assert self._transfercmds == 0
196        self._transfercmds = self._transfercmds + 1
197        return MockSocket(path, self.mock_file_content)
198
199    def close(self):
200        if not self.closed:
201            self.closed = 1
202            assert self._transfercmds == 0
203
204
205class MockUnixFormatSession(MockSession):
206
207    dir_contents = {
208      "/": """\
209drwxr-xr-x   2 45854    200           512 May  4  2000 home""",
210
211      "/home": """\
212drwxr-sr-x   2 45854    200           512 May  4  2000 sschwarzer
213-rw-r--r--   1 45854    200          4605 Jan 19  1970 older
214-rw-r--r--   1 45854    200          4605 Jan 19  2020 newer
215lrwxrwxrwx   1 45854    200            21 Jan 19  2002 link -> sschwarzer/index.html
216lrwxrwxrwx   1 45854    200            15 Jan 19  2002 bad_link -> python/bad_link
217drwxr-sr-x   2 45854    200           512 May  4  2000 dir with spaces
218drwxr-sr-x   2 45854    200           512 May  4  2000 file_name_test""",
219
220      "/home/python": """\
221lrwxrwxrwx   1 45854    200             7 Jan 19  2002 link_link -> ../link
222lrwxrwxrwx   1 45854    200            14 Jan 19  2002 bad_link -> /home/bad_link""",
223
224      "/home/sschwarzer": """\
225total 14
226drwxr-sr-x   2 45854    200           512 May  4  2000 chemeng
227drwxr-sr-x   2 45854    200           512 Jan  3 17:17 download
228drwxr-sr-x   2 45854    200           512 Jul 30 17:14 image
229-rw-r--r--   1 45854    200          4604 Jan 19 23:11 index.html
230drwxr-sr-x   2 45854    200           512 May 29  2000 os2
231lrwxrwxrwx   2 45854    200             6 May 29  2000 osup -> ../os2
232drwxr-sr-x   2 45854    200           512 May 25  2000 publications
233drwxr-sr-x   2 45854    200           512 Jan 20 16:12 python
234drwxr-sr-x   6 45854    200           512 Sep 20  1999 scios2""",
235
236      "/home/dir with spaces": """\
237total 1
238-rw-r--r--   1 45854    200          4604 Jan 19 23:11 file with spaces""",
239
240      "/home/file_name_test": """\
241drwxr-sr-x   2 45854    200           512 May 29  2000 ä
242drwxr-sr-x   2 45854    200           512 May 29  2000 empty_ä
243-rw-r--r--   1 45854    200          4604 Jan 19 23:11 ö
244lrwxrwxrwx   2 45854    200             6 May 29  2000 ü -> ä""",
245
246      "/home/file_name_test/ä": """\
247-rw-r--r--   1 45854    200          4604 Jan 19 23:11 ö
248-rw-r--r--   1 45854    200          4604 Jan 19 23:11 o""",
249
250      "/home/file_name_test/empty_ä": """\
251""",
252      # Fail when trying to write to this directory (the content isn't
253      # relevant).
254      "sschwarzer": "",
255    }
256
257
258class MockMSFormatSession(MockSession):
259
260    dir_contents = {
261      "/": """\
26210-23-01  03:25PM       <DIR>          home""",
263
264      "/home": """\
26510-23-01  03:25PM       <DIR>          msformat""",
266
267      "/home/msformat": """\
26810-23-01  03:25PM       <DIR>          WindowsXP
26912-07-01  02:05PM       <DIR>          XPLaunch
27007-17-00  02:08PM             12266720 abcd.exe
27107-17-00  02:08PM                89264 O2KKeys.exe""",
272
273      "/home/msformat/XPLaunch": """\
27410-23-01  03:25PM       <DIR>          WindowsXP
27512-07-01  02:05PM       <DIR>          XPLaunch
27612-07-01  02:05PM       <DIR>          empty
27707-17-00  02:08PM             12266720 abcd.exe
27807-17-00  02:08PM                89264 O2KKeys.exe""",
279
280      "/home/msformat/XPLaunch/empty": "total 0",
281    }
Note: See TracBrowser for help on using the repository browser.