test_genericpath.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. """
  2. Tests common to genericpath, macpath, ntpath and posixpath
  3. """
  4. import unittest
  5. from test import test_support
  6. import os
  7. import genericpath
  8. import sys
  9. def safe_rmdir(dirname):
  10. try:
  11. os.rmdir(dirname)
  12. except OSError:
  13. pass
  14. class GenericTest(unittest.TestCase):
  15. # The path module to be tested
  16. pathmodule = genericpath
  17. common_attributes = ['commonprefix', 'getsize', 'getatime', 'getctime',
  18. 'getmtime', 'exists', 'isdir', 'isfile']
  19. attributes = []
  20. def test_no_argument(self):
  21. for attr in self.common_attributes + self.attributes:
  22. with self.assertRaises(TypeError):
  23. getattr(self.pathmodule, attr)()
  24. raise self.fail("{}.{}() did not raise a TypeError"
  25. .format(self.pathmodule.__name__, attr))
  26. def test_commonprefix(self):
  27. commonprefix = self.pathmodule.commonprefix
  28. self.assertEqual(
  29. commonprefix([]),
  30. ""
  31. )
  32. self.assertEqual(
  33. commonprefix(["/home/swenson/spam", "/home/swen/spam"]),
  34. "/home/swen"
  35. )
  36. self.assertEqual(
  37. commonprefix(["/home/swen/spam", "/home/swen/eggs"]),
  38. "/home/swen/"
  39. )
  40. self.assertEqual(
  41. commonprefix(["/home/swen/spam", "/home/swen/spam"]),
  42. "/home/swen/spam"
  43. )
  44. self.assertEqual(
  45. commonprefix(["home:swenson:spam", "home:swen:spam"]),
  46. "home:swen"
  47. )
  48. self.assertEqual(
  49. commonprefix([":home:swen:spam", ":home:swen:eggs"]),
  50. ":home:swen:"
  51. )
  52. self.assertEqual(
  53. commonprefix([":home:swen:spam", ":home:swen:spam"]),
  54. ":home:swen:spam"
  55. )
  56. testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd',
  57. 'aXc', 'abd', 'ab', 'aX', 'abcX']
  58. for s1 in testlist:
  59. for s2 in testlist:
  60. p = commonprefix([s1, s2])
  61. self.assertTrue(s1.startswith(p))
  62. self.assertTrue(s2.startswith(p))
  63. if s1 != s2:
  64. n = len(p)
  65. self.assertNotEqual(s1[n:n+1], s2[n:n+1])
  66. def test_getsize(self):
  67. f = open(test_support.TESTFN, "wb")
  68. try:
  69. f.write("foo")
  70. f.close()
  71. self.assertEqual(self.pathmodule.getsize(test_support.TESTFN), 3)
  72. finally:
  73. if not f.closed:
  74. f.close()
  75. test_support.unlink(test_support.TESTFN)
  76. def test_time(self):
  77. f = open(test_support.TESTFN, "wb")
  78. try:
  79. f.write("foo")
  80. f.close()
  81. f = open(test_support.TESTFN, "ab")
  82. f.write("bar")
  83. f.close()
  84. f = open(test_support.TESTFN, "rb")
  85. d = f.read()
  86. f.close()
  87. self.assertEqual(d, "foobar")
  88. self.assertLessEqual(
  89. self.pathmodule.getctime(test_support.TESTFN),
  90. self.pathmodule.getmtime(test_support.TESTFN)
  91. )
  92. finally:
  93. if not f.closed:
  94. f.close()
  95. test_support.unlink(test_support.TESTFN)
  96. def test_exists(self):
  97. self.assertIs(self.pathmodule.exists(test_support.TESTFN), False)
  98. f = open(test_support.TESTFN, "wb")
  99. try:
  100. f.write("foo")
  101. f.close()
  102. self.assertIs(self.pathmodule.exists(test_support.TESTFN), True)
  103. if not self.pathmodule == genericpath:
  104. self.assertIs(self.pathmodule.lexists(test_support.TESTFN),
  105. True)
  106. finally:
  107. if not f.close():
  108. f.close()
  109. test_support.unlink(test_support.TESTFN)
  110. def test_isdir(self):
  111. self.assertIs(self.pathmodule.isdir(test_support.TESTFN), False)
  112. f = open(test_support.TESTFN, "wb")
  113. try:
  114. f.write("foo")
  115. f.close()
  116. self.assertIs(self.pathmodule.isdir(test_support.TESTFN), False)
  117. os.remove(test_support.TESTFN)
  118. os.mkdir(test_support.TESTFN)
  119. self.assertIs(self.pathmodule.isdir(test_support.TESTFN), True)
  120. os.rmdir(test_support.TESTFN)
  121. finally:
  122. if not f.close():
  123. f.close()
  124. test_support.unlink(test_support.TESTFN)
  125. safe_rmdir(test_support.TESTFN)
  126. def test_isfile(self):
  127. self.assertIs(self.pathmodule.isfile(test_support.TESTFN), False)
  128. f = open(test_support.TESTFN, "wb")
  129. try:
  130. f.write("foo")
  131. f.close()
  132. self.assertIs(self.pathmodule.isfile(test_support.TESTFN), True)
  133. os.remove(test_support.TESTFN)
  134. os.mkdir(test_support.TESTFN)
  135. self.assertIs(self.pathmodule.isfile(test_support.TESTFN), False)
  136. os.rmdir(test_support.TESTFN)
  137. finally:
  138. if not f.close():
  139. f.close()
  140. test_support.unlink(test_support.TESTFN)
  141. safe_rmdir(test_support.TESTFN)
  142. # Following TestCase is not supposed to be run from test_genericpath.
  143. # It is inherited by other test modules (macpath, ntpath, posixpath).
  144. class CommonTest(GenericTest):
  145. # The path module to be tested
  146. pathmodule = None
  147. common_attributes = GenericTest.common_attributes + [
  148. # Properties
  149. 'curdir', 'pardir', 'extsep', 'sep',
  150. 'pathsep', 'defpath', 'altsep', 'devnull',
  151. # Methods
  152. 'normcase', 'splitdrive', 'expandvars', 'normpath', 'abspath',
  153. 'join', 'split', 'splitext', 'isabs', 'basename', 'dirname',
  154. 'lexists', 'islink', 'ismount', 'expanduser', 'normpath', 'realpath',
  155. ]
  156. def test_normcase(self):
  157. # Check that normcase() is idempotent
  158. p = "FoO/./BaR"
  159. p = self.pathmodule.normcase(p)
  160. self.assertEqual(p, self.pathmodule.normcase(p))
  161. def test_splitdrive(self):
  162. # splitdrive for non-NT paths
  163. splitdrive = self.pathmodule.splitdrive
  164. self.assertEqual(splitdrive("/foo/bar"), ("", "/foo/bar"))
  165. self.assertEqual(splitdrive("foo:bar"), ("", "foo:bar"))
  166. self.assertEqual(splitdrive(":foo:bar"), ("", ":foo:bar"))
  167. def test_expandvars(self):
  168. if self.pathmodule.__name__ == 'macpath':
  169. self.skipTest('macpath.expandvars is a stub')
  170. expandvars = self.pathmodule.expandvars
  171. with test_support.EnvironmentVarGuard() as env:
  172. env.clear()
  173. env["foo"] = "bar"
  174. env["{foo"] = "baz1"
  175. env["{foo}"] = "baz2"
  176. self.assertEqual(expandvars("foo"), "foo")
  177. self.assertEqual(expandvars("$foo bar"), "bar bar")
  178. self.assertEqual(expandvars("${foo}bar"), "barbar")
  179. self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar")
  180. self.assertEqual(expandvars("$bar bar"), "$bar bar")
  181. self.assertEqual(expandvars("$?bar"), "$?bar")
  182. self.assertEqual(expandvars("$foo}bar"), "bar}bar")
  183. self.assertEqual(expandvars("${foo"), "${foo")
  184. self.assertEqual(expandvars("${{foo}}"), "baz1}")
  185. self.assertEqual(expandvars("$foo$foo"), "barbar")
  186. self.assertEqual(expandvars("$bar$bar"), "$bar$bar")
  187. @unittest.skipUnless(test_support.FS_NONASCII, 'need test_support.FS_NONASCII')
  188. def test_expandvars_nonascii(self):
  189. if self.pathmodule.__name__ == 'macpath':
  190. self.skipTest('macpath.expandvars is a stub')
  191. expandvars = self.pathmodule.expandvars
  192. def check(value, expected):
  193. self.assertEqual(expandvars(value), expected)
  194. encoding = sys.getfilesystemencoding()
  195. with test_support.EnvironmentVarGuard() as env:
  196. env.clear()
  197. unonascii = test_support.FS_NONASCII
  198. snonascii = unonascii.encode(encoding)
  199. env['spam'] = snonascii
  200. env[snonascii] = 'ham' + snonascii
  201. check(snonascii, snonascii)
  202. check('$spam bar', '%s bar' % snonascii)
  203. check('${spam}bar', '%sbar' % snonascii)
  204. check('${%s}bar' % snonascii, 'ham%sbar' % snonascii)
  205. check('$bar%s bar' % snonascii, '$bar%s bar' % snonascii)
  206. check('$spam}bar', '%s}bar' % snonascii)
  207. check(unonascii, unonascii)
  208. check(u'$spam bar', u'%s bar' % unonascii)
  209. check(u'${spam}bar', u'%sbar' % unonascii)
  210. check(u'${%s}bar' % unonascii, u'ham%sbar' % unonascii)
  211. check(u'$bar%s bar' % unonascii, u'$bar%s bar' % unonascii)
  212. check(u'$spam}bar', u'%s}bar' % unonascii)
  213. def test_abspath(self):
  214. self.assertIn("foo", self.pathmodule.abspath("foo"))
  215. # Abspath returns bytes when the arg is bytes
  216. for path in ('', 'foo', 'f\xf2\xf2', '/foo', 'C:\\'):
  217. self.assertIsInstance(self.pathmodule.abspath(path), str)
  218. def test_realpath(self):
  219. self.assertIn("foo", self.pathmodule.realpath("foo"))
  220. @test_support.requires_unicode
  221. def test_normpath_issue5827(self):
  222. # Make sure normpath preserves unicode
  223. for path in (u'', u'.', u'/', u'\\', u'///foo/.//bar//'):
  224. self.assertIsInstance(self.pathmodule.normpath(path), unicode)
  225. @test_support.requires_unicode
  226. def test_abspath_issue3426(self):
  227. # Check that abspath returns unicode when the arg is unicode
  228. # with both ASCII and non-ASCII cwds.
  229. abspath = self.pathmodule.abspath
  230. for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
  231. self.assertIsInstance(abspath(path), unicode)
  232. unicwd = u'\xe7w\xf0'
  233. try:
  234. fsencoding = test_support.TESTFN_ENCODING or "ascii"
  235. unicwd.encode(fsencoding)
  236. except (AttributeError, UnicodeEncodeError):
  237. # FS encoding is probably ASCII
  238. pass
  239. else:
  240. with test_support.temp_cwd(unicwd):
  241. for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
  242. self.assertIsInstance(abspath(path), unicode)
  243. @unittest.skipIf(sys.platform == 'darwin',
  244. "Mac OS X denies the creation of a directory with an invalid utf8 name")
  245. def test_nonascii_abspath(self):
  246. # Test non-ASCII, non-UTF8 bytes in the path.
  247. with test_support.temp_cwd('\xe7w\xf0'):
  248. self.test_abspath()
  249. def test_main():
  250. test_support.run_unittest(GenericTest)
  251. if __name__=="__main__":
  252. test_main()