Debian Codegraph @

Lib/test/test_ntpath.py

raw
1 import inspect
2 import ntpath
3 import os
4 import string
5 import subprocess
6 import sys
7 import unittest
8 import warnings
9 from test import support
10 from test.support import os_helper
11 from ntpath import ALLOW_MISSING
12 from test.support.os_helper import FakePath
13 from test import test_genericpath
14 from tempfile import TemporaryFile
15
16
17 try:
18 import nt
19 except ImportError:
20 # Most tests can complete without the nt module,
21 # but for those that require it we import here.
22 nt = None
23
24 try:
25 ntpath._getfinalpathname
26 except AttributeError:
27 HAVE_GETFINALPATHNAME = False
28 else:
29 HAVE_GETFINALPATHNAME = True
30
31 try:
32 import ctypes
33 except ImportError:
34 HAVE_GETSHORTPATHNAME = False
35 else:
36 HAVE_GETSHORTPATHNAME = True
37 def _getshortpathname(path):
38 GSPN = ctypes.WinDLL("kernel32", use_last_error=True).GetShortPathNameW
39 GSPN.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32]
40 GSPN.restype = ctypes.c_uint32
41 result_len = GSPN(path, None, 0)
42 if not result_len:
43 raise OSError("failed to get short path name 0x{:08X}"
44 .format(ctypes.get_last_error()))
45 result = ctypes.create_unicode_buffer(result_len)
46 result_len = GSPN(path, result, result_len)
47 return result[:result_len]
48
49 def _norm(path):
50 if isinstance(path, (bytes, str, os.PathLike)):
51 return ntpath.normcase(os.fsdecode(path))
52 elif hasattr(path, "__iter__"):
53 return tuple(ntpath.normcase(os.fsdecode(p)) for p in path)
54 return path
55
56
57 def tester(fn, wantResult):
58 fn = fn.replace("\\", "\\\\")
59 gotResult = eval(fn)
60 if wantResult != gotResult and _norm(wantResult) != _norm(gotResult):
61 raise support.TestFailed("%s should return: %s but returned: %s" \
62 %(str(fn), str(wantResult), str(gotResult)))
63
64 # then with bytes
65 fn = fn.replace("('", "(b'")
66 fn = fn.replace('("', '(b"')
67 fn = fn.replace("['", "[b'")
68 fn = fn.replace('["', '[b"')
69 fn = fn.replace(", '", ", b'")
70 fn = fn.replace(', "', ', b"')
71 fn = os.fsencode(fn).decode('latin1')
72 fn = fn.encode('ascii', 'backslashreplace').decode('ascii')
73 with warnings.catch_warnings():
74 warnings.simplefilter("ignore", DeprecationWarning)
75 gotResult = eval(fn)
76 if _norm(wantResult) != _norm(gotResult):
77 raise support.TestFailed("%s should return: %s but returned: %s" \
78 %(str(fn), str(wantResult), repr(gotResult)))
79
80
81 def _parameterize(*parameters):
82 return support.subTests('kwargs', parameters, _do_cleanups=True)
83
84
85 class NtpathTestCase(unittest.TestCase):
86 def assertPathEqual(self, path1, path2):
87 if path1 == path2 or _norm(path1) == _norm(path2):
88 return
89 self.assertEqual(path1, path2)
90
91 def assertPathIn(self, path, pathset):
92 self.assertIn(_norm(path), _norm(pathset))
93
94
95 class TestNtpath(NtpathTestCase):
96 def test_splitext(self):
97 tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
98 tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext'))
99 tester('ntpath.splitext(".ext")', ('.ext', ''))
100 tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', ''))
101 tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', ''))
102 tester('ntpath.splitext("")', ('', ''))
103 tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext'))
104 tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext'))
105 tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext'))
106 tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d'))
107
108 def test_splitdrive(self):
109 tester("ntpath.splitdrive('')", ('', ''))
110 tester("ntpath.splitdrive('foo')", ('', 'foo'))
111 tester("ntpath.splitdrive('foo\\bar')", ('', 'foo\\bar'))
112 tester("ntpath.splitdrive('foo/bar')", ('', 'foo/bar'))
113 tester("ntpath.splitdrive('\\')", ('', '\\'))
114 tester("ntpath.splitdrive('/')", ('', '/'))
115 tester("ntpath.splitdrive('\\foo\\bar')", ('', '\\foo\\bar'))
116 tester("ntpath.splitdrive('/foo/bar')", ('', '/foo/bar'))
117 tester('ntpath.splitdrive("c:foo\\bar")', ('c:', 'foo\\bar'))
118 tester('ntpath.splitdrive("c:foo/bar")', ('c:', 'foo/bar'))
119 tester('ntpath.splitdrive("c:\\foo\\bar")', ('c:', '\\foo\\bar'))
120 tester('ntpath.splitdrive("c:/foo/bar")', ('c:', '/foo/bar'))
121 tester("ntpath.splitdrive('\\\\')", ('\\\\', ''))
122 tester("ntpath.splitdrive('//')", ('//', ''))
123 tester('ntpath.splitdrive("\\\\conky\\mountpoint\\foo\\bar")',
124 ('\\\\conky\\mountpoint', '\\foo\\bar'))
125 tester('ntpath.splitdrive("//conky/mountpoint/foo/bar")',
126 ('//conky/mountpoint', '/foo/bar'))
127 tester('ntpath.splitdrive("\\\\?\\UNC\\server\\share\\dir")',
128 ("\\\\?\\UNC\\server\\share", "\\dir"))
129 tester('ntpath.splitdrive("//?/UNC/server/share/dir")',
130 ("//?/UNC/server/share", "/dir"))
131
132 def test_splitdrive_invalid_paths(self):
133 splitdrive = ntpath.splitdrive
134 self.assertEqual(splitdrive('\\\\ser\x00ver\\sha\x00re\\di\x00r'),
135 ('\\\\ser\x00ver\\sha\x00re', '\\di\x00r'))
136 self.assertEqual(splitdrive(b'\\\\ser\x00ver\\sha\x00re\\di\x00r'),
137 (b'\\\\ser\x00ver\\sha\x00re', b'\\di\x00r'))
138 self.assertEqual(splitdrive("\\\\\udfff\\\udffe\\\udffd"),
139 ('\\\\\udfff\\\udffe', '\\\udffd'))
140 if sys.platform == 'win32':
141 self.assertRaises(UnicodeDecodeError, splitdrive, b'\\\\\xff\\share\\dir')
142 self.assertRaises(UnicodeDecodeError, splitdrive, b'\\\\server\\\xff\\dir')
143 self.assertRaises(UnicodeDecodeError, splitdrive, b'\\\\server\\share\\\xff')
144 else:
145 self.assertEqual(splitdrive(b'\\\\\xff\\\xfe\\\xfd'),
146 (b'\\\\\xff\\\xfe', b'\\\xfd'))
147
148 def test_splitroot(self):
149 tester("ntpath.splitroot('')", ('', '', ''))
150 tester("ntpath.splitroot('foo')", ('', '', 'foo'))
151 tester("ntpath.splitroot('foo\\bar')", ('', '', 'foo\\bar'))
152 tester("ntpath.splitroot('foo/bar')", ('', '', 'foo/bar'))
153 tester("ntpath.splitroot('\\')", ('', '\\', ''))
154 tester("ntpath.splitroot('/')", ('', '/', ''))
155 tester("ntpath.splitroot('\\foo\\bar')", ('', '\\', 'foo\\bar'))
156 tester("ntpath.splitroot('/foo/bar')", ('', '/', 'foo/bar'))
157 tester('ntpath.splitroot("c:foo\\bar")', ('c:', '', 'foo\\bar'))
158 tester('ntpath.splitroot("c:foo/bar")', ('c:', '', 'foo/bar'))
159 tester('ntpath.splitroot("c:\\foo\\bar")', ('c:', '\\', 'foo\\bar'))
160 tester('ntpath.splitroot("c:/foo/bar")', ('c:', '/', 'foo/bar'))
161
162 # Redundant slashes are not included in the root.
163 tester("ntpath.splitroot('c:\\\\a')", ('c:', '\\', '\\a'))
164 tester("ntpath.splitroot('c:\\\\\\a/b')", ('c:', '\\', '\\\\a/b'))
165
166 # Mixed path separators.
167 tester("ntpath.splitroot('c:/\\')", ('c:', '/', '\\'))
168 tester("ntpath.splitroot('c:\\/')", ('c:', '\\', '/'))
169 tester("ntpath.splitroot('/\\a/b\\/\\')", ('/\\a/b', '\\', '/\\'))
170 tester("ntpath.splitroot('\\/a\\b/\\/')", ('\\/a\\b', '/', '\\/'))
171
172 # UNC paths.
173 tester("ntpath.splitroot('\\\\')", ('\\\\', '', ''))
174 tester("ntpath.splitroot('//')", ('//', '', ''))
175 tester('ntpath.splitroot("\\\\conky\\mountpoint\\foo\\bar")',
176 ('\\\\conky\\mountpoint', '\\', 'foo\\bar'))
177 tester('ntpath.splitroot("//conky/mountpoint/foo/bar")',
178 ('//conky/mountpoint', '/', 'foo/bar'))
179 tester('ntpath.splitroot("\\\\\\conky\\mountpoint\\foo\\bar")',
180 ('\\\\\\conky', '\\', 'mountpoint\\foo\\bar'))
181 tester('ntpath.splitroot("///conky/mountpoint/foo/bar")',
182 ('///conky', '/', 'mountpoint/foo/bar'))
183 tester('ntpath.splitroot("\\\\conky\\\\mountpoint\\foo\\bar")',
184 ('\\\\conky\\', '\\', 'mountpoint\\foo\\bar'))
185 tester('ntpath.splitroot("//conky//mountpoint/foo/bar")',
186 ('//conky/', '/', 'mountpoint/foo/bar'))
187
188 # Issue #19911: UNC part containing U+0130
189 self.assertEqual(ntpath.splitroot('//conky/MOUNTPOİNT/foo/bar'),
190 ('//conky/MOUNTPOİNT', '/', 'foo/bar'))
191
192 # gh-81790: support device namespace, including UNC drives.
193 tester('ntpath.splitroot("//?/c:")', ("//?/c:", "", ""))
194 tester('ntpath.splitroot("//./c:")', ("//./c:", "", ""))
195 tester('ntpath.splitroot("//?/c:/")', ("//?/c:", "/", ""))
196 tester('ntpath.splitroot("//?/c:/dir")', ("//?/c:", "/", "dir"))
197 tester('ntpath.splitroot("//?/UNC")', ("//?/UNC", "", ""))
198 tester('ntpath.splitroot("//?/UNC/")', ("//?/UNC/", "", ""))
199 tester('ntpath.splitroot("//?/UNC/server/")', ("//?/UNC/server/", "", ""))
200 tester('ntpath.splitroot("//?/UNC/server/share")', ("//?/UNC/server/share", "", ""))
201 tester('ntpath.splitroot("//?/UNC/server/share/dir")', ("//?/UNC/server/share", "/", "dir"))
202 tester('ntpath.splitroot("//?/VOLUME{00000000-0000-0000-0000-000000000000}/spam")',
203 ('//?/VOLUME{00000000-0000-0000-0000-000000000000}', '/', 'spam'))
204 tester('ntpath.splitroot("//?/BootPartition/")', ("//?/BootPartition", "/", ""))
205 tester('ntpath.splitroot("//./BootPartition/")', ("//./BootPartition", "/", ""))
206 tester('ntpath.splitroot("//./PhysicalDrive0")', ("//./PhysicalDrive0", "", ""))
207 tester('ntpath.splitroot("//./nul")', ("//./nul", "", ""))
208
209 tester('ntpath.splitroot("\\\\?\\c:")', ("\\\\?\\c:", "", ""))
210 tester('ntpath.splitroot("\\\\.\\c:")', ("\\\\.\\c:", "", ""))
211 tester('ntpath.splitroot("\\\\?\\c:\\")', ("\\\\?\\c:", "\\", ""))
212 tester('ntpath.splitroot("\\\\?\\c:\\dir")', ("\\\\?\\c:", "\\", "dir"))
213 tester('ntpath.splitroot("\\\\?\\UNC")', ("\\\\?\\UNC", "", ""))
214 tester('ntpath.splitroot("\\\\?\\UNC\\")', ("\\\\?\\UNC\\", "", ""))
215 tester('ntpath.splitroot("\\\\?\\UNC\\server\\")', ("\\\\?\\UNC\\server\\", "", ""))
216 tester('ntpath.splitroot("\\\\?\\UNC\\server\\share")',
217 ("\\\\?\\UNC\\server\\share", "", ""))
218 tester('ntpath.splitroot("\\\\?\\UNC\\server\\share\\dir")',
219 ("\\\\?\\UNC\\server\\share", "\\", "dir"))
220 tester('ntpath.splitroot("\\\\?\\VOLUME{00000000-0000-0000-0000-000000000000}\\spam")',
221 ('\\\\?\\VOLUME{00000000-0000-0000-0000-000000000000}', '\\', 'spam'))
222 tester('ntpath.splitroot("\\\\?\\BootPartition\\")', ("\\\\?\\BootPartition", "\\", ""))
223 tester('ntpath.splitroot("\\\\.\\BootPartition\\")', ("\\\\.\\BootPartition", "\\", ""))
224 tester('ntpath.splitroot("\\\\.\\PhysicalDrive0")', ("\\\\.\\PhysicalDrive0", "", ""))
225 tester('ntpath.splitroot("\\\\.\\nul")', ("\\\\.\\nul", "", ""))
226
227 # gh-96290: support partial/invalid UNC drives
228 tester('ntpath.splitroot("//")', ("//", "", "")) # empty server & missing share
229 tester('ntpath.splitroot("///")', ("///", "", "")) # empty server & empty share
230 tester('ntpath.splitroot("///y")', ("///y", "", "")) # empty server & non-empty share
231 tester('ntpath.splitroot("//x")', ("//x", "", "")) # non-empty server & missing share
232 tester('ntpath.splitroot("//x/")', ("//x/", "", "")) # non-empty server & empty share
233
234 # gh-101363: match GetFullPathNameW() drive letter parsing behaviour
235 tester('ntpath.splitroot(" :/foo")', (" :", "/", "foo"))
236 tester('ntpath.splitroot("/:/foo")', ("", "/", ":/foo"))
237
238 def test_splitroot_invalid_paths(self):
239 splitroot = ntpath.splitroot
240 self.assertEqual(splitroot('\\\\ser\x00ver\\sha\x00re\\di\x00r'),
241 ('\\\\ser\x00ver\\sha\x00re', '\\', 'di\x00r'))
242 self.assertEqual(splitroot(b'\\\\ser\x00ver\\sha\x00re\\di\x00r'),
243 (b'\\\\ser\x00ver\\sha\x00re', b'\\', b'di\x00r'))
244 self.assertEqual(splitroot("\\\\\udfff\\\udffe\\\udffd"),
245 ('\\\\\udfff\\\udffe', '\\', '\udffd'))
246 if sys.platform == 'win32':
247 self.assertRaises(UnicodeDecodeError, splitroot, b'\\\\\xff\\share\\dir')
248 self.assertRaises(UnicodeDecodeError, splitroot, b'\\\\server\\\xff\\dir')
249 self.assertRaises(UnicodeDecodeError, splitroot, b'\\\\server\\share\\\xff')
250 else:
251 self.assertEqual(splitroot(b'\\\\\xff\\\xfe\\\xfd'),
252 (b'\\\\\xff\\\xfe', b'\\', b'\xfd'))
253
254 def test_split(self):
255 tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
256 tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")',
257 ('\\\\conky\\mountpoint\\foo', 'bar'))
258
259 tester('ntpath.split("c:\\")', ('c:\\', ''))
260 tester('ntpath.split("\\\\conky\\mountpoint\\")',
261 ('\\\\conky\\mountpoint\\', ''))
262
263 tester('ntpath.split("c:/")', ('c:/', ''))
264 tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint/', ''))
265
266 def test_split_invalid_paths(self):
267 split = ntpath.split
268 self.assertEqual(split('c:\\fo\x00o\\ba\x00r'),
269 ('c:\\fo\x00o', 'ba\x00r'))
270 self.assertEqual(split(b'c:\\fo\x00o\\ba\x00r'),
271 (b'c:\\fo\x00o', b'ba\x00r'))
272 self.assertEqual(split('c:\\\udfff\\\udffe'),
273 ('c:\\\udfff', '\udffe'))
274 if sys.platform == 'win32':
275 self.assertRaises(UnicodeDecodeError, split, b'c:\\\xff\\bar')
276 self.assertRaises(UnicodeDecodeError, split, b'c:\\foo\\\xff')
277 else:
278 self.assertEqual(split(b'c:\\\xff\\\xfe'),
279 (b'c:\\\xff', b'\xfe'))
280
281 def test_isabs(self):
282 tester('ntpath.isabs("foo\\bar")', 0)
283 tester('ntpath.isabs("foo/bar")', 0)
284 tester('ntpath.isabs("c:\\")', 1)
285 tester('ntpath.isabs("c:\\foo\\bar")', 1)
286 tester('ntpath.isabs("c:/foo/bar")', 1)
287 tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1)
288
289 # gh-44626: paths with only a drive or root are not absolute.
290 tester('ntpath.isabs("\\foo\\bar")', 0)
291 tester('ntpath.isabs("/foo/bar")', 0)
292 tester('ntpath.isabs("c:foo\\bar")', 0)
293 tester('ntpath.isabs("c:foo/bar")', 0)
294
295 # gh-96290: normal UNC paths and device paths without trailing backslashes
296 tester('ntpath.isabs("\\\\conky\\mountpoint")', 1)
297 tester('ntpath.isabs("\\\\.\\C:")', 1)
298
299 def test_commonprefix(self):
300 tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])',
301 "/home/swen")
302 tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])',
303 "\\home\\swen\\")
304 tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])',
305 "/home/swen/spam")
306
307 def test_join(self):
308 tester('ntpath.join("")', '')
309 tester('ntpath.join("", "", "")', '')
310 tester('ntpath.join("a")', 'a')
311 tester('ntpath.join("/a")', '/a')
312 tester('ntpath.join("\\a")', '\\a')
313 tester('ntpath.join("a:")', 'a:')
314 tester('ntpath.join("a:", "\\b")', 'a:\\b')
315 tester('ntpath.join("a", "\\b")', '\\b')
316 tester('ntpath.join("a", "b", "c")', 'a\\b\\c')
317 tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c')
318 tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c')
319 tester('ntpath.join("a", "b", "c\\")', 'a\\b\\c\\')
320 tester('ntpath.join("a", "b", "\\c")', '\\c')
321 tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep')
322 tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b')
323
324 tester("ntpath.join('', 'a')", 'a')
325 tester("ntpath.join('', '', '', '', 'a')", 'a')
326 tester("ntpath.join('a', '')", 'a\\')
327 tester("ntpath.join('a', '', '', '', '')", 'a\\')
328 tester("ntpath.join('a\\', '')", 'a\\')
329 tester("ntpath.join('a\\', '', '', '', '')", 'a\\')
330 tester("ntpath.join('a/', '')", 'a/')
331
332 tester("ntpath.join('a/b', 'x/y')", 'a/b\\x/y')
333 tester("ntpath.join('/a/b', 'x/y')", '/a/b\\x/y')
334 tester("ntpath.join('/a/b/', 'x/y')", '/a/b/x/y')
335 tester("ntpath.join('c:', 'x/y')", 'c:x/y')
336 tester("ntpath.join('c:a/b', 'x/y')", 'c:a/b\\x/y')
337 tester("ntpath.join('c:a/b/', 'x/y')", 'c:a/b/x/y')
338 tester("ntpath.join('c:/', 'x/y')", 'c:/x/y')
339 tester("ntpath.join('c:/a/b', 'x/y')", 'c:/a/b\\x/y')
340 tester("ntpath.join('c:/a/b/', 'x/y')", 'c:/a/b/x/y')
341 tester("ntpath.join('//computer/share', 'x/y')", '//computer/share\\x/y')
342 tester("ntpath.join('//computer/share/', 'x/y')", '//computer/share/x/y')
343 tester("ntpath.join('//computer/share/a/b', 'x/y')", '//computer/share/a/b\\x/y')
344
345 tester("ntpath.join('a/b', '/x/y')", '/x/y')
346 tester("ntpath.join('/a/b', '/x/y')", '/x/y')
347 tester("ntpath.join('c:', '/x/y')", 'c:/x/y')
348 tester("ntpath.join('c:a/b', '/x/y')", 'c:/x/y')
349 tester("ntpath.join('c:/', '/x/y')", 'c:/x/y')
350 tester("ntpath.join('c:/a/b', '/x/y')", 'c:/x/y')
351 tester("ntpath.join('//computer/share', '/x/y')", '//computer/share/x/y')
352 tester("ntpath.join('//computer/share/', '/x/y')", '//computer/share/x/y')
353 tester("ntpath.join('//computer/share/a', '/x/y')", '//computer/share/x/y')
354
355 tester("ntpath.join('c:', 'C:x/y')", 'C:x/y')
356 tester("ntpath.join('c:a/b', 'C:x/y')", 'C:a/b\\x/y')
357 tester("ntpath.join('c:/', 'C:x/y')", 'C:/x/y')
358 tester("ntpath.join('c:/a/b', 'C:x/y')", 'C:/a/b\\x/y')
359
360 for x in ('', 'a/b', '/a/b', 'c:', 'c:a/b', 'c:/', 'c:/a/b',
361 '//computer/share', '//computer/share/', '//computer/share/a/b'):
362 for y in ('d:', 'd:x/y', 'd:/', 'd:/x/y',
363 '//machine/common', '//machine/common/', '//machine/common/x/y'):
364 tester("ntpath.join(%r, %r)" % (x, y), y)
365
366 tester("ntpath.join('\\\\computer\\share\\', 'a', 'b')", '\\\\computer\\share\\a\\b')
367 tester("ntpath.join('\\\\computer\\share', 'a', 'b')", '\\\\computer\\share\\a\\b')
368 tester("ntpath.join('\\\\computer\\share', 'a\\b')", '\\\\computer\\share\\a\\b')
369 tester("ntpath.join('//computer/share/', 'a', 'b')", '//computer/share/a\\b')
370 tester("ntpath.join('//computer/share', 'a', 'b')", '//computer/share\\a\\b')
371 tester("ntpath.join('//computer/share', 'a/b')", '//computer/share\\a/b')
372
373 tester("ntpath.join('\\\\', 'computer')", '\\\\computer')
374 tester("ntpath.join('\\\\computer\\', 'share')", '\\\\computer\\share')
375 tester("ntpath.join('\\\\computer\\share\\', 'a')", '\\\\computer\\share\\a')
376 tester("ntpath.join('\\\\computer\\share\\a\\', 'b')", '\\\\computer\\share\\a\\b')
377 # Second part is anchored, so that the first part is ignored.
378 tester("ntpath.join('a', 'Z:b', 'c')", 'Z:b\\c')
379 tester("ntpath.join('a', 'Z:\\b', 'c')", 'Z:\\b\\c')
380 tester("ntpath.join('a', '\\\\b\\c', 'd')", '\\\\b\\c\\d')
381 # Second part has a root but not drive.
382 tester("ntpath.join('a', '\\b', 'c')", '\\b\\c')
383 tester("ntpath.join('Z:/a', '/b', 'c')", 'Z:\\b\\c')
384 tester("ntpath.join('//?/Z:/a', '/b', 'c')", '\\\\?\\Z:\\b\\c')
385 tester("ntpath.join('D:a', './c:b')", 'D:a\\.\\c:b')
386 tester("ntpath.join('D:/a', './c:b')", 'D:\\a\\.\\c:b')
387
388 def test_normcase(self):
389 normcase = ntpath.normcase
390 self.assertEqual(normcase(''), '')
391 self.assertEqual(normcase(b''), b'')
392 self.assertEqual(normcase('ABC'), 'abc')
393 self.assertEqual(normcase(b'ABC'), b'abc')
394 self.assertEqual(normcase('\xc4\u0141\u03a8'), '\xe4\u0142\u03c8')
395 expected = '\u03c9\u2126' if sys.platform == 'win32' else '\u03c9\u03c9'
396 self.assertEqual(normcase('\u03a9\u2126'), expected)
397 if sys.platform == 'win32' or sys.getfilesystemencoding() == 'utf-8':
398 self.assertEqual(normcase('\xc4\u0141\u03a8'.encode()),
399 '\xe4\u0142\u03c8'.encode())
400 self.assertEqual(normcase('\u03a9\u2126'.encode()),
401 expected.encode())
402
403 def test_normcase_invalid_paths(self):
404 normcase = ntpath.normcase
405 self.assertEqual(normcase('abc\x00def'), 'abc\x00def')
406 self.assertEqual(normcase(b'abc\x00def'), b'abc\x00def')
407 self.assertEqual(normcase('\udfff'), '\udfff')
408 if sys.platform == 'win32':
409 path = b'ABC' + bytes(range(128, 256))
410 self.assertEqual(normcase(path), path.lower())
411
412 def test_normpath(self):
413 tester("ntpath.normpath('A//////././//.//B')", r'A\B')
414 tester("ntpath.normpath('A/./B')", r'A\B')
415 tester("ntpath.normpath('A/foo/../B')", r'A\B')
416 tester("ntpath.normpath('C:A//B')", r'C:A\B')
417 tester("ntpath.normpath('D:A/./B')", r'D:A\B')
418 tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B')
419
420 tester("ntpath.normpath('C:///A//B')", r'C:\A\B')
421 tester("ntpath.normpath('D:///A/./B')", r'D:\A\B')
422 tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B')
423
424 tester("ntpath.normpath('..')", r'..')
425 tester("ntpath.normpath('.')", r'.')
426 tester("ntpath.normpath('c:.')", 'c:')
427 tester("ntpath.normpath('')", r'.')
428 tester("ntpath.normpath('/')", '\\')
429 tester("ntpath.normpath('c:/')", 'c:\\')
430 tester("ntpath.normpath('/../.././..')", '\\')
431 tester("ntpath.normpath('c:/../../..')", 'c:\\')
432 tester("ntpath.normpath('/./a/b')", r'\a\b')
433 tester("ntpath.normpath('c:/./a/b')", r'c:\a\b')
434 tester("ntpath.normpath('../.././..')", r'..\..\..')
435 tester("ntpath.normpath('K:../.././..')", r'K:..\..\..')
436 tester("ntpath.normpath('./a/b')", r'a\b')
437 tester("ntpath.normpath('c:./a/b')", r'c:a\b')
438 tester("ntpath.normpath('C:////a/b')", r'C:\a\b')
439 tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')
440
441 tester("ntpath.normpath('\\\\.\\NUL')", r'\\.\NUL')
442 tester("ntpath.normpath('\\\\?\\D:/XY\\Z')", r'\\?\D:/XY\Z')
443 tester("ntpath.normpath('handbook/../../Tests/image.png')", r'..\Tests\image.png')
444 tester("ntpath.normpath('handbook/../../../Tests/image.png')", r'..\..\Tests\image.png')
445 tester("ntpath.normpath('handbook///../a/.././../b/c')", r'..\b\c')
446 tester("ntpath.normpath('handbook/a/../..///../../b/c')", r'..\..\b\c')
447
448 tester("ntpath.normpath('//server/share/..')" , '\\\\server\\share\\')
449 tester("ntpath.normpath('//server/share/../')" , '\\\\server\\share\\')
450 tester("ntpath.normpath('//server/share/../..')", '\\\\server\\share\\')
451 tester("ntpath.normpath('//server/share/../../')", '\\\\server\\share\\')
452
453 # gh-96290: don't normalize partial/invalid UNC drives as rooted paths.
454 tester("ntpath.normpath('\\\\foo\\\\')", '\\\\foo\\\\')
455 tester("ntpath.normpath('\\\\foo\\')", '\\\\foo\\')
456 tester("ntpath.normpath('\\\\foo')", '\\\\foo')
457 tester("ntpath.normpath('\\\\')", '\\\\')
458 tester("ntpath.normpath('//?/UNC/server/share/..')", '\\\\?\\UNC\\server\\share\\')
459
460 def test_normpath_invalid_paths(self):
461 normpath = ntpath.normpath
462 self.assertEqual(normpath('fo\x00o'), 'fo\x00o')
463 self.assertEqual(normpath(b'fo\x00o'), b'fo\x00o')
464 self.assertEqual(normpath('fo\x00o\\..\\bar'), 'bar')
465 self.assertEqual(normpath(b'fo\x00o\\..\\bar'), b'bar')
466 self.assertEqual(normpath('\udfff'), '\udfff')
467 self.assertEqual(normpath('\udfff\\..\\foo'), 'foo')
468 if sys.platform == 'win32':
469 self.assertRaises(UnicodeDecodeError, normpath, b'\xff')
470 self.assertRaises(UnicodeDecodeError, normpath, b'\xff\\..\\foo')
471 else:
472 self.assertEqual(normpath(b'\xff'), b'\xff')
473 self.assertEqual(normpath(b'\xff\\..\\foo'), b'foo')
474
475 def test_realpath_curdir(self):
476 expected = ntpath.normpath(os.getcwd())
477 tester("ntpath.realpath('.')", expected)
478 tester("ntpath.realpath('./.')", expected)
479 tester("ntpath.realpath('/'.join(['.'] * 100))", expected)
480 tester("ntpath.realpath('.\\.')", expected)
481 tester("ntpath.realpath('\\'.join(['.'] * 100))", expected)
482
483 def test_realpath_curdir_strict(self):
484 expected = ntpath.normpath(os.getcwd())
485 tester("ntpath.realpath('.', strict=True)", expected)
486 tester("ntpath.realpath('./.', strict=True)", expected)
487 tester("ntpath.realpath('/'.join(['.'] * 100), strict=True)", expected)
488 tester("ntpath.realpath('.\\.', strict=True)", expected)
489 tester("ntpath.realpath('\\'.join(['.'] * 100), strict=True)", expected)
490
491 def test_realpath_curdir_missing_ok(self):
492 expected = ntpath.normpath(os.getcwd())
493 tester("ntpath.realpath('.', strict=ALLOW_MISSING)",
494 expected)
495 tester("ntpath.realpath('./.', strict=ALLOW_MISSING)",
496 expected)
497 tester("ntpath.realpath('/'.join(['.'] * 100), strict=ALLOW_MISSING)",
498 expected)
499 tester("ntpath.realpath('.\\.', strict=ALLOW_MISSING)",
500 expected)
501 tester("ntpath.realpath('\\'.join(['.'] * 100), strict=ALLOW_MISSING)",
502 expected)
503
504 def test_realpath_pardir(self):
505 expected = ntpath.normpath(os.getcwd())
506 tester("ntpath.realpath('..')", ntpath.dirname(expected))
507 tester("ntpath.realpath('../..')",
508 ntpath.dirname(ntpath.dirname(expected)))
509 tester("ntpath.realpath('/'.join(['..'] * 50))",
510 ntpath.splitdrive(expected)[0] + '\\')
511 tester("ntpath.realpath('..\\..')",
512 ntpath.dirname(ntpath.dirname(expected)))
513 tester("ntpath.realpath('\\'.join(['..'] * 50))",
514 ntpath.splitdrive(expected)[0] + '\\')
515
516 def test_realpath_pardir_strict(self):
517 expected = ntpath.normpath(os.getcwd())
518 tester("ntpath.realpath('..', strict=True)", ntpath.dirname(expected))
519 tester("ntpath.realpath('../..', strict=True)",
520 ntpath.dirname(ntpath.dirname(expected)))
521 tester("ntpath.realpath('/'.join(['..'] * 50), strict=True)",
522 ntpath.splitdrive(expected)[0] + '\\')
523 tester("ntpath.realpath('..\\..', strict=True)",
524 ntpath.dirname(ntpath.dirname(expected)))
525 tester("ntpath.realpath('\\'.join(['..'] * 50), strict=True)",
526 ntpath.splitdrive(expected)[0] + '\\')
527
528 def test_realpath_pardir_missing_ok(self):
529 expected = ntpath.normpath(os.getcwd())
530 tester("ntpath.realpath('..', strict=ALLOW_MISSING)",
531 ntpath.dirname(expected))
532 tester("ntpath.realpath('../..', strict=ALLOW_MISSING)",
533 ntpath.dirname(ntpath.dirname(expected)))
534 tester("ntpath.realpath('/'.join(['..'] * 50), strict=ALLOW_MISSING)",
535 ntpath.splitdrive(expected)[0] + '\\')
536 tester("ntpath.realpath('..\\..', strict=ALLOW_MISSING)",
537 ntpath.dirname(ntpath.dirname(expected)))
538 tester("ntpath.realpath('\\'.join(['..'] * 50), strict=ALLOW_MISSING)",
539 ntpath.splitdrive(expected)[0] + '\\')
540
541 @os_helper.skip_unless_symlink
542 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
543 @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING})
544 def test_realpath_basic(self, kwargs):
545 ABSTFN = ntpath.abspath(os_helper.TESTFN)
546 open(ABSTFN, "wb").close()
547 self.addCleanup(os_helper.unlink, ABSTFN)
548 self.addCleanup(os_helper.unlink, ABSTFN + "1")
549
550 os.symlink(ABSTFN, ABSTFN + "1")
551 self.assertPathEqual(ntpath.realpath(ABSTFN + "1", **kwargs), ABSTFN)
552 self.assertPathEqual(ntpath.realpath(os.fsencode(ABSTFN + "1"), **kwargs),
553 os.fsencode(ABSTFN))
554
555 # gh-88013: call ntpath.realpath with binary drive name may raise a
556 # TypeError. The drive should not exist to reproduce the bug.
557 drives = {f"{c}:\\" for c in string.ascii_uppercase} - set(os.listdrives())
558 d = drives.pop().encode()
559 self.assertEqual(ntpath.realpath(d, strict=False), d)
560
561 # gh-106242: Embedded nulls and non-strict fallback to abspath
562 if kwargs:
563 with self.assertRaises(OSError):
564 ntpath.realpath(os_helper.TESTFN + "\0spam",
565 **kwargs)
566 else:
567 self.assertEqual(ABSTFN + "\0spam",
568 ntpath.realpath(os_helper.TESTFN + "\0spam", **kwargs))
569
570 @os_helper.skip_unless_symlink
571 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
572 def test_realpath_strict(self):
573 # Bug #43757: raise FileNotFoundError in strict mode if we encounter
574 # a path that does not exist.
575 ABSTFN = ntpath.abspath(os_helper.TESTFN)
576 os.symlink(ABSTFN + "1", ABSTFN)
577 self.addCleanup(os_helper.unlink, ABSTFN)
578 self.assertRaises(FileNotFoundError, ntpath.realpath, ABSTFN, strict=True)
579 self.assertRaises(FileNotFoundError, ntpath.realpath, ABSTFN + "2", strict=True)
580
581 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
582 def test_realpath_invalid_paths(self):
583 realpath = ntpath.realpath
584 ABSTFN = ntpath.abspath(os_helper.TESTFN)
585 ABSTFNb = os.fsencode(ABSTFN)
586 path = ABSTFN + '\x00'
587 # gh-106242: Embedded nulls and non-strict fallback to abspath
588 self.assertEqual(realpath(path, strict=False), path)
589 # gh-106242: Embedded nulls should raise OSError (not ValueError)
590 self.assertRaises(OSError, realpath, path, strict=True)
591 self.assertRaises(OSError, realpath, path, strict=ALLOW_MISSING)
592 path = ABSTFNb + b'\x00'
593 self.assertEqual(realpath(path, strict=False), path)
594 self.assertRaises(OSError, realpath, path, strict=True)
595 self.assertRaises(OSError, realpath, path, strict=ALLOW_MISSING)
596 path = ABSTFN + '\\nonexistent\\x\x00'
597 self.assertEqual(realpath(path, strict=False), path)
598 self.assertRaises(OSError, realpath, path, strict=True)
599 self.assertRaises(OSError, realpath, path, strict=ALLOW_MISSING)
600 path = ABSTFNb + b'\\nonexistent\\x\x00'
601 self.assertEqual(realpath(path, strict=False), path)
602 self.assertRaises(OSError, realpath, path, strict=True)
603 self.assertRaises(OSError, realpath, path, strict=ALLOW_MISSING)
604 path = ABSTFN + '\x00\\..'
605 self.assertEqual(realpath(path, strict=False), os.getcwd())
606 self.assertEqual(realpath(path, strict=True), os.getcwd())
607 self.assertEqual(realpath(path, strict=ALLOW_MISSING), os.getcwd())
608 path = ABSTFNb + b'\x00\\..'
609 self.assertEqual(realpath(path, strict=False), os.getcwdb())
610 self.assertEqual(realpath(path, strict=True), os.getcwdb())
611 self.assertEqual(realpath(path, strict=ALLOW_MISSING), os.getcwdb())
612 path = ABSTFN + '\\nonexistent\\x\x00\\..'
613 self.assertEqual(realpath(path, strict=False), ABSTFN + '\\nonexistent')
614 self.assertRaises(OSError, realpath, path, strict=True)
615 self.assertEqual(realpath(path, strict=ALLOW_MISSING), ABSTFN + '\\nonexistent')
616 path = ABSTFNb + b'\\nonexistent\\x\x00\\..'
617 self.assertEqual(realpath(path, strict=False), ABSTFNb + b'\\nonexistent')
618 self.assertRaises(OSError, realpath, path, strict=True)
619 self.assertEqual(realpath(path, strict=ALLOW_MISSING), ABSTFNb + b'\\nonexistent')
620
621 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
622 @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING})
623 def test_realpath_invalid_unicode_paths(self, kwargs):
624 realpath = ntpath.realpath
625 ABSTFN = ntpath.abspath(os_helper.TESTFN)
626 ABSTFNb = os.fsencode(ABSTFN)
627 path = ABSTFNb + b'\xff'
628 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
629 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
630 path = ABSTFNb + b'\\nonexistent\\\xff'
631 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
632 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
633 path = ABSTFNb + b'\xff\\..'
634 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
635 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
636 path = ABSTFNb + b'\\nonexistent\\\xff\\..'
637 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
638 self.assertRaises(UnicodeDecodeError, realpath, path, **kwargs)
639
640 @os_helper.skip_unless_symlink
641 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
642 @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING})
643 def test_realpath_relative(self, kwargs):
644 ABSTFN = ntpath.abspath(os_helper.TESTFN)
645 open(ABSTFN, "wb").close()
646 self.addCleanup(os_helper.unlink, ABSTFN)
647 self.addCleanup(os_helper.unlink, ABSTFN + "1")
648
649 os.symlink(ABSTFN, ntpath.relpath(ABSTFN + "1"))
650 self.assertPathEqual(ntpath.realpath(ABSTFN + "1", **kwargs), ABSTFN)
651
652 @os_helper.skip_unless_symlink
653 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
654 def test_realpath_broken_symlinks(self):
655 ABSTFN = ntpath.abspath(os_helper.TESTFN)
656 os.mkdir(ABSTFN)
657 self.addCleanup(os_helper.rmtree, ABSTFN)
658
659 with os_helper.change_cwd(ABSTFN):
660 os.mkdir("subdir")
661 os.chdir("subdir")
662 os.symlink(".", "recursive")
663 os.symlink("..", "parent")
664 os.chdir("..")
665 os.symlink(".", "self")
666 os.symlink("missing", "broken")
667 os.symlink(r"broken\bar", "broken1")
668 os.symlink(r"self\self\broken", "broken2")
669 os.symlink(r"subdir\parent\subdir\parent\broken", "broken3")
670 os.symlink(ABSTFN + r"\broken", "broken4")
671 os.symlink(r"recursive\..\broken", "broken5")
672
673 self.assertPathEqual(ntpath.realpath("broken"),
674 ABSTFN + r"\missing")
675 self.assertPathEqual(ntpath.realpath(r"broken\foo"),
676 ABSTFN + r"\missing\foo")
677 # bpo-38453: We no longer recursively resolve segments of relative
678 # symlinks that the OS cannot resolve.
679 self.assertPathEqual(ntpath.realpath(r"broken1"),
680 ABSTFN + r"\broken\bar")
681 self.assertPathEqual(ntpath.realpath(r"broken1\baz"),
682 ABSTFN + r"\broken\bar\baz")
683 self.assertPathEqual(ntpath.realpath("broken2"),
684 ABSTFN + r"\self\self\missing")
685 self.assertPathEqual(ntpath.realpath("broken3"),
686 ABSTFN + r"\subdir\parent\subdir\parent\missing")
687 self.assertPathEqual(ntpath.realpath("broken4"),
688 ABSTFN + r"\missing")
689 self.assertPathEqual(ntpath.realpath("broken5"),
690 ABSTFN + r"\missing")
691
692 self.assertPathEqual(ntpath.realpath(b"broken"),
693 os.fsencode(ABSTFN + r"\missing"))
694 self.assertPathEqual(ntpath.realpath(rb"broken\foo"),
695 os.fsencode(ABSTFN + r"\missing\foo"))
696 self.assertPathEqual(ntpath.realpath(rb"broken1"),
697 os.fsencode(ABSTFN + r"\broken\bar"))
698 self.assertPathEqual(ntpath.realpath(rb"broken1\baz"),
699 os.fsencode(ABSTFN + r"\broken\bar\baz"))
700 self.assertPathEqual(ntpath.realpath(b"broken2"),
701 os.fsencode(ABSTFN + r"\self\self\missing"))
702 self.assertPathEqual(ntpath.realpath(rb"broken3"),
703 os.fsencode(ABSTFN + r"\subdir\parent\subdir\parent\missing"))
704 self.assertPathEqual(ntpath.realpath(b"broken4"),
705 os.fsencode(ABSTFN + r"\missing"))
706 self.assertPathEqual(ntpath.realpath(b"broken5"),
707 os.fsencode(ABSTFN + r"\missing"))
708
709 @os_helper.skip_unless_symlink
710 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
711 def test_realpath_symlink_loops(self):
712 # Symlink loops in non-strict mode are non-deterministic as to which
713 # path is returned, but it will always be the fully resolved path of
714 # one member of the cycle
715 ABSTFN = ntpath.abspath(os_helper.TESTFN)
716 self.addCleanup(os_helper.unlink, ABSTFN)
717 self.addCleanup(os_helper.unlink, ABSTFN + "1")
718 self.addCleanup(os_helper.unlink, ABSTFN + "2")
719 self.addCleanup(os_helper.unlink, ABSTFN + "y")
720 self.addCleanup(os_helper.unlink, ABSTFN + "c")
721 self.addCleanup(os_helper.unlink, ABSTFN + "a")
722
723 os.symlink(ABSTFN, ABSTFN)
724 self.assertPathEqual(ntpath.realpath(ABSTFN), ABSTFN)
725
726 os.symlink(ABSTFN + "1", ABSTFN + "2")
727 os.symlink(ABSTFN + "2", ABSTFN + "1")
728 expected = (ABSTFN + "1", ABSTFN + "2")
729 self.assertPathIn(ntpath.realpath(ABSTFN + "1"), expected)
730 self.assertPathIn(ntpath.realpath(ABSTFN + "2"), expected)
731
732 self.assertPathIn(ntpath.realpath(ABSTFN + "1\\x"),
733 (ntpath.join(r, "x") for r in expected))
734 self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\.."),
735 ntpath.dirname(ABSTFN))
736 self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\x"),
737 ntpath.dirname(ABSTFN) + "\\x")
738 os.symlink(ABSTFN + "x", ABSTFN + "y")
739 self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\"
740 + ntpath.basename(ABSTFN) + "y"),
741 ABSTFN + "x")
742 self.assertPathIn(ntpath.realpath(ABSTFN + "1\\..\\"
743 + ntpath.basename(ABSTFN) + "1"),
744 expected)
745
746 os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a")
747 self.assertPathEqual(ntpath.realpath(ABSTFN + "a"), ABSTFN + "a")
748
749 os.symlink("..\\" + ntpath.basename(ntpath.dirname(ABSTFN))
750 + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c")
751 self.assertPathEqual(ntpath.realpath(ABSTFN + "c"), ABSTFN + "c")
752
753 # Test using relative path as well.
754 self.assertPathEqual(ntpath.realpath(ntpath.basename(ABSTFN)), ABSTFN)
755
756 @os_helper.skip_unless_symlink
757 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
758 def test_realpath_symlink_loops_strict(self):
759 # Symlink loops raise OSError in strict mode
760 ABSTFN = ntpath.abspath(os_helper.TESTFN)
761 self.addCleanup(os_helper.unlink, ABSTFN)
762 self.addCleanup(os_helper.unlink, ABSTFN + "1")
763 self.addCleanup(os_helper.unlink, ABSTFN + "2")
764 self.addCleanup(os_helper.unlink, ABSTFN + "y")
765 self.addCleanup(os_helper.unlink, ABSTFN + "c")
766 self.addCleanup(os_helper.unlink, ABSTFN + "a")
767
768 os.symlink(ABSTFN, ABSTFN)
769 self.assertRaises(OSError, ntpath.realpath, ABSTFN, strict=True)
770
771 os.symlink(ABSTFN + "1", ABSTFN + "2")
772 os.symlink(ABSTFN + "2", ABSTFN + "1")
773 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1", strict=True)
774 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "2", strict=True)
775 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\x", strict=True)
776 # Windows eliminates '..' components before resolving links, so the
777 # following call is not expected to raise.
778 self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..", strict=True),
779 ntpath.dirname(ABSTFN))
780 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\..\\x", strict=True)
781 os.symlink(ABSTFN + "x", ABSTFN + "y")
782 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\..\\"
783 + ntpath.basename(ABSTFN) + "y",
784 strict=True)
785 self.assertRaises(OSError, ntpath.realpath,
786 ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "1",
787 strict=True)
788
789 os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a")
790 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "a", strict=True)
791
792 os.symlink("..\\" + ntpath.basename(ntpath.dirname(ABSTFN))
793 + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c")
794 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "c", strict=True)
795
796 # Test using relative path as well.
797 self.assertRaises(OSError, ntpath.realpath, ntpath.basename(ABSTFN),
798 strict=True)
799
800 @os_helper.skip_unless_symlink
801 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
802 def test_realpath_symlink_loops_raise(self):
803 # Symlink loops raise OSError in ALLOW_MISSING mode
804 ABSTFN = ntpath.abspath(os_helper.TESTFN)
805 self.addCleanup(os_helper.unlink, ABSTFN)
806 self.addCleanup(os_helper.unlink, ABSTFN + "1")
807 self.addCleanup(os_helper.unlink, ABSTFN + "2")
808 self.addCleanup(os_helper.unlink, ABSTFN + "y")
809 self.addCleanup(os_helper.unlink, ABSTFN + "c")
810 self.addCleanup(os_helper.unlink, ABSTFN + "a")
811 self.addCleanup(os_helper.unlink, ABSTFN + "x")
812
813 os.symlink(ABSTFN, ABSTFN)
814 self.assertRaises(OSError, ntpath.realpath, ABSTFN, strict=ALLOW_MISSING)
815
816 os.symlink(ABSTFN + "1", ABSTFN + "2")
817 os.symlink(ABSTFN + "2", ABSTFN + "1")
818 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1",
819 strict=ALLOW_MISSING)
820 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "2",
821 strict=ALLOW_MISSING)
822 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\x",
823 strict=ALLOW_MISSING)
824
825 # Windows eliminates '..' components before resolving links;
826 # realpath is not expected to raise if this removes the loop.
827 self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\.."),
828 ntpath.dirname(ABSTFN))
829 self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\x"),
830 ntpath.dirname(ABSTFN) + "\\x")
831
832 os.symlink(ABSTFN + "x", ABSTFN + "y")
833 self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\"
834 + ntpath.basename(ABSTFN) + "y"),
835 ABSTFN + "x")
836 self.assertRaises(
837 OSError, ntpath.realpath,
838 ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "1",
839 strict=ALLOW_MISSING)
840
841 os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a")
842 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "a",
843 strict=ALLOW_MISSING)
844
845 os.symlink("..\\" + ntpath.basename(ntpath.dirname(ABSTFN))
846 + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c")
847 self.assertRaises(OSError, ntpath.realpath, ABSTFN + "c",
848 strict=ALLOW_MISSING)
849
850 # Test using relative path as well.
851 self.assertRaises(OSError, ntpath.realpath, ntpath.basename(ABSTFN),
852 strict=ALLOW_MISSING)
853
854 @os_helper.skip_unless_symlink
855 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
856 @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING})
857 def test_realpath_symlink_prefix(self, kwargs):
858 ABSTFN = ntpath.abspath(os_helper.TESTFN)
859 self.addCleanup(os_helper.unlink, ABSTFN + "3")
860 self.addCleanup(os_helper.unlink, "\\\\?\\" + ABSTFN + "3.")
861 self.addCleanup(os_helper.unlink, ABSTFN + "3link")
862 self.addCleanup(os_helper.unlink, ABSTFN + "3.link")
863
864 with open(ABSTFN + "3", "wb") as f:
865 f.write(b'0')
866 os.symlink(ABSTFN + "3", ABSTFN + "3link")
867
868 with open("\\\\?\\" + ABSTFN + "3.", "wb") as f:
869 f.write(b'1')
870 os.symlink("\\\\?\\" + ABSTFN + "3.", ABSTFN + "3.link")
871
872 self.assertPathEqual(ntpath.realpath(ABSTFN + "3link", **kwargs),
873 ABSTFN + "3")
874 self.assertPathEqual(ntpath.realpath(ABSTFN + "3.link", **kwargs),
875 "\\\\?\\" + ABSTFN + "3.")
876
877 # Resolved paths should be usable to open target files
878 with open(ntpath.realpath(ABSTFN + "3link"), "rb") as f:
879 self.assertEqual(f.read(), b'0')
880 with open(ntpath.realpath(ABSTFN + "3.link"), "rb") as f:
881 self.assertEqual(f.read(), b'1')
882
883 # When the prefix is included, it is not stripped
884 self.assertPathEqual(ntpath.realpath("\\\\?\\" + ABSTFN + "3link", **kwargs),
885 "\\\\?\\" + ABSTFN + "3")
886 self.assertPathEqual(ntpath.realpath("\\\\?\\" + ABSTFN + "3.link", **kwargs),
887 "\\\\?\\" + ABSTFN + "3.")
888
889 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
890 def test_realpath_nul(self):
891 tester("ntpath.realpath('NUL')", r'\\.\NUL')
892 tester("ntpath.realpath('NUL', strict=False)", r'\\.\NUL')
893 tester("ntpath.realpath('NUL', strict=True)", r'\\.\NUL')
894 tester("ntpath.realpath('NUL', strict=ALLOW_MISSING)", r'\\.\NUL')
895
896 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
897 @unittest.skipUnless(HAVE_GETSHORTPATHNAME, 'need _getshortpathname')
898 def test_realpath_cwd(self):
899 ABSTFN = ntpath.abspath(os_helper.TESTFN)
900
901 os_helper.unlink(ABSTFN)
902 os_helper.rmtree(ABSTFN)
903 os.mkdir(ABSTFN)
904 self.addCleanup(os_helper.rmtree, ABSTFN)
905
906 test_dir_long = ntpath.join(ABSTFN, "MyVeryLongDirectoryName")
907 os.mkdir(test_dir_long)
908
909 test_dir_short = _getshortpathname(test_dir_long)
910 test_file_long = ntpath.join(test_dir_long, "file.txt")
911 test_file_short = ntpath.join(test_dir_short, "file.txt")
912
913 with open(test_file_long, "wb") as f:
914 f.write(b"content")
915
916 self.assertPathEqual(test_file_long, ntpath.realpath(test_file_short))
917
918 for kwargs in {}, {'strict': True}, {'strict': ALLOW_MISSING}:
919 with self.subTest(**kwargs):
920 with os_helper.change_cwd(test_dir_long):
921 self.assertPathEqual(
922 test_file_long,
923 ntpath.realpath("file.txt", **kwargs))
924 with os_helper.change_cwd(test_dir_long.lower()):
925 self.assertPathEqual(
926 test_file_long,
927 ntpath.realpath("file.txt", **kwargs))
928 with os_helper.change_cwd(test_dir_short):
929 self.assertPathEqual(
930 test_file_long,
931 ntpath.realpath("file.txt", **kwargs))
932
933 @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
934 def test_realpath_permission(self):
935 # Test whether python can resolve the real filename of a
936 # shortened file name even if it does not have permission to access it.
937 ABSTFN = ntpath.realpath(os_helper.TESTFN)
938
939 os_helper.unlink(ABSTFN)
940 os_helper.rmtree(ABSTFN)
941 os.mkdir(ABSTFN)
942 self.addCleanup(os_helper.rmtree, ABSTFN)
943
944 test_file = ntpath.join(ABSTFN, "LongFileName123.txt")
945 test_file_short = ntpath.join(ABSTFN, "LONGFI~1.TXT")
946
947 with open(test_file, "wb") as f:
948 f.write(b"content")
949 # Automatic generation of short names may be disabled on
950 # NTFS volumes for the sake of performance.
951 # They're not supported at all on ReFS and exFAT.
952 p = subprocess.run(
953 # Try to set the short name manually.
954 ['fsutil.exe', 'file', 'setShortName', test_file, 'LONGFI~1.TXT'],
955 creationflags=subprocess.DETACHED_PROCESS
956 )
957
958 if p.returncode:
959 raise unittest.SkipTest('failed to set short name')
960
961 try:
962 self.assertPathEqual(test_file, ntpath.realpath(test_file_short))
963 except AssertionError:
964 raise unittest.SkipTest('the filesystem seems to lack support for short filenames')
965
966 # Deny the right to [S]YNCHRONIZE on the file to
967 # force nt._getfinalpathname to fail with ERROR_ACCESS_DENIED.
968 p = subprocess.run(
969 ['icacls.exe', test_file, '/deny', '*S-1-5-32-545:(S)'],
970 creationflags=subprocess.DETACHED_PROCESS
971 )
972
973 if p.returncode:
974 raise unittest.SkipTest('failed to deny access to the test file')
975
976 self.assertPathEqual(test_file, ntpath.realpath(test_file_short))
977
978 def test_expandvars(self):
979 with os_helper.EnvironmentVarGuard() as env:
980 env.clear()
981 env["foo"] = "bar"
982 env["{foo"] = "baz1"
983 env["{foo}"] = "baz2"
984 tester('ntpath.expandvars("foo")', "foo")
985 tester('ntpath.expandvars("$foo bar")', "bar bar")
986 tester('ntpath.expandvars("${foo}bar")', "barbar")
987 tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
988 tester('ntpath.expandvars("$bar bar")', "$bar bar")
989 tester('ntpath.expandvars("$?bar")', "$?bar")
990 tester('ntpath.expandvars("$foo}bar")', "bar}bar")
991 tester('ntpath.expandvars("${foo")', "${foo")
992 tester('ntpath.expandvars("${{foo}}")', "baz1}")
993 tester('ntpath.expandvars("$foo$foo")', "barbar")
994 tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
995 tester('ntpath.expandvars("%foo% bar")', "bar bar")
996 tester('ntpath.expandvars("%foo%bar")', "barbar")
997 tester('ntpath.expandvars("%foo%%foo%")', "barbar")
998 tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
999 tester('ntpath.expandvars("%?bar%")', "%?bar%")
1000 tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
1001 tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
1002 tester('ntpath.expandvars("bar\'%foo%")', "bar\'%foo%")
1003
1004 @unittest.skipUnless(os_helper.FS_NONASCII, 'need os_helper.FS_NONASCII')
1005 def test_expandvars_nonascii(self):
1006 def check(value, expected):
1007 tester('ntpath.expandvars(%r)' % value, expected)
1008 with os_helper.EnvironmentVarGuard() as env:
1009 env.clear()
1010 nonascii = os_helper.FS_NONASCII
1011 env['spam'] = nonascii
1012 env[nonascii] = 'ham' + nonascii
1013 check('$spam bar', '%s bar' % nonascii)
1014 check('$%s bar' % nonascii, '$%s bar' % nonascii)
1015 check('${spam}bar', '%sbar' % nonascii)
1016 check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
1017 check('$spam}bar', '%s}bar' % nonascii)
1018 check('$%s}bar' % nonascii, '$%s}bar' % nonascii)
1019 check('%spam% bar', '%s bar' % nonascii)
1020 check('%{}% bar'.format(nonascii), 'ham%s bar' % nonascii)
1021 check('%spam%bar', '%sbar' % nonascii)
1022 check('%{}%bar'.format(nonascii), 'ham%sbar' % nonascii)
1023
1024 @support.requires_resource('cpu')
1025 def test_expandvars_large(self):
1026 expandvars = ntpath.expandvars
1027 with os_helper.EnvironmentVarGuard() as env:
1028 env.clear()
1029 env["A"] = "B"
1030 n = 100_000
1031 self.assertEqual(expandvars('%A%'*n), 'B'*n)
1032 self.assertEqual(expandvars('%A%A'*n), 'BA'*n)
1033 self.assertEqual(expandvars("''"*n + '%%'), "''"*n + '%')
1034 self.assertEqual(expandvars("%%"*n), "%"*n)
1035 self.assertEqual(expandvars("$$"*n), "$"*n)
1036
1037 def test_expanduser(self):
1038 tester('ntpath.expanduser("test")', 'test')
1039
1040 with os_helper.EnvironmentVarGuard() as env:
1041 env.clear()
1042 tester('ntpath.expanduser("~test")', '~test')
1043
1044 env['HOMEDRIVE'] = 'C:\\'
1045 env['HOMEPATH'] = 'Users\\eric'
1046 env['USERNAME'] = 'eric'
1047 tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
1048 tester('ntpath.expanduser("~")', 'C:\\Users\\eric')
1049
1050 del env['HOMEDRIVE']
1051 tester('ntpath.expanduser("~test")', 'Users\\test')
1052 tester('ntpath.expanduser("~")', 'Users\\eric')
1053
1054 env.clear()
1055 env['USERPROFILE'] = 'C:\\Users\\eric'
1056 env['USERNAME'] = 'eric'
1057 tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
1058 tester('ntpath.expanduser("~")', 'C:\\Users\\eric')
1059 tester('ntpath.expanduser("~test\\foo\\bar")',
1060 'C:\\Users\\test\\foo\\bar')
1061 tester('ntpath.expanduser("~test/foo/bar")',
1062 'C:\\Users\\test/foo/bar')
1063 tester('ntpath.expanduser("~\\foo\\bar")',
1064 'C:\\Users\\eric\\foo\\bar')
1065 tester('ntpath.expanduser("~/foo/bar")',
1066 'C:\\Users\\eric/foo/bar')
1067
1068 # bpo-36264: ignore `HOME` when set on windows
1069 env.clear()
1070 env['HOME'] = 'F:\\'
1071 env['USERPROFILE'] = 'C:\\Users\\eric'
1072 env['USERNAME'] = 'eric'
1073 tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
1074 tester('ntpath.expanduser("~")', 'C:\\Users\\eric')
1075
1076 # bpo-39899: don't guess another user's home directory if
1077 # `%USERNAME% != basename(%USERPROFILE%)`
1078 env.clear()
1079 env['USERPROFILE'] = 'C:\\Users\\eric'
1080 env['USERNAME'] = 'idle'
1081 tester('ntpath.expanduser("~test")', '~test')
1082 tester('ntpath.expanduser("~")', 'C:\\Users\\eric')
1083
1084
1085
1086 @unittest.skipUnless(nt, "abspath requires 'nt' module")
1087 def test_abspath(self):
1088 tester('ntpath.abspath("C:\\")', "C:\\")
1089 tester('ntpath.abspath("\\\\?\\C:////spam////eggs. . .")', "\\\\?\\C:\\spam\\eggs")
1090 tester('ntpath.abspath("\\\\.\\C:////spam////eggs. . .")', "\\\\.\\C:\\spam\\eggs")
1091 tester('ntpath.abspath("//spam//eggs. . .")', "\\\\spam\\eggs")
1092 tester('ntpath.abspath("\\\\spam\\\\eggs. . .")', "\\\\spam\\eggs")
1093 tester('ntpath.abspath("C:/spam. . .")', "C:\\spam")
1094 tester('ntpath.abspath("C:\\spam. . .")', "C:\\spam")
1095 tester('ntpath.abspath("C:/nul")', "\\\\.\\nul")
1096 tester('ntpath.abspath("C:\\nul")', "\\\\.\\nul")
1097 self.assertTrue(ntpath.isabs(ntpath.abspath("C:spam")))
1098 tester('ntpath.abspath("//..")', "\\\\")
1099 tester('ntpath.abspath("//../")', "\\\\..\\")
1100 tester('ntpath.abspath("//../..")', "\\\\..\\")
1101 tester('ntpath.abspath("//../../")', "\\\\..\\..\\")
1102 tester('ntpath.abspath("//../../../")', "\\\\..\\..\\")
1103 tester('ntpath.abspath("//../../../..")', "\\\\..\\..\\")
1104 tester('ntpath.abspath("//../../../../")', "\\\\..\\..\\")
1105 tester('ntpath.abspath("//server")', "\\\\server")
1106 tester('ntpath.abspath("//server/")', "\\\\server\\")
1107 tester('ntpath.abspath("//server/..")', "\\\\server\\")
1108 tester('ntpath.abspath("//server/../")', "\\\\server\\..\\")
1109 tester('ntpath.abspath("//server/../..")', "\\\\server\\..\\")
1110 tester('ntpath.abspath("//server/../../")', "\\\\server\\..\\")
1111 tester('ntpath.abspath("//server/../../..")', "\\\\server\\..\\")
1112 tester('ntpath.abspath("//server/../../../")', "\\\\server\\..\\")
1113 tester('ntpath.abspath("//server/share")', "\\\\server\\share")
1114 tester('ntpath.abspath("//server/share/")', "\\\\server\\share\\")
1115 tester('ntpath.abspath("//server/share/..")', "\\\\server\\share\\")
1116 tester('ntpath.abspath("//server/share/../")', "\\\\server\\share\\")
1117 tester('ntpath.abspath("//server/share/../..")', "\\\\server\\share\\")
1118 tester('ntpath.abspath("//server/share/../../")', "\\\\server\\share\\")
1119 tester('ntpath.abspath("C:\\nul. . .")', "\\\\.\\nul")
1120 tester('ntpath.abspath("//... . .")', "\\\\")
1121 tester('ntpath.abspath("//.. . . .")', "\\\\")
1122 tester('ntpath.abspath("//../... . .")', "\\\\..\\")
1123 tester('ntpath.abspath("//../.. . . .")', "\\\\..\\")
1124 with os_helper.temp_cwd(os_helper.TESTFN) as cwd_dir: # bpo-31047
1125 tester('ntpath.abspath("")', cwd_dir)
1126 tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
1127 tester('ntpath.abspath("?")', cwd_dir + "\\?")
1128 drive, _ = ntpath.splitdrive(cwd_dir)
1129 tester('ntpath.abspath("/abc/")', drive + "\\abc")
1130
1131 def test_abspath_invalid_paths(self):
1132 abspath = ntpath.abspath
1133 if sys.platform == 'win32':
1134 self.assertEqual(abspath("C:\x00"), ntpath.join(abspath("C:"), "\x00"))
1135 self.assertEqual(abspath(b"C:\x00"), ntpath.join(abspath(b"C:"), b"\x00"))
1136 self.assertEqual(abspath("\x00:spam"), "\x00:\\spam")
1137 self.assertEqual(abspath(b"\x00:spam"), b"\x00:\\spam")
1138 self.assertEqual(abspath('c:\\fo\x00o'), 'c:\\fo\x00o')
1139 self.assertEqual(abspath(b'c:\\fo\x00o'), b'c:\\fo\x00o')
1140 self.assertEqual(abspath('c:\\fo\x00o\\..\\bar'), 'c:\\bar')
1141 self.assertEqual(abspath(b'c:\\fo\x00o\\..\\bar'), b'c:\\bar')
1142 self.assertEqual(abspath('c:\\\udfff'), 'c:\\\udfff')
1143 self.assertEqual(abspath('c:\\\udfff\\..\\foo'), 'c:\\foo')
1144 if sys.platform == 'win32':
1145 self.assertRaises(UnicodeDecodeError, abspath, b'c:\\\xff')
1146 self.assertRaises(UnicodeDecodeError, abspath, b'c:\\\xff\\..\\foo')
1147 else:
1148 self.assertEqual(abspath(b'c:\\\xff'), b'c:\\\xff')
1149 self.assertEqual(abspath(b'c:\\\xff\\..\\foo'), b'c:\\foo')
1150
1151 def test_relpath(self):
1152 tester('ntpath.relpath("a")', 'a')
1153 tester('ntpath.relpath(ntpath.abspath("a"))', 'a')
1154 tester('ntpath.relpath("a/b")', 'a\\b')
1155 tester('ntpath.relpath("../a/b")', '..\\a\\b')
1156 with os_helper.temp_cwd(os_helper.TESTFN) as cwd_dir:
1157 currentdir = ntpath.basename(cwd_dir)
1158 tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
1159 tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
1160 tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
1161 tester('ntpath.relpath("c:/foo/bar/bat", "c:/x/y")', '..\\..\\foo\\bar\\bat')
1162 tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
1163 tester('ntpath.relpath("a", "a")', '.')
1164 tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")', '..\\..\\..\\foo\\bar\\bat')
1165 tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat')
1166 tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat')
1167 tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..')
1168 tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat')
1169 tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x')
1170 tester('ntpath.relpath("/", "/")', '.')
1171 tester('ntpath.relpath("/a", "/a")', '.')
1172 tester('ntpath.relpath("/a/b", "/a/b")', '.')
1173 tester('ntpath.relpath("c:/foo", "C:/FOO")', '.')
1174
1175 def test_commonpath(self):
1176 def check(paths, expected):
1177 tester(('ntpath.commonpath(%r)' % paths).replace('\\\\', '\\'),
1178 expected)
1179 def check_error(paths, expected):
1180 self.assertRaisesRegex(ValueError, expected, ntpath.commonpath, paths)
1181 self.assertRaisesRegex(ValueError, expected, ntpath.commonpath, paths[::-1])
1182 self.assertRaisesRegex(ValueError, expected, ntpath.commonpath,
1183 [os.fsencode(p) for p in paths])
1184 self.assertRaisesRegex(ValueError, expected, ntpath.commonpath,
1185 [os.fsencode(p) for p in paths[::-1]])
1186
1187 self.assertRaises(TypeError, ntpath.commonpath, None)
1188 self.assertRaises(ValueError, ntpath.commonpath, [])
1189 self.assertRaises(ValueError, ntpath.commonpath, iter([]))
1190
1191 # gh-117381: Logical error messages
1192 check_error(['C:\\Foo', 'C:Foo'], "Can't mix absolute and relative paths")
1193 check_error(['C:\\Foo', '\\Foo'], "Paths don't have the same drive")
1194 check_error(['C:\\Foo', 'Foo'], "Paths don't have the same drive")
1195 check_error(['C:Foo', '\\Foo'], "Paths don't have the same drive")
1196 check_error(['C:Foo', 'Foo'], "Paths don't have the same drive")
1197 check_error(['\\Foo', 'Foo'], "Can't mix rooted and not-rooted paths")
1198
1199 check(['C:\\Foo'], 'C:\\Foo')
1200 check(['C:\\Foo', 'C:\\Foo'], 'C:\\Foo')
1201 check(['C:\\Foo\\', 'C:\\Foo'], 'C:\\Foo')
1202 check(['C:\\Foo\\', 'C:\\Foo\\'], 'C:\\Foo')
1203 check(['C:\\\\Foo', 'C:\\Foo\\\\'], 'C:\\Foo')
1204 check(['C:\\.\\Foo', 'C:\\Foo\\.'], 'C:\\Foo')
1205 check(['C:\\', 'C:\\baz'], 'C:\\')
1206 check(['C:\\Bar', 'C:\\baz'], 'C:\\')
1207 check(['C:\\Foo', 'C:\\Foo\\Baz'], 'C:\\Foo')
1208 check(['C:\\Foo\\Bar', 'C:\\Foo\\Baz'], 'C:\\Foo')
1209 check(['C:\\Bar', 'C:\\Baz'], 'C:\\')
1210 check(['C:\\Bar\\', 'C:\\Baz'], 'C:\\')
1211
1212 check(['C:\\Foo\\Bar', 'C:/Foo/Baz'], 'C:\\Foo')
1213 check(['C:\\Foo\\Bar', 'c:/foo/baz'], 'C:\\Foo')
1214 check(['c:/foo/bar', 'C:\\Foo\\Baz'], 'c:\\foo')
1215
1216 # gh-117381: Logical error messages
1217 check_error(['C:\\Foo', 'D:\\Foo'], "Paths don't have the same drive")
1218 check_error(['C:\\Foo', 'D:Foo'], "Paths don't have the same drive")
1219 check_error(['C:Foo', 'D:Foo'], "Paths don't have the same drive")
1220
1221 check(['spam'], 'spam')
1222 check(['spam', 'spam'], 'spam')
1223 check(['spam', 'alot'], '')
1224 check(['and\\jam', 'and\\spam'], 'and')
1225 check(['and\\\\jam', 'and\\spam\\\\'], 'and')
1226 check(['and\\.\\jam', '.\\and\\spam'], 'and')
1227 check(['and\\jam', 'and\\spam', 'alot'], '')
1228 check(['and\\jam', 'and\\spam', 'and'], 'and')
1229 check(['C:and\\jam', 'C:and\\spam'], 'C:and')
1230
1231 check([''], '')
1232 check(['', 'spam\\alot'], '')
1233
1234 # gh-117381: Logical error messages
1235 check_error(['', '\\spam\\alot'], "Can't mix rooted and not-rooted paths")
1236
1237 self.assertRaises(TypeError, ntpath.commonpath, [b'C:\\Foo', 'C:\\Foo\\Baz'])
1238 self.assertRaises(TypeError, ntpath.commonpath, [b'C:\\Foo', 'Foo\\Baz'])
1239 self.assertRaises(TypeError, ntpath.commonpath, [b'Foo', 'C:\\Foo\\Baz'])
1240 self.assertRaises(TypeError, ntpath.commonpath, ['C:\\Foo', b'C:\\Foo\\Baz'])
1241 self.assertRaises(TypeError, ntpath.commonpath, ['C:\\Foo', b'Foo\\Baz'])
1242 self.assertRaises(TypeError, ntpath.commonpath, ['Foo', b'C:\\Foo\\Baz'])
1243
1244 def test_sameopenfile(self):
1245 with TemporaryFile() as tf1, TemporaryFile() as tf2:
1246 # Make sure the same file is really the same
1247 self.assertTrue(ntpath.sameopenfile(tf1.fileno(), tf1.fileno()))
1248 # Make sure different files are really different
1249 self.assertFalse(ntpath.sameopenfile(tf1.fileno(), tf2.fileno()))
1250 # Make sure invalid values don't cause issues on win32
1251 if sys.platform == "win32":
1252 with self.assertRaises(OSError):
1253 # Invalid file descriptors shouldn't display assert
1254 # dialogs (#4804)
1255 ntpath.sameopenfile(-1, -1)
1256
1257 def test_ismount(self):
1258 self.assertTrue(ntpath.ismount("c:\\"))
1259 self.assertTrue(ntpath.ismount("C:\\"))
1260 self.assertTrue(ntpath.ismount("c:/"))
1261 self.assertTrue(ntpath.ismount("C:/"))
1262 self.assertTrue(ntpath.ismount("\\\\.\\c:\\"))
1263 self.assertTrue(ntpath.ismount("\\\\.\\C:\\"))
1264
1265 self.assertTrue(ntpath.ismount(b"c:\\"))
1266 self.assertTrue(ntpath.ismount(b"C:\\"))
1267 self.assertTrue(ntpath.ismount(b"c:/"))
1268 self.assertTrue(ntpath.ismount(b"C:/"))
1269 self.assertTrue(ntpath.ismount(b"\\\\.\\c:\\"))
1270 self.assertTrue(ntpath.ismount(b"\\\\.\\C:\\"))
1271
1272 with os_helper.temp_dir() as d:
1273 self.assertFalse(ntpath.ismount(d))
1274
1275 if sys.platform == "win32":
1276 #
1277 # Make sure the current folder isn't the root folder
1278 # (or any other volume root). The drive-relative
1279 # locations below cannot then refer to mount points
1280 #
1281 test_cwd = os.getenv("SystemRoot")
1282 drive, path = ntpath.splitdrive(test_cwd)
1283 with os_helper.change_cwd(test_cwd):
1284 self.assertFalse(ntpath.ismount(drive.lower()))
1285 self.assertFalse(ntpath.ismount(drive.upper()))
1286
1287 self.assertTrue(ntpath.ismount("\\\\localhost\\c$"))
1288 self.assertTrue(ntpath.ismount("\\\\localhost\\c$\\"))
1289
1290 self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$"))
1291 self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$\\"))
1292
1293 def test_ismount_invalid_paths(self):
1294 ismount = ntpath.ismount
1295 self.assertFalse(ismount("c:\\\udfff"))
1296 if sys.platform == 'win32':
1297 self.assertRaises(ValueError, ismount, "c:\\\x00")
1298 self.assertRaises(ValueError, ismount, b"c:\\\x00")
1299 self.assertRaises(UnicodeDecodeError, ismount, b"c:\\\xff")
1300 else:
1301 self.assertFalse(ismount("c:\\\x00"))
1302 self.assertFalse(ismount(b"c:\\\x00"))
1303 self.assertFalse(ismount(b"c:\\\xff"))
1304
1305 def test_isreserved(self):
1306 self.assertFalse(ntpath.isreserved(''))
1307 self.assertFalse(ntpath.isreserved('.'))
1308 self.assertFalse(ntpath.isreserved('..'))
1309 self.assertFalse(ntpath.isreserved('/'))
1310 self.assertFalse(ntpath.isreserved('/foo/bar'))
1311 # A name that ends with a space or dot is reserved.
1312 self.assertTrue(ntpath.isreserved('foo.'))
1313 self.assertTrue(ntpath.isreserved('foo '))
1314 # ASCII control characters are reserved.
1315 self.assertTrue(ntpath.isreserved('\foo'))
1316 # Wildcard characters, colon, and pipe are reserved.
1317 self.assertTrue(ntpath.isreserved('foo*bar'))
1318 self.assertTrue(ntpath.isreserved('foo?bar'))
1319 self.assertTrue(ntpath.isreserved('foo"bar'))
1320 self.assertTrue(ntpath.isreserved('foo<bar'))
1321 self.assertTrue(ntpath.isreserved('foo>bar'))
1322 self.assertTrue(ntpath.isreserved('foo:bar'))
1323 self.assertTrue(ntpath.isreserved('foo|bar'))
1324 # Case-insensitive DOS-device names are reserved.
1325 self.assertTrue(ntpath.isreserved('nul'))
1326 self.assertTrue(ntpath.isreserved('aux'))
1327 self.assertTrue(ntpath.isreserved('prn'))
1328 self.assertTrue(ntpath.isreserved('con'))
1329 self.assertTrue(ntpath.isreserved('conin$'))
1330 self.assertTrue(ntpath.isreserved('conout$'))
1331 # COM/LPT + 1-9 or + superscript 1-3 are reserved.
1332 self.assertTrue(ntpath.isreserved('COM1'))
1333 self.assertTrue(ntpath.isreserved('LPT9'))
1334 self.assertTrue(ntpath.isreserved('com\xb9'))
1335 self.assertTrue(ntpath.isreserved('com\xb2'))
1336 self.assertTrue(ntpath.isreserved('lpt\xb3'))
1337 # DOS-device name matching ignores characters after a dot or
1338 # a colon and also ignores trailing spaces.
1339 self.assertTrue(ntpath.isreserved('NUL.txt'))
1340 self.assertTrue(ntpath.isreserved('PRN '))
1341 self.assertTrue(ntpath.isreserved('AUX .txt'))
1342 self.assertTrue(ntpath.isreserved('COM1:bar'))
1343 self.assertTrue(ntpath.isreserved('LPT9 :bar'))
1344 # DOS-device names are only matched at the beginning
1345 # of a path component.
1346 self.assertFalse(ntpath.isreserved('bar.com9'))
1347 self.assertFalse(ntpath.isreserved('bar.lpt9'))
1348 # The entire path is checked, except for the drive.
1349 self.assertTrue(ntpath.isreserved('c:/bar/baz/NUL'))
1350 self.assertTrue(ntpath.isreserved('c:/NUL/bar/baz'))
1351 self.assertFalse(ntpath.isreserved('//./NUL'))
1352 # Bytes are supported.
1353 self.assertFalse(ntpath.isreserved(b''))
1354 self.assertFalse(ntpath.isreserved(b'.'))
1355 self.assertFalse(ntpath.isreserved(b'..'))
1356 self.assertFalse(ntpath.isreserved(b'/'))
1357 self.assertFalse(ntpath.isreserved(b'/foo/bar'))
1358 self.assertTrue(ntpath.isreserved(b'foo.'))
1359 self.assertTrue(ntpath.isreserved(b'nul'))
1360
1361 def assertEqualCI(self, s1, s2):
1362 """Assert that two strings are equal ignoring case differences."""
1363 self.assertEqual(s1.lower(), s2.lower())
1364
1365 @unittest.skipUnless(nt, "OS helpers require 'nt' module")
1366 def test_nt_helpers(self):
1367 # Trivial validation that the helpers do not break, and support both
1368 # unicode and bytes (UTF-8) paths
1369
1370 executable = nt._getfinalpathname(sys.executable)
1371
1372 for path in executable, os.fsencode(executable):
1373 volume_path = nt._getvolumepathname(path)
1374 path_drive = ntpath.splitdrive(path)[0]
1375 volume_path_drive = ntpath.splitdrive(volume_path)[0]
1376 self.assertEqualCI(path_drive, volume_path_drive)
1377
1378 cap, free = nt._getdiskusage(sys.exec_prefix)
1379 self.assertGreater(cap, 0)
1380 self.assertGreater(free, 0)
1381 b_cap, b_free = nt._getdiskusage(sys.exec_prefix.encode())
1382 # Free space may change, so only test the capacity is equal
1383 self.assertEqual(b_cap, cap)
1384 self.assertGreater(b_free, 0)
1385
1386 for path in [sys.prefix, sys.executable]:
1387 final_path = nt._getfinalpathname(path)
1388 self.assertIsInstance(final_path, str)
1389 self.assertGreater(len(final_path), 0)
1390
1391 b_final_path = nt._getfinalpathname(path.encode())
1392 self.assertIsInstance(b_final_path, bytes)
1393 self.assertGreater(len(b_final_path), 0)
1394
1395 @unittest.skipIf(sys.platform != 'win32', "Can only test junctions with creation on win32.")
1396 def test_isjunction(self):
1397 with os_helper.temp_dir() as d:
1398 with os_helper.change_cwd(d):
1399 os.mkdir('tmpdir')
1400
1401 import _winapi
1402 try:
1403 _winapi.CreateJunction('tmpdir', 'testjunc')
1404 except OSError:
1405 raise unittest.SkipTest('creating the test junction failed')
1406
1407 self.assertTrue(ntpath.isjunction('testjunc'))
1408 self.assertFalse(ntpath.isjunction('tmpdir'))
1409 self.assertPathEqual(ntpath.realpath('testjunc'), ntpath.realpath('tmpdir'))
1410
1411 def test_isfile_invalid_paths(self):
1412 isfile = ntpath.isfile
1413 self.assertIs(isfile('/tmp\udfffabcds'), False)
1414 self.assertIs(isfile(b'/tmp\xffabcds'), False)
1415 self.assertIs(isfile('/tmp\x00abcds'), False)
1416 self.assertIs(isfile(b'/tmp\x00abcds'), False)
1417
1418 @unittest.skipIf(sys.platform != 'win32', "drive letters are a windows concept")
1419 def test_isfile_driveletter(self):
1420 drive = os.environ.get('SystemDrive')
1421 if drive is None or len(drive) != 2 or drive[1] != ':':
1422 raise unittest.SkipTest('SystemDrive is not defined or malformed')
1423 self.assertFalse(os.path.isfile('\\\\.\\' + drive))
1424
1425 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
1426 def test_isfile_anonymous_pipe(self):
1427 pr, pw = os.pipe()
1428 try:
1429 self.assertFalse(ntpath.isfile(pr))
1430 finally:
1431 os.close(pr)
1432 os.close(pw)
1433
1434 @unittest.skipIf(sys.platform != 'win32', "windows only")
1435 def test_isfile_named_pipe(self):
1436 import _winapi
1437 named_pipe = f'//./PIPE/python_isfile_test_{os.getpid()}'
1438 h = _winapi.CreateNamedPipe(named_pipe,
1439 _winapi.PIPE_ACCESS_INBOUND,
1440 0, 1, 0, 0, 0, 0)
1441 try:
1442 self.assertFalse(ntpath.isfile(named_pipe))
1443 finally:
1444 _winapi.CloseHandle(h)
1445
1446 @unittest.skipIf(sys.platform != 'win32', "windows only")
1447 def test_con_device(self):
1448 self.assertFalse(os.path.isfile(r"\\.\CON"))
1449 self.assertFalse(os.path.isdir(r"\\.\CON"))
1450 self.assertFalse(os.path.islink(r"\\.\CON"))
1451 self.assertTrue(os.path.exists(r"\\.\CON"))
1452
1453 @unittest.skipIf(sys.platform != 'win32', "Fast paths are only for win32")
1454 @support.cpython_only
1455 def test_fast_paths_in_use(self):
1456 # There are fast paths of these functions implemented in posixmodule.c.
1457 # Confirm that they are being used, and not the Python fallbacks in
1458 # genericpath.py.
1459 self.assertTrue(os.path.splitroot is nt._path_splitroot_ex)
1460 self.assertFalse(inspect.isfunction(os.path.splitroot))
1461 self.assertTrue(os.path.normpath is nt._path_normpath)
1462 self.assertFalse(inspect.isfunction(os.path.normpath))
1463 self.assertTrue(os.path.isdir is nt._path_isdir)
1464 self.assertFalse(inspect.isfunction(os.path.isdir))
1465 self.assertTrue(os.path.isfile is nt._path_isfile)
1466 self.assertFalse(inspect.isfunction(os.path.isfile))
1467 self.assertTrue(os.path.islink is nt._path_islink)
1468 self.assertFalse(inspect.isfunction(os.path.islink))
1469 self.assertTrue(os.path.isjunction is nt._path_isjunction)
1470 self.assertFalse(inspect.isfunction(os.path.isjunction))
1471 self.assertTrue(os.path.exists is nt._path_exists)
1472 self.assertFalse(inspect.isfunction(os.path.exists))
1473 self.assertTrue(os.path.lexists is nt._path_lexists)
1474 self.assertFalse(inspect.isfunction(os.path.lexists))
1475
1476 @unittest.skipIf(os.name != 'nt', "Dev Drives only exist on Win32")
1477 def test_isdevdrive(self):
1478 # Result may be True or False, but shouldn't raise
1479 self.assertIn(ntpath.isdevdrive(os_helper.TESTFN), (True, False))
1480 # ntpath.isdevdrive can handle relative paths
1481 self.assertIn(ntpath.isdevdrive("."), (True, False))
1482 self.assertIn(ntpath.isdevdrive(b"."), (True, False))
1483 # Volume syntax is supported
1484 self.assertIn(ntpath.isdevdrive(os.listvolumes()[0]), (True, False))
1485 # Invalid volume returns False from os.path method
1486 self.assertFalse(ntpath.isdevdrive(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\\"))
1487 # Invalid volume raises from underlying helper
1488 with self.assertRaises(OSError):
1489 nt._path_isdevdrive(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\\")
1490
1491 @unittest.skipIf(os.name == 'nt', "isdevdrive fallback only used off Win32")
1492 def test_isdevdrive_fallback(self):
1493 # Fallback always returns False
1494 self.assertFalse(ntpath.isdevdrive(os_helper.TESTFN))
1495
1496
1497 class NtCommonTest(test_genericpath.CommonTest, unittest.TestCase):
1498 pathmodule = ntpath
1499 attributes = ['relpath']
1500
1501
1502 class PathLikeTests(NtpathTestCase):
1503
1504 path = ntpath
1505
1506 def setUp(self):
1507 self.file_name = os_helper.TESTFN
1508 self.file_path = FakePath(os_helper.TESTFN)
1509 self.addCleanup(os_helper.unlink, self.file_name)
1510 with open(self.file_name, 'xb', 0) as file:
1511 file.write(b"test_ntpath.PathLikeTests")
1512
1513 def _check_function(self, func):
1514 self.assertPathEqual(func(self.file_path), func(self.file_name))
1515
1516 def test_path_normcase(self):
1517 self._check_function(self.path.normcase)
1518
1519 def test_path_isabs(self):
1520 self._check_function(self.path.isabs)
1521
1522 def test_path_join(self):
1523 self.assertEqual(self.path.join('a', FakePath('b'), 'c'),
1524 self.path.join('a', 'b', 'c'))
1525
1526 def test_path_split(self):
1527 self._check_function(self.path.split)
1528
1529 def test_path_splitext(self):
1530 self._check_function(self.path.splitext)
1531
1532 def test_path_splitdrive(self):
1533 self._check_function(self.path.splitdrive)
1534
1535 def test_path_splitroot(self):
1536 self._check_function(self.path.splitroot)
1537
1538 def test_path_basename(self):
1539 self._check_function(self.path.basename)
1540
1541 def test_path_dirname(self):
1542 self._check_function(self.path.dirname)
1543
1544 def test_path_islink(self):
1545 self._check_function(self.path.islink)
1546
1547 def test_path_lexists(self):
1548 self._check_function(self.path.lexists)
1549
1550 def test_path_ismount(self):
1551 self._check_function(self.path.ismount)
1552
1553 def test_path_expanduser(self):
1554 self._check_function(self.path.expanduser)
1555
1556 def test_path_expandvars(self):
1557 self._check_function(self.path.expandvars)
1558
1559 def test_path_normpath(self):
1560 self._check_function(self.path.normpath)
1561
1562 def test_path_abspath(self):
1563 self._check_function(self.path.abspath)
1564
1565 def test_path_realpath(self):
1566 self._check_function(self.path.realpath)
1567
1568 def test_path_relpath(self):
1569 self._check_function(self.path.relpath)
1570
1571 def test_path_commonpath(self):
1572 common_path = self.path.commonpath([self.file_path, self.file_name])
1573 self.assertPathEqual(common_path, self.file_name)
1574
1575 def test_path_isdir(self):
1576 self._check_function(self.path.isdir)
1577
1578
1579 if __name__ == "__main__":
1580 unittest.main()