blob: 17292dc1abf73ff08dc66764996fbfcb7613941b [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
Hai Shibb0424b2020-08-04 00:47:42 +080014from test.support import import_helper
15from test.support import os_helper
16from test.support.os_helper import TESTFN, FakePath
Antoine Pitrou31119e42013-11-22 17:38:12 +010017
18try:
19 import grp, pwd
20except ImportError:
21 grp = pwd = None
22
23
24class _BaseFlavourTest(object):
25
26 def _check_parse_parts(self, arg, expected):
27 f = self.flavour.parse_parts
28 sep = self.flavour.sep
29 altsep = self.flavour.altsep
30 actual = f([x.replace('/', sep) for x in arg])
31 self.assertEqual(actual, expected)
32 if altsep:
33 actual = f([x.replace('/', altsep) for x in arg])
34 self.assertEqual(actual, expected)
35
36 def test_parse_parts_common(self):
37 check = self._check_parse_parts
38 sep = self.flavour.sep
Anthony Shaw83da9262019-01-07 07:31:29 +110039 # Unanchored parts.
Antoine Pitrou31119e42013-11-22 17:38:12 +010040 check([], ('', '', []))
41 check(['a'], ('', '', ['a']))
42 check(['a/'], ('', '', ['a']))
43 check(['a', 'b'], ('', '', ['a', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +110044 # Expansion.
Antoine Pitrou31119e42013-11-22 17:38:12 +010045 check(['a/b'], ('', '', ['a', 'b']))
46 check(['a/b/'], ('', '', ['a', 'b']))
47 check(['a', 'b/c', 'd'], ('', '', ['a', 'b', 'c', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +110048 # Collapsing and stripping excess slashes.
Antoine Pitrou31119e42013-11-22 17:38:12 +010049 check(['a', 'b//c', 'd'], ('', '', ['a', 'b', 'c', 'd']))
50 check(['a', 'b/c/', 'd'], ('', '', ['a', 'b', 'c', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +110051 # Eliminating standalone dots.
Antoine Pitrou31119e42013-11-22 17:38:12 +010052 check(['.'], ('', '', []))
53 check(['.', '.', 'b'], ('', '', ['b']))
54 check(['a', '.', 'b'], ('', '', ['a', 'b']))
55 check(['a', '.', '.'], ('', '', ['a']))
Anthony Shaw83da9262019-01-07 07:31:29 +110056 # The first part is anchored.
Antoine Pitrou31119e42013-11-22 17:38:12 +010057 check(['/a/b'], ('', sep, [sep, 'a', 'b']))
58 check(['/a', 'b'], ('', sep, [sep, 'a', 'b']))
59 check(['/a/', 'b'], ('', sep, [sep, 'a', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +110060 # Ignoring parts before an anchored part.
Antoine Pitrou31119e42013-11-22 17:38:12 +010061 check(['a', '/b', 'c'], ('', sep, [sep, 'b', 'c']))
62 check(['a', '/b', '/c'], ('', sep, [sep, 'c']))
63
64
65class PosixFlavourTest(_BaseFlavourTest, unittest.TestCase):
66 flavour = pathlib._posix_flavour
67
68 def test_parse_parts(self):
69 check = self._check_parse_parts
70 # Collapsing of excess leading slashes, except for the double-slash
71 # special case.
72 check(['//a', 'b'], ('', '//', ['//', 'a', 'b']))
73 check(['///a', 'b'], ('', '/', ['/', 'a', 'b']))
74 check(['////a', 'b'], ('', '/', ['/', 'a', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +110075 # Paths which look like NT paths aren't treated specially.
Antoine Pitrou31119e42013-11-22 17:38:12 +010076 check(['c:a'], ('', '', ['c:a']))
77 check(['c:\\a'], ('', '', ['c:\\a']))
78 check(['\\a'], ('', '', ['\\a']))
79
80 def test_splitroot(self):
81 f = self.flavour.splitroot
82 self.assertEqual(f(''), ('', '', ''))
83 self.assertEqual(f('a'), ('', '', 'a'))
84 self.assertEqual(f('a/b'), ('', '', 'a/b'))
85 self.assertEqual(f('a/b/'), ('', '', 'a/b/'))
86 self.assertEqual(f('/a'), ('', '/', 'a'))
87 self.assertEqual(f('/a/b'), ('', '/', 'a/b'))
88 self.assertEqual(f('/a/b/'), ('', '/', 'a/b/'))
89 # The root is collapsed when there are redundant slashes
90 # except when there are exactly two leading slashes, which
91 # is a special case in POSIX.
92 self.assertEqual(f('//a'), ('', '//', 'a'))
93 self.assertEqual(f('///a'), ('', '/', 'a'))
94 self.assertEqual(f('///a/b'), ('', '/', 'a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +110095 # Paths which look like NT paths aren't treated specially.
Antoine Pitrou31119e42013-11-22 17:38:12 +010096 self.assertEqual(f('c:/a/b'), ('', '', 'c:/a/b'))
97 self.assertEqual(f('\\/a/b'), ('', '', '\\/a/b'))
98 self.assertEqual(f('\\a\\b'), ('', '', '\\a\\b'))
99
100
101class NTFlavourTest(_BaseFlavourTest, unittest.TestCase):
102 flavour = pathlib._windows_flavour
103
104 def test_parse_parts(self):
105 check = self._check_parse_parts
Anthony Shaw83da9262019-01-07 07:31:29 +1100106 # First part is anchored.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100107 check(['c:'], ('c:', '', ['c:']))
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100108 check(['c:/'], ('c:', '\\', ['c:\\']))
109 check(['/'], ('', '\\', ['\\']))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100110 check(['c:a'], ('c:', '', ['c:', 'a']))
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100111 check(['c:/a'], ('c:', '\\', ['c:\\', 'a']))
112 check(['/a'], ('', '\\', ['\\', 'a']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100113 # UNC paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100114 check(['//a/b'], ('\\\\a\\b', '\\', ['\\\\a\\b\\']))
115 check(['//a/b/'], ('\\\\a\\b', '\\', ['\\\\a\\b\\']))
116 check(['//a/b/c'], ('\\\\a\\b', '\\', ['\\\\a\\b\\', 'c']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100117 # Second part is anchored, so that the first part is ignored.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100118 check(['a', 'Z:b', 'c'], ('Z:', '', ['Z:', 'b', 'c']))
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100119 check(['a', 'Z:/b', 'c'], ('Z:', '\\', ['Z:\\', 'b', 'c']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100120 # UNC paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100121 check(['a', '//b/c', 'd'], ('\\\\b\\c', '\\', ['\\\\b\\c\\', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100122 # Collapsing and stripping excess slashes.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100123 check(['a', 'Z://b//c/', 'd/'], ('Z:', '\\', ['Z:\\', 'b', 'c', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100124 # UNC paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100125 check(['a', '//b/c//', 'd'], ('\\\\b\\c', '\\', ['\\\\b\\c\\', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100126 # Extended paths.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100127 check(['//?/c:/'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\']))
128 check(['//?/c:/a'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\', 'a']))
129 check(['//?/c:/a', '/b'], ('\\\\?\\c:', '\\', ['\\\\?\\c:\\', 'b']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100130 # Extended UNC paths (format is "\\?\UNC\server\share").
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100131 check(['//?/UNC/b/c'], ('\\\\?\\UNC\\b\\c', '\\', ['\\\\?\\UNC\\b\\c\\']))
132 check(['//?/UNC/b/c/d'], ('\\\\?\\UNC\\b\\c', '\\', ['\\\\?\\UNC\\b\\c\\', 'd']))
Anthony Shaw83da9262019-01-07 07:31:29 +1100133 # Second part has a root but not drive.
Antoine Pitrou57fffd62015-02-15 18:03:59 +0100134 check(['a', '/b', 'c'], ('', '\\', ['\\', 'b', 'c']))
135 check(['Z:/a', '/b', 'c'], ('Z:', '\\', ['Z:\\', 'b', 'c']))
136 check(['//?/Z:/a', '/b', 'c'], ('\\\\?\\Z:', '\\', ['\\\\?\\Z:\\', 'b', 'c']))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100137
138 def test_splitroot(self):
139 f = self.flavour.splitroot
140 self.assertEqual(f(''), ('', '', ''))
141 self.assertEqual(f('a'), ('', '', 'a'))
142 self.assertEqual(f('a\\b'), ('', '', 'a\\b'))
143 self.assertEqual(f('\\a'), ('', '\\', 'a'))
144 self.assertEqual(f('\\a\\b'), ('', '\\', 'a\\b'))
145 self.assertEqual(f('c:a\\b'), ('c:', '', 'a\\b'))
146 self.assertEqual(f('c:\\a\\b'), ('c:', '\\', 'a\\b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100147 # Redundant slashes in the root are collapsed.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100148 self.assertEqual(f('\\\\a'), ('', '\\', 'a'))
149 self.assertEqual(f('\\\\\\a/b'), ('', '\\', 'a/b'))
150 self.assertEqual(f('c:\\\\a'), ('c:', '\\', 'a'))
151 self.assertEqual(f('c:\\\\\\a/b'), ('c:', '\\', 'a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100152 # Valid UNC paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100153 self.assertEqual(f('\\\\a\\b'), ('\\\\a\\b', '\\', ''))
154 self.assertEqual(f('\\\\a\\b\\'), ('\\\\a\\b', '\\', ''))
155 self.assertEqual(f('\\\\a\\b\\c\\d'), ('\\\\a\\b', '\\', 'c\\d'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100156 # These are non-UNC paths (according to ntpath.py and test_ntpath).
Antoine Pitrou31119e42013-11-22 17:38:12 +0100157 # However, command.com says such paths are invalid, so it's
Anthony Shaw83da9262019-01-07 07:31:29 +1100158 # difficult to know what the right semantics are.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100159 self.assertEqual(f('\\\\\\a\\b'), ('', '\\', 'a\\b'))
160 self.assertEqual(f('\\\\a'), ('', '\\', 'a'))
161
162
163#
Anthony Shaw83da9262019-01-07 07:31:29 +1100164# Tests for the pure classes.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100165#
166
167class _BasePurePathTest(object):
168
Anthony Shaw83da9262019-01-07 07:31:29 +1100169 # Keys are canonical paths, values are list of tuples of arguments
170 # supposed to produce equal paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100171 equivalences = {
172 'a/b': [
173 ('a', 'b'), ('a/', 'b'), ('a', 'b/'), ('a/', 'b/'),
174 ('a/b/',), ('a//b',), ('a//b//',),
Anthony Shaw83da9262019-01-07 07:31:29 +1100175 # Empty components get removed.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100176 ('', 'a', 'b'), ('a', '', 'b'), ('a', 'b', ''),
177 ],
178 '/b/c/d': [
179 ('a', '/b/c', 'd'), ('a', '///b//c', 'd/'),
180 ('/a', '/b/c', 'd'),
Anthony Shaw83da9262019-01-07 07:31:29 +1100181 # Empty components get removed.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100182 ('/', 'b', '', 'c/d'), ('/', '', 'b/c/d'), ('', '/b/c/d'),
183 ],
184 }
185
186 def setUp(self):
187 p = self.cls('a')
188 self.flavour = p._flavour
189 self.sep = self.flavour.sep
190 self.altsep = self.flavour.altsep
191
192 def test_constructor_common(self):
193 P = self.cls
194 p = P('a')
195 self.assertIsInstance(p, P)
196 P('a', 'b', 'c')
197 P('/a', 'b', 'c')
198 P('a/b/c')
199 P('/a/b/c')
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200200 P(FakePath("a/b/c"))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100201 self.assertEqual(P(P('a')), P('a'))
202 self.assertEqual(P(P('a'), 'b'), P('a/b'))
203 self.assertEqual(P(P('a'), P('b')), P('a/b'))
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200204 self.assertEqual(P(P('a'), P('b'), P('c')), P(FakePath("a/b/c")))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100205
Antoine Pitroucb5ec772014-04-23 00:34:15 +0200206 def _check_str_subclass(self, *args):
207 # Issue #21127: it should be possible to construct a PurePath object
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300208 # from a str subclass instance, and it then gets converted to
Antoine Pitroucb5ec772014-04-23 00:34:15 +0200209 # a pure str object.
210 class StrSubclass(str):
211 pass
212 P = self.cls
213 p = P(*(StrSubclass(x) for x in args))
214 self.assertEqual(p, P(*args))
215 for part in p.parts:
216 self.assertIs(type(part), str)
217
218 def test_str_subclass_common(self):
219 self._check_str_subclass('')
220 self._check_str_subclass('.')
221 self._check_str_subclass('a')
222 self._check_str_subclass('a/b.txt')
223 self._check_str_subclass('/a/b.txt')
224
Antoine Pitrou31119e42013-11-22 17:38:12 +0100225 def test_join_common(self):
226 P = self.cls
227 p = P('a/b')
228 pp = p.joinpath('c')
229 self.assertEqual(pp, P('a/b/c'))
230 self.assertIs(type(pp), type(p))
231 pp = p.joinpath('c', 'd')
232 self.assertEqual(pp, P('a/b/c/d'))
233 pp = p.joinpath(P('c'))
234 self.assertEqual(pp, P('a/b/c'))
235 pp = p.joinpath('/c')
236 self.assertEqual(pp, P('/c'))
237
238 def test_div_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100239 # Basically the same as joinpath().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100240 P = self.cls
241 p = P('a/b')
242 pp = p / 'c'
243 self.assertEqual(pp, P('a/b/c'))
244 self.assertIs(type(pp), type(p))
245 pp = p / 'c/d'
246 self.assertEqual(pp, P('a/b/c/d'))
247 pp = p / 'c' / 'd'
248 self.assertEqual(pp, P('a/b/c/d'))
249 pp = 'c' / p / 'd'
250 self.assertEqual(pp, P('c/a/b/d'))
251 pp = p / P('c')
252 self.assertEqual(pp, P('a/b/c'))
253 pp = p/ '/c'
254 self.assertEqual(pp, P('/c'))
255
256 def _check_str(self, expected, args):
257 p = self.cls(*args)
258 self.assertEqual(str(p), expected.replace('/', self.sep))
259
260 def test_str_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100261 # Canonicalized paths roundtrip.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100262 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
263 self._check_str(pathstr, (pathstr,))
Anthony Shaw83da9262019-01-07 07:31:29 +1100264 # Special case for the empty path.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100265 self._check_str('.', ('',))
Anthony Shaw83da9262019-01-07 07:31:29 +1100266 # Other tests for str() are in test_equivalences().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100267
268 def test_as_posix_common(self):
269 P = self.cls
270 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
271 self.assertEqual(P(pathstr).as_posix(), pathstr)
Anthony Shaw83da9262019-01-07 07:31:29 +1100272 # Other tests for as_posix() are in test_equivalences().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100273
274 def test_as_bytes_common(self):
275 sep = os.fsencode(self.sep)
276 P = self.cls
277 self.assertEqual(bytes(P('a/b')), b'a' + sep + b'b')
278
279 def test_as_uri_common(self):
280 P = self.cls
281 with self.assertRaises(ValueError):
282 P('a').as_uri()
283 with self.assertRaises(ValueError):
284 P().as_uri()
285
286 def test_repr_common(self):
287 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
288 p = self.cls(pathstr)
289 clsname = p.__class__.__name__
290 r = repr(p)
Anthony Shaw83da9262019-01-07 07:31:29 +1100291 # The repr() is in the form ClassName("forward-slashes path").
Antoine Pitrou31119e42013-11-22 17:38:12 +0100292 self.assertTrue(r.startswith(clsname + '('), r)
293 self.assertTrue(r.endswith(')'), r)
294 inner = r[len(clsname) + 1 : -1]
295 self.assertEqual(eval(inner), p.as_posix())
Anthony Shaw83da9262019-01-07 07:31:29 +1100296 # The repr() roundtrips.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100297 q = eval(r, pathlib.__dict__)
298 self.assertIs(q.__class__, p.__class__)
299 self.assertEqual(q, p)
300 self.assertEqual(repr(q), r)
301
302 def test_eq_common(self):
303 P = self.cls
304 self.assertEqual(P('a/b'), P('a/b'))
305 self.assertEqual(P('a/b'), P('a', 'b'))
306 self.assertNotEqual(P('a/b'), P('a'))
307 self.assertNotEqual(P('a/b'), P('/a/b'))
308 self.assertNotEqual(P('a/b'), P())
309 self.assertNotEqual(P('/a/b'), P('/'))
310 self.assertNotEqual(P(), P('/'))
311 self.assertNotEqual(P(), "")
312 self.assertNotEqual(P(), {})
313 self.assertNotEqual(P(), int)
314
315 def test_match_common(self):
316 P = self.cls
317 self.assertRaises(ValueError, P('a').match, '')
318 self.assertRaises(ValueError, P('a').match, '.')
Anthony Shaw83da9262019-01-07 07:31:29 +1100319 # Simple relative pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100320 self.assertTrue(P('b.py').match('b.py'))
321 self.assertTrue(P('a/b.py').match('b.py'))
322 self.assertTrue(P('/a/b.py').match('b.py'))
323 self.assertFalse(P('a.py').match('b.py'))
324 self.assertFalse(P('b/py').match('b.py'))
325 self.assertFalse(P('/a.py').match('b.py'))
326 self.assertFalse(P('b.py/c').match('b.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100327 # Wilcard relative pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100328 self.assertTrue(P('b.py').match('*.py'))
329 self.assertTrue(P('a/b.py').match('*.py'))
330 self.assertTrue(P('/a/b.py').match('*.py'))
331 self.assertFalse(P('b.pyc').match('*.py'))
332 self.assertFalse(P('b./py').match('*.py'))
333 self.assertFalse(P('b.py/c').match('*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100334 # Multi-part relative pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100335 self.assertTrue(P('ab/c.py').match('a*/*.py'))
336 self.assertTrue(P('/d/ab/c.py').match('a*/*.py'))
337 self.assertFalse(P('a.py').match('a*/*.py'))
338 self.assertFalse(P('/dab/c.py').match('a*/*.py'))
339 self.assertFalse(P('ab/c.py/d').match('a*/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100340 # Absolute pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100341 self.assertTrue(P('/b.py').match('/*.py'))
342 self.assertFalse(P('b.py').match('/*.py'))
343 self.assertFalse(P('a/b.py').match('/*.py'))
344 self.assertFalse(P('/a/b.py').match('/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100345 # Multi-part absolute pattern.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100346 self.assertTrue(P('/a/b.py').match('/a/*.py'))
347 self.assertFalse(P('/ab.py').match('/a/*.py'))
348 self.assertFalse(P('/a/b/c.py').match('/a/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100349 # Multi-part glob-style pattern.
350 self.assertFalse(P('/a/b/c.py').match('/**/*.py'))
351 self.assertTrue(P('/a/b/c.py').match('/a/**/*.py'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100352
353 def test_ordering_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100354 # Ordering is tuple-alike.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100355 def assertLess(a, b):
356 self.assertLess(a, b)
357 self.assertGreater(b, a)
358 P = self.cls
359 a = P('a')
360 b = P('a/b')
361 c = P('abc')
362 d = P('b')
363 assertLess(a, b)
364 assertLess(a, c)
365 assertLess(a, d)
366 assertLess(b, c)
367 assertLess(c, d)
368 P = self.cls
369 a = P('/a')
370 b = P('/a/b')
371 c = P('/abc')
372 d = P('/b')
373 assertLess(a, b)
374 assertLess(a, c)
375 assertLess(a, d)
376 assertLess(b, c)
377 assertLess(c, d)
378 with self.assertRaises(TypeError):
379 P() < {}
380
381 def test_parts_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100382 # `parts` returns a tuple.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100383 sep = self.sep
384 P = self.cls
385 p = P('a/b')
386 parts = p.parts
387 self.assertEqual(parts, ('a', 'b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100388 # The object gets reused.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100389 self.assertIs(parts, p.parts)
Anthony Shaw83da9262019-01-07 07:31:29 +1100390 # When the path is absolute, the anchor is a separate part.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100391 p = P('/a/b')
392 parts = p.parts
393 self.assertEqual(parts, (sep, 'a', 'b'))
394
Brett Cannon568be632016-06-10 12:20:49 -0700395 def test_fspath_common(self):
396 P = self.cls
397 p = P('a/b')
398 self._check_str(p.__fspath__(), ('a/b',))
399 self._check_str(os.fspath(p), ('a/b',))
400
Antoine Pitrou31119e42013-11-22 17:38:12 +0100401 def test_equivalences(self):
402 for k, tuples in self.equivalences.items():
403 canon = k.replace('/', self.sep)
404 posix = k.replace(self.sep, '/')
405 if canon != posix:
406 tuples = tuples + [
407 tuple(part.replace('/', self.sep) for part in t)
408 for t in tuples
409 ]
410 tuples.append((posix, ))
411 pcanon = self.cls(canon)
412 for t in tuples:
413 p = self.cls(*t)
414 self.assertEqual(p, pcanon, "failed with args {}".format(t))
415 self.assertEqual(hash(p), hash(pcanon))
416 self.assertEqual(str(p), canon)
417 self.assertEqual(p.as_posix(), posix)
418
419 def test_parent_common(self):
420 # Relative
421 P = self.cls
422 p = P('a/b/c')
423 self.assertEqual(p.parent, P('a/b'))
424 self.assertEqual(p.parent.parent, P('a'))
425 self.assertEqual(p.parent.parent.parent, P())
426 self.assertEqual(p.parent.parent.parent.parent, P())
427 # Anchored
428 p = P('/a/b/c')
429 self.assertEqual(p.parent, P('/a/b'))
430 self.assertEqual(p.parent.parent, P('/a'))
431 self.assertEqual(p.parent.parent.parent, P('/'))
432 self.assertEqual(p.parent.parent.parent.parent, P('/'))
433
434 def test_parents_common(self):
435 # Relative
436 P = self.cls
437 p = P('a/b/c')
438 par = p.parents
439 self.assertEqual(len(par), 3)
440 self.assertEqual(par[0], P('a/b'))
441 self.assertEqual(par[1], P('a'))
442 self.assertEqual(par[2], P('.'))
443 self.assertEqual(list(par), [P('a/b'), P('a'), P('.')])
444 with self.assertRaises(IndexError):
445 par[-1]
446 with self.assertRaises(IndexError):
447 par[3]
448 with self.assertRaises(TypeError):
449 par[0] = p
450 # Anchored
451 p = P('/a/b/c')
452 par = p.parents
453 self.assertEqual(len(par), 3)
454 self.assertEqual(par[0], P('/a/b'))
455 self.assertEqual(par[1], P('/a'))
456 self.assertEqual(par[2], P('/'))
457 self.assertEqual(list(par), [P('/a/b'), P('/a'), P('/')])
458 with self.assertRaises(IndexError):
459 par[3]
460
461 def test_drive_common(self):
462 P = self.cls
463 self.assertEqual(P('a/b').drive, '')
464 self.assertEqual(P('/a/b').drive, '')
465 self.assertEqual(P('').drive, '')
466
467 def test_root_common(self):
468 P = self.cls
469 sep = self.sep
470 self.assertEqual(P('').root, '')
471 self.assertEqual(P('a/b').root, '')
472 self.assertEqual(P('/').root, sep)
473 self.assertEqual(P('/a/b').root, sep)
474
475 def test_anchor_common(self):
476 P = self.cls
477 sep = self.sep
478 self.assertEqual(P('').anchor, '')
479 self.assertEqual(P('a/b').anchor, '')
480 self.assertEqual(P('/').anchor, sep)
481 self.assertEqual(P('/a/b').anchor, sep)
482
483 def test_name_common(self):
484 P = self.cls
485 self.assertEqual(P('').name, '')
486 self.assertEqual(P('.').name, '')
487 self.assertEqual(P('/').name, '')
488 self.assertEqual(P('a/b').name, 'b')
489 self.assertEqual(P('/a/b').name, 'b')
490 self.assertEqual(P('/a/b/.').name, 'b')
491 self.assertEqual(P('a/b.py').name, 'b.py')
492 self.assertEqual(P('/a/b.py').name, 'b.py')
493
494 def test_suffix_common(self):
495 P = self.cls
496 self.assertEqual(P('').suffix, '')
497 self.assertEqual(P('.').suffix, '')
498 self.assertEqual(P('..').suffix, '')
499 self.assertEqual(P('/').suffix, '')
500 self.assertEqual(P('a/b').suffix, '')
501 self.assertEqual(P('/a/b').suffix, '')
502 self.assertEqual(P('/a/b/.').suffix, '')
503 self.assertEqual(P('a/b.py').suffix, '.py')
504 self.assertEqual(P('/a/b.py').suffix, '.py')
505 self.assertEqual(P('a/.hgrc').suffix, '')
506 self.assertEqual(P('/a/.hgrc').suffix, '')
507 self.assertEqual(P('a/.hg.rc').suffix, '.rc')
508 self.assertEqual(P('/a/.hg.rc').suffix, '.rc')
509 self.assertEqual(P('a/b.tar.gz').suffix, '.gz')
510 self.assertEqual(P('/a/b.tar.gz').suffix, '.gz')
511 self.assertEqual(P('a/Some name. Ending with a dot.').suffix, '')
512 self.assertEqual(P('/a/Some name. Ending with a dot.').suffix, '')
513
514 def test_suffixes_common(self):
515 P = self.cls
516 self.assertEqual(P('').suffixes, [])
517 self.assertEqual(P('.').suffixes, [])
518 self.assertEqual(P('/').suffixes, [])
519 self.assertEqual(P('a/b').suffixes, [])
520 self.assertEqual(P('/a/b').suffixes, [])
521 self.assertEqual(P('/a/b/.').suffixes, [])
522 self.assertEqual(P('a/b.py').suffixes, ['.py'])
523 self.assertEqual(P('/a/b.py').suffixes, ['.py'])
524 self.assertEqual(P('a/.hgrc').suffixes, [])
525 self.assertEqual(P('/a/.hgrc').suffixes, [])
526 self.assertEqual(P('a/.hg.rc').suffixes, ['.rc'])
527 self.assertEqual(P('/a/.hg.rc').suffixes, ['.rc'])
528 self.assertEqual(P('a/b.tar.gz').suffixes, ['.tar', '.gz'])
529 self.assertEqual(P('/a/b.tar.gz').suffixes, ['.tar', '.gz'])
530 self.assertEqual(P('a/Some name. Ending with a dot.').suffixes, [])
531 self.assertEqual(P('/a/Some name. Ending with a dot.').suffixes, [])
532
533 def test_stem_common(self):
534 P = self.cls
535 self.assertEqual(P('').stem, '')
536 self.assertEqual(P('.').stem, '')
537 self.assertEqual(P('..').stem, '..')
538 self.assertEqual(P('/').stem, '')
539 self.assertEqual(P('a/b').stem, 'b')
540 self.assertEqual(P('a/b.py').stem, 'b')
541 self.assertEqual(P('a/.hgrc').stem, '.hgrc')
542 self.assertEqual(P('a/.hg.rc').stem, '.hg')
543 self.assertEqual(P('a/b.tar.gz').stem, 'b.tar')
544 self.assertEqual(P('a/Some name. Ending with a dot.').stem,
545 'Some name. Ending with a dot.')
546
547 def test_with_name_common(self):
548 P = self.cls
549 self.assertEqual(P('a/b').with_name('d.xml'), P('a/d.xml'))
550 self.assertEqual(P('/a/b').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/b.py').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.assertEqual(P('/a/Dot ending.').with_name('d.xml'), P('/a/d.xml'))
555 self.assertRaises(ValueError, P('').with_name, 'd.xml')
556 self.assertRaises(ValueError, P('.').with_name, 'd.xml')
557 self.assertRaises(ValueError, P('/').with_name, 'd.xml')
Antoine Pitrou7084e732014-07-06 21:31:12 -0400558 self.assertRaises(ValueError, P('a/b').with_name, '')
559 self.assertRaises(ValueError, P('a/b').with_name, '/c')
560 self.assertRaises(ValueError, P('a/b').with_name, 'c/')
561 self.assertRaises(ValueError, P('a/b').with_name, 'c/d')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100562
Tim Hoffmann8aea4b32020-04-19 17:29:49 +0200563 def test_with_stem_common(self):
564 P = self.cls
565 self.assertEqual(P('a/b').with_stem('d'), P('a/d'))
566 self.assertEqual(P('/a/b').with_stem('d'), P('/a/d'))
567 self.assertEqual(P('a/b.py').with_stem('d'), P('a/d.py'))
568 self.assertEqual(P('/a/b.py').with_stem('d'), P('/a/d.py'))
569 self.assertEqual(P('/a/b.tar.gz').with_stem('d'), P('/a/d.gz'))
570 self.assertEqual(P('a/Dot ending.').with_stem('d'), P('a/d'))
571 self.assertEqual(P('/a/Dot ending.').with_stem('d'), P('/a/d'))
572 self.assertRaises(ValueError, P('').with_stem, 'd')
573 self.assertRaises(ValueError, P('.').with_stem, 'd')
574 self.assertRaises(ValueError, P('/').with_stem, 'd')
575 self.assertRaises(ValueError, P('a/b').with_stem, '')
576 self.assertRaises(ValueError, P('a/b').with_stem, '/c')
577 self.assertRaises(ValueError, P('a/b').with_stem, 'c/')
578 self.assertRaises(ValueError, P('a/b').with_stem, 'c/d')
579
Antoine Pitrou31119e42013-11-22 17:38:12 +0100580 def test_with_suffix_common(self):
581 P = self.cls
582 self.assertEqual(P('a/b').with_suffix('.gz'), P('a/b.gz'))
583 self.assertEqual(P('/a/b').with_suffix('.gz'), P('/a/b.gz'))
584 self.assertEqual(P('a/b.py').with_suffix('.gz'), P('a/b.gz'))
585 self.assertEqual(P('/a/b.py').with_suffix('.gz'), P('/a/b.gz'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100586 # Stripping suffix.
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400587 self.assertEqual(P('a/b.py').with_suffix(''), P('a/b'))
588 self.assertEqual(P('/a/b').with_suffix(''), P('/a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100589 # Path doesn't have a "filename" component.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100590 self.assertRaises(ValueError, P('').with_suffix, '.gz')
591 self.assertRaises(ValueError, P('.').with_suffix, '.gz')
592 self.assertRaises(ValueError, P('/').with_suffix, '.gz')
Anthony Shaw83da9262019-01-07 07:31:29 +1100593 # Invalid suffix.
Antoine Pitrou1b02da92014-01-03 00:07:17 +0100594 self.assertRaises(ValueError, P('a/b').with_suffix, 'gz')
595 self.assertRaises(ValueError, P('a/b').with_suffix, '/')
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400596 self.assertRaises(ValueError, P('a/b').with_suffix, '.')
Antoine Pitrou1b02da92014-01-03 00:07:17 +0100597 self.assertRaises(ValueError, P('a/b').with_suffix, '/.gz')
598 self.assertRaises(ValueError, P('a/b').with_suffix, 'c/d')
599 self.assertRaises(ValueError, P('a/b').with_suffix, '.c/.d')
Antoine Pitroue50dafc2014-07-06 21:37:15 -0400600 self.assertRaises(ValueError, P('a/b').with_suffix, './.d')
601 self.assertRaises(ValueError, P('a/b').with_suffix, '.d/.')
Berker Peksag423d05f2018-08-11 08:45:06 +0300602 self.assertRaises(ValueError, P('a/b').with_suffix,
603 (self.flavour.sep, 'd'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100604
605 def test_relative_to_common(self):
606 P = self.cls
607 p = P('a/b')
608 self.assertRaises(TypeError, p.relative_to)
Antoine Pitrou156b3612013-12-28 19:49:04 +0100609 self.assertRaises(TypeError, p.relative_to, b'a')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100610 self.assertEqual(p.relative_to(P()), P('a/b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100611 self.assertEqual(p.relative_to(''), P('a/b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100612 self.assertEqual(p.relative_to(P('a')), P('b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100613 self.assertEqual(p.relative_to('a'), P('b'))
614 self.assertEqual(p.relative_to('a/'), P('b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100615 self.assertEqual(p.relative_to(P('a/b')), P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100616 self.assertEqual(p.relative_to('a/b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100617 # With several args.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100618 self.assertEqual(p.relative_to('a', 'b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100619 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100620 self.assertRaises(ValueError, p.relative_to, P('c'))
621 self.assertRaises(ValueError, p.relative_to, P('a/b/c'))
622 self.assertRaises(ValueError, p.relative_to, P('a/c'))
623 self.assertRaises(ValueError, p.relative_to, P('/a'))
624 p = P('/a/b')
625 self.assertEqual(p.relative_to(P('/')), P('a/b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100626 self.assertEqual(p.relative_to('/'), P('a/b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100627 self.assertEqual(p.relative_to(P('/a')), P('b'))
Antoine Pitrou156b3612013-12-28 19:49:04 +0100628 self.assertEqual(p.relative_to('/a'), P('b'))
629 self.assertEqual(p.relative_to('/a/'), P('b'))
Antoine Pitrou31119e42013-11-22 17:38:12 +0100630 self.assertEqual(p.relative_to(P('/a/b')), P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100631 self.assertEqual(p.relative_to('/a/b'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +1100632 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100633 self.assertRaises(ValueError, p.relative_to, P('/c'))
634 self.assertRaises(ValueError, p.relative_to, P('/a/b/c'))
635 self.assertRaises(ValueError, p.relative_to, P('/a/c'))
636 self.assertRaises(ValueError, p.relative_to, P())
Antoine Pitrou156b3612013-12-28 19:49:04 +0100637 self.assertRaises(ValueError, p.relative_to, '')
Antoine Pitrou31119e42013-11-22 17:38:12 +0100638 self.assertRaises(ValueError, p.relative_to, P('a'))
639
Hai Shi82642a02019-08-13 14:54:02 -0500640 def test_is_relative_to_common(self):
641 P = self.cls
642 p = P('a/b')
643 self.assertRaises(TypeError, p.is_relative_to)
644 self.assertRaises(TypeError, p.is_relative_to, b'a')
645 self.assertTrue(p.is_relative_to(P()))
646 self.assertTrue(p.is_relative_to(''))
647 self.assertTrue(p.is_relative_to(P('a')))
648 self.assertTrue(p.is_relative_to('a/'))
649 self.assertTrue(p.is_relative_to(P('a/b')))
650 self.assertTrue(p.is_relative_to('a/b'))
651 # With several args.
652 self.assertTrue(p.is_relative_to('a', 'b'))
653 # Unrelated paths.
654 self.assertFalse(p.is_relative_to(P('c')))
655 self.assertFalse(p.is_relative_to(P('a/b/c')))
656 self.assertFalse(p.is_relative_to(P('a/c')))
657 self.assertFalse(p.is_relative_to(P('/a')))
658 p = P('/a/b')
659 self.assertTrue(p.is_relative_to(P('/')))
660 self.assertTrue(p.is_relative_to('/'))
661 self.assertTrue(p.is_relative_to(P('/a')))
662 self.assertTrue(p.is_relative_to('/a'))
663 self.assertTrue(p.is_relative_to('/a/'))
664 self.assertTrue(p.is_relative_to(P('/a/b')))
665 self.assertTrue(p.is_relative_to('/a/b'))
666 # Unrelated paths.
667 self.assertFalse(p.is_relative_to(P('/c')))
668 self.assertFalse(p.is_relative_to(P('/a/b/c')))
669 self.assertFalse(p.is_relative_to(P('/a/c')))
670 self.assertFalse(p.is_relative_to(P()))
671 self.assertFalse(p.is_relative_to(''))
672 self.assertFalse(p.is_relative_to(P('a')))
673
Antoine Pitrou31119e42013-11-22 17:38:12 +0100674 def test_pickling_common(self):
675 P = self.cls
676 p = P('/a/b')
677 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
678 dumped = pickle.dumps(p, proto)
679 pp = pickle.loads(dumped)
680 self.assertIs(pp.__class__, p.__class__)
681 self.assertEqual(pp, p)
682 self.assertEqual(hash(pp), hash(p))
683 self.assertEqual(str(pp), str(p))
684
685
686class PurePosixPathTest(_BasePurePathTest, unittest.TestCase):
687 cls = pathlib.PurePosixPath
688
689 def test_root(self):
690 P = self.cls
691 self.assertEqual(P('/a/b').root, '/')
692 self.assertEqual(P('///a/b').root, '/')
Anthony Shaw83da9262019-01-07 07:31:29 +1100693 # POSIX special case for two leading slashes.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100694 self.assertEqual(P('//a/b').root, '//')
695
696 def test_eq(self):
697 P = self.cls
698 self.assertNotEqual(P('a/b'), P('A/b'))
699 self.assertEqual(P('/a'), P('///a'))
700 self.assertNotEqual(P('/a'), P('//a'))
701
702 def test_as_uri(self):
Antoine Pitrou31119e42013-11-22 17:38:12 +0100703 P = self.cls
704 self.assertEqual(P('/').as_uri(), 'file:///')
705 self.assertEqual(P('/a/b.c').as_uri(), 'file:///a/b.c')
706 self.assertEqual(P('/a/b%#c').as_uri(), 'file:///a/b%25%23c')
Antoine Pitrou29eac422013-11-22 17:57:03 +0100707
708 def test_as_uri_non_ascii(self):
709 from urllib.parse import quote_from_bytes
710 P = self.cls
711 try:
712 os.fsencode('\xe9')
713 except UnicodeEncodeError:
714 self.skipTest("\\xe9 cannot be encoded to the filesystem encoding")
Antoine Pitrou31119e42013-11-22 17:38:12 +0100715 self.assertEqual(P('/a/b\xe9').as_uri(),
716 'file:///a/b' + quote_from_bytes(os.fsencode('\xe9')))
717
718 def test_match(self):
719 P = self.cls
720 self.assertFalse(P('A.py').match('a.PY'))
721
722 def test_is_absolute(self):
723 P = self.cls
724 self.assertFalse(P().is_absolute())
725 self.assertFalse(P('a').is_absolute())
726 self.assertFalse(P('a/b/').is_absolute())
727 self.assertTrue(P('/').is_absolute())
728 self.assertTrue(P('/a').is_absolute())
729 self.assertTrue(P('/a/b/').is_absolute())
730 self.assertTrue(P('//a').is_absolute())
731 self.assertTrue(P('//a/b').is_absolute())
732
733 def test_is_reserved(self):
734 P = self.cls
735 self.assertIs(False, P('').is_reserved())
736 self.assertIs(False, P('/').is_reserved())
737 self.assertIs(False, P('/foo/bar').is_reserved())
738 self.assertIs(False, P('/dev/con/PRN/NUL').is_reserved())
739
740 def test_join(self):
741 P = self.cls
742 p = P('//a')
743 pp = p.joinpath('b')
744 self.assertEqual(pp, P('//a/b'))
745 pp = P('/a').joinpath('//c')
746 self.assertEqual(pp, P('//c'))
747 pp = P('//a').joinpath('/c')
748 self.assertEqual(pp, P('/c'))
749
750 def test_div(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100751 # Basically the same as joinpath().
Antoine Pitrou31119e42013-11-22 17:38:12 +0100752 P = self.cls
753 p = P('//a')
754 pp = p / 'b'
755 self.assertEqual(pp, P('//a/b'))
756 pp = P('/a') / '//c'
757 self.assertEqual(pp, P('//c'))
758 pp = P('//a') / '/c'
759 self.assertEqual(pp, P('/c'))
760
761
762class PureWindowsPathTest(_BasePurePathTest, unittest.TestCase):
763 cls = pathlib.PureWindowsPath
764
765 equivalences = _BasePurePathTest.equivalences.copy()
766 equivalences.update({
767 'c:a': [ ('c:', 'a'), ('c:', 'a/'), ('/', 'c:', 'a') ],
768 'c:/a': [
769 ('c:/', 'a'), ('c:', '/', 'a'), ('c:', '/a'),
770 ('/z', 'c:/', 'a'), ('//x/y', 'c:/', 'a'),
771 ],
772 '//a/b/': [ ('//a/b',) ],
773 '//a/b/c': [
774 ('//a/b', 'c'), ('//a/b/', 'c'),
775 ],
776 })
777
778 def test_str(self):
779 p = self.cls('a/b/c')
780 self.assertEqual(str(p), 'a\\b\\c')
781 p = self.cls('c:/a/b/c')
782 self.assertEqual(str(p), 'c:\\a\\b\\c')
783 p = self.cls('//a/b')
784 self.assertEqual(str(p), '\\\\a\\b\\')
785 p = self.cls('//a/b/c')
786 self.assertEqual(str(p), '\\\\a\\b\\c')
787 p = self.cls('//a/b/c/d')
788 self.assertEqual(str(p), '\\\\a\\b\\c\\d')
789
Antoine Pitroucb5ec772014-04-23 00:34:15 +0200790 def test_str_subclass(self):
791 self._check_str_subclass('c:')
792 self._check_str_subclass('c:a')
793 self._check_str_subclass('c:a\\b.txt')
794 self._check_str_subclass('c:\\')
795 self._check_str_subclass('c:\\a')
796 self._check_str_subclass('c:\\a\\b.txt')
797 self._check_str_subclass('\\\\some\\share')
798 self._check_str_subclass('\\\\some\\share\\a')
799 self._check_str_subclass('\\\\some\\share\\a\\b.txt')
800
Antoine Pitrou31119e42013-11-22 17:38:12 +0100801 def test_eq(self):
802 P = self.cls
803 self.assertEqual(P('c:a/b'), P('c:a/b'))
804 self.assertEqual(P('c:a/b'), P('c:', 'a', 'b'))
805 self.assertNotEqual(P('c:a/b'), P('d:a/b'))
806 self.assertNotEqual(P('c:a/b'), P('c:/a/b'))
807 self.assertNotEqual(P('/a/b'), P('c:/a/b'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100808 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100809 self.assertEqual(P('a/B'), P('A/b'))
810 self.assertEqual(P('C:a/B'), P('c:A/b'))
811 self.assertEqual(P('//Some/SHARE/a/B'), P('//somE/share/A/b'))
812
813 def test_as_uri(self):
Antoine Pitrou31119e42013-11-22 17:38:12 +0100814 P = self.cls
815 with self.assertRaises(ValueError):
816 P('/a/b').as_uri()
817 with self.assertRaises(ValueError):
818 P('c:a/b').as_uri()
819 self.assertEqual(P('c:/').as_uri(), 'file:///c:/')
820 self.assertEqual(P('c:/a/b.c').as_uri(), 'file:///c:/a/b.c')
821 self.assertEqual(P('c:/a/b%#c').as_uri(), 'file:///c:/a/b%25%23c')
822 self.assertEqual(P('c:/a/b\xe9').as_uri(), 'file:///c:/a/b%C3%A9')
823 self.assertEqual(P('//some/share/').as_uri(), 'file://some/share/')
824 self.assertEqual(P('//some/share/a/b.c').as_uri(),
825 'file://some/share/a/b.c')
826 self.assertEqual(P('//some/share/a/b%#c\xe9').as_uri(),
827 'file://some/share/a/b%25%23c%C3%A9')
828
829 def test_match_common(self):
830 P = self.cls
Anthony Shaw83da9262019-01-07 07:31:29 +1100831 # Absolute patterns.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100832 self.assertTrue(P('c:/b.py').match('/*.py'))
833 self.assertTrue(P('c:/b.py').match('c:*.py'))
834 self.assertTrue(P('c:/b.py').match('c:/*.py'))
835 self.assertFalse(P('d:/b.py').match('c:/*.py')) # wrong drive
836 self.assertFalse(P('b.py').match('/*.py'))
837 self.assertFalse(P('b.py').match('c:*.py'))
838 self.assertFalse(P('b.py').match('c:/*.py'))
839 self.assertFalse(P('c:b.py').match('/*.py'))
840 self.assertFalse(P('c:b.py').match('c:/*.py'))
841 self.assertFalse(P('/b.py').match('c:*.py'))
842 self.assertFalse(P('/b.py').match('c:/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100843 # UNC patterns.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100844 self.assertTrue(P('//some/share/a.py').match('/*.py'))
845 self.assertTrue(P('//some/share/a.py').match('//some/share/*.py'))
846 self.assertFalse(P('//other/share/a.py').match('//some/share/*.py'))
847 self.assertFalse(P('//some/share/a/b.py').match('//some/share/*.py'))
Anthony Shaw83da9262019-01-07 07:31:29 +1100848 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100849 self.assertTrue(P('B.py').match('b.PY'))
850 self.assertTrue(P('c:/a/B.Py').match('C:/A/*.pY'))
851 self.assertTrue(P('//Some/Share/B.Py').match('//somE/sharE/*.pY'))
852
853 def test_ordering_common(self):
Anthony Shaw83da9262019-01-07 07:31:29 +1100854 # Case-insensitivity.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100855 def assertOrderedEqual(a, b):
856 self.assertLessEqual(a, b)
857 self.assertGreaterEqual(b, a)
858 P = self.cls
859 p = P('c:A/b')
860 q = P('C:a/B')
861 assertOrderedEqual(p, q)
862 self.assertFalse(p < q)
863 self.assertFalse(p > q)
864 p = P('//some/Share/A/b')
865 q = P('//Some/SHARE/a/B')
866 assertOrderedEqual(p, q)
867 self.assertFalse(p < q)
868 self.assertFalse(p > q)
869
870 def test_parts(self):
871 P = self.cls
872 p = P('c:a/b')
873 parts = p.parts
874 self.assertEqual(parts, ('c:', 'a', 'b'))
875 p = P('c:/a/b')
876 parts = p.parts
877 self.assertEqual(parts, ('c:\\', 'a', 'b'))
878 p = P('//a/b/c/d')
879 parts = p.parts
880 self.assertEqual(parts, ('\\\\a\\b\\', 'c', 'd'))
881
882 def test_parent(self):
883 # Anchored
884 P = self.cls
885 p = P('z:a/b/c')
886 self.assertEqual(p.parent, P('z:a/b'))
887 self.assertEqual(p.parent.parent, P('z:a'))
888 self.assertEqual(p.parent.parent.parent, P('z:'))
889 self.assertEqual(p.parent.parent.parent.parent, P('z:'))
890 p = P('z:/a/b/c')
891 self.assertEqual(p.parent, P('z:/a/b'))
892 self.assertEqual(p.parent.parent, P('z:/a'))
893 self.assertEqual(p.parent.parent.parent, P('z:/'))
894 self.assertEqual(p.parent.parent.parent.parent, P('z:/'))
895 p = P('//a/b/c/d')
896 self.assertEqual(p.parent, P('//a/b/c'))
897 self.assertEqual(p.parent.parent, P('//a/b'))
898 self.assertEqual(p.parent.parent.parent, P('//a/b'))
899
900 def test_parents(self):
901 # Anchored
902 P = self.cls
903 p = P('z:a/b/')
904 par = p.parents
905 self.assertEqual(len(par), 2)
906 self.assertEqual(par[0], P('z:a'))
907 self.assertEqual(par[1], P('z:'))
908 self.assertEqual(list(par), [P('z:a'), P('z:')])
909 with self.assertRaises(IndexError):
910 par[2]
911 p = P('z:/a/b/')
912 par = p.parents
913 self.assertEqual(len(par), 2)
914 self.assertEqual(par[0], P('z:/a'))
915 self.assertEqual(par[1], P('z:/'))
916 self.assertEqual(list(par), [P('z:/a'), P('z:/')])
917 with self.assertRaises(IndexError):
918 par[2]
919 p = P('//a/b/c/d')
920 par = p.parents
921 self.assertEqual(len(par), 2)
922 self.assertEqual(par[0], P('//a/b/c'))
923 self.assertEqual(par[1], P('//a/b'))
924 self.assertEqual(list(par), [P('//a/b/c'), P('//a/b')])
925 with self.assertRaises(IndexError):
926 par[2]
927
928 def test_drive(self):
929 P = self.cls
930 self.assertEqual(P('c:').drive, 'c:')
931 self.assertEqual(P('c:a/b').drive, 'c:')
932 self.assertEqual(P('c:/').drive, 'c:')
933 self.assertEqual(P('c:/a/b/').drive, 'c:')
934 self.assertEqual(P('//a/b').drive, '\\\\a\\b')
935 self.assertEqual(P('//a/b/').drive, '\\\\a\\b')
936 self.assertEqual(P('//a/b/c/d').drive, '\\\\a\\b')
937
938 def test_root(self):
939 P = self.cls
940 self.assertEqual(P('c:').root, '')
941 self.assertEqual(P('c:a/b').root, '')
942 self.assertEqual(P('c:/').root, '\\')
943 self.assertEqual(P('c:/a/b/').root, '\\')
944 self.assertEqual(P('//a/b').root, '\\')
945 self.assertEqual(P('//a/b/').root, '\\')
946 self.assertEqual(P('//a/b/c/d').root, '\\')
947
948 def test_anchor(self):
949 P = self.cls
950 self.assertEqual(P('c:').anchor, 'c:')
951 self.assertEqual(P('c:a/b').anchor, 'c:')
952 self.assertEqual(P('c:/').anchor, 'c:\\')
953 self.assertEqual(P('c:/a/b/').anchor, 'c:\\')
954 self.assertEqual(P('//a/b').anchor, '\\\\a\\b\\')
955 self.assertEqual(P('//a/b/').anchor, '\\\\a\\b\\')
956 self.assertEqual(P('//a/b/c/d').anchor, '\\\\a\\b\\')
957
958 def test_name(self):
959 P = self.cls
960 self.assertEqual(P('c:').name, '')
961 self.assertEqual(P('c:/').name, '')
962 self.assertEqual(P('c:a/b').name, 'b')
963 self.assertEqual(P('c:/a/b').name, 'b')
964 self.assertEqual(P('c:a/b.py').name, 'b.py')
965 self.assertEqual(P('c:/a/b.py').name, 'b.py')
966 self.assertEqual(P('//My.py/Share.php').name, '')
967 self.assertEqual(P('//My.py/Share.php/a/b').name, 'b')
968
969 def test_suffix(self):
970 P = self.cls
971 self.assertEqual(P('c:').suffix, '')
972 self.assertEqual(P('c:/').suffix, '')
973 self.assertEqual(P('c:a/b').suffix, '')
974 self.assertEqual(P('c:/a/b').suffix, '')
975 self.assertEqual(P('c:a/b.py').suffix, '.py')
976 self.assertEqual(P('c:/a/b.py').suffix, '.py')
977 self.assertEqual(P('c:a/.hgrc').suffix, '')
978 self.assertEqual(P('c:/a/.hgrc').suffix, '')
979 self.assertEqual(P('c:a/.hg.rc').suffix, '.rc')
980 self.assertEqual(P('c:/a/.hg.rc').suffix, '.rc')
981 self.assertEqual(P('c:a/b.tar.gz').suffix, '.gz')
982 self.assertEqual(P('c:/a/b.tar.gz').suffix, '.gz')
983 self.assertEqual(P('c:a/Some name. Ending with a dot.').suffix, '')
984 self.assertEqual(P('c:/a/Some name. Ending with a dot.').suffix, '')
985 self.assertEqual(P('//My.py/Share.php').suffix, '')
986 self.assertEqual(P('//My.py/Share.php/a/b').suffix, '')
987
988 def test_suffixes(self):
989 P = self.cls
990 self.assertEqual(P('c:').suffixes, [])
991 self.assertEqual(P('c:/').suffixes, [])
992 self.assertEqual(P('c:a/b').suffixes, [])
993 self.assertEqual(P('c:/a/b').suffixes, [])
994 self.assertEqual(P('c:a/b.py').suffixes, ['.py'])
995 self.assertEqual(P('c:/a/b.py').suffixes, ['.py'])
996 self.assertEqual(P('c:a/.hgrc').suffixes, [])
997 self.assertEqual(P('c:/a/.hgrc').suffixes, [])
998 self.assertEqual(P('c:a/.hg.rc').suffixes, ['.rc'])
999 self.assertEqual(P('c:/a/.hg.rc').suffixes, ['.rc'])
1000 self.assertEqual(P('c:a/b.tar.gz').suffixes, ['.tar', '.gz'])
1001 self.assertEqual(P('c:/a/b.tar.gz').suffixes, ['.tar', '.gz'])
1002 self.assertEqual(P('//My.py/Share.php').suffixes, [])
1003 self.assertEqual(P('//My.py/Share.php/a/b').suffixes, [])
1004 self.assertEqual(P('c:a/Some name. Ending with a dot.').suffixes, [])
1005 self.assertEqual(P('c:/a/Some name. Ending with a dot.').suffixes, [])
1006
1007 def test_stem(self):
1008 P = self.cls
1009 self.assertEqual(P('c:').stem, '')
1010 self.assertEqual(P('c:.').stem, '')
1011 self.assertEqual(P('c:..').stem, '..')
1012 self.assertEqual(P('c:/').stem, '')
1013 self.assertEqual(P('c:a/b').stem, 'b')
1014 self.assertEqual(P('c:a/b.py').stem, 'b')
1015 self.assertEqual(P('c:a/.hgrc').stem, '.hgrc')
1016 self.assertEqual(P('c:a/.hg.rc').stem, '.hg')
1017 self.assertEqual(P('c:a/b.tar.gz').stem, 'b.tar')
1018 self.assertEqual(P('c:a/Some name. Ending with a dot.').stem,
1019 'Some name. Ending with a dot.')
1020
1021 def test_with_name(self):
1022 P = self.cls
1023 self.assertEqual(P('c:a/b').with_name('d.xml'), P('c:a/d.xml'))
1024 self.assertEqual(P('c:/a/b').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.assertEqual(P('c:/a/Dot ending.').with_name('d.xml'), P('c:/a/d.xml'))
1027 self.assertRaises(ValueError, P('c:').with_name, 'd.xml')
1028 self.assertRaises(ValueError, P('c:/').with_name, 'd.xml')
1029 self.assertRaises(ValueError, P('//My/Share').with_name, 'd.xml')
Antoine Pitrou7084e732014-07-06 21:31:12 -04001030 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:')
1031 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:e')
1032 self.assertRaises(ValueError, P('c:a/b').with_name, 'd:/e')
1033 self.assertRaises(ValueError, P('c:a/b').with_name, '//My/Share')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001034
Tim Hoffmann8aea4b32020-04-19 17:29:49 +02001035 def test_with_stem(self):
1036 P = self.cls
1037 self.assertEqual(P('c:a/b').with_stem('d'), P('c:a/d'))
1038 self.assertEqual(P('c:/a/b').with_stem('d'), P('c:/a/d'))
1039 self.assertEqual(P('c:a/Dot ending.').with_stem('d'), P('c:a/d'))
1040 self.assertEqual(P('c:/a/Dot ending.').with_stem('d'), P('c:/a/d'))
1041 self.assertRaises(ValueError, P('c:').with_stem, 'd')
1042 self.assertRaises(ValueError, P('c:/').with_stem, 'd')
1043 self.assertRaises(ValueError, P('//My/Share').with_stem, 'd')
1044 self.assertRaises(ValueError, P('c:a/b').with_stem, 'd:')
1045 self.assertRaises(ValueError, P('c:a/b').with_stem, 'd:e')
1046 self.assertRaises(ValueError, P('c:a/b').with_stem, 'd:/e')
1047 self.assertRaises(ValueError, P('c:a/b').with_stem, '//My/Share')
1048
Antoine Pitrou31119e42013-11-22 17:38:12 +01001049 def test_with_suffix(self):
1050 P = self.cls
1051 self.assertEqual(P('c:a/b').with_suffix('.gz'), P('c:a/b.gz'))
1052 self.assertEqual(P('c:/a/b').with_suffix('.gz'), P('c:/a/b.gz'))
1053 self.assertEqual(P('c:a/b.py').with_suffix('.gz'), P('c:a/b.gz'))
1054 self.assertEqual(P('c:/a/b.py').with_suffix('.gz'), P('c:/a/b.gz'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001055 # Path doesn't have a "filename" component.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001056 self.assertRaises(ValueError, P('').with_suffix, '.gz')
1057 self.assertRaises(ValueError, P('.').with_suffix, '.gz')
1058 self.assertRaises(ValueError, P('/').with_suffix, '.gz')
1059 self.assertRaises(ValueError, P('//My/Share').with_suffix, '.gz')
Anthony Shaw83da9262019-01-07 07:31:29 +11001060 # Invalid suffix.
Antoine Pitrou1b02da92014-01-03 00:07:17 +01001061 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'gz')
1062 self.assertRaises(ValueError, P('c:a/b').with_suffix, '/')
1063 self.assertRaises(ValueError, P('c:a/b').with_suffix, '\\')
1064 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c:')
1065 self.assertRaises(ValueError, P('c:a/b').with_suffix, '/.gz')
1066 self.assertRaises(ValueError, P('c:a/b').with_suffix, '\\.gz')
1067 self.assertRaises(ValueError, P('c:a/b').with_suffix, 'c:.gz')
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')
1071 self.assertRaises(ValueError, P('c:a/b').with_suffix, '.c\\d')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001072
1073 def test_relative_to(self):
1074 P = self.cls
Antoine Pitrou156b3612013-12-28 19:49:04 +01001075 p = P('C:Foo/Bar')
1076 self.assertEqual(p.relative_to(P('c:')), P('Foo/Bar'))
1077 self.assertEqual(p.relative_to('c:'), P('Foo/Bar'))
1078 self.assertEqual(p.relative_to(P('c:foO')), P('Bar'))
1079 self.assertEqual(p.relative_to('c:foO'), P('Bar'))
1080 self.assertEqual(p.relative_to('c:foO/'), P('Bar'))
1081 self.assertEqual(p.relative_to(P('c:foO/baR')), P())
1082 self.assertEqual(p.relative_to('c:foO/baR'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001083 # Unrelated paths.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001084 self.assertRaises(ValueError, p.relative_to, P())
Antoine Pitrou156b3612013-12-28 19:49:04 +01001085 self.assertRaises(ValueError, p.relative_to, '')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001086 self.assertRaises(ValueError, p.relative_to, P('d:'))
Antoine Pitrou156b3612013-12-28 19:49:04 +01001087 self.assertRaises(ValueError, p.relative_to, P('/'))
1088 self.assertRaises(ValueError, p.relative_to, P('Foo'))
1089 self.assertRaises(ValueError, p.relative_to, P('/Foo'))
1090 self.assertRaises(ValueError, p.relative_to, P('C:/Foo'))
1091 self.assertRaises(ValueError, p.relative_to, P('C:Foo/Bar/Baz'))
1092 self.assertRaises(ValueError, p.relative_to, P('C:Foo/Baz'))
1093 p = P('C:/Foo/Bar')
1094 self.assertEqual(p.relative_to(P('c:')), P('/Foo/Bar'))
1095 self.assertEqual(p.relative_to('c:'), P('/Foo/Bar'))
1096 self.assertEqual(str(p.relative_to(P('c:'))), '\\Foo\\Bar')
1097 self.assertEqual(str(p.relative_to('c:')), '\\Foo\\Bar')
1098 self.assertEqual(p.relative_to(P('c:/')), P('Foo/Bar'))
1099 self.assertEqual(p.relative_to('c:/'), P('Foo/Bar'))
1100 self.assertEqual(p.relative_to(P('c:/foO')), P('Bar'))
1101 self.assertEqual(p.relative_to('c:/foO'), P('Bar'))
1102 self.assertEqual(p.relative_to('c:/foO/'), P('Bar'))
1103 self.assertEqual(p.relative_to(P('c:/foO/baR')), P())
1104 self.assertEqual(p.relative_to('c:/foO/baR'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001105 # Unrelated paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001106 self.assertRaises(ValueError, p.relative_to, P('C:/Baz'))
1107 self.assertRaises(ValueError, p.relative_to, P('C:/Foo/Bar/Baz'))
1108 self.assertRaises(ValueError, p.relative_to, P('C:/Foo/Baz'))
1109 self.assertRaises(ValueError, p.relative_to, P('C:Foo'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001110 self.assertRaises(ValueError, p.relative_to, P('d:'))
1111 self.assertRaises(ValueError, p.relative_to, P('d:/'))
Antoine Pitrou156b3612013-12-28 19:49:04 +01001112 self.assertRaises(ValueError, p.relative_to, P('/'))
1113 self.assertRaises(ValueError, p.relative_to, P('/Foo'))
1114 self.assertRaises(ValueError, p.relative_to, P('//C/Foo'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001115 # UNC paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001116 p = P('//Server/Share/Foo/Bar')
1117 self.assertEqual(p.relative_to(P('//sErver/sHare')), P('Foo/Bar'))
1118 self.assertEqual(p.relative_to('//sErver/sHare'), P('Foo/Bar'))
1119 self.assertEqual(p.relative_to('//sErver/sHare/'), P('Foo/Bar'))
1120 self.assertEqual(p.relative_to(P('//sErver/sHare/Foo')), P('Bar'))
1121 self.assertEqual(p.relative_to('//sErver/sHare/Foo'), P('Bar'))
1122 self.assertEqual(p.relative_to('//sErver/sHare/Foo/'), P('Bar'))
1123 self.assertEqual(p.relative_to(P('//sErver/sHare/Foo/Bar')), P())
1124 self.assertEqual(p.relative_to('//sErver/sHare/Foo/Bar'), P())
Anthony Shaw83da9262019-01-07 07:31:29 +11001125 # Unrelated paths.
Antoine Pitrou156b3612013-12-28 19:49:04 +01001126 self.assertRaises(ValueError, p.relative_to, P('/Server/Share/Foo'))
1127 self.assertRaises(ValueError, p.relative_to, P('c:/Server/Share/Foo'))
1128 self.assertRaises(ValueError, p.relative_to, P('//z/Share/Foo'))
1129 self.assertRaises(ValueError, p.relative_to, P('//Server/z/Foo'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001130
Hai Shi82642a02019-08-13 14:54:02 -05001131 def test_is_relative_to(self):
1132 P = self.cls
1133 p = P('C:Foo/Bar')
1134 self.assertTrue(p.is_relative_to(P('c:')))
1135 self.assertTrue(p.is_relative_to('c:'))
1136 self.assertTrue(p.is_relative_to(P('c:foO')))
1137 self.assertTrue(p.is_relative_to('c:foO'))
1138 self.assertTrue(p.is_relative_to('c:foO/'))
1139 self.assertTrue(p.is_relative_to(P('c:foO/baR')))
1140 self.assertTrue(p.is_relative_to('c:foO/baR'))
1141 # Unrelated paths.
1142 self.assertFalse(p.is_relative_to(P()))
1143 self.assertFalse(p.is_relative_to(''))
1144 self.assertFalse(p.is_relative_to(P('d:')))
1145 self.assertFalse(p.is_relative_to(P('/')))
1146 self.assertFalse(p.is_relative_to(P('Foo')))
1147 self.assertFalse(p.is_relative_to(P('/Foo')))
1148 self.assertFalse(p.is_relative_to(P('C:/Foo')))
1149 self.assertFalse(p.is_relative_to(P('C:Foo/Bar/Baz')))
1150 self.assertFalse(p.is_relative_to(P('C:Foo/Baz')))
1151 p = P('C:/Foo/Bar')
1152 self.assertTrue(p.is_relative_to('c:'))
1153 self.assertTrue(p.is_relative_to(P('c:/')))
1154 self.assertTrue(p.is_relative_to(P('c:/foO')))
1155 self.assertTrue(p.is_relative_to('c:/foO/'))
1156 self.assertTrue(p.is_relative_to(P('c:/foO/baR')))
1157 self.assertTrue(p.is_relative_to('c:/foO/baR'))
1158 # Unrelated paths.
1159 self.assertFalse(p.is_relative_to(P('C:/Baz')))
1160 self.assertFalse(p.is_relative_to(P('C:/Foo/Bar/Baz')))
1161 self.assertFalse(p.is_relative_to(P('C:/Foo/Baz')))
1162 self.assertFalse(p.is_relative_to(P('C:Foo')))
1163 self.assertFalse(p.is_relative_to(P('d:')))
1164 self.assertFalse(p.is_relative_to(P('d:/')))
1165 self.assertFalse(p.is_relative_to(P('/')))
1166 self.assertFalse(p.is_relative_to(P('/Foo')))
1167 self.assertFalse(p.is_relative_to(P('//C/Foo')))
1168 # UNC paths.
1169 p = P('//Server/Share/Foo/Bar')
1170 self.assertTrue(p.is_relative_to(P('//sErver/sHare')))
1171 self.assertTrue(p.is_relative_to('//sErver/sHare'))
1172 self.assertTrue(p.is_relative_to('//sErver/sHare/'))
1173 self.assertTrue(p.is_relative_to(P('//sErver/sHare/Foo')))
1174 self.assertTrue(p.is_relative_to('//sErver/sHare/Foo'))
1175 self.assertTrue(p.is_relative_to('//sErver/sHare/Foo/'))
1176 self.assertTrue(p.is_relative_to(P('//sErver/sHare/Foo/Bar')))
1177 self.assertTrue(p.is_relative_to('//sErver/sHare/Foo/Bar'))
1178 # Unrelated paths.
1179 self.assertFalse(p.is_relative_to(P('/Server/Share/Foo')))
1180 self.assertFalse(p.is_relative_to(P('c:/Server/Share/Foo')))
1181 self.assertFalse(p.is_relative_to(P('//z/Share/Foo')))
1182 self.assertFalse(p.is_relative_to(P('//Server/z/Foo')))
1183
Antoine Pitrou31119e42013-11-22 17:38:12 +01001184 def test_is_absolute(self):
1185 P = self.cls
Anthony Shaw83da9262019-01-07 07:31:29 +11001186 # Under NT, only paths with both a drive and a root are absolute.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001187 self.assertFalse(P().is_absolute())
1188 self.assertFalse(P('a').is_absolute())
1189 self.assertFalse(P('a/b/').is_absolute())
1190 self.assertFalse(P('/').is_absolute())
1191 self.assertFalse(P('/a').is_absolute())
1192 self.assertFalse(P('/a/b/').is_absolute())
1193 self.assertFalse(P('c:').is_absolute())
1194 self.assertFalse(P('c:a').is_absolute())
1195 self.assertFalse(P('c:a/b/').is_absolute())
1196 self.assertTrue(P('c:/').is_absolute())
1197 self.assertTrue(P('c:/a').is_absolute())
1198 self.assertTrue(P('c:/a/b/').is_absolute())
Anthony Shaw83da9262019-01-07 07:31:29 +11001199 # UNC paths are absolute by definition.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001200 self.assertTrue(P('//a/b').is_absolute())
1201 self.assertTrue(P('//a/b/').is_absolute())
1202 self.assertTrue(P('//a/b/c').is_absolute())
1203 self.assertTrue(P('//a/b/c/d').is_absolute())
1204
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001205 def test_join(self):
1206 P = self.cls
1207 p = P('C:/a/b')
1208 pp = p.joinpath('x/y')
1209 self.assertEqual(pp, P('C:/a/b/x/y'))
1210 pp = p.joinpath('/x/y')
1211 self.assertEqual(pp, P('C:/x/y'))
1212 # Joining with a different drive => the first path is ignored, even
1213 # if the second path is relative.
1214 pp = p.joinpath('D:x/y')
1215 self.assertEqual(pp, P('D:x/y'))
1216 pp = p.joinpath('D:/x/y')
1217 self.assertEqual(pp, P('D:/x/y'))
1218 pp = p.joinpath('//host/share/x/y')
1219 self.assertEqual(pp, P('//host/share/x/y'))
1220 # Joining with the same drive => the first path is appended to if
1221 # the second path is relative.
1222 pp = p.joinpath('c:x/y')
1223 self.assertEqual(pp, P('C:/a/b/x/y'))
1224 pp = p.joinpath('c:/x/y')
1225 self.assertEqual(pp, P('C:/x/y'))
1226
1227 def test_div(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001228 # Basically the same as joinpath().
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001229 P = self.cls
1230 p = P('C:/a/b')
1231 self.assertEqual(p / 'x/y', P('C:/a/b/x/y'))
1232 self.assertEqual(p / 'x' / 'y', P('C:/a/b/x/y'))
1233 self.assertEqual(p / '/x/y', P('C:/x/y'))
1234 self.assertEqual(p / '/x' / 'y', P('C:/x/y'))
1235 # Joining with a different drive => the first path is ignored, even
1236 # if the second path is relative.
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 / 'D:' / '/x/y', P('D:/x/y'))
1241 self.assertEqual(p / '//host/share/x/y', P('//host/share/x/y'))
1242 # Joining with the same drive => the first path is appended to if
1243 # the second path is relative.
Serhiy Storchaka010ff582013-12-06 17:25:51 +02001244 self.assertEqual(p / 'c:x/y', P('C:/a/b/x/y'))
1245 self.assertEqual(p / 'c:/x/y', P('C:/x/y'))
Serhiy Storchakaa9939022013-12-06 17:14:12 +02001246
Antoine Pitrou31119e42013-11-22 17:38:12 +01001247 def test_is_reserved(self):
1248 P = self.cls
1249 self.assertIs(False, P('').is_reserved())
1250 self.assertIs(False, P('/').is_reserved())
1251 self.assertIs(False, P('/foo/bar').is_reserved())
1252 self.assertIs(True, P('con').is_reserved())
1253 self.assertIs(True, P('NUL').is_reserved())
1254 self.assertIs(True, P('NUL.txt').is_reserved())
1255 self.assertIs(True, P('com1').is_reserved())
1256 self.assertIs(True, P('com9.bar').is_reserved())
1257 self.assertIs(False, P('bar.com9').is_reserved())
1258 self.assertIs(True, P('lpt1').is_reserved())
1259 self.assertIs(True, P('lpt9.bar').is_reserved())
1260 self.assertIs(False, P('bar.lpt9').is_reserved())
Anthony Shaw83da9262019-01-07 07:31:29 +11001261 # Only the last component matters.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001262 self.assertIs(False, P('c:/NUL/con/baz').is_reserved())
Anthony Shaw83da9262019-01-07 07:31:29 +11001263 # UNC paths are never reserved.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001264 self.assertIs(False, P('//my/share/nul/con/aux').is_reserved())
1265
Antoine Pitrou31119e42013-11-22 17:38:12 +01001266class PurePathTest(_BasePurePathTest, unittest.TestCase):
1267 cls = pathlib.PurePath
1268
1269 def test_concrete_class(self):
1270 p = self.cls('a')
1271 self.assertIs(type(p),
1272 pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath)
1273
1274 def test_different_flavours_unequal(self):
1275 p = pathlib.PurePosixPath('a')
1276 q = pathlib.PureWindowsPath('a')
1277 self.assertNotEqual(p, q)
1278
1279 def test_different_flavours_unordered(self):
1280 p = pathlib.PurePosixPath('a')
1281 q = pathlib.PureWindowsPath('a')
1282 with self.assertRaises(TypeError):
1283 p < q
1284 with self.assertRaises(TypeError):
1285 p <= q
1286 with self.assertRaises(TypeError):
1287 p > q
1288 with self.assertRaises(TypeError):
1289 p >= q
1290
1291
1292#
Anthony Shaw83da9262019-01-07 07:31:29 +11001293# Tests for the concrete classes.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001294#
1295
Anthony Shaw83da9262019-01-07 07:31:29 +11001296# Make sure any symbolic links in the base test path are resolved.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001297BASE = os.path.realpath(TESTFN)
1298join = lambda *x: os.path.join(BASE, *x)
1299rel_join = lambda *x: os.path.join(TESTFN, *x)
1300
Antoine Pitrou31119e42013-11-22 17:38:12 +01001301only_nt = unittest.skipIf(os.name != 'nt',
1302 'test requires a Windows-compatible system')
1303only_posix = unittest.skipIf(os.name == 'nt',
1304 'test requires a POSIX-compatible system')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001305
1306@only_posix
1307class PosixPathAsPureTest(PurePosixPathTest):
1308 cls = pathlib.PosixPath
1309
1310@only_nt
1311class WindowsPathAsPureTest(PureWindowsPathTest):
1312 cls = pathlib.WindowsPath
1313
Victor Stinnerd7569632016-03-11 22:53:00 +01001314 def test_owner(self):
1315 P = self.cls
1316 with self.assertRaises(NotImplementedError):
1317 P('c:/').owner()
1318
1319 def test_group(self):
1320 P = self.cls
1321 with self.assertRaises(NotImplementedError):
1322 P('c:/').group()
1323
Antoine Pitrou31119e42013-11-22 17:38:12 +01001324
1325class _BasePathTest(object):
1326 """Tests for the FS-accessing functionalities of the Path classes."""
1327
1328 # (BASE)
1329 # |
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001330 # |-- brokenLink -> non-existing
1331 # |-- dirA
1332 # | `-- linkC -> ../dirB
1333 # |-- dirB
1334 # | |-- fileB
1335 # | `-- linkD -> ../dirB
1336 # |-- dirC
1337 # | |-- dirD
1338 # | | `-- fileD
1339 # | `-- fileC
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001340 # |-- dirE # No permissions
Antoine Pitrou31119e42013-11-22 17:38:12 +01001341 # |-- fileA
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001342 # |-- linkA -> fileA
Jörg Stucked5c120f2019-05-21 19:44:40 +02001343 # |-- linkB -> dirB
1344 # `-- brokenLinkLoop -> brokenLinkLoop
Antoine Pitrou31119e42013-11-22 17:38:12 +01001345 #
1346
1347 def setUp(self):
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001348 def cleanup():
1349 os.chmod(join('dirE'), 0o777)
Hai Shibb0424b2020-08-04 00:47:42 +08001350 os_helper.rmtree(BASE)
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001351 self.addCleanup(cleanup)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001352 os.mkdir(BASE)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001353 os.mkdir(join('dirA'))
1354 os.mkdir(join('dirB'))
1355 os.mkdir(join('dirC'))
1356 os.mkdir(join('dirC', 'dirD'))
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001357 os.mkdir(join('dirE'))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001358 with open(join('fileA'), 'wb') as f:
1359 f.write(b"this is file A\n")
1360 with open(join('dirB', 'fileB'), 'wb') as f:
1361 f.write(b"this is file B\n")
1362 with open(join('dirC', 'fileC'), 'wb') as f:
1363 f.write(b"this is file C\n")
1364 with open(join('dirC', 'dirD', 'fileD'), 'wb') as f:
1365 f.write(b"this is file D\n")
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001366 os.chmod(join('dirE'), 0)
Hai Shibb0424b2020-08-04 00:47:42 +08001367 if os_helper.can_symlink():
Anthony Shaw83da9262019-01-07 07:31:29 +11001368 # Relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001369 os.symlink('fileA', join('linkA'))
1370 os.symlink('non-existing', join('brokenLink'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001371 self.dirlink('dirB', join('linkB'))
1372 self.dirlink(os.path.join('..', 'dirB'), join('dirA', 'linkC'))
Anthony Shaw83da9262019-01-07 07:31:29 +11001373 # This one goes upwards, creating a loop.
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001374 self.dirlink(os.path.join('..', 'dirB'), join('dirB', 'linkD'))
Jörg Stucked5c120f2019-05-21 19:44:40 +02001375 # Broken symlink (pointing to itself).
1376 os.symlink('brokenLinkLoop', join('brokenLinkLoop'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001377
1378 if os.name == 'nt':
Anthony Shaw83da9262019-01-07 07:31:29 +11001379 # Workaround for http://bugs.python.org/issue13772.
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001380 def dirlink(self, src, dest):
1381 os.symlink(src, dest, target_is_directory=True)
1382 else:
1383 def dirlink(self, src, dest):
1384 os.symlink(src, dest)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001385
1386 def assertSame(self, path_a, path_b):
1387 self.assertTrue(os.path.samefile(str(path_a), str(path_b)),
1388 "%r and %r don't point to the same file" %
1389 (path_a, path_b))
1390
1391 def assertFileNotFound(self, func, *args, **kwargs):
1392 with self.assertRaises(FileNotFoundError) as cm:
1393 func(*args, **kwargs)
1394 self.assertEqual(cm.exception.errno, errno.ENOENT)
1395
Steve Dower97d79062019-09-10 14:52:48 +01001396 def assertEqualNormCase(self, path_a, path_b):
1397 self.assertEqual(os.path.normcase(path_a), os.path.normcase(path_b))
1398
Antoine Pitrou31119e42013-11-22 17:38:12 +01001399 def _test_cwd(self, p):
1400 q = self.cls(os.getcwd())
1401 self.assertEqual(p, q)
Steve Dower97d79062019-09-10 14:52:48 +01001402 self.assertEqualNormCase(str(p), str(q))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001403 self.assertIs(type(p), type(q))
1404 self.assertTrue(p.is_absolute())
1405
1406 def test_cwd(self):
1407 p = self.cls.cwd()
1408 self._test_cwd(p)
1409
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001410 def _test_home(self, p):
1411 q = self.cls(os.path.expanduser('~'))
1412 self.assertEqual(p, q)
Steve Dower97d79062019-09-10 14:52:48 +01001413 self.assertEqualNormCase(str(p), str(q))
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001414 self.assertIs(type(p), type(q))
1415 self.assertTrue(p.is_absolute())
1416
1417 def test_home(self):
Hai Shibb0424b2020-08-04 00:47:42 +08001418 with os_helper.EnvironmentVarGuard() as env:
Christoph Reiterc45a2aa2020-01-28 10:41:50 +01001419 self._test_home(self.cls.home())
1420
1421 env.clear()
1422 env['USERPROFILE'] = os.path.join(BASE, 'userprofile')
1423 self._test_home(self.cls.home())
1424
1425 # bpo-38883: ignore `HOME` when set on windows
1426 env['HOME'] = os.path.join(BASE, 'home')
1427 self._test_home(self.cls.home())
Antoine Pitrou17cba7d2015-01-12 21:03:41 +01001428
Antoine Pitrou43e3d942014-05-13 10:50:15 +02001429 def test_samefile(self):
1430 fileA_path = os.path.join(BASE, 'fileA')
1431 fileB_path = os.path.join(BASE, 'dirB', 'fileB')
1432 p = self.cls(fileA_path)
1433 pp = self.cls(fileA_path)
1434 q = self.cls(fileB_path)
1435 self.assertTrue(p.samefile(fileA_path))
1436 self.assertTrue(p.samefile(pp))
1437 self.assertFalse(p.samefile(fileB_path))
1438 self.assertFalse(p.samefile(q))
1439 # Test the non-existent file case
1440 non_existent = os.path.join(BASE, 'foo')
1441 r = self.cls(non_existent)
1442 self.assertRaises(FileNotFoundError, p.samefile, r)
1443 self.assertRaises(FileNotFoundError, p.samefile, non_existent)
1444 self.assertRaises(FileNotFoundError, r.samefile, p)
1445 self.assertRaises(FileNotFoundError, r.samefile, non_existent)
1446 self.assertRaises(FileNotFoundError, r.samefile, r)
1447 self.assertRaises(FileNotFoundError, r.samefile, non_existent)
1448
Antoine Pitrou31119e42013-11-22 17:38:12 +01001449 def test_empty_path(self):
1450 # The empty path points to '.'
1451 p = self.cls('')
1452 self.assertEqual(p.stat(), os.stat('.'))
1453
Antoine Pitrou8477ed62014-12-30 20:54:45 +01001454 def test_expanduser_common(self):
1455 P = self.cls
1456 p = P('~')
1457 self.assertEqual(p.expanduser(), P(os.path.expanduser('~')))
1458 p = P('foo')
1459 self.assertEqual(p.expanduser(), p)
1460 p = P('/~')
1461 self.assertEqual(p.expanduser(), p)
1462 p = P('../~')
1463 self.assertEqual(p.expanduser(), p)
1464 p = P(P('').absolute().anchor) / '~'
1465 self.assertEqual(p.expanduser(), p)
1466
Antoine Pitrou31119e42013-11-22 17:38:12 +01001467 def test_exists(self):
1468 P = self.cls
1469 p = P(BASE)
1470 self.assertIs(True, p.exists())
1471 self.assertIs(True, (p / 'dirA').exists())
1472 self.assertIs(True, (p / 'fileA').exists())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001473 self.assertIs(False, (p / 'fileA' / 'bah').exists())
Hai Shibb0424b2020-08-04 00:47:42 +08001474 if os_helper.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001475 self.assertIs(True, (p / 'linkA').exists())
1476 self.assertIs(True, (p / 'linkB').exists())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01001477 self.assertIs(True, (p / 'linkB' / 'fileB').exists())
1478 self.assertIs(False, (p / 'linkA' / 'bah').exists())
Antoine Pitrou31119e42013-11-22 17:38:12 +01001479 self.assertIs(False, (p / 'foo').exists())
1480 self.assertIs(False, P('/xyzzy').exists())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03001481 self.assertIs(False, P(BASE + '\udfff').exists())
1482 self.assertIs(False, P(BASE + '\x00').exists())
Antoine Pitrou31119e42013-11-22 17:38:12 +01001483
1484 def test_open_common(self):
1485 p = self.cls(BASE)
1486 with (p / 'fileA').open('r') as f:
1487 self.assertIsInstance(f, io.TextIOBase)
1488 self.assertEqual(f.read(), "this is file A\n")
1489 with (p / 'fileA').open('rb') as f:
1490 self.assertIsInstance(f, io.BufferedIOBase)
1491 self.assertEqual(f.read().strip(), b"this is file A")
1492 with (p / 'fileA').open('rb', buffering=0) as f:
1493 self.assertIsInstance(f, io.RawIOBase)
1494 self.assertEqual(f.read().strip(), b"this is file A")
1495
Georg Brandlea683982014-10-01 19:12:33 +02001496 def test_read_write_bytes(self):
1497 p = self.cls(BASE)
1498 (p / 'fileA').write_bytes(b'abcdefg')
1499 self.assertEqual((p / 'fileA').read_bytes(), b'abcdefg')
Anthony Shaw83da9262019-01-07 07:31:29 +11001500 # Check that trying to write str does not truncate the file.
Georg Brandlea683982014-10-01 19:12:33 +02001501 self.assertRaises(TypeError, (p / 'fileA').write_bytes, 'somestr')
1502 self.assertEqual((p / 'fileA').read_bytes(), b'abcdefg')
1503
1504 def test_read_write_text(self):
1505 p = self.cls(BASE)
1506 (p / 'fileA').write_text('äbcdefg', encoding='latin-1')
1507 self.assertEqual((p / 'fileA').read_text(
1508 encoding='utf-8', errors='ignore'), 'bcdefg')
Anthony Shaw83da9262019-01-07 07:31:29 +11001509 # Check that trying to write bytes does not truncate the file.
Georg Brandlea683982014-10-01 19:12:33 +02001510 self.assertRaises(TypeError, (p / 'fileA').write_text, b'somebytes')
1511 self.assertEqual((p / 'fileA').read_text(encoding='latin-1'), 'äbcdefg')
1512
Максим5f227412020-10-21 05:08:19 +03001513 def test_write_text_with_newlines(self):
1514 p = self.cls(BASE)
1515 # Check that `\n` character change nothing
1516 (p / 'fileA').write_text('abcde\r\nfghlk\n\rmnopq', newline='\n')
1517 self.assertEqual((p / 'fileA').read_bytes(),
1518 b'abcde\r\nfghlk\n\rmnopq')
1519 # Check that `\r` character replaces `\n`
1520 (p / 'fileA').write_text('abcde\r\nfghlk\n\rmnopq', newline='\r')
1521 self.assertEqual((p / 'fileA').read_bytes(),
1522 b'abcde\r\rfghlk\r\rmnopq')
1523 # Check that `\r\n` character replaces `\n`
1524 (p / 'fileA').write_text('abcde\r\nfghlk\n\rmnopq', newline='\r\n')
1525 self.assertEqual((p / 'fileA').read_bytes(),
1526 b'abcde\r\r\nfghlk\r\n\rmnopq')
1527 # Check that no argument passed will change `\n` to `os.linesep`
1528 os_linesep_byte = bytes(os.linesep, encoding='ascii')
1529 (p / 'fileA').write_text('abcde\nfghlk\n\rmnopq')
1530 self.assertEqual((p / 'fileA').read_bytes(),
1531 b'abcde' + os_linesep_byte + b'fghlk' + os_linesep_byte + b'\rmnopq')
1532
Antoine Pitrou31119e42013-11-22 17:38:12 +01001533 def test_iterdir(self):
1534 P = self.cls
1535 p = P(BASE)
1536 it = p.iterdir()
1537 paths = set(it)
Guido van Rossum6c2d33a2016-01-06 09:42:07 -08001538 expected = ['dirA', 'dirB', 'dirC', 'dirE', 'fileA']
Hai Shibb0424b2020-08-04 00:47:42 +08001539 if os_helper.can_symlink():
Jörg Stucked5c120f2019-05-21 19:44:40 +02001540 expected += ['linkA', 'linkB', 'brokenLink', 'brokenLinkLoop']
Antoine Pitrou31119e42013-11-22 17:38:12 +01001541 self.assertEqual(paths, { P(BASE, q) for q in expected })
1542
Hai Shibb0424b2020-08-04 00:47:42 +08001543 @os_helper.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001544 def test_iterdir_symlink(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001545 # __iter__ on a symlink to a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001546 P = self.cls
1547 p = P(BASE, 'linkB')
1548 paths = set(p.iterdir())
1549 expected = { P(BASE, 'linkB', q) for q in ['fileB', 'linkD'] }
1550 self.assertEqual(paths, expected)
1551
1552 def test_iterdir_nodir(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001553 # __iter__ on something that is not a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001554 p = self.cls(BASE, 'fileA')
1555 with self.assertRaises(OSError) as cm:
1556 next(p.iterdir())
1557 # ENOENT or EINVAL under Windows, ENOTDIR otherwise
Anthony Shaw83da9262019-01-07 07:31:29 +11001558 # (see issue #12802).
Antoine Pitrou31119e42013-11-22 17:38:12 +01001559 self.assertIn(cm.exception.errno, (errno.ENOTDIR,
1560 errno.ENOENT, errno.EINVAL))
1561
1562 def test_glob_common(self):
1563 def _check(glob, expected):
1564 self.assertEqual(set(glob), { P(BASE, q) for q in expected })
1565 P = self.cls
1566 p = P(BASE)
1567 it = p.glob("fileA")
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001568 self.assertIsInstance(it, collections.abc.Iterator)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001569 _check(it, ["fileA"])
1570 _check(p.glob("fileB"), [])
1571 _check(p.glob("dir*/file*"), ["dirB/fileB", "dirC/fileC"])
Hai Shibb0424b2020-08-04 00:47:42 +08001572 if not os_helper.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001573 _check(p.glob("*A"), ['dirA', 'fileA'])
1574 else:
1575 _check(p.glob("*A"), ['dirA', 'fileA', 'linkA'])
Hai Shibb0424b2020-08-04 00:47:42 +08001576 if not os_helper.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001577 _check(p.glob("*B/*"), ['dirB/fileB'])
1578 else:
1579 _check(p.glob("*B/*"), ['dirB/fileB', 'dirB/linkD',
1580 'linkB/fileB', 'linkB/linkD'])
Hai Shibb0424b2020-08-04 00:47:42 +08001581 if not os_helper.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01001582 _check(p.glob("*/fileB"), ['dirB/fileB'])
1583 else:
1584 _check(p.glob("*/fileB"), ['dirB/fileB', 'linkB/fileB'])
1585
1586 def test_rglob_common(self):
1587 def _check(glob, expected):
1588 self.assertEqual(set(glob), { P(BASE, q) for q in expected })
1589 P = self.cls
1590 p = P(BASE)
1591 it = p.rglob("fileA")
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001592 self.assertIsInstance(it, collections.abc.Iterator)
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001593 _check(it, ["fileA"])
1594 _check(p.rglob("fileB"), ["dirB/fileB"])
1595 _check(p.rglob("*/fileA"), [])
Hai Shibb0424b2020-08-04 00:47:42 +08001596 if not os_helper.can_symlink():
Guido van Rossum9c39b672016-01-07 13:12:34 -08001597 _check(p.rglob("*/fileB"), ["dirB/fileB"])
1598 else:
1599 _check(p.rglob("*/fileB"), ["dirB/fileB", "dirB/linkD/fileB",
1600 "linkB/fileB", "dirA/linkC/fileB"])
Guido van Rossumbc9fdda2016-01-07 10:56:36 -08001601 _check(p.rglob("file*"), ["fileA", "dirB/fileB",
1602 "dirC/fileC", "dirC/dirD/fileD"])
Antoine Pitrou31119e42013-11-22 17:38:12 +01001603 p = P(BASE, "dirC")
1604 _check(p.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"])
1605 _check(p.rglob("*/*"), ["dirC/dirD/fileD"])
1606
Hai Shibb0424b2020-08-04 00:47:42 +08001607 @os_helper.skip_unless_symlink
Guido van Rossum69bfb152016-01-06 10:31:33 -08001608 def test_rglob_symlink_loop(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001609 # Don't get fooled by symlink loops (Issue #26012).
Guido van Rossum69bfb152016-01-06 10:31:33 -08001610 P = self.cls
1611 p = P(BASE)
1612 given = set(p.rglob('*'))
1613 expect = {'brokenLink',
1614 'dirA', 'dirA/linkC',
1615 'dirB', 'dirB/fileB', 'dirB/linkD',
1616 'dirC', 'dirC/dirD', 'dirC/dirD/fileD', 'dirC/fileC',
1617 'dirE',
1618 'fileA',
1619 'linkA',
1620 'linkB',
Jörg Stucked5c120f2019-05-21 19:44:40 +02001621 'brokenLinkLoop',
Guido van Rossum69bfb152016-01-06 10:31:33 -08001622 }
1623 self.assertEqual(given, {p / x for x in expect})
1624
Serhiy Storchakaf9dc2ad2019-09-12 15:54:48 +03001625 def test_glob_many_open_files(self):
1626 depth = 30
1627 P = self.cls
1628 base = P(BASE) / 'deep'
1629 p = P(base, *(['d']*depth))
1630 p.mkdir(parents=True)
1631 pattern = '/'.join(['*'] * depth)
1632 iters = [base.glob(pattern) for j in range(100)]
1633 for it in iters:
1634 self.assertEqual(next(it), p)
1635 iters = [base.rglob('d') for j in range(100)]
1636 p = base
1637 for i in range(depth):
1638 p = p / 'd'
1639 for it in iters:
1640 self.assertEqual(next(it), p)
1641
Antoine Pitrou31119e42013-11-22 17:38:12 +01001642 def test_glob_dotdot(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001643 # ".." is not special in globs.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001644 P = self.cls
1645 p = P(BASE)
1646 self.assertEqual(set(p.glob("..")), { P(BASE, "..") })
1647 self.assertEqual(set(p.glob("dirA/../file*")), { P(BASE, "dirA/../fileA") })
1648 self.assertEqual(set(p.glob("../xyzzy")), set())
1649
Hai Shibb0424b2020-08-04 00:47:42 +08001650 @os_helper.skip_unless_symlink
Pablo Galindoeb7560a2020-03-07 17:53:20 +00001651 def test_glob_permissions(self):
1652 # See bpo-38894
1653 P = self.cls
1654 base = P(BASE) / 'permissions'
1655 base.mkdir()
1656
1657 file1 = base / "file1"
1658 file1.touch()
1659 file2 = base / "file2"
1660 file2.touch()
1661
1662 subdir = base / "subdir"
1663
1664 file3 = base / "file3"
1665 file3.symlink_to(subdir / "other")
1666
1667 # Patching is needed to avoid relying on the filesystem
1668 # to return the order of the files as the error will not
1669 # happen if the symlink is the last item.
1670
1671 with mock.patch("os.scandir") as scandir:
1672 scandir.return_value = sorted(os.scandir(base))
1673 self.assertEqual(len(set(base.glob("*"))), 3)
1674
1675 subdir.mkdir()
1676
1677 with mock.patch("os.scandir") as scandir:
1678 scandir.return_value = sorted(os.scandir(base))
1679 self.assertEqual(len(set(base.glob("*"))), 4)
1680
1681 subdir.chmod(000)
1682
1683 with mock.patch("os.scandir") as scandir:
1684 scandir.return_value = sorted(os.scandir(base))
1685 self.assertEqual(len(set(base.glob("*"))), 4)
Ezio Melottiac1e7f62015-12-28 23:50:19 +02001686
Steve Dower98eb3602016-11-09 12:58:17 -08001687 def _check_resolve(self, p, expected, strict=True):
1688 q = p.resolve(strict)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001689 self.assertEqual(q, expected)
1690
Anthony Shaw83da9262019-01-07 07:31:29 +11001691 # This can be used to check both relative and absolute resolutions.
Ezio Melottiac1e7f62015-12-28 23:50:19 +02001692 _check_resolve_relative = _check_resolve_absolute = _check_resolve
Antoine Pitrou31119e42013-11-22 17:38:12 +01001693
Hai Shibb0424b2020-08-04 00:47:42 +08001694 @os_helper.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001695 def test_resolve_common(self):
1696 P = self.cls
1697 p = P(BASE, 'foo')
1698 with self.assertRaises(OSError) as cm:
Steve Dower98eb3602016-11-09 12:58:17 -08001699 p.resolve(strict=True)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001700 self.assertEqual(cm.exception.errno, errno.ENOENT)
Steve Dower98eb3602016-11-09 12:58:17 -08001701 # Non-strict
Steve Dower97d79062019-09-10 14:52:48 +01001702 self.assertEqualNormCase(str(p.resolve(strict=False)),
1703 os.path.join(BASE, 'foo'))
Steve Dower98eb3602016-11-09 12:58:17 -08001704 p = P(BASE, 'foo', 'in', 'spam')
Steve Dower97d79062019-09-10 14:52:48 +01001705 self.assertEqualNormCase(str(p.resolve(strict=False)),
1706 os.path.join(BASE, 'foo', 'in', 'spam'))
Steve Dower98eb3602016-11-09 12:58:17 -08001707 p = P(BASE, '..', 'foo', 'in', 'spam')
Steve Dower97d79062019-09-10 14:52:48 +01001708 self.assertEqualNormCase(str(p.resolve(strict=False)),
1709 os.path.abspath(os.path.join('foo', 'in', 'spam')))
Anthony Shaw83da9262019-01-07 07:31:29 +11001710 # These are all relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001711 p = P(BASE, 'dirB', 'fileB')
1712 self._check_resolve_relative(p, p)
1713 p = P(BASE, 'linkA')
1714 self._check_resolve_relative(p, P(BASE, 'fileA'))
1715 p = P(BASE, 'dirA', 'linkC', 'fileB')
1716 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB'))
1717 p = P(BASE, 'dirB', 'linkD', 'fileB')
1718 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB'))
Steve Dower98eb3602016-11-09 12:58:17 -08001719 # Non-strict
1720 p = P(BASE, 'dirA', 'linkC', 'fileB', 'foo', 'in', 'spam')
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001721 self._check_resolve_relative(p, P(BASE, 'dirB', 'fileB', 'foo', 'in',
1722 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001723 p = P(BASE, 'dirA', 'linkC', '..', '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(BASE, 'dirA', 'foo', 'in',
1728 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001729 else:
1730 # In Posix, if linkY points to dirB, 'dirA/linkY/..'
1731 # resolves to 'dirB/..' first before resolving to parent of dirB.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001732 self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
Anthony Shaw83da9262019-01-07 07:31:29 +11001733 # Now create absolute symlinks.
Hai Shibb0424b2020-08-04 00:47:42 +08001734 d = os_helper._longpath(tempfile.mkdtemp(suffix='-dirD',
1735 dir=os.getcwd()))
1736 self.addCleanup(os_helper.rmtree, d)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001737 os.symlink(os.path.join(d), join('dirA', 'linkX'))
1738 os.symlink(join('dirB'), os.path.join(d, 'linkY'))
1739 p = P(BASE, 'dirA', 'linkX', 'linkY', 'fileB')
1740 self._check_resolve_absolute(p, P(BASE, 'dirB', 'fileB'))
Steve Dower98eb3602016-11-09 12:58:17 -08001741 # Non-strict
1742 p = P(BASE, 'dirA', 'linkX', 'linkY', 'foo', 'in', 'spam')
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001743 self._check_resolve_relative(p, P(BASE, 'dirB', 'foo', 'in', 'spam'),
1744 False)
Steve Dower98eb3602016-11-09 12:58:17 -08001745 p = P(BASE, 'dirA', 'linkX', 'linkY', '..', 'foo', 'in', 'spam')
1746 if os.name == 'nt':
1747 # In Windows, if linkY points to dirB, 'dirA\linkY\..'
1748 # resolves to 'dirA' without resolving linkY first.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001749 self._check_resolve_relative(p, P(d, 'foo', 'in', 'spam'), False)
Steve Dower98eb3602016-11-09 12:58:17 -08001750 else:
1751 # In Posix, if linkY points to dirB, 'dirA/linkY/..'
1752 # resolves to 'dirB/..' first before resolving to parent of dirB.
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001753 self._check_resolve_relative(p, P(BASE, 'foo', 'in', 'spam'), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001754
Hai Shibb0424b2020-08-04 00:47:42 +08001755 @os_helper.skip_unless_symlink
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001756 def test_resolve_dot(self):
1757 # See https://bitbucket.org/pitrou/pathlib/issue/9/pathresolve-fails-on-complex-symlinks
1758 p = self.cls(BASE)
1759 self.dirlink('.', join('0'))
Antoine Pitroucc157512013-12-03 17:13:13 +01001760 self.dirlink(os.path.join('0', '0'), join('1'))
1761 self.dirlink(os.path.join('1', '1'), join('2'))
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001762 q = p / '2'
Steve Dower98eb3602016-11-09 12:58:17 -08001763 self.assertEqual(q.resolve(strict=True), p)
1764 r = q / '3' / '4'
1765 self.assertRaises(FileNotFoundError, r.resolve, strict=True)
1766 # Non-strict
Antoine Pietriadd98eb2017-06-07 17:29:17 +02001767 self.assertEqual(r.resolve(strict=False), p / '3' / '4')
Antoine Pitrou51af82c2013-12-03 11:01:08 +01001768
Antoine Pitrou31119e42013-11-22 17:38:12 +01001769 def test_with(self):
1770 p = self.cls(BASE)
1771 it = p.iterdir()
1772 it2 = p.iterdir()
1773 next(it2)
1774 with p:
1775 pass
Barney Gale00002e62020-04-01 15:10:51 +01001776 # Using a path as a context manager is a no-op, thus the following
1777 # operations should still succeed after the context manage exits.
1778 next(it)
1779 next(it2)
1780 p.exists()
1781 p.resolve()
1782 p.absolute()
1783 with p:
1784 pass
Antoine Pitrou31119e42013-11-22 17:38:12 +01001785
1786 def test_chmod(self):
1787 p = self.cls(BASE) / 'fileA'
1788 mode = p.stat().st_mode
Anthony Shaw83da9262019-01-07 07:31:29 +11001789 # Clear writable bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001790 new_mode = mode & ~0o222
1791 p.chmod(new_mode)
1792 self.assertEqual(p.stat().st_mode, new_mode)
Anthony Shaw83da9262019-01-07 07:31:29 +11001793 # Set writable bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001794 new_mode = mode | 0o222
1795 p.chmod(new_mode)
1796 self.assertEqual(p.stat().st_mode, new_mode)
1797
Anthony Shaw83da9262019-01-07 07:31:29 +11001798 # XXX also need a test for lchmod.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001799
1800 def test_stat(self):
1801 p = self.cls(BASE) / 'fileA'
1802 st = p.stat()
1803 self.assertEqual(p.stat(), st)
Anthony Shaw83da9262019-01-07 07:31:29 +11001804 # Change file mode by flipping write bit.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001805 p.chmod(st.st_mode ^ 0o222)
1806 self.addCleanup(p.chmod, st.st_mode)
1807 self.assertNotEqual(p.stat(), st)
1808
Hai Shibb0424b2020-08-04 00:47:42 +08001809 @os_helper.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01001810 def test_lstat(self):
1811 p = self.cls(BASE)/ 'linkA'
1812 st = p.stat()
1813 self.assertNotEqual(st, p.lstat())
1814
1815 def test_lstat_nosymlink(self):
1816 p = self.cls(BASE) / 'fileA'
1817 st = p.stat()
1818 self.assertEqual(st, p.lstat())
1819
1820 @unittest.skipUnless(pwd, "the pwd module is needed for this test")
1821 def test_owner(self):
1822 p = self.cls(BASE) / 'fileA'
1823 uid = p.stat().st_uid
Antoine Pitrou2cf4b0f2013-11-25 19:51:53 +01001824 try:
1825 name = pwd.getpwuid(uid).pw_name
1826 except KeyError:
1827 self.skipTest(
1828 "user %d doesn't have an entry in the system database" % uid)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001829 self.assertEqual(name, p.owner())
1830
1831 @unittest.skipUnless(grp, "the grp module is needed for this test")
1832 def test_group(self):
1833 p = self.cls(BASE) / 'fileA'
1834 gid = p.stat().st_gid
Antoine Pitrou2cf4b0f2013-11-25 19:51:53 +01001835 try:
1836 name = grp.getgrgid(gid).gr_name
1837 except KeyError:
1838 self.skipTest(
1839 "group %d doesn't have an entry in the system database" % gid)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001840 self.assertEqual(name, p.group())
1841
1842 def test_unlink(self):
1843 p = self.cls(BASE) / 'fileA'
1844 p.unlink()
1845 self.assertFileNotFound(p.stat)
1846 self.assertFileNotFound(p.unlink)
1847
‮zlohhcuB treboRd9e006b2019-05-16 00:02:11 +02001848 def test_unlink_missing_ok(self):
1849 p = self.cls(BASE) / 'fileAAA'
1850 self.assertFileNotFound(p.unlink)
1851 p.unlink(missing_ok=True)
1852
Antoine Pitrou31119e42013-11-22 17:38:12 +01001853 def test_rmdir(self):
1854 p = self.cls(BASE) / 'dirA'
1855 for q in p.iterdir():
1856 q.unlink()
1857 p.rmdir()
1858 self.assertFileNotFound(p.stat)
1859 self.assertFileNotFound(p.unlink)
1860
Toke Høiland-Jørgensen092435e2019-12-16 13:23:55 +01001861 @unittest.skipUnless(hasattr(os, "link"), "os.link() is not present")
Joannah Nanjekye6b5b0132019-05-04 11:27:10 -04001862 def test_link_to(self):
1863 P = self.cls(BASE)
1864 p = P / 'fileA'
1865 size = p.stat().st_size
1866 # linking to another path.
1867 q = P / 'dirA' / 'fileAA'
1868 try:
1869 p.link_to(q)
1870 except PermissionError as e:
1871 self.skipTest('os.link(): %s' % e)
1872 self.assertEqual(q.stat().st_size, size)
1873 self.assertEqual(os.path.samefile(p, q), True)
1874 self.assertTrue(p.stat)
1875 # Linking to a str of a relative path.
1876 r = rel_join('fileAAA')
1877 q.link_to(r)
1878 self.assertEqual(os.stat(r).st_size, size)
1879 self.assertTrue(q.stat)
1880
Toke Høiland-Jørgensen092435e2019-12-16 13:23:55 +01001881 @unittest.skipIf(hasattr(os, "link"), "os.link() is present")
1882 def test_link_to_not_implemented(self):
1883 P = self.cls(BASE)
1884 p = P / 'fileA'
1885 # linking to another path.
1886 q = P / 'dirA' / 'fileAA'
1887 with self.assertRaises(NotImplementedError):
1888 p.link_to(q)
1889
Antoine Pitrou31119e42013-11-22 17:38:12 +01001890 def test_rename(self):
1891 P = self.cls(BASE)
1892 p = P / 'fileA'
1893 size = p.stat().st_size
Anthony Shaw83da9262019-01-07 07:31:29 +11001894 # Renaming to another path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001895 q = P / 'dirA' / 'fileAA'
hui shang088a09a2019-09-11 21:26:49 +08001896 renamed_p = p.rename(q)
1897 self.assertEqual(renamed_p, q)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001898 self.assertEqual(q.stat().st_size, size)
1899 self.assertFileNotFound(p.stat)
Anthony Shaw83da9262019-01-07 07:31:29 +11001900 # Renaming to a str of a relative path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001901 r = rel_join('fileAAA')
hui shang088a09a2019-09-11 21:26:49 +08001902 renamed_q = q.rename(r)
1903 self.assertEqual(renamed_q, self.cls(r))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001904 self.assertEqual(os.stat(r).st_size, size)
1905 self.assertFileNotFound(q.stat)
1906
1907 def test_replace(self):
1908 P = self.cls(BASE)
1909 p = P / 'fileA'
1910 size = p.stat().st_size
Anthony Shaw83da9262019-01-07 07:31:29 +11001911 # Replacing a non-existing path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001912 q = P / 'dirA' / 'fileAA'
hui shang088a09a2019-09-11 21:26:49 +08001913 replaced_p = p.replace(q)
1914 self.assertEqual(replaced_p, q)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001915 self.assertEqual(q.stat().st_size, size)
1916 self.assertFileNotFound(p.stat)
Anthony Shaw83da9262019-01-07 07:31:29 +11001917 # Replacing another (existing) path.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001918 r = rel_join('dirB', 'fileB')
hui shang088a09a2019-09-11 21:26:49 +08001919 replaced_q = q.replace(r)
1920 self.assertEqual(replaced_q, self.cls(r))
Antoine Pitrou31119e42013-11-22 17:38:12 +01001921 self.assertEqual(os.stat(r).st_size, size)
1922 self.assertFileNotFound(q.stat)
1923
Hai Shibb0424b2020-08-04 00:47:42 +08001924 @os_helper.skip_unless_symlink
Girtsa01ba332019-10-23 14:18:40 -07001925 def test_readlink(self):
1926 P = self.cls(BASE)
1927 self.assertEqual((P / 'linkA').readlink(), self.cls('fileA'))
1928 self.assertEqual((P / 'brokenLink').readlink(),
1929 self.cls('non-existing'))
1930 self.assertEqual((P / 'linkB').readlink(), self.cls('dirB'))
1931 with self.assertRaises(OSError):
1932 (P / 'fileA').readlink()
1933
Antoine Pitrou31119e42013-11-22 17:38:12 +01001934 def test_touch_common(self):
1935 P = self.cls(BASE)
1936 p = P / 'newfileA'
1937 self.assertFalse(p.exists())
1938 p.touch()
1939 self.assertTrue(p.exists())
Antoine Pitrou0f575642013-11-22 23:20:08 +01001940 st = p.stat()
1941 old_mtime = st.st_mtime
1942 old_mtime_ns = st.st_mtime_ns
Antoine Pitrou31119e42013-11-22 17:38:12 +01001943 # Rewind the mtime sufficiently far in the past to work around
1944 # filesystem-specific timestamp granularity.
1945 os.utime(str(p), (old_mtime - 10, old_mtime - 10))
Anthony Shaw83da9262019-01-07 07:31:29 +11001946 # The file mtime should be refreshed by calling touch() again.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001947 p.touch()
Antoine Pitrou0f575642013-11-22 23:20:08 +01001948 st = p.stat()
Antoine Pitrou2cf39172013-11-23 15:25:59 +01001949 self.assertGreaterEqual(st.st_mtime_ns, old_mtime_ns)
1950 self.assertGreaterEqual(st.st_mtime, old_mtime)
Anthony Shaw83da9262019-01-07 07:31:29 +11001951 # Now with exist_ok=False.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001952 p = P / 'newfileB'
1953 self.assertFalse(p.exists())
1954 p.touch(mode=0o700, exist_ok=False)
1955 self.assertTrue(p.exists())
1956 self.assertRaises(OSError, p.touch, exist_ok=False)
1957
Antoine Pitrou8b784932013-11-23 14:52:39 +01001958 def test_touch_nochange(self):
1959 P = self.cls(BASE)
1960 p = P / 'fileA'
1961 p.touch()
1962 with p.open('rb') as f:
1963 self.assertEqual(f.read().strip(), b"this is file A")
1964
Antoine Pitrou31119e42013-11-22 17:38:12 +01001965 def test_mkdir(self):
1966 P = self.cls(BASE)
1967 p = P / 'newdirA'
1968 self.assertFalse(p.exists())
1969 p.mkdir()
1970 self.assertTrue(p.exists())
1971 self.assertTrue(p.is_dir())
1972 with self.assertRaises(OSError) as cm:
1973 p.mkdir()
1974 self.assertEqual(cm.exception.errno, errno.EEXIST)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001975
1976 def test_mkdir_parents(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11001977 # Creating a chain of directories.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001978 p = self.cls(BASE, 'newdirB', 'newdirC')
1979 self.assertFalse(p.exists())
1980 with self.assertRaises(OSError) as cm:
1981 p.mkdir()
1982 self.assertEqual(cm.exception.errno, errno.ENOENT)
1983 p.mkdir(parents=True)
1984 self.assertTrue(p.exists())
1985 self.assertTrue(p.is_dir())
1986 with self.assertRaises(OSError) as cm:
1987 p.mkdir(parents=True)
1988 self.assertEqual(cm.exception.errno, errno.EEXIST)
Anthony Shaw83da9262019-01-07 07:31:29 +11001989 # Test `mode` arg.
1990 mode = stat.S_IMODE(p.stat().st_mode) # Default mode.
Antoine Pitrou0048c982013-12-16 20:22:37 +01001991 p = self.cls(BASE, 'newdirD', 'newdirE')
1992 p.mkdir(0o555, parents=True)
1993 self.assertTrue(p.exists())
1994 self.assertTrue(p.is_dir())
1995 if os.name != 'nt':
Anthony Shaw83da9262019-01-07 07:31:29 +11001996 # The directory's permissions follow the mode argument.
Gregory P. Smithb599c612014-01-20 01:10:33 -08001997 self.assertEqual(stat.S_IMODE(p.stat().st_mode), 0o7555 & mode)
Anthony Shaw83da9262019-01-07 07:31:29 +11001998 # The parent's permissions follow the default process settings.
Antoine Pitrou0048c982013-12-16 20:22:37 +01001999 self.assertEqual(stat.S_IMODE(p.parent.stat().st_mode), mode)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002000
Barry Warsaw7c549c42014-08-05 11:28:12 -04002001 def test_mkdir_exist_ok(self):
2002 p = self.cls(BASE, 'dirB')
2003 st_ctime_first = p.stat().st_ctime
2004 self.assertTrue(p.exists())
2005 self.assertTrue(p.is_dir())
2006 with self.assertRaises(FileExistsError) as cm:
2007 p.mkdir()
2008 self.assertEqual(cm.exception.errno, errno.EEXIST)
2009 p.mkdir(exist_ok=True)
2010 self.assertTrue(p.exists())
2011 self.assertEqual(p.stat().st_ctime, st_ctime_first)
2012
2013 def test_mkdir_exist_ok_with_parent(self):
2014 p = self.cls(BASE, 'dirC')
2015 self.assertTrue(p.exists())
2016 with self.assertRaises(FileExistsError) as cm:
2017 p.mkdir()
2018 self.assertEqual(cm.exception.errno, errno.EEXIST)
2019 p = p / 'newdirC'
2020 p.mkdir(parents=True)
2021 st_ctime_first = p.stat().st_ctime
2022 self.assertTrue(p.exists())
2023 with self.assertRaises(FileExistsError) as cm:
2024 p.mkdir(parents=True)
2025 self.assertEqual(cm.exception.errno, errno.EEXIST)
2026 p.mkdir(parents=True, exist_ok=True)
2027 self.assertTrue(p.exists())
2028 self.assertEqual(p.stat().st_ctime, st_ctime_first)
2029
Serhiy Storchakaaf7b9ec2017-03-24 20:51:53 +02002030 def test_mkdir_exist_ok_root(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002031 # Issue #25803: A drive root could raise PermissionError on Windows.
Serhiy Storchakaaf7b9ec2017-03-24 20:51:53 +02002032 self.cls('/').resolve().mkdir(exist_ok=True)
2033 self.cls('/').resolve().mkdir(parents=True, exist_ok=True)
2034
Anthony Shaw83da9262019-01-07 07:31:29 +11002035 @only_nt # XXX: not sure how to test this on POSIX.
Steve Dowerd3c48532017-02-04 14:54:56 -08002036 def test_mkdir_with_unknown_drive(self):
2037 for d in 'ZYXWVUTSRQPONMLKJIHGFEDCBA':
2038 p = self.cls(d + ':\\')
2039 if not p.is_dir():
2040 break
2041 else:
2042 self.skipTest("cannot find a drive that doesn't exist")
2043 with self.assertRaises(OSError):
2044 (p / 'child' / 'path').mkdir(parents=True)
2045
Barry Warsaw7c549c42014-08-05 11:28:12 -04002046 def test_mkdir_with_child_file(self):
2047 p = self.cls(BASE, 'dirB', 'fileB')
2048 self.assertTrue(p.exists())
2049 # An exception is raised when the last path component is an existing
2050 # regular file, regardless of whether exist_ok is true or not.
2051 with self.assertRaises(FileExistsError) as cm:
2052 p.mkdir(parents=True)
2053 self.assertEqual(cm.exception.errno, errno.EEXIST)
2054 with self.assertRaises(FileExistsError) as cm:
2055 p.mkdir(parents=True, exist_ok=True)
2056 self.assertEqual(cm.exception.errno, errno.EEXIST)
2057
2058 def test_mkdir_no_parents_file(self):
2059 p = self.cls(BASE, 'fileA')
2060 self.assertTrue(p.exists())
2061 # An exception is raised when the last path component is an existing
2062 # regular file, regardless of whether exist_ok is true or not.
2063 with self.assertRaises(FileExistsError) as cm:
2064 p.mkdir()
2065 self.assertEqual(cm.exception.errno, errno.EEXIST)
2066 with self.assertRaises(FileExistsError) as cm:
2067 p.mkdir(exist_ok=True)
2068 self.assertEqual(cm.exception.errno, errno.EEXIST)
2069
Armin Rigo22a594a2017-04-13 20:08:15 +02002070 def test_mkdir_concurrent_parent_creation(self):
2071 for pattern_num in range(32):
2072 p = self.cls(BASE, 'dirCPC%d' % pattern_num)
2073 self.assertFalse(p.exists())
2074
2075 def my_mkdir(path, mode=0o777):
2076 path = str(path)
2077 # Emulate another process that would create the directory
2078 # just before we try to create it ourselves. We do it
2079 # in all possible pattern combinations, assuming that this
2080 # function is called at most 5 times (dirCPC/dir1/dir2,
2081 # dirCPC/dir1, dirCPC, dirCPC/dir1, dirCPC/dir1/dir2).
2082 if pattern.pop():
Anthony Shaw83da9262019-01-07 07:31:29 +11002083 os.mkdir(path, mode) # From another process.
Armin Rigo22a594a2017-04-13 20:08:15 +02002084 concurrently_created.add(path)
Anthony Shaw83da9262019-01-07 07:31:29 +11002085 os.mkdir(path, mode) # Our real call.
Armin Rigo22a594a2017-04-13 20:08:15 +02002086
2087 pattern = [bool(pattern_num & (1 << n)) for n in range(5)]
2088 concurrently_created = set()
2089 p12 = p / 'dir1' / 'dir2'
2090 try:
2091 with mock.patch("pathlib._normal_accessor.mkdir", my_mkdir):
2092 p12.mkdir(parents=True, exist_ok=False)
2093 except FileExistsError:
2094 self.assertIn(str(p12), concurrently_created)
2095 else:
2096 self.assertNotIn(str(p12), concurrently_created)
2097 self.assertTrue(p.exists())
2098
Hai Shibb0424b2020-08-04 00:47:42 +08002099 @os_helper.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01002100 def test_symlink_to(self):
2101 P = self.cls(BASE)
2102 target = P / 'fileA'
Anthony Shaw83da9262019-01-07 07:31:29 +11002103 # Symlinking a path target.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002104 link = P / 'dirA' / 'linkAA'
2105 link.symlink_to(target)
2106 self.assertEqual(link.stat(), target.stat())
2107 self.assertNotEqual(link.lstat(), target.stat())
Anthony Shaw83da9262019-01-07 07:31:29 +11002108 # Symlinking a str target.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002109 link = P / 'dirA' / 'linkAAA'
2110 link.symlink_to(str(target))
2111 self.assertEqual(link.stat(), target.stat())
2112 self.assertNotEqual(link.lstat(), target.stat())
2113 self.assertFalse(link.is_dir())
Anthony Shaw83da9262019-01-07 07:31:29 +11002114 # Symlinking to a directory.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002115 target = P / 'dirB'
2116 link = P / 'dirA' / 'linkAAAA'
2117 link.symlink_to(target, target_is_directory=True)
2118 self.assertEqual(link.stat(), target.stat())
2119 self.assertNotEqual(link.lstat(), target.stat())
2120 self.assertTrue(link.is_dir())
2121 self.assertTrue(list(link.iterdir()))
2122
2123 def test_is_dir(self):
2124 P = self.cls(BASE)
2125 self.assertTrue((P / 'dirA').is_dir())
2126 self.assertFalse((P / 'fileA').is_dir())
2127 self.assertFalse((P / 'non-existing').is_dir())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002128 self.assertFalse((P / 'fileA' / 'bah').is_dir())
Hai Shibb0424b2020-08-04 00:47:42 +08002129 if os_helper.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01002130 self.assertFalse((P / 'linkA').is_dir())
2131 self.assertTrue((P / 'linkB').is_dir())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002132 self.assertFalse((P/ 'brokenLink').is_dir(), False)
2133 self.assertIs((P / 'dirA\udfff').is_dir(), False)
2134 self.assertIs((P / 'dirA\x00').is_dir(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002135
2136 def test_is_file(self):
2137 P = self.cls(BASE)
2138 self.assertTrue((P / 'fileA').is_file())
2139 self.assertFalse((P / 'dirA').is_file())
2140 self.assertFalse((P / 'non-existing').is_file())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002141 self.assertFalse((P / 'fileA' / 'bah').is_file())
Hai Shibb0424b2020-08-04 00:47:42 +08002142 if os_helper.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01002143 self.assertTrue((P / 'linkA').is_file())
2144 self.assertFalse((P / 'linkB').is_file())
2145 self.assertFalse((P/ 'brokenLink').is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002146 self.assertIs((P / 'fileA\udfff').is_file(), False)
2147 self.assertIs((P / 'fileA\x00').is_file(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002148
Cooper Lees173ff4a2017-08-01 15:35:45 -07002149 @only_posix
2150 def test_is_mount(self):
2151 P = self.cls(BASE)
Anthony Shaw83da9262019-01-07 07:31:29 +11002152 R = self.cls('/') # TODO: Work out Windows.
Cooper Lees173ff4a2017-08-01 15:35:45 -07002153 self.assertFalse((P / 'fileA').is_mount())
2154 self.assertFalse((P / 'dirA').is_mount())
2155 self.assertFalse((P / 'non-existing').is_mount())
2156 self.assertFalse((P / 'fileA' / 'bah').is_mount())
2157 self.assertTrue(R.is_mount())
Hai Shibb0424b2020-08-04 00:47:42 +08002158 if os_helper.can_symlink():
Cooper Lees173ff4a2017-08-01 15:35:45 -07002159 self.assertFalse((P / 'linkA').is_mount())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002160 self.assertIs(self.cls('/\udfff').is_mount(), False)
2161 self.assertIs(self.cls('/\x00').is_mount(), False)
Cooper Lees173ff4a2017-08-01 15:35:45 -07002162
Antoine Pitrou31119e42013-11-22 17:38:12 +01002163 def test_is_symlink(self):
2164 P = self.cls(BASE)
2165 self.assertFalse((P / 'fileA').is_symlink())
2166 self.assertFalse((P / 'dirA').is_symlink())
2167 self.assertFalse((P / 'non-existing').is_symlink())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002168 self.assertFalse((P / 'fileA' / 'bah').is_symlink())
Hai Shibb0424b2020-08-04 00:47:42 +08002169 if os_helper.can_symlink():
Antoine Pitrou31119e42013-11-22 17:38:12 +01002170 self.assertTrue((P / 'linkA').is_symlink())
2171 self.assertTrue((P / 'linkB').is_symlink())
2172 self.assertTrue((P/ 'brokenLink').is_symlink())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002173 self.assertIs((P / 'fileA\udfff').is_file(), False)
2174 self.assertIs((P / 'fileA\x00').is_file(), False)
Hai Shibb0424b2020-08-04 00:47:42 +08002175 if os_helper.can_symlink():
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002176 self.assertIs((P / 'linkA\udfff').is_file(), False)
2177 self.assertIs((P / 'linkA\x00').is_file(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002178
2179 def test_is_fifo_false(self):
2180 P = self.cls(BASE)
2181 self.assertFalse((P / 'fileA').is_fifo())
2182 self.assertFalse((P / 'dirA').is_fifo())
2183 self.assertFalse((P / 'non-existing').is_fifo())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002184 self.assertFalse((P / 'fileA' / 'bah').is_fifo())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002185 self.assertIs((P / 'fileA\udfff').is_fifo(), False)
2186 self.assertIs((P / 'fileA\x00').is_fifo(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002187
2188 @unittest.skipUnless(hasattr(os, "mkfifo"), "os.mkfifo() required")
2189 def test_is_fifo_true(self):
2190 P = self.cls(BASE, 'myfifo')
xdegaye92c2ca72017-11-12 17:31:07 +01002191 try:
2192 os.mkfifo(str(P))
2193 except PermissionError as e:
2194 self.skipTest('os.mkfifo(): %s' % e)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002195 self.assertTrue(P.is_fifo())
2196 self.assertFalse(P.is_socket())
2197 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002198 self.assertIs(self.cls(BASE, 'myfifo\udfff').is_fifo(), False)
2199 self.assertIs(self.cls(BASE, 'myfifo\x00').is_fifo(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002200
2201 def test_is_socket_false(self):
2202 P = self.cls(BASE)
2203 self.assertFalse((P / 'fileA').is_socket())
2204 self.assertFalse((P / 'dirA').is_socket())
2205 self.assertFalse((P / 'non-existing').is_socket())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002206 self.assertFalse((P / 'fileA' / 'bah').is_socket())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002207 self.assertIs((P / 'fileA\udfff').is_socket(), False)
2208 self.assertIs((P / 'fileA\x00').is_socket(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002209
2210 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required")
2211 def test_is_socket_true(self):
2212 P = self.cls(BASE, 'mysock')
Antoine Pitrou330ce592013-11-22 18:05:06 +01002213 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002214 self.addCleanup(sock.close)
Antoine Pitrou330ce592013-11-22 18:05:06 +01002215 try:
2216 sock.bind(str(P))
2217 except OSError as e:
Xavier de Gayee88ed052016-12-14 11:52:28 +01002218 if (isinstance(e, PermissionError) or
2219 "AF_UNIX path too long" in str(e)):
Antoine Pitrou330ce592013-11-22 18:05:06 +01002220 self.skipTest("cannot bind Unix socket: " + str(e))
Antoine Pitrou31119e42013-11-22 17:38:12 +01002221 self.assertTrue(P.is_socket())
2222 self.assertFalse(P.is_fifo())
2223 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002224 self.assertIs(self.cls(BASE, 'mysock\udfff').is_socket(), False)
2225 self.assertIs(self.cls(BASE, 'mysock\x00').is_socket(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002226
2227 def test_is_block_device_false(self):
2228 P = self.cls(BASE)
2229 self.assertFalse((P / 'fileA').is_block_device())
2230 self.assertFalse((P / 'dirA').is_block_device())
2231 self.assertFalse((P / 'non-existing').is_block_device())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002232 self.assertFalse((P / 'fileA' / 'bah').is_block_device())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002233 self.assertIs((P / 'fileA\udfff').is_block_device(), False)
2234 self.assertIs((P / 'fileA\x00').is_block_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002235
2236 def test_is_char_device_false(self):
2237 P = self.cls(BASE)
2238 self.assertFalse((P / 'fileA').is_char_device())
2239 self.assertFalse((P / 'dirA').is_char_device())
2240 self.assertFalse((P / 'non-existing').is_char_device())
Antoine Pitrou2b2852b2014-10-30 23:14:03 +01002241 self.assertFalse((P / 'fileA' / 'bah').is_char_device())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002242 self.assertIs((P / 'fileA\udfff').is_char_device(), False)
2243 self.assertIs((P / 'fileA\x00').is_char_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002244
2245 def test_is_char_device_true(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002246 # Under Unix, /dev/null should generally be a char device.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002247 P = self.cls('/dev/null')
2248 if not P.exists():
2249 self.skipTest("/dev/null required")
2250 self.assertTrue(P.is_char_device())
2251 self.assertFalse(P.is_block_device())
2252 self.assertFalse(P.is_file())
Serhiy Storchaka0185f342018-09-18 11:28:51 +03002253 self.assertIs(self.cls('/dev/null\udfff').is_char_device(), False)
2254 self.assertIs(self.cls('/dev/null\x00').is_char_device(), False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002255
2256 def test_pickling_common(self):
2257 p = self.cls(BASE, 'fileA')
2258 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
2259 dumped = pickle.dumps(p, proto)
2260 pp = pickle.loads(dumped)
2261 self.assertEqual(pp.stat(), p.stat())
2262
2263 def test_parts_interning(self):
2264 P = self.cls
2265 p = P('/usr/bin/foo')
2266 q = P('/usr/local/bin')
2267 # 'usr'
2268 self.assertIs(p.parts[1], q.parts[1])
2269 # 'bin'
2270 self.assertIs(p.parts[2], q.parts[3])
2271
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002272 def _check_complex_symlinks(self, link0_target):
Anthony Shaw83da9262019-01-07 07:31:29 +11002273 # Test solving a non-looping chain of symlinks (issue #19887).
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002274 P = self.cls(BASE)
2275 self.dirlink(os.path.join('link0', 'link0'), join('link1'))
2276 self.dirlink(os.path.join('link1', 'link1'), join('link2'))
2277 self.dirlink(os.path.join('link2', 'link2'), join('link3'))
2278 self.dirlink(link0_target, join('link0'))
2279
Anthony Shaw83da9262019-01-07 07:31:29 +11002280 # Resolve absolute paths.
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002281 p = (P / 'link0').resolve()
2282 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002283 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002284 p = (P / 'link1').resolve()
2285 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002286 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002287 p = (P / 'link2').resolve()
2288 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002289 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002290 p = (P / 'link3').resolve()
2291 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002292 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002293
Anthony Shaw83da9262019-01-07 07:31:29 +11002294 # Resolve relative paths.
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002295 old_path = os.getcwd()
2296 os.chdir(BASE)
2297 try:
2298 p = self.cls('link0').resolve()
2299 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002300 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002301 p = self.cls('link1').resolve()
2302 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002303 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002304 p = self.cls('link2').resolve()
2305 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002306 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002307 p = self.cls('link3').resolve()
2308 self.assertEqual(p, P)
Steve Dower97d79062019-09-10 14:52:48 +01002309 self.assertEqualNormCase(str(p), BASE)
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002310 finally:
2311 os.chdir(old_path)
2312
Hai Shibb0424b2020-08-04 00:47:42 +08002313 @os_helper.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002314 def test_complex_symlinks_absolute(self):
2315 self._check_complex_symlinks(BASE)
2316
Hai Shibb0424b2020-08-04 00:47:42 +08002317 @os_helper.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002318 def test_complex_symlinks_relative(self):
2319 self._check_complex_symlinks('.')
2320
Hai Shibb0424b2020-08-04 00:47:42 +08002321 @os_helper.skip_unless_symlink
Antoine Pitrouc274fd22013-12-16 19:57:41 +01002322 def test_complex_symlinks_relative_dot_dot(self):
2323 self._check_complex_symlinks(os.path.join('dirA', '..'))
2324
Antoine Pitrou31119e42013-11-22 17:38:12 +01002325
2326class PathTest(_BasePathTest, unittest.TestCase):
2327 cls = pathlib.Path
2328
Batuhan Taşkaya526606b2019-12-08 23:31:15 +03002329 def test_class_getitem(self):
2330 self.assertIs(self.cls[str], self.cls)
2331
Antoine Pitrou31119e42013-11-22 17:38:12 +01002332 def test_concrete_class(self):
2333 p = self.cls('a')
2334 self.assertIs(type(p),
2335 pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath)
2336
2337 def test_unsupported_flavour(self):
2338 if os.name == 'nt':
2339 self.assertRaises(NotImplementedError, pathlib.PosixPath)
2340 else:
2341 self.assertRaises(NotImplementedError, pathlib.WindowsPath)
2342
Berker Peksag4a208e42016-01-30 17:50:48 +02002343 def test_glob_empty_pattern(self):
2344 p = self.cls()
2345 with self.assertRaisesRegex(ValueError, 'Unacceptable pattern'):
2346 list(p.glob(''))
2347
Antoine Pitrou31119e42013-11-22 17:38:12 +01002348
2349@only_posix
2350class PosixPathTest(_BasePathTest, unittest.TestCase):
2351 cls = pathlib.PosixPath
2352
Steve Dower98eb3602016-11-09 12:58:17 -08002353 def _check_symlink_loop(self, *args, strict=True):
Antoine Pitrou31119e42013-11-22 17:38:12 +01002354 path = self.cls(*args)
2355 with self.assertRaises(RuntimeError):
Steve Dower98eb3602016-11-09 12:58:17 -08002356 print(path.resolve(strict))
Antoine Pitrou31119e42013-11-22 17:38:12 +01002357
2358 def test_open_mode(self):
2359 old_mask = os.umask(0)
2360 self.addCleanup(os.umask, old_mask)
2361 p = self.cls(BASE)
2362 with (p / 'new_file').open('wb'):
2363 pass
2364 st = os.stat(join('new_file'))
2365 self.assertEqual(stat.S_IMODE(st.st_mode), 0o666)
2366 os.umask(0o022)
2367 with (p / 'other_new_file').open('wb'):
2368 pass
2369 st = os.stat(join('other_new_file'))
2370 self.assertEqual(stat.S_IMODE(st.st_mode), 0o644)
2371
Dong-hee Na94ad6c62018-06-12 23:30:45 +09002372 def test_resolve_root(self):
2373 current_directory = os.getcwd()
2374 try:
2375 os.chdir('/')
2376 p = self.cls('spam')
2377 self.assertEqual(str(p.resolve()), '/spam')
2378 finally:
2379 os.chdir(current_directory)
2380
Antoine Pitrou31119e42013-11-22 17:38:12 +01002381 def test_touch_mode(self):
2382 old_mask = os.umask(0)
2383 self.addCleanup(os.umask, old_mask)
2384 p = self.cls(BASE)
2385 (p / 'new_file').touch()
2386 st = os.stat(join('new_file'))
2387 self.assertEqual(stat.S_IMODE(st.st_mode), 0o666)
2388 os.umask(0o022)
2389 (p / 'other_new_file').touch()
2390 st = os.stat(join('other_new_file'))
2391 self.assertEqual(stat.S_IMODE(st.st_mode), 0o644)
2392 (p / 'masked_new_file').touch(mode=0o750)
2393 st = os.stat(join('masked_new_file'))
2394 self.assertEqual(stat.S_IMODE(st.st_mode), 0o750)
2395
Hai Shibb0424b2020-08-04 00:47:42 +08002396 @os_helper.skip_unless_symlink
Antoine Pitrou31119e42013-11-22 17:38:12 +01002397 def test_resolve_loop(self):
Anthony Shaw83da9262019-01-07 07:31:29 +11002398 # Loops with relative symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002399 os.symlink('linkX/inside', join('linkX'))
2400 self._check_symlink_loop(BASE, 'linkX')
2401 os.symlink('linkY', join('linkY'))
2402 self._check_symlink_loop(BASE, 'linkY')
2403 os.symlink('linkZ/../linkZ', join('linkZ'))
2404 self._check_symlink_loop(BASE, 'linkZ')
Steve Dower98eb3602016-11-09 12:58:17 -08002405 # Non-strict
2406 self._check_symlink_loop(BASE, 'linkZ', 'foo', strict=False)
Anthony Shaw83da9262019-01-07 07:31:29 +11002407 # Loops with absolute symlinks.
Antoine Pitrou31119e42013-11-22 17:38:12 +01002408 os.symlink(join('linkU/inside'), join('linkU'))
2409 self._check_symlink_loop(BASE, 'linkU')
2410 os.symlink(join('linkV'), join('linkV'))
2411 self._check_symlink_loop(BASE, 'linkV')
2412 os.symlink(join('linkW/../linkW'), join('linkW'))
2413 self._check_symlink_loop(BASE, 'linkW')
Steve Dower98eb3602016-11-09 12:58:17 -08002414 # Non-strict
2415 self._check_symlink_loop(BASE, 'linkW', 'foo', strict=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01002416
2417 def test_glob(self):
2418 P = self.cls
2419 p = P(BASE)
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002420 given = set(p.glob("FILEa"))
Hai Shibb0424b2020-08-04 00:47:42 +08002421 expect = set() if not os_helper.fs_is_case_insensitive(BASE) else given
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002422 self.assertEqual(given, expect)
Antoine Pitrou2dd38fb2013-11-22 22:26:01 +01002423 self.assertEqual(set(p.glob("FILEa*")), set())
Antoine Pitrou31119e42013-11-22 17:38:12 +01002424
2425 def test_rglob(self):
2426 P = self.cls
2427 p = P(BASE, "dirC")
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002428 given = set(p.rglob("FILEd"))
Hai Shibb0424b2020-08-04 00:47:42 +08002429 expect = set() if not os_helper.fs_is_case_insensitive(BASE) else given
Brett Cannonfe77f4e2013-11-22 16:14:10 -05002430 self.assertEqual(given, expect)
Antoine Pitrou2dd38fb2013-11-22 22:26:01 +01002431 self.assertEqual(set(p.rglob("FILEd*")), set())
Antoine Pitrou31119e42013-11-22 17:38:12 +01002432
Xavier de Gayefb24eea2016-12-13 09:11:38 +01002433 @unittest.skipUnless(hasattr(pwd, 'getpwall'),
2434 'pwd module does not expose getpwall()')
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002435 def test_expanduser(self):
2436 P = self.cls
Hai Shibb0424b2020-08-04 00:47:42 +08002437 import_helper.import_module('pwd')
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002438 import pwd
2439 pwdent = pwd.getpwuid(os.getuid())
2440 username = pwdent.pw_name
Serhiy Storchakaa3fd0b22016-05-03 21:17:03 +03002441 userhome = pwdent.pw_dir.rstrip('/') or '/'
Anthony Shaw83da9262019-01-07 07:31:29 +11002442 # Find arbitrary different user (if exists).
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002443 for pwdent in pwd.getpwall():
2444 othername = pwdent.pw_name
2445 otherhome = pwdent.pw_dir.rstrip('/')
Victor Stinnere9694392015-01-10 09:00:20 +01002446 if othername != username and otherhome:
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002447 break
Anders Kaseorg5c0d4622018-05-14 10:00:37 -04002448 else:
2449 othername = username
2450 otherhome = userhome
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002451
2452 p1 = P('~/Documents')
2453 p2 = P('~' + username + '/Documents')
2454 p3 = P('~' + othername + '/Documents')
2455 p4 = P('../~' + username + '/Documents')
2456 p5 = P('/~' + username + '/Documents')
2457 p6 = P('')
2458 p7 = P('~fakeuser/Documents')
2459
Hai Shibb0424b2020-08-04 00:47:42 +08002460 with os_helper.EnvironmentVarGuard() as env:
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002461 env.pop('HOME', None)
2462
2463 self.assertEqual(p1.expanduser(), P(userhome) / 'Documents')
2464 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
2465 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
2466 self.assertEqual(p4.expanduser(), p4)
2467 self.assertEqual(p5.expanduser(), p5)
2468 self.assertEqual(p6.expanduser(), p6)
2469 self.assertRaises(RuntimeError, p7.expanduser)
2470
2471 env['HOME'] = '/tmp'
2472 self.assertEqual(p1.expanduser(), P('/tmp/Documents'))
2473 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
2474 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
2475 self.assertEqual(p4.expanduser(), p4)
2476 self.assertEqual(p5.expanduser(), p5)
2477 self.assertEqual(p6.expanduser(), p6)
2478 self.assertRaises(RuntimeError, p7.expanduser)
2479
Przemysław Spodymek216b7452018-08-27 23:33:45 +02002480 @unittest.skipIf(sys.platform != "darwin",
2481 "Bad file descriptor in /dev/fd affects only macOS")
2482 def test_handling_bad_descriptor(self):
2483 try:
2484 file_descriptors = list(pathlib.Path('/dev/fd').rglob("*"))[3:]
2485 if not file_descriptors:
2486 self.skipTest("no file descriptors - issue was not reproduced")
2487 # Checking all file descriptors because there is no guarantee
2488 # which one will fail.
2489 for f in file_descriptors:
2490 f.exists()
2491 f.is_dir()
2492 f.is_file()
2493 f.is_symlink()
2494 f.is_block_device()
2495 f.is_char_device()
2496 f.is_fifo()
2497 f.is_socket()
2498 except OSError as e:
2499 if e.errno == errno.EBADF:
2500 self.fail("Bad file descriptor not handled.")
2501 raise
2502
Antoine Pitrou31119e42013-11-22 17:38:12 +01002503
2504@only_nt
2505class WindowsPathTest(_BasePathTest, unittest.TestCase):
2506 cls = pathlib.WindowsPath
2507
2508 def test_glob(self):
2509 P = self.cls
2510 p = P(BASE)
2511 self.assertEqual(set(p.glob("FILEa")), { P(BASE, "fileA") })
Serhiy Storchaka10ecbad2019-10-21 20:37:15 +03002512 self.assertEqual(set(p.glob("F*a")), { P(BASE, "fileA") })
2513 self.assertEqual(set(map(str, p.glob("FILEa"))), {f"{p}\\FILEa"})
2514 self.assertEqual(set(map(str, p.glob("F*a"))), {f"{p}\\fileA"})
Antoine Pitrou31119e42013-11-22 17:38:12 +01002515
2516 def test_rglob(self):
2517 P = self.cls
2518 p = P(BASE, "dirC")
2519 self.assertEqual(set(p.rglob("FILEd")), { P(BASE, "dirC/dirD/fileD") })
Serhiy Storchaka10ecbad2019-10-21 20:37:15 +03002520 self.assertEqual(set(map(str, p.rglob("FILEd"))), {f"{p}\\dirD\\FILEd"})
Antoine Pitrou31119e42013-11-22 17:38:12 +01002521
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002522 def test_expanduser(self):
2523 P = self.cls
Hai Shibb0424b2020-08-04 00:47:42 +08002524 with os_helper.EnvironmentVarGuard() as env:
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002525 env.pop('HOME', None)
2526 env.pop('USERPROFILE', None)
2527 env.pop('HOMEPATH', None)
2528 env.pop('HOMEDRIVE', None)
2529 env['USERNAME'] = 'alice'
2530
2531 # test that the path returns unchanged
2532 p1 = P('~/My Documents')
2533 p2 = P('~alice/My Documents')
2534 p3 = P('~bob/My Documents')
2535 p4 = P('/~/My Documents')
2536 p5 = P('d:~/My Documents')
2537 p6 = P('')
2538 self.assertRaises(RuntimeError, p1.expanduser)
2539 self.assertRaises(RuntimeError, p2.expanduser)
2540 self.assertRaises(RuntimeError, p3.expanduser)
2541 self.assertEqual(p4.expanduser(), p4)
2542 self.assertEqual(p5.expanduser(), p5)
2543 self.assertEqual(p6.expanduser(), p6)
2544
2545 def check():
2546 env.pop('USERNAME', None)
2547 self.assertEqual(p1.expanduser(),
2548 P('C:/Users/alice/My Documents'))
2549 self.assertRaises(KeyError, p2.expanduser)
2550 env['USERNAME'] = 'alice'
2551 self.assertEqual(p2.expanduser(),
2552 P('C:/Users/alice/My Documents'))
2553 self.assertEqual(p3.expanduser(),
2554 P('C:/Users/bob/My Documents'))
2555 self.assertEqual(p4.expanduser(), p4)
2556 self.assertEqual(p5.expanduser(), p5)
2557 self.assertEqual(p6.expanduser(), p6)
2558
Antoine Pitrou8477ed62014-12-30 20:54:45 +01002559 env['HOMEPATH'] = 'C:\\Users\\alice'
2560 check()
2561
2562 env['HOMEDRIVE'] = 'C:\\'
2563 env['HOMEPATH'] = 'Users\\alice'
2564 check()
2565
2566 env.pop('HOMEDRIVE', None)
2567 env.pop('HOMEPATH', None)
2568 env['USERPROFILE'] = 'C:\\Users\\alice'
2569 check()
2570
Christoph Reiterc45a2aa2020-01-28 10:41:50 +01002571 # bpo-38883: ignore `HOME` when set on windows
2572 env['HOME'] = 'C:\\Users\\eve'
2573 check()
2574
Antoine Pitrou31119e42013-11-22 17:38:12 +01002575
aiudirog4c69be22019-08-08 01:41:10 -04002576class CompatiblePathTest(unittest.TestCase):
2577 """
2578 Test that a type can be made compatible with PurePath
2579 derivatives by implementing division operator overloads.
2580 """
2581
2582 class CompatPath:
2583 """
2584 Minimum viable class to test PurePath compatibility.
2585 Simply uses the division operator to join a given
2586 string and the string value of another object with
2587 a forward slash.
2588 """
2589 def __init__(self, string):
2590 self.string = string
2591
2592 def __truediv__(self, other):
2593 return type(self)(f"{self.string}/{other}")
2594
2595 def __rtruediv__(self, other):
2596 return type(self)(f"{other}/{self.string}")
2597
2598 def test_truediv(self):
2599 result = pathlib.PurePath("test") / self.CompatPath("right")
2600 self.assertIsInstance(result, self.CompatPath)
2601 self.assertEqual(result.string, "test/right")
2602
2603 with self.assertRaises(TypeError):
2604 # Verify improper operations still raise a TypeError
2605 pathlib.PurePath("test") / 10
2606
2607 def test_rtruediv(self):
2608 result = self.CompatPath("left") / pathlib.PurePath("test")
2609 self.assertIsInstance(result, self.CompatPath)
2610 self.assertEqual(result.string, "left/test")
2611
2612 with self.assertRaises(TypeError):
2613 # Verify improper operations still raise a TypeError
2614 10 / pathlib.PurePath("test")
2615
2616
Antoine Pitrou31119e42013-11-22 17:38:12 +01002617if __name__ == "__main__":
2618 unittest.main()