blob: 97fc5d8ad783829f502455952a3941648669ed71 [file] [log] [blame]
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001import collections.abc
Antoine Pitrou31119e42013-11-22 17:38:12 +01002import io
3import os
Przemysław Spodymek216b7452018-08-27 23:33:45 +02004import sys
Antoine Pitrou31119e42013-11-22 17:38:12 +01005import errno
6import pathlib
7import pickle
Antoine Pitrou31119e42013-11-22 17:38:12 +01008import socket
9import stat
Antoine Pitrou31119e42013-11-22 17:38:12 +010010import tempfile
11import unittest
Armin Rigo22a594a2017-04-13 20:08:15 +020012from unittest import mock
Antoine Pitrou31119e42013-11-22 17:38:12 +010013
14from test import support
Serhiy Storchakab21d1552018-03-02 11:53:51 +020015from test.support import TESTFN, FakePath
Antoine Pitrou31119e42013-11-22 17:38:12 +010016
17try:
18 import grp, pwd
19except ImportError:
20 grp = pwd = None
21
22
23class _BaseFlavourTest(object):
24
25 def _check_parse_parts(self, arg, expected):
26 f = self.flavour.parse_parts
27 sep = self.flavour.sep
28 altsep = self.flavour.altsep
29 actual = f([x.replace('/', sep) for x in arg])
30 self.assertEqual(actual, expected)
31 if altsep:
32 actual = f([x.replace('/', altsep) for x in arg])
33 self.assertEqual(actual, expected)
34
35 def test_parse_parts_common(self):
36 check = self._check_parse_parts
37 sep = self.flavour.sep
Anthony Shaw83da9262019-01-07 07:31:29 +110038 # Unanchored parts.
Antoine Pitrou31119e42013-11-22 17:38:12 +010039 check([], ('', '', []))
40 check(['a'], ('', '', ['a']))
41 check(['a/'], ('', '', ['a']))
42 check(['a', 'b'], ('', '', ['a', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +110043 # Expansion.
Antoine Pitrou31119e42013-11-22 17:38:12 +010044 check(['a/b'], ('', '', ['a', 'b']))
45 check(['a/b/'], ('', '', ['a', 'b']))
46 check(['a', 'b/c', 'd'], ('', '', ['a', 'b', 'c', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +110047 # Collapsing and stripping excess slashes.
Antoine Pitrou31119e42013-11-22 17:38:12 +010048 check(['a', 'b//c', 'd'], ('', '', ['a', 'b', 'c', 'd']))
49 check(['a', 'b/c/', 'd'], ('', '', ['a', 'b', 'c', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +110050 # Eliminating standalone dots.
Antoine Pitrou31119e42013-11-22 17:38:12 +010051 check(['.'], ('', '', []))
52 check(['.', '.', 'b'], ('', '', ['b']))
53 check(['a', '.', 'b'], ('', '', ['a', 'b']))
54 check(['a', '.', '.'], ('', '', ['a']))
Anthony Shaw83da9262019-01-07 07:31:29 +110055 # The first part is anchored.
Antoine Pitrou31119e42013-11-22 17:38:12 +010056 check(['/a/b'], ('', sep, [sep, 'a', 'b']))
57 check(['/a', 'b'], ('', sep, [sep, 'a', 'b']))
58 check(['/a/', 'b'], ('', sep, [sep, 'a', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +110059 # Ignoring parts before an anchored part.
Antoine Pitrou31119e42013-11-22 17:38:12 +010060 check(['a', '/b', 'c'], ('', sep, [sep, 'b', 'c']))
61 check(['a', '/b', '/c'], ('', sep, [sep, 'c']))
62
63
64class PosixFlavourTest(_BaseFlavourTest, unittest.TestCase):
65 flavour = pathlib._posix_flavour
66
67 def test_parse_parts(self):
68 check = self._check_parse_parts
69 # Collapsing of excess leading slashes, except for the double-slash
70 # special case.
71 check(['//a', 'b'], ('', '//', ['//', 'a', 'b']))
72 check(['///a', 'b'], ('', '/', ['/', 'a', 'b']))
73 check(['////a', 'b'], ('', '/', ['/', 'a', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +110074 # Paths which look like NT paths aren't treated specially.
Antoine Pitrou31119e42013-11-22 17:38:12 +010075 check(['c:a'], ('', '', ['c:a']))
76 check(['c:\\a'], ('', '', ['c:\\a']))
77 check(['\\a'], ('', '', ['\\a']))
78
79 def test_splitroot(self):
80 f = self.flavour.splitroot
81 self.assertEqual(f(''), ('', '', ''))
82 self.assertEqual(f('a'), ('', '', 'a'))
83 self.assertEqual(f('a/b'), ('', '', 'a/b'))
84 self.assertEqual(f('a/b/'), ('', '', 'a/b/'))
85 self.assertEqual(f('/a'), ('', '/', 'a'))
86 self.assertEqual(f('/a/b'), ('', '/', 'a/b'))
87 self.assertEqual(f('/a/b/'), ('', '/', 'a/b/'))
88 # The root is collapsed when there are redundant slashes
89 # except when there are exactly two leading slashes, which
90 # is a special case in POSIX.
91 self.assertEqual(f('//a'), ('', '//', 'a'))
92 self.assertEqual(f('///a'), ('', '/', 'a'))
93 self.assertEqual(f('///a/b'), ('', '/', 'a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +110094 # Paths which look like NT paths aren't treated specially.
Antoine Pitrou31119e42013-11-22 17:38:12 +010095 self.assertEqual(f('c:/a/b'), ('', '', 'c:/a/b'))
96 self.assertEqual(f('\\/a/b'), ('', '', '\\/a/b'))
97 self.assertEqual(f('\\a\\b'), ('', '', '\\a\\b'))
98
99
100class NTFlavourTest(_BaseFlavourTest, unittest.TestCase):
101 flavour = pathlib._windows_flavour
102
103 def test_parse_parts(self):
104 check = self._check_parse_parts
Anthony Shaw83da9262019-01-07 07:31:29 +1100105 # First part is anchored.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100106 check(['c:'], ('c:', '', ['c:']))
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100107 check(['c:/'], ('c:', '\\', ['c:\\']))
108 check(['/'], ('', '\\', ['\\']))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100109 check(['c:a'], ('c:', '', ['c:', 'a']))
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100110 check(['c:/a'], ('c:', '\\', ['c:\\', 'a']))
111 check(['/a'], ('', '\\', ['\\', 'a']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100112 # UNC paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100113 check(['//a/b'], ('\\\\a\\b', '\\', ['\\\\a\\b\\']))
114 check(['//a/b/'], ('\\\\a\\b', '\\', ['\\\\a\\b\\']))
115 check(['//a/b/c'], ('\\\\a\\b', '\\', ['\\\\a\\b\\', 'c']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100116 # Second part is anchored, so that the first part is ignored.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100117 check(['a', 'Z:b', 'c'], ('Z:', '', ['Z:', 'b', 'c']))
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100118 check(['a', 'Z:/b', 'c'], ('Z:', '\\', ['Z:\\', 'b', 'c']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100119 # UNC paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100120 check(['a', '//b/c', 'd'], ('\\\\b\\c', '\\', ['\\\\b\\c\\', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100121 # Collapsing and stripping excess slashes.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100122 check(['a', 'Z://b//c/', 'd/'], ('Z:', '\\', ['Z:\\', 'b', 'c', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100123 # UNC paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100124 check(['a', '//b/c//', 'd'], ('\\\\b\\c', '\\', ['\\\\b\\c\\', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100125 # Extended paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100126 check(['//?/c:/'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\']))
127 check(['//?/c:/a'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\', 'a']))
128 check(['//?/c:/a', '/b'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100129 # Extended UNC paths (format is "\\?\UNC\server\share").
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100130 check(['//?/UNC/b/c'], ('\\\\?\\UNC\\b\\c', '\\', ['\\\\?\\UNC\\b\\c\\']))
131 check(['//?/UNC/b/c/d'], ('\\\\?\\UNC\\b\\c', '\\', ['\\\\?\\UNC\\b\\c\\', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100132 # Second part has a root but not drive.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100133 check(['a', '/b', 'c'], ('', '\\', ['\\', 'b', 'c']))
134 check(['Z:/a', '/b', 'c'], ('Z:', '\\', ['Z:\\', 'b', 'c']))
135 check(['//?/Z:/a', '/b', 'c'], ('\\\\?\\Z:', '\\', ['\\\\?\\Z:\\', 'b', 'c']))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100136
137 def test_splitroot(self):
138 f = self.flavour.splitroot
139 self.assertEqual(f(''), ('', '', ''))
140 self.assertEqual(f('a'), ('', '', 'a'))
141 self.assertEqual(f('a\\b'), ('', '', 'a\\b'))
142 self.assertEqual(f('\\a'), ('', '\\', 'a'))
143 self.assertEqual(f('\\a\\b'), ('', '\\', 'a\\b'))
144 self.assertEqual(f('c:a\\b'), ('c:', '', 'a\\b'))
145 self.assertEqual(f('c:\\a\\b'), ('c:', '\\', 'a\\b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100146 # Redundant slashes in the root are collapsed.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100147 self.assertEqual(f('\\\\a'), ('', '\\', 'a'))
148 self.assertEqual(f('\\\\\\a/b'), ('', '\\', 'a/b'))
149 self.assertEqual(f('c:\\\\a'), ('c:', '\\', 'a'))
150 self.assertEqual(f('c:\\\\\\a/b'), ('c:', '\\', 'a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100151 # Valid UNC paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100152 self.assertEqual(f('\\\\a\\b'), ('\\\\a\\b', '\\', ''))
153 self.assertEqual(f('\\\\a\\b\\'), ('\\\\a\\b', '\\', ''))
154 self.assertEqual(f('\\\\a\\b\\c\\d'), ('\\\\a\\b', '\\', 'c\\d'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100155 # These are non-UNC paths (according to ntpath.py and test_ntpath).
Antoine Pitrou31119e42013-11-22 17:38:12 +0100156 # However, command.com says such paths are invalid, so it's
Anthony Shaw83da9262019-01-07 07:31:29 +1100157 # difficult to know what the right semantics are.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100158 self.assertEqual(f('\\\\\\a\\b'), ('', '\\', 'a\\b'))
159 self.assertEqual(f('\\\\a'), ('', '\\', 'a'))
160
161
162#
Anthony Shaw83da9262019-01-07 07:31:29 +1100163# Tests for the pure classes.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100164#
165
166class _BasePurePathTest(object):
167
Anthony Shaw83da9262019-01-07 07:31:29 +1100168 # Keys are canonical paths, values are list of tuples of arguments
169 # supposed to produce equal paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100170 equivalences = {
171 'a/b': [
172 ('a', 'b'), ('a/', 'b'), ('a', 'b/'), ('a/', 'b/'),
173 ('a/b/',), ('a//b',), ('a//b//',),
Anthony Shaw83da9262019-01-07 07:31:29 +1100174 # Empty components get removed.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100175 ('', 'a', 'b'), ('a', '', 'b'), ('a', 'b', ''),
176 ],
177 '/b/c/d': [
178 ('a', '/b/c', 'd'), ('a', '///b//c', 'd/'),
179 ('/a', '/b/c', 'd'),
Anthony Shaw83da9262019-01-07 07:31:29 +1100180 # Empty components get removed.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100181 ('/', 'b', '', 'c/d'), ('/', '', 'b/c/d'), ('', '/b/c/d'),
182 ],
183 }
184
185 def setUp(self):
186 p = self.cls('a')
187 self.flavour = p._flavour
188 self.sep = self.flavour.sep
189 self.altsep = self.flavour.altsep
190
191 def test_constructor_common(self):
192 P = self.cls
193 p = P('a')
194 self.assertIsInstance(p, P)
195 P('a', 'b', 'c')
196 P('/a', 'b', 'c')
197 P('a/b/c')
198 P('/a/b/c')
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200199 P(FakePath("a/b/c"))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100200 self.assertEqual(P(P('a')), P('a'))
201 self.assertEqual(P(P('a'), 'b'), P('a/b'))
202 self.assertEqual(P(P('a'), P('b')), P('a/b'))
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200203 self.assertEqual(P(P('a'), P('b'), P('c')), P(FakePath("a/b/c")))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100204
Antoine Pitroucb5ec772014-04-23 00:34:15 +0200205 def _check_str_subclass(self, *args):
206 # Issue #21127: it should be possible to construct a PurePath object
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300207 # from a str subclass instance, and it then gets converted to
Antoine Pitroucb5ec772014-04-23 00:34:15 +0200208 # a pure str object.
209 class StrSubclass(str):
210 pass
211 P = self.cls
212 p = P(*(StrSubclass(x) for x in args))
213 self.assertEqual(p, P(*args))
214 for part in p.parts:
215 self.assertIs(type(part), str)
216
217 def test_str_subclass_common(self):
218 self._check_str_subclass('')
219 self._check_str_subclass('.')
220 self._check_str_subclass('a')
221 self._check_str_subclass('a/b.txt')
222 self._check_str_subclass('/a/b.txt')
223
Antoine Pitrou31119e42013-11-22 17:38:12 +0100224 def test_join_common(self):
225 P = self.cls
226 p = P('a/b')
227 pp = p.joinpath('c')
228 self.assertEqual(pp, P('a/b/c'))
229 self.assertIs(type(pp), type(p))
230 pp = p.joinpath('c', 'd')
231 self.assertEqual(pp, P('a/b/c/d'))
232 pp = p.joinpath(P('c'))
233 self.assertEqual(pp, P('a/b/c'))
234 pp = p.joinpath('/c')
235 self.assertEqual(pp, P('/c'))
236
237 def test_div_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100238 # Basically the same as joinpath().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100239 P = self.cls
240 p = P('a/b')
241 pp = p / 'c'
242 self.assertEqual(pp, P('a/b/c'))
243 self.assertIs(type(pp), type(p))
244 pp = p / 'c/d'
245 self.assertEqual(pp, P('a/b/c/d'))
246 pp = p / 'c' / 'd'
247 self.assertEqual(pp, P('a/b/c/d'))
248 pp = 'c' / p / 'd'
249 self.assertEqual(pp, P('c/a/b/d'))
250 pp = p / P('c')
251 self.assertEqual(pp, P('a/b/c'))
252 pp = p/ '/c'
253 self.assertEqual(pp, P('/c'))
254
255 def _check_str(self, expected, args):
256 p = self.cls(*args)
257 self.assertEqual(str(p), expected.replace('/', self.sep))
258
259 def test_str_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100260 # Canonicalized paths roundtrip.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100261 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
262 self._check_str(pathstr, (pathstr,))
Anthony Shaw83da9262019-01-07 07:31:29 +1100263 # Special case for the empty path.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100264 self._check_str('.', ('',))
Anthony Shaw83da9262019-01-07 07:31:29 +1100265 # Other tests for str() are in test_equivalences().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100266
267 def test_as_posix_common(self):
268 P = self.cls
269 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
270 self.assertEqual(P(pathstr).as_posix(), pathstr)
Anthony Shaw83da9262019-01-07 07:31:29 +1100271 # Other tests for as_posix() are in test_equivalences().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100272
273 def test_as_bytes_common(self):
274 sep = os.fsencode(self.sep)
275 P = self.cls
276 self.assertEqual(bytes(P('a/b')), b'a' + sep + b'b')
277
278 def test_as_uri_common(self):
279 P = self.cls
280 with self.assertRaises(ValueError):
281 P('a').as_uri()
282 with self.assertRaises(ValueError):
283 P().as_uri()
284
285 def test_repr_common(self):
286 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
287 p = self.cls(pathstr)
288 clsname = p.__class__.__name__
289 r = repr(p)
Anthony Shaw83da9262019-01-07 07:31:29 +1100290 # The repr() is in the form ClassName("forward-slashes path").
Antoine Pitrou31119e42013-11-22 17:38:12 +0100291 self.assertTrue(r.startswith(clsname + '('), r)
292 self.assertTrue(r.endswith(')'), r)
293 inner = r[len(clsname) + 1 : -1]
294 self.assertEqual(eval(inner), p.as_posix())
Anthony Shaw83da9262019-01-07 07:31:29 +1100295 # The repr() roundtrips.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100296 q = eval(r, pathlib.__dict__)
297 self.assertIs(q.__class__, p.__class__)
298 self.assertEqual(q, p)
299 self.assertEqual(repr(q), r)
300
301 def test_eq_common(self):
302 P = self.cls
303 self.assertEqual(P('a/b'), P('a/b'))
304 self.assertEqual(P('a/b'), P('a', 'b'))
305 self.assertNotEqual(P('a/b'), P('a'))
306 self.assertNotEqual(P('a/b'), P('/a/b'))
307 self.assertNotEqual(P('a/b'), P())
308 self.assertNotEqual(P('/a/b'), P('/'))
309 self.assertNotEqual(P(), P('/'))
310 self.assertNotEqual(P(), "")
311 self.assertNotEqual(P(), {})
312 self.assertNotEqual(P(), int)
313
314 def test_match_common(self):
315 P = self.cls
316 self.assertRaises(ValueError, P('a').match, '')
317 self.assertRaises(ValueError, P('a').match, '.')
Anthony Shaw83da9262019-01-07 07:31:29 +1100318 # Simple relative pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100319 self.assertTrue(P('b.py').match('b.py'))
320 self.assertTrue(P('a/b.py').match('b.py'))
321 self.assertTrue(P('/a/b.py').match('b.py'))
322 self.assertFalse(P('a.py').match('b.py'))
323 self.assertFalse(P('b/py').match('b.py'))
324 self.assertFalse(P('/a.py').match('b.py'))
325 self.assertFalse(P('b.py/c').match('b.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100326 # Wilcard relative pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100327 self.assertTrue(P('b.py').match('*.py'))
328 self.assertTrue(P('a/b.py').match('*.py'))
329 self.assertTrue(P('/a/b.py').match('*.py'))
330 self.assertFalse(P('b.pyc').match('*.py'))
331 self.assertFalse(P('b./py').match('*.py'))
332 self.assertFalse(P('b.py/c').match('*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100333 # Multi-part relative pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100334 self.assertTrue(P('ab/c.py').match('a*/*.py'))
335 self.assertTrue(P('/d/ab/c.py').match('a*/*.py'))
336 self.assertFalse(P('a.py').match('a*/*.py'))
337 self.assertFalse(P('/dab/c.py').match('a*/*.py'))
338 self.assertFalse(P('ab/c.py/d').match('a*/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100339 # Absolute pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100340 self.assertTrue(P('/b.py').match('/*.py'))
341 self.assertFalse(P('b.py').match('/*.py'))
342 self.assertFalse(P('a/b.py').match('/*.py'))
343 self.assertFalse(P('/a/b.py').match('/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100344 # Multi-part absolute pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100345 self.assertTrue(P('/a/b.py').match('/a/*.py'))
346 self.assertFalse(P('/ab.py').match('/a/*.py'))
347 self.assertFalse(P('/a/b/c.py').match('/a/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100348 # Multi-part glob-style pattern.
349 self.assertFalse(P('/a/b/c.py').match('/**/*.py'))
350 self.assertTrue(P('/a/b/c.py').match('/a/**/*.py'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100351
352 def test_ordering_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100353 # Ordering is tuple-alike.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100354 def assertLess(a, b):
355 self.assertLess(a, b)
356 self.assertGreater(b, a)
357 P = self.cls
358 a = P('a')
359 b = P('a/b')
360 c = P('abc')
361 d = P('b')
362 assertLess(a, b)
363 assertLess(a, c)
364 assertLess(a, d)
365 assertLess(b, c)
366 assertLess(c, d)
367 P = self.cls
368 a = P('/a')
369 b = P('/a/b')
370 c = P('/abc')
371 d = P('/b')
372 assertLess(a, b)
373 assertLess(a, c)
374 assertLess(a, d)
375 assertLess(b, c)
376 assertLess(c, d)
377 with self.assertRaises(TypeError):
378 P() < {}
379
380 def test_parts_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100381 # `parts` returns a tuple.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100382 sep = self.sep
383 P = self.cls
384 p = P('a/b')
385 parts = p.parts
386 self.assertEqual(parts, ('a', 'b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100387 # The object gets reused.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100388 self.assertIs(parts, p.parts)
Anthony Shaw83da9262019-01-07 07:31:29 +1100389 # When the path is absolute, the anchor is a separate part.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100390 p = P('/a/b')
391 parts = p.parts
392 self.assertEqual(parts, (sep, 'a', 'b'))
393
Brett Cannon568be632016-06-10 12:20:49 -0700394 def test_fspath_common(self):
395 P = self.cls
396 p = P('a/b')
397 self._check_str(p.__fspath__(), ('a/b',))
398 self._check_str(os.fspath(p), ('a/b',))
399
Antoine Pitrou31119e42013-11-22 17:38:12 +0100400 def test_equivalences(self):
401 for k, tuples in self.equivalences.items():
402 canon = k.replace('/', self.sep)
403 posix = k.replace(self.sep, '/')
404 if canon != posix:
405 tuples = tuples + [
406 tuple(part.replace('/', self.sep) for part in t)
407 for t in tuples
408 ]
409 tuples.append((posix, ))
410 pcanon = self.cls(canon)
411 for t in tuples:
412 p = self.cls(*t)
413 self.assertEqual(p, pcanon, "failed with args {}".format(t))
414 self.assertEqual(hash(p), hash(pcanon))
415 self.assertEqual(str(p), canon)
416 self.assertEqual(p.as_posix(), posix)
417
418 def test_parent_common(self):
419 # Relative
420 P = self.cls
421 p = P('a/b/c')
422 self.assertEqual(p.parent, P('a/b'))
423 self.assertEqual(p.parent.parent, P('a'))
424 self.assertEqual(p.parent.parent.parent, P())
425 self.assertEqual(p.parent.parent.parent.parent, P())
426 # Anchored
427 p = P('/a/b/c')
428 self.assertEqual(p.parent, P('/a/b'))
429 self.assertEqual(p.parent.parent, P('/a'))
430 self.assertEqual(p.parent.parent.parent, P('/'))
431 self.assertEqual(p.parent.parent.parent.parent, P('/'))
432
433 def test_parents_common(self):
434 # Relative
435 P = self.cls
436 p = P('a/b/c')
437 par = p.parents
438 self.assertEqual(len(par), 3)
439 self.assertEqual(par[0], P('a/b'))
440 self.assertEqual(par[1], P('a'))
441 self.assertEqual(par[2], P('.'))
442 self.assertEqual(list(par), [P('a/b'), P('a'), P('.')])
443 with self.assertRaises(IndexError):
444 par[-1]
445 with self.assertRaises(IndexError):
446 par[3]
447 with self.assertRaises(TypeError):
448 par[0] = p
449 # Anchored
450 p = P('/a/b/c')
451 par = p.parents
452 self.assertEqual(len(par), 3)
453 self.assertEqual(par[0], P('/a/b'))
454 self.assertEqual(par[1], P('/a'))
455 self.assertEqual(par[2], P('/'))
456 self.assertEqual(list(par), [P('/a/b'), P('/a'), P('/')])
457 with self.assertRaises(IndexError):
458 par[3]
459
460 def test_drive_common(self):
461 P = self.cls
462 self.assertEqual(P('a/b').drive, '')
463 self.assertEqual(P('/a/b').drive, '')
464 self.assertEqual(P('').drive, '')
465
466 def test_root_common(self):
467 P = self.cls
468 sep = self.sep
469 self.assertEqual(P('').root, '')
470 self.assertEqual(P('a/b').root, '')
471 self.assertEqual(P('/').root, sep)
472 self.assertEqual(P('/a/b').root, sep)
473
474 def test_anchor_common(self):
475 P = self.cls
476 sep = self.sep
477 self.assertEqual(P('').anchor, '')
478 self.assertEqual(P('a/b').anchor, '')
479 self.assertEqual(P('/').anchor, sep)
480 self.assertEqual(P('/a/b').anchor, sep)
481
482 def test_name_common(self):
483 P = self.cls
484 self.assertEqual(P('').name, '')
485 self.assertEqual(P('.').name, '')
486 self.assertEqual(P('/').name, '')
487 self.assertEqual(P('a/b').name, 'b')
488 self.assertEqual(P('/a/b').name, 'b')
489 self.assertEqual(P('/a/b/.').name, 'b')
490 self.assertEqual(P('a/b.py').name, 'b.py')
491 self.assertEqual(P('/a/b.py').name, 'b.py')
492
493 def test_suffix_common(self):
494 P = self.cls
495 self.assertEqual(P('').suffix, '')
496 self.assertEqual(P('.').suffix, '')
497 self.assertEqual(P('..').suffix, '')
498 self.assertEqual(P('/').suffix, '')
499 self.assertEqual(P('a/b').suffix, '')
500 self.assertEqual(P('/a/b').suffix, '')
501 self.assertEqual(P('/a/b/.').suffix, '')
502 self.assertEqual(P('a/b.py').suffix, '.py')
503 self.assertEqual(P('/a/b.py').suffix, '.py')
504 self.assertEqual(P('a/.hgrc').suffix, '')
505 self.assertEqual(P('/a/.hgrc').suffix, '')
506 self.assertEqual(P('a/.hg.rc').suffix, '.rc')
507 self.assertEqual(P('/a/.hg.rc').suffix, '.rc')
508 self.assertEqual(P('a/b.tar.gz').suffix, '.gz')
509 self.assertEqual(P('/a/b.tar.gz').suffix, '.gz')
510 self.assertEqual(P('a/Some name. Ending with a dot.').suffix, '')
511 self.assertEqual(P('/a/Some name. Ending with a dot.').suffix, '')
512
513 def test_suffixes_common(self):
514 P = self.cls
515 self.assertEqual(P('').suffixes, [])
516 self.assertEqual(P('.').suffixes, [])
517 self.assertEqual(P('/').suffixes, [])
518 self.assertEqual(P('a/b').suffixes, [])
519 self.assertEqual(P('/a/b').suffixes, [])
520 self.assertEqual(P('/a/b/.').suffixes, [])
521 self.assertEqual(P('a/b.py').suffixes, ['.py'])
522 self.assertEqual(P('/a/b.py').suffixes, ['.py'])
523 self.assertEqual(P('a/.hgrc').suffixes, [])
524 self.assertEqual(P('/a/.hgrc').suffixes, [])
525 self.assertEqual(P('a/.hg.rc').suffixes, ['.rc'])
526 self.assertEqual(P('/a/.hg.rc').suffixes, ['.rc'])
527 self.assertEqual(P('a/b.tar.gz').suffixes, ['.tar', '.gz'])
528 self.assertEqual(P('/a/b.tar.gz').suffixes, ['.tar', '.gz'])
529 self.assertEqual(P('a/Some name. Ending with a dot.').suffixes, [])
530 self.assertEqual(P('/a/Some name. Ending with a dot.').suffixes, [])
531
532 def test_stem_common(self):
533 P = self.cls
534 self.assertEqual(P('').stem, '')
535 self.assertEqual(P('.').stem, '')
536 self.assertEqual(P('..').stem, '..')
537 self.assertEqual(P('/').stem, '')
538 self.assertEqual(P('a/b').stem, 'b')
539 self.assertEqual(P('a/b.py').stem, 'b')
540 self.assertEqual(P('a/.hgrc').stem, '.hgrc')
541 self.assertEqual(P('a/.hg.rc').stem, '.hg')
542 self.assertEqual(P('a/b.tar.gz').stem, 'b.tar')
543 self.assertEqual(P('a/Some name. Ending with a dot.').stem,
544 'Some name. Ending with a dot.')
545
546 def test_with_name_common(self):
547 P = self.cls
548 self.assertEqual(P('a/b').with_name('d.xml'), P('a/d.xml'))
549 self.assertEqual(P('/a/b').with_name('d.xml'), P('/a/d.xml'))
550 self.assertEqual(P('a/b.py').with_name('d.xml'), P('a/d.xml'))
551 self.assertEqual(P('/a/b.py').with_name('d.xml'), P('/a/d.xml'))
552 self.assertEqual(P('a/Dot ending.').with_name('d.xml'), P('a/d.xml'))
553 self.assertEqual(P('/a/Dot ending.').with_name('d.xml'), P('/a/d.xml'))
554 self.assertRaises(ValueError, P('').with_name, 'd.xml')
555 self.assertRaises(ValueError, P('.').with_name, 'd.xml')
556 self.assertRaises(ValueError, P('/').with_name, 'd.xml')
Antoine Pitrou7084e732014-07-06 21:31:12 -0400557 self.assertRaises(ValueError, P('a/b').with_name, '')
558 self.assertRaises(ValueError, P('a/b').with_name, '/c')
559 self.assertRaises(ValueError, P('a/b').with_name, 'c/')
560 self.assertRaises(ValueError, P('a/b').with_name, 'c/d')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100561
562 def test_with_suffix_common(self):
563 P = self.cls
564 self.assertEqual(P('a/b').with_suffix('.gz'), P('a/b.gz'))
565 self.assertEqual(P('/a/b').with_suffix('.gz'), P('/a/b.gz'))
566 self.assertEqual(P('a/b.py').with_suffix('.gz'), P('a/b.gz'))
567 self.assertEqual(P('/a/b.py').with_suffix('.gz'), P('/a/b.gz'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100568 # Stripping suffix.
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400569 self.assertEqual(P('a/b.py').with_suffix(''), P('a/b'))
570 self.assertEqual(P('/a/b').with_suffix(''), P('/a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100571 # Path doesn't have a "filename" component.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100572 self.assertRaises(ValueError, P('').with_suffix, '.gz')
573 self.assertRaises(ValueError, P('.').with_suffix, '.gz')
574 self.assertRaises(ValueError, P('/').with_suffix, '.gz')
Anthony Shaw83da9262019-01-07 07:31:29 +1100575 # Invalid suffix.
Antoine Pitrou1b02da92014-01-03 00:07:17 +0100576 self.assertRaises(ValueError, P('a/b').with_suffix, 'gz')
577 self.assertRaises(ValueError, P('a/b').with_suffix, '/')
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400578 self.assertRaises(ValueError, P('a/b').with_suffix, '.')
Antoine Pitrou1b02da92014-01-03 00:07:17 +0100579 self.assertRaises(ValueError, P('a/b').with_suffix, '/.gz')
580 self.assertRaises(ValueError, P('a/b').with_suffix, 'c/d')
581 self.assertRaises(ValueError, P('a/b').with_suffix, '.c/.d')
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400582 self.assertRaises(ValueError, P('a/b').with_suffix, './.d')
583 self.assertRaises(ValueError, P('a/b').with_suffix, '.d/.')
Berker Peksag423d05f2018-08-11 08:45:06 +0300584 self.assertRaises(ValueError, P('a/b').with_suffix,
585 (self.flavour.sep, 'd'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100586
587 def test_relative_to_common(self):
588 P = self.cls
589 p = P('a/b')
590 self.assertRaises(TypeError, p.relative_to)
Antoine Pitrou156b3612013-12-28 19:49:04 +0100591 self.assertRaises(TypeError, p.relative_to, b'a')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100592 self.assertEqual(p.relative_to(P()), P('a/b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100593 self.assertEqual(p.relative_to(''), P('a/b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100594 self.assertEqual(p.relative_to(P('a')), P('b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100595 self.assertEqual(p.relative_to('a'), P('b'))
596 self.assertEqual(p.relative_to('a/'), P('b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100597 self.assertEqual(p.relative_to(P('a/b')), P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100598 self.assertEqual(p.relative_to('a/b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100599 # With several args.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100600 self.assertEqual(p.relative_to('a', 'b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100601 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100602 self.assertRaises(ValueError, p.relative_to, P('c'))
603 self.assertRaises(ValueError, p.relative_to, P('a/b/c'))
604 self.assertRaises(ValueError, p.relative_to, P('a/c'))
605 self.assertRaises(ValueError, p.relative_to, P('/a'))
606 p = P('/a/b')
607 self.assertEqual(p.relative_to(P('/')), P('a/b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100608 self.assertEqual(p.relative_to('/'), P('a/b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100609 self.assertEqual(p.relative_to(P('/a')), P('b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100610 self.assertEqual(p.relative_to('/a'), P('b'))
611 self.assertEqual(p.relative_to('/a/'), P('b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100612 self.assertEqual(p.relative_to(P('/a/b')), P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100613 self.assertEqual(p.relative_to('/a/b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100614 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100615 self.assertRaises(ValueError, p.relative_to, P('/c'))
616 self.assertRaises(ValueError, p.relative_to, P('/a/b/c'))
617 self.assertRaises(ValueError, p.relative_to, P('/a/c'))
618 self.assertRaises(ValueError, p.relative_to, P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100619 self.assertRaises(ValueError, p.relative_to, '')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100620 self.assertRaises(ValueError, p.relative_to, P('a'))
621
622 def test_pickling_common(self):
623 P = self.cls
624 p = P('/a/b')
625 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
626 dumped = pickle.dumps(p, proto)
627 pp = pickle.loads(dumped)
628 self.assertIs(pp.__class__, p.__class__)
629 self.assertEqual(pp, p)
630 self.assertEqual(hash(pp), hash(p))
631 self.assertEqual(str(pp), str(p))
632
633
634class PurePosixPathTest(_BasePurePathTest, unittest.TestCase):
635 cls = pathlib.PurePosixPath
636
637 def test_root(self):
638 P = self.cls
639 self.assertEqual(P('/a/b').root, '/')
640 self.assertEqual(P('///a/b').root, '/')
Anthony Shaw83da9262019-01-07 07:31:29 +1100641 # POSIX special case for two leading slashes.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100642 self.assertEqual(P('//a/b').root, '//')
643
644 def test_eq(self):
645 P = self.cls
646 self.assertNotEqual(P('a/b'), P('A/b'))
647 self.assertEqual(P('/a'), P('///a'))
648 self.assertNotEqual(P('/a'), P('//a'))
649
650 def test_as_uri(self):
Antoine Pitrou31119e42013-11-22 17:38:12 +0100651 P = self.cls
652 self.assertEqual(P('/').as_uri(), 'file:///')
653 self.assertEqual(P('/a/b.c').as_uri(), 'file:///a/b.c')
654 self.assertEqual(P('/a/b%#c').as_uri(), 'file:///a/b%25%23c')
Antoine Pitrou29eac422013-11-22 17:57:03 +0100655
656 def test_as_uri_non_ascii(self):
657 from urllib.parse import quote_from_bytes
658 P = self.cls
659 try:
660 os.fsencode('\xe9')
661 except UnicodeEncodeError:
662 self.skipTest("\\xe9 cannot be encoded to the filesystem encoding")
Antoine Pitrou31119e42013-11-22 17:38:12 +0100663 self.assertEqual(P('/a/b\xe9').as_uri(),
664 'file:///a/b' + quote_from_bytes(os.fsencode('\xe9')))
665
666 def test_match(self):
667 P = self.cls
668 self.assertFalse(P('A.py').match('a.PY'))
669
670 def test_is_absolute(self):
671 P = self.cls
672 self.assertFalse(P().is_absolute())
673 self.assertFalse(P('a').is_absolute())
674 self.assertFalse(P('a/b/').is_absolute())
675 self.assertTrue(P('/').is_absolute())
676 self.assertTrue(P('/a').is_absolute())
677 self.assertTrue(P('/a/b/').is_absolute())
678 self.assertTrue(P('//a').is_absolute())
679 self.assertTrue(P('//a/b').is_absolute())
680
681 def test_is_reserved(self):
682 P = self.cls
683 self.assertIs(False, P('').is_reserved())
684 self.assertIs(False, P('/').is_reserved())
685 self.assertIs(False, P('/foo/bar').is_reserved())
686 self.assertIs(False, P('/dev/con/PRN/NUL').is_reserved())
687
688 def test_join(self):
689 P = self.cls
690 p = P('//a')
691 pp = p.joinpath('b')
692 self.assertEqual(pp, P('//a/b'))
693 pp = P('/a').joinpath('//c')
694 self.assertEqual(pp, P('//c'))
695 pp = P('//a').joinpath('/c')
696 self.assertEqual(pp, P('/c'))
697
698 def test_div(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100699 # Basically the same as joinpath().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100700 P = self.cls
701 p = P('//a')
702 pp = p / 'b'
703 self.assertEqual(pp, P('//a/b'))
704 pp = P('/a') / '//c'
705 self.assertEqual(pp, P('//c'))
706 pp = P('//a') / '/c'
707 self.assertEqual(pp, P('/c'))
708
709
710class PureWindowsPathTest(_BasePurePathTest, unittest.TestCase):
711 cls = pathlib.PureWindowsPath
712
713 equivalences = _BasePurePathTest.equivalences.copy()
714 equivalences.update({
715 'c:a': [ ('c:', 'a'), ('c:', 'a/'), ('/', 'c:', 'a') ],
716 'c:/a': [
717 ('c:/', 'a'), ('c:', '/', 'a'), ('c:', '/a'),
718 ('/z', 'c:/', 'a'), ('//x/y', 'c:/', 'a'),
719 ],
720 '//a/b/': [ ('//a/b',) ],
721 '//a/b/c': [
722 ('//a/b', 'c'), ('//a/b/', 'c'),
723 ],
724 })
725
726 def test_str(self):
727 p = self.cls('a/b/c')
728 self.assertEqual(str(p), 'a\\b\\c')
729 p = self.cls('c:/a/b/c')
730 self.assertEqual(str(p), 'c:\\a\\b\\c')
731 p = self.cls('//a/b')
732 self.assertEqual(str(p), '\\\\a\\b\\')
733 p = self.cls('//a/b/c')
734 self.assertEqual(str(p), '\\\\a\\b\\c')
735 p = self.cls('//a/b/c/d')
736 self.assertEqual(str(p), '\\\\a\\b\\c\\d')
737
Antoine Pitroucb5ec772014-04-23 00:34:15 +0200738 def test_str_subclass(self):
739 self._check_str_subclass('c:')
740 self._check_str_subclass('c:a')
741 self._check_str_subclass('c:a\\b.txt')
742 self._check_str_subclass('c:\\')
743 self._check_str_subclass('c:\\a')
744 self._check_str_subclass('c:\\a\\b.txt')
745 self._check_str_subclass('\\\\some\\share')
746 self._check_str_subclass('\\\\some\\share\\a')
747 self._check_str_subclass('\\\\some\\share\\a\\b.txt')
748
Antoine Pitrou31119e42013-11-22 17:38:12 +0100749 def test_eq(self):
750 P = self.cls
751 self.assertEqual(P('c:a/b'), P('c:a/b'))
752 self.assertEqual(P('c:a/b'), P('c:', 'a', 'b'))
753 self.assertNotEqual(P('c:a/b'), P('d:a/b'))
754 self.assertNotEqual(P('c:a/b'), P('c:/a/b'))
755 self.assertNotEqual(P('/a/b'), P('c:/a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100756 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100757 self.assertEqual(P('a/B'), P('A/b'))
758 self.assertEqual(P('C:a/B'), P('c:A/b'))
759 self.assertEqual(P('//Some/SHARE/a/B'), P('//somE/share/A/b'))
760
761 def test_as_uri(self):
Antoine Pitrou31119e42013-11-22 17:38:12 +0100762 P = self.cls
763 with self.assertRaises(ValueError):
764 P('/a/b').as_uri()
765 with self.assertRaises(ValueError):
766 P('c:a/b').as_uri()
767 self.assertEqual(P('c:/').as_uri(), 'file:///c:/')
768 self.assertEqual(P('c:/a/b.c').as_uri(), 'file:///c:/a/b.c')
769 self.assertEqual(P('c:/a/b%#c').as_uri(), 'file:///c:/a/b%25%23c')
770 self.assertEqual(P('c:/a/b\xe9').as_uri(), 'file:///c:/a/b%C3%A9')
771 self.assertEqual(P('//some/share/').as_uri(), 'file://some/share/')
772 self.assertEqual(P('//some/share/a/b.c').as_uri(),
773 'file://some/share/a/b.c')
774 self.assertEqual(P('//some/share/a/b%#c\xe9').as_uri(),
775 'file://some/share/a/b%25%23c%C3%A9')
776
777 def test_match_common(self):
778 P = self.cls
Anthony Shaw83da9262019-01-07 07:31:29 +1100779 # Absolute patterns.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100780 self.assertTrue(P('c:/b.py').match('/*.py'))
781 self.assertTrue(P('c:/b.py').match('c:*.py'))
782 self.assertTrue(P('c:/b.py').match('c:/*.py'))
783 self.assertFalse(P('d:/b.py').match('c:/*.py')) # wrong drive
784 self.assertFalse(P('b.py').match('/*.py'))
785 self.assertFalse(P('b.py').match('c:*.py'))
786 self.assertFalse(P('b.py').match('c:/*.py'))
787 self.assertFalse(P('c:b.py').match('/*.py'))
788 self.assertFalse(P('c:b.py').match('c:/*.py'))
789 self.assertFalse(P('/b.py').match('c:*.py'))
790 self.assertFalse(P('/b.py').match('c:/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100791 # UNC patterns.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100792 self.assertTrue(P('//some/share/a.py').match('/*.py'))
793 self.assertTrue(P('//some/share/a.py').match('//some/share/*.py'))
794 self.assertFalse(P('//other/share/a.py').match('//some/share/*.py'))
795 self.assertFalse(P('//some/share/a/b.py').match('//some/share/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100796 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100797 self.assertTrue(P('B.py').match('b.PY'))
798 self.assertTrue(P('c:/a/B.Py').match('C:/A/*.pY'))
799 self.assertTrue(P('//Some/Share/B.Py').match('//somE/sharE/*.pY'))
800
801 def test_ordering_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100802 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100803 def assertOrderedEqual(a, b):
804 self.assertLessEqual(a, b)
805 self.assertGreaterEqual(b, a)
806 P = self.cls
807 p = P('c:A/b')
808 q = P('C:a/B')
809 assertOrderedEqual(p, q)
810 self.assertFalse(p < q)
811 self.assertFalse(p > q)
812 p = P('//some/Share/A/b')
813 q = P('//Some/SHARE/a/B')
814 assertOrderedEqual(p, q)
815 self.assertFalse(p < q)
816 self.assertFalse(p > q)
817
818 def test_parts(self):
819 P = self.cls
820 p = P('c:a/b')
821 parts = p.parts
822 self.assertEqual(parts, ('c:', 'a', 'b'))
823 p = P('c:/a/b')
824 parts = p.parts
825 self.assertEqual(parts, ('c:\\', 'a', 'b'))
826 p = P('//a/b/c/d')
827 parts = p.parts
828 self.assertEqual(parts, ('\\\\a\\b\\', 'c', 'd'))
829
830 def test_parent(self):
831 # Anchored
832 P = self.cls
833 p = P('z:a/b/c')
834 self.assertEqual(p.parent, P('z:a/b'))
835 self.assertEqual(p.parent.parent, P('z:a'))
836 self.assertEqual(p.parent.parent.parent, P('z:'))
837 self.assertEqual(p.parent.parent.parent.parent, P('z:'))
838 p = P('z:/a/b/c')
839 self.assertEqual(p.parent, P('z:/a/b'))
840 self.assertEqual(p.parent.parent, P('z:/a'))
841 self.assertEqual(p.parent.parent.parent, P('z:/'))
842 self.assertEqual(p.parent.parent.parent.parent, P('z:/'))
843 p = P('//a/b/c/d')
844 self.assertEqual(p.parent, P('//a/b/c'))
845 self.assertEqual(p.parent.parent, P('//a/b'))
846 self.assertEqual(p.parent.parent.parent, P('//a/b'))
847
848 def test_parents(self):
849 # Anchored
850 P = self.cls
851 p = P('z:a/b/')
852 par = p.parents
853 self.assertEqual(len(par), 2)
854 self.assertEqual(par[0], P('z:a'))
855 self.assertEqual(par[1], P('z:'))
856 self.assertEqual(list(par), [P('z:a'), P('z:')])
857 with self.assertRaises(IndexError):
858 par[2]
859 p = P('z:/a/b/')
860 par = p.parents
861 self.assertEqual(len(par), 2)
862 self.assertEqual(par[0], P('z:/a'))
863 self.assertEqual(par[1], P('z:/'))
864 self.assertEqual(list(par), [P('z:/a'), P('z:/')])
865 with self.assertRaises(IndexError):
866 par[2]
867 p = P('//a/b/c/d')
868 par = p.parents
869 self.assertEqual(len(par), 2)
870 self.assertEqual(par[0], P('//a/b/c'))
871 self.assertEqual(par[1], P('//a/b'))
872 self.assertEqual(list(par), [P('//a/b/c'), P('//a/b')])
873 with self.assertRaises(IndexError):
874 par[2]
875
876 def test_drive(self):
877 P = self.cls
878 self.assertEqual(P('c:').drive, 'c:')
879 self.assertEqual(P('c:a/b').drive, 'c:')
880 self.assertEqual(P('c:/').drive, 'c:')
881 self.assertEqual(P('c:/a/b/').drive, 'c:')
882 self.assertEqual(P('//a/b').drive, '\\\\a\\b')
883 self.assertEqual(P('//a/b/').drive, '\\\\a\\b')
884 self.assertEqual(P('//a/b/c/d').drive, '\\\\a\\b')
885
886 def test_root(self):
887 P = self.cls
888 self.assertEqual(P('c:').root, '')
889 self.assertEqual(P('c:a/b').root, '')
890 self.assertEqual(P('c:/').root, '\\')
891 self.assertEqual(P('c:/a/b/').root, '\\')
892 self.assertEqual(P('//a/b').root, '\\')
893 self.assertEqual(P('//a/b/').root, '\\')
894 self.assertEqual(P('//a/b/c/d').root, '\\')
895
896 def test_anchor(self):
897 P = self.cls
898 self.assertEqual(P('c:').anchor, 'c:')
899 self.assertEqual(P('c:a/b').anchor, 'c:')
900 self.assertEqual(P('c:/').anchor, 'c:\\')
901 self.assertEqual(P('c:/a/b/').anchor, 'c:\\')
902 self.assertEqual(P('//a/b').anchor, '\\\\a\\b\\')
903 self.assertEqual(P('//a/b/').anchor, '\\\\a\\b\\')
904 self.assertEqual(P('//a/b/c/d').anchor, '\\\\a\\b\\')
905
906 def test_name(self):
907 P = self.cls
908 self.assertEqual(P('c:').name, '')
909 self.assertEqual(P('c:/').name, '')
910 self.assertEqual(P('c:a/b').name, 'b')
911 self.assertEqual(P('c:/a/b').name, 'b')
912 self.assertEqual(P('c:a/b.py').name, 'b.py')
913 self.assertEqual(P('c:/a/b.py').name, 'b.py')
914 self.assertEqual(P('//My.py/Share.php').name, '')
915 self.assertEqual(P('//My.py/Share.php/a/b').name, 'b')
916
917 def test_suffix(self):
918 P = self.cls
919 self.assertEqual(P('c:').suffix, '')
920 self.assertEqual(P('c:/').suffix, '')
921 self.assertEqual(P('c:a/b').suffix, '')
922 self.assertEqual(P('c:/a/b').suffix, '')
923 self.assertEqual(P('c:a/b.py').suffix, '.py')
924 self.assertEqual(P('c:/a/b.py').suffix, '.py')
925 self.assertEqual(P('c:a/.hgrc').suffix, '')
926 self.assertEqual(P('c:/a/.hgrc').suffix, '')
927 self.assertEqual(P('c:a/.hg.rc').suffix, '.rc')
928 self.assertEqual(P('c:/a/.hg.rc').suffix, '.rc')
929 self.assertEqual(P('c:a/b.tar.gz').suffix, '.gz')
930 self.assertEqual(P('c:/a/b.tar.gz').suffix, '.gz')
931 self.assertEqual(P('c:a/Some name. Ending with a dot.').suffix, '')
932 self.assertEqual(P('c:/a/Some name. Ending with a dot.').suffix, '')
933 self.assertEqual(P('//My.py/Share.php').suffix, '')
934 self.assertEqual(P('//My.py/Share.php/a/b').suffix, '')
935
936 def test_suffixes(self):
937 P = self.cls
938 self.assertEqual(P('c:').suffixes, [])
939 self.assertEqual(P('c:/').suffixes, [])
940 self.assertEqual(P('c:a/b').suffixes, [])
941 self.assertEqual(P('c:/a/b').suffixes, [])
942 self.assertEqual(P('c:a/b.py').suffixes, ['.py'])
943 self.assertEqual(P('c:/a/b.py').suffixes, ['.py'])
944 self.assertEqual(P('c:a/.hgrc').suffixes, [])
945 self.assertEqual(P('c:/a/.hgrc').suffixes, [])
946 self.assertEqual(P('c:a/.hg.rc').suffixes, ['.rc'])
947 self.assertEqual(P('c:/a/.hg.rc').suffixes, ['.rc'])
948 self.assertEqual(P('c:a/b.tar.gz').suffixes, ['.tar', '.gz'])
949 self.assertEqual(P('c:/a/b.tar.gz').suffixes, ['.tar', '.gz'])
950 self.assertEqual(P('//My.py/Share.php').suffixes, [])
951 self.assertEqual(P('//My.py/Share.php/a/b').suffixes, [])
952 self.assertEqual(P('c:a/Some name. Ending with a dot.').suffixes, [])
953 self.assertEqual(P('c:/a/Some name. Ending with a dot.').suffixes, [])
954
955 def test_stem(self):
956 P = self.cls
957 self.assertEqual(P('c:').stem, '')
958 self.assertEqual(P('c:.').stem, '')
959 self.assertEqual(P('c:..').stem, '..')
960 self.assertEqual(P('c:/').stem, '')
961 self.assertEqual(P('c:a/b').stem, 'b')
962 self.assertEqual(P('c:a/b.py').stem, 'b')
963 self.assertEqual(P('c:a/.hgrc').stem, '.hgrc')
964 self.assertEqual(P('c:a/.hg.rc').stem, '.hg')
965 self.assertEqual(P('c:a/b.tar.gz').stem, 'b.tar')
966 self.assertEqual(P('c:a/Some name. Ending with a dot.').stem,
967 'Some name. Ending with a dot.')
968
969 def test_with_name(self):
970 P = self.cls
971 self.assertEqual(P('c:a/b').with_name('d.xml'), P('c:a/d.xml'))
972 self.assertEqual(P('c:/a/b').with_name('d.xml'), P('c:/a/d.xml'))
973 self.assertEqual(P('c:a/Dot ending.').with_name('d.xml'), P('c:a/d.xml'))
974 self.assertEqual(P('c:/a/Dot ending.').with_name('d.xml'), P('c:/a/d.xml'))
975 self.assertRaises(ValueError, P('c:').with_name, 'd.xml')
976 self.assertRaises(ValueError, P('c:/').with_name, 'd.xml')
977 self.assertRaises(ValueError, P('//My/Share').with_name, 'd.xml')
Antoine Pitrou7084e732014-07-06 21:31:12 -0400978 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:')
979 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:e')
980 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:/e')
981 self.assertRaises(ValueError, P('c:a/b').with_name, '//My/Share')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100982
983 def test_with_suffix(self):
984 P = self.cls
985 self.assertEqual(P('c:a/b').with_suffix('.gz'), P('c:a/b.gz'))
986 self.assertEqual(P('c:/a/b').with_suffix('.gz'), P('c:/a/b.gz'))
987 self.assertEqual(P('c:a/b.py').with_suffix('.gz'), P('c:a/b.gz'))
988 self.assertEqual(P('c:/a/b.py').with_suffix('.gz'), P('c:/a/b.gz'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100989 # Path doesn't have a "filename" component.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100990 self.assertRaises(ValueError, P('').with_suffix, '.gz')
991 self.assertRaises(ValueError, P('.').with_suffix, '.gz')
992 self.assertRaises(ValueError, P('/').with_suffix, '.gz')
993 self.assertRaises(ValueError, P('//My/Share').with_suffix, '.gz')
Anthony Shaw83da9262019-01-07 07:31:29 +1100994 # Invalid suffix.
Antoine Pitrou1b02da92014-01-03 00:07:17 +0100995 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'gz')
996 self.assertRaises(ValueError, P('c:a/b').with_suffix, '/')
997 self.assertRaises(ValueError, P('c:a/b').with_suffix, '\\')
998 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c:')
999 self.assertRaises(ValueError, P('c:a/b').with_suffix, '/.gz')
1000 self.assertRaises(ValueError, P('c:a/b').with_suffix, '\\.gz')
1001 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c:.gz')
1002 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c/d')
1003 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c\\d')
1004 self.assertRaises(ValueError, P('c:a/b').with_suffix, '.c/d')
1005 self.assertRaises(ValueError, P('c:a/b').with_suffix, '.c\\d')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001006
1007 def test_relative_to(self):
1008 P = self.cls
Antoine Pitrou156b3612013-12-28 19:49:04 +01001009 p = P('C:Foo/Bar')
1010 self.assertEqual(p.relative_to(P('c:')), P('Foo/Bar'))
1011 self.assertEqual(p.relative_to('c:'), P('Foo/Bar'))
1012 self.assertEqual(p.relative_to(P('c:foO')), P('Bar'))
1013 self.assertEqual(p.relative_to('c:foO'), P('Bar'))
1014 self.assertEqual(p.relative_to('c:foO/'), P('Bar'))
1015 self.assertEqual(p.relative_to(P('c:foO/baR')), P())
1016 self.assertEqual(p.relative_to('c:foO/baR'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001017 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001018 self.assertRaises(ValueError, p.relative_to, P())
Antoine Pitrou156b3612013-12-28 19:49:04 +01001019 self.assertRaises(ValueError, p.relative_to, '')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001020 self.assertRaises(ValueError, p.relative_to, P('d:'))
Antoine Pitrou156b3612013-12-28 19:49:04 +01001021 self.assertRaises(ValueError, p.relative_to, P('/'))
1022 self.assertRaises(ValueError, p.relative_to, P('Foo'))
1023 self.assertRaises(ValueError, p.relative_to, P('/Foo'))
1024 self.assertRaises(ValueError, p.relative_to, P('C:/Foo'))
1025 self.assertRaises(ValueError, p.relative_to, P('C:Foo/Bar/Baz'))
1026 self.assertRaises(ValueError, p.relative_to, P('C:Foo/Baz'))
1027 p = P('C:/Foo/Bar')
1028 self.assertEqual(p.relative_to(P('c:')), P('/Foo/Bar'))
1029 self.assertEqual(p.relative_to('c:'), P('/Foo/Bar'))
1030 self.assertEqual(str(p.relative_to(P('c:'))), '\\Foo\\Bar')
1031 self.assertEqual(str(p.relative_to('c:')), '\\Foo\\Bar')
1032 self.assertEqual(p.relative_to(P('c:/')), P('Foo/Bar'))
1033 self.assertEqual(p.relative_to('c:/'), P('Foo/Bar'))
1034 self.assertEqual(p.relative_to(P('c:/foO')), P('Bar'))
1035 self.assertEqual(p.relative_to('c:/foO'), P('Bar'))
1036 self.assertEqual(p.relative_to('c:/foO/'), P('Bar'))
1037 self.assertEqual(p.relative_to(P('c:/foO/baR')), P())
1038 self.assertEqual(p.relative_to('c:/foO/baR'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001039 # Unrelated paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001040 self.assertRaises(ValueError, p.relative_to, P('C:/Baz'))
1041 self.assertRaises(ValueError, p.relative_to, P('C:/Foo/Bar/Baz'))
1042 self.assertRaises(ValueError, p.relative_to, P('C:/Foo/Baz'))
1043 self.assertRaises(ValueError, p.relative_to, P('C:Foo'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001044 self.assertRaises(ValueError, p.relative_to, P('d:'))
1045 self.assertRaises(ValueError, p.relative_to, P('d:/'))
Antoine Pitrou156b3612013-12-28 19:49:04 +01001046 self.assertRaises(ValueError, p.relative_to, P('/'))
1047 self.assertRaises(ValueError, p.relative_to, P('/Foo'))
1048 self.assertRaises(ValueError, p.relative_to, P('//C/Foo'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001049 # UNC paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001050 p = P('//Server/Share/Foo/Bar')
1051 self.assertEqual(p.relative_to(P('//sErver/sHare')), P('Foo/Bar'))
1052 self.assertEqual(p.relative_to('//sErver/sHare'), P('Foo/Bar'))
1053 self.assertEqual(p.relative_to('//sErver/sHare/'), P('Foo/Bar'))
1054 self.assertEqual(p.relative_to(P('//sErver/sHare/Foo')), P('Bar'))
1055 self.assertEqual(p.relative_to('//sErver/sHare/Foo'), P('Bar'))
1056 self.assertEqual(p.relative_to('//sErver/sHare/Foo/'), P('Bar'))
1057 self.assertEqual(p.relative_to(P('//sErver/sHare/Foo/Bar')), P())
1058 self.assertEqual(p.relative_to('//sErver/sHare/Foo/Bar'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001059 # Unrelated paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001060 self.assertRaises(ValueError, p.relative_to, P('/Server/Share/Foo'))
1061 self.assertRaises(ValueError, p.relative_to, P('c:/Server/Share/Foo'))
1062 self.assertRaises(ValueError, p.relative_to, P('//z/Share/Foo'))
1063 self.assertRaises(ValueError, p.relative_to, P('//Server/z/Foo'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001064
1065 def test_is_absolute(self):
1066 P = self.cls
Anthony Shaw83da9262019-01-07 07:31:29 +11001067 # Under NT, only paths with both a drive and a root are absolute.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001068 self.assertFalse(P().is_absolute())
1069 self.assertFalse(P('a').is_absolute())
1070 self.assertFalse(P('a/b/').is_absolute())
1071 self.assertFalse(P('/').is_absolute())
1072 self.assertFalse(P('/a').is_absolute())
1073 self.assertFalse(P('/a/b/').is_absolute())
1074 self.assertFalse(P('c:').is_absolute())
1075 self.assertFalse(P('c:a').is_absolute())
1076 self.assertFalse(P('c:a/b/').is_absolute())
1077 self.assertTrue(P('c:/').is_absolute())
1078 self.assertTrue(P('c:/a').is_absolute())
1079 self.assertTrue(P('c:/a/b/').is_absolute())
Anthony Shaw83da9262019-01-07 07:31:29 +11001080 # UNC paths are absolute by definition.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001081 self.assertTrue(P('//a/b').is_absolute())
1082 self.assertTrue(P('//a/b/').is_absolute())
1083 self.assertTrue(P('//a/b/c').is_absolute())
1084 self.assertTrue(P('//a/b/c/d').is_absolute())
1085
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001086 def test_join(self):
1087 P = self.cls
1088 p = P('C:/a/b')
1089 pp = p.joinpath('x/y')
1090 self.assertEqual(pp, P('C:/a/b/x/y'))
1091 pp = p.joinpath('/x/y')
1092 self.assertEqual(pp, P('C:/x/y'))
1093 # Joining with a different drive => the first path is ignored, even
1094 # if the second path is relative.
1095 pp = p.joinpath('D:x/y')
1096 self.assertEqual(pp, P('D:x/y'))
1097 pp = p.joinpath('D:/x/y')
1098 self.assertEqual(pp, P('D:/x/y'))
1099 pp = p.joinpath('//host/share/x/y')
1100 self.assertEqual(pp, P('//host/share/x/y'))
1101 # Joining with the same drive => the first path is appended to if
1102 # the second path is relative.
1103 pp = p.joinpath('c:x/y')
1104 self.assertEqual(pp, P('C:/a/b/x/y'))
1105 pp = p.joinpath('c:/x/y')
1106 self.assertEqual(pp, P('C:/x/y'))
1107
1108 def test_div(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001109 # Basically the same as joinpath().
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001110 P = self.cls
1111 p = P('C:/a/b')
1112 self.assertEqual(p / 'x/y', P('C:/a/b/x/y'))
1113 self.assertEqual(p / 'x' / 'y', P('C:/a/b/x/y'))
1114 self.assertEqual(p / '/x/y', P('C:/x/y'))
1115 self.assertEqual(p / '/x' / 'y', P('C:/x/y'))
1116 # Joining with a different drive => the first path is ignored, even
1117 # if the second path is relative.
1118 self.assertEqual(p / 'D:x/y', P('D:x/y'))
1119 self.assertEqual(p / 'D:' / 'x/y', P('D:x/y'))
1120 self.assertEqual(p / 'D:/x/y', P('D:/x/y'))
1121 self.assertEqual(p / 'D:' / '/x/y', P('D:/x/y'))
1122 self.assertEqual(p / '//host/share/x/y', P('//host/share/x/y'))
1123 # Joining with the same drive => the first path is appended to if
1124 # the second path is relative.
Serhiy Storchaka010ff582013-12-06 17:25:51 +02001125 self.assertEqual(p / 'c:x/y', P('C:/a/b/x/y'))
1126 self.assertEqual(p / 'c:/x/y', P('C:/x/y'))
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001127
Antoine Pitrou31119e42013-11-22 17:38:12 +01001128 def test_is_reserved(self):
1129 P = self.cls
1130 self.assertIs(False, P('').is_reserved())
1131 self.assertIs(False, P('/').is_reserved())
1132 self.assertIs(False, P('/foo/bar').is_reserved())
1133 self.assertIs(True, P('con').is_reserved())
1134 self.assertIs(True, P('NUL').is_reserved())
1135 self.assertIs(True, P('NUL.txt').is_reserved())
1136 self.assertIs(True, P('com1').is_reserved())
1137 self.assertIs(True, P('com9.bar').is_reserved())
1138 self.assertIs(False, P('bar.com9').is_reserved())
1139 self.assertIs(True, P('lpt1').is_reserved())
1140 self.assertIs(True, P('lpt9.bar').is_reserved())
1141 self.assertIs(False, P('bar.lpt9').is_reserved())
Anthony Shaw83da9262019-01-07 07:31:29 +11001142 # Only the last component matters.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001143 self.assertIs(False, P('c:/NUL/con/baz').is_reserved())
Anthony Shaw83da9262019-01-07 07:31:29 +11001144 # UNC paths are never reserved.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001145 self.assertIs(False, P('//my/share/nul/con/aux').is_reserved())
1146
Antoine Pitrou31119e42013-11-22 17:38:12 +01001147class PurePathTest(_BasePurePathTest, unittest.TestCase):
1148 cls = pathlib.PurePath
1149
1150 def test_concrete_class(self):
1151 p = self.cls('a')
1152 self.assertIs(type(p),
1153 pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath)
1154
1155 def test_different_flavours_unequal(self):
1156 p = pathlib.PurePosixPath('a')
1157 q = pathlib.PureWindowsPath('a')
1158 self.assertNotEqual(p, q)
1159
1160 def test_different_flavours_unordered(self):
1161 p = pathlib.PurePosixPath('a')
1162 q = pathlib.PureWindowsPath('a')
1163 with self.assertRaises(TypeError):
1164 p < q
1165 with self.assertRaises(TypeError):
1166 p <= q
1167 with self.assertRaises(TypeError):
1168 p > q
1169 with self.assertRaises(TypeError):
1170 p >= q
1171
1172
1173#
Anthony Shaw83da9262019-01-07 07:31:29 +11001174# Tests for the concrete classes.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001175#
1176
Anthony Shaw83da9262019-01-07 07:31:29 +11001177# Make sure any symbolic links in the base test path are resolved.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001178BASE = os.path.realpath(TESTFN)
1179join = lambda *x: os.path.join(BASE, *x)
1180rel_join = lambda *x: os.path.join(TESTFN, *x)
1181
Antoine Pitrou31119e42013-11-22 17:38:12 +01001182only_nt = unittest.skipIf(os.name != 'nt',
1183 'test requires a Windows-compatible system')
1184only_posix = unittest.skipIf(os.name == 'nt',
1185 'test requires a POSIX-compatible system')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001186
1187@only_posix
1188class PosixPathAsPureTest(PurePosixPathTest):
1189 cls = pathlib.PosixPath
1190
1191@only_nt
1192class WindowsPathAsPureTest(PureWindowsPathTest):
1193 cls = pathlib.WindowsPath
1194
Victor Stinnerd7569632016-03-11 22:53:00 +01001195 def test_owner(self):
1196 P = self.cls
1197 with self.assertRaises(NotImplementedError):
1198 P('c:/').owner()
1199
1200 def test_group(self):
1201 P = self.cls
1202 with self.assertRaises(NotImplementedError):
1203 P('c:/').group()
1204
Antoine Pitrou31119e42013-11-22 17:38:12 +01001205
1206class _BasePathTest(object):
1207 """Tests for the FS-accessing functionalities of the Path classes."""
1208
1209 # (BASE)
1210 # |
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001211 # |-- brokenLink -> non-existing
1212 # |-- dirA
1213 # | `-- linkC -> ../dirB
1214 # |-- dirB
1215 # | |-- fileB
1216 # | `-- linkD -> ../dirB
1217 # |-- dirC
1218 # | |-- dirD
1219 # | | `-- fileD
1220 # | `-- fileC
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001221 # |-- dirE # No permissions
Antoine Pitrou31119e42013-11-22 17:38:12 +01001222 # |-- fileA
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001223 # |-- linkA -> fileA
Jörg Stucked5c120f2019-05-21 19:44:40 +02001224 # |-- linkB -> dirB
1225 # `-- brokenLinkLoop -> brokenLinkLoop
Antoine Pitrou31119e42013-11-22 17:38:12 +01001226 #
1227
1228 def setUp(self):
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001229 def cleanup():
1230 os.chmod(join('dirE'), 0o777)
1231 support.rmtree(BASE)
1232 self.addCleanup(cleanup)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001233 os.mkdir(BASE)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001234 os.mkdir(join('dirA'))
1235 os.mkdir(join('dirB'))
1236 os.mkdir(join('dirC'))
1237 os.mkdir(join('dirC', 'dirD'))
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001238 os.mkdir(join('dirE'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001239 with open(join('fileA'), 'wb') as f:
1240 f.write(b"this is file A\n")
1241 with open(join('dirB', 'fileB'), 'wb') as f:
1242 f.write(b"this is file B\n")
1243 with open(join('dirC', 'fileC'), 'wb') as f:
1244 f.write(b"this is file C\n")
1245 with open(join('dirC', 'dirD', 'fileD'), 'wb') as f:
1246 f.write(b"this is file D\n")
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001247 os.chmod(join('dirE'), 0)
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001248 if support.can_symlink():
Anthony Shaw83da9262019-01-07 07:31:29 +11001249 # Relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001250 os.symlink('fileA', join('linkA'))
1251 os.symlink('non-existing', join('brokenLink'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001252 self.dirlink('dirB', join('linkB'))
1253 self.dirlink(os.path.join('..', 'dirB'), join('dirA', 'linkC'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001254 # This one goes upwards, creating a loop.
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001255 self.dirlink(os.path.join('..', 'dirB'), join('dirB', 'linkD'))
Jörg Stucked5c120f2019-05-21 19:44:40 +02001256 # Broken symlink (pointing to itself).
1257 os.symlink('brokenLinkLoop', join('brokenLinkLoop'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001258
1259 if os.name == 'nt':
Anthony Shaw83da9262019-01-07 07:31:29 +11001260 # Workaround for http://bugs.python.org/issue13772.
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001261 def dirlink(self, src, dest):
1262 os.symlink(src, dest, target_is_directory=True)
1263 else:
1264 def dirlink(self, src, dest):
1265 os.symlink(src, dest)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001266
1267 def assertSame(self, path_a, path_b):
1268 self.assertTrue(os.path.samefile(str(path_a), str(path_b)),
1269 "%r and %r don't point to the same file" %
1270 (path_a, path_b))
1271
1272 def assertFileNotFound(self, func, *args, **kwargs):
1273 with self.assertRaises(FileNotFoundError) as cm:
1274 func(*args, **kwargs)
1275 self.assertEqual(cm.exception.errno, errno.ENOENT)
1276
Steve Dower206e4c32019-09-10 15:29:28 +01001277 def assertEqualNormCase(self, path_a, path_b):
1278 self.assertEqual(os.path.normcase(path_a), os.path.normcase(path_b))
1279
Antoine Pitrou31119e42013-11-22 17:38:12 +01001280 def _test_cwd(self, p):
1281 q = self.cls(os.getcwd())
1282 self.assertEqual(p, q)
Steve Dower206e4c32019-09-10 15:29:28 +01001283 self.assertEqualNormCase(str(p), str(q))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001284 self.assertIs(type(p), type(q))
1285 self.assertTrue(p.is_absolute())
1286
1287 def test_cwd(self):
1288 p = self.cls.cwd()
1289 self._test_cwd(p)
1290
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001291 def _test_home(self, p):
1292 q = self.cls(os.path.expanduser('~'))
1293 self.assertEqual(p, q)
Steve Dower206e4c32019-09-10 15:29:28 +01001294 self.assertEqualNormCase(str(p), str(q))
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001295 self.assertIs(type(p), type(q))
1296 self.assertTrue(p.is_absolute())
1297
1298 def test_home(self):
Miss Islington (bot)595b5162020-01-28 01:59:43 -08001299 with support.EnvironmentVarGuard() as env:
1300 self._test_home(self.cls.home())
1301
1302 env.clear()
1303 env['USERPROFILE'] = os.path.join(BASE, 'userprofile')
1304 self._test_home(self.cls.home())
1305
1306 # bpo-38883: ignore `HOME` when set on windows
1307 env['HOME'] = os.path.join(BASE, 'home')
1308 self._test_home(self.cls.home())
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001309
Antoine Pitrou43e3d942014-05-13 10:50:15 +02001310 def test_samefile(self):
1311 fileA_path = os.path.join(BASE, 'fileA')
1312 fileB_path = os.path.join(BASE, 'dirB', 'fileB')
1313 p = self.cls(fileA_path)
1314 pp = self.cls(fileA_path)
1315 q = self.cls(fileB_path)
1316 self.assertTrue(p.samefile(fileA_path))
1317 self.assertTrue(p.samefile(pp))
1318 self.assertFalse(p.samefile(fileB_path))
1319 self.assertFalse(p.samefile(q))
1320 # Test the non-existent file case
1321 non_existent = os.path.join(BASE, 'foo')
1322 r = self.cls(non_existent)
1323 self.assertRaises(FileNotFoundError, p.samefile, r)
1324 self.assertRaises(FileNotFoundError, p.samefile, non_existent)
1325 self.assertRaises(FileNotFoundError, r.samefile, p)
1326 self.assertRaises(FileNotFoundError, r.samefile, non_existent)
1327 self.assertRaises(FileNotFoundError, r.samefile, r)
1328 self.assertRaises(FileNotFoundError, r.samefile, non_existent)
1329
Antoine Pitrou31119e42013-11-22 17:38:12 +01001330 def test_empty_path(self):
1331 # The empty path points to '.'
1332 p = self.cls('')
1333 self.assertEqual(p.stat(), os.stat('.'))
1334
Antoine Pitrou8477ed62014-12-30 20:54:45 +01001335 def test_expanduser_common(self):
1336 P = self.cls
1337 p = P('~')
1338 self.assertEqual(p.expanduser(), P(os.path.expanduser('~')))
1339 p = P('foo')
1340 self.assertEqual(p.expanduser(), p)
1341 p = P('/~')
1342 self.assertEqual(p.expanduser(), p)
1343 p = P('../~')
1344 self.assertEqual(p.expanduser(), p)
1345 p = P(P('').absolute().anchor) / '~'
1346 self.assertEqual(p.expanduser(), p)
1347
Antoine Pitrou31119e42013-11-22 17:38:12 +01001348 def test_exists(self):
1349 P = self.cls
1350 p = P(BASE)
1351 self.assertIs(True, p.exists())
1352 self.assertIs(True, (p / 'dirA').exists())
1353 self.assertIs(True, (p / 'fileA').exists())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001354 self.assertIs(False, (p / 'fileA' / 'bah').exists())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001355 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001356 self.assertIs(True, (p / 'linkA').exists())
1357 self.assertIs(True, (p / 'linkB').exists())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001358 self.assertIs(True, (p / 'linkB' / 'fileB').exists())
1359 self.assertIs(False, (p / 'linkA' / 'bah').exists())
Antoine Pitrou31119e42013-11-22 17:38:12 +01001360 self.assertIs(False, (p / 'foo').exists())
1361 self.assertIs(False, P('/xyzzy').exists())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001362 self.assertIs(False, P(BASE + '\udfff').exists())
1363 self.assertIs(False, P(BASE + '\x00').exists())
Antoine Pitrou31119e42013-11-22 17:38:12 +01001364
1365 def test_open_common(self):
1366 p = self.cls(BASE)
1367 with (p / 'fileA').open('r') as f:
1368 self.assertIsInstance(f, io.TextIOBase)
1369 self.assertEqual(f.read(), "this is file A\n")
1370 with (p / 'fileA').open('rb') as f:
1371 self.assertIsInstance(f, io.BufferedIOBase)
1372 self.assertEqual(f.read().strip(), b"this is file A")
1373 with (p / 'fileA').open('rb', buffering=0) as f:
1374 self.assertIsInstance(f, io.RawIOBase)
1375 self.assertEqual(f.read().strip(), b"this is file A")
1376
Georg Brandlea683982014-10-01 19:12:33 +02001377 def test_read_write_bytes(self):
1378 p = self.cls(BASE)
1379 (p / 'fileA').write_bytes(b'abcdefg')
1380 self.assertEqual((p / 'fileA').read_bytes(), b'abcdefg')
Anthony Shaw83da9262019-01-07 07:31:29 +11001381 # Check that trying to write str does not truncate the file.
Georg Brandlea683982014-10-01 19:12:33 +02001382 self.assertRaises(TypeError, (p / 'fileA').write_bytes, 'somestr')
1383 self.assertEqual((p / 'fileA').read_bytes(), b'abcdefg')
1384
1385 def test_read_write_text(self):
1386 p = self.cls(BASE)
1387 (p / 'fileA').write_text('äbcdefg', encoding='latin-1')
1388 self.assertEqual((p / 'fileA').read_text(
1389 encoding='utf-8', errors='ignore'), 'bcdefg')
Anthony Shaw83da9262019-01-07 07:31:29 +11001390 # Check that trying to write bytes does not truncate the file.
Georg Brandlea683982014-10-01 19:12:33 +02001391 self.assertRaises(TypeError, (p / 'fileA').write_text, b'somebytes')
1392 self.assertEqual((p / 'fileA').read_text(encoding='latin-1'), 'äbcdefg')
1393
Antoine Pitrou31119e42013-11-22 17:38:12 +01001394 def test_iterdir(self):
1395 P = self.cls
1396 p = P(BASE)
1397 it = p.iterdir()
1398 paths = set(it)
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001399 expected = ['dirA', 'dirB', 'dirC', 'dirE', 'fileA']
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001400 if support.can_symlink():
Jörg Stucked5c120f2019-05-21 19:44:40 +02001401 expected += ['linkA', 'linkB', 'brokenLink', 'brokenLinkLoop']
Antoine Pitrou31119e42013-11-22 17:38:12 +01001402 self.assertEqual(paths, { P(BASE, q) for q in expected })
1403
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001404 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001405 def test_iterdir_symlink(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001406 # __iter__ on a symlink to a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001407 P = self.cls
1408 p = P(BASE, 'linkB')
1409 paths = set(p.iterdir())
1410 expected = { P(BASE, 'linkB', q) for q in ['fileB', 'linkD'] }
1411 self.assertEqual(paths, expected)
1412
1413 def test_iterdir_nodir(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001414 # __iter__ on something that is not a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001415 p = self.cls(BASE, 'fileA')
1416 with self.assertRaises(OSError) as cm:
1417 next(p.iterdir())
1418 # ENOENT or EINVAL under Windows, ENOTDIR otherwise
Anthony Shaw83da9262019-01-07 07:31:29 +11001419 # (see issue #12802).
Antoine Pitrou31119e42013-11-22 17:38:12 +01001420 self.assertIn(cm.exception.errno, (errno.ENOTDIR,
1421 errno.ENOENT, errno.EINVAL))
1422
1423 def test_glob_common(self):
1424 def _check(glob, expected):
1425 self.assertEqual(set(glob), { P(BASE, q) for q in expected })
1426 P = self.cls
1427 p = P(BASE)
1428 it = p.glob("fileA")
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001429 self.assertIsInstance(it, collections.abc.Iterator)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001430 _check(it, ["fileA"])
1431 _check(p.glob("fileB"), [])
1432 _check(p.glob("dir*/file*"), ["dirB/fileB", "dirC/fileC"])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001433 if not support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001434 _check(p.glob("*A"), ['dirA', 'fileA'])
1435 else:
1436 _check(p.glob("*A"), ['dirA', 'fileA', 'linkA'])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001437 if not support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001438 _check(p.glob("*B/*"), ['dirB/fileB'])
1439 else:
1440 _check(p.glob("*B/*"), ['dirB/fileB', 'dirB/linkD',
1441 'linkB/fileB', 'linkB/linkD'])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001442 if not support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001443 _check(p.glob("*/fileB"), ['dirB/fileB'])
1444 else:
1445 _check(p.glob("*/fileB"), ['dirB/fileB', 'linkB/fileB'])
1446
1447 def test_rglob_common(self):
1448 def _check(glob, expected):
1449 self.assertEqual(set(glob), { P(BASE, q) for q in expected })
1450 P = self.cls
1451 p = P(BASE)
1452 it = p.rglob("fileA")
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001453 self.assertIsInstance(it, collections.abc.Iterator)
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001454 _check(it, ["fileA"])
1455 _check(p.rglob("fileB"), ["dirB/fileB"])
1456 _check(p.rglob("*/fileA"), [])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001457 if not support.can_symlink():
Guido van Rossum9c39b672016-01-07 13:12:34 -08001458 _check(p.rglob("*/fileB"), ["dirB/fileB"])
1459 else:
1460 _check(p.rglob("*/fileB"), ["dirB/fileB", "dirB/linkD/fileB",
1461 "linkB/fileB", "dirA/linkC/fileB"])
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001462 _check(p.rglob("file*"), ["fileA", "dirB/fileB",
1463 "dirC/fileC", "dirC/dirD/fileD"])
Antoine Pitrou31119e42013-11-22 17:38:12 +01001464 p = P(BASE, "dirC")
1465 _check(p.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"])
1466 _check(p.rglob("*/*"), ["dirC/dirD/fileD"])
1467
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001468 @support.skip_unless_symlink
Guido van Rossum69bfb152016-01-06 10:31:33 -08001469 def test_rglob_symlink_loop(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001470 # Don't get fooled by symlink loops (Issue #26012).
Guido van Rossum69bfb152016-01-06 10:31:33 -08001471 P = self.cls
1472 p = P(BASE)
1473 given = set(p.rglob('*'))
1474 expect = {'brokenLink',
1475 'dirA', 'dirA/linkC',
1476 'dirB', 'dirB/fileB', 'dirB/linkD',
1477 'dirC', 'dirC/dirD', 'dirC/dirD/fileD', 'dirC/fileC',
1478 'dirE',
1479 'fileA',
1480 'linkA',
1481 'linkB',
Jörg Stucked5c120f2019-05-21 19:44:40 +02001482 'brokenLinkLoop',
Guido van Rossum69bfb152016-01-06 10:31:33 -08001483 }
1484 self.assertEqual(given, {p / x for x in expect})
1485
Miss Islington (bot)98a4a712019-09-12 08:07:47 -07001486 def test_glob_many_open_files(self):
1487 depth = 30
1488 P = self.cls
1489 base = P(BASE) / 'deep'
1490 p = P(base, *(['d']*depth))
1491 p.mkdir(parents=True)
1492 pattern = '/'.join(['*'] * depth)
1493 iters = [base.glob(pattern) for j in range(100)]
1494 for it in iters:
1495 self.assertEqual(next(it), p)
1496 iters = [base.rglob('d') for j in range(100)]
1497 p = base
1498 for i in range(depth):
1499 p = p / 'd'
1500 for it in iters:
1501 self.assertEqual(next(it), p)
1502
Antoine Pitrou31119e42013-11-22 17:38:12 +01001503 def test_glob_dotdot(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001504 # ".." is not special in globs.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001505 P = self.cls
1506 p = P(BASE)
1507 self.assertEqual(set(p.glob("..")), { P(BASE, "..") })
1508 self.assertEqual(set(p.glob("dirA/../file*")), { P(BASE, "dirA/../fileA") })
1509 self.assertEqual(set(p.glob("../xyzzy")), set())
1510
Ezio Melottiac1e7f62015-12-28 23:50:19 +02001511
Steve Dower98eb3602016-11-09 12:58:17 -08001512 def _check_resolve(self, p, expected, strict=True):
1513 q = p.resolve(strict)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001514 self.assertEqual(q, expected)
1515
Anthony Shaw83da9262019-01-07 07:31:29 +11001516 # This can be used to check both relative and absolute resolutions.
Ezio Melottiac1e7f62015-12-28 23:50:19 +02001517 _check_resolve_relative = _check_resolve_absolute = _check_resolve
Antoine Pitrou31119e42013-11-22 17:38:12 +01001518
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001519 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001520 def test_resolve_common(self):
1521 P = self.cls
1522 p = P(BASE, 'foo')
1523 with self.assertRaises(OSError) as cm:
Steve Dower98eb3602016-11-09 12:58:17 -08001524 p.resolve(strict=True)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001525 self.assertEqual(cm.exception.errno, errno.ENOENT)
Steve Dower98eb3602016-11-09 12:58:17 -08001526 # Non-strict
Steve Dower206e4c32019-09-10 15:29:28 +01001527 self.assertEqualNormCase(str(p.resolve(strict=False)),
1528 os.path.join(BASE, 'foo'))
Steve Dower98eb3602016-11-09 12:58:17 -08001529 p = P(BASE, 'foo', 'in', 'spam')
Steve Dower206e4c32019-09-10 15:29:28 +01001530 self.assertEqualNormCase(str(p.resolve(strict=False)),
1531 os.path.join(BASE, 'foo', 'in', 'spam'))
Steve Dower98eb3602016-11-09 12:58:17 -08001532 p = P(BASE, '..', 'foo', 'in', 'spam')
Steve Dower206e4c32019-09-10 15:29:28 +01001533 self.assertEqualNormCase(str(p.resolve(strict=False)),
1534 os.path.abspath(os.path.join('foo', 'in', 'spam')))
Anthony Shaw83da9262019-01-07 07:31:29 +11001535 # These are all relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001536 p = P(BASE, 'dirB', 'fileB')
1537 self._check_resolve_relative(p, p)
1538 p = P(BASE, 'linkA')
1539 self._check_resolve_relative(p, P(BASE, 'fileA'))
1540 p = P(BASE, 'dirA', 'linkC', 'fileB')
1541 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB'))
1542 p = P(BASE, 'dirB', 'linkD', 'fileB')
1543 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB'))
Steve Dower98eb3602016-11-09 12:58:17 -08001544 # Non-strict
1545 p = P(BASE, 'dirA', 'linkC', 'fileB', 'foo', 'in', 'spam')
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001546 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB', 'foo', 'in',
1547 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001548 p = P(BASE, 'dirA', 'linkC', '..', 'foo', 'in', 'spam')
1549 if os.name == 'nt':
1550 # In Windows, if linkY points to dirB, 'dirA\linkY\..'
1551 # resolves to 'dirA' without resolving linkY first.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001552 self._check_resolve_relative(p, P(BASE, 'dirA', 'foo', 'in',
1553 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001554 else:
1555 # In Posix, if linkY points to dirB, 'dirA/linkY/..'
1556 # resolves to 'dirB/..' first before resolving to parent of dirB.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001557 self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
Anthony Shaw83da9262019-01-07 07:31:29 +11001558 # Now create absolute symlinks.
Steve Dower0cd63912018-12-10 18:52:57 -08001559 d = support._longpath(tempfile.mkdtemp(suffix='-dirD', dir=os.getcwd()))
Victor Stinnerec864692014-07-21 19:19:05 +02001560 self.addCleanup(support.rmtree, d)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001561 os.symlink(os.path.join(d), join('dirA', 'linkX'))
1562 os.symlink(join('dirB'), os.path.join(d, 'linkY'))
1563 p = P(BASE, 'dirA', 'linkX', 'linkY', 'fileB')
1564 self._check_resolve_absolute(p, P(BASE, 'dirB', 'fileB'))
Steve Dower98eb3602016-11-09 12:58:17 -08001565 # Non-strict
1566 p = P(BASE, 'dirA', 'linkX', 'linkY', 'foo', 'in', 'spam')
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001567 self._check_resolve_relative(p, P(BASE, 'dirB', 'foo', 'in', 'spam'),
1568 False)
Steve Dower98eb3602016-11-09 12:58:17 -08001569 p = P(BASE, 'dirA', 'linkX', 'linkY', '..', 'foo', 'in', 'spam')
1570 if os.name == 'nt':
1571 # In Windows, if linkY points to dirB, 'dirA\linkY\..'
1572 # resolves to 'dirA' without resolving linkY first.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001573 self._check_resolve_relative(p, P(d, 'foo', 'in', 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001574 else:
1575 # In Posix, if linkY points to dirB, 'dirA/linkY/..'
1576 # resolves to 'dirB/..' first before resolving to parent of dirB.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001577 self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001578
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001579 @support.skip_unless_symlink
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001580 def test_resolve_dot(self):
1581 # See https://bitbucket.org/pitrou/pathlib/issue/9/pathresolve-fails-on-complex-symlinks
1582 p = self.cls(BASE)
1583 self.dirlink('.', join('0'))
Antoine Pitroucc157512013-12-03 17:13:13 +01001584 self.dirlink(os.path.join('0', '0'), join('1'))
1585 self.dirlink(os.path.join('1', '1'), join('2'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001586 q = p / '2'
Steve Dower98eb3602016-11-09 12:58:17 -08001587 self.assertEqual(q.resolve(strict=True), p)
1588 r = q / '3' / '4'
1589 self.assertRaises(FileNotFoundError, r.resolve, strict=True)
1590 # Non-strict
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001591 self.assertEqual(r.resolve(strict=False), p / '3' / '4')
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001592
Antoine Pitrou31119e42013-11-22 17:38:12 +01001593 def test_with(self):
1594 p = self.cls(BASE)
1595 it = p.iterdir()
1596 it2 = p.iterdir()
1597 next(it2)
1598 with p:
1599 pass
Anthony Shaw83da9262019-01-07 07:31:29 +11001600 # I/O operation on closed path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001601 self.assertRaises(ValueError, next, it)
1602 self.assertRaises(ValueError, next, it2)
1603 self.assertRaises(ValueError, p.open)
1604 self.assertRaises(ValueError, p.resolve)
1605 self.assertRaises(ValueError, p.absolute)
1606 self.assertRaises(ValueError, p.__enter__)
1607
1608 def test_chmod(self):
1609 p = self.cls(BASE) / 'fileA'
1610 mode = p.stat().st_mode
Anthony Shaw83da9262019-01-07 07:31:29 +11001611 # Clear writable bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001612 new_mode = mode & ~0o222
1613 p.chmod(new_mode)
1614 self.assertEqual(p.stat().st_mode, new_mode)
Anthony Shaw83da9262019-01-07 07:31:29 +11001615 # Set writable bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001616 new_mode = mode | 0o222
1617 p.chmod(new_mode)
1618 self.assertEqual(p.stat().st_mode, new_mode)
1619
Anthony Shaw83da9262019-01-07 07:31:29 +11001620 # XXX also need a test for lchmod.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001621
1622 def test_stat(self):
1623 p = self.cls(BASE) / 'fileA'
1624 st = p.stat()
1625 self.assertEqual(p.stat(), st)
Anthony Shaw83da9262019-01-07 07:31:29 +11001626 # Change file mode by flipping write bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001627 p.chmod(st.st_mode ^ 0o222)
1628 self.addCleanup(p.chmod, st.st_mode)
1629 self.assertNotEqual(p.stat(), st)
1630
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001631 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001632 def test_lstat(self):
1633 p = self.cls(BASE)/ 'linkA'
1634 st = p.stat()
1635 self.assertNotEqual(st, p.lstat())
1636
1637 def test_lstat_nosymlink(self):
1638 p = self.cls(BASE) / 'fileA'
1639 st = p.stat()
1640 self.assertEqual(st, p.lstat())
1641
1642 @unittest.skipUnless(pwd, "the pwd module is needed for this test")
1643 def test_owner(self):
1644 p = self.cls(BASE) / 'fileA'
1645 uid = p.stat().st_uid
Antoine Pitrou2cf4b0f2013-11-25 19:51:53 +01001646 try:
1647 name = pwd.getpwuid(uid).pw_name
1648 except KeyError:
1649 self.skipTest(
1650 "user %d doesn't have an entry in the system database" % uid)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001651 self.assertEqual(name, p.owner())
1652
1653 @unittest.skipUnless(grp, "the grp module is needed for this test")
1654 def test_group(self):
1655 p = self.cls(BASE) / 'fileA'
1656 gid = p.stat().st_gid
Antoine Pitrou2cf4b0f2013-11-25 19:51:53 +01001657 try:
1658 name = grp.getgrgid(gid).gr_name
1659 except KeyError:
1660 self.skipTest(
1661 "group %d doesn't have an entry in the system database" % gid)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001662 self.assertEqual(name, p.group())
1663
1664 def test_unlink(self):
1665 p = self.cls(BASE) / 'fileA'
1666 p.unlink()
1667 self.assertFileNotFound(p.stat)
1668 self.assertFileNotFound(p.unlink)
1669
‮zlohhcuB treboRd9e006b2019-05-16 00:02:11 +02001670 def test_unlink_missing_ok(self):
1671 p = self.cls(BASE) / 'fileAAA'
1672 self.assertFileNotFound(p.unlink)
1673 p.unlink(missing_ok=True)
1674
Antoine Pitrou31119e42013-11-22 17:38:12 +01001675 def test_rmdir(self):
1676 p = self.cls(BASE) / 'dirA'
1677 for q in p.iterdir():
1678 q.unlink()
1679 p.rmdir()
1680 self.assertFileNotFound(p.stat)
1681 self.assertFileNotFound(p.unlink)
1682
Miss Islington (bot)8d0f3692019-12-16 04:42:20 -08001683 @unittest.skipUnless(hasattr(os, "link"), "os.link() is not present")
Joannah Nanjekye6b5b0132019-05-04 11:27:10 -04001684 def test_link_to(self):
1685 P = self.cls(BASE)
1686 p = P / 'fileA'
1687 size = p.stat().st_size
1688 # linking to another path.
1689 q = P / 'dirA' / 'fileAA'
1690 try:
1691 p.link_to(q)
1692 except PermissionError as e:
1693 self.skipTest('os.link(): %s' % e)
1694 self.assertEqual(q.stat().st_size, size)
1695 self.assertEqual(os.path.samefile(p, q), True)
1696 self.assertTrue(p.stat)
1697 # Linking to a str of a relative path.
1698 r = rel_join('fileAAA')
1699 q.link_to(r)
1700 self.assertEqual(os.stat(r).st_size, size)
1701 self.assertTrue(q.stat)
1702
Miss Islington (bot)8d0f3692019-12-16 04:42:20 -08001703 @unittest.skipIf(hasattr(os, "link"), "os.link() is present")
1704 def test_link_to_not_implemented(self):
1705 P = self.cls(BASE)
1706 p = P / 'fileA'
1707 # linking to another path.
1708 q = P / 'dirA' / 'fileAA'
1709 with self.assertRaises(NotImplementedError):
1710 p.link_to(q)
1711
Antoine Pitrou31119e42013-11-22 17:38:12 +01001712 def test_rename(self):
1713 P = self.cls(BASE)
1714 p = P / 'fileA'
1715 size = p.stat().st_size
Anthony Shaw83da9262019-01-07 07:31:29 +11001716 # Renaming to another path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001717 q = P / 'dirA' / 'fileAA'
Miss Islington (bot)cbd7b2a2019-09-11 07:12:54 -07001718 renamed_p = p.rename(q)
1719 self.assertEqual(renamed_p, q)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001720 self.assertEqual(q.stat().st_size, size)
1721 self.assertFileNotFound(p.stat)
Anthony Shaw83da9262019-01-07 07:31:29 +11001722 # Renaming to a str of a relative path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001723 r = rel_join('fileAAA')
Miss Islington (bot)cbd7b2a2019-09-11 07:12:54 -07001724 renamed_q = q.rename(r)
1725 self.assertEqual(renamed_q, self.cls(r))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001726 self.assertEqual(os.stat(r).st_size, size)
1727 self.assertFileNotFound(q.stat)
1728
1729 def test_replace(self):
1730 P = self.cls(BASE)
1731 p = P / 'fileA'
1732 size = p.stat().st_size
Anthony Shaw83da9262019-01-07 07:31:29 +11001733 # Replacing a non-existing path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001734 q = P / 'dirA' / 'fileAA'
Miss Islington (bot)cbd7b2a2019-09-11 07:12:54 -07001735 replaced_p = p.replace(q)
1736 self.assertEqual(replaced_p, q)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001737 self.assertEqual(q.stat().st_size, size)
1738 self.assertFileNotFound(p.stat)
Anthony Shaw83da9262019-01-07 07:31:29 +11001739 # Replacing another (existing) path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001740 r = rel_join('dirB', 'fileB')
Miss Islington (bot)cbd7b2a2019-09-11 07:12:54 -07001741 replaced_q = q.replace(r)
1742 self.assertEqual(replaced_q, self.cls(r))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001743 self.assertEqual(os.stat(r).st_size, size)
1744 self.assertFileNotFound(q.stat)
1745
1746 def test_touch_common(self):
1747 P = self.cls(BASE)
1748 p = P / 'newfileA'
1749 self.assertFalse(p.exists())
1750 p.touch()
1751 self.assertTrue(p.exists())
Antoine Pitrou0f575642013-11-22 23:20:08 +01001752 st = p.stat()
1753 old_mtime = st.st_mtime
1754 old_mtime_ns = st.st_mtime_ns
Antoine Pitrou31119e42013-11-22 17:38:12 +01001755 # Rewind the mtime sufficiently far in the past to work around
1756 # filesystem-specific timestamp granularity.
1757 os.utime(str(p), (old_mtime - 10, old_mtime - 10))
Anthony Shaw83da9262019-01-07 07:31:29 +11001758 # The file mtime should be refreshed by calling touch() again.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001759 p.touch()
Antoine Pitrou0f575642013-11-22 23:20:08 +01001760 st = p.stat()
Antoine Pitrou2cf39172013-11-23 15:25:59 +01001761 self.assertGreaterEqual(st.st_mtime_ns, old_mtime_ns)
1762 self.assertGreaterEqual(st.st_mtime, old_mtime)
Anthony Shaw83da9262019-01-07 07:31:29 +11001763 # Now with exist_ok=False.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001764 p = P / 'newfileB'
1765 self.assertFalse(p.exists())
1766 p.touch(mode=0o700, exist_ok=False)
1767 self.assertTrue(p.exists())
1768 self.assertRaises(OSError, p.touch, exist_ok=False)
1769
Antoine Pitrou8b784932013-11-23 14:52:39 +01001770 def test_touch_nochange(self):
1771 P = self.cls(BASE)
1772 p = P / 'fileA'
1773 p.touch()
1774 with p.open('rb') as f:
1775 self.assertEqual(f.read().strip(), b"this is file A")
1776
Antoine Pitrou31119e42013-11-22 17:38:12 +01001777 def test_mkdir(self):
1778 P = self.cls(BASE)
1779 p = P / 'newdirA'
1780 self.assertFalse(p.exists())
1781 p.mkdir()
1782 self.assertTrue(p.exists())
1783 self.assertTrue(p.is_dir())
1784 with self.assertRaises(OSError) as cm:
1785 p.mkdir()
1786 self.assertEqual(cm.exception.errno, errno.EEXIST)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001787
1788 def test_mkdir_parents(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001789 # Creating a chain of directories.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001790 p = self.cls(BASE, 'newdirB', 'newdirC')
1791 self.assertFalse(p.exists())
1792 with self.assertRaises(OSError) as cm:
1793 p.mkdir()
1794 self.assertEqual(cm.exception.errno, errno.ENOENT)
1795 p.mkdir(parents=True)
1796 self.assertTrue(p.exists())
1797 self.assertTrue(p.is_dir())
1798 with self.assertRaises(OSError) as cm:
1799 p.mkdir(parents=True)
1800 self.assertEqual(cm.exception.errno, errno.EEXIST)
Anthony Shaw83da9262019-01-07 07:31:29 +11001801 # Test `mode` arg.
1802 mode = stat.S_IMODE(p.stat().st_mode) # Default mode.
Antoine Pitrou0048c982013-12-16 20:22:37 +01001803 p = self.cls(BASE, 'newdirD', 'newdirE')
1804 p.mkdir(0o555, parents=True)
1805 self.assertTrue(p.exists())
1806 self.assertTrue(p.is_dir())
1807 if os.name != 'nt':
Anthony Shaw83da9262019-01-07 07:31:29 +11001808 # The directory's permissions follow the mode argument.
Gregory P. Smithb599c612014-01-20 01:10:33 -08001809 self.assertEqual(stat.S_IMODE(p.stat().st_mode), 0o7555 & mode)
Anthony Shaw83da9262019-01-07 07:31:29 +11001810 # The parent's permissions follow the default process settings.
Antoine Pitrou0048c982013-12-16 20:22:37 +01001811 self.assertEqual(stat.S_IMODE(p.parent.stat().st_mode), mode)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001812
Barry Warsaw7c549c42014-08-05 11:28:12 -04001813 def test_mkdir_exist_ok(self):
1814 p = self.cls(BASE, 'dirB')
1815 st_ctime_first = p.stat().st_ctime
1816 self.assertTrue(p.exists())
1817 self.assertTrue(p.is_dir())
1818 with self.assertRaises(FileExistsError) as cm:
1819 p.mkdir()
1820 self.assertEqual(cm.exception.errno, errno.EEXIST)
1821 p.mkdir(exist_ok=True)
1822 self.assertTrue(p.exists())
1823 self.assertEqual(p.stat().st_ctime, st_ctime_first)
1824
1825 def test_mkdir_exist_ok_with_parent(self):
1826 p = self.cls(BASE, 'dirC')
1827 self.assertTrue(p.exists())
1828 with self.assertRaises(FileExistsError) as cm:
1829 p.mkdir()
1830 self.assertEqual(cm.exception.errno, errno.EEXIST)
1831 p = p / 'newdirC'
1832 p.mkdir(parents=True)
1833 st_ctime_first = p.stat().st_ctime
1834 self.assertTrue(p.exists())
1835 with self.assertRaises(FileExistsError) as cm:
1836 p.mkdir(parents=True)
1837 self.assertEqual(cm.exception.errno, errno.EEXIST)
1838 p.mkdir(parents=True, exist_ok=True)
1839 self.assertTrue(p.exists())
1840 self.assertEqual(p.stat().st_ctime, st_ctime_first)
1841
Serhiy Storchakaaf7b9ec2017-03-24 20:51:53 +02001842 def test_mkdir_exist_ok_root(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001843 # Issue #25803: A drive root could raise PermissionError on Windows.
Serhiy Storchakaaf7b9ec2017-03-24 20:51:53 +02001844 self.cls('/').resolve().mkdir(exist_ok=True)
1845 self.cls('/').resolve().mkdir(parents=True, exist_ok=True)
1846
Anthony Shaw83da9262019-01-07 07:31:29 +11001847 @only_nt # XXX: not sure how to test this on POSIX.
Steve Dowerd3c48532017-02-04 14:54:56 -08001848 def test_mkdir_with_unknown_drive(self):
1849 for d in 'ZYXWVUTSRQPONMLKJIHGFEDCBA':
1850 p = self.cls(d + ':\\')
1851 if not p.is_dir():
1852 break
1853 else:
1854 self.skipTest("cannot find a drive that doesn't exist")
1855 with self.assertRaises(OSError):
1856 (p / 'child' / 'path').mkdir(parents=True)
1857
Barry Warsaw7c549c42014-08-05 11:28:12 -04001858 def test_mkdir_with_child_file(self):
1859 p = self.cls(BASE, 'dirB', 'fileB')
1860 self.assertTrue(p.exists())
1861 # An exception is raised when the last path component is an existing
1862 # regular file, regardless of whether exist_ok is true or not.
1863 with self.assertRaises(FileExistsError) as cm:
1864 p.mkdir(parents=True)
1865 self.assertEqual(cm.exception.errno, errno.EEXIST)
1866 with self.assertRaises(FileExistsError) as cm:
1867 p.mkdir(parents=True, exist_ok=True)
1868 self.assertEqual(cm.exception.errno, errno.EEXIST)
1869
1870 def test_mkdir_no_parents_file(self):
1871 p = self.cls(BASE, 'fileA')
1872 self.assertTrue(p.exists())
1873 # An exception is raised when the last path component is an existing
1874 # regular file, regardless of whether exist_ok is true or not.
1875 with self.assertRaises(FileExistsError) as cm:
1876 p.mkdir()
1877 self.assertEqual(cm.exception.errno, errno.EEXIST)
1878 with self.assertRaises(FileExistsError) as cm:
1879 p.mkdir(exist_ok=True)
1880 self.assertEqual(cm.exception.errno, errno.EEXIST)
1881
Armin Rigo22a594a2017-04-13 20:08:15 +02001882 def test_mkdir_concurrent_parent_creation(self):
1883 for pattern_num in range(32):
1884 p = self.cls(BASE, 'dirCPC%d' % pattern_num)
1885 self.assertFalse(p.exists())
1886
1887 def my_mkdir(path, mode=0o777):
1888 path = str(path)
1889 # Emulate another process that would create the directory
1890 # just before we try to create it ourselves. We do it
1891 # in all possible pattern combinations, assuming that this
1892 # function is called at most 5 times (dirCPC/dir1/dir2,
1893 # dirCPC/dir1, dirCPC, dirCPC/dir1, dirCPC/dir1/dir2).
1894 if pattern.pop():
Anthony Shaw83da9262019-01-07 07:31:29 +11001895 os.mkdir(path, mode) # From another process.
Armin Rigo22a594a2017-04-13 20:08:15 +02001896 concurrently_created.add(path)
Anthony Shaw83da9262019-01-07 07:31:29 +11001897 os.mkdir(path, mode) # Our real call.
Armin Rigo22a594a2017-04-13 20:08:15 +02001898
1899 pattern = [bool(pattern_num & (1 << n)) for n in range(5)]
1900 concurrently_created = set()
1901 p12 = p / 'dir1' / 'dir2'
1902 try:
1903 with mock.patch("pathlib._normal_accessor.mkdir", my_mkdir):
1904 p12.mkdir(parents=True, exist_ok=False)
1905 except FileExistsError:
1906 self.assertIn(str(p12), concurrently_created)
1907 else:
1908 self.assertNotIn(str(p12), concurrently_created)
1909 self.assertTrue(p.exists())
1910
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001911 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001912 def test_symlink_to(self):
1913 P = self.cls(BASE)
1914 target = P / 'fileA'
Anthony Shaw83da9262019-01-07 07:31:29 +11001915 # Symlinking a path target.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001916 link = P / 'dirA' / 'linkAA'
1917 link.symlink_to(target)
1918 self.assertEqual(link.stat(), target.stat())
1919 self.assertNotEqual(link.lstat(), target.stat())
Anthony Shaw83da9262019-01-07 07:31:29 +11001920 # Symlinking a str target.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001921 link = P / 'dirA' / 'linkAAA'
1922 link.symlink_to(str(target))
1923 self.assertEqual(link.stat(), target.stat())
1924 self.assertNotEqual(link.lstat(), target.stat())
1925 self.assertFalse(link.is_dir())
Anthony Shaw83da9262019-01-07 07:31:29 +11001926 # Symlinking to a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001927 target = P / 'dirB'
1928 link = P / 'dirA' / 'linkAAAA'
1929 link.symlink_to(target, target_is_directory=True)
1930 self.assertEqual(link.stat(), target.stat())
1931 self.assertNotEqual(link.lstat(), target.stat())
1932 self.assertTrue(link.is_dir())
1933 self.assertTrue(list(link.iterdir()))
1934
1935 def test_is_dir(self):
1936 P = self.cls(BASE)
1937 self.assertTrue((P / 'dirA').is_dir())
1938 self.assertFalse((P / 'fileA').is_dir())
1939 self.assertFalse((P / 'non-existing').is_dir())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001940 self.assertFalse((P / 'fileA' / 'bah').is_dir())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001941 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001942 self.assertFalse((P / 'linkA').is_dir())
1943 self.assertTrue((P / 'linkB').is_dir())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001944 self.assertFalse((P/ 'brokenLink').is_dir(), False)
1945 self.assertIs((P / 'dirA\udfff').is_dir(), False)
1946 self.assertIs((P / 'dirA\x00').is_dir(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001947
1948 def test_is_file(self):
1949 P = self.cls(BASE)
1950 self.assertTrue((P / 'fileA').is_file())
1951 self.assertFalse((P / 'dirA').is_file())
1952 self.assertFalse((P / 'non-existing').is_file())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001953 self.assertFalse((P / 'fileA' / 'bah').is_file())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001954 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001955 self.assertTrue((P / 'linkA').is_file())
1956 self.assertFalse((P / 'linkB').is_file())
1957 self.assertFalse((P/ 'brokenLink').is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001958 self.assertIs((P / 'fileA\udfff').is_file(), False)
1959 self.assertIs((P / 'fileA\x00').is_file(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001960
Cooper Lees173ff4a2017-08-01 15:35:45 -07001961 @only_posix
1962 def test_is_mount(self):
1963 P = self.cls(BASE)
Anthony Shaw83da9262019-01-07 07:31:29 +11001964 R = self.cls('/') # TODO: Work out Windows.
Cooper Lees173ff4a2017-08-01 15:35:45 -07001965 self.assertFalse((P / 'fileA').is_mount())
1966 self.assertFalse((P / 'dirA').is_mount())
1967 self.assertFalse((P / 'non-existing').is_mount())
1968 self.assertFalse((P / 'fileA' / 'bah').is_mount())
1969 self.assertTrue(R.is_mount())
1970 if support.can_symlink():
1971 self.assertFalse((P / 'linkA').is_mount())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001972 self.assertIs(self.cls('/\udfff').is_mount(), False)
1973 self.assertIs(self.cls('/\x00').is_mount(), False)
Cooper Lees173ff4a2017-08-01 15:35:45 -07001974
Antoine Pitrou31119e42013-11-22 17:38:12 +01001975 def test_is_symlink(self):
1976 P = self.cls(BASE)
1977 self.assertFalse((P / 'fileA').is_symlink())
1978 self.assertFalse((P / 'dirA').is_symlink())
1979 self.assertFalse((P / 'non-existing').is_symlink())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001980 self.assertFalse((P / 'fileA' / 'bah').is_symlink())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001981 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001982 self.assertTrue((P / 'linkA').is_symlink())
1983 self.assertTrue((P / 'linkB').is_symlink())
1984 self.assertTrue((P/ 'brokenLink').is_symlink())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001985 self.assertIs((P / 'fileA\udfff').is_file(), False)
1986 self.assertIs((P / 'fileA\x00').is_file(), False)
1987 if support.can_symlink():
1988 self.assertIs((P / 'linkA\udfff').is_file(), False)
1989 self.assertIs((P / 'linkA\x00').is_file(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001990
1991 def test_is_fifo_false(self):
1992 P = self.cls(BASE)
1993 self.assertFalse((P / 'fileA').is_fifo())
1994 self.assertFalse((P / 'dirA').is_fifo())
1995 self.assertFalse((P / 'non-existing').is_fifo())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001996 self.assertFalse((P / 'fileA' / 'bah').is_fifo())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001997 self.assertIs((P / 'fileA\udfff').is_fifo(), False)
1998 self.assertIs((P / 'fileA\x00').is_fifo(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001999
2000 @unittest.skipUnless(hasattr(os, "mkfifo"), "os.mkfifo() required")
2001 def test_is_fifo_true(self):
2002 P = self.cls(BASE, 'myfifo')
xdegaye92c2ca72017-11-12 17:31:07 +01002003 try:
2004 os.mkfifo(str(P))
2005 except PermissionError as e:
2006 self.skipTest('os.mkfifo(): %s' % e)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002007 self.assertTrue(P.is_fifo())
2008 self.assertFalse(P.is_socket())
2009 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002010 self.assertIs(self.cls(BASE, 'myfifo\udfff').is_fifo(), False)
2011 self.assertIs(self.cls(BASE, 'myfifo\x00').is_fifo(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002012
2013 def test_is_socket_false(self):
2014 P = self.cls(BASE)
2015 self.assertFalse((P / 'fileA').is_socket())
2016 self.assertFalse((P / 'dirA').is_socket())
2017 self.assertFalse((P / 'non-existing').is_socket())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002018 self.assertFalse((P / 'fileA' / 'bah').is_socket())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002019 self.assertIs((P / 'fileA\udfff').is_socket(), False)
2020 self.assertIs((P / 'fileA\x00').is_socket(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002021
2022 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required")
2023 def test_is_socket_true(self):
2024 P = self.cls(BASE, 'mysock')
Antoine Pitrou330ce592013-11-22 18:05:06 +01002025 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002026 self.addCleanup(sock.close)
Antoine Pitrou330ce592013-11-22 18:05:06 +01002027 try:
2028 sock.bind(str(P))
2029 except OSError as e:
Xavier de Gayee88ed052016-12-14 11:52:28 +01002030 if (isinstance(e, PermissionError) or
2031 "AF_UNIX path too long" in str(e)):
Antoine Pitrou330ce592013-11-22 18:05:06 +01002032 self.skipTest("cannot bind Unix socket: " + str(e))
Antoine Pitrou31119e42013-11-22 17:38:12 +01002033 self.assertTrue(P.is_socket())
2034 self.assertFalse(P.is_fifo())
2035 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002036 self.assertIs(self.cls(BASE, 'mysock\udfff').is_socket(), False)
2037 self.assertIs(self.cls(BASE, 'mysock\x00').is_socket(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002038
2039 def test_is_block_device_false(self):
2040 P = self.cls(BASE)
2041 self.assertFalse((P / 'fileA').is_block_device())
2042 self.assertFalse((P / 'dirA').is_block_device())
2043 self.assertFalse((P / 'non-existing').is_block_device())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002044 self.assertFalse((P / 'fileA' / 'bah').is_block_device())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002045 self.assertIs((P / 'fileA\udfff').is_block_device(), False)
2046 self.assertIs((P / 'fileA\x00').is_block_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002047
2048 def test_is_char_device_false(self):
2049 P = self.cls(BASE)
2050 self.assertFalse((P / 'fileA').is_char_device())
2051 self.assertFalse((P / 'dirA').is_char_device())
2052 self.assertFalse((P / 'non-existing').is_char_device())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002053 self.assertFalse((P / 'fileA' / 'bah').is_char_device())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002054 self.assertIs((P / 'fileA\udfff').is_char_device(), False)
2055 self.assertIs((P / 'fileA\x00').is_char_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002056
2057 def test_is_char_device_true(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002058 # Under Unix, /dev/null should generally be a char device.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002059 P = self.cls('/dev/null')
2060 if not P.exists():
2061 self.skipTest("/dev/null required")
2062 self.assertTrue(P.is_char_device())
2063 self.assertFalse(P.is_block_device())
2064 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002065 self.assertIs(self.cls('/dev/null\udfff').is_char_device(), False)
2066 self.assertIs(self.cls('/dev/null\x00').is_char_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002067
2068 def test_pickling_common(self):
2069 p = self.cls(BASE, 'fileA')
2070 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
2071 dumped = pickle.dumps(p, proto)
2072 pp = pickle.loads(dumped)
2073 self.assertEqual(pp.stat(), p.stat())
2074
2075 def test_parts_interning(self):
2076 P = self.cls
2077 p = P('/usr/bin/foo')
2078 q = P('/usr/local/bin')
2079 # 'usr'
2080 self.assertIs(p.parts[1], q.parts[1])
2081 # 'bin'
2082 self.assertIs(p.parts[2], q.parts[3])
2083
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002084 def _check_complex_symlinks(self, link0_target):
Anthony Shaw83da9262019-01-07 07:31:29 +11002085 # Test solving a non-looping chain of symlinks (issue #19887).
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002086 P = self.cls(BASE)
2087 self.dirlink(os.path.join('link0', 'link0'), join('link1'))
2088 self.dirlink(os.path.join('link1', 'link1'), join('link2'))
2089 self.dirlink(os.path.join('link2', 'link2'), join('link3'))
2090 self.dirlink(link0_target, join('link0'))
2091
Anthony Shaw83da9262019-01-07 07:31:29 +11002092 # Resolve absolute paths.
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002093 p = (P / 'link0').resolve()
2094 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002095 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002096 p = (P / 'link1').resolve()
2097 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002098 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002099 p = (P / 'link2').resolve()
2100 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002101 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002102 p = (P / 'link3').resolve()
2103 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002104 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002105
Anthony Shaw83da9262019-01-07 07:31:29 +11002106 # Resolve relative paths.
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002107 old_path = os.getcwd()
2108 os.chdir(BASE)
2109 try:
2110 p = self.cls('link0').resolve()
2111 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002112 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002113 p = self.cls('link1').resolve()
2114 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002115 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002116 p = self.cls('link2').resolve()
2117 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002118 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002119 p = self.cls('link3').resolve()
2120 self.assertEqual(p, P)
Steve Dower206e4c32019-09-10 15:29:28 +01002121 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002122 finally:
2123 os.chdir(old_path)
2124
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002125 @support.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002126 def test_complex_symlinks_absolute(self):
2127 self._check_complex_symlinks(BASE)
2128
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002129 @support.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002130 def test_complex_symlinks_relative(self):
2131 self._check_complex_symlinks('.')
2132
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002133 @support.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002134 def test_complex_symlinks_relative_dot_dot(self):
2135 self._check_complex_symlinks(os.path.join('dirA', '..'))
2136
Antoine Pitrou31119e42013-11-22 17:38:12 +01002137
2138class PathTest(_BasePathTest, unittest.TestCase):
2139 cls = pathlib.Path
2140
2141 def test_concrete_class(self):
2142 p = self.cls('a')
2143 self.assertIs(type(p),
2144 pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath)
2145
2146 def test_unsupported_flavour(self):
2147 if os.name == 'nt':
2148 self.assertRaises(NotImplementedError, pathlib.PosixPath)
2149 else:
2150 self.assertRaises(NotImplementedError, pathlib.WindowsPath)
2151
Berker Peksag4a208e42016-01-30 17:50:48 +02002152 def test_glob_empty_pattern(self):
2153 p = self.cls()
2154 with self.assertRaisesRegex(ValueError, 'Unacceptable pattern'):
2155 list(p.glob(''))
2156
Antoine Pitrou31119e42013-11-22 17:38:12 +01002157
2158@only_posix
2159class PosixPathTest(_BasePathTest, unittest.TestCase):
2160 cls = pathlib.PosixPath
2161
Steve Dower98eb3602016-11-09 12:58:17 -08002162 def _check_symlink_loop(self, *args, strict=True):
Antoine Pitrou31119e42013-11-22 17:38:12 +01002163 path = self.cls(*args)
2164 with self.assertRaises(RuntimeError):
Steve Dower98eb3602016-11-09 12:58:17 -08002165 print(path.resolve(strict))
Antoine Pitrou31119e42013-11-22 17:38:12 +01002166
2167 def test_open_mode(self):
2168 old_mask = os.umask(0)
2169 self.addCleanup(os.umask, old_mask)
2170 p = self.cls(BASE)
2171 with (p / 'new_file').open('wb'):
2172 pass
2173 st = os.stat(join('new_file'))
2174 self.assertEqual(stat.S_IMODE(st.st_mode), 0o666)
2175 os.umask(0o022)
2176 with (p / 'other_new_file').open('wb'):
2177 pass
2178 st = os.stat(join('other_new_file'))
2179 self.assertEqual(stat.S_IMODE(st.st_mode), 0o644)
2180
2181 def test_touch_mode(self):
2182 old_mask = os.umask(0)
2183 self.addCleanup(os.umask, old_mask)
2184 p = self.cls(BASE)
2185 (p / 'new_file').touch()
2186 st = os.stat(join('new_file'))
2187 self.assertEqual(stat.S_IMODE(st.st_mode), 0o666)
2188 os.umask(0o022)
2189 (p / 'other_new_file').touch()
2190 st = os.stat(join('other_new_file'))
2191 self.assertEqual(stat.S_IMODE(st.st_mode), 0o644)
2192 (p / 'masked_new_file').touch(mode=0o750)
2193 st = os.stat(join('masked_new_file'))
2194 self.assertEqual(stat.S_IMODE(st.st_mode), 0o750)
2195
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002196 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01002197 def test_resolve_loop(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002198 # Loops with relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002199 os.symlink('linkX/inside', join('linkX'))
2200 self._check_symlink_loop(BASE, 'linkX')
2201 os.symlink('linkY', join('linkY'))
2202 self._check_symlink_loop(BASE, 'linkY')
2203 os.symlink('linkZ/../linkZ', join('linkZ'))
2204 self._check_symlink_loop(BASE, 'linkZ')
Steve Dower98eb3602016-11-09 12:58:17 -08002205 # Non-strict
2206 self._check_symlink_loop(BASE, 'linkZ', 'foo', strict=False)
Anthony Shaw83da9262019-01-07 07:31:29 +11002207 # Loops with absolute symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002208 os.symlink(join('linkU/inside'), join('linkU'))
2209 self._check_symlink_loop(BASE, 'linkU')
2210 os.symlink(join('linkV'), join('linkV'))
2211 self._check_symlink_loop(BASE, 'linkV')
2212 os.symlink(join('linkW/../linkW'), join('linkW'))
2213 self._check_symlink_loop(BASE, 'linkW')
Steve Dower98eb3602016-11-09 12:58:17 -08002214 # Non-strict
2215 self._check_symlink_loop(BASE, 'linkW', 'foo', strict=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002216
2217 def test_glob(self):
2218 P = self.cls
2219 p = P(BASE)
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002220 given = set(p.glob("FILEa"))
2221 expect = set() if not support.fs_is_case_insensitive(BASE) else given
2222 self.assertEqual(given, expect)
Antoine Pitrou2dd38fb2013-11-22 22:26:01 +01002223 self.assertEqual(set(p.glob("FILEa*")), set())
Antoine Pitrou31119e42013-11-22 17:38:12 +01002224
2225 def test_rglob(self):
2226 P = self.cls
2227 p = P(BASE, "dirC")
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002228 given = set(p.rglob("FILEd"))
2229 expect = set() if not support.fs_is_case_insensitive(BASE) else given
2230 self.assertEqual(given, expect)
Antoine Pitrou2dd38fb2013-11-22 22:26:01 +01002231 self.assertEqual(set(p.rglob("FILEd*")), set())
Antoine Pitrou31119e42013-11-22 17:38:12 +01002232
Xavier de Gayefb24eea2016-12-13 09:11:38 +01002233 @unittest.skipUnless(hasattr(pwd, 'getpwall'),
2234 'pwd module does not expose getpwall()')
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002235 def test_expanduser(self):
2236 P = self.cls
2237 support.import_module('pwd')
2238 import pwd
2239 pwdent = pwd.getpwuid(os.getuid())
2240 username = pwdent.pw_name
Serhiy Storchakaa3fd0b22016-05-03 21:17:03 +03002241 userhome = pwdent.pw_dir.rstrip('/') or '/'
Anthony Shaw83da9262019-01-07 07:31:29 +11002242 # Find arbitrary different user (if exists).
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002243 for pwdent in pwd.getpwall():
2244 othername = pwdent.pw_name
2245 otherhome = pwdent.pw_dir.rstrip('/')
Victor Stinnere9694392015-01-10 09:00:20 +01002246 if othername != username and otherhome:
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002247 break
Anders Kaseorg5c0d4622018-05-14 10:00:37 -04002248 else:
2249 othername = username
2250 otherhome = userhome
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002251
2252 p1 = P('~/Documents')
2253 p2 = P('~' + username + '/Documents')
2254 p3 = P('~' + othername + '/Documents')
2255 p4 = P('../~' + username + '/Documents')
2256 p5 = P('/~' + username + '/Documents')
2257 p6 = P('')
2258 p7 = P('~fakeuser/Documents')
2259
2260 with support.EnvironmentVarGuard() as env:
2261 env.pop('HOME', None)
2262
2263 self.assertEqual(p1.expanduser(), P(userhome) / 'Documents')
2264 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
2265 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
2266 self.assertEqual(p4.expanduser(), p4)
2267 self.assertEqual(p5.expanduser(), p5)
2268 self.assertEqual(p6.expanduser(), p6)
2269 self.assertRaises(RuntimeError, p7.expanduser)
2270
2271 env['HOME'] = '/tmp'
2272 self.assertEqual(p1.expanduser(), P('/tmp/Documents'))
2273 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
2274 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
2275 self.assertEqual(p4.expanduser(), p4)
2276 self.assertEqual(p5.expanduser(), p5)
2277 self.assertEqual(p6.expanduser(), p6)
2278 self.assertRaises(RuntimeError, p7.expanduser)
2279
Przemysław Spodymek216b7452018-08-27 23:33:45 +02002280 @unittest.skipIf(sys.platform != "darwin",
2281 "Bad file descriptor in /dev/fd affects only macOS")
2282 def test_handling_bad_descriptor(self):
2283 try:
2284 file_descriptors = list(pathlib.Path('/dev/fd').rglob("*"))[3:]
2285 if not file_descriptors:
2286 self.skipTest("no file descriptors - issue was not reproduced")
2287 # Checking all file descriptors because there is no guarantee
2288 # which one will fail.
2289 for f in file_descriptors:
2290 f.exists()
2291 f.is_dir()
2292 f.is_file()
2293 f.is_symlink()
2294 f.is_block_device()
2295 f.is_char_device()
2296 f.is_fifo()
2297 f.is_socket()
2298 except OSError as e:
2299 if e.errno == errno.EBADF:
2300 self.fail("Bad file descriptor not handled.")
2301 raise
2302
Antoine Pitrou31119e42013-11-22 17:38:12 +01002303
2304@only_nt
2305class WindowsPathTest(_BasePathTest, unittest.TestCase):
2306 cls = pathlib.WindowsPath
2307
2308 def test_glob(self):
2309 P = self.cls
2310 p = P(BASE)
2311 self.assertEqual(set(p.glob("FILEa")), { P(BASE, "fileA") })
Miss Skeleton (bot)2f8d4f02019-10-21 11:17:57 -07002312 self.assertEqual(set(p.glob("F*a")), { P(BASE, "fileA") })
2313 self.assertEqual(set(map(str, p.glob("FILEa"))), {f"{p}\\FILEa"})
2314 self.assertEqual(set(map(str, p.glob("F*a"))), {f"{p}\\fileA"})
Antoine Pitrou31119e42013-11-22 17:38:12 +01002315
2316 def test_rglob(self):
2317 P = self.cls
2318 p = P(BASE, "dirC")
2319 self.assertEqual(set(p.rglob("FILEd")), { P(BASE, "dirC/dirD/fileD") })
Miss Skeleton (bot)2f8d4f02019-10-21 11:17:57 -07002320 self.assertEqual(set(map(str, p.rglob("FILEd"))), {f"{p}\\dirD\\FILEd"})
Antoine Pitrou31119e42013-11-22 17:38:12 +01002321
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002322 def test_expanduser(self):
2323 P = self.cls
2324 with support.EnvironmentVarGuard() as env:
2325 env.pop('HOME', None)
2326 env.pop('USERPROFILE', None)
2327 env.pop('HOMEPATH', None)
2328 env.pop('HOMEDRIVE', None)
2329 env['USERNAME'] = 'alice'
2330
2331 # test that the path returns unchanged
2332 p1 = P('~/My Documents')
2333 p2 = P('~alice/My Documents')
2334 p3 = P('~bob/My Documents')
2335 p4 = P('/~/My Documents')
2336 p5 = P('d:~/My Documents')
2337 p6 = P('')
2338 self.assertRaises(RuntimeError, p1.expanduser)
2339 self.assertRaises(RuntimeError, p2.expanduser)
2340 self.assertRaises(RuntimeError, p3.expanduser)
2341 self.assertEqual(p4.expanduser(), p4)
2342 self.assertEqual(p5.expanduser(), p5)
2343 self.assertEqual(p6.expanduser(), p6)
2344
2345 def check():
2346 env.pop('USERNAME', None)
2347 self.assertEqual(p1.expanduser(),
2348 P('C:/Users/alice/My Documents'))
2349 self.assertRaises(KeyError, p2.expanduser)
2350 env['USERNAME'] = 'alice'
2351 self.assertEqual(p2.expanduser(),
2352 P('C:/Users/alice/My Documents'))
2353 self.assertEqual(p3.expanduser(),
2354 P('C:/Users/bob/My Documents'))
2355 self.assertEqual(p4.expanduser(), p4)
2356 self.assertEqual(p5.expanduser(), p5)
2357 self.assertEqual(p6.expanduser(), p6)
2358
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002359 env['HOMEPATH'] = 'C:\\Users\\alice'
2360 check()
2361
2362 env['HOMEDRIVE'] = 'C:\\'
2363 env['HOMEPATH'] = 'Users\\alice'
2364 check()
2365
2366 env.pop('HOMEDRIVE', None)
2367 env.pop('HOMEPATH', None)
2368 env['USERPROFILE'] = 'C:\\Users\\alice'
2369 check()
2370
Miss Islington (bot)595b5162020-01-28 01:59:43 -08002371 # bpo-38883: ignore `HOME` when set on windows
2372 env['HOME'] = 'C:\\Users\\eve'
2373 check()
2374
Antoine Pitrou31119e42013-11-22 17:38:12 +01002375
Miss Islington (bot)4adcaf82019-08-28 22:05:59 -07002376class CompatiblePathTest(unittest.TestCase):
2377 """
2378 Test that a type can be made compatible with PurePath
2379 derivatives by implementing division operator overloads.
2380 """
2381
2382 class CompatPath:
2383 """
2384 Minimum viable class to test PurePath compatibility.
2385 Simply uses the division operator to join a given
2386 string and the string value of another object with
2387 a forward slash.
2388 """
2389 def __init__(self, string):
2390 self.string = string
2391
2392 def __truediv__(self, other):
2393 return type(self)(f"{self.string}/{other}")
2394
2395 def __rtruediv__(self, other):
2396 return type(self)(f"{other}/{self.string}")
2397
2398 def test_truediv(self):
2399 result = pathlib.PurePath("test") / self.CompatPath("right")
2400 self.assertIsInstance(result, self.CompatPath)
2401 self.assertEqual(result.string, "test/right")
2402
2403 with self.assertRaises(TypeError):
2404 # Verify improper operations still raise a TypeError
2405 pathlib.PurePath("test") / 10
2406
2407 def test_rtruediv(self):
2408 result = self.CompatPath("left") / pathlib.PurePath("test")
2409 self.assertIsInstance(result, self.CompatPath)
2410 self.assertEqual(result.string, "left/test")
2411
2412 with self.assertRaises(TypeError):
2413 # Verify improper operations still raise a TypeError
2414 10 / pathlib.PurePath("test")
2415
2416
Antoine Pitrou31119e42013-11-22 17:38:12 +01002417if __name__ == "__main__":
2418 unittest.main()