test_genericpath.py 10.9 KB
Newer Older
1 2 3 4
"""
Tests common to genericpath, macpath, ntpath and posixpath
"""

5
import unittest
6
from test import support
7 8
import os
import genericpath
9
import sys
10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

def safe_rmdir(dirname):
    try:
        os.rmdir(dirname)
    except OSError:
        pass


class GenericTest(unittest.TestCase):
    # The path module to be tested
    pathmodule = genericpath
    common_attributes = ['commonprefix', 'getsize', 'getatime', 'getctime',
                         'getmtime', 'exists', 'isdir', 'isfile']
    attributes = []

    def test_no_argument(self):
        for attr in self.common_attributes + self.attributes:
            with self.assertRaises(TypeError):
                getattr(self.pathmodule, attr)()
                raise self.fail("{}.{}() did not raise a TypeError"
                                .format(self.pathmodule.__name__, attr))
32 33

    def test_commonprefix(self):
34
        commonprefix = self.pathmodule.commonprefix
35
        self.assertEqual(
36
            commonprefix([]),
37 38 39
            ""
        )
        self.assertEqual(
40
            commonprefix(["/home/swenson/spam", "/home/swen/spam"]),
41 42 43
            "/home/swen"
        )
        self.assertEqual(
44
            commonprefix(["/home/swen/spam", "/home/swen/eggs"]),
45 46 47
            "/home/swen/"
        )
        self.assertEqual(
48
            commonprefix(["/home/swen/spam", "/home/swen/spam"]),
49 50
            "/home/swen/spam"
        )
51 52 53 54 55 56 57 58 59 60 61 62
        self.assertEqual(
            commonprefix(["home:swenson:spam", "home:swen:spam"]),
            "home:swen"
        )
        self.assertEqual(
            commonprefix([":home:swen:spam", ":home:swen:eggs"]),
            ":home:swen:"
        )
        self.assertEqual(
            commonprefix([":home:swen:spam", ":home:swen:spam"]),
            ":home:swen:spam"
        )
63

64 65 66 67 68 69 70 71 72 73 74 75
        self.assertEqual(
            commonprefix([b"/home/swenson/spam", b"/home/swen/spam"]),
            b"/home/swen"
        )
        self.assertEqual(
            commonprefix([b"/home/swen/spam", b"/home/swen/eggs"]),
            b"/home/swen/"
        )
        self.assertEqual(
            commonprefix([b"/home/swen/spam", b"/home/swen/spam"]),
            b"/home/swen/spam"
        )
76 77 78 79 80 81 82 83 84 85 86 87
        self.assertEqual(
            commonprefix([b"home:swenson:spam", b"home:swen:spam"]),
            b"home:swen"
        )
        self.assertEqual(
            commonprefix([b":home:swen:spam", b":home:swen:eggs"]),
            b":home:swen:"
        )
        self.assertEqual(
            commonprefix([b":home:swen:spam", b":home:swen:spam"]),
            b":home:swen:spam"
        )
88 89 90 91 92 93 94 95 96 97 98 99

        testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd',
                    'aXc', 'abd', 'ab', 'aX', 'abcX']
        for s1 in testlist:
            for s2 in testlist:
                p = commonprefix([s1, s2])
                self.assertTrue(s1.startswith(p))
                self.assertTrue(s2.startswith(p))
                if s1 != s2:
                    n = len(p)
                    self.assertNotEqual(s1[n:n+1], s2[n:n+1])

100
    def test_getsize(self):
101
        f = open(support.TESTFN, "wb")
102
        try:
Guido van Rossum's avatar
Guido van Rossum committed
103
            f.write(b"foo")
104
            f.close()
105
            self.assertEqual(self.pathmodule.getsize(support.TESTFN), 3)
106 107 108
        finally:
            if not f.closed:
                f.close()
109
            support.unlink(support.TESTFN)
110 111

    def test_time(self):
112
        f = open(support.TESTFN, "wb")
113
        try:
Guido van Rossum's avatar
Guido van Rossum committed
114
            f.write(b"foo")
115
            f.close()
116
            f = open(support.TESTFN, "ab")
Guido van Rossum's avatar
Guido van Rossum committed
117
            f.write(b"bar")
118
            f.close()
119
            f = open(support.TESTFN, "rb")
120 121
            d = f.read()
            f.close()
122
            self.assertEqual(d, b"foobar")
123

124
            self.assertLessEqual(
125 126
                self.pathmodule.getctime(support.TESTFN),
                self.pathmodule.getmtime(support.TESTFN)
127 128 129 130
            )
        finally:
            if not f.closed:
                f.close()
131
            support.unlink(support.TESTFN)
132 133

    def test_exists(self):
134
        self.assertIs(self.pathmodule.exists(support.TESTFN), False)
135
        f = open(support.TESTFN, "wb")
136
        try:
Guido van Rossum's avatar
Guido van Rossum committed
137
            f.write(b"foo")
138
            f.close()
139 140 141 142
            self.assertIs(self.pathmodule.exists(support.TESTFN), True)
            if not self.pathmodule == genericpath:
                self.assertIs(self.pathmodule.lexists(support.TESTFN),
                              True)
143 144 145
        finally:
            if not f.close():
                f.close()
146
            support.unlink(support.TESTFN)
147 148

    def test_isdir(self):
149
        self.assertIs(self.pathmodule.isdir(support.TESTFN), False)
150
        f = open(support.TESTFN, "wb")
151
        try:
Guido van Rossum's avatar
Guido van Rossum committed
152
            f.write(b"foo")
153
            f.close()
154
            self.assertIs(self.pathmodule.isdir(support.TESTFN), False)
155 156
            os.remove(support.TESTFN)
            os.mkdir(support.TESTFN)
157
            self.assertIs(self.pathmodule.isdir(support.TESTFN), True)
158
            os.rmdir(support.TESTFN)
159 160 161
        finally:
            if not f.close():
                f.close()
162 163
            support.unlink(support.TESTFN)
            safe_rmdir(support.TESTFN)
164 165

    def test_isfile(self):
166
        self.assertIs(self.pathmodule.isfile(support.TESTFN), False)
167
        f = open(support.TESTFN, "wb")
168
        try:
Guido van Rossum's avatar
Guido van Rossum committed
169
            f.write(b"foo")
170
            f.close()
171
            self.assertIs(self.pathmodule.isfile(support.TESTFN), True)
172 173
            os.remove(support.TESTFN)
            os.mkdir(support.TESTFN)
174
            self.assertIs(self.pathmodule.isfile(support.TESTFN), False)
175
            os.rmdir(support.TESTFN)
176 177 178
        finally:
            if not f.close():
                f.close()
179 180 181 182
            support.unlink(support.TESTFN)
            safe_rmdir(support.TESTFN)


183 184 185
# Following TestCase is not supposed to be run from test_genericpath.
# It is inherited by other test modules (macpath, ntpath, posixpath).

186 187 188 189 190 191 192 193 194 195 196 197 198 199
class CommonTest(GenericTest):
    # The path module to be tested
    pathmodule = None
    common_attributes = GenericTest.common_attributes + [
        # Properties
        'curdir', 'pardir', 'extsep', 'sep',
        'pathsep', 'defpath', 'altsep', 'devnull',
        # Methods
        'normcase', 'splitdrive', 'expandvars', 'normpath', 'abspath',
        'join', 'split', 'splitext', 'isabs', 'basename', 'dirname',
        'lexists', 'islink', 'ismount', 'expanduser', 'normpath', 'realpath',
    ]

    def test_normcase(self):
200 201 202 203 204 205 206 207 208 209 210 211
        normcase = self.pathmodule.normcase
        # check that normcase() is idempotent
        for p in ["FoO/./BaR", b"FoO/./BaR"]:
            p = normcase(p)
            self.assertEqual(p, normcase(p))

        self.assertEqual(normcase(''), '')
        self.assertEqual(normcase(b''), b'')

        # check that normcase raises a TypeError for invalid types
        for path in (None, True, 0, 2.5, [], bytearray(b''), {'o','o'}):
            self.assertRaises(TypeError, normcase, path)
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

    def test_splitdrive(self):
        # splitdrive for non-NT paths
        splitdrive = self.pathmodule.splitdrive
        self.assertEqual(splitdrive("/foo/bar"), ("", "/foo/bar"))
        self.assertEqual(splitdrive("foo:bar"), ("", "foo:bar"))
        self.assertEqual(splitdrive(":foo:bar"), ("", ":foo:bar"))

        self.assertEqual(splitdrive(b"/foo/bar"), (b"", b"/foo/bar"))
        self.assertEqual(splitdrive(b"foo:bar"), (b"", b"foo:bar"))
        self.assertEqual(splitdrive(b":foo:bar"), (b"", b":foo:bar"))

    def test_expandvars(self):
        if self.pathmodule.__name__ == 'macpath':
            self.skipTest('macpath.expandvars is a stub')
        expandvars = self.pathmodule.expandvars
        with support.EnvironmentVarGuard() as env:
            env.clear()
            env["foo"] = "bar"
            env["{foo"] = "baz1"
            env["{foo}"] = "baz2"
            self.assertEqual(expandvars("foo"), "foo")
            self.assertEqual(expandvars("$foo bar"), "bar bar")
            self.assertEqual(expandvars("${foo}bar"), "barbar")
            self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar")
            self.assertEqual(expandvars("$bar bar"), "$bar bar")
            self.assertEqual(expandvars("$?bar"), "$?bar")
            self.assertEqual(expandvars("${foo}bar"), "barbar")
            self.assertEqual(expandvars("$foo}bar"), "bar}bar")
            self.assertEqual(expandvars("${foo"), "${foo")
            self.assertEqual(expandvars("${{foo}}"), "baz1}")
            self.assertEqual(expandvars("$foo$foo"), "barbar")
            self.assertEqual(expandvars("$bar$bar"), "$bar$bar")

            self.assertEqual(expandvars(b"foo"), b"foo")
            self.assertEqual(expandvars(b"$foo bar"), b"bar bar")
            self.assertEqual(expandvars(b"${foo}bar"), b"barbar")
            self.assertEqual(expandvars(b"$[foo]bar"), b"$[foo]bar")
            self.assertEqual(expandvars(b"$bar bar"), b"$bar bar")
            self.assertEqual(expandvars(b"$?bar"), b"$?bar")
            self.assertEqual(expandvars(b"${foo}bar"), b"barbar")
            self.assertEqual(expandvars(b"$foo}bar"), b"bar}bar")
            self.assertEqual(expandvars(b"${foo"), b"${foo")
            self.assertEqual(expandvars(b"${{foo}}"), b"baz1}")
            self.assertEqual(expandvars(b"$foo$foo"), b"barbar")
            self.assertEqual(expandvars(b"$bar$bar"), b"$bar$bar")

    def test_abspath(self):
        self.assertIn("foo", self.pathmodule.abspath("foo"))
        self.assertIn(b"foo", self.pathmodule.abspath(b"foo"))

        # Abspath returns bytes when the arg is bytes
        for path in (b'', b'foo', b'f\xf2\xf2', b'/foo', b'C:\\'):
            self.assertIsInstance(self.pathmodule.abspath(path), bytes)

    def test_realpath(self):
        self.assertIn("foo", self.pathmodule.realpath("foo"))
        self.assertIn(b"foo", self.pathmodule.realpath(b"foo"))

    def test_normpath_issue5827(self):
        # Make sure normpath preserves unicode
        for path in ('', '.', '/', '\\', '///foo/.//bar//'):
            self.assertIsInstance(self.pathmodule.normpath(path), str)

    def test_abspath_issue3426(self):
        # Check that abspath returns unicode when the arg is unicode
        # with both ASCII and non-ASCII cwds.
        abspath = self.pathmodule.abspath
        for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
            self.assertIsInstance(abspath(path), str)

        unicwd = '\xe7w\xf0'
        try:
            fsencoding = support.TESTFN_ENCODING or "ascii"
            unicwd.encode(fsencoding)
        except (AttributeError, UnicodeEncodeError):
            # FS encoding is probably ASCII
            pass
        else:
            with support.temp_cwd(unicwd):
                for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
                    self.assertIsInstance(abspath(path), str)

295
    @unittest.skipIf(sys.platform == 'darwin',
296
        "Mac OS X denies the creation of a directory with an invalid utf8 name")
297
    def test_nonascii_abspath(self):
298
        # Test non-ASCII, non-UTF8 bytes in the path.
299
        with support.temp_cwd(b'\xe7w\xf0'):
300 301
            self.test_abspath()

302 303

def test_main():
304 305
    support.run_unittest(GenericTest)

306 307 308

if __name__=="__main__":
    test_main()