Debian Codegraph @

Lib/test/test_pathlib/test_pathlib.py

raw
1 import io
2 import os
3 import sys
4 import errno
5 import ntpath
6 import pathlib
7 import pickle
8 import posixpath
9 import socket
10 import stat
11 import tempfile
12 import unittest
13 from unittest import mock
14 from urllib.request import pathname2url
15
16 from test.support import import_helper
17 from test.support import is_emscripten, is_wasi
18 from test.support import infinite_recursion
19 from test.support import os_helper
20 from test.support.os_helper import TESTFN, FS_NONASCII, FakePath
21 from test.test_pathlib import test_pathlib_abc
22 from test.test_pathlib.test_pathlib_abc import needs_posix, needs_windows, needs_symlinks
23
24 try:
25 import grp, pwd
26 except ImportError:
27 grp = pwd = None
28
29
30 root_in_posix = False
31 if hasattr(os, 'geteuid'):
32 root_in_posix = (os.geteuid() == 0)
33
34 #
35 # Tests for the pure classes.
36 #
37
38 class PurePathTest(test_pathlib_abc.DummyPurePathTest):
39 cls = pathlib.PurePath
40
41 # Make sure any symbolic links in the base test path are resolved.
42 base = os.path.realpath(TESTFN)
43
44 # Keys are canonical paths, values are list of tuples of arguments
45 # supposed to produce equal paths.
46 equivalences = {
47 'a/b': [
48 ('a', 'b'), ('a/', 'b'), ('a', 'b/'), ('a/', 'b/'),
49 ('a/b/',), ('a//b',), ('a//b//',),
50 # Empty components get removed.
51 ('', 'a', 'b'), ('a', '', 'b'), ('a', 'b', ''),
52 ],
53 '/b/c/d': [
54 ('a', '/b/c', 'd'), ('/a', '/b/c', 'd'),
55 # Empty components get removed.
56 ('/', 'b', '', 'c/d'), ('/', '', 'b/c/d'), ('', '/b/c/d'),
57 ],
58 }
59
60 def test_concrete_class(self):
61 if self.cls is pathlib.PurePath:
62 expected = pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath
63 else:
64 expected = self.cls
65 p = self.cls('a')
66 self.assertIs(type(p), expected)
67
68 def test_concrete_parser(self):
69 if self.cls is pathlib.PurePosixPath:
70 expected = posixpath
71 elif self.cls is pathlib.PureWindowsPath:
72 expected = ntpath
73 else:
74 expected = os.path
75 p = self.cls('a')
76 self.assertIs(p.parser, expected)
77
78 def test_different_parsers_unequal(self):
79 p = self.cls('a')
80 if p.parser is posixpath:
81 q = pathlib.PureWindowsPath('a')
82 else:
83 q = pathlib.PurePosixPath('a')
84 self.assertNotEqual(p, q)
85
86 def test_different_parsers_unordered(self):
87 p = self.cls('a')
88 if p.parser is posixpath:
89 q = pathlib.PureWindowsPath('a')
90 else:
91 q = pathlib.PurePosixPath('a')
92 with self.assertRaises(TypeError):
93 p < q
94 with self.assertRaises(TypeError):
95 p <= q
96 with self.assertRaises(TypeError):
97 p > q
98 with self.assertRaises(TypeError):
99 p >= q
100
101 def test_constructor_nested(self):
102 P = self.cls
103 P(FakePath("a/b/c"))
104 self.assertEqual(P(P('a')), P('a'))
105 self.assertEqual(P(P('a'), 'b'), P('a/b'))
106 self.assertEqual(P(P('a'), P('b')), P('a/b'))
107 self.assertEqual(P(P('a'), P('b'), P('c')), P(FakePath("a/b/c")))
108 self.assertEqual(P(P('./a:b')), P('./a:b'))
109
110 @needs_windows
111 def test_constructor_nested_foreign_flavour(self):
112 # See GH-125069.
113 p1 = pathlib.PurePosixPath('b/c:\\d')
114 p2 = pathlib.PurePosixPath('b/', 'c:\\d')
115 self.assertEqual(p1, p2)
116 self.assertEqual(self.cls(p1), self.cls('b/c:/d'))
117 self.assertEqual(self.cls(p2), self.cls('b/c:/d'))
118
119 def _check_parse_path(self, raw_path, *expected):
120 sep = self.parser.sep
121 actual = self.cls._parse_path(raw_path.replace('/', sep))
122 self.assertEqual(actual, expected)
123 if altsep := self.parser.altsep:
124 actual = self.cls._parse_path(raw_path.replace('/', altsep))
125 self.assertEqual(actual, expected)
126
127 def test_parse_path_common(self):
128 check = self._check_parse_path
129 sep = self.parser.sep
130 check('', '', '', [])
131 check('a', '', '', ['a'])
132 check('a/', '', '', ['a'])
133 check('a/b', '', '', ['a', 'b'])
134 check('a/b/', '', '', ['a', 'b'])
135 check('a/b/c/d', '', '', ['a', 'b', 'c', 'd'])
136 check('a/b//c/d', '', '', ['a', 'b', 'c', 'd'])
137 check('a/b/c/d', '', '', ['a', 'b', 'c', 'd'])
138 check('.', '', '', [])
139 check('././b', '', '', ['b'])
140 check('a/./b', '', '', ['a', 'b'])
141 check('a/./.', '', '', ['a'])
142 check('/a/b', '', sep, ['a', 'b'])
143
144 def test_empty_path(self):
145 # The empty path points to '.'
146 p = self.cls('')
147 self.assertEqual(str(p), '.')
148 # Special case for the empty path.
149 self._check_str('.', ('',))
150
151 def test_parts_interning(self):
152 P = self.cls
153 p = P('/usr/bin/foo')
154 q = P('/usr/local/bin')
155 # 'usr'
156 self.assertIs(p.parts[1], q.parts[1])
157 # 'bin'
158 self.assertIs(p.parts[2], q.parts[3])
159
160 def test_join_nested(self):
161 P = self.cls
162 p = P('a/b').joinpath(P('c'))
163 self.assertEqual(p, P('a/b/c'))
164
165 def test_div_nested(self):
166 P = self.cls
167 p = P('a/b') / P('c')
168 self.assertEqual(p, P('a/b/c'))
169
170 def test_pickling_common(self):
171 P = self.cls
172 for pathstr in ('a', 'a/', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c', 'a/b/c/'):
173 with self.subTest(pathstr=pathstr):
174 p = P(pathstr)
175 for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
176 dumped = pickle.dumps(p, proto)
177 pp = pickle.loads(dumped)
178 self.assertIs(pp.__class__, p.__class__)
179 self.assertEqual(pp, p)
180 self.assertEqual(hash(pp), hash(p))
181 self.assertEqual(str(pp), str(p))
182
183 def test_repr_common(self):
184 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
185 with self.subTest(pathstr=pathstr):
186 p = self.cls(pathstr)
187 clsname = p.__class__.__name__
188 r = repr(p)
189 # The repr() is in the form ClassName("forward-slashes path").
190 self.assertTrue(r.startswith(clsname + '('), r)
191 self.assertTrue(r.endswith(')'), r)
192 inner = r[len(clsname) + 1 : -1]
193 self.assertEqual(eval(inner), p.as_posix())
194
195 def test_fspath_common(self):
196 P = self.cls
197 p = P('a/b')
198 self._check_str(p.__fspath__(), ('a/b',))
199 self._check_str(os.fspath(p), ('a/b',))
200
201 def test_bytes_exc_message(self):
202 P = self.cls
203 message = (r"argument should be a str or an os\.PathLike object "
204 r"where __fspath__ returns a str, not 'bytes'")
205 with self.assertRaisesRegex(TypeError, message):
206 P(b'a')
207 with self.assertRaisesRegex(TypeError, message):
208 P(b'a', 'b')
209 with self.assertRaisesRegex(TypeError, message):
210 P('a', b'b')
211
212 def test_as_bytes_common(self):
213 sep = os.fsencode(self.sep)
214 P = self.cls
215 self.assertEqual(bytes(P('a/b')), b'a' + sep + b'b')
216
217 def test_eq_common(self):
218 P = self.cls
219 self.assertEqual(P('a/b'), P('a/b'))
220 self.assertEqual(P('a/b'), P('a', 'b'))
221 self.assertNotEqual(P('a/b'), P('a'))
222 self.assertNotEqual(P('a/b'), P('/a/b'))
223 self.assertNotEqual(P('a/b'), P())
224 self.assertNotEqual(P('/a/b'), P('/'))
225 self.assertNotEqual(P(), P('/'))
226 self.assertNotEqual(P(), "")
227 self.assertNotEqual(P(), {})
228 self.assertNotEqual(P(), int)
229
230 def test_equivalences(self, equivalences=None):
231 if equivalences is None:
232 equivalences = self.equivalences
233 for k, tuples in equivalences.items():
234 canon = k.replace('/', self.sep)
235 posix = k.replace(self.sep, '/')
236 if canon != posix:
237 tuples = tuples + [
238 tuple(part.replace('/', self.sep) for part in t)
239 for t in tuples
240 ]
241 tuples.append((posix, ))
242 pcanon = self.cls(canon)
243 for t in tuples:
244 p = self.cls(*t)
245 self.assertEqual(p, pcanon, "failed with args {}".format(t))
246 self.assertEqual(hash(p), hash(pcanon))
247 self.assertEqual(str(p), canon)
248 self.assertEqual(p.as_posix(), posix)
249
250 def test_ordering_common(self):
251 # Ordering is tuple-alike.
252 def assertLess(a, b):
253 self.assertLess(a, b)
254 self.assertGreater(b, a)
255 P = self.cls
256 a = P('a')
257 b = P('a/b')
258 c = P('abc')
259 d = P('b')
260 assertLess(a, b)
261 assertLess(a, c)
262 assertLess(a, d)
263 assertLess(b, c)
264 assertLess(c, d)
265 P = self.cls
266 a = P('/a')
267 b = P('/a/b')
268 c = P('/abc')
269 d = P('/b')
270 assertLess(a, b)
271 assertLess(a, c)
272 assertLess(a, d)
273 assertLess(b, c)
274 assertLess(c, d)
275 with self.assertRaises(TypeError):
276 P() < {}
277
278 def test_as_uri_common(self):
279 P = self.cls
280 with self.assertRaises(ValueError):
281 P('a').as_uri()
282 with self.assertRaises(ValueError):
283 P().as_uri()
284
285 def test_repr_roundtrips(self):
286 for pathstr in ('a', 'a/b', 'a/b/c', '/', '/a/b', '/a/b/c'):
287 with self.subTest(pathstr=pathstr):
288 p = self.cls(pathstr)
289 r = repr(p)
290 # The repr() roundtrips.
291 q = eval(r, pathlib.__dict__)
292 self.assertIs(q.__class__, p.__class__)
293 self.assertEqual(q, p)
294 self.assertEqual(repr(q), r)
295
296 def test_name_empty(self):
297 P = self.cls
298 self.assertEqual(P('').name, '')
299 self.assertEqual(P('.').name, '')
300 self.assertEqual(P('/a/b/.').name, 'b')
301
302 def test_stem_empty(self):
303 P = self.cls
304 self.assertEqual(P('').stem, '')
305 self.assertEqual(P('.').stem, '')
306
307 def test_with_name_empty(self):
308 P = self.cls
309 self.assertRaises(ValueError, P('').with_name, 'd.xml')
310 self.assertRaises(ValueError, P('.').with_name, 'd.xml')
311 self.assertRaises(ValueError, P('/').with_name, 'd.xml')
312 self.assertRaises(ValueError, P('a/b').with_name, '')
313 self.assertRaises(ValueError, P('a/b').with_name, '.')
314
315 def test_with_stem_empty(self):
316 P = self.cls
317 self.assertRaises(ValueError, P('').with_stem, 'd')
318 self.assertRaises(ValueError, P('.').with_stem, 'd')
319 self.assertRaises(ValueError, P('/').with_stem, 'd')
320 self.assertRaises(ValueError, P('a/b').with_stem, '')
321 self.assertRaises(ValueError, P('a/b').with_stem, '.')
322
323 def test_relative_to_several_args(self):
324 P = self.cls
325 p = P('a/b')
326 with self.assertWarns(DeprecationWarning):
327 p.relative_to('a', 'b')
328 p.relative_to('a', 'b', walk_up=True)
329
330 def test_is_relative_to_several_args(self):
331 P = self.cls
332 p = P('a/b')
333 with self.assertWarns(DeprecationWarning):
334 p.is_relative_to('a', 'b')
335
336 def test_is_reserved_deprecated(self):
337 P = self.cls
338 p = P('a/b')
339 with self.assertWarns(DeprecationWarning):
340 p.is_reserved()
341
342 def test_match_empty(self):
343 P = self.cls
344 self.assertRaises(ValueError, P('a').match, '')
345 self.assertRaises(ValueError, P('a').match, '.')
346
347 @needs_posix
348 def test_parse_path_posix(self):
349 check = self._check_parse_path
350 # Collapsing of excess leading slashes, except for the double-slash
351 # special case.
352 check('//a/b', '', '//', ['a', 'b'])
353 check('///a/b', '', '/', ['a', 'b'])
354 check('////a/b', '', '/', ['a', 'b'])
355 # Paths which look like NT paths aren't treated specially.
356 check('c:a', '', '', ['c:a',])
357 check('c:\\a', '', '', ['c:\\a',])
358 check('\\a', '', '', ['\\a',])
359
360 @needs_posix
361 def test_eq_posix(self):
362 P = self.cls
363 self.assertNotEqual(P('a/b'), P('A/b'))
364 self.assertEqual(P('/a'), P('///a'))
365 self.assertNotEqual(P('/a'), P('//a'))
366
367 @needs_posix
368 def test_as_uri_posix(self):
369 P = self.cls
370 self.assertEqual(P('/').as_uri(), 'file:///')
371 self.assertEqual(P('/a/b.c').as_uri(), 'file:///a/b.c')
372 self.assertEqual(P('/a/b%#c').as_uri(), 'file:///a/b%25%23c')
373
374 @needs_posix
375 def test_as_uri_non_ascii(self):
376 from urllib.parse import quote_from_bytes
377 P = self.cls
378 try:
379 os.fsencode('\xe9')
380 except UnicodeEncodeError:
381 self.skipTest("\\xe9 cannot be encoded to the filesystem encoding")
382 self.assertEqual(P('/a/b\xe9').as_uri(),
383 'file:///a/b' + quote_from_bytes(os.fsencode('\xe9')))
384
385 @needs_posix
386 def test_parse_windows_path(self):
387 P = self.cls
388 p = P('c:', 'a', 'b')
389 pp = P(pathlib.PureWindowsPath('c:\\a\\b'))
390 self.assertEqual(p, pp)
391
392 windows_equivalences = {
393 './a:b': [ ('./a:b',) ],
394 'c:a': [ ('c:', 'a'), ('c:', 'a/'), ('.', 'c:', 'a') ],
395 'c:/a': [
396 ('c:/', 'a'), ('c:', '/', 'a'), ('c:', '/a'),
397 ('/z', 'c:/', 'a'), ('//x/y', 'c:/', 'a'),
398 ],
399 '//a/b/': [ ('//a/b',) ],
400 '//a/b/c': [
401 ('//a/b', 'c'), ('//a/b/', 'c'),
402 ],
403 }
404
405 @needs_windows
406 def test_equivalences_windows(self):
407 self.test_equivalences(self.windows_equivalences)
408
409 @needs_windows
410 def test_parse_path_windows(self):
411 check = self._check_parse_path
412 # First part is anchored.
413 check('c:', 'c:', '', [])
414 check('c:/', 'c:', '\\', [])
415 check('/', '', '\\', [])
416 check('c:a', 'c:', '', ['a'])
417 check('c:/a', 'c:', '\\', ['a'])
418 check('/a', '', '\\', ['a'])
419 # UNC paths.
420 check('//', '\\\\', '', [])
421 check('//a', '\\\\a', '', [])
422 check('//a/', '\\\\a\\', '', [])
423 check('//a/b', '\\\\a\\b', '\\', [])
424 check('//a/b/', '\\\\a\\b', '\\', [])
425 check('//a/b/c', '\\\\a\\b', '\\', ['c'])
426 # Collapsing and stripping excess slashes.
427 check('Z://b//c/d/', 'Z:', '\\', ['b', 'c', 'd'])
428 # UNC paths.
429 check('//b/c//d', '\\\\b\\c', '\\', ['d'])
430 # Extended paths.
431 check('//./c:', '\\\\.\\c:', '', [])
432 check('//?/c:/', '\\\\?\\c:', '\\', [])
433 check('//?/c:/a', '\\\\?\\c:', '\\', ['a'])
434 # Extended UNC paths (format is "\\?\UNC\server\share").
435 check('//?', '\\\\?', '', [])
436 check('//?/', '\\\\?\\', '', [])
437 check('//?/UNC', '\\\\?\\UNC', '', [])
438 check('//?/UNC/', '\\\\?\\UNC\\', '', [])
439 check('//?/UNC/b', '\\\\?\\UNC\\b', '', [])
440 check('//?/UNC/b/', '\\\\?\\UNC\\b\\', '', [])
441 check('//?/UNC/b/c', '\\\\?\\UNC\\b\\c', '\\', [])
442 check('//?/UNC/b/c/', '\\\\?\\UNC\\b\\c', '\\', [])
443 check('//?/UNC/b/c/d', '\\\\?\\UNC\\b\\c', '\\', ['d'])
444 # UNC device paths
445 check('//./BootPartition/', '\\\\.\\BootPartition', '\\', [])
446 check('//?/BootPartition/', '\\\\?\\BootPartition', '\\', [])
447 check('//./PhysicalDrive0', '\\\\.\\PhysicalDrive0', '', [])
448 check('//?/Volume{}/', '\\\\?\\Volume{}', '\\', [])
449 check('//./nul', '\\\\.\\nul', '', [])
450 # Paths to files with NTFS alternate data streams
451 check('./c:s', '', '', ['c:s'])
452 check('cc:s', '', '', ['cc:s'])
453 check('C:c:s', 'C:', '', ['c:s'])
454 check('C:/c:s', 'C:', '\\', ['c:s'])
455 check('D:a/c:b', 'D:', '', ['a', 'c:b'])
456 check('D:/a/c:b', 'D:', '\\', ['a', 'c:b'])
457
458 @needs_windows
459 def test_eq_windows(self):
460 P = self.cls
461 self.assertEqual(P('c:a/b'), P('c:a/b'))
462 self.assertEqual(P('c:a/b'), P('c:', 'a', 'b'))
463 self.assertNotEqual(P('c:a/b'), P('d:a/b'))
464 self.assertNotEqual(P('c:a/b'), P('c:/a/b'))
465 self.assertNotEqual(P('/a/b'), P('c:/a/b'))
466 # Case-insensitivity.
467 self.assertEqual(P('a/B'), P('A/b'))
468 self.assertEqual(P('C:a/B'), P('c:A/b'))
469 self.assertEqual(P('//Some/SHARE/a/B'), P('//somE/share/A/b'))
470 self.assertEqual(P('\u0130'), P('i\u0307'))
471
472 @needs_windows
473 def test_as_uri_windows(self):
474 P = self.cls
475 with self.assertRaises(ValueError):
476 P('/a/b').as_uri()
477 with self.assertRaises(ValueError):
478 P('c:a/b').as_uri()
479 self.assertEqual(P('c:/').as_uri(), 'file:///c:/')
480 self.assertEqual(P('c:/a/b.c').as_uri(), 'file:///c:/a/b.c')
481 self.assertEqual(P('c:/a/b%#c').as_uri(), 'file:///c:/a/b%25%23c')
482 self.assertEqual(P('//some/share/').as_uri(), 'file://some/share/')
483 self.assertEqual(P('//some/share/a/b.c').as_uri(),
484 'file://some/share/a/b.c')
485
486 from urllib.parse import quote_from_bytes
487 QUOTED_FS_NONASCII = quote_from_bytes(os.fsencode(FS_NONASCII))
488 self.assertEqual(P('c:/a/b' + FS_NONASCII).as_uri(),
489 'file:///c:/a/b' + QUOTED_FS_NONASCII)
490 self.assertEqual(P('//some/share/a/b%#c' + FS_NONASCII).as_uri(),
491 'file://some/share/a/b%25%23c' + QUOTED_FS_NONASCII)
492
493 @needs_windows
494 def test_ordering_windows(self):
495 # Case-insensitivity.
496 def assertOrderedEqual(a, b):
497 self.assertLessEqual(a, b)
498 self.assertGreaterEqual(b, a)
499 P = self.cls
500 p = P('c:A/b')
501 q = P('C:a/B')
502 assertOrderedEqual(p, q)
503 self.assertFalse(p < q)
504 self.assertFalse(p > q)
505 p = P('//some/Share/A/b')
506 q = P('//Some/SHARE/a/B')
507 assertOrderedEqual(p, q)
508 self.assertFalse(p < q)
509 self.assertFalse(p > q)
510
511
512 class PurePosixPathTest(PurePathTest):
513 cls = pathlib.PurePosixPath
514
515
516 class PureWindowsPathTest(PurePathTest):
517 cls = pathlib.PureWindowsPath
518
519
520 class PurePathSubclassTest(PurePathTest):
521 class cls(pathlib.PurePath):
522 pass
523
524 # repr() roundtripping is not supported in custom subclass.
525 test_repr_roundtrips = None
526
527
528 #
529 # Tests for the concrete classes.
530 #
531
532 class PathTest(test_pathlib_abc.DummyPathTest, PurePathTest):
533 """Tests for the FS-accessing functionalities of the Path classes."""
534 cls = pathlib.Path
535 can_symlink = os_helper.can_symlink()
536
537 def setUp(self):
538 super().setUp()
539 os.chmod(self.parser.join(self.base, 'dirE'), 0)
540
541 def tearDown(self):
542 os.chmod(self.parser.join(self.base, 'dirE'), 0o777)
543 os_helper.rmtree(self.base)
544
545 def tempdir(self):
546 d = os_helper._longpath(tempfile.mkdtemp(suffix='-dirD',
547 dir=os.getcwd()))
548 self.addCleanup(os_helper.rmtree, d)
549 return d
550
551 def test_matches_pathbase_api(self):
552 our_names = {name for name in dir(self.cls) if name[0] != '_'}
553 our_names.remove('is_reserved') # only present in PurePath
554 path_names = {name for name in dir(pathlib._abc.PathBase) if name[0] != '_'}
555 self.assertEqual(our_names, path_names)
556 for attr_name in our_names:
557 if attr_name == 'parser':
558 # On Windows, Path.parser is ntpath, but PathBase.parser is
559 # posixpath, and so their docstrings differ.
560 continue
561 our_attr = getattr(self.cls, attr_name)
562 path_attr = getattr(pathlib._abc.PathBase, attr_name)
563 self.assertEqual(our_attr.__doc__, path_attr.__doc__)
564
565 def test_concrete_class(self):
566 if self.cls is pathlib.Path:
567 expected = pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath
568 else:
569 expected = self.cls
570 p = self.cls('a')
571 self.assertIs(type(p), expected)
572
573 def test_unsupported_parser(self):
574 if self.cls.parser is os.path:
575 self.skipTest("path parser is supported")
576 else:
577 self.assertRaises(pathlib.UnsupportedOperation, self.cls)
578
579 def _test_cwd(self, p):
580 q = self.cls(os.getcwd())
581 self.assertEqual(p, q)
582 self.assertEqualNormCase(str(p), str(q))
583 self.assertIs(type(p), type(q))
584 self.assertTrue(p.is_absolute())
585
586 def test_cwd(self):
587 p = self.cls.cwd()
588 self._test_cwd(p)
589
590 def test_absolute_common(self):
591 P = self.cls
592
593 with mock.patch("os.getcwd") as getcwd:
594 getcwd.return_value = self.base
595
596 # Simple relative paths.
597 self.assertEqual(str(P().absolute()), self.base)
598 self.assertEqual(str(P('.').absolute()), self.base)
599 self.assertEqual(str(P('a').absolute()), os.path.join(self.base, 'a'))
600 self.assertEqual(str(P('a', 'b', 'c').absolute()), os.path.join(self.base, 'a', 'b', 'c'))
601
602 # Symlinks should not be resolved.
603 self.assertEqual(str(P('linkB', 'fileB').absolute()), os.path.join(self.base, 'linkB', 'fileB'))
604 self.assertEqual(str(P('brokenLink').absolute()), os.path.join(self.base, 'brokenLink'))
605 self.assertEqual(str(P('brokenLinkLoop').absolute()), os.path.join(self.base, 'brokenLinkLoop'))
606
607 # '..' entries should be preserved and not normalised.
608 self.assertEqual(str(P('..').absolute()), os.path.join(self.base, '..'))
609 self.assertEqual(str(P('a', '..').absolute()), os.path.join(self.base, 'a', '..'))
610 self.assertEqual(str(P('..', 'b').absolute()), os.path.join(self.base, '..', 'b'))
611
612 def _test_home(self, p):
613 q = self.cls(os.path.expanduser('~'))
614 self.assertEqual(p, q)
615 self.assertEqualNormCase(str(p), str(q))
616 self.assertIs(type(p), type(q))
617 self.assertTrue(p.is_absolute())
618
619 @unittest.skipIf(
620 pwd is None, reason="Test requires pwd module to get homedir."
621 )
622 def test_home(self):
623 with os_helper.EnvironmentVarGuard() as env:
624 self._test_home(self.cls.home())
625
626 env.clear()
627 env['USERPROFILE'] = os.path.join(self.base, 'userprofile')
628 self._test_home(self.cls.home())
629
630 # bpo-38883: ignore `HOME` when set on windows
631 env['HOME'] = os.path.join(self.base, 'home')
632 self._test_home(self.cls.home())
633
634 @unittest.skipIf(is_wasi, "WASI has no user accounts.")
635 def test_expanduser_common(self):
636 P = self.cls
637 p = P('~')
638 self.assertEqual(p.expanduser(), P(os.path.expanduser('~')))
639 p = P('foo')
640 self.assertEqual(p.expanduser(), p)
641 p = P('/~')
642 self.assertEqual(p.expanduser(), p)
643 p = P('../~')
644 self.assertEqual(p.expanduser(), p)
645 p = P(P('').absolute().anchor) / '~'
646 self.assertEqual(p.expanduser(), p)
647 p = P('~/a:b')
648 self.assertEqual(p.expanduser(), P(os.path.expanduser('~'), './a:b'))
649
650 def test_with_segments(self):
651 class P(self.cls):
652 def __init__(self, *pathsegments, session_id):
653 super().__init__(*pathsegments)
654 self.session_id = session_id
655
656 def with_segments(self, *pathsegments):
657 return type(self)(*pathsegments, session_id=self.session_id)
658 p = P(self.base, session_id=42)
659 self.assertEqual(42, p.absolute().session_id)
660 self.assertEqual(42, p.resolve().session_id)
661 if not is_wasi: # WASI has no user accounts.
662 self.assertEqual(42, p.with_segments('~').expanduser().session_id)
663 self.assertEqual(42, (p / 'fileA').rename(p / 'fileB').session_id)
664 self.assertEqual(42, (p / 'fileB').replace(p / 'fileA').session_id)
665 if self.can_symlink:
666 self.assertEqual(42, (p / 'linkA').readlink().session_id)
667 for path in p.iterdir():
668 self.assertEqual(42, path.session_id)
669 for path in p.glob('*'):
670 self.assertEqual(42, path.session_id)
671 for path in p.rglob('*'):
672 self.assertEqual(42, path.session_id)
673 for dirpath, dirnames, filenames in p.walk():
674 self.assertEqual(42, dirpath.session_id)
675
676 def test_open_unbuffered(self):
677 p = self.cls(self.base)
678 with (p / 'fileA').open('rb', buffering=0) as f:
679 self.assertIsInstance(f, io.RawIOBase)
680 self.assertEqual(f.read().strip(), b"this is file A")
681
682 def test_resolve_nonexist_relative_issue38671(self):
683 p = self.cls('non', 'exist')
684
685 old_cwd = os.getcwd()
686 os.chdir(self.base)
687 try:
688 self.assertEqual(p.resolve(), self.cls(self.base, p))
689 finally:
690 os.chdir(old_cwd)
691
692 @os_helper.skip_unless_working_chmod
693 def test_chmod(self):
694 p = self.cls(self.base) / 'fileA'
695 mode = p.stat().st_mode
696 # Clear writable bit.
697 new_mode = mode & ~0o222
698 p.chmod(new_mode)
699 self.assertEqual(p.stat().st_mode, new_mode)
700 # Set writable bit.
701 new_mode = mode | 0o222
702 p.chmod(new_mode)
703 self.assertEqual(p.stat().st_mode, new_mode)
704
705 # On Windows, os.chmod does not follow symlinks (issue #15411)
706 @needs_posix
707 @os_helper.skip_unless_working_chmod
708 def test_chmod_follow_symlinks_true(self):
709 p = self.cls(self.base) / 'linkA'
710 q = p.resolve()
711 mode = q.stat().st_mode
712 # Clear writable bit.
713 new_mode = mode & ~0o222
714 p.chmod(new_mode, follow_symlinks=True)
715 self.assertEqual(q.stat().st_mode, new_mode)
716 # Set writable bit
717 new_mode = mode | 0o222
718 p.chmod(new_mode, follow_symlinks=True)
719 self.assertEqual(q.stat().st_mode, new_mode)
720
721 # XXX also need a test for lchmod.
722
723 def _get_pw_name_or_skip_test(self, uid):
724 try:
725 return pwd.getpwuid(uid).pw_name
726 except KeyError:
727 self.skipTest(
728 "user %d doesn't have an entry in the system database" % uid)
729
730 @unittest.skipUnless(pwd, "the pwd module is needed for this test")
731 def test_owner(self):
732 p = self.cls(self.base) / 'fileA'
733 expected_uid = p.stat().st_uid
734 expected_name = self._get_pw_name_or_skip_test(expected_uid)
735
736 self.assertEqual(expected_name, p.owner())
737
738 @unittest.skipUnless(pwd, "the pwd module is needed for this test")
739 @unittest.skipUnless(root_in_posix, "test needs root privilege")
740 def test_owner_no_follow_symlinks(self):
741 all_users = [u.pw_uid for u in pwd.getpwall()]
742 if len(all_users) < 2:
743 self.skipTest("test needs more than one user")
744
745 target = self.cls(self.base) / 'fileA'
746 link = self.cls(self.base) / 'linkA'
747
748 uid_1, uid_2 = all_users[:2]
749 os.chown(target, uid_1, -1)
750 os.chown(link, uid_2, -1, follow_symlinks=False)
751
752 expected_uid = link.stat(follow_symlinks=False).st_uid
753 expected_name = self._get_pw_name_or_skip_test(expected_uid)
754
755 self.assertEqual(expected_uid, uid_2)
756 self.assertEqual(expected_name, link.owner(follow_symlinks=False))
757
758 def _get_gr_name_or_skip_test(self, gid):
759 try:
760 return grp.getgrgid(gid).gr_name
761 except KeyError:
762 self.skipTest(
763 "group %d doesn't have an entry in the system database" % gid)
764
765 @unittest.skipUnless(grp, "the grp module is needed for this test")
766 def test_group(self):
767 p = self.cls(self.base) / 'fileA'
768 expected_gid = p.stat().st_gid
769 expected_name = self._get_gr_name_or_skip_test(expected_gid)
770
771 self.assertEqual(expected_name, p.group())
772
773 @unittest.skipUnless(grp, "the grp module is needed for this test")
774 @unittest.skipUnless(root_in_posix, "test needs root privilege")
775 def test_group_no_follow_symlinks(self):
776 all_groups = [g.gr_gid for g in grp.getgrall()]
777 if len(all_groups) < 2:
778 self.skipTest("test needs more than one group")
779
780 target = self.cls(self.base) / 'fileA'
781 link = self.cls(self.base) / 'linkA'
782
783 gid_1, gid_2 = all_groups[:2]
784 os.chown(target, -1, gid_1)
785 os.chown(link, -1, gid_2, follow_symlinks=False)
786
787 expected_gid = link.stat(follow_symlinks=False).st_gid
788 expected_name = self._get_gr_name_or_skip_test(expected_gid)
789
790 self.assertEqual(expected_gid, gid_2)
791 self.assertEqual(expected_name, link.group(follow_symlinks=False))
792
793 def test_unlink(self):
794 p = self.cls(self.base) / 'fileA'
795 p.unlink()
796 self.assertFileNotFound(p.stat)
797 self.assertFileNotFound(p.unlink)
798
799 def test_unlink_missing_ok(self):
800 p = self.cls(self.base) / 'fileAAA'
801 self.assertFileNotFound(p.unlink)
802 p.unlink(missing_ok=True)
803
804 def test_rmdir(self):
805 p = self.cls(self.base) / 'dirA'
806 for q in p.iterdir():
807 q.unlink()
808 p.rmdir()
809 self.assertFileNotFound(p.stat)
810 self.assertFileNotFound(p.unlink)
811
812 @os_helper.skip_unless_hardlink
813 def test_hardlink_to(self):
814 P = self.cls(self.base)
815 target = P / 'fileA'
816 size = target.stat().st_size
817 # linking to another path.
818 link = P / 'dirA' / 'fileAA'
819 link.hardlink_to(target)
820 self.assertEqual(link.stat().st_size, size)
821 self.assertTrue(os.path.samefile(target, link))
822 self.assertTrue(target.exists())
823 # Linking to a str of a relative path.
824 link2 = P / 'dirA' / 'fileAAA'
825 target2 = self.parser.join(TESTFN, 'fileA')
826 link2.hardlink_to(target2)
827 self.assertEqual(os.stat(target2).st_size, size)
828 self.assertTrue(link2.exists())
829
830 @unittest.skipIf(hasattr(os, "link"), "os.link() is present")
831 def test_hardlink_to_unsupported(self):
832 P = self.cls(self.base)
833 p = P / 'fileA'
834 # linking to another path.
835 q = P / 'dirA' / 'fileAA'
836 with self.assertRaises(pathlib.UnsupportedOperation):
837 q.hardlink_to(p)
838
839 def test_rename(self):
840 P = self.cls(self.base)
841 p = P / 'fileA'
842 size = p.stat().st_size
843 # Renaming to another path.
844 q = P / 'dirA' / 'fileAA'
845 renamed_p = p.rename(q)
846 self.assertEqual(renamed_p, q)
847 self.assertEqual(q.stat().st_size, size)
848 self.assertFileNotFound(p.stat)
849 # Renaming to a str of a relative path.
850 r = self.parser.join(TESTFN, 'fileAAA')
851 renamed_q = q.rename(r)
852 self.assertEqual(renamed_q, self.cls(r))
853 self.assertEqual(os.stat(r).st_size, size)
854 self.assertFileNotFound(q.stat)
855
856 def test_replace(self):
857 P = self.cls(self.base)
858 p = P / 'fileA'
859 size = p.stat().st_size
860 # Replacing a non-existing path.
861 q = P / 'dirA' / 'fileAA'
862 replaced_p = p.replace(q)
863 self.assertEqual(replaced_p, q)
864 self.assertEqual(q.stat().st_size, size)
865 self.assertFileNotFound(p.stat)
866 # Replacing another (existing) path.
867 r = self.parser.join(TESTFN, 'dirB', 'fileB')
868 replaced_q = q.replace(r)
869 self.assertEqual(replaced_q, self.cls(r))
870 self.assertEqual(os.stat(r).st_size, size)
871 self.assertFileNotFound(q.stat)
872
873 def test_touch_common(self):
874 P = self.cls(self.base)
875 p = P / 'newfileA'
876 self.assertFalse(p.exists())
877 p.touch()
878 self.assertTrue(p.exists())
879 st = p.stat()
880 old_mtime = st.st_mtime
881 old_mtime_ns = st.st_mtime_ns
882 # Rewind the mtime sufficiently far in the past to work around
883 # filesystem-specific timestamp granularity.
884 os.utime(str(p), (old_mtime - 10, old_mtime - 10))
885 # The file mtime should be refreshed by calling touch() again.
886 p.touch()
887 st = p.stat()
888 self.assertGreaterEqual(st.st_mtime_ns, old_mtime_ns)
889 self.assertGreaterEqual(st.st_mtime, old_mtime)
890 # Now with exist_ok=False.
891 p = P / 'newfileB'
892 self.assertFalse(p.exists())
893 p.touch(mode=0o700, exist_ok=False)
894 self.assertTrue(p.exists())
895 self.assertRaises(OSError, p.touch, exist_ok=False)
896
897 def test_touch_nochange(self):
898 P = self.cls(self.base)
899 p = P / 'fileA'
900 p.touch()
901 with p.open('rb') as f:
902 self.assertEqual(f.read().strip(), b"this is file A")
903
904 def test_mkdir(self):
905 P = self.cls(self.base)
906 p = P / 'newdirA'
907 self.assertFalse(p.exists())
908 p.mkdir()
909 self.assertTrue(p.exists())
910 self.assertTrue(p.is_dir())
911 with self.assertRaises(OSError) as cm:
912 p.mkdir()
913 self.assertEqual(cm.exception.errno, errno.EEXIST)
914
915 def test_mkdir_parents(self):
916 # Creating a chain of directories.
917 p = self.cls(self.base, 'newdirB', 'newdirC')
918 self.assertFalse(p.exists())
919 with self.assertRaises(OSError) as cm:
920 p.mkdir()
921 self.assertEqual(cm.exception.errno, errno.ENOENT)
922 p.mkdir(parents=True)
923 self.assertTrue(p.exists())
924 self.assertTrue(p.is_dir())
925 with self.assertRaises(OSError) as cm:
926 p.mkdir(parents=True)
927 self.assertEqual(cm.exception.errno, errno.EEXIST)
928 # Test `mode` arg.
929 mode = stat.S_IMODE(p.stat().st_mode) # Default mode.
930 p = self.cls(self.base, 'newdirD', 'newdirE')
931 p.mkdir(0o555, parents=True)
932 self.assertTrue(p.exists())
933 self.assertTrue(p.is_dir())
934 if os.name != 'nt':
935 # The directory's permissions follow the mode argument.
936 self.assertEqual(stat.S_IMODE(p.stat().st_mode), 0o7555 & mode)
937 # The parent's permissions follow the default process settings.
938 self.assertEqual(stat.S_IMODE(p.parent.stat().st_mode), mode)
939
940 def test_mkdir_exist_ok(self):
941 p = self.cls(self.base, 'dirB')
942 st_ctime_first = p.stat().st_ctime
943 self.assertTrue(p.exists())
944 self.assertTrue(p.is_dir())
945 with self.assertRaises(FileExistsError) as cm:
946 p.mkdir()
947 self.assertEqual(cm.exception.errno, errno.EEXIST)
948 p.mkdir(exist_ok=True)
949 self.assertTrue(p.exists())
950 self.assertEqual(p.stat().st_ctime, st_ctime_first)
951
952 def test_mkdir_exist_ok_with_parent(self):
953 p = self.cls(self.base, 'dirC')
954 self.assertTrue(p.exists())
955 with self.assertRaises(FileExistsError) as cm:
956 p.mkdir()
957 self.assertEqual(cm.exception.errno, errno.EEXIST)
958 p = p / 'newdirC'
959 p.mkdir(parents=True)
960 st_ctime_first = p.stat().st_ctime
961 self.assertTrue(p.exists())
962 with self.assertRaises(FileExistsError) as cm:
963 p.mkdir(parents=True)
964 self.assertEqual(cm.exception.errno, errno.EEXIST)
965 p.mkdir(parents=True, exist_ok=True)
966 self.assertTrue(p.exists())
967 self.assertEqual(p.stat().st_ctime, st_ctime_first)
968
969 @unittest.skipIf(is_emscripten, "FS root cannot be modified on Emscripten.")
970 def test_mkdir_exist_ok_root(self):
971 # Issue #25803: A drive root could raise PermissionError on Windows.
972 self.cls('/').resolve().mkdir(exist_ok=True)
973 self.cls('/').resolve().mkdir(parents=True, exist_ok=True)
974
975 @needs_windows # XXX: not sure how to test this on POSIX.
976 def test_mkdir_with_unknown_drive(self):
977 for d in 'ZYXWVUTSRQPONMLKJIHGFEDCBA':
978 p = self.cls(d + ':\\')
979 if not p.is_dir():
980 break
981 else:
982 self.skipTest("cannot find a drive that doesn't exist")
983 with self.assertRaises(OSError):
984 (p / 'child' / 'path').mkdir(parents=True)
985
986 def test_mkdir_with_child_file(self):
987 p = self.cls(self.base, 'dirB', 'fileB')
988 self.assertTrue(p.exists())
989 # An exception is raised when the last path component is an existing
990 # regular file, regardless of whether exist_ok is true or not.
991 with self.assertRaises(FileExistsError) as cm:
992 p.mkdir(parents=True)
993 self.assertEqual(cm.exception.errno, errno.EEXIST)
994 with self.assertRaises(FileExistsError) as cm:
995 p.mkdir(parents=True, exist_ok=True)
996 self.assertEqual(cm.exception.errno, errno.EEXIST)
997
998 def test_mkdir_no_parents_file(self):
999 p = self.cls(self.base, 'fileA')
1000 self.assertTrue(p.exists())
1001 # An exception is raised when the last path component is an existing
1002 # regular file, regardless of whether exist_ok is true or not.
1003 with self.assertRaises(FileExistsError) as cm:
1004 p.mkdir()
1005 self.assertEqual(cm.exception.errno, errno.EEXIST)
1006 with self.assertRaises(FileExistsError) as cm:
1007 p.mkdir(exist_ok=True)
1008 self.assertEqual(cm.exception.errno, errno.EEXIST)
1009
1010 def test_mkdir_concurrent_parent_creation(self):
1011 for pattern_num in range(32):
1012 p = self.cls(self.base, 'dirCPC%d' % pattern_num)
1013 self.assertFalse(p.exists())
1014
1015 real_mkdir = os.mkdir
1016 def my_mkdir(path, mode=0o777):
1017 path = str(path)
1018 # Emulate another process that would create the directory
1019 # just before we try to create it ourselves. We do it
1020 # in all possible pattern combinations, assuming that this
1021 # function is called at most 5 times (dirCPC/dir1/dir2,
1022 # dirCPC/dir1, dirCPC, dirCPC/dir1, dirCPC/dir1/dir2).
1023 if pattern.pop():
1024 real_mkdir(path, mode) # From another process.
1025 concurrently_created.add(path)
1026 real_mkdir(path, mode) # Our real call.
1027
1028 pattern = [bool(pattern_num & (1 << n)) for n in range(5)]
1029 concurrently_created = set()
1030 p12 = p / 'dir1' / 'dir2'
1031 try:
1032 with mock.patch("os.mkdir", my_mkdir):
1033 p12.mkdir(parents=True, exist_ok=False)
1034 except FileExistsError:
1035 self.assertIn(str(p12), concurrently_created)
1036 else:
1037 self.assertNotIn(str(p12), concurrently_created)
1038 self.assertTrue(p.exists())
1039
1040 @needs_symlinks
1041 def test_symlink_to(self):
1042 P = self.cls(self.base)
1043 target = P / 'fileA'
1044 # Symlinking a path target.
1045 link = P / 'dirA' / 'linkAA'
1046 link.symlink_to(target)
1047 self.assertEqual(link.stat(), target.stat())
1048 self.assertNotEqual(link.lstat(), target.stat())
1049 # Symlinking a str target.
1050 link = P / 'dirA' / 'linkAAA'
1051 link.symlink_to(str(target))
1052 self.assertEqual(link.stat(), target.stat())
1053 self.assertNotEqual(link.lstat(), target.stat())
1054 self.assertFalse(link.is_dir())
1055 # Symlinking to a directory.
1056 target = P / 'dirB'
1057 link = P / 'dirA' / 'linkAAAA'
1058 link.symlink_to(target, target_is_directory=True)
1059 self.assertEqual(link.stat(), target.stat())
1060 self.assertNotEqual(link.lstat(), target.stat())
1061 self.assertTrue(link.is_dir())
1062 self.assertTrue(list(link.iterdir()))
1063
1064 @unittest.skipIf(hasattr(os, "symlink"), "os.symlink() is present")
1065 def test_symlink_to_unsupported(self):
1066 P = self.cls(self.base)
1067 p = P / 'fileA'
1068 # linking to another path.
1069 q = P / 'dirA' / 'fileAA'
1070 with self.assertRaises(pathlib.UnsupportedOperation):
1071 q.symlink_to(p)
1072
1073 def test_is_junction(self):
1074 P = self.cls(self.base)
1075
1076 with mock.patch.object(P.parser, 'isjunction'):
1077 self.assertEqual(P.is_junction(), P.parser.isjunction.return_value)
1078 P.parser.isjunction.assert_called_once_with(P)
1079
1080 @unittest.skipUnless(hasattr(os, "mkfifo"), "os.mkfifo() required")
1081 @unittest.skipIf(sys.platform == "vxworks",
1082 "fifo requires special path on VxWorks")
1083 def test_is_fifo_true(self):
1084 P = self.cls(self.base, 'myfifo')
1085 try:
1086 os.mkfifo(str(P))
1087 except PermissionError as e:
1088 self.skipTest('os.mkfifo(): %s' % e)
1089 self.assertTrue(P.is_fifo())
1090 self.assertFalse(P.is_socket())
1091 self.assertFalse(P.is_file())
1092 self.assertIs(self.cls(self.base, 'myfifo\udfff').is_fifo(), False)
1093 self.assertIs(self.cls(self.base, 'myfifo\x00').is_fifo(), False)
1094
1095 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required")
1096 @unittest.skipIf(
1097 is_emscripten, "Unix sockets are not implemented on Emscripten."
1098 )
1099 @unittest.skipIf(
1100 is_wasi, "Cannot create socket on WASI."
1101 )
1102 def test_is_socket_true(self):
1103 P = self.cls(self.base, 'mysock')
1104 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1105 self.addCleanup(sock.close)
1106 try:
1107 sock.bind(str(P))
1108 except OSError as e:
1109 if (isinstance(e, PermissionError) or
1110 "AF_UNIX path too long" in str(e)):
1111 self.skipTest("cannot bind Unix socket: " + str(e))
1112 self.assertTrue(P.is_socket())
1113 self.assertFalse(P.is_fifo())
1114 self.assertFalse(P.is_file())
1115 self.assertIs(self.cls(self.base, 'mysock\udfff').is_socket(), False)
1116 self.assertIs(self.cls(self.base, 'mysock\x00').is_socket(), False)
1117
1118 def test_is_char_device_true(self):
1119 # os.devnull should generally be a char device.
1120 P = self.cls(os.devnull)
1121 if not P.exists():
1122 self.skipTest("null device required")
1123 self.assertTrue(P.is_char_device())
1124 self.assertFalse(P.is_block_device())
1125 self.assertFalse(P.is_file())
1126 self.assertIs(self.cls(f'{os.devnull}\udfff').is_char_device(), False)
1127 self.assertIs(self.cls(f'{os.devnull}\x00').is_char_device(), False)
1128
1129 def test_is_mount_root(self):
1130 if os.name == 'nt':
1131 R = self.cls('c:\\')
1132 else:
1133 R = self.cls('/')
1134 self.assertTrue(R.is_mount())
1135 self.assertFalse((R / '\udfff').is_mount())
1136
1137 def test_passing_kwargs_deprecated(self):
1138 with self.assertWarns(DeprecationWarning):
1139 self.cls(foo="bar")
1140
1141 def setUpWalk(self):
1142 super().setUpWalk()
1143 sub21_path= self.sub2_path / "SUB21"
1144 tmp5_path = sub21_path / "tmp3"
1145 broken_link3_path = self.sub2_path / "broken_link3"
1146
1147 os.makedirs(sub21_path)
1148 tmp5_path.write_text("I am tmp5, blame test_pathlib.")
1149 if self.can_symlink:
1150 os.symlink(tmp5_path, broken_link3_path)
1151 self.sub2_tree[2].append('broken_link3')
1152 self.sub2_tree[2].sort()
1153 if not is_emscripten:
1154 # Emscripten fails with inaccessible directories.
1155 os.chmod(sub21_path, 0)
1156 try:
1157 os.listdir(sub21_path)
1158 except PermissionError:
1159 self.sub2_tree[1].append('SUB21')
1160 else:
1161 os.chmod(sub21_path, stat.S_IRWXU)
1162 os.unlink(tmp5_path)
1163 os.rmdir(sub21_path)
1164
1165 def test_walk_bad_dir(self):
1166 self.setUpWalk()
1167 errors = []
1168 walk_it = self.walk_path.walk(on_error=errors.append)
1169 root, dirs, files = next(walk_it)
1170 self.assertEqual(errors, [])
1171 dir1 = 'SUB1'
1172 path1 = root / dir1
1173 path1new = (root / dir1).with_suffix(".new")
1174 path1.rename(path1new)
1175 try:
1176 roots = [r for r, _, _ in walk_it]
1177 self.assertTrue(errors)
1178 self.assertNotIn(path1, roots)
1179 self.assertNotIn(path1new, roots)
1180 for dir2 in dirs:
1181 if dir2 != dir1:
1182 self.assertIn(root / dir2, roots)
1183 finally:
1184 path1new.rename(path1)
1185
1186 def test_walk_many_open_files(self):
1187 depth = 30
1188 base = self.cls(self.base, 'deep')
1189 path = self.cls(base, *(['d']*depth))
1190 path.mkdir(parents=True)
1191
1192 iters = [base.walk(top_down=False) for _ in range(100)]
1193 for i in range(depth + 1):
1194 expected = (path, ['d'] if i else [], [])
1195 for it in iters:
1196 self.assertEqual(next(it), expected)
1197 path = path.parent
1198
1199 iters = [base.walk(top_down=True) for _ in range(100)]
1200 path = base
1201 for i in range(depth + 1):
1202 expected = (path, ['d'] if i < depth else [], [])
1203 for it in iters:
1204 self.assertEqual(next(it), expected)
1205 path = path / 'd'
1206
1207 def test_walk_above_recursion_limit(self):
1208 recursion_limit = 40
1209 # directory_depth > recursion_limit
1210 directory_depth = recursion_limit + 10
1211 base = self.cls(self.base, 'deep')
1212 path = base.joinpath(*(['d'] * directory_depth))
1213 path.mkdir(parents=True)
1214
1215 with infinite_recursion(recursion_limit):
1216 list(base.walk())
1217 list(base.walk(top_down=False))
1218
1219 def test_glob_empty_pattern(self):
1220 p = self.cls('')
1221 with self.assertRaisesRegex(ValueError, 'Unacceptable pattern'):
1222 list(p.glob(''))
1223 with self.assertRaisesRegex(ValueError, 'Unacceptable pattern'):
1224 list(p.glob('.'))
1225 with self.assertRaisesRegex(ValueError, 'Unacceptable pattern'):
1226 list(p.glob('./'))
1227
1228 def test_glob_many_open_files(self):
1229 depth = 30
1230 P = self.cls
1231 p = base = P(self.base) / 'deep'
1232 p.mkdir()
1233 for _ in range(depth):
1234 p /= 'd'
1235 p.mkdir()
1236 pattern = '/'.join(['*'] * depth)
1237 iters = [base.glob(pattern) for j in range(100)]
1238 for it in iters:
1239 self.assertEqual(next(it), p)
1240 iters = [base.rglob('d') for j in range(100)]
1241 p = base
1242 for i in range(depth):
1243 p = p / 'd'
1244 for it in iters:
1245 self.assertEqual(next(it), p)
1246
1247 def test_glob_above_recursion_limit(self):
1248 recursion_limit = 50
1249 # directory_depth > recursion_limit
1250 directory_depth = recursion_limit + 10
1251 base = self.cls(self.base, 'deep')
1252 path = base.joinpath(*(['d'] * directory_depth))
1253 path.mkdir(parents=True)
1254
1255 with infinite_recursion(recursion_limit):
1256 list(base.glob('**/'))
1257
1258 def test_glob_pathlike(self):
1259 P = self.cls
1260 p = P(self.base)
1261 pattern = "dir*/file*"
1262 expect = {p / "dirB/fileB", p / "dirC/fileC"}
1263 self.assertEqual(expect, set(p.glob(P(pattern))))
1264 self.assertEqual(expect, set(p.glob(FakePath(pattern))))
1265
1266 @needs_symlinks
1267 def test_glob_dot(self):
1268 P = self.cls
1269 with os_helper.change_cwd(P(self.base, "dirC")):
1270 self.assertEqual(
1271 set(P('.').glob('*')), {P("fileC"), P("novel.txt"), P("dirD")})
1272 self.assertEqual(
1273 set(P('.').glob('**')), {P("fileC"), P("novel.txt"), P("dirD"), P("dirD/fileD"), P(".")})
1274 self.assertEqual(
1275 set(P('.').glob('**/*')), {P("fileC"), P("novel.txt"), P("dirD"), P("dirD/fileD")})
1276 self.assertEqual(
1277 set(P('.').glob('**/*/*')), {P("dirD/fileD")})
1278
1279 def test_glob_inaccessible(self):
1280 P = self.cls
1281 p = P(self.base, "mydir1", "mydir2")
1282 p.mkdir(parents=True)
1283 p.parent.chmod(0)
1284 self.assertEqual(set(p.glob('*')), set())
1285
1286 def test_rglob_pathlike(self):
1287 P = self.cls
1288 p = P(self.base, "dirC")
1289 pattern = "**/file*"
1290 expect = {p / "fileC", p / "dirD/fileD"}
1291 self.assertEqual(expect, set(p.rglob(P(pattern))))
1292 self.assertEqual(expect, set(p.rglob(FakePath(pattern))))
1293
1294 @needs_posix
1295 def test_absolute_posix(self):
1296 P = self.cls
1297 self.assertEqual(str(P('/').absolute()), '/')
1298 self.assertEqual(str(P('/a').absolute()), '/a')
1299 self.assertEqual(str(P('/a/b').absolute()), '/a/b')
1300
1301 # '//'-prefixed absolute path (supported by POSIX).
1302 self.assertEqual(str(P('//').absolute()), '//')
1303 self.assertEqual(str(P('//a').absolute()), '//a')
1304 self.assertEqual(str(P('//a/b').absolute()), '//a/b')
1305
1306 @unittest.skipIf(
1307 is_emscripten or is_wasi,
1308 "umask is not implemented on Emscripten/WASI."
1309 )
1310 @needs_posix
1311 def test_open_mode(self):
1312 # Unmask all permissions except world-write, which may
1313 # not be supported on some filesystems (see GH-85633.)
1314 old_mask = os.umask(0o002)
1315 self.addCleanup(os.umask, old_mask)
1316 p = self.cls(self.base)
1317 with (p / 'new_file').open('wb'):
1318 pass
1319 st = os.stat(self.parser.join(self.base, 'new_file'))
1320 self.assertEqual(stat.S_IMODE(st.st_mode), 0o664)
1321 os.umask(0o026)
1322 with (p / 'other_new_file').open('wb'):
1323 pass
1324 st = os.stat(self.parser.join(self.base, 'other_new_file'))
1325 self.assertEqual(stat.S_IMODE(st.st_mode), 0o640)
1326
1327 @needs_posix
1328 def test_resolve_root(self):
1329 current_directory = os.getcwd()
1330 try:
1331 os.chdir('/')
1332 p = self.cls('spam')
1333 self.assertEqual(str(p.resolve()), '/spam')
1334 finally:
1335 os.chdir(current_directory)
1336
1337 @unittest.skipIf(
1338 is_emscripten or is_wasi,
1339 "umask is not implemented on Emscripten/WASI."
1340 )
1341 @needs_posix
1342 def test_touch_mode(self):
1343 # Unmask all permissions except world-write, which may
1344 # not be supported on some filesystems (see GH-85633.)
1345 old_mask = os.umask(0o002)
1346 self.addCleanup(os.umask, old_mask)
1347 p = self.cls(self.base)
1348 (p / 'new_file').touch()
1349 st = os.stat(self.parser.join(self.base, 'new_file'))
1350 self.assertEqual(stat.S_IMODE(st.st_mode), 0o664)
1351 os.umask(0o026)
1352 (p / 'other_new_file').touch()
1353 st = os.stat(self.parser.join(self.base, 'other_new_file'))
1354 self.assertEqual(stat.S_IMODE(st.st_mode), 0o640)
1355 (p / 'masked_new_file').touch(mode=0o750)
1356 st = os.stat(self.parser.join(self.base, 'masked_new_file'))
1357 self.assertEqual(stat.S_IMODE(st.st_mode), 0o750)
1358
1359 @unittest.skipUnless(hasattr(pwd, 'getpwall'),
1360 'pwd module does not expose getpwall()')
1361 @unittest.skipIf(sys.platform == "vxworks",
1362 "no home directory on VxWorks")
1363 @needs_posix
1364 def test_expanduser_posix(self):
1365 P = self.cls
1366 import_helper.import_module('pwd')
1367 import pwd
1368 pwdent = pwd.getpwuid(os.getuid())
1369 username = pwdent.pw_name
1370 userhome = pwdent.pw_dir.rstrip('/') or '/'
1371 # Find arbitrary different user (if exists).
1372 for pwdent in pwd.getpwall():
1373 othername = pwdent.pw_name
1374 otherhome = pwdent.pw_dir.rstrip('/')
1375 if othername != username and otherhome:
1376 break
1377 else:
1378 othername = username
1379 otherhome = userhome
1380
1381 fakename = 'fakeuser'
1382 # This user can theoretically exist on a test runner. Create unique name:
1383 try:
1384 while pwd.getpwnam(fakename):
1385 fakename += '1'
1386 except KeyError:
1387 pass # Non-existent name found
1388
1389 p1 = P('~/Documents')
1390 p2 = P(f'~{username}/Documents')
1391 p3 = P(f'~{othername}/Documents')
1392 p4 = P(f'../~{username}/Documents')
1393 p5 = P(f'/~{username}/Documents')
1394 p6 = P('')
1395 p7 = P(f'~{fakename}/Documents')
1396
1397 with os_helper.EnvironmentVarGuard() as env:
1398 env.unset('HOME')
1399
1400 self.assertEqual(p1.expanduser(), P(userhome) / 'Documents')
1401 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
1402 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
1403 self.assertEqual(p4.expanduser(), p4)
1404 self.assertEqual(p5.expanduser(), p5)
1405 self.assertEqual(p6.expanduser(), p6)
1406 self.assertRaises(RuntimeError, p7.expanduser)
1407
1408 env['HOME'] = '/tmp'
1409 self.assertEqual(p1.expanduser(), P('/tmp/Documents'))
1410 self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
1411 self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
1412 self.assertEqual(p4.expanduser(), p4)
1413 self.assertEqual(p5.expanduser(), p5)
1414 self.assertEqual(p6.expanduser(), p6)
1415 self.assertRaises(RuntimeError, p7.expanduser)
1416
1417 @unittest.skipIf(sys.platform != "darwin",
1418 "Bad file descriptor in /dev/fd affects only macOS")
1419 @needs_posix
1420 def test_handling_bad_descriptor(self):
1421 try:
1422 file_descriptors = list(pathlib.Path('/dev/fd').rglob("*"))[3:]
1423 if not file_descriptors:
1424 self.skipTest("no file descriptors - issue was not reproduced")
1425 # Checking all file descriptors because there is no guarantee
1426 # which one will fail.
1427 for f in file_descriptors:
1428 f.exists()
1429 f.is_dir()
1430 f.is_file()
1431 f.is_symlink()
1432 f.is_block_device()
1433 f.is_char_device()
1434 f.is_fifo()
1435 f.is_socket()
1436 except OSError as e:
1437 if e.errno == errno.EBADF:
1438 self.fail("Bad file descriptor not handled.")
1439 raise
1440
1441 @needs_posix
1442 def test_from_uri_posix(self):
1443 P = self.cls
1444 self.assertEqual(P.from_uri('file:/foo/bar'), P('/foo/bar'))
1445 self.assertEqual(P.from_uri('file://foo/bar'), P('//foo/bar'))
1446 self.assertEqual(P.from_uri('file:///foo/bar'), P('/foo/bar'))
1447 self.assertEqual(P.from_uri('file:////foo/bar'), P('//foo/bar'))
1448 self.assertEqual(P.from_uri('file://localhost/foo/bar'), P('/foo/bar'))
1449 self.assertRaises(ValueError, P.from_uri, 'foo/bar')
1450 self.assertRaises(ValueError, P.from_uri, '/foo/bar')
1451 self.assertRaises(ValueError, P.from_uri, '//foo/bar')
1452 self.assertRaises(ValueError, P.from_uri, 'file:foo/bar')
1453 self.assertRaises(ValueError, P.from_uri, 'http://foo/bar')
1454
1455 @needs_posix
1456 def test_from_uri_pathname2url_posix(self):
1457 P = self.cls
1458 self.assertEqual(P.from_uri('file:' + pathname2url('/foo/bar')), P('/foo/bar'))
1459 self.assertEqual(P.from_uri('file:' + pathname2url('//foo/bar')), P('//foo/bar'))
1460
1461 @needs_windows
1462 def test_absolute_windows(self):
1463 P = self.cls
1464
1465 # Simple absolute paths.
1466 self.assertEqual(str(P('c:\\').absolute()), 'c:\\')
1467 self.assertEqual(str(P('c:\\a').absolute()), 'c:\\a')
1468 self.assertEqual(str(P('c:\\a\\b').absolute()), 'c:\\a\\b')
1469
1470 # UNC absolute paths.
1471 share = '\\\\server\\share\\'
1472 self.assertEqual(str(P(share).absolute()), share)
1473 self.assertEqual(str(P(share + 'a').absolute()), share + 'a')
1474 self.assertEqual(str(P(share + 'a\\b').absolute()), share + 'a\\b')
1475
1476 # UNC relative paths.
1477 with mock.patch("os.getcwd") as getcwd:
1478 getcwd.return_value = share
1479
1480 self.assertEqual(str(P().absolute()), share)
1481 self.assertEqual(str(P('.').absolute()), share)
1482 self.assertEqual(str(P('a').absolute()), os.path.join(share, 'a'))
1483 self.assertEqual(str(P('a', 'b', 'c').absolute()),
1484 os.path.join(share, 'a', 'b', 'c'))
1485
1486 drive = os.path.splitdrive(self.base)[0]
1487 with os_helper.change_cwd(self.base):
1488 # Relative path with root
1489 self.assertEqual(str(P('\\').absolute()), drive + '\\')
1490 self.assertEqual(str(P('\\foo').absolute()), drive + '\\foo')
1491
1492 # Relative path on current drive
1493 self.assertEqual(str(P(drive).absolute()), self.base)
1494 self.assertEqual(str(P(drive + 'foo').absolute()), os.path.join(self.base, 'foo'))
1495
1496 with os_helper.subst_drive(self.base) as other_drive:
1497 # Set the working directory on the substitute drive
1498 saved_cwd = os.getcwd()
1499 other_cwd = f'{other_drive}\\dirA'
1500 os.chdir(other_cwd)
1501 os.chdir(saved_cwd)
1502
1503 # Relative path on another drive
1504 self.assertEqual(str(P(other_drive).absolute()), other_cwd)
1505 self.assertEqual(str(P(other_drive + 'foo').absolute()), other_cwd + '\\foo')
1506
1507 @needs_windows
1508 def test_expanduser_windows(self):
1509 P = self.cls
1510 with os_helper.EnvironmentVarGuard() as env:
1511 env.unset('HOME', 'USERPROFILE', 'HOMEPATH', 'HOMEDRIVE')
1512 env['USERNAME'] = 'alice'
1513
1514 # test that the path returns unchanged
1515 p1 = P('~/My Documents')
1516 p2 = P('~alice/My Documents')
1517 p3 = P('~bob/My Documents')
1518 p4 = P('/~/My Documents')
1519 p5 = P('d:~/My Documents')
1520 p6 = P('')
1521 self.assertRaises(RuntimeError, p1.expanduser)
1522 self.assertRaises(RuntimeError, p2.expanduser)
1523 self.assertRaises(RuntimeError, p3.expanduser)
1524 self.assertEqual(p4.expanduser(), p4)
1525 self.assertEqual(p5.expanduser(), p5)
1526 self.assertEqual(p6.expanduser(), p6)
1527
1528 def check():
1529 env.pop('USERNAME', None)
1530 self.assertEqual(p1.expanduser(),
1531 P('C:/Users/alice/My Documents'))
1532 self.assertRaises(RuntimeError, p2.expanduser)
1533 env['USERNAME'] = 'alice'
1534 self.assertEqual(p2.expanduser(),
1535 P('C:/Users/alice/My Documents'))
1536 self.assertEqual(p3.expanduser(),
1537 P('C:/Users/bob/My Documents'))
1538 self.assertEqual(p4.expanduser(), p4)
1539 self.assertEqual(p5.expanduser(), p5)
1540 self.assertEqual(p6.expanduser(), p6)
1541
1542 env['HOMEPATH'] = 'C:\\Users\\alice'
1543 check()
1544
1545 env['HOMEDRIVE'] = 'C:\\'
1546 env['HOMEPATH'] = 'Users\\alice'
1547 check()
1548
1549 env.unset('HOMEDRIVE', 'HOMEPATH')
1550 env['USERPROFILE'] = 'C:\\Users\\alice'
1551 check()
1552
1553 # bpo-38883: ignore `HOME` when set on windows
1554 env['HOME'] = 'C:\\Users\\eve'
1555 check()
1556
1557 @needs_windows
1558 def test_from_uri_windows(self):
1559 P = self.cls
1560 # DOS drive paths
1561 self.assertEqual(P.from_uri('file:c:/path/to/file'), P('c:/path/to/file'))
1562 self.assertEqual(P.from_uri('file:c|/path/to/file'), P('c:/path/to/file'))
1563 self.assertEqual(P.from_uri('file:/c|/path/to/file'), P('c:/path/to/file'))
1564 self.assertEqual(P.from_uri('file:///c|/path/to/file'), P('c:/path/to/file'))
1565 # UNC paths
1566 self.assertEqual(P.from_uri('file://server/path/to/file'), P('//server/path/to/file'))
1567 self.assertEqual(P.from_uri('file:////server/path/to/file'), P('//server/path/to/file'))
1568 self.assertEqual(P.from_uri('file://///server/path/to/file'), P('//server/path/to/file'))
1569 # Localhost paths
1570 self.assertEqual(P.from_uri('file://localhost/c:/path/to/file'), P('c:/path/to/file'))
1571 self.assertEqual(P.from_uri('file://localhost/c|/path/to/file'), P('c:/path/to/file'))
1572 # Invalid paths
1573 self.assertRaises(ValueError, P.from_uri, 'foo/bar')
1574 self.assertRaises(ValueError, P.from_uri, 'c:/foo/bar')
1575 self.assertRaises(ValueError, P.from_uri, '//foo/bar')
1576 self.assertRaises(ValueError, P.from_uri, 'file:foo/bar')
1577 self.assertRaises(ValueError, P.from_uri, 'http://foo/bar')
1578
1579 @needs_windows
1580 def test_from_uri_pathname2url_windows(self):
1581 P = self.cls
1582 self.assertEqual(P.from_uri('file:' + pathname2url(r'c:\path\to\file')), P('c:/path/to/file'))
1583 self.assertEqual(P.from_uri('file:' + pathname2url(r'\\server\path\to\file')), P('//server/path/to/file'))
1584
1585 @needs_windows
1586 def test_owner_windows(self):
1587 P = self.cls
1588 with self.assertRaises(pathlib.UnsupportedOperation):
1589 P('c:/').owner()
1590
1591 @needs_windows
1592 def test_group_windows(self):
1593 P = self.cls
1594 with self.assertRaises(pathlib.UnsupportedOperation):
1595 P('c:/').group()
1596
1597
1598 @unittest.skipIf(os.name == 'nt', 'test requires a POSIX-compatible system')
1599 class PosixPathTest(PathTest, PurePosixPathTest):
1600 cls = pathlib.PosixPath
1601
1602
1603 @unittest.skipIf(os.name != 'nt', 'test requires a Windows-compatible system')
1604 class WindowsPathTest(PathTest, PureWindowsPathTest):
1605 cls = pathlib.WindowsPath
1606
1607
1608 class PathSubclassTest(PathTest):
1609 class cls(pathlib.Path):
1610 pass
1611
1612 # repr() roundtripping is not supported in custom subclass.
1613 test_repr_roundtrips = None
1614
1615
1616 class CompatiblePathTest(unittest.TestCase):
1617 """
1618 Test that a type can be made compatible with PurePath
1619 derivatives by implementing division operator overloads.
1620 """
1621
1622 class CompatPath:
1623 """
1624 Minimum viable class to test PurePath compatibility.
1625 Simply uses the division operator to join a given
1626 string and the string value of another object with
1627 a forward slash.
1628 """
1629 def __init__(self, string):
1630 self.string = string
1631
1632 def __truediv__(self, other):
1633 return type(self)(f"{self.string}/{other}")
1634
1635 def __rtruediv__(self, other):
1636 return type(self)(f"{other}/{self.string}")
1637
1638 def test_truediv(self):
1639 result = pathlib.PurePath("test") / self.CompatPath("right")
1640 self.assertIsInstance(result, self.CompatPath)
1641 self.assertEqual(result.string, "test/right")
1642
1643 with self.assertRaises(TypeError):
1644 # Verify improper operations still raise a TypeError
1645 pathlib.PurePath("test") / 10
1646
1647 def test_rtruediv(self):
1648 result = self.CompatPath("left") / pathlib.PurePath("test")
1649 self.assertIsInstance(result, self.CompatPath)
1650 self.assertEqual(result.string, "left/test")
1651
1652 with self.assertRaises(TypeError):
1653 # Verify improper operations still raise a TypeError
1654 10 / pathlib.PurePath("test")
1655
1656
1657 if __name__ == "__main__":
1658 unittest.main()