1""" 2Tests common to genericpath, macpath, ntpath and posixpath 3""" 4 5import genericpath 6import os 7import sys 8import unittest 9import warnings 10from test import support 11from test.support.script_helper import assert_python_ok 12from test.support import FakePath 13 14 15def create_file(filename, data=b'foo'): 16 with open(filename, 'xb', 0) as fp: 17 fp.write(data) 18 19 20class GenericTest: 21 common_attributes = ['commonprefix', 'getsize', 'getatime', 'getctime', 22 'getmtime', 'exists', 'isdir', 'isfile'] 23 attributes = [] 24 25 def test_no_argument(self): 26 for attr in self.common_attributes + self.attributes: 27 with self.assertRaises(TypeError): 28 getattr(self.pathmodule, attr)() 29 raise self.fail("{}.{}() did not raise a TypeError" 30 .format(self.pathmodule.__name__, attr)) 31 32 def test_commonprefix(self): 33 commonprefix = self.pathmodule.commonprefix 34 self.assertEqual( 35 commonprefix([]), 36 "" 37 ) 38 self.assertEqual( 39 commonprefix(["/home/swenson/spam", "/home/swen/spam"]), 40 "/home/swen" 41 ) 42 self.assertEqual( 43 commonprefix(["/home/swen/spam", "/home/swen/eggs"]), 44 "/home/swen/" 45 ) 46 self.assertEqual( 47 commonprefix(["/home/swen/spam", "/home/swen/spam"]), 48 "/home/swen/spam" 49 ) 50 self.assertEqual( 51 commonprefix(["home:swenson:spam", "home:swen:spam"]), 52 "home:swen" 53 ) 54 self.assertEqual( 55 commonprefix([":home:swen:spam", ":home:swen:eggs"]), 56 ":home:swen:" 57 ) 58 self.assertEqual( 59 commonprefix([":home:swen:spam", ":home:swen:spam"]), 60 ":home:swen:spam" 61 ) 62 63 self.assertEqual( 64 commonprefix([b"/home/swenson/spam", b"/home/swen/spam"]), 65 b"/home/swen" 66 ) 67 self.assertEqual( 68 commonprefix([b"/home/swen/spam", b"/home/swen/eggs"]), 69 b"/home/swen/" 70 ) 71 self.assertEqual( 72 commonprefix([b"/home/swen/spam", b"/home/swen/spam"]), 73 b"/home/swen/spam" 74 ) 75 self.assertEqual( 76 commonprefix([b"home:swenson:spam", b"home:swen:spam"]), 77 b"home:swen" 78 ) 79 self.assertEqual( 80 commonprefix([b":home:swen:spam", b":home:swen:eggs"]), 81 b":home:swen:" 82 ) 83 self.assertEqual( 84 commonprefix([b":home:swen:spam", b":home:swen:spam"]), 85 b":home:swen:spam" 86 ) 87 88 testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd', 89 'aXc', 'abd', 'ab', 'aX', 'abcX'] 90 for s1 in testlist: 91 for s2 in testlist: 92 p = commonprefix([s1, s2]) 93 self.assertTrue(s1.startswith(p)) 94 self.assertTrue(s2.startswith(p)) 95 if s1 != s2: 96 n = len(p) 97 self.assertNotEqual(s1[n:n+1], s2[n:n+1]) 98 99 def test_getsize(self): 100 filename = support.TESTFN 101 self.addCleanup(support.unlink, filename) 102 103 create_file(filename, b'Hello') 104 self.assertEqual(self.pathmodule.getsize(filename), 5) 105 os.remove(filename) 106 107 create_file(filename, b'Hello World!') 108 self.assertEqual(self.pathmodule.getsize(filename), 12) 109 110 def test_filetime(self): 111 filename = support.TESTFN 112 self.addCleanup(support.unlink, filename) 113 114 create_file(filename, b'foo') 115 116 with open(filename, "ab", 0) as f: 117 f.write(b"bar") 118 119 with open(filename, "rb", 0) as f: 120 data = f.read() 121 self.assertEqual(data, b"foobar") 122 123 self.assertLessEqual( 124 self.pathmodule.getctime(filename), 125 self.pathmodule.getmtime(filename) 126 ) 127 128 def test_exists(self): 129 filename = support.TESTFN 130 bfilename = os.fsencode(filename) 131 self.addCleanup(support.unlink, filename) 132 133 self.assertIs(self.pathmodule.exists(filename), False) 134 self.assertIs(self.pathmodule.exists(bfilename), False) 135 136 create_file(filename) 137 138 self.assertIs(self.pathmodule.exists(filename), True) 139 self.assertIs(self.pathmodule.exists(bfilename), True) 140 141 if self.pathmodule is not genericpath: 142 self.assertIs(self.pathmodule.lexists(filename), True) 143 self.assertIs(self.pathmodule.lexists(bfilename), True) 144 145 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") 146 def test_exists_fd(self): 147 r, w = os.pipe() 148 try: 149 self.assertTrue(self.pathmodule.exists(r)) 150 finally: 151 os.close(r) 152 os.close(w) 153 self.assertFalse(self.pathmodule.exists(r)) 154 155 def test_isdir(self): 156 filename = support.TESTFN 157 bfilename = os.fsencode(filename) 158 self.assertIs(self.pathmodule.isdir(filename), False) 159 self.assertIs(self.pathmodule.isdir(bfilename), False) 160 161 try: 162 create_file(filename) 163 self.assertIs(self.pathmodule.isdir(filename), False) 164 self.assertIs(self.pathmodule.isdir(bfilename), False) 165 finally: 166 support.unlink(filename) 167 168 try: 169 os.mkdir(filename) 170 self.assertIs(self.pathmodule.isdir(filename), True) 171 self.assertIs(self.pathmodule.isdir(bfilename), True) 172 finally: 173 support.rmdir(filename) 174 175 def test_isfile(self): 176 filename = support.TESTFN 177 bfilename = os.fsencode(filename) 178 self.assertIs(self.pathmodule.isfile(filename), False) 179 self.assertIs(self.pathmodule.isfile(bfilename), False) 180 181 try: 182 create_file(filename) 183 self.assertIs(self.pathmodule.isfile(filename), True) 184 self.assertIs(self.pathmodule.isfile(bfilename), True) 185 finally: 186 support.unlink(filename) 187 188 try: 189 os.mkdir(filename) 190 self.assertIs(self.pathmodule.isfile(filename), False) 191 self.assertIs(self.pathmodule.isfile(bfilename), False) 192 finally: 193 support.rmdir(filename) 194 195 def test_samefile(self): 196 file1 = support.TESTFN 197 file2 = support.TESTFN + "2" 198 self.addCleanup(support.unlink, file1) 199 self.addCleanup(support.unlink, file2) 200 201 create_file(file1) 202 self.assertTrue(self.pathmodule.samefile(file1, file1)) 203 204 create_file(file2) 205 self.assertFalse(self.pathmodule.samefile(file1, file2)) 206 207 self.assertRaises(TypeError, self.pathmodule.samefile) 208 209 def _test_samefile_on_link_func(self, func): 210 test_fn1 = support.TESTFN 211 test_fn2 = support.TESTFN + "2" 212 self.addCleanup(support.unlink, test_fn1) 213 self.addCleanup(support.unlink, test_fn2) 214 215 create_file(test_fn1) 216 217 func(test_fn1, test_fn2) 218 self.assertTrue(self.pathmodule.samefile(test_fn1, test_fn2)) 219 os.remove(test_fn2) 220 221 create_file(test_fn2) 222 self.assertFalse(self.pathmodule.samefile(test_fn1, test_fn2)) 223 224 @support.skip_unless_symlink 225 def test_samefile_on_symlink(self): 226 self._test_samefile_on_link_func(os.symlink) 227 228 def test_samefile_on_link(self): 229 try: 230 self._test_samefile_on_link_func(os.link) 231 except PermissionError as e: 232 self.skipTest('os.link(): %s' % e) 233 234 def test_samestat(self): 235 test_fn1 = support.TESTFN 236 test_fn2 = support.TESTFN + "2" 237 self.addCleanup(support.unlink, test_fn1) 238 self.addCleanup(support.unlink, test_fn2) 239 240 create_file(test_fn1) 241 stat1 = os.stat(test_fn1) 242 self.assertTrue(self.pathmodule.samestat(stat1, os.stat(test_fn1))) 243 244 create_file(test_fn2) 245 stat2 = os.stat(test_fn2) 246 self.assertFalse(self.pathmodule.samestat(stat1, stat2)) 247 248 self.assertRaises(TypeError, self.pathmodule.samestat) 249 250 def _test_samestat_on_link_func(self, func): 251 test_fn1 = support.TESTFN + "1" 252 test_fn2 = support.TESTFN + "2" 253 self.addCleanup(support.unlink, test_fn1) 254 self.addCleanup(support.unlink, test_fn2) 255 256 create_file(test_fn1) 257 func(test_fn1, test_fn2) 258 self.assertTrue(self.pathmodule.samestat(os.stat(test_fn1), 259 os.stat(test_fn2))) 260 os.remove(test_fn2) 261 262 create_file(test_fn2) 263 self.assertFalse(self.pathmodule.samestat(os.stat(test_fn1), 264 os.stat(test_fn2))) 265 266 @support.skip_unless_symlink 267 def test_samestat_on_symlink(self): 268 self._test_samestat_on_link_func(os.symlink) 269 270 def test_samestat_on_link(self): 271 try: 272 self._test_samestat_on_link_func(os.link) 273 except PermissionError as e: 274 self.skipTest('os.link(): %s' % e) 275 276 def test_sameopenfile(self): 277 filename = support.TESTFN 278 self.addCleanup(support.unlink, filename) 279 create_file(filename) 280 281 with open(filename, "rb", 0) as fp1: 282 fd1 = fp1.fileno() 283 with open(filename, "rb", 0) as fp2: 284 fd2 = fp2.fileno() 285 self.assertTrue(self.pathmodule.sameopenfile(fd1, fd2)) 286 287 288class TestGenericTest(GenericTest, unittest.TestCase): 289 # Issue 16852: GenericTest can't inherit from unittest.TestCase 290 # for test discovery purposes; CommonTest inherits from GenericTest 291 # and is only meant to be inherited by others. 292 pathmodule = genericpath 293 294 def test_invalid_paths(self): 295 for attr in GenericTest.common_attributes: 296 # os.path.commonprefix doesn't raise ValueError 297 if attr == 'commonprefix': 298 continue 299 func = getattr(self.pathmodule, attr) 300 with self.subTest(attr=attr): 301 try: 302 func('/tmp\udfffabcds') 303 except (OSError, UnicodeEncodeError): 304 pass 305 try: 306 func(b'/tmp\xffabcds') 307 except (OSError, UnicodeDecodeError): 308 pass 309 with self.assertRaisesRegex(ValueError, 'embedded null'): 310 func('/tmp\x00abcds') 311 with self.assertRaisesRegex(ValueError, 'embedded null'): 312 func(b'/tmp\x00abcds') 313 314# Following TestCase is not supposed to be run from test_genericpath. 315# It is inherited by other test modules (macpath, ntpath, posixpath). 316 317class CommonTest(GenericTest): 318 common_attributes = GenericTest.common_attributes + [ 319 # Properties 320 'curdir', 'pardir', 'extsep', 'sep', 321 'pathsep', 'defpath', 'altsep', 'devnull', 322 # Methods 323 'normcase', 'splitdrive', 'expandvars', 'normpath', 'abspath', 324 'join', 'split', 'splitext', 'isabs', 'basename', 'dirname', 325 'lexists', 'islink', 'ismount', 'expanduser', 'normpath', 'realpath', 326 ] 327 328 def test_normcase(self): 329 normcase = self.pathmodule.normcase 330 # check that normcase() is idempotent 331 for p in ["FoO/./BaR", b"FoO/./BaR"]: 332 p = normcase(p) 333 self.assertEqual(p, normcase(p)) 334 335 self.assertEqual(normcase(''), '') 336 self.assertEqual(normcase(b''), b'') 337 338 # check that normcase raises a TypeError for invalid types 339 for path in (None, True, 0, 2.5, [], bytearray(b''), {'o','o'}): 340 self.assertRaises(TypeError, normcase, path) 341 342 def test_splitdrive(self): 343 # splitdrive for non-NT paths 344 splitdrive = self.pathmodule.splitdrive 345 self.assertEqual(splitdrive("/foo/bar"), ("", "/foo/bar")) 346 self.assertEqual(splitdrive("foo:bar"), ("", "foo:bar")) 347 self.assertEqual(splitdrive(":foo:bar"), ("", ":foo:bar")) 348 349 self.assertEqual(splitdrive(b"/foo/bar"), (b"", b"/foo/bar")) 350 self.assertEqual(splitdrive(b"foo:bar"), (b"", b"foo:bar")) 351 self.assertEqual(splitdrive(b":foo:bar"), (b"", b":foo:bar")) 352 353 def test_expandvars(self): 354 if self.pathmodule.__name__ == 'macpath': 355 self.skipTest('macpath.expandvars is a stub') 356 expandvars = self.pathmodule.expandvars 357 with support.EnvironmentVarGuard() as env: 358 env.clear() 359 env["foo"] = "bar" 360 env["{foo"] = "baz1" 361 env["{foo}"] = "baz2" 362 self.assertEqual(expandvars("foo"), "foo") 363 self.assertEqual(expandvars("$foo bar"), "bar bar") 364 self.assertEqual(expandvars("${foo}bar"), "barbar") 365 self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar") 366 self.assertEqual(expandvars("$bar bar"), "$bar bar") 367 self.assertEqual(expandvars("$?bar"), "$?bar") 368 self.assertEqual(expandvars("$foo}bar"), "bar}bar") 369 self.assertEqual(expandvars("${foo"), "${foo") 370 self.assertEqual(expandvars("${{foo}}"), "baz1}") 371 self.assertEqual(expandvars("$foo$foo"), "barbar") 372 self.assertEqual(expandvars("$bar$bar"), "$bar$bar") 373 374 self.assertEqual(expandvars(b"foo"), b"foo") 375 self.assertEqual(expandvars(b"$foo bar"), b"bar bar") 376 self.assertEqual(expandvars(b"${foo}bar"), b"barbar") 377 self.assertEqual(expandvars(b"$[foo]bar"), b"$[foo]bar") 378 self.assertEqual(expandvars(b"$bar bar"), b"$bar bar") 379 self.assertEqual(expandvars(b"$?bar"), b"$?bar") 380 self.assertEqual(expandvars(b"$foo}bar"), b"bar}bar") 381 self.assertEqual(expandvars(b"${foo"), b"${foo") 382 self.assertEqual(expandvars(b"${{foo}}"), b"baz1}") 383 self.assertEqual(expandvars(b"$foo$foo"), b"barbar") 384 self.assertEqual(expandvars(b"$bar$bar"), b"$bar$bar") 385 386 @unittest.skipUnless(support.FS_NONASCII, 'need support.FS_NONASCII') 387 def test_expandvars_nonascii(self): 388 if self.pathmodule.__name__ == 'macpath': 389 self.skipTest('macpath.expandvars is a stub') 390 expandvars = self.pathmodule.expandvars 391 def check(value, expected): 392 self.assertEqual(expandvars(value), expected) 393 with support.EnvironmentVarGuard() as env: 394 env.clear() 395 nonascii = support.FS_NONASCII 396 env['spam'] = nonascii 397 env[nonascii] = 'ham' + nonascii 398 check(nonascii, nonascii) 399 check('$spam bar', '%s bar' % nonascii) 400 check('${spam}bar', '%sbar' % nonascii) 401 check('${%s}bar' % nonascii, 'ham%sbar' % nonascii) 402 check('$bar%s bar' % nonascii, '$bar%s bar' % nonascii) 403 check('$spam}bar', '%s}bar' % nonascii) 404 405 check(os.fsencode(nonascii), os.fsencode(nonascii)) 406 check(b'$spam bar', os.fsencode('%s bar' % nonascii)) 407 check(b'${spam}bar', os.fsencode('%sbar' % nonascii)) 408 check(os.fsencode('${%s}bar' % nonascii), 409 os.fsencode('ham%sbar' % nonascii)) 410 check(os.fsencode('$bar%s bar' % nonascii), 411 os.fsencode('$bar%s bar' % nonascii)) 412 check(b'$spam}bar', os.fsencode('%s}bar' % nonascii)) 413 414 def test_abspath(self): 415 self.assertIn("foo", self.pathmodule.abspath("foo")) 416 with warnings.catch_warnings(): 417 warnings.simplefilter("ignore", DeprecationWarning) 418 self.assertIn(b"foo", self.pathmodule.abspath(b"foo")) 419 420 # avoid UnicodeDecodeError on Windows 421 undecodable_path = b'' if sys.platform == 'win32' else b'f\xf2\xf2' 422 423 # Abspath returns bytes when the arg is bytes 424 with warnings.catch_warnings(): 425 warnings.simplefilter("ignore", DeprecationWarning) 426 for path in (b'', b'foo', undecodable_path, b'/foo', b'C:\\'): 427 self.assertIsInstance(self.pathmodule.abspath(path), bytes) 428 429 def test_realpath(self): 430 self.assertIn("foo", self.pathmodule.realpath("foo")) 431 with warnings.catch_warnings(): 432 warnings.simplefilter("ignore", DeprecationWarning) 433 self.assertIn(b"foo", self.pathmodule.realpath(b"foo")) 434 435 def test_normpath_issue5827(self): 436 # Make sure normpath preserves unicode 437 for path in ('', '.', '/', '\\', '///foo/.//bar//'): 438 self.assertIsInstance(self.pathmodule.normpath(path), str) 439 440 def test_abspath_issue3426(self): 441 # Check that abspath returns unicode when the arg is unicode 442 # with both ASCII and non-ASCII cwds. 443 abspath = self.pathmodule.abspath 444 for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): 445 self.assertIsInstance(abspath(path), str) 446 447 unicwd = '\xe7w\xf0' 448 try: 449 os.fsencode(unicwd) 450 except (AttributeError, UnicodeEncodeError): 451 # FS encoding is probably ASCII 452 pass 453 else: 454 with support.temp_cwd(unicwd): 455 for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): 456 self.assertIsInstance(abspath(path), str) 457 458 def test_nonascii_abspath(self): 459 if (support.TESTFN_UNDECODABLE 460 # Mac OS X denies the creation of a directory with an invalid 461 # UTF-8 name. Windows allows creating a directory with an 462 # arbitrary bytes name, but fails to enter this directory 463 # (when the bytes name is used). 464 and sys.platform not in ('win32', 'darwin')): 465 name = support.TESTFN_UNDECODABLE 466 elif support.TESTFN_NONASCII: 467 name = support.TESTFN_NONASCII 468 else: 469 self.skipTest("need support.TESTFN_NONASCII") 470 471 with warnings.catch_warnings(): 472 warnings.simplefilter("ignore", DeprecationWarning) 473 with support.temp_cwd(name): 474 self.test_abspath() 475 476 def test_join_errors(self): 477 # Check join() raises friendly TypeErrors. 478 with support.check_warnings(('', BytesWarning), quiet=True): 479 errmsg = "Can't mix strings and bytes in path components" 480 with self.assertRaisesRegex(TypeError, errmsg): 481 self.pathmodule.join(b'bytes', 'str') 482 with self.assertRaisesRegex(TypeError, errmsg): 483 self.pathmodule.join('str', b'bytes') 484 # regression, see #15377 485 with self.assertRaisesRegex(TypeError, 'int'): 486 self.pathmodule.join(42, 'str') 487 with self.assertRaisesRegex(TypeError, 'int'): 488 self.pathmodule.join('str', 42) 489 with self.assertRaisesRegex(TypeError, 'int'): 490 self.pathmodule.join(42) 491 with self.assertRaisesRegex(TypeError, 'list'): 492 self.pathmodule.join([]) 493 with self.assertRaisesRegex(TypeError, 'bytearray'): 494 self.pathmodule.join(bytearray(b'foo'), bytearray(b'bar')) 495 496 def test_relpath_errors(self): 497 # Check relpath() raises friendly TypeErrors. 498 with support.check_warnings(('', (BytesWarning, DeprecationWarning)), 499 quiet=True): 500 errmsg = "Can't mix strings and bytes in path components" 501 with self.assertRaisesRegex(TypeError, errmsg): 502 self.pathmodule.relpath(b'bytes', 'str') 503 with self.assertRaisesRegex(TypeError, errmsg): 504 self.pathmodule.relpath('str', b'bytes') 505 with self.assertRaisesRegex(TypeError, 'int'): 506 self.pathmodule.relpath(42, 'str') 507 with self.assertRaisesRegex(TypeError, 'int'): 508 self.pathmodule.relpath('str', 42) 509 with self.assertRaisesRegex(TypeError, 'bytearray'): 510 self.pathmodule.relpath(bytearray(b'foo'), bytearray(b'bar')) 511 512 def test_import(self): 513 assert_python_ok('-S', '-c', 'import ' + self.pathmodule.__name__) 514 515 516class PathLikeTests(unittest.TestCase): 517 518 def setUp(self): 519 self.file_name = support.TESTFN.lower() 520 self.file_path = FakePath(support.TESTFN) 521 self.addCleanup(support.unlink, self.file_name) 522 create_file(self.file_name, b"test_genericpath.PathLikeTests") 523 524 def assertPathEqual(self, func): 525 self.assertEqual(func(self.file_path), func(self.file_name)) 526 527 def test_path_exists(self): 528 self.assertPathEqual(os.path.exists) 529 530 def test_path_isfile(self): 531 self.assertPathEqual(os.path.isfile) 532 533 def test_path_isdir(self): 534 self.assertPathEqual(os.path.isdir) 535 536 def test_path_commonprefix(self): 537 self.assertEqual(os.path.commonprefix([self.file_path, self.file_name]), 538 self.file_name) 539 540 def test_path_getsize(self): 541 self.assertPathEqual(os.path.getsize) 542 543 def test_path_getmtime(self): 544 self.assertPathEqual(os.path.getatime) 545 546 def test_path_getctime(self): 547 self.assertPathEqual(os.path.getctime) 548 549 def test_path_samefile(self): 550 self.assertTrue(os.path.samefile(self.file_path, self.file_name)) 551 552 553if __name__ == "__main__": 554 unittest.main() 555