PageRenderTime 40ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/SiRFLive/PythonStdLib/test/test_os.py

https://bitbucket.org/x893/sirflive
Python | 368 lines | 255 code | 51 blank | 62 comment | 43 complexity | 892e4271d6b192e6e2df2ab22c794f86 MD5 | raw file
  1. # As a test suite for the os module, this is woefully inadequate, but this
  2. # does add tests for a few functions which have been determined to be more
  3. # portable than they had been thought to be.
  4. import os
  5. import unittest
  6. import warnings
  7. from test import test_support
  8. warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
  9. warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
  10. class TemporaryFileTests(unittest.TestCase):
  11. def setUp(self):
  12. self.files = []
  13. os.mkdir(test_support.TESTFN)
  14. def tearDown(self):
  15. for name in self.files:
  16. os.unlink(name)
  17. os.rmdir(test_support.TESTFN)
  18. def check_tempfile(self, name):
  19. # make sure it doesn't already exist:
  20. self.failIf(os.path.exists(name),
  21. "file already exists for temporary file")
  22. # make sure we can create the file
  23. open(name, "w")
  24. self.files.append(name)
  25. def test_tempnam(self):
  26. if not hasattr(os, "tempnam"):
  27. return
  28. warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
  29. r"test_os$")
  30. self.check_tempfile(os.tempnam())
  31. name = os.tempnam(test_support.TESTFN)
  32. self.check_tempfile(name)
  33. name = os.tempnam(test_support.TESTFN, "pfx")
  34. self.assert_(os.path.basename(name)[:3] == "pfx")
  35. self.check_tempfile(name)
  36. def test_tmpfile(self):
  37. if not hasattr(os, "tmpfile"):
  38. return
  39. fp = os.tmpfile()
  40. fp.write("foobar")
  41. fp.seek(0,0)
  42. s = fp.read()
  43. fp.close()
  44. self.assert_(s == "foobar")
  45. def test_tmpnam(self):
  46. import sys
  47. if not hasattr(os, "tmpnam"):
  48. return
  49. warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
  50. r"test_os$")
  51. name = os.tmpnam()
  52. if sys.platform in ("win32",):
  53. # The Windows tmpnam() seems useless. From the MS docs:
  54. #
  55. # The character string that tmpnam creates consists of
  56. # the path prefix, defined by the entry P_tmpdir in the
  57. # file STDIO.H, followed by a sequence consisting of the
  58. # digit characters '0' through '9'; the numerical value
  59. # of this string is in the range 1 - 65,535. Changing the
  60. # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
  61. # change the operation of tmpnam.
  62. #
  63. # The really bizarre part is that, at least under MSVC6,
  64. # P_tmpdir is "\\". That is, the path returned refers to
  65. # the root of the current drive. That's a terrible place to
  66. # put temp files, and, depending on privileges, the user
  67. # may not even be able to open a file in the root directory.
  68. self.failIf(os.path.exists(name),
  69. "file already exists for temporary file")
  70. else:
  71. self.check_tempfile(name)
  72. # Test attributes on return values from os.*stat* family.
  73. class StatAttributeTests(unittest.TestCase):
  74. def setUp(self):
  75. os.mkdir(test_support.TESTFN)
  76. self.fname = os.path.join(test_support.TESTFN, "f1")
  77. f = open(self.fname, 'wb')
  78. f.write("ABC")
  79. f.close()
  80. def tearDown(self):
  81. os.unlink(self.fname)
  82. os.rmdir(test_support.TESTFN)
  83. def test_stat_attributes(self):
  84. if not hasattr(os, "stat"):
  85. return
  86. import stat
  87. result = os.stat(self.fname)
  88. # Make sure direct access works
  89. self.assertEquals(result[stat.ST_SIZE], 3)
  90. self.assertEquals(result.st_size, 3)
  91. import sys
  92. # Make sure all the attributes are there
  93. members = dir(result)
  94. for name in dir(stat):
  95. if name[:3] == 'ST_':
  96. attr = name.lower()
  97. self.assertEquals(getattr(result, attr),
  98. result[getattr(stat, name)])
  99. self.assert_(attr in members)
  100. try:
  101. result[200]
  102. self.fail("No exception thrown")
  103. except IndexError:
  104. pass
  105. # Make sure that assignment fails
  106. try:
  107. result.st_mode = 1
  108. self.fail("No exception thrown")
  109. except TypeError:
  110. pass
  111. try:
  112. result.st_rdev = 1
  113. self.fail("No exception thrown")
  114. except (AttributeError, TypeError):
  115. pass
  116. try:
  117. result.parrot = 1
  118. self.fail("No exception thrown")
  119. except AttributeError:
  120. pass
  121. # Use the stat_result constructor with a too-short tuple.
  122. try:
  123. result2 = os.stat_result((10,))
  124. self.fail("No exception thrown")
  125. except TypeError:
  126. pass
  127. # Use the constructr with a too-long tuple.
  128. try:
  129. result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  130. except TypeError:
  131. pass
  132. def test_statvfs_attributes(self):
  133. if not hasattr(os, "statvfs"):
  134. return
  135. import statvfs
  136. try:
  137. result = os.statvfs(self.fname)
  138. except OSError, e:
  139. # On AtheOS, glibc always returns ENOSYS
  140. import errno
  141. if e.errno == errno.ENOSYS:
  142. return
  143. # Make sure direct access works
  144. self.assertEquals(result.f_bfree, result[statvfs.F_BFREE])
  145. # Make sure all the attributes are there
  146. members = dir(result)
  147. for name in dir(statvfs):
  148. if name[:2] == 'F_':
  149. attr = name.lower()
  150. self.assertEquals(getattr(result, attr),
  151. result[getattr(statvfs, name)])
  152. self.assert_(attr in members)
  153. # Make sure that assignment really fails
  154. try:
  155. result.f_bfree = 1
  156. self.fail("No exception thrown")
  157. except TypeError:
  158. pass
  159. try:
  160. result.parrot = 1
  161. self.fail("No exception thrown")
  162. except AttributeError:
  163. pass
  164. # Use the constructor with a too-short tuple.
  165. try:
  166. result2 = os.statvfs_result((10,))
  167. self.fail("No exception thrown")
  168. except TypeError:
  169. pass
  170. # Use the constructr with a too-long tuple.
  171. try:
  172. result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  173. except TypeError:
  174. pass
  175. from test import mapping_tests
  176. class EnvironTests(mapping_tests.BasicTestMappingProtocol):
  177. """check that os.environ object conform to mapping protocol"""
  178. type2test = None
  179. def _reference(self):
  180. return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
  181. def _empty_mapping(self):
  182. os.environ.clear()
  183. return os.environ
  184. def setUp(self):
  185. self.__save = dict(os.environ)
  186. os.environ.clear()
  187. def tearDown(self):
  188. os.environ.clear()
  189. os.environ.update(self.__save)
  190. class WalkTests(unittest.TestCase):
  191. """Tests for os.walk()."""
  192. def test_traversal(self):
  193. import os
  194. from os.path import join
  195. # Build:
  196. # TESTFN/ a file kid and two directory kids
  197. # tmp1
  198. # SUB1/ a file kid and a directory kid
  199. # tmp2
  200. # SUB11/ no kids
  201. # SUB2/ just a file kid
  202. # tmp3
  203. sub1_path = join(test_support.TESTFN, "SUB1")
  204. sub11_path = join(sub1_path, "SUB11")
  205. sub2_path = join(test_support.TESTFN, "SUB2")
  206. tmp1_path = join(test_support.TESTFN, "tmp1")
  207. tmp2_path = join(sub1_path, "tmp2")
  208. tmp3_path = join(sub2_path, "tmp3")
  209. # Create stuff.
  210. os.makedirs(sub11_path)
  211. os.makedirs(sub2_path)
  212. for path in tmp1_path, tmp2_path, tmp3_path:
  213. f = file(path, "w")
  214. f.write("I'm " + path + " and proud of it. Blame test_os.\n")
  215. f.close()
  216. # Walk top-down.
  217. all = list(os.walk(test_support.TESTFN))
  218. self.assertEqual(len(all), 4)
  219. # We can't know which order SUB1 and SUB2 will appear in.
  220. # Not flipped: TESTFN, SUB1, SUB11, SUB2
  221. # flipped: TESTFN, SUB2, SUB1, SUB11
  222. flipped = all[0][1][0] != "SUB1"
  223. all[0][1].sort()
  224. self.assertEqual(all[0], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
  225. self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
  226. self.assertEqual(all[2 + flipped], (sub11_path, [], []))
  227. self.assertEqual(all[3 - 2 * flipped], (sub2_path, [], ["tmp3"]))
  228. # Prune the search.
  229. all = []
  230. for root, dirs, files in os.walk(test_support.TESTFN):
  231. all.append((root, dirs, files))
  232. # Don't descend into SUB1.
  233. if 'SUB1' in dirs:
  234. # Note that this also mutates the dirs we appended to all!
  235. dirs.remove('SUB1')
  236. self.assertEqual(len(all), 2)
  237. self.assertEqual(all[0], (test_support.TESTFN, ["SUB2"], ["tmp1"]))
  238. self.assertEqual(all[1], (sub2_path, [], ["tmp3"]))
  239. # Walk bottom-up.
  240. all = list(os.walk(test_support.TESTFN, topdown=False))
  241. self.assertEqual(len(all), 4)
  242. # We can't know which order SUB1 and SUB2 will appear in.
  243. # Not flipped: SUB11, SUB1, SUB2, TESTFN
  244. # flipped: SUB2, SUB11, SUB1, TESTFN
  245. flipped = all[3][1][0] != "SUB1"
  246. all[3][1].sort()
  247. self.assertEqual(all[3], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
  248. self.assertEqual(all[flipped], (sub11_path, [], []))
  249. self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
  250. self.assertEqual(all[2 - 2 * flipped], (sub2_path, [], ["tmp3"]))
  251. # Tear everything down. This is a decent use for bottom-up on
  252. # Windows, which doesn't have a recursive delete command. The
  253. # (not so) subtlety is that rmdir will fail unless the dir's
  254. # kids are removed first, so bottom up is essential.
  255. for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
  256. for name in files:
  257. os.remove(join(root, name))
  258. for name in dirs:
  259. os.rmdir(join(root, name))
  260. os.rmdir(test_support.TESTFN)
  261. class MakedirTests (unittest.TestCase):
  262. def setUp(self):
  263. os.mkdir(test_support.TESTFN)
  264. def test_makedir(self):
  265. base = test_support.TESTFN
  266. path = os.path.join(base, 'dir1', 'dir2', 'dir3')
  267. os.makedirs(path) # Should work
  268. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
  269. os.makedirs(path)
  270. # Try paths with a '.' in them
  271. self.failUnlessRaises(OSError, os.makedirs, os.curdir)
  272. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
  273. os.makedirs(path)
  274. path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
  275. 'dir5', 'dir6')
  276. os.makedirs(path)
  277. def tearDown(self):
  278. path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
  279. 'dir4', 'dir5', 'dir6')
  280. # If the tests failed, the bottom-most directory ('../dir6')
  281. # may not have been created, so we look for the outermost directory
  282. # that exists.
  283. while not os.path.exists(path) and path != test_support.TESTFN:
  284. path = os.path.dirname(path)
  285. os.removedirs(path)
  286. class DevNullTests (unittest.TestCase):
  287. def test_devnull(self):
  288. f = file(os.devnull, 'w')
  289. f.write('hello')
  290. f.close()
  291. f = file(os.devnull, 'r')
  292. self.assertEqual(f.read(), '')
  293. f.close()
  294. class URandomTests (unittest.TestCase):
  295. def test_urandom(self):
  296. try:
  297. self.assertEqual(len(os.urandom(1)), 1)
  298. self.assertEqual(len(os.urandom(10)), 10)
  299. self.assertEqual(len(os.urandom(100)), 100)
  300. self.assertEqual(len(os.urandom(1000)), 1000)
  301. except NotImplementedError:
  302. pass
  303. def test_main():
  304. test_support.run_unittest(
  305. TemporaryFileTests,
  306. StatAttributeTests,
  307. EnvironTests,
  308. WalkTests,
  309. MakedirTests,
  310. DevNullTests,
  311. URandomTests
  312. )
  313. if __name__ == "__main__":
  314. test_main()