source: test/test_path.py @ 1663:40280d912474

Last change on this file since 1663:40280d912474 was 1663:40280d912474, checked in by Stefan Schwarzer <sschwarzer@…>, 4 years ago
Remove `unittest` dependency - Remove `unittest` imports - Let test case classes inherit from `object` instead of `unittest.TestCase` - Use `setup_method` and `teardown_method` instead of `unittest`'s `setUp` and `tearDown` - Use `pytest.mark.skipif` instead of `unittest.skipIf` - Use `pytest.mark.slow_test` instead of decorator in `test/__init__.py`. Exclude slow tests with py.test -m "not slow_test" test - Replace some leftover `assert*` calls with `assert` statements - Replace `assert False, ...` with `pytest.fail` ticket: 98
File size: 8.1 KB
Line 
1# encoding: utf-8
2# Copyright (C) 2003-2016, Stefan Schwarzer <sschwarzer@sschwarzer.net>
3# and ftputil contributors (see `doc/contributors.txt`)
4# See the file LICENSE for licensing terms.
5
6from __future__ import unicode_literals
7
8import ftplib
9import time
10
11import pytest
12
13import ftputil
14import ftputil.compat
15import ftputil.error
16import ftputil.tool
17
18from test import mock_ftplib
19from test import test_base
20
21
22class FailingFTPHost(ftputil.FTPHost):
23
24    def _dir(self, path):
25        raise ftputil.error.FTPOSError("simulate a failure, e. g. timeout")
26
27
28# Mock session, used for testing an inaccessible login directory
29class SessionWithInaccessibleLoginDirectory(mock_ftplib.MockSession):
30
31    def cwd(self, dir):
32        # Assume that `dir` is the inaccessible login directory.
33        raise ftplib.error_perm("can't change into this directory")
34
35
36class TestPath(object):
37    """Test operations in `FTPHost.path`."""
38
39    def test_regular_isdir_isfile_islink(self):
40        """Test regular `FTPHost._Path.isdir/isfile/islink`."""
41        host = test_base.ftp_host_factory()
42        testdir = "/home/sschwarzer"
43        host.chdir(testdir)
44        # Test a path which isn't there.
45        assert not host.path.isdir("notthere")
46        assert not host.path.isfile("notthere")
47        assert not host.path.islink("notthere")
48        #  This checks additional code (see ticket #66).
49        assert not host.path.isdir("/notthere/notthere")
50        assert not host.path.isfile("/notthere/notthere")
51        assert not host.path.islink("/notthere/notthere")
52        # Test a directory.
53        assert host.path.isdir(testdir)
54        assert not host.path.isfile(testdir)
55        assert not host.path.islink(testdir)
56        # Test a file.
57        testfile = "/home/sschwarzer/index.html"
58        assert not host.path.isdir(testfile)
59        assert host.path.isfile(testfile)
60        assert not host.path.islink(testfile)
61        # Test a link. Since the link target of `osup` doesn't exist,
62        # neither `isdir` nor `isfile` return `True`.
63        testlink = "/home/sschwarzer/osup"
64        assert not host.path.isdir(testlink)
65        assert not host.path.isfile(testlink)
66        assert host.path.islink(testlink)
67
68    def test_workaround_for_spaces(self):
69        """Test whether the workaround for space-containing paths is used."""
70        host = test_base.ftp_host_factory()
71        testdir = "/home/sschwarzer"
72        host.chdir(testdir)
73        # Test a file name containing spaces.
74        testfile = "/home/dir with spaces/file with spaces"
75        assert not host.path.isdir(testfile)
76        assert host.path.isfile(testfile)
77        assert not host.path.islink(testfile)
78
79    def test_inaccessible_home_directory_and_whitespace_workaround(self):
80        "Test combination of inaccessible home directory + whitespace in path."
81        host = test_base.ftp_host_factory(
82               session_factory=SessionWithInaccessibleLoginDirectory)
83        with pytest.raises(ftputil.error.InaccessibleLoginDirError):
84            host._dir("/home dir")
85
86    def test_isdir_isfile_islink_with_exception(self):
87        """Test failing `FTPHost._Path.isdir/isfile/islink`."""
88        host = test_base.ftp_host_factory(ftp_host_class=FailingFTPHost)
89        testdir = "/home/sschwarzer"
90        host.chdir(testdir)
91        # Test if exceptions are propagated.
92        FTPOSError = ftputil.error.FTPOSError
93        with pytest.raises(FTPOSError):
94            host.path.isdir("index.html")
95        with pytest.raises(FTPOSError):
96            host.path.isfile("index.html")
97        with pytest.raises(FTPOSError):
98            host.path.islink("index.html")
99
100    def test_exists(self):
101        """Test `FTPHost.path.exists`."""
102        # Regular use of `exists`
103        host = test_base.ftp_host_factory()
104        testdir = "/home/sschwarzer"
105        host.chdir(testdir)
106        assert host.path.exists("index.html")
107        assert not host.path.exists("notthere")
108        # Test if exceptions are propagated.
109        host = test_base.ftp_host_factory(ftp_host_class=FailingFTPHost)
110        with pytest.raises(ftputil.error.FTPOSError):
111            host.path.exists("index.html")
112
113
114class TestAcceptEitherBytesOrUnicode(object):
115
116    def setup_method(self, method):
117        self.host = test_base.ftp_host_factory()
118
119    def _test_method_string_types(self, method, path):
120        expected_type = type(path)
121        assert isinstance(method(path), expected_type)
122
123    def test_methods_that_take_and_return_one_string(self):
124        """
125        Test whether the same string type as for the argument is returned.
126        """
127        bytes_type = ftputil.compat.bytes_type
128        unicode_type = ftputil.compat.unicode_type
129        method_names = ("abspath basename dirname join normcase normpath".
130                        split())
131        for method_name in method_names:
132            method = getattr(self.host.path, method_name)
133            self._test_method_string_types(method, "/")
134            self._test_method_string_types(method, ".")
135            self._test_method_string_types(method, b"/")
136            self._test_method_string_types(method, b".")
137
138    def test_methods_that_take_a_string_and_return_a_bool(self):
139        """Test whether the methods accept byte and unicode strings."""
140        host = self.host
141        as_bytes = ftputil.tool.as_bytes
142        host.chdir("/home/file_name_test")
143        # `isabs`
144        assert not host.path.isabs("ä")
145        assert not host.path.isabs(as_bytes("ä"))
146        # `exists`
147        assert host.path.exists("ä")
148        assert host.path.exists(as_bytes("ä"))
149        # `isdir`, `isfile`, `islink`
150        assert host.path.isdir("ä")
151        assert host.path.isdir(as_bytes("ä"))
152        assert host.path.isfile("ö")
153        assert host.path.isfile(as_bytes("ö"))
154        assert host.path.islink("ü")
155        assert host.path.islink(as_bytes("ü"))
156
157    def test_join(self):
158        """
159        Test whether `FTPHost.path.join` accepts only arguments of
160        the same string type and returns the same string type.
161        """
162        join = self.host.path.join
163        as_bytes = ftputil.tool.as_bytes
164        # Only unicode
165        parts = list("äöü")
166        result = join(*parts)
167        assert result == "ä/ö/ü"
168        #  Need explicit type check for Python 2
169        assert isinstance(result, ftputil.compat.unicode_type)
170        # Only bytes
171        parts = [as_bytes(s) for s in "äöü"]
172        result = join(*parts)
173        assert result == as_bytes("ä/ö/ü")
174        #  Need explicit type check for Python 2
175        assert isinstance(result, ftputil.compat.bytes_type)
176        # Mixture of unicode and bytes
177        parts = ["ä", as_bytes("ö")]
178        with pytest.raises(TypeError):
179            join(*parts)
180        parts = [as_bytes("ä"), as_bytes("ö"), "ü"]
181        with pytest.raises(TypeError):
182            join(*parts)
183
184    def test_getmtime(self):
185        """
186        Test whether `FTPHost.path.getmtime` accepts byte and unicode
187        paths.
188        """
189        host = self.host
190        as_bytes = ftputil.tool.as_bytes
191        host.chdir("/home/file_name_test")
192        # We don't care about the _exact_ time, so don't bother with
193        # timezone differences. Instead, do a simple sanity check.
194        day = 24 * 60 * 60  # seconds
195        expected_mtime = time.mktime((2000, 5, 29, 0, 0, 0, 0, 0, 0))
196        mtime_makes_sense = (lambda mtime: expected_mtime - day <= mtime <=
197                                           expected_mtime + day)
198        assert mtime_makes_sense(host.path.getmtime("ä"))
199        assert mtime_makes_sense(host.path.getmtime(as_bytes("ä")))
200
201    def test_getsize(self):
202        """
203        Test whether `FTPHost.path.getsize` accepts byte and unicode paths.
204        """
205        host = self.host
206        as_bytes = ftputil.tool.as_bytes
207        host.chdir("/home/file_name_test")
208        assert host.path.getsize("ä") == 512
209        assert host.path.getsize(as_bytes("ä")) == 512
210
211    def test_walk(self):
212        """Test whether `FTPHost.path.walk` accepts bytes and unicode paths."""
213        host = self.host
214        as_bytes = ftputil.tool.as_bytes
215        def noop(arg, top, names):
216            del names[:]
217        host.path.walk("ä", noop, None)
218        host.path.walk(as_bytes("ä"), noop, None)
Note: See TracBrowser for help on using the repository browser.