PageRenderTime 84ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/client/bower_components/brython/www/src/Lib/test/test_os.py

https://gitlab.com/Verner/brython-misc
Python | 1348 lines | 1085 code | 146 blank | 117 comment | 175 complexity | b4bf81172a2f22e2b8e993a3f6bdd98b 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. import shutil
  13. from test import support
  14. import contextlib
  15. import mmap
  16. import platform
  17. import re
  18. import uuid
  19. import asyncore
  20. import asynchat
  21. import socket
  22. import itertools
  23. import stat
  24. import locale
  25. import codecs
  26. try:
  27. import threading
  28. except ImportError:
  29. threading = None
  30. try:
  31. import resource
  32. except ImportError:
  33. resource = None
  34. from test.script_helper import assert_python_ok
  35. with warnings.catch_warnings():
  36. warnings.simplefilter("ignore", DeprecationWarning)
  37. os.stat_float_times(True)
  38. st = os.stat(__file__)
  39. stat_supports_subsecond = (
  40. # check if float and int timestamps are different
  41. (st.st_atime != st[7])
  42. or (st.st_mtime != st[8])
  43. or (st.st_ctime != st[9]))
  44. # Detect whether we're on a Linux system that uses the (now outdated
  45. # and unmaintained) linuxthreads threading library. There's an issue
  46. # when combining linuxthreads with a failed execv call: see
  47. # http://bugs.python.org/issue4970.
  48. if hasattr(sys, 'thread_info') and sys.thread_info.version:
  49. USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
  50. else:
  51. USING_LINUXTHREADS = False
  52. # Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
  53. HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
  54. # Tests creating TESTFN
  55. class FileTests(unittest.TestCase):
  56. def setUp(self):
  57. if os.path.exists(support.TESTFN):
  58. os.unlink(support.TESTFN)
  59. tearDown = setUp
  60. def test_access(self):
  61. f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
  62. os.close(f)
  63. self.assertTrue(os.access(support.TESTFN, os.W_OK))
  64. def test_closerange(self):
  65. first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
  66. # We must allocate two consecutive file descriptors, otherwise
  67. # it will mess up other file descriptors (perhaps even the three
  68. # standard ones).
  69. second = os.dup(first)
  70. try:
  71. retries = 0
  72. while second != first + 1:
  73. os.close(first)
  74. retries += 1
  75. if retries > 10:
  76. # XXX test skipped
  77. self.skipTest("couldn't allocate two consecutive fds")
  78. first, second = second, os.dup(second)
  79. finally:
  80. os.close(second)
  81. # close a fd that is open, and one that isn't
  82. os.closerange(first, first + 2)
  83. self.assertRaises(OSError, os.write, first, b"a")
  84. @support.cpython_only
  85. def test_rename(self):
  86. path = support.TESTFN
  87. old = sys.getrefcount(path)
  88. self.assertRaises(TypeError, os.rename, path, 0)
  89. new = sys.getrefcount(path)
  90. self.assertEqual(old, new)
  91. def test_read(self):
  92. with open(support.TESTFN, "w+b") as fobj:
  93. fobj.write(b"spam")
  94. fobj.flush()
  95. fd = fobj.fileno()
  96. os.lseek(fd, 0, 0)
  97. s = os.read(fd, 4)
  98. self.assertEqual(type(s), bytes)
  99. self.assertEqual(s, b"spam")
  100. def test_write(self):
  101. # os.write() accepts bytes- and buffer-like objects but not strings
  102. fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY)
  103. self.assertRaises(TypeError, os.write, fd, "beans")
  104. os.write(fd, b"bacon\n")
  105. os.write(fd, bytearray(b"eggs\n"))
  106. os.write(fd, memoryview(b"spam\n"))
  107. os.close(fd)
  108. with open(support.TESTFN, "rb") as fobj:
  109. self.assertEqual(fobj.read().splitlines(),
  110. [b"bacon", b"eggs", b"spam"])
  111. def write_windows_console(self, *args):
  112. retcode = subprocess.call(args,
  113. # use a new console to not flood the test output
  114. creationflags=subprocess.CREATE_NEW_CONSOLE,
  115. # use a shell to hide the console window (SW_HIDE)
  116. shell=True)
  117. self.assertEqual(retcode, 0)
  118. @unittest.skipUnless(sys.platform == 'win32',
  119. 'test specific to the Windows console')
  120. def test_write_windows_console(self):
  121. # Issue #11395: the Windows console returns an error (12: not enough
  122. # space error) on writing into stdout if stdout mode is binary and the
  123. # length is greater than 66,000 bytes (or less, depending on heap
  124. # usage).
  125. code = "print('x' * 100000)"
  126. self.write_windows_console(sys.executable, "-c", code)
  127. self.write_windows_console(sys.executable, "-u", "-c", code)
  128. def fdopen_helper(self, *args):
  129. fd = os.open(support.TESTFN, os.O_RDONLY)
  130. f = os.fdopen(fd, *args)
  131. f.close()
  132. def test_fdopen(self):
  133. fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
  134. os.close(fd)
  135. self.fdopen_helper()
  136. self.fdopen_helper('r')
  137. self.fdopen_helper('r', 100)
  138. def test_replace(self):
  139. TESTFN2 = support.TESTFN + ".2"
  140. with open(support.TESTFN, 'w') as f:
  141. f.write("1")
  142. with open(TESTFN2, 'w') as f:
  143. f.write("2")
  144. self.addCleanup(os.unlink, TESTFN2)
  145. os.replace(support.TESTFN, TESTFN2)
  146. self.assertRaises(FileNotFoundError, os.stat, support.TESTFN)
  147. with open(TESTFN2, 'r') as f:
  148. self.assertEqual(f.read(), "1")
  149. # Test attributes on return values from os.*stat* family.
  150. class StatAttributeTests(unittest.TestCase):
  151. def setUp(self):
  152. os.mkdir(support.TESTFN)
  153. self.fname = os.path.join(support.TESTFN, "f1")
  154. f = open(self.fname, 'wb')
  155. f.write(b"ABC")
  156. f.close()
  157. def tearDown(self):
  158. os.unlink(self.fname)
  159. os.rmdir(support.TESTFN)
  160. def check_stat_attributes(self, fname):
  161. if not hasattr(os, "stat"):
  162. return
  163. result = os.stat(fname)
  164. # Make sure direct access works
  165. self.assertEqual(result[stat.ST_SIZE], 3)
  166. self.assertEqual(result.st_size, 3)
  167. # Make sure all the attributes are there
  168. members = dir(result)
  169. for name in dir(stat):
  170. if name[:3] == 'ST_':
  171. attr = name.lower()
  172. if name.endswith("TIME"):
  173. def trunc(x): return int(x)
  174. else:
  175. def trunc(x): return x
  176. self.assertEqual(trunc(getattr(result, attr)),
  177. result[getattr(stat, name)])
  178. self.assertIn(attr, members)
  179. # Make sure that the st_?time and st_?time_ns fields roughly agree
  180. # (they should always agree up to around tens-of-microseconds)
  181. for name in 'st_atime st_mtime st_ctime'.split():
  182. floaty = int(getattr(result, name) * 100000)
  183. nanosecondy = getattr(result, name + "_ns") // 10000
  184. self.assertAlmostEqual(floaty, nanosecondy, delta=2)
  185. try:
  186. result[200]
  187. self.fail("No exception raised")
  188. except IndexError:
  189. pass
  190. # Make sure that assignment fails
  191. try:
  192. result.st_mode = 1
  193. self.fail("No exception raised")
  194. except AttributeError:
  195. pass
  196. try:
  197. result.st_rdev = 1
  198. self.fail("No exception raised")
  199. except (AttributeError, TypeError):
  200. pass
  201. try:
  202. result.parrot = 1
  203. self.fail("No exception raised")
  204. except AttributeError:
  205. pass
  206. # Use the stat_result constructor with a too-short tuple.
  207. try:
  208. result2 = os.stat_result((10,))
  209. self.fail("No exception raised")
  210. except TypeError:
  211. pass
  212. # Use the constructor with a too-long tuple.
  213. try:
  214. result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  215. except TypeError:
  216. pass
  217. def test_stat_attributes(self):
  218. self.check_stat_attributes(self.fname)
  219. def test_stat_attributes_bytes(self):
  220. try:
  221. fname = self.fname.encode(sys.getfilesystemencoding())
  222. except UnicodeEncodeError:
  223. self.skipTest("cannot encode %a for the filesystem" % self.fname)
  224. with warnings.catch_warnings():
  225. warnings.simplefilter("ignore", DeprecationWarning)
  226. self.check_stat_attributes(fname)
  227. def test_statvfs_attributes(self):
  228. if not hasattr(os, "statvfs"):
  229. return
  230. try:
  231. result = os.statvfs(self.fname)
  232. except OSError as e:
  233. # On AtheOS, glibc always returns ENOSYS
  234. if e.errno == errno.ENOSYS:
  235. return
  236. # Make sure direct access works
  237. self.assertEqual(result.f_bfree, result[3])
  238. # Make sure all the attributes are there.
  239. members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
  240. 'ffree', 'favail', 'flag', 'namemax')
  241. for value, member in enumerate(members):
  242. self.assertEqual(getattr(result, 'f_' + member), result[value])
  243. # Make sure that assignment really fails
  244. try:
  245. result.f_bfree = 1
  246. self.fail("No exception raised")
  247. except AttributeError:
  248. pass
  249. try:
  250. result.parrot = 1
  251. self.fail("No exception raised")
  252. except AttributeError:
  253. pass
  254. # Use the constructor with a too-short tuple.
  255. try:
  256. result2 = os.statvfs_result((10,))
  257. self.fail("No exception raised")
  258. except TypeError:
  259. pass
  260. # Use the constructor with a too-long tuple.
  261. try:
  262. result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  263. except TypeError:
  264. pass
  265. def test_utime_dir(self):
  266. delta = 1000000
  267. st = os.stat(support.TESTFN)
  268. # round to int, because some systems may support sub-second
  269. # time stamps in stat, but not in utime.
  270. os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
  271. st2 = os.stat(support.TESTFN)
  272. self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
  273. def _test_utime(self, filename, attr, utime, delta):
  274. # Issue #13327 removed the requirement to pass None as the
  275. # second argument. Check that the previous methods of passing
  276. # a time tuple or None work in addition to no argument.
  277. st0 = os.stat(filename)
  278. # Doesn't set anything new, but sets the time tuple way
  279. utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime")))
  280. # Setting the time to the time you just read, then reading again,
  281. # should always return exactly the same times.
  282. st1 = os.stat(filename)
  283. self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime"))
  284. self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime"))
  285. # Set to the current time in the old explicit way.
  286. os.utime(filename, None)
  287. st2 = os.stat(support.TESTFN)
  288. # Set to the current time in the new way
  289. os.utime(filename)
  290. st3 = os.stat(filename)
  291. self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta)
  292. def test_utime(self):
  293. def utime(file, times):
  294. return os.utime(file, times)
  295. self._test_utime(self.fname, getattr, utime, 10)
  296. self._test_utime(support.TESTFN, getattr, utime, 10)
  297. def _test_utime_ns(self, set_times_ns, test_dir=True):
  298. def getattr_ns(o, attr):
  299. return getattr(o, attr + "_ns")
  300. ten_s = 10 * 1000 * 1000 * 1000
  301. self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s)
  302. if test_dir:
  303. self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s)
  304. def test_utime_ns(self):
  305. def utime_ns(file, times):
  306. return os.utime(file, ns=times)
  307. self._test_utime_ns(utime_ns)
  308. requires_utime_dir_fd = unittest.skipUnless(
  309. os.utime in os.supports_dir_fd,
  310. "dir_fd support for utime required for this test.")
  311. requires_utime_fd = unittest.skipUnless(
  312. os.utime in os.supports_fd,
  313. "fd support for utime required for this test.")
  314. requires_utime_nofollow_symlinks = unittest.skipUnless(
  315. os.utime in os.supports_follow_symlinks,
  316. "follow_symlinks support for utime required for this test.")
  317. @requires_utime_nofollow_symlinks
  318. def test_lutimes_ns(self):
  319. def lutimes_ns(file, times):
  320. return os.utime(file, ns=times, follow_symlinks=False)
  321. self._test_utime_ns(lutimes_ns)
  322. @requires_utime_fd
  323. def test_futimes_ns(self):
  324. def futimes_ns(file, times):
  325. with open(file, "wb") as f:
  326. os.utime(f.fileno(), ns=times)
  327. self._test_utime_ns(futimes_ns, test_dir=False)
  328. def _utime_invalid_arguments(self, name, arg):
  329. with self.assertRaises(ValueError):
  330. getattr(os, name)(arg, (5, 5), ns=(5, 5))
  331. def test_utime_invalid_arguments(self):
  332. self._utime_invalid_arguments('utime', self.fname)
  333. @unittest.skipUnless(stat_supports_subsecond,
  334. "os.stat() doesn't has a subsecond resolution")
  335. def _test_utime_subsecond(self, set_time_func):
  336. asec, amsec = 1, 901
  337. atime = asec + amsec * 1e-3
  338. msec, mmsec = 2, 901
  339. mtime = msec + mmsec * 1e-3
  340. filename = self.fname
  341. os.utime(filename, (0, 0))
  342. set_time_func(filename, atime, mtime)
  343. with warnings.catch_warnings():
  344. warnings.simplefilter("ignore", DeprecationWarning)
  345. os.stat_float_times(True)
  346. st = os.stat(filename)
  347. self.assertAlmostEqual(st.st_atime, atime, places=3)
  348. self.assertAlmostEqual(st.st_mtime, mtime, places=3)
  349. def test_utime_subsecond(self):
  350. def set_time(filename, atime, mtime):
  351. os.utime(filename, (atime, mtime))
  352. self._test_utime_subsecond(set_time)
  353. @requires_utime_fd
  354. def test_futimes_subsecond(self):
  355. def set_time(filename, atime, mtime):
  356. with open(filename, "wb") as f:
  357. os.utime(f.fileno(), times=(atime, mtime))
  358. self._test_utime_subsecond(set_time)
  359. @requires_utime_fd
  360. def test_futimens_subsecond(self):
  361. def set_time(filename, atime, mtime):
  362. with open(filename, "wb") as f:
  363. os.utime(f.fileno(), times=(atime, mtime))
  364. self._test_utime_subsecond(set_time)
  365. @requires_utime_dir_fd
  366. def test_futimesat_subsecond(self):
  367. def set_time(filename, atime, mtime):
  368. dirname = os.path.dirname(filename)
  369. dirfd = os.open(dirname, os.O_RDONLY)
  370. try:
  371. os.utime(os.path.basename(filename), dir_fd=dirfd,
  372. times=(atime, mtime))
  373. finally:
  374. os.close(dirfd)
  375. self._test_utime_subsecond(set_time)
  376. @requires_utime_nofollow_symlinks
  377. def test_lutimes_subsecond(self):
  378. def set_time(filename, atime, mtime):
  379. os.utime(filename, (atime, mtime), follow_symlinks=False)
  380. self._test_utime_subsecond(set_time)
  381. @requires_utime_dir_fd
  382. def test_utimensat_subsecond(self):
  383. def set_time(filename, atime, mtime):
  384. dirname = os.path.dirname(filename)
  385. dirfd = os.open(dirname, os.O_RDONLY)
  386. try:
  387. os.utime(os.path.basename(filename), dir_fd=dirfd,
  388. times=(atime, mtime))
  389. finally:
  390. os.close(dirfd)
  391. self._test_utime_subsecond(set_time)
  392. # Restrict test to Win32, since there is no guarantee other
  393. # systems support centiseconds
  394. if sys.platform == 'win32':
  395. def get_file_system(path):
  396. root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
  397. import ctypes
  398. kernel32 = ctypes.windll.kernel32
  399. buf = ctypes.create_unicode_buffer("", 100)
  400. if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)):
  401. return buf.value
  402. if get_file_system(support.TESTFN) == "NTFS":
  403. def test_1565150(self):
  404. t1 = 1159195039.25
  405. os.utime(self.fname, (t1, t1))
  406. self.assertEqual(os.stat(self.fname).st_mtime, t1)
  407. def test_large_time(self):
  408. t1 = 5000000000 # some day in 2128
  409. os.utime(self.fname, (t1, t1))
  410. self.assertEqual(os.stat(self.fname).st_mtime, t1)
  411. def test_1686475(self):
  412. # Verify that an open file can be stat'ed
  413. try:
  414. os.stat(r"c:\pagefile.sys")
  415. except WindowsError as e:
  416. if e.errno == 2: # file does not exist; cannot run test
  417. return
  418. self.fail("Could not stat pagefile.sys")
  419. @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
  420. def test_15261(self):
  421. # Verify that stat'ing a closed fd does not cause crash
  422. r, w = os.pipe()
  423. try:
  424. os.stat(r) # should not raise error
  425. finally:
  426. os.close(r)
  427. os.close(w)
  428. with self.assertRaises(OSError) as ctx:
  429. os.stat(r)
  430. self.assertEqual(ctx.exception.errno, errno.EBADF)
  431. from test import mapping_tests
  432. class EnvironTests(mapping_tests.BasicTestMappingProtocol):
  433. """check that os.environ object conform to mapping protocol"""
  434. type2test = None
  435. def setUp(self):
  436. self.__save = dict(os.environ)
  437. if os.supports_bytes_environ:
  438. self.__saveb = dict(os.environb)
  439. for key, value in self._reference().items():
  440. os.environ[key] = value
  441. def tearDown(self):
  442. os.environ.clear()
  443. os.environ.update(self.__save)
  444. if os.supports_bytes_environ:
  445. os.environb.clear()
  446. os.environb.update(self.__saveb)
  447. def _reference(self):
  448. return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
  449. def _empty_mapping(self):
  450. os.environ.clear()
  451. return os.environ
  452. # Bug 1110478
  453. @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
  454. def test_update2(self):
  455. os.environ.clear()
  456. os.environ.update(HELLO="World")
  457. with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
  458. value = popen.read().strip()
  459. self.assertEqual(value, "World")
  460. @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
  461. def test_os_popen_iter(self):
  462. with os.popen(
  463. "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
  464. it = iter(popen)
  465. self.assertEqual(next(it), "line1\n")
  466. self.assertEqual(next(it), "line2\n")
  467. self.assertEqual(next(it), "line3\n")
  468. self.assertRaises(StopIteration, next, it)
  469. # Verify environ keys and values from the OS are of the
  470. # correct str type.
  471. def test_keyvalue_types(self):
  472. for key, val in os.environ.items():
  473. self.assertEqual(type(key), str)
  474. self.assertEqual(type(val), str)
  475. def test_items(self):
  476. for key, value in self._reference().items():
  477. self.assertEqual(os.environ.get(key), value)
  478. # Issue 7310
  479. def test___repr__(self):
  480. """Check that the repr() of os.environ looks like environ({...})."""
  481. env = os.environ
  482. self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join(
  483. '{!r}: {!r}'.format(key, value)
  484. for key, value in env.items())))
  485. def test_get_exec_path(self):
  486. defpath_list = os.defpath.split(os.pathsep)
  487. test_path = ['/monty', '/python', '', '/flying/circus']
  488. test_env = {'PATH': os.pathsep.join(test_path)}
  489. saved_environ = os.environ
  490. try:
  491. os.environ = dict(test_env)
  492. # Test that defaulting to os.environ works.
  493. self.assertSequenceEqual(test_path, os.get_exec_path())
  494. self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
  495. finally:
  496. os.environ = saved_environ
  497. # No PATH environment variable
  498. self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
  499. # Empty PATH environment variable
  500. self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
  501. # Supplied PATH environment variable
  502. self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
  503. if os.supports_bytes_environ:
  504. # env cannot contain 'PATH' and b'PATH' keys
  505. try:
  506. # ignore BytesWarning warning
  507. with warnings.catch_warnings(record=True):
  508. mixed_env = {'PATH': '1', b'PATH': b'2'}
  509. except BytesWarning:
  510. # mixed_env cannot be created with python -bb
  511. pass
  512. else:
  513. self.assertRaises(ValueError, os.get_exec_path, mixed_env)
  514. # bytes key and/or value
  515. self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
  516. ['abc'])
  517. self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
  518. ['abc'])
  519. self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
  520. ['abc'])
  521. @unittest.skipUnless(os.supports_bytes_environ,
  522. "os.environb required for this test.")
  523. def test_environb(self):
  524. # os.environ -> os.environb
  525. value = 'euro\u20ac'
  526. try:
  527. value_bytes = value.encode(sys.getfilesystemencoding(),
  528. 'surrogateescape')
  529. except UnicodeEncodeError:
  530. msg = "U+20AC character is not encodable to %s" % (
  531. sys.getfilesystemencoding(),)
  532. self.skipTest(msg)
  533. os.environ['unicode'] = value
  534. self.assertEqual(os.environ['unicode'], value)
  535. self.assertEqual(os.environb[b'unicode'], value_bytes)
  536. # os.environb -> os.environ
  537. value = b'\xff'
  538. os.environb[b'bytes'] = value
  539. self.assertEqual(os.environb[b'bytes'], value)
  540. value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
  541. self.assertEqual(os.environ['bytes'], value_str)
  542. # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
  543. # #13415).
  544. @support.requires_freebsd_version(7)
  545. @support.requires_mac_ver(10, 6)
  546. def test_unset_error(self):
  547. if sys.platform == "win32":
  548. # an environment variable is limited to 32,767 characters
  549. key = 'x' * 50000
  550. self.assertRaises(ValueError, os.environ.__delitem__, key)
  551. else:
  552. # "=" is not allowed in a variable name
  553. key = 'key='
  554. self.assertRaises(OSError, os.environ.__delitem__, key)
  555. def test_key_type(self):
  556. missing = 'missingkey'
  557. self.assertNotIn(missing, os.environ)
  558. with self.assertRaises(KeyError) as cm:
  559. os.environ[missing]
  560. self.assertIs(cm.exception.args[0], missing)
  561. self.assertTrue(cm.exception.__suppress_context__)
  562. with self.assertRaises(KeyError) as cm:
  563. del os.environ[missing]
  564. self.assertIs(cm.exception.args[0], missing)
  565. self.assertTrue(cm.exception.__suppress_context__)
  566. class WalkTests(unittest.TestCase):
  567. """Tests for os.walk()."""
  568. def setUp(self):
  569. import os
  570. from os.path import join
  571. # Build:
  572. # TESTFN/
  573. # TEST1/ a file kid and two directory kids
  574. # tmp1
  575. # SUB1/ a file kid and a directory kid
  576. # tmp2
  577. # SUB11/ no kids
  578. # SUB2/ a file kid and a dirsymlink kid
  579. # tmp3
  580. # link/ a symlink to TESTFN.2
  581. # broken_link
  582. # TEST2/
  583. # tmp4 a lone file
  584. walk_path = join(support.TESTFN, "TEST1")
  585. sub1_path = join(walk_path, "SUB1")
  586. sub11_path = join(sub1_path, "SUB11")
  587. sub2_path = join(walk_path, "SUB2")
  588. tmp1_path = join(walk_path, "tmp1")
  589. tmp2_path = join(sub1_path, "tmp2")
  590. tmp3_path = join(sub2_path, "tmp3")
  591. link_path = join(sub2_path, "link")
  592. t2_path = join(support.TESTFN, "TEST2")
  593. tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
  594. link_path = join(sub2_path, "link")
  595. broken_link_path = join(sub2_path, "broken_link")
  596. # Create stuff.
  597. os.makedirs(sub11_path)
  598. os.makedirs(sub2_path)
  599. os.makedirs(t2_path)
  600. for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
  601. f = open(path, "w")
  602. f.write("I'm " + path + " and proud of it. Blame test_os.\n")
  603. f.close()
  604. if support.can_symlink():
  605. os.symlink(os.path.abspath(t2_path), link_path)
  606. os.symlink('broken', broken_link_path, True)
  607. sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
  608. else:
  609. sub2_tree = (sub2_path, [], ["tmp3"])
  610. # Walk top-down.
  611. all = list(os.walk(walk_path))
  612. self.assertEqual(len(all), 4)
  613. # We can't know which order SUB1 and SUB2 will appear in.
  614. # Not flipped: TESTFN, SUB1, SUB11, SUB2
  615. # flipped: TESTFN, SUB2, SUB1, SUB11
  616. flipped = all[0][1][0] != "SUB1"
  617. all[0][1].sort()
  618. all[3 - 2 * flipped][-1].sort()
  619. self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
  620. self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
  621. self.assertEqual(all[2 + flipped], (sub11_path, [], []))
  622. self.assertEqual(all[3 - 2 * flipped], sub2_tree)
  623. # Prune the search.
  624. all = []
  625. for root, dirs, files in os.walk(walk_path):
  626. all.append((root, dirs, files))
  627. # Don't descend into SUB1.
  628. if 'SUB1' in dirs:
  629. # Note that this also mutates the dirs we appended to all!
  630. dirs.remove('SUB1')
  631. self.assertEqual(len(all), 2)
  632. self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
  633. all[1][-1].sort()
  634. self.assertEqual(all[1], sub2_tree)
  635. # Walk bottom-up.
  636. all = list(os.walk(walk_path, topdown=False))
  637. self.assertEqual(len(all), 4)
  638. # We can't know which order SUB1 and SUB2 will appear in.
  639. # Not flipped: SUB11, SUB1, SUB2, TESTFN
  640. # flipped: SUB2, SUB11, SUB1, TESTFN
  641. flipped = all[3][1][0] != "SUB1"
  642. all[3][1].sort()
  643. all[2 - 2 * flipped][-1].sort()
  644. self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
  645. self.assertEqual(all[flipped], (sub11_path, [], []))
  646. self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
  647. self.assertEqual(all[2 - 2 * flipped], sub2_tree)
  648. if support.can_symlink():
  649. # Walk, following symlinks.
  650. for root, dirs, files in os.walk(walk_path, followlinks=True):
  651. if root == link_path:
  652. self.assertEqual(dirs, [])
  653. self.assertEqual(files, ["tmp4"])
  654. break
  655. else:
  656. self.fail("Didn't follow symlink with followlinks=True")
  657. def tearDown(self):
  658. # Tear everything down. This is a decent use for bottom-up on
  659. # Windows, which doesn't have a recursive delete command. The
  660. # (not so) subtlety is that rmdir will fail unless the dir's
  661. # kids are removed first, so bottom up is essential.
  662. for root, dirs, files in os.walk(support.TESTFN, topdown=False):
  663. for name in files:
  664. os.remove(os.path.join(root, name))
  665. for name in dirs:
  666. dirname = os.path.join(root, name)
  667. if not os.path.islink(dirname):
  668. os.rmdir(dirname)
  669. else:
  670. os.remove(dirname)
  671. os.rmdir(support.TESTFN)
  672. @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
  673. class FwalkTests(WalkTests):
  674. """Tests for os.fwalk()."""
  675. def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
  676. """
  677. compare with walk() results.
  678. """
  679. walk_kwargs = walk_kwargs.copy()
  680. fwalk_kwargs = fwalk_kwargs.copy()
  681. for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
  682. walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
  683. fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
  684. expected = {}
  685. for root, dirs, files in os.walk(**walk_kwargs):
  686. expected[root] = (set(dirs), set(files))
  687. for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs):
  688. self.assertIn(root, expected)
  689. self.assertEqual(expected[root], (set(dirs), set(files)))
  690. def test_compare_to_walk(self):
  691. kwargs = {'top': support.TESTFN}
  692. self._compare_to_walk(kwargs, kwargs)
  693. def test_dir_fd(self):
  694. try:
  695. fd = os.open(".", os.O_RDONLY)
  696. walk_kwargs = {'top': support.TESTFN}
  697. fwalk_kwargs = walk_kwargs.copy()
  698. fwalk_kwargs['dir_fd'] = fd
  699. self._compare_to_walk(walk_kwargs, fwalk_kwargs)
  700. finally:
  701. os.close(fd)
  702. def test_yields_correct_dir_fd(self):
  703. # check returned file descriptors
  704. for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
  705. args = support.TESTFN, topdown, None
  706. for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks):
  707. # check that the FD is valid
  708. os.fstat(rootfd)
  709. # redundant check
  710. os.stat(rootfd)
  711. # check that listdir() returns consistent information
  712. self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
  713. def test_fd_leak(self):
  714. # Since we're opening a lot of FDs, we must be careful to avoid leaks:
  715. # we both check that calling fwalk() a large number of times doesn't
  716. # yield EMFILE, and that the minimum allocated FD hasn't changed.
  717. minfd = os.dup(1)
  718. os.close(minfd)
  719. for i in range(256):
  720. for x in os.fwalk(support.TESTFN):
  721. pass
  722. newfd = os.dup(1)
  723. self.addCleanup(os.close, newfd)
  724. self.assertEqual(newfd, minfd)
  725. def tearDown(self):
  726. # cleanup
  727. for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
  728. for name in files:
  729. os.unlink(name, dir_fd=rootfd)
  730. for name in dirs:
  731. st = os.stat(name, dir_fd=rootfd, follow_symlinks=False)
  732. if stat.S_ISDIR(st.st_mode):
  733. os.rmdir(name, dir_fd=rootfd)
  734. else:
  735. os.unlink(name, dir_fd=rootfd)
  736. os.rmdir(support.TESTFN)
  737. class MakedirTests(unittest.TestCase):
  738. def setUp(self):
  739. os.mkdir(support.TESTFN)
  740. def test_makedir(self):
  741. base = support.TESTFN
  742. path = os.path.join(base, 'dir1', 'dir2', 'dir3')
  743. os.makedirs(path) # Should work
  744. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
  745. os.makedirs(path)
  746. # Try paths with a '.' in them
  747. self.assertRaises(OSError, os.makedirs, os.curdir)
  748. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
  749. os.makedirs(path)
  750. path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
  751. 'dir5', 'dir6')
  752. os.makedirs(path)
  753. def test_exist_ok_existing_directory(self):
  754. path = os.path.join(support.TESTFN, 'dir1')
  755. mode = 0o777
  756. old_mask = os.umask(0o022)
  757. os.makedirs(path, mode)
  758. self.assertRaises(OSError, os.makedirs, path, mode)
  759. self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
  760. self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
  761. os.makedirs(path, mode=mode, exist_ok=True)
  762. os.umask(old_mask)
  763. def test_exist_ok_s_isgid_directory(self):
  764. path = os.path.join(support.TESTFN, 'dir1')
  765. S_ISGID = stat.S_ISGID
  766. mode = 0o777
  767. old_mask = os.umask(0o022)
  768. try:
  769. existing_testfn_mode = stat.S_IMODE(
  770. os.lstat(support.TESTFN).st_mode)
  771. try:
  772. os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID)
  773. except PermissionError:
  774. raise unittest.SkipTest('Cannot set S_ISGID for dir.')
  775. if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID):
  776. raise unittest.SkipTest('No support for S_ISGID dir mode.')
  777. # The os should apply S_ISGID from the parent dir for us, but
  778. # this test need not depend on that behavior. Be explicit.
  779. os.makedirs(path, mode | S_ISGID)
  780. # http://bugs.python.org/issue14992
  781. # Should not fail when the bit is already set.
  782. os.makedirs(path, mode, exist_ok=True)
  783. # remove the bit.
  784. os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
  785. with self.assertRaises(OSError):
  786. # Should fail when the bit is not already set when demanded.
  787. os.makedirs(path, mode | S_ISGID, exist_ok=True)
  788. finally:
  789. os.umask(old_mask)
  790. def test_exist_ok_existing_regular_file(self):
  791. base = support.TESTFN
  792. path = os.path.join(support.TESTFN, 'dir1')
  793. f = open(path, 'w')
  794. f.write('abc')
  795. f.close()
  796. self.assertRaises(OSError, os.makedirs, path)
  797. self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
  798. self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
  799. os.remove(path)
  800. def tearDown(self):
  801. path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
  802. 'dir4', 'dir5', 'dir6')
  803. # If the tests failed, the bottom-most directory ('../dir6')
  804. # may not have been created, so we look for the outermost directory
  805. # that exists.
  806. while not os.path.exists(path) and path != support.TESTFN:
  807. path = os.path.dirname(path)
  808. os.removedirs(path)
  809. class RemoveDirsTests(unittest.TestCase):
  810. def setUp(self):
  811. os.makedirs(support.TESTFN)
  812. def tearDown(self):
  813. support.rmtree(support.TESTFN)
  814. def test_remove_all(self):
  815. dira = os.path.join(support.TESTFN, 'dira')
  816. os.mkdir(dira)
  817. dirb = os.path.join(dira, 'dirb')
  818. os.mkdir(dirb)
  819. os.removedirs(dirb)
  820. self.assertFalse(os.path.exists(dirb))
  821. self.assertFalse(os.path.exists(dira))
  822. self.assertFalse(os.path.exists(support.TESTFN))
  823. def test_remove_partial(self):
  824. dira = os.path.join(support.TESTFN, 'dira')
  825. os.mkdir(dira)
  826. dirb = os.path.join(dira, 'dirb')
  827. os.mkdir(dirb)
  828. with open(os.path.join(dira, 'file.txt'), 'w') as f:
  829. f.write('text')
  830. os.removedirs(dirb)
  831. self.assertFalse(os.path.exists(dirb))
  832. self.assertTrue(os.path.exists(dira))
  833. self.assertTrue(os.path.exists(support.TESTFN))
  834. def test_remove_nothing(self):
  835. dira = os.path.join(support.TESTFN, 'dira')
  836. os.mkdir(dira)
  837. dirb = os.path.join(dira, 'dirb')
  838. os.mkdir(dirb)
  839. with open(os.path.join(dirb, 'file.txt'), 'w') as f:
  840. f.write('text')
  841. with self.assertRaises(OSError):
  842. os.removedirs(dirb)
  843. self.assertTrue(os.path.exists(dirb))
  844. self.assertTrue(os.path.exists(dira))
  845. self.assertTrue(os.path.exists(support.TESTFN))
  846. class DevNullTests(unittest.TestCase):
  847. def test_devnull(self):
  848. with open(os.devnull, 'wb') as f:
  849. f.write(b'hello')
  850. f.close()
  851. with open(os.devnull, 'rb') as f:
  852. self.assertEqual(f.read(), b'')
  853. class URandomTests(unittest.TestCase):
  854. def test_urandom_length(self):
  855. self.assertEqual(len(os.urandom(0)), 0)
  856. self.assertEqual(len(os.urandom(1)), 1)
  857. self.assertEqual(len(os.urandom(10)), 10)
  858. self.assertEqual(len(os.urandom(100)), 100)
  859. self.assertEqual(len(os.urandom(1000)), 1000)
  860. def test_urandom_value(self):
  861. data1 = os.urandom(16)
  862. data2 = os.urandom(16)
  863. self.assertNotEqual(data1, data2)
  864. def get_urandom_subprocess(self, count):
  865. code = '\n'.join((
  866. 'import os, sys',
  867. 'data = os.urandom(%s)' % count,
  868. 'sys.stdout.buffer.write(data)',
  869. 'sys.stdout.buffer.flush()'))
  870. out = assert_python_ok('-c', code)
  871. stdout = out[1]
  872. self.assertEqual(len(stdout), 16)
  873. return stdout
  874. def test_urandom_subprocess(self):
  875. data1 = self.get_urandom_subprocess(16)
  876. data2 = self.get_urandom_subprocess(16)
  877. self.assertNotEqual(data1, data2)
  878. @unittest.skipUnless(resource, "test requires the resource module")
  879. def test_urandom_failure(self):
  880. # Check urandom() failing when it is not able to open /dev/random.
  881. # We spawn a new process to make the test more robust (if getrlimit()
  882. # failed to restore the file descriptor limit after this, the whole
  883. # test suite would crash; this actually happened on the OS X Tiger
  884. # buildbot).
  885. code = """if 1:
  886. import errno
  887. import os
  888. import resource
  889. soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
  890. resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
  891. try:
  892. os.urandom(16)
  893. except OSError as e:
  894. assert e.errno == errno.EMFILE, e.errno
  895. else:
  896. raise AssertionError("OSError not raised")
  897. """
  898. assert_python_ok('-c', code)
  899. @contextlib.contextmanager
  900. def _execvpe_mockup(defpath=None):
  901. """
  902. Stubs out execv and execve functions when used as context manager.
  903. Records exec calls. The mock execv and execve functions always raise an
  904. exception as they would normally never return.
  905. """
  906. # A list of tuples containing (function name, first arg, args)
  907. # of calls to execv or execve that have been made.
  908. calls = []
  909. def mock_execv(name, *args):
  910. calls.append(('execv', name, args))
  911. raise RuntimeError("execv called")
  912. def mock_execve(name, *args):
  913. calls.append(('execve', name, args))
  914. raise OSError(errno.ENOTDIR, "execve called")
  915. try:
  916. orig_execv = os.execv
  917. orig_execve = os.execve
  918. orig_defpath = os.defpath
  919. os.execv = mock_execv
  920. os.execve = mock_execve
  921. if defpath is not None:
  922. os.defpath = defpath
  923. yield calls
  924. finally:
  925. os.execv = orig_execv
  926. os.execve = orig_execve
  927. os.defpath = orig_defpath
  928. class ExecTests(unittest.TestCase):
  929. @unittest.skipIf(USING_LINUXTHREADS,
  930. "avoid triggering a linuxthreads bug: see issue #4970")
  931. def test_execvpe_with_bad_program(self):
  932. self.assertRaises(OSError, os.execvpe, 'no such app-',
  933. ['no such app-'], None)
  934. def test_execvpe_with_bad_arglist(self):
  935. self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
  936. @unittest.skipUnless(hasattr(os, '_execvpe'),
  937. "No internal os._execvpe function to test.")
  938. def _test_internal_execvpe(self, test_type):
  939. program_path = os.sep + 'absolutepath'
  940. if test_type is bytes:
  941. program = b'executable'
  942. fullpath = os.path.join(os.fsencode(program_path), program)
  943. native_fullpath = fullpath
  944. arguments = [b'progname', 'arg1', 'arg2']
  945. else:
  946. program = 'executable'
  947. arguments = ['progname', 'arg1', 'arg2']
  948. fullpath = os.path.join(program_path, program)
  949. if os.name != "nt":
  950. native_fullpath = os.fsencode(fullpath)
  951. else:
  952. native_fullpath = fullpath
  953. env = {'spam': 'beans'}
  954. # test os._execvpe() with an absolute path
  955. with _execvpe_mockup() as calls:
  956. self.assertRaises(RuntimeError,
  957. os._execvpe, fullpath, arguments)
  958. self.assertEqual(len(calls), 1)
  959. self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
  960. # test os._execvpe() with a relative path:
  961. # os.get_exec_path() returns defpath
  962. with _execvpe_mockup(defpath=program_path) as calls:
  963. self.assertRaises(OSError,
  964. os._execvpe, program, arguments, env=env)
  965. self.assertEqual(len(calls), 1)
  966. self.assertSequenceEqual(calls[0],
  967. ('execve', native_fullpath, (arguments, env)))
  968. # test os._execvpe() with a relative path:
  969. # os.get_exec_path() reads the 'PATH' variable
  970. with _execvpe_mockup() as calls:
  971. env_path = env.copy()
  972. if test_type is bytes:
  973. env_path[b'PATH'] = program_path
  974. else:
  975. env_path['PATH'] = program_path
  976. self.assertRaises(OSError,
  977. os._execvpe, program, arguments, env=env_path)
  978. self.assertEqual(len(calls), 1)
  979. self.assertSequenceEqual(calls[0],
  980. ('execve', native_fullpath, (arguments, env_path)))
  981. def test_internal_execvpe_str(self):
  982. self._test_internal_execvpe(str)
  983. if os.name != "nt":
  984. self._test_internal_execvpe(bytes)
  985. class Win32ErrorTests(unittest.TestCase):
  986. def test_rename(self):
  987. self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak")
  988. def test_remove(self):
  989. self.assertRaises(WindowsError, os.remove, support.TESTFN)
  990. def test_chdir(self):
  991. self.assertRaises(WindowsError, os.chdir, support.TESTFN)
  992. def test_mkdir(self):
  993. f = open(support.TESTFN, "w")
  994. try:
  995. self.assertRaises(WindowsError, os.mkdir, support.TESTFN)
  996. finally:
  997. f.close()
  998. os.unlink(support.TESTFN)
  999. def test_utime(self):
  1000. self.assertRaises(WindowsError, os.utime, support.TESTFN, None)
  1001. def test_chmod(self):
  1002. self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0)
  1003. class TestInvalidFD(unittest.TestCase):
  1004. singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
  1005. "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
  1006. #singles.append("close")
  1007. #We omit close because it doesn'r raise an exception on some platforms
  1008. def get_single(f):
  1009. def helper(self):
  1010. if hasattr(os, f):
  1011. self.check(getattr(os, f))
  1012. return helper
  1013. for f in singles:
  1014. locals()["test_"+f] = get_single(f)
  1015. def check(self, f, *args):
  1016. try:
  1017. f(support.make_bad_fd(), *args)
  1018. except OSError as e:
  1019. self.assertEqual(e.errno, errno.EBADF)
  1020. else:
  1021. self.fail("%r didn't raise a OSError with a bad file descriptor"
  1022. % f)
  1023. def test_isatty(self):
  1024. if hasattr(os, "isatty"):
  1025. self.assertEqual(os.isatty(support.make_bad_fd()), False)
  1026. def test_closerange(self):
  1027. if hasattr(os, "closerange"):
  1028. fd = support.make_bad_fd()
  1029. # Make sure none of the descriptors we are about to close are
  1030. # currently valid (issue 6542).
  1031. for i in range(10):
  1032. try: os.fstat(fd+i)
  1033. except OSError:
  1034. pass
  1035. else:
  1036. break
  1037. if i < 2:
  1038. raise unittest.SkipTest(
  1039. "Unable to acquire a range of invalid file descriptors")
  1040. self.assertEqual(os.closerange(fd, fd + i-1), None)
  1041. def test_dup2(self):
  1042. if hasattr(os, "dup2"):
  1043. self.check(os.dup2, 20)
  1044. def test_fchmod(self):
  1045. if hasattr(os, "fchmod"):
  1046. self.check(os.fchmod, 0)
  1047. def test_fchown(self):
  1048. if hasattr(os, "fchown"):
  1049. self.check(os.fchown, -1, -1)
  1050. def test_fpathconf(self):
  1051. if hasattr(os, "fpathconf"):
  1052. self.check(os.pathconf, "PC_NAME_MAX")
  1053. self.check(os.fpathconf, "PC_NAME_MAX")
  1054. def test_ftruncate(self):
  1055. if hasattr(os, "ftruncate"):
  1056. self.check(os.truncate, 0)
  1057. self.check(os.ftruncate, 0)
  1058. def test_lseek(self):
  1059. if hasattr(os, "lseek"):
  1060. self.check(os.lseek, 0, 0)
  1061. def test_read(self):
  1062. if hasattr(os, "read"):
  1063. self.check(os.read, 1)
  1064. def test_tcsetpgrpt(self):
  1065. if hasattr(os, "tcsetpgrp"):
  1066. self.check(os.tcsetpgrp, 0)
  1067. def test_write(self):
  1068. if hasattr(os, "write"):
  1069. self.check(os.write, b" ")
  1070. class LinkTests(unittest.TestCase):
  1071. def setUp(self):
  1072. self.file1 = support.TESTFN
  1073. self.file2 = os.path.join(support.TESTFN + "2")
  1074. def tearDown(self):
  1075. for file in (self.file1, self.file2):
  1076. if os.path.exists(file):
  1077. os.unlink(file)
  1078. def _test_link(self, file1, file2):
  1079. with open(file1, "w") as f1:
  1080. f1.write("test")
  1081. with warnings.catch_warnings():
  1082. warnings.simplefilter("ignore", DeprecationWarning)
  1083. os.link(file1, file2)
  1084. with open(file1, "r") as f1, open(file2, "r") as f2:
  1085. self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
  1086. def test_link(self):
  1087. self._test_link(self.file1, self.file2)
  1088. def test_link_bytes(self):
  1089. self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
  1090. bytes(self.file2, sys.getfilesystemencoding()))
  1091. def test_unicode_name(self):
  1092. try:
  1093. os.fsencode("\xf1")
  1094. except UnicodeError:
  1095. raise unittest.SkipTest("Unable to encode for this platform.")
  1096. self.file1 += "\xf1"
  1097. self.file2 = self.file1 + "2"
  1098. self._test_link(self.file1, self.file2)
  1099. if sys.platform != 'win32':
  1100. class Win32ErrorTests(unittest.TestCase):
  1101. pass
  1102. class PosixUidGidTests(unittest.TestCase):
  1103. if hasattr(os, 'setuid'):
  1104. def test_setuid(self):
  1105. if os.getuid() != 0:
  1106. self.assertRaises(os.error, os.setuid, 0)
  1107. self.assertRaises(OverflowError, os.setuid, 1<<32)
  1108. if hasattr(os, 'setgid'):
  1109. def test_setgid(self):
  1110. if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
  1111. self.assertRaises(os.error, os.setgid, 0)
  1112. self.assertRaises(OverflowError, os.setgid, 1<<32)
  1113. if hasattr(os, 'seteuid'):
  1114. def test_seteuid(self):
  1115. if os.getuid() != 0:
  1116. self.assertRaises(os.error, os.seteuid, 0)
  1117. self.assertRaises(OverflowError, os.seteuid, 1<<32)
  1118. if hasattr(os, 'setegid'):
  1119. def test_setegid(self):
  1120. if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
  1121. self.assertRaises(os.error, os.setegid, 0)
  1122. self.assertRaises(OverflowError, os.setegid, 1<<32)
  1123. if hasattr(os, 'setreuid'):
  1124. def test_setreuid(self):
  1125. if os.getuid() != 0:
  1126. self.assertRaises(os.error, os.setreuid, 0, 0)
  1127. self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
  1128. self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
  1129. def test_setreuid_neg1(self):
  1130. # Needs to accept -1. We run this in a subprocess to avoid
  1131. # altering the test runner's process state (issue8045).
  1132. subprocess.check_call([
  1133. sys.executable, '-c',
  1134. 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
  1135. if hasattr(os, 'setregid'):
  1136. def test_setregid(self):
  1137. if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
  1138. self.assertRaises(os.error, os.setregid, 0, 0)
  1139. self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
  1140. self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
  1141. def test_setregid_neg1(self):
  1142. # Needs to accept -1. We run this in a subprocess to avoid
  1143. # altering the test runner's process state (issue8045).
  1144. subprocess.check_call([
  1145. sys.executable, '-c',
  1146. 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
  1147. class Pep383Tests(unittest.TestCase):
  1148. def setUp(self):
  1149. if support.TESTFN_UNENCODABLE:
  1150. self.dir = support.TESTFN_UNENCODABLE
  1151. elif support.TESTFN_NONASCII:
  1152. self.dir = support.TESTFN_NONASCII
  1153. else:
  1154. self.dir = support.TESTFN
  1155. self.bdir = os.fsencode(self.dir)
  1156. bytesfn = []
  1157. def add_filename(fn):
  1158. try:
  1159. fn = os.fsencode(fn)
  1160. except UnicodeEncodeError:
  1161. return
  1162. bytesfn.append(fn)
  1163. add_filename(support.TESTFN_UNICODE)
  1164. if support.TESTFN_UNENCODABLE:
  1165. add_filename(support.TE