source: test/mock_ftplib.py @ 1444:233234b92f40

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