blob: 1589282886b6b88ab938f7dff09f9fcd5b21d615 [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
Tim Hoffmann8aea4b32020-04-19 17:29:49 +0200562 def test_with_stem_common(self):
563 P = self.cls
564 self.assertEqual(P('a/b').with_stem('d'), P('a/d'))
565 self.assertEqual(P('/a/b').with_stem('d'), P('/a/d'))
566 self.assertEqual(P('a/b.py').with_stem('d'), P('a/d.py'))
567 self.assertEqual(P('/a/b.py').with_stem('d'), P('/a/d.py'))
568 self.assertEqual(P('/a/b.tar.gz').with_stem('d'), P('/a/d.gz'))
569 self.assertEqual(P('a/Dot ending.').with_stem('d'), P('a/d'))
570 self.assertEqual(P('/a/Dot ending.').with_stem('d'), P('/a/d'))
571 self.assertRaises(ValueError, P('').with_stem, 'd')
572 self.assertRaises(ValueError, P('.').with_stem, 'd')
573 self.assertRaises(ValueError, P('/').with_stem, 'd')
574 self.assertRaises(ValueError, P('a/b').with_stem, '')
575 self.assertRaises(ValueError, P('a/b').with_stem, '/c')
576 self.assertRaises(ValueError, P('a/b').with_stem, 'c/')
577 self.assertRaises(ValueError, P('a/b').with_stem, 'c/d')
578
Antoine Pitrou31119e42013-11-22 17:38:12 +0100579 def test_with_suffix_common(self):
580 P = self.cls
581 self.assertEqual(P('a/b').with_suffix('.gz'), P('a/b.gz'))
582 self.assertEqual(P('/a/b').with_suffix('.gz'), P('/a/b.gz'))
583 self.assertEqual(P('a/b.py').with_suffix('.gz'), P('a/b.gz'))
584 self.assertEqual(P('/a/b.py').with_suffix('.gz'), P('/a/b.gz'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100585 # Stripping suffix.
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400586 self.assertEqual(P('a/b.py').with_suffix(''), P('a/b'))
587 self.assertEqual(P('/a/b').with_suffix(''), P('/a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100588 # Path doesn't have a "filename" component.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100589 self.assertRaises(ValueError, P('').with_suffix, '.gz')
590 self.assertRaises(ValueError, P('.').with_suffix, '.gz')
591 self.assertRaises(ValueError, P('/').with_suffix, '.gz')
Anthony Shaw83da9262019-01-07 07:31:29 +1100592 # Invalid suffix.
Antoine Pitrou1b02da92014-01-03 00:07:17 +0100593 self.assertRaises(ValueError, P('a/b').with_suffix, 'gz')
594 self.assertRaises(ValueError, P('a/b').with_suffix, '/')
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400595 self.assertRaises(ValueError, P('a/b').with_suffix, '.')
Antoine Pitrou1b02da92014-01-03 00:07:17 +0100596 self.assertRaises(ValueError, P('a/b').with_suffix, '/.gz')
597 self.assertRaises(ValueError, P('a/b').with_suffix, 'c/d')
598 self.assertRaises(ValueError, P('a/b').with_suffix, '.c/.d')
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400599 self.assertRaises(ValueError, P('a/b').with_suffix, './.d')
600 self.assertRaises(ValueError, P('a/b').with_suffix, '.d/.')
Berker Peksag423d05f2018-08-11 08:45:06 +0300601 self.assertRaises(ValueError, P('a/b').with_suffix,
602 (self.flavour.sep, 'd'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100603
604 def test_relative_to_common(self):
605 P = self.cls
606 p = P('a/b')
607 self.assertRaises(TypeError, p.relative_to)
Antoine Pitrou156b3612013-12-28 19:49:04 +0100608 self.assertRaises(TypeError, p.relative_to, b'a')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100609 self.assertEqual(p.relative_to(P()), P('a/b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100610 self.assertEqual(p.relative_to(''), P('a/b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100611 self.assertEqual(p.relative_to(P('a')), P('b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100612 self.assertEqual(p.relative_to('a'), P('b'))
613 self.assertEqual(p.relative_to('a/'), P('b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100614 self.assertEqual(p.relative_to(P('a/b')), P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100615 self.assertEqual(p.relative_to('a/b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100616 # With several args.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100617 self.assertEqual(p.relative_to('a', 'b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100618 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100619 self.assertRaises(ValueError, p.relative_to, P('c'))
620 self.assertRaises(ValueError, p.relative_to, P('a/b/c'))
621 self.assertRaises(ValueError, p.relative_to, P('a/c'))
622 self.assertRaises(ValueError, p.relative_to, P('/a'))
623 p = P('/a/b')
624 self.assertEqual(p.relative_to(P('/')), P('a/b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100625 self.assertEqual(p.relative_to('/'), P('a/b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100626 self.assertEqual(p.relative_to(P('/a')), P('b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100627 self.assertEqual(p.relative_to('/a'), P('b'))
628 self.assertEqual(p.relative_to('/a/'), P('b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100629 self.assertEqual(p.relative_to(P('/a/b')), P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100630 self.assertEqual(p.relative_to('/a/b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100631 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100632 self.assertRaises(ValueError, p.relative_to, P('/c'))
633 self.assertRaises(ValueError, p.relative_to, P('/a/b/c'))
634 self.assertRaises(ValueError, p.relative_to, P('/a/c'))
635 self.assertRaises(ValueError, p.relative_to, P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100636 self.assertRaises(ValueError, p.relative_to, '')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100637 self.assertRaises(ValueError, p.relative_to, P('a'))
638
Hai Shi82642a02019-08-13 14:54:02 -0500639 def test_is_relative_to_common(self):
640 P = self.cls
641 p = P('a/b')
642 self.assertRaises(TypeError, p.is_relative_to)
643 self.assertRaises(TypeError, p.is_relative_to, b'a')
644 self.assertTrue(p.is_relative_to(P()))
645 self.assertTrue(p.is_relative_to(''))
646 self.assertTrue(p.is_relative_to(P('a')))
647 self.assertTrue(p.is_relative_to('a/'))
648 self.assertTrue(p.is_relative_to(P('a/b')))
649 self.assertTrue(p.is_relative_to('a/b'))
650 # With several args.
651 self.assertTrue(p.is_relative_to('a', 'b'))
652 # Unrelated paths.
653 self.assertFalse(p.is_relative_to(P('c')))
654 self.assertFalse(p.is_relative_to(P('a/b/c')))
655 self.assertFalse(p.is_relative_to(P('a/c')))
656 self.assertFalse(p.is_relative_to(P('/a')))
657 p = P('/a/b')
658 self.assertTrue(p.is_relative_to(P('/')))
659 self.assertTrue(p.is_relative_to('/'))
660 self.assertTrue(p.is_relative_to(P('/a')))
661 self.assertTrue(p.is_relative_to('/a'))
662 self.assertTrue(p.is_relative_to('/a/'))
663 self.assertTrue(p.is_relative_to(P('/a/b')))
664 self.assertTrue(p.is_relative_to('/a/b'))
665 # Unrelated paths.
666 self.assertFalse(p.is_relative_to(P('/c')))
667 self.assertFalse(p.is_relative_to(P('/a/b/c')))
668 self.assertFalse(p.is_relative_to(P('/a/c')))
669 self.assertFalse(p.is_relative_to(P()))
670 self.assertFalse(p.is_relative_to(''))
671 self.assertFalse(p.is_relative_to(P('a')))
672
Antoine Pitrou31119e42013-11-22 17:38:12 +0100673 def test_pickling_common(self):
674 P = self.cls
675 p = P('/a/b')
676 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
677 dumped = pickle.dumps(p, proto)
678 pp = pickle.loads(dumped)
679 self.assertIs(pp.__class__, p.__class__)
680 self.assertEqual(pp, p)
681 self.assertEqual(hash(pp), hash(p))
682 self.assertEqual(str(pp), str(p))
683
684
685class PurePosixPathTest(_BasePurePathTest, unittest.TestCase):
686 cls = pathlib.PurePosixPath
687
688 def test_root(self):
689 P = self.cls
690 self.assertEqual(P('/a/b').root, '/')
691 self.assertEqual(P('///a/b').root, '/')
Anthony Shaw83da9262019-01-07 07:31:29 +1100692 # POSIX special case for two leading slashes.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100693 self.assertEqual(P('//a/b').root, '//')
694
695 def test_eq(self):
696 P = self.cls
697 self.assertNotEqual(P('a/b'), P('A/b'))
698 self.assertEqual(P('/a'), P('///a'))
699 self.assertNotEqual(P('/a'), P('//a'))
700
701 def test_as_uri(self):
Antoine Pitrou31119e42013-11-22 17:38:12 +0100702 P = self.cls
703 self.assertEqual(P('/').as_uri(), 'file:///')
704 self.assertEqual(P('/a/b.c').as_uri(), 'file:///a/b.c')
705 self.assertEqual(P('/a/b%#c').as_uri(), 'file:///a/b%25%23c')
Antoine Pitrou29eac422013-11-22 17:57:03 +0100706
707 def test_as_uri_non_ascii(self):
708 from urllib.parse import quote_from_bytes
709 P = self.cls
710 try:
711 os.fsencode('\xe9')
712 except UnicodeEncodeError:
713 self.skipTest("\\xe9 cannot be encoded to the filesystem encoding")
Antoine Pitrou31119e42013-11-22 17:38:12 +0100714 self.assertEqual(P('/a/b\xe9').as_uri(),
715 'file:///a/b' + quote_from_bytes(os.fsencode('\xe9')))
716
717 def test_match(self):
718 P = self.cls
719 self.assertFalse(P('A.py').match('a.PY'))
720
721 def test_is_absolute(self):
722 P = self.cls
723 self.assertFalse(P().is_absolute())
724 self.assertFalse(P('a').is_absolute())
725 self.assertFalse(P('a/b/').is_absolute())
726 self.assertTrue(P('/').is_absolute())
727 self.assertTrue(P('/a').is_absolute())
728 self.assertTrue(P('/a/b/').is_absolute())
729 self.assertTrue(P('//a').is_absolute())
730 self.assertTrue(P('//a/b').is_absolute())
731
732 def test_is_reserved(self):
733 P = self.cls
734 self.assertIs(False, P('').is_reserved())
735 self.assertIs(False, P('/').is_reserved())
736 self.assertIs(False, P('/foo/bar').is_reserved())
737 self.assertIs(False, P('/dev/con/PRN/NUL').is_reserved())
738
739 def test_join(self):
740 P = self.cls
741 p = P('//a')
742 pp = p.joinpath('b')
743 self.assertEqual(pp, P('//a/b'))
744 pp = P('/a').joinpath('//c')
745 self.assertEqual(pp, P('//c'))
746 pp = P('//a').joinpath('/c')
747 self.assertEqual(pp, P('/c'))
748
749 def test_div(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100750 # Basically the same as joinpath().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100751 P = self.cls
752 p = P('//a')
753 pp = p / 'b'
754 self.assertEqual(pp, P('//a/b'))
755 pp = P('/a') / '//c'
756 self.assertEqual(pp, P('//c'))
757 pp = P('//a') / '/c'
758 self.assertEqual(pp, P('/c'))
759
760
761class PureWindowsPathTest(_BasePurePathTest, unittest.TestCase):
762 cls = pathlib.PureWindowsPath
763
764 equivalences = _BasePurePathTest.equivalences.copy()
765 equivalences.update({
766 'c:a': [ ('c:', 'a'), ('c:', 'a/'), ('/', 'c:', 'a') ],
767 'c:/a': [
768 ('c:/', 'a'), ('c:', '/', 'a'), ('c:', '/a'),
769 ('/z', 'c:/', 'a'), ('//x/y', 'c:/', 'a'),
770 ],
771 '//a/b/': [ ('//a/b',) ],
772 '//a/b/c': [
773 ('//a/b', 'c'), ('//a/b/', 'c'),
774 ],
775 })
776
777 def test_str(self):
778 p = self.cls('a/b/c')
779 self.assertEqual(str(p), 'a\\b\\c')
780 p = self.cls('c:/a/b/c')
781 self.assertEqual(str(p), 'c:\\a\\b\\c')
782 p = self.cls('//a/b')
783 self.assertEqual(str(p), '\\\\a\\b\\')
784 p = self.cls('//a/b/c')
785 self.assertEqual(str(p), '\\\\a\\b\\c')
786 p = self.cls('//a/b/c/d')
787 self.assertEqual(str(p), '\\\\a\\b\\c\\d')
788
Antoine Pitroucb5ec772014-04-23 00:34:15 +0200789 def test_str_subclass(self):
790 self._check_str_subclass('c:')
791 self._check_str_subclass('c:a')
792 self._check_str_subclass('c:a\\b.txt')
793 self._check_str_subclass('c:\\')
794 self._check_str_subclass('c:\\a')
795 self._check_str_subclass('c:\\a\\b.txt')
796 self._check_str_subclass('\\\\some\\share')
797 self._check_str_subclass('\\\\some\\share\\a')
798 self._check_str_subclass('\\\\some\\share\\a\\b.txt')
799
Antoine Pitrou31119e42013-11-22 17:38:12 +0100800 def test_eq(self):
801 P = self.cls
802 self.assertEqual(P('c:a/b'), P('c:a/b'))
803 self.assertEqual(P('c:a/b'), P('c:', 'a', 'b'))
804 self.assertNotEqual(P('c:a/b'), P('d:a/b'))
805 self.assertNotEqual(P('c:a/b'), P('c:/a/b'))
806 self.assertNotEqual(P('/a/b'), P('c:/a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100807 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100808 self.assertEqual(P('a/B'), P('A/b'))
809 self.assertEqual(P('C:a/B'), P('c:A/b'))
810 self.assertEqual(P('//Some/SHARE/a/B'), P('//somE/share/A/b'))
811
812 def test_as_uri(self):
Antoine Pitrou31119e42013-11-22 17:38:12 +0100813 P = self.cls
814 with self.assertRaises(ValueError):
815 P('/a/b').as_uri()
816 with self.assertRaises(ValueError):
817 P('c:a/b').as_uri()
818 self.assertEqual(P('c:/').as_uri(), 'file:///c:/')
819 self.assertEqual(P('c:/a/b.c').as_uri(), 'file:///c:/a/b.c')
820 self.assertEqual(P('c:/a/b%#c').as_uri(), 'file:///c:/a/b%25%23c')
821 self.assertEqual(P('c:/a/b\xe9').as_uri(), 'file:///c:/a/b%C3%A9')
822 self.assertEqual(P('//some/share/').as_uri(), 'file://some/share/')
823 self.assertEqual(P('//some/share/a/b.c').as_uri(),
824 'file://some/share/a/b.c')
825 self.assertEqual(P('//some/share/a/b%#c\xe9').as_uri(),
826 'file://some/share/a/b%25%23c%C3%A9')
827
828 def test_match_common(self):
829 P = self.cls
Anthony Shaw83da9262019-01-07 07:31:29 +1100830 # Absolute patterns.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100831 self.assertTrue(P('c:/b.py').match('/*.py'))
832 self.assertTrue(P('c:/b.py').match('c:*.py'))
833 self.assertTrue(P('c:/b.py').match('c:/*.py'))
834 self.assertFalse(P('d:/b.py').match('c:/*.py')) # wrong drive
835 self.assertFalse(P('b.py').match('/*.py'))
836 self.assertFalse(P('b.py').match('c:*.py'))
837 self.assertFalse(P('b.py').match('c:/*.py'))
838 self.assertFalse(P('c:b.py').match('/*.py'))
839 self.assertFalse(P('c:b.py').match('c:/*.py'))
840 self.assertFalse(P('/b.py').match('c:*.py'))
841 self.assertFalse(P('/b.py').match('c:/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100842 # UNC patterns.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100843 self.assertTrue(P('//some/share/a.py').match('/*.py'))
844 self.assertTrue(P('//some/share/a.py').match('//some/share/*.py'))
845 self.assertFalse(P('//other/share/a.py').match('//some/share/*.py'))
846 self.assertFalse(P('//some/share/a/b.py').match('//some/share/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100847 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100848 self.assertTrue(P('B.py').match('b.PY'))
849 self.assertTrue(P('c:/a/B.Py').match('C:/A/*.pY'))
850 self.assertTrue(P('//Some/Share/B.Py').match('//somE/sharE/*.pY'))
851
852 def test_ordering_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100853 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100854 def assertOrderedEqual(a, b):
855 self.assertLessEqual(a, b)
856 self.assertGreaterEqual(b, a)
857 P = self.cls
858 p = P('c:A/b')
859 q = P('C:a/B')
860 assertOrderedEqual(p, q)
861 self.assertFalse(p < q)
862 self.assertFalse(p > q)
863 p = P('//some/Share/A/b')
864 q = P('//Some/SHARE/a/B')
865 assertOrderedEqual(p, q)
866 self.assertFalse(p < q)
867 self.assertFalse(p > q)
868
869 def test_parts(self):
870 P = self.cls
871 p = P('c:a/b')
872 parts = p.parts
873 self.assertEqual(parts, ('c:', 'a', 'b'))
874 p = P('c:/a/b')
875 parts = p.parts
876 self.assertEqual(parts, ('c:\\', 'a', 'b'))
877 p = P('//a/b/c/d')
878 parts = p.parts
879 self.assertEqual(parts, ('\\\\a\\b\\', 'c', 'd'))
880
881 def test_parent(self):
882 # Anchored
883 P = self.cls
884 p = P('z:a/b/c')
885 self.assertEqual(p.parent, P('z:a/b'))
886 self.assertEqual(p.parent.parent, P('z:a'))
887 self.assertEqual(p.parent.parent.parent, P('z:'))
888 self.assertEqual(p.parent.parent.parent.parent, P('z:'))
889 p = P('z:/a/b/c')
890 self.assertEqual(p.parent, P('z:/a/b'))
891 self.assertEqual(p.parent.parent, P('z:/a'))
892 self.assertEqual(p.parent.parent.parent, P('z:/'))
893 self.assertEqual(p.parent.parent.parent.parent, P('z:/'))
894 p = P('//a/b/c/d')
895 self.assertEqual(p.parent, P('//a/b/c'))
896 self.assertEqual(p.parent.parent, P('//a/b'))
897 self.assertEqual(p.parent.parent.parent, P('//a/b'))
898
899 def test_parents(self):
900 # Anchored
901 P = self.cls
902 p = P('z:a/b/')
903 par = p.parents
904 self.assertEqual(len(par), 2)
905 self.assertEqual(par[0], P('z:a'))
906 self.assertEqual(par[1], P('z:'))
907 self.assertEqual(list(par), [P('z:a'), P('z:')])
908 with self.assertRaises(IndexError):
909 par[2]
910 p = P('z:/a/b/')
911 par = p.parents
912 self.assertEqual(len(par), 2)
913 self.assertEqual(par[0], P('z:/a'))
914 self.assertEqual(par[1], P('z:/'))
915 self.assertEqual(list(par), [P('z:/a'), P('z:/')])
916 with self.assertRaises(IndexError):
917 par[2]
918 p = P('//a/b/c/d')
919 par = p.parents
920 self.assertEqual(len(par), 2)
921 self.assertEqual(par[0], P('//a/b/c'))
922 self.assertEqual(par[1], P('//a/b'))
923 self.assertEqual(list(par), [P('//a/b/c'), P('//a/b')])
924 with self.assertRaises(IndexError):
925 par[2]
926
927 def test_drive(self):
928 P = self.cls
929 self.assertEqual(P('c:').drive, 'c:')
930 self.assertEqual(P('c:a/b').drive, 'c:')
931 self.assertEqual(P('c:/').drive, 'c:')
932 self.assertEqual(P('c:/a/b/').drive, 'c:')
933 self.assertEqual(P('//a/b').drive, '\\\\a\\b')
934 self.assertEqual(P('//a/b/').drive, '\\\\a\\b')
935 self.assertEqual(P('//a/b/c/d').drive, '\\\\a\\b')
936
937 def test_root(self):
938 P = self.cls
939 self.assertEqual(P('c:').root, '')
940 self.assertEqual(P('c:a/b').root, '')
941 self.assertEqual(P('c:/').root, '\\')
942 self.assertEqual(P('c:/a/b/').root, '\\')
943 self.assertEqual(P('//a/b').root, '\\')
944 self.assertEqual(P('//a/b/').root, '\\')
945 self.assertEqual(P('//a/b/c/d').root, '\\')
946
947 def test_anchor(self):
948 P = self.cls
949 self.assertEqual(P('c:').anchor, 'c:')
950 self.assertEqual(P('c:a/b').anchor, 'c:')
951 self.assertEqual(P('c:/').anchor, 'c:\\')
952 self.assertEqual(P('c:/a/b/').anchor, 'c:\\')
953 self.assertEqual(P('//a/b').anchor, '\\\\a\\b\\')
954 self.assertEqual(P('//a/b/').anchor, '\\\\a\\b\\')
955 self.assertEqual(P('//a/b/c/d').anchor, '\\\\a\\b\\')
956
957 def test_name(self):
958 P = self.cls
959 self.assertEqual(P('c:').name, '')
960 self.assertEqual(P('c:/').name, '')
961 self.assertEqual(P('c:a/b').name, 'b')
962 self.assertEqual(P('c:/a/b').name, 'b')
963 self.assertEqual(P('c:a/b.py').name, 'b.py')
964 self.assertEqual(P('c:/a/b.py').name, 'b.py')
965 self.assertEqual(P('//My.py/Share.php').name, '')
966 self.assertEqual(P('//My.py/Share.php/a/b').name, 'b')
967
968 def test_suffix(self):
969 P = self.cls
970 self.assertEqual(P('c:').suffix, '')
971 self.assertEqual(P('c:/').suffix, '')
972 self.assertEqual(P('c:a/b').suffix, '')
973 self.assertEqual(P('c:/a/b').suffix, '')
974 self.assertEqual(P('c:a/b.py').suffix, '.py')
975 self.assertEqual(P('c:/a/b.py').suffix, '.py')
976 self.assertEqual(P('c:a/.hgrc').suffix, '')
977 self.assertEqual(P('c:/a/.hgrc').suffix, '')
978 self.assertEqual(P('c:a/.hg.rc').suffix, '.rc')
979 self.assertEqual(P('c:/a/.hg.rc').suffix, '.rc')
980 self.assertEqual(P('c:a/b.tar.gz').suffix, '.gz')
981 self.assertEqual(P('c:/a/b.tar.gz').suffix, '.gz')
982 self.assertEqual(P('c:a/Some name. Ending with a dot.').suffix, '')
983 self.assertEqual(P('c:/a/Some name. Ending with a dot.').suffix, '')
984 self.assertEqual(P('//My.py/Share.php').suffix, '')
985 self.assertEqual(P('//My.py/Share.php/a/b').suffix, '')
986
987 def test_suffixes(self):
988 P = self.cls
989 self.assertEqual(P('c:').suffixes, [])
990 self.assertEqual(P('c:/').suffixes, [])
991 self.assertEqual(P('c:a/b').suffixes, [])
992 self.assertEqual(P('c:/a/b').suffixes, [])
993 self.assertEqual(P('c:a/b.py').suffixes, ['.py'])
994 self.assertEqual(P('c:/a/b.py').suffixes, ['.py'])
995 self.assertEqual(P('c:a/.hgrc').suffixes, [])
996 self.assertEqual(P('c:/a/.hgrc').suffixes, [])
997 self.assertEqual(P('c:a/.hg.rc').suffixes, ['.rc'])
998 self.assertEqual(P('c:/a/.hg.rc').suffixes, ['.rc'])
999 self.assertEqual(P('c:a/b.tar.gz').suffixes, ['.tar', '.gz'])
1000 self.assertEqual(P('c:/a/b.tar.gz').suffixes, ['.tar', '.gz'])
1001 self.assertEqual(P('//My.py/Share.php').suffixes, [])
1002 self.assertEqual(P('//My.py/Share.php/a/b').suffixes, [])
1003 self.assertEqual(P('c:a/Some name. Ending with a dot.').suffixes, [])
1004 self.assertEqual(P('c:/a/Some name. Ending with a dot.').suffixes, [])
1005
1006 def test_stem(self):
1007 P = self.cls
1008 self.assertEqual(P('c:').stem, '')
1009 self.assertEqual(P('c:.').stem, '')
1010 self.assertEqual(P('c:..').stem, '..')
1011 self.assertEqual(P('c:/').stem, '')
1012 self.assertEqual(P('c:a/b').stem, 'b')
1013 self.assertEqual(P('c:a/b.py').stem, 'b')
1014 self.assertEqual(P('c:a/.hgrc').stem, '.hgrc')
1015 self.assertEqual(P('c:a/.hg.rc').stem, '.hg')
1016 self.assertEqual(P('c:a/b.tar.gz').stem, 'b.tar')
1017 self.assertEqual(P('c:a/Some name. Ending with a dot.').stem,
1018 'Some name. Ending with a dot.')
1019
1020 def test_with_name(self):
1021 P = self.cls
1022 self.assertEqual(P('c:a/b').with_name('d.xml'), P('c:a/d.xml'))
1023 self.assertEqual(P('c:/a/b').with_name('d.xml'), P('c:/a/d.xml'))
1024 self.assertEqual(P('c:a/Dot ending.').with_name('d.xml'), P('c:a/d.xml'))
1025 self.assertEqual(P('c:/a/Dot ending.').with_name('d.xml'), P('c:/a/d.xml'))
1026 self.assertRaises(ValueError, P('c:').with_name, 'd.xml')
1027 self.assertRaises(ValueError, P('c:/').with_name, 'd.xml')
1028 self.assertRaises(ValueError, P('//My/Share').with_name, 'd.xml')
Antoine Pitrou7084e732014-07-06 21:31:12 -04001029 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:')
1030 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:e')
1031 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:/e')
1032 self.assertRaises(ValueError, P('c:a/b').with_name, '//My/Share')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001033
Tim Hoffmann8aea4b32020-04-19 17:29:49 +02001034 def test_with_stem(self):
1035 P = self.cls
1036 self.assertEqual(P('c:a/b').with_stem('d'), P('c:a/d'))
1037 self.assertEqual(P('c:/a/b').with_stem('d'), P('c:/a/d'))
1038 self.assertEqual(P('c:a/Dot ending.').with_stem('d'), P('c:a/d'))
1039 self.assertEqual(P('c:/a/Dot ending.').with_stem('d'), P('c:/a/d'))
1040 self.assertRaises(ValueError, P('c:').with_stem, 'd')
1041 self.assertRaises(ValueError, P('c:/').with_stem, 'd')
1042 self.assertRaises(ValueError, P('//My/Share').with_stem, 'd')
1043 self.assertRaises(ValueError, P('c:a/b').with_stem, 'd:')
1044 self.assertRaises(ValueError, P('c:a/b').with_stem, 'd:e')
1045 self.assertRaises(ValueError, P('c:a/b').with_stem, 'd:/e')
1046 self.assertRaises(ValueError, P('c:a/b').with_stem, '//My/Share')
1047
Antoine Pitrou31119e42013-11-22 17:38:12 +01001048 def test_with_suffix(self):
1049 P = self.cls
1050 self.assertEqual(P('c:a/b').with_suffix('.gz'), P('c:a/b.gz'))
1051 self.assertEqual(P('c:/a/b').with_suffix('.gz'), P('c:/a/b.gz'))
1052 self.assertEqual(P('c:a/b.py').with_suffix('.gz'), P('c:a/b.gz'))
1053 self.assertEqual(P('c:/a/b.py').with_suffix('.gz'), P('c:/a/b.gz'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001054 # Path doesn't have a "filename" component.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001055 self.assertRaises(ValueError, P('').with_suffix, '.gz')
1056 self.assertRaises(ValueError, P('.').with_suffix, '.gz')
1057 self.assertRaises(ValueError, P('/').with_suffix, '.gz')
1058 self.assertRaises(ValueError, P('//My/Share').with_suffix, '.gz')
Anthony Shaw83da9262019-01-07 07:31:29 +11001059 # Invalid suffix.
Antoine Pitrou1b02da92014-01-03 00:07:17 +01001060 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'gz')
1061 self.assertRaises(ValueError, P('c:a/b').with_suffix, '/')
1062 self.assertRaises(ValueError, P('c:a/b').with_suffix, '\\')
1063 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c:')
1064 self.assertRaises(ValueError, P('c:a/b').with_suffix, '/.gz')
1065 self.assertRaises(ValueError, P('c:a/b').with_suffix, '\\.gz')
1066 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c:.gz')
1067 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c/d')
1068 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c\\d')
1069 self.assertRaises(ValueError, P('c:a/b').with_suffix, '.c/d')
1070 self.assertRaises(ValueError, P('c:a/b').with_suffix, '.c\\d')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001071
1072 def test_relative_to(self):
1073 P = self.cls
Antoine Pitrou156b3612013-12-28 19:49:04 +01001074 p = P('C:Foo/Bar')
1075 self.assertEqual(p.relative_to(P('c:')), P('Foo/Bar'))
1076 self.assertEqual(p.relative_to('c:'), P('Foo/Bar'))
1077 self.assertEqual(p.relative_to(P('c:foO')), P('Bar'))
1078 self.assertEqual(p.relative_to('c:foO'), P('Bar'))
1079 self.assertEqual(p.relative_to('c:foO/'), P('Bar'))
1080 self.assertEqual(p.relative_to(P('c:foO/baR')), P())
1081 self.assertEqual(p.relative_to('c:foO/baR'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001082 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001083 self.assertRaises(ValueError, p.relative_to, P())
Antoine Pitrou156b3612013-12-28 19:49:04 +01001084 self.assertRaises(ValueError, p.relative_to, '')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001085 self.assertRaises(ValueError, p.relative_to, P('d:'))
Antoine Pitrou156b3612013-12-28 19:49:04 +01001086 self.assertRaises(ValueError, p.relative_to, P('/'))
1087 self.assertRaises(ValueError, p.relative_to, P('Foo'))
1088 self.assertRaises(ValueError, p.relative_to, P('/Foo'))
1089 self.assertRaises(ValueError, p.relative_to, P('C:/Foo'))
1090 self.assertRaises(ValueError, p.relative_to, P('C:Foo/Bar/Baz'))
1091 self.assertRaises(ValueError, p.relative_to, P('C:Foo/Baz'))
1092 p = P('C:/Foo/Bar')
1093 self.assertEqual(p.relative_to(P('c:')), P('/Foo/Bar'))
1094 self.assertEqual(p.relative_to('c:'), P('/Foo/Bar'))
1095 self.assertEqual(str(p.relative_to(P('c:'))), '\\Foo\\Bar')
1096 self.assertEqual(str(p.relative_to('c:')), '\\Foo\\Bar')
1097 self.assertEqual(p.relative_to(P('c:/')), P('Foo/Bar'))
1098 self.assertEqual(p.relative_to('c:/'), P('Foo/Bar'))
1099 self.assertEqual(p.relative_to(P('c:/foO')), P('Bar'))
1100 self.assertEqual(p.relative_to('c:/foO'), P('Bar'))
1101 self.assertEqual(p.relative_to('c:/foO/'), P('Bar'))
1102 self.assertEqual(p.relative_to(P('c:/foO/baR')), P())
1103 self.assertEqual(p.relative_to('c:/foO/baR'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001104 # Unrelated paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001105 self.assertRaises(ValueError, p.relative_to, P('C:/Baz'))
1106 self.assertRaises(ValueError, p.relative_to, P('C:/Foo/Bar/Baz'))
1107 self.assertRaises(ValueError, p.relative_to, P('C:/Foo/Baz'))
1108 self.assertRaises(ValueError, p.relative_to, P('C:Foo'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001109 self.assertRaises(ValueError, p.relative_to, P('d:'))
1110 self.assertRaises(ValueError, p.relative_to, P('d:/'))
Antoine Pitrou156b3612013-12-28 19:49:04 +01001111 self.assertRaises(ValueError, p.relative_to, P('/'))
1112 self.assertRaises(ValueError, p.relative_to, P('/Foo'))
1113 self.assertRaises(ValueError, p.relative_to, P('//C/Foo'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001114 # UNC paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001115 p = P('//Server/Share/Foo/Bar')
1116 self.assertEqual(p.relative_to(P('//sErver/sHare')), P('Foo/Bar'))
1117 self.assertEqual(p.relative_to('//sErver/sHare'), P('Foo/Bar'))
1118 self.assertEqual(p.relative_to('//sErver/sHare/'), P('Foo/Bar'))
1119 self.assertEqual(p.relative_to(P('//sErver/sHare/Foo')), P('Bar'))
1120 self.assertEqual(p.relative_to('//sErver/sHare/Foo'), P('Bar'))
1121 self.assertEqual(p.relative_to('//sErver/sHare/Foo/'), P('Bar'))
1122 self.assertEqual(p.relative_to(P('//sErver/sHare/Foo/Bar')), P())
1123 self.assertEqual(p.relative_to('//sErver/sHare/Foo/Bar'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001124 # Unrelated paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001125 self.assertRaises(ValueError, p.relative_to, P('/Server/Share/Foo'))
1126 self.assertRaises(ValueError, p.relative_to, P('c:/Server/Share/Foo'))
1127 self.assertRaises(ValueError, p.relative_to, P('//z/Share/Foo'))
1128 self.assertRaises(ValueError, p.relative_to, P('//Server/z/Foo'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001129
Hai Shi82642a02019-08-13 14:54:02 -05001130 def test_is_relative_to(self):
1131 P = self.cls
1132 p = P('C:Foo/Bar')
1133 self.assertTrue(p.is_relative_to(P('c:')))
1134 self.assertTrue(p.is_relative_to('c:'))
1135 self.assertTrue(p.is_relative_to(P('c:foO')))
1136 self.assertTrue(p.is_relative_to('c:foO'))
1137 self.assertTrue(p.is_relative_to('c:foO/'))
1138 self.assertTrue(p.is_relative_to(P('c:foO/baR')))
1139 self.assertTrue(p.is_relative_to('c:foO/baR'))
1140 # Unrelated paths.
1141 self.assertFalse(p.is_relative_to(P()))
1142 self.assertFalse(p.is_relative_to(''))
1143 self.assertFalse(p.is_relative_to(P('d:')))
1144 self.assertFalse(p.is_relative_to(P('/')))
1145 self.assertFalse(p.is_relative_to(P('Foo')))
1146 self.assertFalse(p.is_relative_to(P('/Foo')))
1147 self.assertFalse(p.is_relative_to(P('C:/Foo')))
1148 self.assertFalse(p.is_relative_to(P('C:Foo/Bar/Baz')))
1149 self.assertFalse(p.is_relative_to(P('C:Foo/Baz')))
1150 p = P('C:/Foo/Bar')
1151 self.assertTrue(p.is_relative_to('c:'))
1152 self.assertTrue(p.is_relative_to(P('c:/')))
1153 self.assertTrue(p.is_relative_to(P('c:/foO')))
1154 self.assertTrue(p.is_relative_to('c:/foO/'))
1155 self.assertTrue(p.is_relative_to(P('c:/foO/baR')))
1156 self.assertTrue(p.is_relative_to('c:/foO/baR'))
1157 # Unrelated paths.
1158 self.assertFalse(p.is_relative_to(P('C:/Baz')))
1159 self.assertFalse(p.is_relative_to(P('C:/Foo/Bar/Baz')))
1160 self.assertFalse(p.is_relative_to(P('C:/Foo/Baz')))
1161 self.assertFalse(p.is_relative_to(P('C:Foo')))
1162 self.assertFalse(p.is_relative_to(P('d:')))
1163 self.assertFalse(p.is_relative_to(P('d:/')))
1164 self.assertFalse(p.is_relative_to(P('/')))
1165 self.assertFalse(p.is_relative_to(P('/Foo')))
1166 self.assertFalse(p.is_relative_to(P('//C/Foo')))
1167 # UNC paths.
1168 p = P('//Server/Share/Foo/Bar')
1169 self.assertTrue(p.is_relative_to(P('//sErver/sHare')))
1170 self.assertTrue(p.is_relative_to('//sErver/sHare'))
1171 self.assertTrue(p.is_relative_to('//sErver/sHare/'))
1172 self.assertTrue(p.is_relative_to(P('//sErver/sHare/Foo')))
1173 self.assertTrue(p.is_relative_to('//sErver/sHare/Foo'))
1174 self.assertTrue(p.is_relative_to('//sErver/sHare/Foo/'))
1175 self.assertTrue(p.is_relative_to(P('//sErver/sHare/Foo/Bar')))
1176 self.assertTrue(p.is_relative_to('//sErver/sHare/Foo/Bar'))
1177 # Unrelated paths.
1178 self.assertFalse(p.is_relative_to(P('/Server/Share/Foo')))
1179 self.assertFalse(p.is_relative_to(P('c:/Server/Share/Foo')))
1180 self.assertFalse(p.is_relative_to(P('//z/Share/Foo')))
1181 self.assertFalse(p.is_relative_to(P('//Server/z/Foo')))
1182
Antoine Pitrou31119e42013-11-22 17:38:12 +01001183 def test_is_absolute(self):
1184 P = self.cls
Anthony Shaw83da9262019-01-07 07:31:29 +11001185 # Under NT, only paths with both a drive and a root are absolute.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001186 self.assertFalse(P().is_absolute())
1187 self.assertFalse(P('a').is_absolute())
1188 self.assertFalse(P('a/b/').is_absolute())
1189 self.assertFalse(P('/').is_absolute())
1190 self.assertFalse(P('/a').is_absolute())
1191 self.assertFalse(P('/a/b/').is_absolute())
1192 self.assertFalse(P('c:').is_absolute())
1193 self.assertFalse(P('c:a').is_absolute())
1194 self.assertFalse(P('c:a/b/').is_absolute())
1195 self.assertTrue(P('c:/').is_absolute())
1196 self.assertTrue(P('c:/a').is_absolute())
1197 self.assertTrue(P('c:/a/b/').is_absolute())
Anthony Shaw83da9262019-01-07 07:31:29 +11001198 # UNC paths are absolute by definition.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001199 self.assertTrue(P('//a/b').is_absolute())
1200 self.assertTrue(P('//a/b/').is_absolute())
1201 self.assertTrue(P('//a/b/c').is_absolute())
1202 self.assertTrue(P('//a/b/c/d').is_absolute())
1203
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001204 def test_join(self):
1205 P = self.cls
1206 p = P('C:/a/b')
1207 pp = p.joinpath('x/y')
1208 self.assertEqual(pp, P('C:/a/b/x/y'))
1209 pp = p.joinpath('/x/y')
1210 self.assertEqual(pp, P('C:/x/y'))
1211 # Joining with a different drive => the first path is ignored, even
1212 # if the second path is relative.
1213 pp = p.joinpath('D:x/y')
1214 self.assertEqual(pp, P('D:x/y'))
1215 pp = p.joinpath('D:/x/y')
1216 self.assertEqual(pp, P('D:/x/y'))
1217 pp = p.joinpath('//host/share/x/y')
1218 self.assertEqual(pp, P('//host/share/x/y'))
1219 # Joining with the same drive => the first path is appended to if
1220 # the second path is relative.
1221 pp = p.joinpath('c:x/y')
1222 self.assertEqual(pp, P('C:/a/b/x/y'))
1223 pp = p.joinpath('c:/x/y')
1224 self.assertEqual(pp, P('C:/x/y'))
1225
1226 def test_div(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001227 # Basically the same as joinpath().
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001228 P = self.cls
1229 p = P('C:/a/b')
1230 self.assertEqual(p / 'x/y', P('C:/a/b/x/y'))
1231 self.assertEqual(p / 'x' / 'y', P('C:/a/b/x/y'))
1232 self.assertEqual(p / '/x/y', P('C:/x/y'))
1233 self.assertEqual(p / '/x' / 'y', P('C:/x/y'))
1234 # Joining with a different drive => the first path is ignored, even
1235 # if the second path is relative.
1236 self.assertEqual(p / 'D:x/y', P('D:x/y'))
1237 self.assertEqual(p / 'D:' / 'x/y', P('D:x/y'))
1238 self.assertEqual(p / 'D:/x/y', P('D:/x/y'))
1239 self.assertEqual(p / 'D:' / '/x/y', P('D:/x/y'))
1240 self.assertEqual(p / '//host/share/x/y', P('//host/share/x/y'))
1241 # Joining with the same drive => the first path is appended to if
1242 # the second path is relative.
Serhiy Storchaka010ff582013-12-06 17:25:51 +02001243 self.assertEqual(p / 'c:x/y', P('C:/a/b/x/y'))
1244 self.assertEqual(p / 'c:/x/y', P('C:/x/y'))
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001245
Antoine Pitrou31119e42013-11-22 17:38:12 +01001246 def test_is_reserved(self):
1247 P = self.cls
1248 self.assertIs(False, P('').is_reserved())
1249 self.assertIs(False, P('/').is_reserved())
1250 self.assertIs(False, P('/foo/bar').is_reserved())
1251 self.assertIs(True, P('con').is_reserved())
1252 self.assertIs(True, P('NUL').is_reserved())
1253 self.assertIs(True, P('NUL.txt').is_reserved())
1254 self.assertIs(True, P('com1').is_reserved())
1255 self.assertIs(True, P('com9.bar').is_reserved())
1256 self.assertIs(False, P('bar.com9').is_reserved())
1257 self.assertIs(True, P('lpt1').is_reserved())
1258 self.assertIs(True, P('lpt9.bar').is_reserved())
1259 self.assertIs(False, P('bar.lpt9').is_reserved())
Anthony Shaw83da9262019-01-07 07:31:29 +11001260 # Only the last component matters.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001261 self.assertIs(False, P('c:/NUL/con/baz').is_reserved())
Anthony Shaw83da9262019-01-07 07:31:29 +11001262 # UNC paths are never reserved.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001263 self.assertIs(False, P('//my/share/nul/con/aux').is_reserved())
1264
Antoine Pitrou31119e42013-11-22 17:38:12 +01001265class PurePathTest(_BasePurePathTest, unittest.TestCase):
1266 cls = pathlib.PurePath
1267
1268 def test_concrete_class(self):
1269 p = self.cls('a')
1270 self.assertIs(type(p),
1271 pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath)
1272
1273 def test_different_flavours_unequal(self):
1274 p = pathlib.PurePosixPath('a')
1275 q = pathlib.PureWindowsPath('a')
1276 self.assertNotEqual(p, q)
1277
1278 def test_different_flavours_unordered(self):
1279 p = pathlib.PurePosixPath('a')
1280 q = pathlib.PureWindowsPath('a')
1281 with self.assertRaises(TypeError):
1282 p < q
1283 with self.assertRaises(TypeError):
1284 p <= q
1285 with self.assertRaises(TypeError):
1286 p > q
1287 with self.assertRaises(TypeError):
1288 p >= q
1289
1290
1291#
Anthony Shaw83da9262019-01-07 07:31:29 +11001292# Tests for the concrete classes.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001293#
1294
Anthony Shaw83da9262019-01-07 07:31:29 +11001295# Make sure any symbolic links in the base test path are resolved.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001296BASE = os.path.realpath(TESTFN)
1297join = lambda *x: os.path.join(BASE, *x)
1298rel_join = lambda *x: os.path.join(TESTFN, *x)
1299
Antoine Pitrou31119e42013-11-22 17:38:12 +01001300only_nt = unittest.skipIf(os.name != 'nt',
1301 'test requires a Windows-compatible system')
1302only_posix = unittest.skipIf(os.name == 'nt',
1303 'test requires a POSIX-compatible system')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001304
1305@only_posix
1306class PosixPathAsPureTest(PurePosixPathTest):
1307 cls = pathlib.PosixPath
1308
1309@only_nt
1310class WindowsPathAsPureTest(PureWindowsPathTest):
1311 cls = pathlib.WindowsPath
1312
Victor Stinnerd7569632016-03-11 22:53:00 +01001313 def test_owner(self):
1314 P = self.cls
1315 with self.assertRaises(NotImplementedError):
1316 P('c:/').owner()
1317
1318 def test_group(self):
1319 P = self.cls
1320 with self.assertRaises(NotImplementedError):
1321 P('c:/').group()
1322
Antoine Pitrou31119e42013-11-22 17:38:12 +01001323
1324class _BasePathTest(object):
1325 """Tests for the FS-accessing functionalities of the Path classes."""
1326
1327 # (BASE)
1328 # |
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001329 # |-- brokenLink -> non-existing
1330 # |-- dirA
1331 # | `-- linkC -> ../dirB
1332 # |-- dirB
1333 # | |-- fileB
1334 # | `-- linkD -> ../dirB
1335 # |-- dirC
1336 # | |-- dirD
1337 # | | `-- fileD
1338 # | `-- fileC
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001339 # |-- dirE # No permissions
Antoine Pitrou31119e42013-11-22 17:38:12 +01001340 # |-- fileA
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001341 # |-- linkA -> fileA
Jörg Stucked5c120f2019-05-21 19:44:40 +02001342 # |-- linkB -> dirB
1343 # `-- brokenLinkLoop -> brokenLinkLoop
Antoine Pitrou31119e42013-11-22 17:38:12 +01001344 #
1345
1346 def setUp(self):
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001347 def cleanup():
1348 os.chmod(join('dirE'), 0o777)
1349 support.rmtree(BASE)
1350 self.addCleanup(cleanup)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001351 os.mkdir(BASE)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001352 os.mkdir(join('dirA'))
1353 os.mkdir(join('dirB'))
1354 os.mkdir(join('dirC'))
1355 os.mkdir(join('dirC', 'dirD'))
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001356 os.mkdir(join('dirE'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001357 with open(join('fileA'), 'wb') as f:
1358 f.write(b"this is file A\n")
1359 with open(join('dirB', 'fileB'), 'wb') as f:
1360 f.write(b"this is file B\n")
1361 with open(join('dirC', 'fileC'), 'wb') as f:
1362 f.write(b"this is file C\n")
1363 with open(join('dirC', 'dirD', 'fileD'), 'wb') as f:
1364 f.write(b"this is file D\n")
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001365 os.chmod(join('dirE'), 0)
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001366 if support.can_symlink():
Anthony Shaw83da9262019-01-07 07:31:29 +11001367 # Relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001368 os.symlink('fileA', join('linkA'))
1369 os.symlink('non-existing', join('brokenLink'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001370 self.dirlink('dirB', join('linkB'))
1371 self.dirlink(os.path.join('..', 'dirB'), join('dirA', 'linkC'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001372 # This one goes upwards, creating a loop.
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001373 self.dirlink(os.path.join('..', 'dirB'), join('dirB', 'linkD'))
Jörg Stucked5c120f2019-05-21 19:44:40 +02001374 # Broken symlink (pointing to itself).
1375 os.symlink('brokenLinkLoop', join('brokenLinkLoop'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001376
1377 if os.name == 'nt':
Anthony Shaw83da9262019-01-07 07:31:29 +11001378 # Workaround for http://bugs.python.org/issue13772.
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001379 def dirlink(self, src, dest):
1380 os.symlink(src, dest, target_is_directory=True)
1381 else:
1382 def dirlink(self, src, dest):
1383 os.symlink(src, dest)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001384
1385 def assertSame(self, path_a, path_b):
1386 self.assertTrue(os.path.samefile(str(path_a), str(path_b)),
1387 "%r and %r don't point to the same file" %
1388 (path_a, path_b))
1389
1390 def assertFileNotFound(self, func, *args, **kwargs):
1391 with self.assertRaises(FileNotFoundError) as cm:
1392 func(*args, **kwargs)
1393 self.assertEqual(cm.exception.errno, errno.ENOENT)
1394
Steve Dower97d79062019-09-10 14:52:48 +01001395 def assertEqualNormCase(self, path_a, path_b):
1396 self.assertEqual(os.path.normcase(path_a), os.path.normcase(path_b))
1397
Antoine Pitrou31119e42013-11-22 17:38:12 +01001398 def _test_cwd(self, p):
1399 q = self.cls(os.getcwd())
1400 self.assertEqual(p, q)
Steve Dower97d79062019-09-10 14:52:48 +01001401 self.assertEqualNormCase(str(p), str(q))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001402 self.assertIs(type(p), type(q))
1403 self.assertTrue(p.is_absolute())
1404
1405 def test_cwd(self):
1406 p = self.cls.cwd()
1407 self._test_cwd(p)
1408
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001409 def _test_home(self, p):
1410 q = self.cls(os.path.expanduser('~'))
1411 self.assertEqual(p, q)
Steve Dower97d79062019-09-10 14:52:48 +01001412 self.assertEqualNormCase(str(p), str(q))
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001413 self.assertIs(type(p), type(q))
1414 self.assertTrue(p.is_absolute())
1415
1416 def test_home(self):
Christoph Reiterc45a2aa2020-01-28 10:41:50 +01001417 with support.EnvironmentVarGuard() as env:
1418 self._test_home(self.cls.home())
1419
1420 env.clear()
1421 env['USERPROFILE'] = os.path.join(BASE, 'userprofile')
1422 self._test_home(self.cls.home())
1423
1424 # bpo-38883: ignore `HOME` when set on windows
1425 env['HOME'] = os.path.join(BASE, 'home')
1426 self._test_home(self.cls.home())
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001427
Antoine Pitrou43e3d942014-05-13 10:50:15 +02001428 def test_samefile(self):
1429 fileA_path = os.path.join(BASE, 'fileA')
1430 fileB_path = os.path.join(BASE, 'dirB', 'fileB')
1431 p = self.cls(fileA_path)
1432 pp = self.cls(fileA_path)
1433 q = self.cls(fileB_path)
1434 self.assertTrue(p.samefile(fileA_path))
1435 self.assertTrue(p.samefile(pp))
1436 self.assertFalse(p.samefile(fileB_path))
1437 self.assertFalse(p.samefile(q))
1438 # Test the non-existent file case
1439 non_existent = os.path.join(BASE, 'foo')
1440 r = self.cls(non_existent)
1441 self.assertRaises(FileNotFoundError, p.samefile, r)
1442 self.assertRaises(FileNotFoundError, p.samefile, non_existent)
1443 self.assertRaises(FileNotFoundError, r.samefile, p)
1444 self.assertRaises(FileNotFoundError, r.samefile, non_existent)
1445 self.assertRaises(FileNotFoundError, r.samefile, r)
1446 self.assertRaises(FileNotFoundError, r.samefile, non_existent)
1447
Antoine Pitrou31119e42013-11-22 17:38:12 +01001448 def test_empty_path(self):
1449 # The empty path points to '.'
1450 p = self.cls('')
1451 self.assertEqual(p.stat(), os.stat('.'))
1452
Antoine Pitrou8477ed62014-12-30 20:54:45 +01001453 def test_expanduser_common(self):
1454 P = self.cls
1455 p = P('~')
1456 self.assertEqual(p.expanduser(), P(os.path.expanduser('~')))
1457 p = P('foo')
1458 self.assertEqual(p.expanduser(), p)
1459 p = P('/~')
1460 self.assertEqual(p.expanduser(), p)
1461 p = P('../~')
1462 self.assertEqual(p.expanduser(), p)
1463 p = P(P('').absolute().anchor) / '~'
1464 self.assertEqual(p.expanduser(), p)
1465
Antoine Pitrou31119e42013-11-22 17:38:12 +01001466 def test_exists(self):
1467 P = self.cls
1468 p = P(BASE)
1469 self.assertIs(True, p.exists())
1470 self.assertIs(True, (p / 'dirA').exists())
1471 self.assertIs(True, (p / 'fileA').exists())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001472 self.assertIs(False, (p / 'fileA' / 'bah').exists())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001473 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001474 self.assertIs(True, (p / 'linkA').exists())
1475 self.assertIs(True, (p / 'linkB').exists())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001476 self.assertIs(True, (p / 'linkB' / 'fileB').exists())
1477 self.assertIs(False, (p / 'linkA' / 'bah').exists())
Antoine Pitrou31119e42013-11-22 17:38:12 +01001478 self.assertIs(False, (p / 'foo').exists())
1479 self.assertIs(False, P('/xyzzy').exists())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001480 self.assertIs(False, P(BASE + '\udfff').exists())
1481 self.assertIs(False, P(BASE + '\x00').exists())
Antoine Pitrou31119e42013-11-22 17:38:12 +01001482
1483 def test_open_common(self):
1484 p = self.cls(BASE)
1485 with (p / 'fileA').open('r') as f:
1486 self.assertIsInstance(f, io.TextIOBase)
1487 self.assertEqual(f.read(), "this is file A\n")
1488 with (p / 'fileA').open('rb') as f:
1489 self.assertIsInstance(f, io.BufferedIOBase)
1490 self.assertEqual(f.read().strip(), b"this is file A")
1491 with (p / 'fileA').open('rb', buffering=0) as f:
1492 self.assertIsInstance(f, io.RawIOBase)
1493 self.assertEqual(f.read().strip(), b"this is file A")
1494
Georg Brandlea683982014-10-01 19:12:33 +02001495 def test_read_write_bytes(self):
1496 p = self.cls(BASE)
1497 (p / 'fileA').write_bytes(b'abcdefg')
1498 self.assertEqual((p / 'fileA').read_bytes(), b'abcdefg')
Anthony Shaw83da9262019-01-07 07:31:29 +11001499 # Check that trying to write str does not truncate the file.
Georg Brandlea683982014-10-01 19:12:33 +02001500 self.assertRaises(TypeError, (p / 'fileA').write_bytes, 'somestr')
1501 self.assertEqual((p / 'fileA').read_bytes(), b'abcdefg')
1502
1503 def test_read_write_text(self):
1504 p = self.cls(BASE)
1505 (p / 'fileA').write_text('äbcdefg', encoding='latin-1')
1506 self.assertEqual((p / 'fileA').read_text(
1507 encoding='utf-8', errors='ignore'), 'bcdefg')
Anthony Shaw83da9262019-01-07 07:31:29 +11001508 # Check that trying to write bytes does not truncate the file.
Georg Brandlea683982014-10-01 19:12:33 +02001509 self.assertRaises(TypeError, (p / 'fileA').write_text, b'somebytes')
1510 self.assertEqual((p / 'fileA').read_text(encoding='latin-1'), 'äbcdefg')
1511
Antoine Pitrou31119e42013-11-22 17:38:12 +01001512 def test_iterdir(self):
1513 P = self.cls
1514 p = P(BASE)
1515 it = p.iterdir()
1516 paths = set(it)
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001517 expected = ['dirA', 'dirB', 'dirC', 'dirE', 'fileA']
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001518 if support.can_symlink():
Jörg Stucked5c120f2019-05-21 19:44:40 +02001519 expected += ['linkA', 'linkB', 'brokenLink', 'brokenLinkLoop']
Antoine Pitrou31119e42013-11-22 17:38:12 +01001520 self.assertEqual(paths, { P(BASE, q) for q in expected })
1521
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001522 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001523 def test_iterdir_symlink(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001524 # __iter__ on a symlink to a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001525 P = self.cls
1526 p = P(BASE, 'linkB')
1527 paths = set(p.iterdir())
1528 expected = { P(BASE, 'linkB', q) for q in ['fileB', 'linkD'] }
1529 self.assertEqual(paths, expected)
1530
1531 def test_iterdir_nodir(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001532 # __iter__ on something that is not a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001533 p = self.cls(BASE, 'fileA')
1534 with self.assertRaises(OSError) as cm:
1535 next(p.iterdir())
1536 # ENOENT or EINVAL under Windows, ENOTDIR otherwise
Anthony Shaw83da9262019-01-07 07:31:29 +11001537 # (see issue #12802).
Antoine Pitrou31119e42013-11-22 17:38:12 +01001538 self.assertIn(cm.exception.errno, (errno.ENOTDIR,
1539 errno.ENOENT, errno.EINVAL))
1540
1541 def test_glob_common(self):
1542 def _check(glob, expected):
1543 self.assertEqual(set(glob), { P(BASE, q) for q in expected })
1544 P = self.cls
1545 p = P(BASE)
1546 it = p.glob("fileA")
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001547 self.assertIsInstance(it, collections.abc.Iterator)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001548 _check(it, ["fileA"])
1549 _check(p.glob("fileB"), [])
1550 _check(p.glob("dir*/file*"), ["dirB/fileB", "dirC/fileC"])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001551 if not support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001552 _check(p.glob("*A"), ['dirA', 'fileA'])
1553 else:
1554 _check(p.glob("*A"), ['dirA', 'fileA', 'linkA'])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001555 if not support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001556 _check(p.glob("*B/*"), ['dirB/fileB'])
1557 else:
1558 _check(p.glob("*B/*"), ['dirB/fileB', 'dirB/linkD',
1559 'linkB/fileB', 'linkB/linkD'])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001560 if not support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001561 _check(p.glob("*/fileB"), ['dirB/fileB'])
1562 else:
1563 _check(p.glob("*/fileB"), ['dirB/fileB', 'linkB/fileB'])
1564
1565 def test_rglob_common(self):
1566 def _check(glob, expected):
1567 self.assertEqual(set(glob), { P(BASE, q) for q in expected })
1568 P = self.cls
1569 p = P(BASE)
1570 it = p.rglob("fileA")
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001571 self.assertIsInstance(it, collections.abc.Iterator)
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001572 _check(it, ["fileA"])
1573 _check(p.rglob("fileB"), ["dirB/fileB"])
1574 _check(p.rglob("*/fileA"), [])
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001575 if not support.can_symlink():
Guido van Rossum9c39b672016-01-07 13:12:34 -08001576 _check(p.rglob("*/fileB"), ["dirB/fileB"])
1577 else:
1578 _check(p.rglob("*/fileB"), ["dirB/fileB", "dirB/linkD/fileB",
1579 "linkB/fileB", "dirA/linkC/fileB"])
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001580 _check(p.rglob("file*"), ["fileA", "dirB/fileB",
1581 "dirC/fileC", "dirC/dirD/fileD"])
Antoine Pitrou31119e42013-11-22 17:38:12 +01001582 p = P(BASE, "dirC")
1583 _check(p.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"])
1584 _check(p.rglob("*/*"), ["dirC/dirD/fileD"])
1585
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001586 @support.skip_unless_symlink
Guido van Rossum69bfb152016-01-06 10:31:33 -08001587 def test_rglob_symlink_loop(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001588 # Don't get fooled by symlink loops (Issue #26012).
Guido van Rossum69bfb152016-01-06 10:31:33 -08001589 P = self.cls
1590 p = P(BASE)
1591 given = set(p.rglob('*'))
1592 expect = {'brokenLink',
1593 'dirA', 'dirA/linkC',
1594 'dirB', 'dirB/fileB', 'dirB/linkD',
1595 'dirC', 'dirC/dirD', 'dirC/dirD/fileD', 'dirC/fileC',
1596 'dirE',
1597 'fileA',
1598 'linkA',
1599 'linkB',
Jörg Stucked5c120f2019-05-21 19:44:40 +02001600 'brokenLinkLoop',
Guido van Rossum69bfb152016-01-06 10:31:33 -08001601 }
1602 self.assertEqual(given, {p / x for x in expect})
1603
Serhiy Storchakaf9dc2ad2019-09-12 15:54:48 +03001604 def test_glob_many_open_files(self):
1605 depth = 30
1606 P = self.cls
1607 base = P(BASE) / 'deep'
1608 p = P(base, *(['d']*depth))
1609 p.mkdir(parents=True)
1610 pattern = '/'.join(['*'] * depth)
1611 iters = [base.glob(pattern) for j in range(100)]
1612 for it in iters:
1613 self.assertEqual(next(it), p)
1614 iters = [base.rglob('d') for j in range(100)]
1615 p = base
1616 for i in range(depth):
1617 p = p / 'd'
1618 for it in iters:
1619 self.assertEqual(next(it), p)
1620
Antoine Pitrou31119e42013-11-22 17:38:12 +01001621 def test_glob_dotdot(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001622 # ".." is not special in globs.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001623 P = self.cls
1624 p = P(BASE)
1625 self.assertEqual(set(p.glob("..")), { P(BASE, "..") })
1626 self.assertEqual(set(p.glob("dirA/../file*")), { P(BASE, "dirA/../fileA") })
1627 self.assertEqual(set(p.glob("../xyzzy")), set())
1628
Pablo Galindoeb7560a2020-03-07 17:53:20 +00001629 @support.skip_unless_symlink
1630 def test_glob_permissions(self):
1631 # See bpo-38894
1632 P = self.cls
1633 base = P(BASE) / 'permissions'
1634 base.mkdir()
1635
1636 file1 = base / "file1"
1637 file1.touch()
1638 file2 = base / "file2"
1639 file2.touch()
1640
1641 subdir = base / "subdir"
1642
1643 file3 = base / "file3"
1644 file3.symlink_to(subdir / "other")
1645
1646 # Patching is needed to avoid relying on the filesystem
1647 # to return the order of the files as the error will not
1648 # happen if the symlink is the last item.
1649
1650 with mock.patch("os.scandir") as scandir:
1651 scandir.return_value = sorted(os.scandir(base))
1652 self.assertEqual(len(set(base.glob("*"))), 3)
1653
1654 subdir.mkdir()
1655
1656 with mock.patch("os.scandir") as scandir:
1657 scandir.return_value = sorted(os.scandir(base))
1658 self.assertEqual(len(set(base.glob("*"))), 4)
1659
1660 subdir.chmod(000)
1661
1662 with mock.patch("os.scandir") as scandir:
1663 scandir.return_value = sorted(os.scandir(base))
1664 self.assertEqual(len(set(base.glob("*"))), 4)
Ezio Melottiac1e7f62015-12-28 23:50:19 +02001665
Steve Dower98eb3602016-11-09 12:58:17 -08001666 def _check_resolve(self, p, expected, strict=True):
1667 q = p.resolve(strict)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001668 self.assertEqual(q, expected)
1669
Anthony Shaw83da9262019-01-07 07:31:29 +11001670 # This can be used to check both relative and absolute resolutions.
Ezio Melottiac1e7f62015-12-28 23:50:19 +02001671 _check_resolve_relative = _check_resolve_absolute = _check_resolve
Antoine Pitrou31119e42013-11-22 17:38:12 +01001672
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001673 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001674 def test_resolve_common(self):
1675 P = self.cls
1676 p = P(BASE, 'foo')
1677 with self.assertRaises(OSError) as cm:
Steve Dower98eb3602016-11-09 12:58:17 -08001678 p.resolve(strict=True)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001679 self.assertEqual(cm.exception.errno, errno.ENOENT)
Steve Dower98eb3602016-11-09 12:58:17 -08001680 # Non-strict
Steve Dower97d79062019-09-10 14:52:48 +01001681 self.assertEqualNormCase(str(p.resolve(strict=False)),
1682 os.path.join(BASE, 'foo'))
Steve Dower98eb3602016-11-09 12:58:17 -08001683 p = P(BASE, 'foo', 'in', 'spam')
Steve Dower97d79062019-09-10 14:52:48 +01001684 self.assertEqualNormCase(str(p.resolve(strict=False)),
1685 os.path.join(BASE, 'foo', 'in', 'spam'))
Steve Dower98eb3602016-11-09 12:58:17 -08001686 p = P(BASE, '..', 'foo', 'in', 'spam')
Steve Dower97d79062019-09-10 14:52:48 +01001687 self.assertEqualNormCase(str(p.resolve(strict=False)),
1688 os.path.abspath(os.path.join('foo', 'in', 'spam')))
Anthony Shaw83da9262019-01-07 07:31:29 +11001689 # These are all relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001690 p = P(BASE, 'dirB', 'fileB')
1691 self._check_resolve_relative(p, p)
1692 p = P(BASE, 'linkA')
1693 self._check_resolve_relative(p, P(BASE, 'fileA'))
1694 p = P(BASE, 'dirA', 'linkC', 'fileB')
1695 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB'))
1696 p = P(BASE, 'dirB', 'linkD', 'fileB')
1697 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB'))
Steve Dower98eb3602016-11-09 12:58:17 -08001698 # Non-strict
1699 p = P(BASE, 'dirA', 'linkC', 'fileB', 'foo', 'in', 'spam')
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001700 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB', 'foo', 'in',
1701 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001702 p = P(BASE, 'dirA', 'linkC', '..', 'foo', 'in', 'spam')
1703 if os.name == 'nt':
1704 # In Windows, if linkY points to dirB, 'dirA\linkY\..'
1705 # resolves to 'dirA' without resolving linkY first.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001706 self._check_resolve_relative(p, P(BASE, 'dirA', 'foo', 'in',
1707 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001708 else:
1709 # In Posix, if linkY points to dirB, 'dirA/linkY/..'
1710 # resolves to 'dirB/..' first before resolving to parent of dirB.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001711 self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
Anthony Shaw83da9262019-01-07 07:31:29 +11001712 # Now create absolute symlinks.
Steve Dower0cd63912018-12-10 18:52:57 -08001713 d = support._longpath(tempfile.mkdtemp(suffix='-dirD', dir=os.getcwd()))
Victor Stinnerec864692014-07-21 19:19:05 +02001714 self.addCleanup(support.rmtree, d)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001715 os.symlink(os.path.join(d), join('dirA', 'linkX'))
1716 os.symlink(join('dirB'), os.path.join(d, 'linkY'))
1717 p = P(BASE, 'dirA', 'linkX', 'linkY', 'fileB')
1718 self._check_resolve_absolute(p, P(BASE, 'dirB', 'fileB'))
Steve Dower98eb3602016-11-09 12:58:17 -08001719 # Non-strict
1720 p = P(BASE, 'dirA', 'linkX', 'linkY', 'foo', 'in', 'spam')
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001721 self._check_resolve_relative(p, P(BASE, 'dirB', 'foo', 'in', 'spam'),
1722 False)
Steve Dower98eb3602016-11-09 12:58:17 -08001723 p = P(BASE, 'dirA', 'linkX', 'linkY', '..', 'foo', 'in', 'spam')
1724 if os.name == 'nt':
1725 # In Windows, if linkY points to dirB, 'dirA\linkY\..'
1726 # resolves to 'dirA' without resolving linkY first.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001727 self._check_resolve_relative(p, P(d, 'foo', 'in', 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001728 else:
1729 # In Posix, if linkY points to dirB, 'dirA/linkY/..'
1730 # resolves to 'dirB/..' first before resolving to parent of dirB.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001731 self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001732
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001733 @support.skip_unless_symlink
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001734 def test_resolve_dot(self):
1735 # See https://bitbucket.org/pitrou/pathlib/issue/9/pathresolve-fails-on-complex-symlinks
1736 p = self.cls(BASE)
1737 self.dirlink('.', join('0'))
Antoine Pitroucc157512013-12-03 17:13:13 +01001738 self.dirlink(os.path.join('0', '0'), join('1'))
1739 self.dirlink(os.path.join('1', '1'), join('2'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001740 q = p / '2'
Steve Dower98eb3602016-11-09 12:58:17 -08001741 self.assertEqual(q.resolve(strict=True), p)
1742 r = q / '3' / '4'
1743 self.assertRaises(FileNotFoundError, r.resolve, strict=True)
1744 # Non-strict
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001745 self.assertEqual(r.resolve(strict=False), p / '3' / '4')
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001746
Antoine Pitrou31119e42013-11-22 17:38:12 +01001747 def test_with(self):
1748 p = self.cls(BASE)
1749 it = p.iterdir()
1750 it2 = p.iterdir()
1751 next(it2)
1752 with p:
1753 pass
Barney Gale00002e62020-04-01 15:10:51 +01001754 # Using a path as a context manager is a no-op, thus the following
1755 # operations should still succeed after the context manage exits.
1756 next(it)
1757 next(it2)
1758 p.exists()
1759 p.resolve()
1760 p.absolute()
1761 with p:
1762 pass
Antoine Pitrou31119e42013-11-22 17:38:12 +01001763
1764 def test_chmod(self):
1765 p = self.cls(BASE) / 'fileA'
1766 mode = p.stat().st_mode
Anthony Shaw83da9262019-01-07 07:31:29 +11001767 # Clear writable bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001768 new_mode = mode & ~0o222
1769 p.chmod(new_mode)
1770 self.assertEqual(p.stat().st_mode, new_mode)
Anthony Shaw83da9262019-01-07 07:31:29 +11001771 # Set writable bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001772 new_mode = mode | 0o222
1773 p.chmod(new_mode)
1774 self.assertEqual(p.stat().st_mode, new_mode)
1775
Anthony Shaw83da9262019-01-07 07:31:29 +11001776 # XXX also need a test for lchmod.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001777
1778 def test_stat(self):
1779 p = self.cls(BASE) / 'fileA'
1780 st = p.stat()
1781 self.assertEqual(p.stat(), st)
Anthony Shaw83da9262019-01-07 07:31:29 +11001782 # Change file mode by flipping write bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001783 p.chmod(st.st_mode ^ 0o222)
1784 self.addCleanup(p.chmod, st.st_mode)
1785 self.assertNotEqual(p.stat(), st)
1786
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07001787 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001788 def test_lstat(self):
1789 p = self.cls(BASE)/ 'linkA'
1790 st = p.stat()
1791 self.assertNotEqual(st, p.lstat())
1792
1793 def test_lstat_nosymlink(self):
1794 p = self.cls(BASE) / 'fileA'
1795 st = p.stat()
1796 self.assertEqual(st, p.lstat())
1797
1798 @unittest.skipUnless(pwd, "the pwd module is needed for this test")
1799 def test_owner(self):
1800 p = self.cls(BASE) / 'fileA'
1801 uid = p.stat().st_uid
Antoine Pitrou2cf4b0f2013-11-25 19:51:53 +01001802 try:
1803 name = pwd.getpwuid(uid).pw_name
1804 except KeyError:
1805 self.skipTest(
1806 "user %d doesn't have an entry in the system database" % uid)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001807 self.assertEqual(name, p.owner())
1808
1809 @unittest.skipUnless(grp, "the grp module is needed for this test")
1810 def test_group(self):
1811 p = self.cls(BASE) / 'fileA'
1812 gid = p.stat().st_gid
Antoine Pitrou2cf4b0f2013-11-25 19:51:53 +01001813 try:
1814 name = grp.getgrgid(gid).gr_name
1815 except KeyError:
1816 self.skipTest(
1817 "group %d doesn't have an entry in the system database" % gid)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001818 self.assertEqual(name, p.group())
1819
1820 def test_unlink(self):
1821 p = self.cls(BASE) / 'fileA'
1822 p.unlink()
1823 self.assertFileNotFound(p.stat)
1824 self.assertFileNotFound(p.unlink)
1825
‮zlohhcuB treboRd9e006b2019-05-16 00:02:11 +02001826 def test_unlink_missing_ok(self):
1827 p = self.cls(BASE) / 'fileAAA'
1828 self.assertFileNotFound(p.unlink)
1829 p.unlink(missing_ok=True)
1830
Antoine Pitrou31119e42013-11-22 17:38:12 +01001831 def test_rmdir(self):
1832 p = self.cls(BASE) / 'dirA'
1833 for q in p.iterdir():
1834 q.unlink()
1835 p.rmdir()
1836 self.assertFileNotFound(p.stat)
1837 self.assertFileNotFound(p.unlink)
1838
Toke Høiland-Jørgensen092435e2019-12-16 13:23:55 +01001839 @unittest.skipUnless(hasattr(os, "link"), "os.link() is not present")
Joannah Nanjekye6b5b0132019-05-04 11:27:10 -04001840 def test_link_to(self):
1841 P = self.cls(BASE)
1842 p = P / 'fileA'
1843 size = p.stat().st_size
1844 # linking to another path.
1845 q = P / 'dirA' / 'fileAA'
1846 try:
1847 p.link_to(q)
1848 except PermissionError as e:
1849 self.skipTest('os.link(): %s' % e)
1850 self.assertEqual(q.stat().st_size, size)
1851 self.assertEqual(os.path.samefile(p, q), True)
1852 self.assertTrue(p.stat)
1853 # Linking to a str of a relative path.
1854 r = rel_join('fileAAA')
1855 q.link_to(r)
1856 self.assertEqual(os.stat(r).st_size, size)
1857 self.assertTrue(q.stat)
1858
Toke Høiland-Jørgensen092435e2019-12-16 13:23:55 +01001859 @unittest.skipIf(hasattr(os, "link"), "os.link() is present")
1860 def test_link_to_not_implemented(self):
1861 P = self.cls(BASE)
1862 p = P / 'fileA'
1863 # linking to another path.
1864 q = P / 'dirA' / 'fileAA'
1865 with self.assertRaises(NotImplementedError):
1866 p.link_to(q)
1867
Antoine Pitrou31119e42013-11-22 17:38:12 +01001868 def test_rename(self):
1869 P = self.cls(BASE)
1870 p = P / 'fileA'
1871 size = p.stat().st_size
Anthony Shaw83da9262019-01-07 07:31:29 +11001872 # Renaming to another path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001873 q = P / 'dirA' / 'fileAA'
hui shang088a09a2019-09-11 21:26:49 +08001874 renamed_p = p.rename(q)
1875 self.assertEqual(renamed_p, q)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001876 self.assertEqual(q.stat().st_size, size)
1877 self.assertFileNotFound(p.stat)
Anthony Shaw83da9262019-01-07 07:31:29 +11001878 # Renaming to a str of a relative path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001879 r = rel_join('fileAAA')
hui shang088a09a2019-09-11 21:26:49 +08001880 renamed_q = q.rename(r)
1881 self.assertEqual(renamed_q, self.cls(r))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001882 self.assertEqual(os.stat(r).st_size, size)
1883 self.assertFileNotFound(q.stat)
1884
1885 def test_replace(self):
1886 P = self.cls(BASE)
1887 p = P / 'fileA'
1888 size = p.stat().st_size
Anthony Shaw83da9262019-01-07 07:31:29 +11001889 # Replacing a non-existing path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001890 q = P / 'dirA' / 'fileAA'
hui shang088a09a2019-09-11 21:26:49 +08001891 replaced_p = p.replace(q)
1892 self.assertEqual(replaced_p, q)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001893 self.assertEqual(q.stat().st_size, size)
1894 self.assertFileNotFound(p.stat)
Anthony Shaw83da9262019-01-07 07:31:29 +11001895 # Replacing another (existing) path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001896 r = rel_join('dirB', 'fileB')
hui shang088a09a2019-09-11 21:26:49 +08001897 replaced_q = q.replace(r)
1898 self.assertEqual(replaced_q, self.cls(r))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001899 self.assertEqual(os.stat(r).st_size, size)
1900 self.assertFileNotFound(q.stat)
1901
Girtsa01ba332019-10-23 14:18:40 -07001902 @support.skip_unless_symlink
1903 def test_readlink(self):
1904 P = self.cls(BASE)
1905 self.assertEqual((P / 'linkA').readlink(), self.cls('fileA'))
1906 self.assertEqual((P / 'brokenLink').readlink(),
1907 self.cls('non-existing'))
1908 self.assertEqual((P / 'linkB').readlink(), self.cls('dirB'))
1909 with self.assertRaises(OSError):
1910 (P / 'fileA').readlink()
1911
Antoine Pitrou31119e42013-11-22 17:38:12 +01001912 def test_touch_common(self):
1913 P = self.cls(BASE)
1914 p = P / 'newfileA'
1915 self.assertFalse(p.exists())
1916 p.touch()
1917 self.assertTrue(p.exists())
Antoine Pitrou0f575642013-11-22 23:20:08 +01001918 st = p.stat()
1919 old_mtime = st.st_mtime
1920 old_mtime_ns = st.st_mtime_ns
Antoine Pitrou31119e42013-11-22 17:38:12 +01001921 # Rewind the mtime sufficiently far in the past to work around
1922 # filesystem-specific timestamp granularity.
1923 os.utime(str(p), (old_mtime - 10, old_mtime - 10))
Anthony Shaw83da9262019-01-07 07:31:29 +11001924 # The file mtime should be refreshed by calling touch() again.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001925 p.touch()
Antoine Pitrou0f575642013-11-22 23:20:08 +01001926 st = p.stat()
Antoine Pitrou2cf39172013-11-23 15:25:59 +01001927 self.assertGreaterEqual(st.st_mtime_ns, old_mtime_ns)
1928 self.assertGreaterEqual(st.st_mtime, old_mtime)
Anthony Shaw83da9262019-01-07 07:31:29 +11001929 # Now with exist_ok=False.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001930 p = P / 'newfileB'
1931 self.assertFalse(p.exists())
1932 p.touch(mode=0o700, exist_ok=False)
1933 self.assertTrue(p.exists())
1934 self.assertRaises(OSError, p.touch, exist_ok=False)
1935
Antoine Pitrou8b784932013-11-23 14:52:39 +01001936 def test_touch_nochange(self):
1937 P = self.cls(BASE)
1938 p = P / 'fileA'
1939 p.touch()
1940 with p.open('rb') as f:
1941 self.assertEqual(f.read().strip(), b"this is file A")
1942
Antoine Pitrou31119e42013-11-22 17:38:12 +01001943 def test_mkdir(self):
1944 P = self.cls(BASE)
1945 p = P / 'newdirA'
1946 self.assertFalse(p.exists())
1947 p.mkdir()
1948 self.assertTrue(p.exists())
1949 self.assertTrue(p.is_dir())
1950 with self.assertRaises(OSError) as cm:
1951 p.mkdir()
1952 self.assertEqual(cm.exception.errno, errno.EEXIST)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001953
1954 def test_mkdir_parents(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001955 # Creating a chain of directories.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001956 p = self.cls(BASE, 'newdirB', 'newdirC')
1957 self.assertFalse(p.exists())
1958 with self.assertRaises(OSError) as cm:
1959 p.mkdir()
1960 self.assertEqual(cm.exception.errno, errno.ENOENT)
1961 p.mkdir(parents=True)
1962 self.assertTrue(p.exists())
1963 self.assertTrue(p.is_dir())
1964 with self.assertRaises(OSError) as cm:
1965 p.mkdir(parents=True)
1966 self.assertEqual(cm.exception.errno, errno.EEXIST)
Anthony Shaw83da9262019-01-07 07:31:29 +11001967 # Test `mode` arg.
1968 mode = stat.S_IMODE(p.stat().st_mode) # Default mode.
Antoine Pitrou0048c982013-12-16 20:22:37 +01001969 p = self.cls(BASE, 'newdirD', 'newdirE')
1970 p.mkdir(0o555, parents=True)
1971 self.assertTrue(p.exists())
1972 self.assertTrue(p.is_dir())
1973 if os.name != 'nt':
Anthony Shaw83da9262019-01-07 07:31:29 +11001974 # The directory's permissions follow the mode argument.
Gregory P. Smithb599c612014-01-20 01:10:33 -08001975 self.assertEqual(stat.S_IMODE(p.stat().st_mode), 0o7555 & mode)
Anthony Shaw83da9262019-01-07 07:31:29 +11001976 # The parent's permissions follow the default process settings.
Antoine Pitrou0048c982013-12-16 20:22:37 +01001977 self.assertEqual(stat.S_IMODE(p.parent.stat().st_mode), mode)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001978
Barry Warsaw7c549c42014-08-05 11:28:12 -04001979 def test_mkdir_exist_ok(self):
1980 p = self.cls(BASE, 'dirB')
1981 st_ctime_first = p.stat().st_ctime
1982 self.assertTrue(p.exists())
1983 self.assertTrue(p.is_dir())
1984 with self.assertRaises(FileExistsError) as cm:
1985 p.mkdir()
1986 self.assertEqual(cm.exception.errno, errno.EEXIST)
1987 p.mkdir(exist_ok=True)
1988 self.assertTrue(p.exists())
1989 self.assertEqual(p.stat().st_ctime, st_ctime_first)
1990
1991 def test_mkdir_exist_ok_with_parent(self):
1992 p = self.cls(BASE, 'dirC')
1993 self.assertTrue(p.exists())
1994 with self.assertRaises(FileExistsError) as cm:
1995 p.mkdir()
1996 self.assertEqual(cm.exception.errno, errno.EEXIST)
1997 p = p / 'newdirC'
1998 p.mkdir(parents=True)
1999 st_ctime_first = p.stat().st_ctime
2000 self.assertTrue(p.exists())
2001 with self.assertRaises(FileExistsError) as cm:
2002 p.mkdir(parents=True)
2003 self.assertEqual(cm.exception.errno, errno.EEXIST)
2004 p.mkdir(parents=True, exist_ok=True)
2005 self.assertTrue(p.exists())
2006 self.assertEqual(p.stat().st_ctime, st_ctime_first)
2007
Serhiy Storchakaaf7b9ec2017-03-24 20:51:53 +02002008 def test_mkdir_exist_ok_root(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002009 # Issue #25803: A drive root could raise PermissionError on Windows.
Serhiy Storchakaaf7b9ec2017-03-24 20:51:53 +02002010 self.cls('/').resolve().mkdir(exist_ok=True)
2011 self.cls('/').resolve().mkdir(parents=True, exist_ok=True)
2012
Anthony Shaw83da9262019-01-07 07:31:29 +11002013 @only_nt # XXX: not sure how to test this on POSIX.
Steve Dowerd3c48532017-02-04 14:54:56 -08002014 def test_mkdir_with_unknown_drive(self):
2015 for d in 'ZYXWVUTSRQPONMLKJIHGFEDCBA':
2016 p = self.cls(d + ':\\')
2017 if not p.is_dir():
2018 break
2019 else:
2020 self.skipTest("cannot find a drive that doesn't exist")
2021 with self.assertRaises(OSError):
2022 (p / 'child' / 'path').mkdir(parents=True)
2023
Barry Warsaw7c549c42014-08-05 11:28:12 -04002024 def test_mkdir_with_child_file(self):
2025 p = self.cls(BASE, 'dirB', 'fileB')
2026 self.assertTrue(p.exists())
2027 # An exception is raised when the last path component is an existing
2028 # regular file, regardless of whether exist_ok is true or not.
2029 with self.assertRaises(FileExistsError) as cm:
2030 p.mkdir(parents=True)
2031 self.assertEqual(cm.exception.errno, errno.EEXIST)
2032 with self.assertRaises(FileExistsError) as cm:
2033 p.mkdir(parents=True, exist_ok=True)
2034 self.assertEqual(cm.exception.errno, errno.EEXIST)
2035
2036 def test_mkdir_no_parents_file(self):
2037 p = self.cls(BASE, 'fileA')
2038 self.assertTrue(p.exists())
2039 # An exception is raised when the last path component is an existing
2040 # regular file, regardless of whether exist_ok is true or not.
2041 with self.assertRaises(FileExistsError) as cm:
2042 p.mkdir()
2043 self.assertEqual(cm.exception.errno, errno.EEXIST)
2044 with self.assertRaises(FileExistsError) as cm:
2045 p.mkdir(exist_ok=True)
2046 self.assertEqual(cm.exception.errno, errno.EEXIST)
2047
Armin Rigo22a594a2017-04-13 20:08:15 +02002048 def test_mkdir_concurrent_parent_creation(self):
2049 for pattern_num in range(32):
2050 p = self.cls(BASE, 'dirCPC%d' % pattern_num)
2051 self.assertFalse(p.exists())
2052
2053 def my_mkdir(path, mode=0o777):
2054 path = str(path)
2055 # Emulate another process that would create the directory
2056 # just before we try to create it ourselves. We do it
2057 # in all possible pattern combinations, assuming that this
2058 # function is called at most 5 times (dirCPC/dir1/dir2,
2059 # dirCPC/dir1, dirCPC, dirCPC/dir1, dirCPC/dir1/dir2).
2060 if pattern.pop():
Anthony Shaw83da9262019-01-07 07:31:29 +11002061 os.mkdir(path, mode) # From another process.
Armin Rigo22a594a2017-04-13 20:08:15 +02002062 concurrently_created.add(path)
Anthony Shaw83da9262019-01-07 07:31:29 +11002063 os.mkdir(path, mode) # Our real call.
Armin Rigo22a594a2017-04-13 20:08:15 +02002064
2065 pattern = [bool(pattern_num & (1 << n)) for n in range(5)]
2066 concurrently_created = set()
2067 p12 = p / 'dir1' / 'dir2'
2068 try:
2069 with mock.patch("pathlib._normal_accessor.mkdir", my_mkdir):
2070 p12.mkdir(parents=True, exist_ok=False)
2071 except FileExistsError:
2072 self.assertIn(str(p12), concurrently_created)
2073 else:
2074 self.assertNotIn(str(p12), concurrently_created)
2075 self.assertTrue(p.exists())
2076
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002077 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01002078 def test_symlink_to(self):
2079 P = self.cls(BASE)
2080 target = P / 'fileA'
Anthony Shaw83da9262019-01-07 07:31:29 +11002081 # Symlinking a path target.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002082 link = P / 'dirA' / 'linkAA'
2083 link.symlink_to(target)
2084 self.assertEqual(link.stat(), target.stat())
2085 self.assertNotEqual(link.lstat(), target.stat())
Anthony Shaw83da9262019-01-07 07:31:29 +11002086 # Symlinking a str target.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002087 link = P / 'dirA' / 'linkAAA'
2088 link.symlink_to(str(target))
2089 self.assertEqual(link.stat(), target.stat())
2090 self.assertNotEqual(link.lstat(), target.stat())
2091 self.assertFalse(link.is_dir())
Anthony Shaw83da9262019-01-07 07:31:29 +11002092 # Symlinking to a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002093 target = P / 'dirB'
2094 link = P / 'dirA' / 'linkAAAA'
2095 link.symlink_to(target, target_is_directory=True)
2096 self.assertEqual(link.stat(), target.stat())
2097 self.assertNotEqual(link.lstat(), target.stat())
2098 self.assertTrue(link.is_dir())
2099 self.assertTrue(list(link.iterdir()))
2100
2101 def test_is_dir(self):
2102 P = self.cls(BASE)
2103 self.assertTrue((P / 'dirA').is_dir())
2104 self.assertFalse((P / 'fileA').is_dir())
2105 self.assertFalse((P / 'non-existing').is_dir())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002106 self.assertFalse((P / 'fileA' / 'bah').is_dir())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002107 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01002108 self.assertFalse((P / 'linkA').is_dir())
2109 self.assertTrue((P / 'linkB').is_dir())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002110 self.assertFalse((P/ 'brokenLink').is_dir(), False)
2111 self.assertIs((P / 'dirA\udfff').is_dir(), False)
2112 self.assertIs((P / 'dirA\x00').is_dir(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002113
2114 def test_is_file(self):
2115 P = self.cls(BASE)
2116 self.assertTrue((P / 'fileA').is_file())
2117 self.assertFalse((P / 'dirA').is_file())
2118 self.assertFalse((P / 'non-existing').is_file())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002119 self.assertFalse((P / 'fileA' / 'bah').is_file())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002120 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01002121 self.assertTrue((P / 'linkA').is_file())
2122 self.assertFalse((P / 'linkB').is_file())
2123 self.assertFalse((P/ 'brokenLink').is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002124 self.assertIs((P / 'fileA\udfff').is_file(), False)
2125 self.assertIs((P / 'fileA\x00').is_file(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002126
Cooper Lees173ff4a2017-08-01 15:35:45 -07002127 @only_posix
2128 def test_is_mount(self):
2129 P = self.cls(BASE)
Anthony Shaw83da9262019-01-07 07:31:29 +11002130 R = self.cls('/') # TODO: Work out Windows.
Cooper Lees173ff4a2017-08-01 15:35:45 -07002131 self.assertFalse((P / 'fileA').is_mount())
2132 self.assertFalse((P / 'dirA').is_mount())
2133 self.assertFalse((P / 'non-existing').is_mount())
2134 self.assertFalse((P / 'fileA' / 'bah').is_mount())
2135 self.assertTrue(R.is_mount())
2136 if support.can_symlink():
2137 self.assertFalse((P / 'linkA').is_mount())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002138 self.assertIs(self.cls('/\udfff').is_mount(), False)
2139 self.assertIs(self.cls('/\x00').is_mount(), False)
Cooper Lees173ff4a2017-08-01 15:35:45 -07002140
Antoine Pitrou31119e42013-11-22 17:38:12 +01002141 def test_is_symlink(self):
2142 P = self.cls(BASE)
2143 self.assertFalse((P / 'fileA').is_symlink())
2144 self.assertFalse((P / 'dirA').is_symlink())
2145 self.assertFalse((P / 'non-existing').is_symlink())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002146 self.assertFalse((P / 'fileA' / 'bah').is_symlink())
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002147 if support.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01002148 self.assertTrue((P / 'linkA').is_symlink())
2149 self.assertTrue((P / 'linkB').is_symlink())
2150 self.assertTrue((P/ 'brokenLink').is_symlink())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002151 self.assertIs((P / 'fileA\udfff').is_file(), False)
2152 self.assertIs((P / 'fileA\x00').is_file(), False)
2153 if support.can_symlink():
2154 self.assertIs((P / 'linkA\udfff').is_file(), False)
2155 self.assertIs((P / 'linkA\x00').is_file(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002156
2157 def test_is_fifo_false(self):
2158 P = self.cls(BASE)
2159 self.assertFalse((P / 'fileA').is_fifo())
2160 self.assertFalse((P / 'dirA').is_fifo())
2161 self.assertFalse((P / 'non-existing').is_fifo())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002162 self.assertFalse((P / 'fileA' / 'bah').is_fifo())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002163 self.assertIs((P / 'fileA\udfff').is_fifo(), False)
2164 self.assertIs((P / 'fileA\x00').is_fifo(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002165
2166 @unittest.skipUnless(hasattr(os, "mkfifo"), "os.mkfifo() required")
2167 def test_is_fifo_true(self):
2168 P = self.cls(BASE, 'myfifo')
xdegaye92c2ca72017-11-12 17:31:07 +01002169 try:
2170 os.mkfifo(str(P))
2171 except PermissionError as e:
2172 self.skipTest('os.mkfifo(): %s' % e)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002173 self.assertTrue(P.is_fifo())
2174 self.assertFalse(P.is_socket())
2175 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002176 self.assertIs(self.cls(BASE, 'myfifo\udfff').is_fifo(), False)
2177 self.assertIs(self.cls(BASE, 'myfifo\x00').is_fifo(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002178
2179 def test_is_socket_false(self):
2180 P = self.cls(BASE)
2181 self.assertFalse((P / 'fileA').is_socket())
2182 self.assertFalse((P / 'dirA').is_socket())
2183 self.assertFalse((P / 'non-existing').is_socket())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002184 self.assertFalse((P / 'fileA' / 'bah').is_socket())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002185 self.assertIs((P / 'fileA\udfff').is_socket(), False)
2186 self.assertIs((P / 'fileA\x00').is_socket(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002187
2188 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required")
2189 def test_is_socket_true(self):
2190 P = self.cls(BASE, 'mysock')
Antoine Pitrou330ce592013-11-22 18:05:06 +01002191 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002192 self.addCleanup(sock.close)
Antoine Pitrou330ce592013-11-22 18:05:06 +01002193 try:
2194 sock.bind(str(P))
2195 except OSError as e:
Xavier de Gayee88ed052016-12-14 11:52:28 +01002196 if (isinstance(e, PermissionError) or
2197 "AF_UNIX path too long" in str(e)):
Antoine Pitrou330ce592013-11-22 18:05:06 +01002198 self.skipTest("cannot bind Unix socket: " + str(e))
Antoine Pitrou31119e42013-11-22 17:38:12 +01002199 self.assertTrue(P.is_socket())
2200 self.assertFalse(P.is_fifo())
2201 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002202 self.assertIs(self.cls(BASE, 'mysock\udfff').is_socket(), False)
2203 self.assertIs(self.cls(BASE, 'mysock\x00').is_socket(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002204
2205 def test_is_block_device_false(self):
2206 P = self.cls(BASE)
2207 self.assertFalse((P / 'fileA').is_block_device())
2208 self.assertFalse((P / 'dirA').is_block_device())
2209 self.assertFalse((P / 'non-existing').is_block_device())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002210 self.assertFalse((P / 'fileA' / 'bah').is_block_device())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002211 self.assertIs((P / 'fileA\udfff').is_block_device(), False)
2212 self.assertIs((P / 'fileA\x00').is_block_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002213
2214 def test_is_char_device_false(self):
2215 P = self.cls(BASE)
2216 self.assertFalse((P / 'fileA').is_char_device())
2217 self.assertFalse((P / 'dirA').is_char_device())
2218 self.assertFalse((P / 'non-existing').is_char_device())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002219 self.assertFalse((P / 'fileA' / 'bah').is_char_device())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002220 self.assertIs((P / 'fileA\udfff').is_char_device(), False)
2221 self.assertIs((P / 'fileA\x00').is_char_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002222
2223 def test_is_char_device_true(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002224 # Under Unix, /dev/null should generally be a char device.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002225 P = self.cls('/dev/null')
2226 if not P.exists():
2227 self.skipTest("/dev/null required")
2228 self.assertTrue(P.is_char_device())
2229 self.assertFalse(P.is_block_device())
2230 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002231 self.assertIs(self.cls('/dev/null\udfff').is_char_device(), False)
2232 self.assertIs(self.cls('/dev/null\x00').is_char_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002233
2234 def test_pickling_common(self):
2235 p = self.cls(BASE, 'fileA')
2236 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
2237 dumped = pickle.dumps(p, proto)
2238 pp = pickle.loads(dumped)
2239 self.assertEqual(pp.stat(), p.stat())
2240
2241 def test_parts_interning(self):
2242 P = self.cls
2243 p = P('/usr/bin/foo')
2244 q = P('/usr/local/bin')
2245 # 'usr'
2246 self.assertIs(p.parts[1], q.parts[1])
2247 # 'bin'
2248 self.assertIs(p.parts[2], q.parts[3])
2249
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002250 def _check_complex_symlinks(self, link0_target):
Anthony Shaw83da9262019-01-07 07:31:29 +11002251 # Test solving a non-looping chain of symlinks (issue #19887).
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002252 P = self.cls(BASE)
2253 self.dirlink(os.path.join('link0', 'link0'), join('link1'))
2254 self.dirlink(os.path.join('link1', 'link1'), join('link2'))
2255 self.dirlink(os.path.join('link2', 'link2'), join('link3'))
2256 self.dirlink(link0_target, join('link0'))
2257
Anthony Shaw83da9262019-01-07 07:31:29 +11002258 # Resolve absolute paths.
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002259 p = (P / 'link0').resolve()
2260 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002261 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002262 p = (P / 'link1').resolve()
2263 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002264 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002265 p = (P / 'link2').resolve()
2266 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002267 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002268 p = (P / 'link3').resolve()
2269 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002270 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002271
Anthony Shaw83da9262019-01-07 07:31:29 +11002272 # Resolve relative paths.
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002273 old_path = os.getcwd()
2274 os.chdir(BASE)
2275 try:
2276 p = self.cls('link0').resolve()
2277 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002278 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002279 p = self.cls('link1').resolve()
2280 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002281 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002282 p = self.cls('link2').resolve()
2283 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002284 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002285 p = self.cls('link3').resolve()
2286 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002287 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002288 finally:
2289 os.chdir(old_path)
2290
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002291 @support.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002292 def test_complex_symlinks_absolute(self):
2293 self._check_complex_symlinks(BASE)
2294
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002295 @support.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002296 def test_complex_symlinks_relative(self):
2297 self._check_complex_symlinks('.')
2298
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002299 @support.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002300 def test_complex_symlinks_relative_dot_dot(self):
2301 self._check_complex_symlinks(os.path.join('dirA', '..'))
2302
Antoine Pitrou31119e42013-11-22 17:38:12 +01002303
2304class PathTest(_BasePathTest, unittest.TestCase):
2305 cls = pathlib.Path
2306
Batuhan Taşkaya526606b2019-12-08 23:31:15 +03002307 def test_class_getitem(self):
2308 self.assertIs(self.cls[str], self.cls)
2309
Antoine Pitrou31119e42013-11-22 17:38:12 +01002310 def test_concrete_class(self):
2311 p = self.cls('a')
2312 self.assertIs(type(p),
2313 pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath)
2314
2315 def test_unsupported_flavour(self):
2316 if os.name == 'nt':
2317 self.assertRaises(NotImplementedError, pathlib.PosixPath)
2318 else:
2319 self.assertRaises(NotImplementedError, pathlib.WindowsPath)
2320
Berker Peksag4a208e42016-01-30 17:50:48 +02002321 def test_glob_empty_pattern(self):
2322 p = self.cls()
2323 with self.assertRaisesRegex(ValueError, 'Unacceptable pattern'):
2324 list(p.glob(''))
2325
Antoine Pitrou31119e42013-11-22 17:38:12 +01002326
2327@only_posix
2328class PosixPathTest(_BasePathTest, unittest.TestCase):
2329 cls = pathlib.PosixPath
2330
Steve Dower98eb3602016-11-09 12:58:17 -08002331 def _check_symlink_loop(self, *args, strict=True):
Antoine Pitrou31119e42013-11-22 17:38:12 +01002332 path = self.cls(*args)
2333 with self.assertRaises(RuntimeError):
Steve Dower98eb3602016-11-09 12:58:17 -08002334 print(path.resolve(strict))
Antoine Pitrou31119e42013-11-22 17:38:12 +01002335
2336 def test_open_mode(self):
2337 old_mask = os.umask(0)
2338 self.addCleanup(os.umask, old_mask)
2339 p = self.cls(BASE)
2340 with (p / 'new_file').open('wb'):
2341 pass
2342 st = os.stat(join('new_file'))
2343 self.assertEqual(stat.S_IMODE(st.st_mode), 0o666)
2344 os.umask(0o022)
2345 with (p / 'other_new_file').open('wb'):
2346 pass
2347 st = os.stat(join('other_new_file'))
2348 self.assertEqual(stat.S_IMODE(st.st_mode), 0o644)
2349
2350 def test_touch_mode(self):
2351 old_mask = os.umask(0)
2352 self.addCleanup(os.umask, old_mask)
2353 p = self.cls(BASE)
2354 (p / 'new_file').touch()
2355 st = os.stat(join('new_file'))
2356 self.assertEqual(stat.S_IMODE(st.st_mode), 0o666)
2357 os.umask(0o022)
2358 (p / 'other_new_file').touch()
2359 st = os.stat(join('other_new_file'))
2360 self.assertEqual(stat.S_IMODE(st.st_mode), 0o644)
2361 (p / 'masked_new_file').touch(mode=0o750)
2362 st = os.stat(join('masked_new_file'))
2363 self.assertEqual(stat.S_IMODE(st.st_mode), 0o750)
2364
Vajrasky Kokec1f5df2017-03-29 02:32:35 +07002365 @support.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01002366 def test_resolve_loop(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002367 # Loops with relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002368 os.symlink('linkX/inside', join('linkX'))
2369 self._check_symlink_loop(BASE, 'linkX')
2370 os.symlink('linkY', join('linkY'))
2371 self._check_symlink_loop(BASE, 'linkY')
2372 os.symlink('linkZ/../linkZ', join('linkZ'))
2373 self._check_symlink_loop(BASE, 'linkZ')
Steve Dower98eb3602016-11-09 12:58:17 -08002374 # Non-strict
2375 self._check_symlink_loop(BASE, 'linkZ', 'foo', strict=False)
Anthony Shaw83da9262019-01-07 07:31:29 +11002376 # Loops with absolute symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002377 os.symlink(join('linkU/inside'), join('linkU'))
2378 self._check_symlink_loop(BASE, 'linkU')
2379 os.symlink(join('linkV'), join('linkV'))
2380 self._check_symlink_loop(BASE, 'linkV')
2381 os.symlink(join('linkW/../linkW'), join('linkW'))
2382 self._check_symlink_loop(BASE, 'linkW')
Steve Dower98eb3602016-11-09 12:58:17 -08002383 # Non-strict
2384 self._check_symlink_loop(BASE, 'linkW', 'foo', strict=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002385
2386 def test_glob(self):
2387 P = self.cls
2388 p = P(BASE)
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002389 given = set(p.glob("FILEa"))
2390 expect = set() if not support.fs_is_case_insensitive(BASE) else given
2391 self.assertEqual(given, expect)
Antoine Pitrou2dd38fb2013-11-22 22:26:01 +01002392 self.assertEqual(set(p.glob("FILEa*")), set())
Antoine Pitrou31119e42013-11-22 17:38:12 +01002393
2394 def test_rglob(self):
2395 P = self.cls
2396 p = P(BASE, "dirC")
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002397 given = set(p.rglob("FILEd"))
2398 expect = set() if not support.fs_is_case_insensitive(BASE) else given
2399 self.assertEqual(given, expect)
Antoine Pitrou2dd38fb2013-11-22 22:26:01 +01002400 self.assertEqual(set(p.rglob("FILEd*")), set())
Antoine Pitrou31119e42013-11-22 17:38:12 +01002401
Xavier de Gayefb24eea2016-12-13 09:11:38 +01002402 @unittest.skipUnless(hasattr(pwd, 'getpwall'),
2403 'pwd module does not expose getpwall()')
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002404 def test_expanduser(self):
2405 P = self.cls
2406 support.import_module('pwd')
2407 import pwd
2408 pwdent = pwd.getpwuid(os.getuid())
2409 username = pwdent.pw_name
Serhiy Storchakaa3fd0b22016-05-03 21:17:03 +03002410 userhome = pwdent.pw_dir.rstrip('/') or '/'
Anthony Shaw83da9262019-01-07 07:31:29 +11002411 # Find arbitrary different user (if exists).
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002412 for pwdent in pwd.getpwall():
2413 othername = pwdent.pw_name
2414 otherhome = pwdent.pw_dir.rstrip('/')
Victor Stinnere9694392015-01-10 09:00:20 +01002415 if othername != username and otherhome:
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002416 break
Anders Kaseorg5c0d4622018-05-14 10:00:37 -04002417 else:
2418 othername = username
2419 otherhome = userhome
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002420
2421 p1 = P('~/Documents')
2422 p2 = P('~' + username + '/Documents')
2423 p3 = P('~' + othername + '/Documents')
2424 p4 = P('../~' + username + '/Documents')
2425 p5 = P('/~' + username + '/Documents')
2426 p6 = P('')
2427 p7 = P('~fakeuser/Documents')
2428
2429 with support.EnvironmentVarGuard() as env:
2430 env.pop('HOME', None)
2431
2432 self.assertEqual(p1.expanduser(), P(userhome) / 'Documents')
2433 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
2434 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
2435 self.assertEqual(p4.expanduser(), p4)
2436 self.assertEqual(p5.expanduser(), p5)
2437 self.assertEqual(p6.expanduser(), p6)
2438 self.assertRaises(RuntimeError, p7.expanduser)
2439
2440 env['HOME'] = '/tmp'
2441 self.assertEqual(p1.expanduser(), P('/tmp/Documents'))
2442 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
2443 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
2444 self.assertEqual(p4.expanduser(), p4)
2445 self.assertEqual(p5.expanduser(), p5)
2446 self.assertEqual(p6.expanduser(), p6)
2447 self.assertRaises(RuntimeError, p7.expanduser)
2448
Przemysław Spodymek216b7452018-08-27 23:33:45 +02002449 @unittest.skipIf(sys.platform != "darwin",
2450 "Bad file descriptor in /dev/fd affects only macOS")
2451 def test_handling_bad_descriptor(self):
2452 try:
2453 file_descriptors = list(pathlib.Path('/dev/fd').rglob("*"))[3:]
2454 if not file_descriptors:
2455 self.skipTest("no file descriptors - issue was not reproduced")
2456 # Checking all file descriptors because there is no guarantee
2457 # which one will fail.
2458 for f in file_descriptors:
2459 f.exists()
2460 f.is_dir()
2461 f.is_file()
2462 f.is_symlink()
2463 f.is_block_device()
2464 f.is_char_device()
2465 f.is_fifo()
2466 f.is_socket()
2467 except OSError as e:
2468 if e.errno == errno.EBADF:
2469 self.fail("Bad file descriptor not handled.")
2470 raise
2471
Antoine Pitrou31119e42013-11-22 17:38:12 +01002472
2473@only_nt
2474class WindowsPathTest(_BasePathTest, unittest.TestCase):
2475 cls = pathlib.WindowsPath
2476
2477 def test_glob(self):
2478 P = self.cls
2479 p = P(BASE)
2480 self.assertEqual(set(p.glob("FILEa")), { P(BASE, "fileA") })
Serhiy Storchaka10ecbad2019-10-21 20:37:15 +03002481 self.assertEqual(set(p.glob("F*a")), { P(BASE, "fileA") })
2482 self.assertEqual(set(map(str, p.glob("FILEa"))), {f"{p}\\FILEa"})
2483 self.assertEqual(set(map(str, p.glob("F*a"))), {f"{p}\\fileA"})
Antoine Pitrou31119e42013-11-22 17:38:12 +01002484
2485 def test_rglob(self):
2486 P = self.cls
2487 p = P(BASE, "dirC")
2488 self.assertEqual(set(p.rglob("FILEd")), { P(BASE, "dirC/dirD/fileD") })
Serhiy Storchaka10ecbad2019-10-21 20:37:15 +03002489 self.assertEqual(set(map(str, p.rglob("FILEd"))), {f"{p}\\dirD\\FILEd"})
Antoine Pitrou31119e42013-11-22 17:38:12 +01002490
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002491 def test_expanduser(self):
2492 P = self.cls
2493 with support.EnvironmentVarGuard() as env:
2494 env.pop('HOME', None)
2495 env.pop('USERPROFILE', None)
2496 env.pop('HOMEPATH', None)
2497 env.pop('HOMEDRIVE', None)
2498 env['USERNAME'] = 'alice'
2499
2500 # test that the path returns unchanged
2501 p1 = P('~/My Documents')
2502 p2 = P('~alice/My Documents')
2503 p3 = P('~bob/My Documents')
2504 p4 = P('/~/My Documents')
2505 p5 = P('d:~/My Documents')
2506 p6 = P('')
2507 self.assertRaises(RuntimeError, p1.expanduser)
2508 self.assertRaises(RuntimeError, p2.expanduser)
2509 self.assertRaises(RuntimeError, p3.expanduser)
2510 self.assertEqual(p4.expanduser(), p4)
2511 self.assertEqual(p5.expanduser(), p5)
2512 self.assertEqual(p6.expanduser(), p6)
2513
2514 def check():
2515 env.pop('USERNAME', None)
2516 self.assertEqual(p1.expanduser(),
2517 P('C:/Users/alice/My Documents'))
2518 self.assertRaises(KeyError, p2.expanduser)
2519 env['USERNAME'] = 'alice'
2520 self.assertEqual(p2.expanduser(),
2521 P('C:/Users/alice/My Documents'))
2522 self.assertEqual(p3.expanduser(),
2523 P('C:/Users/bob/My Documents'))
2524 self.assertEqual(p4.expanduser(), p4)
2525 self.assertEqual(p5.expanduser(), p5)
2526 self.assertEqual(p6.expanduser(), p6)
2527
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002528 env['HOMEPATH'] = 'C:\\Users\\alice'
2529 check()
2530
2531 env['HOMEDRIVE'] = 'C:\\'
2532 env['HOMEPATH'] = 'Users\\alice'
2533 check()
2534
2535 env.pop('HOMEDRIVE', None)
2536 env.pop('HOMEPATH', None)
2537 env['USERPROFILE'] = 'C:\\Users\\alice'
2538 check()
2539
Christoph Reiterc45a2aa2020-01-28 10:41:50 +01002540 # bpo-38883: ignore `HOME` when set on windows
2541 env['HOME'] = 'C:\\Users\\eve'
2542 check()
2543
Antoine Pitrou31119e42013-11-22 17:38:12 +01002544
aiudirog4c69be22019-08-08 01:41:10 -04002545class CompatiblePathTest(unittest.TestCase):
2546 """
2547 Test that a type can be made compatible with PurePath
2548 derivatives by implementing division operator overloads.
2549 """
2550
2551 class CompatPath:
2552 """
2553 Minimum viable class to test PurePath compatibility.
2554 Simply uses the division operator to join a given
2555 string and the string value of another object with
2556 a forward slash.
2557 """
2558 def __init__(self, string):
2559 self.string = string
2560
2561 def __truediv__(self, other):
2562 return type(self)(f"{self.string}/{other}")
2563
2564 def __rtruediv__(self, other):
2565 return type(self)(f"{other}/{self.string}")
2566
2567 def test_truediv(self):
2568 result = pathlib.PurePath("test") / self.CompatPath("right")
2569 self.assertIsInstance(result, self.CompatPath)
2570 self.assertEqual(result.string, "test/right")
2571
2572 with self.assertRaises(TypeError):
2573 # Verify improper operations still raise a TypeError
2574 pathlib.PurePath("test") / 10
2575
2576 def test_rtruediv(self):
2577 result = self.CompatPath("left") / pathlib.PurePath("test")
2578 self.assertIsInstance(result, self.CompatPath)
2579 self.assertEqual(result.string, "left/test")
2580
2581 with self.assertRaises(TypeError):
2582 # Verify improper operations still raise a TypeError
2583 10 / pathlib.PurePath("test")
2584
2585
Antoine Pitrou31119e42013-11-22 17:38:12 +01002586if __name__ == "__main__":
2587 unittest.main()