PageRenderTime 68ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/test/test_os.py

https://bitbucket.org/dac_io/pypy
Python | 824 lines | 600 code | 98 blank | 126 comment | 119 complexity | 754d0cbd072c564d756c62b902deb182 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 errno
  6. import unittest
  7. import warnings
  8. import sys
  9. import signal
  10. import subprocess
  11. import time
  12. from test import test_support
  13. import mmap
  14. import uuid
  15. warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
  16. warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
  17. # Tests creating TESTFN
  18. class FileTests(unittest.TestCase):
  19. def setUp(self):
  20. if os.path.exists(test_support.TESTFN):
  21. os.unlink(test_support.TESTFN)
  22. tearDown = setUp
  23. def test_access(self):
  24. f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
  25. os.close(f)
  26. self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
  27. def test_closerange(self):
  28. first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
  29. # We must allocate two consecutive file descriptors, otherwise
  30. # it will mess up other file descriptors (perhaps even the three
  31. # standard ones).
  32. second = os.dup(first)
  33. try:
  34. retries = 0
  35. while second != first + 1:
  36. os.close(first)
  37. retries += 1
  38. if retries > 10:
  39. # XXX test skipped
  40. self.skipTest("couldn't allocate two consecutive fds")
  41. first, second = second, os.dup(second)
  42. finally:
  43. os.close(second)
  44. # close a fd that is open, and one that isn't
  45. os.closerange(first, first + 2)
  46. self.assertRaises(OSError, os.write, first, "a")
  47. @test_support.cpython_only
  48. def test_rename(self):
  49. path = unicode(test_support.TESTFN)
  50. old = sys.getrefcount(path)
  51. self.assertRaises(TypeError, os.rename, path, 0)
  52. new = sys.getrefcount(path)
  53. self.assertEqual(old, new)
  54. class TemporaryFileTests(unittest.TestCase):
  55. def setUp(self):
  56. self.files = []
  57. os.mkdir(test_support.TESTFN)
  58. def tearDown(self):
  59. for name in self.files:
  60. os.unlink(name)
  61. os.rmdir(test_support.TESTFN)
  62. def check_tempfile(self, name):
  63. # make sure it doesn't already exist:
  64. self.assertFalse(os.path.exists(name),
  65. "file already exists for temporary file")
  66. # make sure we can create the file
  67. open(name, "w")
  68. self.files.append(name)
  69. def test_tempnam(self):
  70. if not hasattr(os, "tempnam"):
  71. return
  72. with warnings.catch_warnings():
  73. warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
  74. r"test_os$")
  75. warnings.filterwarnings("ignore", "tempnam", DeprecationWarning)
  76. self.check_tempfile(os.tempnam())
  77. name = os.tempnam(test_support.TESTFN)
  78. self.check_tempfile(name)
  79. name = os.tempnam(test_support.TESTFN, "pfx")
  80. self.assertTrue(os.path.basename(name)[:3] == "pfx")
  81. self.check_tempfile(name)
  82. def test_tmpfile(self):
  83. if not hasattr(os, "tmpfile"):
  84. return
  85. # As with test_tmpnam() below, the Windows implementation of tmpfile()
  86. # attempts to create a file in the root directory of the current drive.
  87. # On Vista and Server 2008, this test will always fail for normal users
  88. # as writing to the root directory requires elevated privileges. With
  89. # XP and below, the semantics of tmpfile() are the same, but the user
  90. # running the test is more likely to have administrative privileges on
  91. # their account already. If that's the case, then os.tmpfile() should
  92. # work. In order to make this test as useful as possible, rather than
  93. # trying to detect Windows versions or whether or not the user has the
  94. # right permissions, just try and create a file in the root directory
  95. # and see if it raises a 'Permission denied' OSError. If it does, then
  96. # test that a subsequent call to os.tmpfile() raises the same error. If
  97. # it doesn't, assume we're on XP or below and the user running the test
  98. # has administrative privileges, and proceed with the test as normal.
  99. with warnings.catch_warnings():
  100. warnings.filterwarnings("ignore", "tmpfile", DeprecationWarning)
  101. if sys.platform == 'win32':
  102. name = '\\python_test_os_test_tmpfile.txt'
  103. if os.path.exists(name):
  104. os.remove(name)
  105. try:
  106. fp = open(name, 'w')
  107. except IOError, first:
  108. # open() failed, assert tmpfile() fails in the same way.
  109. # Although open() raises an IOError and os.tmpfile() raises an
  110. # OSError(), 'args' will be (13, 'Permission denied') in both
  111. # cases.
  112. try:
  113. fp = os.tmpfile()
  114. except OSError, second:
  115. self.assertEqual(first.args, second.args)
  116. else:
  117. self.fail("expected os.tmpfile() to raise OSError")
  118. return
  119. else:
  120. # open() worked, therefore, tmpfile() should work. Close our
  121. # dummy file and proceed with the test as normal.
  122. fp.close()
  123. os.remove(name)
  124. fp = os.tmpfile()
  125. fp.write("foobar")
  126. fp.seek(0,0)
  127. s = fp.read()
  128. fp.close()
  129. self.assertTrue(s == "foobar")
  130. def test_tmpnam(self):
  131. if not hasattr(os, "tmpnam"):
  132. return
  133. with warnings.catch_warnings():
  134. warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
  135. r"test_os$")
  136. warnings.filterwarnings("ignore", "tmpnam", DeprecationWarning)
  137. name = os.tmpnam()
  138. if sys.platform in ("win32",):
  139. # The Windows tmpnam() seems useless. From the MS docs:
  140. #
  141. # The character string that tmpnam creates consists of
  142. # the path prefix, defined by the entry P_tmpdir in the
  143. # file STDIO.H, followed by a sequence consisting of the
  144. # digit characters '0' through '9'; the numerical value
  145. # of this string is in the range 1 - 65,535. Changing the
  146. # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
  147. # change the operation of tmpnam.
  148. #
  149. # The really bizarre part is that, at least under MSVC6,
  150. # P_tmpdir is "\\". That is, the path returned refers to
  151. # the root of the current drive. That's a terrible place to
  152. # put temp files, and, depending on privileges, the user
  153. # may not even be able to open a file in the root directory.
  154. self.assertFalse(os.path.exists(name),
  155. "file already exists for temporary file")
  156. else:
  157. self.check_tempfile(name)
  158. # Test attributes on return values from os.*stat* family.
  159. class StatAttributeTests(unittest.TestCase):
  160. def setUp(self):
  161. os.mkdir(test_support.TESTFN)
  162. self.fname = os.path.join(test_support.TESTFN, "f1")
  163. f = open(self.fname, 'wb')
  164. f.write("ABC")
  165. f.close()
  166. def tearDown(self):
  167. os.unlink(self.fname)
  168. os.rmdir(test_support.TESTFN)
  169. def test_stat_attributes(self):
  170. if not hasattr(os, "stat"):
  171. return
  172. import stat
  173. result = os.stat(self.fname)
  174. # Make sure direct access works
  175. self.assertEqual(result[stat.ST_SIZE], 3)
  176. self.assertEqual(result.st_size, 3)
  177. # Make sure all the attributes are there
  178. members = dir(result)
  179. for name in dir(stat):
  180. if name[:3] == 'ST_':
  181. attr = name.lower()
  182. if name.endswith("TIME"):
  183. def trunc(x): return int(x)
  184. else:
  185. def trunc(x): return x
  186. self.assertEqual(trunc(getattr(result, attr)),
  187. result[getattr(stat, name)])
  188. self.assertIn(attr, members)
  189. try:
  190. result[200]
  191. self.fail("No exception thrown")
  192. except IndexError:
  193. pass
  194. # Make sure that assignment fails
  195. try:
  196. result.st_mode = 1
  197. self.fail("No exception thrown")
  198. except (AttributeError, TypeError):
  199. pass
  200. try:
  201. result.st_rdev = 1
  202. self.fail("No exception thrown")
  203. except (AttributeError, TypeError):
  204. pass
  205. try:
  206. result.parrot = 1
  207. self.fail("No exception thrown")
  208. except AttributeError:
  209. pass
  210. # Use the stat_result constructor with a too-short tuple.
  211. try:
  212. result2 = os.stat_result((10,))
  213. self.fail("No exception thrown")
  214. except TypeError:
  215. pass
  216. # Use the constructor with a too-long tuple.
  217. try:
  218. result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  219. except TypeError:
  220. pass
  221. def test_statvfs_attributes(self):
  222. if not hasattr(os, "statvfs"):
  223. return
  224. try:
  225. result = os.statvfs(self.fname)
  226. except OSError, e:
  227. # On AtheOS, glibc always returns ENOSYS
  228. if e.errno == errno.ENOSYS:
  229. return
  230. # Make sure direct access works
  231. self.assertEqual(result.f_bfree, result[3])
  232. # Make sure all the attributes are there.
  233. members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
  234. 'ffree', 'favail', 'flag', 'namemax')
  235. for value, member in enumerate(members):
  236. self.assertEqual(getattr(result, 'f_' + member), result[value])
  237. # Make sure that assignment really fails
  238. try:
  239. result.f_bfree = 1
  240. self.fail("No exception thrown")
  241. except TypeError:
  242. pass
  243. try:
  244. result.parrot = 1
  245. self.fail("No exception thrown")
  246. except AttributeError:
  247. pass
  248. # Use the constructor with a too-short tuple.
  249. try:
  250. result2 = os.statvfs_result((10,))
  251. self.fail("No exception thrown")
  252. except TypeError:
  253. pass
  254. # Use the constructor with a too-long tuple.
  255. try:
  256. result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  257. except TypeError:
  258. pass
  259. def test_utime_dir(self):
  260. delta = 1000000
  261. st = os.stat(test_support.TESTFN)
  262. # round to int, because some systems may support sub-second
  263. # time stamps in stat, but not in utime.
  264. os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
  265. st2 = os.stat(test_support.TESTFN)
  266. self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
  267. # Restrict test to Win32, since there is no guarantee other
  268. # systems support centiseconds
  269. if sys.platform == 'win32':
  270. def get_file_system(path):
  271. root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
  272. import ctypes
  273. kernel32 = ctypes.windll.kernel32
  274. buf = ctypes.create_string_buffer("", 100)
  275. if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
  276. return buf.value
  277. if get_file_system(test_support.TESTFN) == "NTFS":
  278. def test_1565150(self):
  279. t1 = 1159195039.25
  280. os.utime(self.fname, (t1, t1))
  281. self.assertEqual(os.stat(self.fname).st_mtime, t1)
  282. def test_large_time(self):
  283. t1 = 5000000000 # some day in 2128
  284. os.utime(self.fname, (t1, t1))
  285. self.assertEqual(os.stat(self.fname).st_mtime, t1)
  286. def test_1686475(self):
  287. # Verify that an open file can be stat'ed
  288. try:
  289. os.stat(r"c:\pagefile.sys")
  290. except WindowsError, e:
  291. if e.errno == 2: # file does not exist; cannot run test
  292. return
  293. self.fail("Could not stat pagefile.sys")
  294. from test import mapping_tests
  295. class EnvironTests(mapping_tests.BasicTestMappingProtocol):
  296. """check that os.environ object conform to mapping protocol"""
  297. type2test = None
  298. def _reference(self):
  299. return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
  300. def _empty_mapping(self):
  301. os.environ.clear()
  302. return os.environ
  303. def setUp(self):
  304. self.__save = dict(os.environ)
  305. os.environ.clear()
  306. def tearDown(self):
  307. os.environ.clear()
  308. os.environ.update(self.__save)
  309. # Bug 1110478
  310. def test_update2(self):
  311. if os.path.exists("/bin/sh"):
  312. os.environ.update(HELLO="World")
  313. with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
  314. value = popen.read().strip()
  315. self.assertEqual(value, "World")
  316. class WalkTests(unittest.TestCase):
  317. """Tests for os.walk()."""
  318. def test_traversal(self):
  319. import os
  320. from os.path import join
  321. # Build:
  322. # TESTFN/
  323. # TEST1/ a file kid and two directory kids
  324. # tmp1
  325. # SUB1/ a file kid and a directory kid
  326. # tmp2
  327. # SUB11/ no kids
  328. # SUB2/ a file kid and a dirsymlink kid
  329. # tmp3
  330. # link/ a symlink to TESTFN.2
  331. # TEST2/
  332. # tmp4 a lone file
  333. walk_path = join(test_support.TESTFN, "TEST1")
  334. sub1_path = join(walk_path, "SUB1")
  335. sub11_path = join(sub1_path, "SUB11")
  336. sub2_path = join(walk_path, "SUB2")
  337. tmp1_path = join(walk_path, "tmp1")
  338. tmp2_path = join(sub1_path, "tmp2")
  339. tmp3_path = join(sub2_path, "tmp3")
  340. link_path = join(sub2_path, "link")
  341. t2_path = join(test_support.TESTFN, "TEST2")
  342. tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
  343. # Create stuff.
  344. os.makedirs(sub11_path)
  345. os.makedirs(sub2_path)
  346. os.makedirs(t2_path)
  347. for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
  348. f = file(path, "w")
  349. f.write("I'm " + path + " and proud of it. Blame test_os.\n")
  350. f.close()
  351. if hasattr(os, "symlink"):
  352. os.symlink(os.path.abspath(t2_path), link_path)
  353. sub2_tree = (sub2_path, ["link"], ["tmp3"])
  354. else:
  355. sub2_tree = (sub2_path, [], ["tmp3"])
  356. # Walk top-down.
  357. all = list(os.walk(walk_path))
  358. self.assertEqual(len(all), 4)
  359. # We can't know which order SUB1 and SUB2 will appear in.
  360. # Not flipped: TESTFN, SUB1, SUB11, SUB2
  361. # flipped: TESTFN, SUB2, SUB1, SUB11
  362. flipped = all[0][1][0] != "SUB1"
  363. all[0][1].sort()
  364. self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
  365. self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
  366. self.assertEqual(all[2 + flipped], (sub11_path, [], []))
  367. self.assertEqual(all[3 - 2 * flipped], sub2_tree)
  368. # Prune the search.
  369. all = []
  370. for root, dirs, files in os.walk(walk_path):
  371. all.append((root, dirs, files))
  372. # Don't descend into SUB1.
  373. if 'SUB1' in dirs:
  374. # Note that this also mutates the dirs we appended to all!
  375. dirs.remove('SUB1')
  376. self.assertEqual(len(all), 2)
  377. self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
  378. self.assertEqual(all[1], sub2_tree)
  379. # Walk bottom-up.
  380. all = list(os.walk(walk_path, topdown=False))
  381. self.assertEqual(len(all), 4)
  382. # We can't know which order SUB1 and SUB2 will appear in.
  383. # Not flipped: SUB11, SUB1, SUB2, TESTFN
  384. # flipped: SUB2, SUB11, SUB1, TESTFN
  385. flipped = all[3][1][0] != "SUB1"
  386. all[3][1].sort()
  387. self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
  388. self.assertEqual(all[flipped], (sub11_path, [], []))
  389. self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
  390. self.assertEqual(all[2 - 2 * flipped], sub2_tree)
  391. if hasattr(os, "symlink"):
  392. # Walk, following symlinks.
  393. for root, dirs, files in os.walk(walk_path, followlinks=True):
  394. if root == link_path:
  395. self.assertEqual(dirs, [])
  396. self.assertEqual(files, ["tmp4"])
  397. break
  398. else:
  399. self.fail("Didn't follow symlink with followlinks=True")
  400. def tearDown(self):
  401. # Tear everything down. This is a decent use for bottom-up on
  402. # Windows, which doesn't have a recursive delete command. The
  403. # (not so) subtlety is that rmdir will fail unless the dir's
  404. # kids are removed first, so bottom up is essential.
  405. for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
  406. for name in files:
  407. os.remove(os.path.join(root, name))
  408. for name in dirs:
  409. dirname = os.path.join(root, name)
  410. if not os.path.islink(dirname):
  411. os.rmdir(dirname)
  412. else:
  413. os.remove(dirname)
  414. os.rmdir(test_support.TESTFN)
  415. class MakedirTests (unittest.TestCase):
  416. def setUp(self):
  417. os.mkdir(test_support.TESTFN)
  418. def test_makedir(self):
  419. base = test_support.TESTFN
  420. path = os.path.join(base, 'dir1', 'dir2', 'dir3')
  421. os.makedirs(path) # Should work
  422. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
  423. os.makedirs(path)
  424. # Try paths with a '.' in them
  425. self.assertRaises(OSError, os.makedirs, os.curdir)
  426. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
  427. os.makedirs(path)
  428. path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
  429. 'dir5', 'dir6')
  430. os.makedirs(path)
  431. def tearDown(self):
  432. path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
  433. 'dir4', 'dir5', 'dir6')
  434. # If the tests failed, the bottom-most directory ('../dir6')
  435. # may not have been created, so we look for the outermost directory
  436. # that exists.
  437. while not os.path.exists(path) and path != test_support.TESTFN:
  438. path = os.path.dirname(path)
  439. os.removedirs(path)
  440. class DevNullTests (unittest.TestCase):
  441. def test_devnull(self):
  442. f = file(os.devnull, 'w')
  443. f.write('hello')
  444. f.close()
  445. f = file(os.devnull, 'r')
  446. self.assertEqual(f.read(), '')
  447. f.close()
  448. class URandomTests (unittest.TestCase):
  449. def test_urandom(self):
  450. try:
  451. self.assertEqual(len(os.urandom(1)), 1)
  452. self.assertEqual(len(os.urandom(10)), 10)
  453. self.assertEqual(len(os.urandom(100)), 100)
  454. self.assertEqual(len(os.urandom(1000)), 1000)
  455. # see http://bugs.python.org/issue3708
  456. self.assertRaises(TypeError, os.urandom, 0.9)
  457. self.assertRaises(TypeError, os.urandom, 1.1)
  458. self.assertRaises(TypeError, os.urandom, 2.0)
  459. except NotImplementedError:
  460. pass
  461. def test_execvpe_with_bad_arglist(self):
  462. self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
  463. class Win32ErrorTests(unittest.TestCase):
  464. def test_rename(self):
  465. self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
  466. def test_remove(self):
  467. self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
  468. def test_chdir(self):
  469. self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
  470. def test_mkdir(self):
  471. f = open(test_support.TESTFN, "w")
  472. try:
  473. self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
  474. finally:
  475. f.close()
  476. os.unlink(test_support.TESTFN)
  477. def test_utime(self):
  478. self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
  479. def test_chmod(self):
  480. self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
  481. class TestInvalidFD(unittest.TestCase):
  482. singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
  483. "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
  484. #singles.append("close")
  485. #We omit close because it doesn'r raise an exception on some platforms
  486. def get_single(f):
  487. def helper(self):
  488. if hasattr(os, f):
  489. self.check(getattr(os, f))
  490. return helper
  491. for f in singles:
  492. locals()["test_"+f] = get_single(f)
  493. def check(self, f, *args):
  494. try:
  495. f(test_support.make_bad_fd(), *args)
  496. except OSError as e:
  497. self.assertEqual(e.errno, errno.EBADF)
  498. else:
  499. self.fail("%r didn't raise a OSError with a bad file descriptor"
  500. % f)
  501. def test_isatty(self):
  502. if hasattr(os, "isatty"):
  503. self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
  504. def test_closerange(self):
  505. if hasattr(os, "closerange"):
  506. fd = test_support.make_bad_fd()
  507. # Make sure none of the descriptors we are about to close are
  508. # currently valid (issue 6542).
  509. for i in range(10):
  510. try: os.fstat(fd+i)
  511. except OSError:
  512. pass
  513. else:
  514. break
  515. if i < 2:
  516. raise unittest.SkipTest(
  517. "Unable to acquire a range of invalid file descriptors")
  518. self.assertEqual(os.closerange(fd, fd + i-1), None)
  519. def test_dup2(self):
  520. if hasattr(os, "dup2"):
  521. self.check(os.dup2, 20)
  522. def test_fchmod(self):
  523. if hasattr(os, "fchmod"):
  524. self.check(os.fchmod, 0)
  525. def test_fchown(self):
  526. if hasattr(os, "fchown"):
  527. self.check(os.fchown, -1, -1)
  528. def test_fpathconf(self):
  529. if hasattr(os, "fpathconf"):
  530. self.check(os.fpathconf, "PC_NAME_MAX")
  531. def test_ftruncate(self):
  532. if hasattr(os, "ftruncate"):
  533. self.check(os.ftruncate, 0)
  534. def test_lseek(self):
  535. if hasattr(os, "lseek"):
  536. self.check(os.lseek, 0, 0)
  537. def test_read(self):
  538. if hasattr(os, "read"):
  539. self.check(os.read, 1)
  540. def test_tcsetpgrpt(self):
  541. if hasattr(os, "tcsetpgrp"):
  542. self.check(os.tcsetpgrp, 0)
  543. def test_write(self):
  544. if hasattr(os, "write"):
  545. self.check(os.write, " ")
  546. if sys.platform != 'win32':
  547. class Win32ErrorTests(unittest.TestCase):
  548. pass
  549. class PosixUidGidTests(unittest.TestCase):
  550. if hasattr(os, 'setuid'):
  551. def test_setuid(self):
  552. if os.getuid() != 0:
  553. self.assertRaises(os.error, os.setuid, 0)
  554. self.assertRaises(OverflowError, os.setuid, 1<<32)
  555. if hasattr(os, 'setgid'):
  556. def test_setgid(self):
  557. if os.getuid() != 0:
  558. self.assertRaises(os.error, os.setgid, 0)
  559. self.assertRaises(OverflowError, os.setgid, 1<<32)
  560. if hasattr(os, 'seteuid'):
  561. def test_seteuid(self):
  562. if os.getuid() != 0:
  563. self.assertRaises(os.error, os.seteuid, 0)
  564. self.assertRaises(OverflowError, os.seteuid, 1<<32)
  565. if hasattr(os, 'setegid'):
  566. def test_setegid(self):
  567. if os.getuid() != 0:
  568. self.assertRaises(os.error, os.setegid, 0)
  569. self.assertRaises(OverflowError, os.setegid, 1<<32)
  570. if hasattr(os, 'setreuid'):
  571. def test_setreuid(self):
  572. if os.getuid() != 0:
  573. self.assertRaises(os.error, os.setreuid, 0, 0)
  574. self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
  575. self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
  576. def test_setreuid_neg1(self):
  577. # Needs to accept -1. We run this in a subprocess to avoid
  578. # altering the test runner's process state (issue8045).
  579. subprocess.check_call([
  580. sys.executable, '-c',
  581. 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
  582. if hasattr(os, 'setregid'):
  583. def test_setregid(self):
  584. if os.getuid() != 0:
  585. self.assertRaises(os.error, os.setregid, 0, 0)
  586. self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
  587. self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
  588. def test_setregid_neg1(self):
  589. # Needs to accept -1. We run this in a subprocess to avoid
  590. # altering the test runner's process state (issue8045).
  591. subprocess.check_call([
  592. sys.executable, '-c',
  593. 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
  594. else:
  595. class PosixUidGidTests(unittest.TestCase):
  596. pass
  597. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  598. class Win32KillTests(unittest.TestCase):
  599. def _kill(self, sig):
  600. # Start sys.executable as a subprocess and communicate from the
  601. # subprocess to the parent that the interpreter is ready. When it
  602. # becomes ready, send *sig* via os.kill to the subprocess and check
  603. # that the return code is equal to *sig*.
  604. import ctypes
  605. from ctypes import wintypes
  606. import msvcrt
  607. # Since we can't access the contents of the process' stdout until the
  608. # process has exited, use PeekNamedPipe to see what's inside stdout
  609. # without waiting. This is done so we can tell that the interpreter
  610. # is started and running at a point where it could handle a signal.
  611. PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
  612. PeekNamedPipe.restype = wintypes.BOOL
  613. PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
  614. ctypes.POINTER(ctypes.c_char), # stdout buf
  615. wintypes.DWORD, # Buffer size
  616. ctypes.POINTER(wintypes.DWORD), # bytes read
  617. ctypes.POINTER(wintypes.DWORD), # bytes avail
  618. ctypes.POINTER(wintypes.DWORD)) # bytes left
  619. msg = "running"
  620. proc = subprocess.Popen([sys.executable, "-c",
  621. "import sys;"
  622. "sys.stdout.write('{}');"
  623. "sys.stdout.flush();"
  624. "input()".format(msg)],
  625. stdout=subprocess.PIPE,
  626. stderr=subprocess.PIPE,
  627. stdin=subprocess.PIPE)
  628. self.addCleanup(proc.stdout.close)
  629. self.addCleanup(proc.stderr.close)
  630. self.addCleanup(proc.stdin.close)
  631. count, max = 0, 100
  632. while count < max and proc.poll() is None:
  633. # Create a string buffer to store the result of stdout from the pipe
  634. buf = ctypes.create_string_buffer(len(msg))
  635. # Obtain the text currently in proc.stdout
  636. # Bytes read/avail/left are left as NULL and unused
  637. rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
  638. buf, ctypes.sizeof(buf), None, None, None)
  639. self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
  640. if buf.value:
  641. self.assertEqual(msg, buf.value)
  642. break
  643. time.sleep(0.1)
  644. count += 1
  645. else:
  646. self.fail("Did not receive communication from the subprocess")
  647. os.kill(proc.pid, sig)
  648. self.assertEqual(proc.wait(), sig)
  649. def test_kill_sigterm(self):
  650. # SIGTERM doesn't mean anything special, but make sure it works
  651. self._kill(signal.SIGTERM)
  652. def test_kill_int(self):
  653. # os.kill on Windows can take an int which gets set as the exit code
  654. self._kill(100)
  655. def _kill_with_event(self, event, name):
  656. tagname = "test_os_%s" % uuid.uuid1()
  657. m = mmap.mmap(-1, 1, tagname)
  658. m[0] = '0'
  659. # Run a script which has console control handling enabled.
  660. proc = subprocess.Popen([sys.executable,
  661. os.path.join(os.path.dirname(__file__),
  662. "win_console_handler.py"), tagname],
  663. creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
  664. # Let the interpreter startup before we send signals. See #3137.
  665. count, max = 0, 20
  666. while count < max and proc.poll() is None:
  667. if m[0] == '1':
  668. break
  669. time.sleep(0.5)
  670. count += 1
  671. else:
  672. self.fail("Subprocess didn't finish initialization")
  673. os.kill(proc.pid, event)
  674. # proc.send_signal(event) could also be done here.
  675. # Allow time for the signal to be passed and the process to exit.
  676. time.sleep(0.5)
  677. if not proc.poll():
  678. # Forcefully kill the process if we weren't able to signal it.
  679. os.kill(proc.pid, signal.SIGINT)
  680. self.fail("subprocess did not stop on {}".format(name))
  681. @unittest.skip("subprocesses aren't inheriting CTRL+C property")
  682. def test_CTRL_C_EVENT(self):
  683. from ctypes import wintypes
  684. import ctypes
  685. # Make a NULL value by creating a pointer with no argument.
  686. NULL = ctypes.POINTER(ctypes.c_int)()
  687. SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
  688. SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
  689. wintypes.BOOL)
  690. SetConsoleCtrlHandler.restype = wintypes.BOOL
  691. # Calling this with NULL and FALSE causes the calling process to
  692. # handle CTRL+C, rather than ignore it. This property is inherited
  693. # by subprocesses.
  694. SetConsoleCtrlHandler(NULL, 0)
  695. self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
  696. def test_CTRL_BREAK_EVENT(self):
  697. self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
  698. def test_main():
  699. test_support.run_unittest(
  700. FileTests,
  701. TemporaryFileTests,
  702. StatAttributeTests,
  703. EnvironTests,
  704. WalkTests,
  705. MakedirTests,
  706. DevNullTests,
  707. URandomTests,
  708. Win32ErrorTests,
  709. TestInvalidFD,
  710. PosixUidGidTests,
  711. Win32KillTests
  712. )
  713. if __name__ == "__main__":
  714. test_main()