blob: fc2398c2d518ba19ab734278842b95377b9f1377 [file] [log] [blame]
Guido van Rossumead9d8d1999-02-03 17:21:21 +00001import ntpath
Mark Hammond673c6cf2000-08-14 06:21:26 +00002import os
Brian Curtin13a0db52010-09-06 19:46:17 +00003import sys
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01004import unittest
5import warnings
Serhiy Storchakab21d1552018-03-02 11:53:51 +02006from test.support import TestFailed, FakePath
Florent Xiclunac9c79782010-03-08 12:24:53 +00007from test import support, test_genericpath
Brian Curtin62857742010-09-06 17:07:27 +00008from tempfile import TemporaryFile
Guido van Rossumead9d8d1999-02-03 17:21:21 +00009
Steve Dower23ad6d02018-02-22 10:39:10 -080010try:
11 import nt
12except ImportError:
13 # Most tests can complete without the nt module,
14 # but for those that require it we import here.
15 nt = None
Guido van Rossumead9d8d1999-02-03 17:21:21 +000016
17def tester(fn, wantResult):
Eric S. Raymondfc170b12001-02-09 11:51:27 +000018 fn = fn.replace("\\", "\\\\")
Fred Drake004d5e62000-10-23 17:22:08 +000019 gotResult = eval(fn)
20 if wantResult != gotResult:
Christian Heimesf6cd9672008-03-26 13:45:42 +000021 raise TestFailed("%s should return: %s but returned: %s" \
22 %(str(fn), str(wantResult), str(gotResult)))
Tim Peters6578dc92002-12-24 18:31:27 +000023
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000024 # then with bytes
25 fn = fn.replace("('", "(b'")
26 fn = fn.replace('("', '(b"')
27 fn = fn.replace("['", "[b'")
28 fn = fn.replace('["', '[b"')
29 fn = fn.replace(", '", ", b'")
30 fn = fn.replace(', "', ', b"')
Serhiy Storchakadbb10192014-02-13 10:13:53 +020031 fn = os.fsencode(fn).decode('latin1')
32 fn = fn.encode('ascii', 'backslashreplace').decode('ascii')
Victor Stinner1ab6c2d2011-11-15 22:27:41 +010033 with warnings.catch_warnings():
34 warnings.simplefilter("ignore", DeprecationWarning)
35 gotResult = eval(fn)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000036 if isinstance(wantResult, str):
Serhiy Storchakadbb10192014-02-13 10:13:53 +020037 wantResult = os.fsencode(wantResult)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000038 elif isinstance(wantResult, tuple):
Serhiy Storchakadbb10192014-02-13 10:13:53 +020039 wantResult = tuple(os.fsencode(r) for r in wantResult)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000040
41 gotResult = eval(fn)
42 if wantResult != gotResult:
43 raise TestFailed("%s should return: %s but returned: %s" \
44 %(str(fn), str(wantResult), repr(gotResult)))
Guido van Rossumead9d8d1999-02-03 17:21:21 +000045
Mark Hammond5a607a32009-05-06 08:04:54 +000046
Christian Heimesf6cd9672008-03-26 13:45:42 +000047class TestNtpath(unittest.TestCase):
48 def test_splitext(self):
49 tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
50 tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext'))
51 tester('ntpath.splitext(".ext")', ('.ext', ''))
52 tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', ''))
53 tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', ''))
54 tester('ntpath.splitext("")', ('', ''))
55 tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext'))
56 tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext'))
57 tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext'))
58 tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d'))
Guido van Rossumead9d8d1999-02-03 17:21:21 +000059
Christian Heimesf6cd9672008-03-26 13:45:42 +000060 def test_splitdrive(self):
61 tester('ntpath.splitdrive("c:\\foo\\bar")',
62 ('c:', '\\foo\\bar'))
63 tester('ntpath.splitdrive("c:/foo/bar")',
64 ('c:', '/foo/bar'))
Mark Hammond5a607a32009-05-06 08:04:54 +000065 tester('ntpath.splitdrive("\\\\conky\\mountpoint\\foo\\bar")',
Christian Heimesf6cd9672008-03-26 13:45:42 +000066 ('\\\\conky\\mountpoint', '\\foo\\bar'))
Mark Hammond5a607a32009-05-06 08:04:54 +000067 tester('ntpath.splitdrive("//conky/mountpoint/foo/bar")',
Christian Heimesf6cd9672008-03-26 13:45:42 +000068 ('//conky/mountpoint', '/foo/bar'))
Mark Hammond5a607a32009-05-06 08:04:54 +000069 tester('ntpath.splitdrive("\\\\\\conky\\mountpoint\\foo\\bar")',
70 ('', '\\\\\\conky\\mountpoint\\foo\\bar'))
71 tester('ntpath.splitdrive("///conky/mountpoint/foo/bar")',
72 ('', '///conky/mountpoint/foo/bar'))
73 tester('ntpath.splitdrive("\\\\conky\\\\mountpoint\\foo\\bar")',
74 ('', '\\\\conky\\\\mountpoint\\foo\\bar'))
75 tester('ntpath.splitdrive("//conky//mountpoint/foo/bar")',
76 ('', '//conky//mountpoint/foo/bar'))
Serhiy Storchaka3d7e1152013-12-16 14:34:55 +020077 # Issue #19911: UNC part containing U+0130
78 self.assertEqual(ntpath.splitdrive('//conky/MOUNTPOİNT/foo/bar'),
79 ('//conky/MOUNTPOİNT', '/foo/bar'))
Guido van Rossumead9d8d1999-02-03 17:21:21 +000080
Christian Heimesf6cd9672008-03-26 13:45:42 +000081 def test_split(self):
82 tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
83 tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")',
84 ('\\\\conky\\mountpoint\\foo', 'bar'))
Guido van Rossumead9d8d1999-02-03 17:21:21 +000085
Christian Heimesf6cd9672008-03-26 13:45:42 +000086 tester('ntpath.split("c:\\")', ('c:\\', ''))
87 tester('ntpath.split("\\\\conky\\mountpoint\\")',
Mark Hammond5a607a32009-05-06 08:04:54 +000088 ('\\\\conky\\mountpoint\\', ''))
Guido van Rossumead9d8d1999-02-03 17:21:21 +000089
Christian Heimesf6cd9672008-03-26 13:45:42 +000090 tester('ntpath.split("c:/")', ('c:/', ''))
Mark Hammond5a607a32009-05-06 08:04:54 +000091 tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint/', ''))
Mark Hammond673c6cf2000-08-14 06:21:26 +000092
Christian Heimesf6cd9672008-03-26 13:45:42 +000093 def test_isabs(self):
94 tester('ntpath.isabs("c:\\")', 1)
95 tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1)
96 tester('ntpath.isabs("\\foo")', 1)
97 tester('ntpath.isabs("\\foo\\bar")', 1)
Tim Petersd4f7f602001-07-19 19:11:41 +000098
Christian Heimesf6cd9672008-03-26 13:45:42 +000099 def test_commonprefix(self):
100 tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])',
101 "/home/swen")
102 tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])',
103 "\\home\\swen\\")
104 tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])',
105 "/home/swen/spam")
Tim Peters6a3e5f12001-11-05 21:25:02 +0000106
Christian Heimesf6cd9672008-03-26 13:45:42 +0000107 def test_join(self):
108 tester('ntpath.join("")', '')
109 tester('ntpath.join("", "", "")', '')
110 tester('ntpath.join("a")', 'a')
111 tester('ntpath.join("/a")', '/a')
112 tester('ntpath.join("\\a")', '\\a')
113 tester('ntpath.join("a:")', 'a:')
Christian Heimesf6cd9672008-03-26 13:45:42 +0000114 tester('ntpath.join("a:", "\\b")', 'a:\\b')
Christian Heimesf6cd9672008-03-26 13:45:42 +0000115 tester('ntpath.join("a", "\\b")', '\\b')
116 tester('ntpath.join("a", "b", "c")', 'a\\b\\c')
117 tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c')
118 tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c')
119 tester('ntpath.join("a", "b", "\\c")', '\\c')
120 tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep')
121 tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b')
Tim Peters54a14a32001-08-30 22:05:26 +0000122
Christian Heimesf6cd9672008-03-26 13:45:42 +0000123 tester("ntpath.join('', 'a')", 'a')
124 tester("ntpath.join('', '', '', '', 'a')", 'a')
125 tester("ntpath.join('a', '')", 'a\\')
126 tester("ntpath.join('a', '', '', '', '')", 'a\\')
127 tester("ntpath.join('a\\', '')", 'a\\')
128 tester("ntpath.join('a\\', '', '', '', '')", 'a\\')
Serhiy Storchakac369c2c2014-01-27 23:15:14 +0200129 tester("ntpath.join('a/', '')", 'a/')
Tim Peters54a14a32001-08-30 22:05:26 +0000130
Serhiy Storchakac369c2c2014-01-27 23:15:14 +0200131 tester("ntpath.join('a/b', 'x/y')", 'a/b\\x/y')
132 tester("ntpath.join('/a/b', 'x/y')", '/a/b\\x/y')
133 tester("ntpath.join('/a/b/', 'x/y')", '/a/b/x/y')
134 tester("ntpath.join('c:', 'x/y')", 'c:x/y')
135 tester("ntpath.join('c:a/b', 'x/y')", 'c:a/b\\x/y')
136 tester("ntpath.join('c:a/b/', 'x/y')", 'c:a/b/x/y')
137 tester("ntpath.join('c:/', 'x/y')", 'c:/x/y')
138 tester("ntpath.join('c:/a/b', 'x/y')", 'c:/a/b\\x/y')
139 tester("ntpath.join('c:/a/b/', 'x/y')", 'c:/a/b/x/y')
140 tester("ntpath.join('//computer/share', 'x/y')", '//computer/share\\x/y')
141 tester("ntpath.join('//computer/share/', 'x/y')", '//computer/share/x/y')
142 tester("ntpath.join('//computer/share/a/b', 'x/y')", '//computer/share/a/b\\x/y')
Mark Hammond5a607a32009-05-06 08:04:54 +0000143
Serhiy Storchakac369c2c2014-01-27 23:15:14 +0200144 tester("ntpath.join('a/b', '/x/y')", '/x/y')
145 tester("ntpath.join('/a/b', '/x/y')", '/x/y')
146 tester("ntpath.join('c:', '/x/y')", 'c:/x/y')
147 tester("ntpath.join('c:a/b', '/x/y')", 'c:/x/y')
148 tester("ntpath.join('c:/', '/x/y')", 'c:/x/y')
149 tester("ntpath.join('c:/a/b', '/x/y')", 'c:/x/y')
150 tester("ntpath.join('//computer/share', '/x/y')", '//computer/share/x/y')
151 tester("ntpath.join('//computer/share/', '/x/y')", '//computer/share/x/y')
152 tester("ntpath.join('//computer/share/a', '/x/y')", '//computer/share/x/y')
153
154 tester("ntpath.join('c:', 'C:x/y')", 'C:x/y')
155 tester("ntpath.join('c:a/b', 'C:x/y')", 'C:a/b\\x/y')
156 tester("ntpath.join('c:/', 'C:x/y')", 'C:/x/y')
157 tester("ntpath.join('c:/a/b', 'C:x/y')", 'C:/a/b\\x/y')
158
159 for x in ('', 'a/b', '/a/b', 'c:', 'c:a/b', 'c:/', 'c:/a/b',
160 '//computer/share', '//computer/share/', '//computer/share/a/b'):
161 for y in ('d:', 'd:x/y', 'd:/', 'd:/x/y',
162 '//machine/common', '//machine/common/', '//machine/common/x/y'):
163 tester("ntpath.join(%r, %r)" % (x, y), y)
Mark Hammond5a607a32009-05-06 08:04:54 +0000164
165 tester("ntpath.join('\\\\computer\\share\\', 'a', 'b')", '\\\\computer\\share\\a\\b')
166 tester("ntpath.join('\\\\computer\\share', 'a', 'b')", '\\\\computer\\share\\a\\b')
167 tester("ntpath.join('\\\\computer\\share', 'a\\b')", '\\\\computer\\share\\a\\b')
168 tester("ntpath.join('//computer/share/', 'a', 'b')", '//computer/share/a\\b')
169 tester("ntpath.join('//computer/share', 'a', 'b')", '//computer/share\\a\\b')
170 tester("ntpath.join('//computer/share', 'a/b')", '//computer/share\\a/b')
171
Christian Heimesf6cd9672008-03-26 13:45:42 +0000172 def test_normpath(self):
173 tester("ntpath.normpath('A//////././//.//B')", r'A\B')
174 tester("ntpath.normpath('A/./B')", r'A\B')
175 tester("ntpath.normpath('A/foo/../B')", r'A\B')
176 tester("ntpath.normpath('C:A//B')", r'C:A\B')
177 tester("ntpath.normpath('D:A/./B')", r'D:A\B')
178 tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B')
Tim Peters54a14a32001-08-30 22:05:26 +0000179
Christian Heimesf6cd9672008-03-26 13:45:42 +0000180 tester("ntpath.normpath('C:///A//B')", r'C:\A\B')
181 tester("ntpath.normpath('D:///A/./B')", r'D:\A\B')
182 tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B')
Thomas Woutersb2137042007-02-01 18:02:27 +0000183
Christian Heimesf6cd9672008-03-26 13:45:42 +0000184 tester("ntpath.normpath('..')", r'..')
185 tester("ntpath.normpath('.')", r'.')
186 tester("ntpath.normpath('')", r'.')
187 tester("ntpath.normpath('/')", '\\')
188 tester("ntpath.normpath('c:/')", 'c:\\')
189 tester("ntpath.normpath('/../.././..')", '\\')
190 tester("ntpath.normpath('c:/../../..')", 'c:\\')
191 tester("ntpath.normpath('../.././..')", r'..\..\..')
192 tester("ntpath.normpath('K:../.././..')", r'K:..\..\..')
193 tester("ntpath.normpath('C:////a/b')", r'C:\a\b')
194 tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')
Fred Drake5e997312002-01-15 03:46:43 +0000195
Georg Brandlcfb68212010-07-31 21:40:15 +0000196 tester("ntpath.normpath('\\\\.\\NUL')", r'\\.\NUL')
197 tester("ntpath.normpath('\\\\?\\D:/XY\\Z')", r'\\?\D:/XY\Z')
198
Christian Heimesf6cd9672008-03-26 13:45:42 +0000199 def test_expandvars(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000200 with support.EnvironmentVarGuard() as env:
201 env.clear()
202 env["foo"] = "bar"
203 env["{foo"] = "baz1"
204 env["{foo}"] = "baz2"
Christian Heimesf6cd9672008-03-26 13:45:42 +0000205 tester('ntpath.expandvars("foo")', "foo")
206 tester('ntpath.expandvars("$foo bar")', "bar bar")
207 tester('ntpath.expandvars("${foo}bar")', "barbar")
208 tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
209 tester('ntpath.expandvars("$bar bar")', "$bar bar")
210 tester('ntpath.expandvars("$?bar")', "$?bar")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000211 tester('ntpath.expandvars("$foo}bar")', "bar}bar")
212 tester('ntpath.expandvars("${foo")', "${foo")
213 tester('ntpath.expandvars("${{foo}}")', "baz1}")
214 tester('ntpath.expandvars("$foo$foo")', "barbar")
215 tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
216 tester('ntpath.expandvars("%foo% bar")', "bar bar")
217 tester('ntpath.expandvars("%foo%bar")', "barbar")
218 tester('ntpath.expandvars("%foo%%foo%")', "barbar")
219 tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
220 tester('ntpath.expandvars("%?bar%")', "%?bar%")
221 tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
222 tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
Serhiy Storchaka1b87ae02015-03-25 16:40:15 +0200223 tester('ntpath.expandvars("bar\'%foo%")', "bar\'%foo%")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200225 @unittest.skipUnless(support.FS_NONASCII, 'need support.FS_NONASCII')
226 def test_expandvars_nonascii(self):
227 def check(value, expected):
228 tester('ntpath.expandvars(%r)' % value, expected)
229 with support.EnvironmentVarGuard() as env:
230 env.clear()
231 nonascii = support.FS_NONASCII
232 env['spam'] = nonascii
233 env[nonascii] = 'ham' + nonascii
234 check('$spam bar', '%s bar' % nonascii)
235 check('$%s bar' % nonascii, '$%s bar' % nonascii)
236 check('${spam}bar', '%sbar' % nonascii)
237 check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
238 check('$spam}bar', '%s}bar' % nonascii)
239 check('$%s}bar' % nonascii, '$%s}bar' % nonascii)
240 check('%spam% bar', '%s bar' % nonascii)
241 check('%{}% bar'.format(nonascii), 'ham%s bar' % nonascii)
242 check('%spam%bar', '%sbar' % nonascii)
243 check('%{}%bar'.format(nonascii), 'ham%sbar' % nonascii)
244
Serhiy Storchakaffc1e6d2014-05-28 18:11:29 +0300245 def test_expanduser(self):
246 tester('ntpath.expanduser("test")', 'test')
247
248 with support.EnvironmentVarGuard() as env:
249 env.clear()
250 tester('ntpath.expanduser("~test")', '~test')
251
252 env['HOMEPATH'] = 'eric\\idle'
253 env['HOMEDRIVE'] = 'C:\\'
254 tester('ntpath.expanduser("~test")', 'C:\\eric\\test')
255 tester('ntpath.expanduser("~")', 'C:\\eric\\idle')
256
257 del env['HOMEDRIVE']
258 tester('ntpath.expanduser("~test")', 'eric\\test')
259 tester('ntpath.expanduser("~")', 'eric\\idle')
260
261 env.clear()
262 env['USERPROFILE'] = 'C:\\eric\\idle'
263 tester('ntpath.expanduser("~test")', 'C:\\eric\\test')
264 tester('ntpath.expanduser("~")', 'C:\\eric\\idle')
Serhiy Storchakaffc1e6d2014-05-28 18:11:29 +0300265 tester('ntpath.expanduser("~test\\foo\\bar")',
Anthony Sottile25ec4a42019-03-12 08:39:57 -0700266 'C:\\eric\\test\\foo\\bar')
Serhiy Storchakaffc1e6d2014-05-28 18:11:29 +0300267 tester('ntpath.expanduser("~test/foo/bar")',
Anthony Sottile25ec4a42019-03-12 08:39:57 -0700268 'C:\\eric\\test/foo/bar')
Serhiy Storchakaffc1e6d2014-05-28 18:11:29 +0300269 tester('ntpath.expanduser("~\\foo\\bar")',
Anthony Sottile25ec4a42019-03-12 08:39:57 -0700270 'C:\\eric\\idle\\foo\\bar')
Serhiy Storchakaffc1e6d2014-05-28 18:11:29 +0300271 tester('ntpath.expanduser("~/foo/bar")',
Anthony Sottile25ec4a42019-03-12 08:39:57 -0700272 'C:\\eric\\idle/foo/bar')
273
274 # bpo-36264: ignore `HOME` when set on windows
275 env.clear()
276 env['HOME'] = 'F:\\'
277 env['USERPROFILE'] = 'C:\\eric\\idle'
278 tester('ntpath.expanduser("~test")', 'C:\\eric\\test')
279 tester('ntpath.expanduser("~")', 'C:\\eric\\idle')
Serhiy Storchakaffc1e6d2014-05-28 18:11:29 +0300280
Steve Dower23ad6d02018-02-22 10:39:10 -0800281 @unittest.skipUnless(nt, "abspath requires 'nt' module")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000282 def test_abspath(self):
Steve Dower23ad6d02018-02-22 10:39:10 -0800283 tester('ntpath.abspath("C:\\")', "C:\\")
Franz Wöllertd2e902e2018-07-29 14:47:09 +0200284 with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047
285 tester('ntpath.abspath("")', cwd_dir)
286 tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
287 tester('ntpath.abspath("?")', cwd_dir + "\\?")
Tim Grahamd03b7752018-10-25 11:26:38 -0400288 drive, _ = ntpath.splitdrive(cwd_dir)
289 tester('ntpath.abspath("/abc/")', drive + "\\abc")
Christian Heimesf6cd9672008-03-26 13:45:42 +0000290
291 def test_relpath(self):
Christian Heimesf6cd9672008-03-26 13:45:42 +0000292 tester('ntpath.relpath("a")', 'a')
293 tester('ntpath.relpath(os.path.abspath("a"))', 'a')
294 tester('ntpath.relpath("a/b")', 'a\\b')
295 tester('ntpath.relpath("../a/b")', '..\\a\\b')
Serhiy Storchaka5106d042015-01-26 10:26:14 +0200296 with support.temp_cwd(support.TESTFN) as cwd_dir:
297 currentdir = os.path.basename(cwd_dir)
298 tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
299 tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
Christian Heimesf6cd9672008-03-26 13:45:42 +0000300 tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
Mark Hammond5a607a32009-05-06 08:04:54 +0000301 tester('ntpath.relpath("c:/foo/bar/bat", "c:/x/y")', '..\\..\\foo\\bar\\bat')
Christian Heimesf6cd9672008-03-26 13:45:42 +0000302 tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
303 tester('ntpath.relpath("a", "a")', '.')
Mark Hammond5a607a32009-05-06 08:04:54 +0000304 tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")', '..\\..\\..\\foo\\bar\\bat')
305 tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat')
306 tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat')
307 tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..')
308 tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat')
309 tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x')
310 tester('ntpath.relpath("/", "/")', '.')
311 tester('ntpath.relpath("/a", "/a")', '.')
312 tester('ntpath.relpath("/a/b", "/a/b")', '.')
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000313 tester('ntpath.relpath("c:/foo", "C:/FOO")', '.')
Christian Heimesf6cd9672008-03-26 13:45:42 +0000314
Serhiy Storchaka38220932015-03-31 15:31:53 +0300315 def test_commonpath(self):
316 def check(paths, expected):
317 tester(('ntpath.commonpath(%r)' % paths).replace('\\\\', '\\'),
318 expected)
319 def check_error(exc, paths):
320 self.assertRaises(exc, ntpath.commonpath, paths)
321 self.assertRaises(exc, ntpath.commonpath,
322 [os.fsencode(p) for p in paths])
323
324 self.assertRaises(ValueError, ntpath.commonpath, [])
325 check_error(ValueError, ['C:\\Program Files', 'Program Files'])
326 check_error(ValueError, ['C:\\Program Files', 'C:Program Files'])
327 check_error(ValueError, ['\\Program Files', 'Program Files'])
328 check_error(ValueError, ['Program Files', 'C:\\Program Files'])
329 check(['C:\\Program Files'], 'C:\\Program Files')
330 check(['C:\\Program Files', 'C:\\Program Files'], 'C:\\Program Files')
331 check(['C:\\Program Files\\', 'C:\\Program Files'],
332 'C:\\Program Files')
333 check(['C:\\Program Files\\', 'C:\\Program Files\\'],
334 'C:\\Program Files')
335 check(['C:\\\\Program Files', 'C:\\Program Files\\\\'],
336 'C:\\Program Files')
337 check(['C:\\.\\Program Files', 'C:\\Program Files\\.'],
338 'C:\\Program Files')
339 check(['C:\\', 'C:\\bin'], 'C:\\')
340 check(['C:\\Program Files', 'C:\\bin'], 'C:\\')
341 check(['C:\\Program Files', 'C:\\Program Files\\Bar'],
342 'C:\\Program Files')
343 check(['C:\\Program Files\\Foo', 'C:\\Program Files\\Bar'],
344 'C:\\Program Files')
345 check(['C:\\Program Files', 'C:\\Projects'], 'C:\\')
346 check(['C:\\Program Files\\', 'C:\\Projects'], 'C:\\')
347
348 check(['C:\\Program Files\\Foo', 'C:/Program Files/Bar'],
349 'C:\\Program Files')
350 check(['C:\\Program Files\\Foo', 'c:/program files/bar'],
351 'C:\\Program Files')
352 check(['c:/program files/bar', 'C:\\Program Files\\Foo'],
353 'c:\\program files')
354
355 check_error(ValueError, ['C:\\Program Files', 'D:\\Program Files'])
356
357 check(['spam'], 'spam')
358 check(['spam', 'spam'], 'spam')
359 check(['spam', 'alot'], '')
360 check(['and\\jam', 'and\\spam'], 'and')
361 check(['and\\\\jam', 'and\\spam\\\\'], 'and')
362 check(['and\\.\\jam', '.\\and\\spam'], 'and')
363 check(['and\\jam', 'and\\spam', 'alot'], '')
364 check(['and\\jam', 'and\\spam', 'and'], 'and')
365 check(['C:and\\jam', 'C:and\\spam'], 'C:and')
366
367 check([''], '')
368 check(['', 'spam\\alot'], '')
369 check_error(ValueError, ['', '\\spam\\alot'])
370
371 self.assertRaises(TypeError, ntpath.commonpath,
372 [b'C:\\Program Files', 'C:\\Program Files\\Foo'])
373 self.assertRaises(TypeError, ntpath.commonpath,
374 [b'C:\\Program Files', 'Program Files\\Foo'])
375 self.assertRaises(TypeError, ntpath.commonpath,
376 [b'Program Files', 'C:\\Program Files\\Foo'])
377 self.assertRaises(TypeError, ntpath.commonpath,
378 ['C:\\Program Files', b'C:\\Program Files\\Foo'])
379 self.assertRaises(TypeError, ntpath.commonpath,
380 ['C:\\Program Files', b'Program Files\\Foo'])
381 self.assertRaises(TypeError, ntpath.commonpath,
382 ['Program Files', b'C:\\Program Files\\Foo'])
383
Brian Curtin62857742010-09-06 17:07:27 +0000384 def test_sameopenfile(self):
385 with TemporaryFile() as tf1, TemporaryFile() as tf2:
386 # Make sure the same file is really the same
387 self.assertTrue(ntpath.sameopenfile(tf1.fileno(), tf1.fileno()))
388 # Make sure different files are really different
389 self.assertFalse(ntpath.sameopenfile(tf1.fileno(), tf2.fileno()))
Brian Curtin13a0db52010-09-06 19:46:17 +0000390 # Make sure invalid values don't cause issues on win32
391 if sys.platform == "win32":
Hirokazu Yamamoto26253bb2010-12-05 04:16:47 +0000392 with self.assertRaises(OSError):
Brian Curtin13a0db52010-09-06 19:46:17 +0000393 # Invalid file descriptors shouldn't display assert
394 # dialogs (#4804)
395 ntpath.sameopenfile(-1, -1)
Brian Curtin62857742010-09-06 17:07:27 +0000396
Tim Golden6b528062013-08-01 12:44:00 +0100397 def test_ismount(self):
398 self.assertTrue(ntpath.ismount("c:\\"))
399 self.assertTrue(ntpath.ismount("C:\\"))
400 self.assertTrue(ntpath.ismount("c:/"))
401 self.assertTrue(ntpath.ismount("C:/"))
402 self.assertTrue(ntpath.ismount("\\\\.\\c:\\"))
403 self.assertTrue(ntpath.ismount("\\\\.\\C:\\"))
404
405 self.assertTrue(ntpath.ismount(b"c:\\"))
406 self.assertTrue(ntpath.ismount(b"C:\\"))
407 self.assertTrue(ntpath.ismount(b"c:/"))
408 self.assertTrue(ntpath.ismount(b"C:/"))
409 self.assertTrue(ntpath.ismount(b"\\\\.\\c:\\"))
410 self.assertTrue(ntpath.ismount(b"\\\\.\\C:\\"))
411
412 with support.temp_dir() as d:
413 self.assertFalse(ntpath.ismount(d))
414
Tim Goldenb2fcebb2013-08-01 13:58:58 +0100415 if sys.platform == "win32":
416 #
417 # Make sure the current folder isn't the root folder
418 # (or any other volume root). The drive-relative
419 # locations below cannot then refer to mount points
420 #
421 drive, path = ntpath.splitdrive(sys.executable)
422 with support.change_cwd(os.path.dirname(sys.executable)):
423 self.assertFalse(ntpath.ismount(drive.lower()))
424 self.assertFalse(ntpath.ismount(drive.upper()))
Tim Golden6b528062013-08-01 12:44:00 +0100425
Tim Goldenb2fcebb2013-08-01 13:58:58 +0100426 self.assertTrue(ntpath.ismount("\\\\localhost\\c$"))
427 self.assertTrue(ntpath.ismount("\\\\localhost\\c$\\"))
Tim Golden6b528062013-08-01 12:44:00 +0100428
Tim Goldenb2fcebb2013-08-01 13:58:58 +0100429 self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$"))
430 self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$\\"))
Christian Heimesf6cd9672008-03-26 13:45:42 +0000431
Tim Goldenff64add2018-07-25 14:36:54 +0100432 def assertEqualCI(self, s1, s2):
433 """Assert that two strings are equal ignoring case differences."""
434 self.assertEqual(s1.lower(), s2.lower())
435
Steve Dower23ad6d02018-02-22 10:39:10 -0800436 @unittest.skipUnless(nt, "OS helpers require 'nt' module")
437 def test_nt_helpers(self):
438 # Trivial validation that the helpers do not break, and support both
439 # unicode and bytes (UTF-8) paths
440
Tim Goldenff64add2018-07-25 14:36:54 +0100441 executable = nt._getfinalpathname(sys.executable)
442
443 for path in executable, os.fsencode(executable):
444 volume_path = nt._getvolumepathname(path)
445 path_drive = ntpath.splitdrive(path)[0]
446 volume_path_drive = ntpath.splitdrive(volume_path)[0]
447 self.assertEqualCI(path_drive, volume_path_drive)
Steve Dower23ad6d02018-02-22 10:39:10 -0800448
449 cap, free = nt._getdiskusage(sys.exec_prefix)
450 self.assertGreater(cap, 0)
451 self.assertGreater(free, 0)
452 b_cap, b_free = nt._getdiskusage(sys.exec_prefix.encode())
453 # Free space may change, so only test the capacity is equal
454 self.assertEqual(b_cap, cap)
455 self.assertGreater(b_free, 0)
456
457 for path in [sys.prefix, sys.executable]:
458 final_path = nt._getfinalpathname(path)
459 self.assertIsInstance(final_path, str)
460 self.assertGreater(len(final_path), 0)
461
462 b_final_path = nt._getfinalpathname(path.encode())
463 self.assertIsInstance(b_final_path, bytes)
464 self.assertGreater(len(b_final_path), 0)
465
Ezio Melottid0dfe9a2013-01-10 03:12:50 +0200466class NtCommonTest(test_genericpath.CommonTest, unittest.TestCase):
Florent Xiclunac9c79782010-03-08 12:24:53 +0000467 pathmodule = ntpath
Serhiy Storchaka9ed707e2017-01-13 20:55:05 +0200468 attributes = ['relpath']
Florent Xiclunac9c79782010-03-08 12:24:53 +0000469
470
Brett Cannon3f9183b2016-08-26 14:44:48 -0700471class PathLikeTests(unittest.TestCase):
472
473 path = ntpath
474
Brett Cannon3f9183b2016-08-26 14:44:48 -0700475 def setUp(self):
476 self.file_name = support.TESTFN.lower()
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200477 self.file_path = FakePath(support.TESTFN)
Brett Cannon3f9183b2016-08-26 14:44:48 -0700478 self.addCleanup(support.unlink, self.file_name)
479 with open(self.file_name, 'xb', 0) as file:
480 file.write(b"test_ntpath.PathLikeTests")
481
482 def assertPathEqual(self, func):
483 self.assertEqual(func(self.file_path), func(self.file_name))
484
485 def test_path_normcase(self):
486 self.assertPathEqual(self.path.normcase)
487
488 def test_path_isabs(self):
489 self.assertPathEqual(self.path.isabs)
490
491 def test_path_join(self):
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200492 self.assertEqual(self.path.join('a', FakePath('b'), 'c'),
Brett Cannon3f9183b2016-08-26 14:44:48 -0700493 self.path.join('a', 'b', 'c'))
494
495 def test_path_split(self):
496 self.assertPathEqual(self.path.split)
497
498 def test_path_splitext(self):
499 self.assertPathEqual(self.path.splitext)
500
501 def test_path_splitdrive(self):
502 self.assertPathEqual(self.path.splitdrive)
503
504 def test_path_basename(self):
505 self.assertPathEqual(self.path.basename)
506
507 def test_path_dirname(self):
508 self.assertPathEqual(self.path.dirname)
509
510 def test_path_islink(self):
511 self.assertPathEqual(self.path.islink)
512
513 def test_path_lexists(self):
514 self.assertPathEqual(self.path.lexists)
515
516 def test_path_ismount(self):
517 self.assertPathEqual(self.path.ismount)
518
519 def test_path_expanduser(self):
520 self.assertPathEqual(self.path.expanduser)
521
522 def test_path_expandvars(self):
523 self.assertPathEqual(self.path.expandvars)
524
525 def test_path_normpath(self):
526 self.assertPathEqual(self.path.normpath)
527
528 def test_path_abspath(self):
529 self.assertPathEqual(self.path.abspath)
530
531 def test_path_realpath(self):
532 self.assertPathEqual(self.path.realpath)
533
534 def test_path_relpath(self):
535 self.assertPathEqual(self.path.relpath)
536
537 def test_path_commonpath(self):
538 common_path = self.path.commonpath([self.file_path, self.file_name])
539 self.assertEqual(common_path, self.file_name)
540
541 def test_path_isdir(self):
542 self.assertPathEqual(self.path.isdir)
543
544
Christian Heimesf6cd9672008-03-26 13:45:42 +0000545if __name__ == "__main__":
546 unittest.main()