test_posix.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. "Test posix functions"
  2. from test import test_support
  3. # Skip these tests if there is no posix module.
  4. posix = test_support.import_module('posix')
  5. import errno
  6. import sys
  7. import time
  8. import os
  9. import platform
  10. import pwd
  11. import shutil
  12. import stat
  13. import sys
  14. import tempfile
  15. import unittest
  16. import warnings
  17. _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
  18. test_support.TESTFN + '-dummy-symlink')
  19. warnings.filterwarnings('ignore', '.* potential security risk .*',
  20. RuntimeWarning)
  21. class PosixTester(unittest.TestCase):
  22. def setUp(self):
  23. # create empty file
  24. fp = open(test_support.TESTFN, 'w+')
  25. fp.close()
  26. self.teardown_files = [ test_support.TESTFN ]
  27. def tearDown(self):
  28. for teardown_file in self.teardown_files:
  29. os.unlink(teardown_file)
  30. def testNoArgFunctions(self):
  31. # test posix functions which take no arguments and have
  32. # no side-effects which we need to cleanup (e.g., fork, wait, abort)
  33. NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname",
  34. "times", "getloadavg", "tmpnam",
  35. "getegid", "geteuid", "getgid", "getgroups",
  36. "getpid", "getpgrp", "getppid", "getuid",
  37. ]
  38. with warnings.catch_warnings():
  39. warnings.filterwarnings("ignore", "", DeprecationWarning)
  40. for name in NO_ARG_FUNCTIONS:
  41. posix_func = getattr(posix, name, None)
  42. if posix_func is not None:
  43. posix_func()
  44. self.assertRaises(TypeError, posix_func, 1)
  45. @unittest.skipUnless(hasattr(posix, 'getresuid'),
  46. 'test needs posix.getresuid()')
  47. def test_getresuid(self):
  48. user_ids = posix.getresuid()
  49. self.assertEqual(len(user_ids), 3)
  50. for val in user_ids:
  51. self.assertGreaterEqual(val, 0)
  52. @unittest.skipUnless(hasattr(posix, 'getresgid'),
  53. 'test needs posix.getresgid()')
  54. def test_getresgid(self):
  55. group_ids = posix.getresgid()
  56. self.assertEqual(len(group_ids), 3)
  57. for val in group_ids:
  58. self.assertGreaterEqual(val, 0)
  59. @unittest.skipUnless(hasattr(posix, 'setresuid'),
  60. 'test needs posix.setresuid()')
  61. def test_setresuid(self):
  62. current_user_ids = posix.getresuid()
  63. self.assertIsNone(posix.setresuid(*current_user_ids))
  64. # -1 means don't change that value.
  65. self.assertIsNone(posix.setresuid(-1, -1, -1))
  66. @unittest.skipUnless(hasattr(posix, 'setresuid'),
  67. 'test needs posix.setresuid()')
  68. def test_setresuid_exception(self):
  69. # Don't do this test if someone is silly enough to run us as root.
  70. current_user_ids = posix.getresuid()
  71. if 0 not in current_user_ids:
  72. new_user_ids = (current_user_ids[0]+1, -1, -1)
  73. self.assertRaises(OSError, posix.setresuid, *new_user_ids)
  74. @unittest.skipUnless(hasattr(posix, 'setresgid'),
  75. 'test needs posix.setresgid()')
  76. def test_setresgid(self):
  77. current_group_ids = posix.getresgid()
  78. self.assertIsNone(posix.setresgid(*current_group_ids))
  79. # -1 means don't change that value.
  80. self.assertIsNone(posix.setresgid(-1, -1, -1))
  81. @unittest.skipUnless(hasattr(posix, 'setresgid'),
  82. 'test needs posix.setresgid()')
  83. def test_setresgid_exception(self):
  84. # Don't do this test if someone is silly enough to run us as root.
  85. current_group_ids = posix.getresgid()
  86. if 0 not in current_group_ids:
  87. new_group_ids = (current_group_ids[0]+1, -1, -1)
  88. self.assertRaises(OSError, posix.setresgid, *new_group_ids)
  89. @unittest.skipUnless(hasattr(posix, 'initgroups'),
  90. "test needs os.initgroups()")
  91. def test_initgroups(self):
  92. # It takes a string and an integer; check that it raises a TypeError
  93. # for other argument lists.
  94. self.assertRaises(TypeError, posix.initgroups)
  95. self.assertRaises(TypeError, posix.initgroups, None)
  96. self.assertRaises(TypeError, posix.initgroups, 3, "foo")
  97. self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
  98. # If a non-privileged user invokes it, it should fail with OSError
  99. # EPERM.
  100. if os.getuid() != 0:
  101. try:
  102. name = pwd.getpwuid(posix.getuid()).pw_name
  103. except KeyError:
  104. # the current UID may not have a pwd entry
  105. raise unittest.SkipTest("need a pwd entry")
  106. try:
  107. posix.initgroups(name, 13)
  108. except OSError as e:
  109. self.assertEqual(e.errno, errno.EPERM)
  110. else:
  111. self.fail("Expected OSError to be raised by initgroups")
  112. @unittest.skipUnless(hasattr(posix, 'statvfs'),
  113. 'test needs posix.statvfs()')
  114. def test_statvfs(self):
  115. self.assertTrue(posix.statvfs(os.curdir))
  116. @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
  117. 'test needs posix.fstatvfs()')
  118. def test_fstatvfs(self):
  119. fp = open(test_support.TESTFN)
  120. try:
  121. self.assertTrue(posix.fstatvfs(fp.fileno()))
  122. finally:
  123. fp.close()
  124. @unittest.skipUnless(hasattr(posix, 'ftruncate'),
  125. 'test needs posix.ftruncate()')
  126. def test_ftruncate(self):
  127. fp = open(test_support.TESTFN, 'w+')
  128. try:
  129. # we need to have some data to truncate
  130. fp.write('test')
  131. fp.flush()
  132. posix.ftruncate(fp.fileno(), 0)
  133. finally:
  134. fp.close()
  135. @unittest.skipUnless(hasattr(posix, 'dup'),
  136. 'test needs posix.dup()')
  137. def test_dup(self):
  138. fp = open(test_support.TESTFN)
  139. try:
  140. fd = posix.dup(fp.fileno())
  141. self.assertIsInstance(fd, int)
  142. os.close(fd)
  143. finally:
  144. fp.close()
  145. @unittest.skipUnless(hasattr(posix, 'confstr'),
  146. 'test needs posix.confstr()')
  147. def test_confstr(self):
  148. self.assertRaises(ValueError, posix.confstr, "CS_garbage")
  149. self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
  150. @unittest.skipUnless(hasattr(posix, 'dup2'),
  151. 'test needs posix.dup2()')
  152. def test_dup2(self):
  153. fp1 = open(test_support.TESTFN)
  154. fp2 = open(test_support.TESTFN)
  155. try:
  156. posix.dup2(fp1.fileno(), fp2.fileno())
  157. finally:
  158. fp1.close()
  159. fp2.close()
  160. def fdopen_helper(self, *args):
  161. fd = os.open(test_support.TESTFN, os.O_RDONLY)
  162. fp2 = posix.fdopen(fd, *args)
  163. fp2.close()
  164. @unittest.skipUnless(hasattr(posix, 'fdopen'),
  165. 'test needs posix.fdopen()')
  166. def test_fdopen(self):
  167. self.fdopen_helper()
  168. self.fdopen_helper('r')
  169. self.fdopen_helper('r', 100)
  170. @unittest.skipUnless(hasattr(posix, 'fdopen'),
  171. 'test needs posix.fdopen()')
  172. def test_fdopen_directory(self):
  173. try:
  174. fd = os.open('.', os.O_RDONLY)
  175. except OSError as e:
  176. self.assertEqual(e.errno, errno.EACCES)
  177. self.skipTest("system cannot open directories")
  178. with self.assertRaises(IOError) as cm:
  179. os.fdopen(fd, 'r')
  180. self.assertEqual(cm.exception.errno, errno.EISDIR)
  181. @unittest.skipUnless(hasattr(posix, 'fdopen') and
  182. not sys.platform.startswith("sunos"),
  183. 'test needs posix.fdopen()')
  184. def test_fdopen_keeps_fd_open_on_errors(self):
  185. fd = os.open(test_support.TESTFN, os.O_RDONLY)
  186. self.assertRaises(OSError, posix.fdopen, fd, 'w')
  187. os.close(fd) # fd should not be closed.
  188. @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
  189. 'test needs posix.O_EXLOCK')
  190. def test_osexlock(self):
  191. fd = os.open(test_support.TESTFN,
  192. os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
  193. self.assertRaises(OSError, os.open, test_support.TESTFN,
  194. os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
  195. os.close(fd)
  196. if hasattr(posix, "O_SHLOCK"):
  197. fd = os.open(test_support.TESTFN,
  198. os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
  199. self.assertRaises(OSError, os.open, test_support.TESTFN,
  200. os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
  201. os.close(fd)
  202. @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
  203. 'test needs posix.O_SHLOCK')
  204. def test_osshlock(self):
  205. fd1 = os.open(test_support.TESTFN,
  206. os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
  207. fd2 = os.open(test_support.TESTFN,
  208. os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
  209. os.close(fd2)
  210. os.close(fd1)
  211. if hasattr(posix, "O_EXLOCK"):
  212. fd = os.open(test_support.TESTFN,
  213. os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
  214. self.assertRaises(OSError, os.open, test_support.TESTFN,
  215. os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
  216. os.close(fd)
  217. @unittest.skipUnless(hasattr(posix, 'fstat'),
  218. 'test needs posix.fstat()')
  219. def test_fstat(self):
  220. fp = open(test_support.TESTFN)
  221. try:
  222. self.assertTrue(posix.fstat(fp.fileno()))
  223. finally:
  224. fp.close()
  225. @unittest.skipUnless(hasattr(posix, 'stat'),
  226. 'test needs posix.stat()')
  227. def test_stat(self):
  228. self.assertTrue(posix.stat(test_support.TESTFN))
  229. @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
  230. @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
  231. def test_makedev(self):
  232. st = posix.stat(test_support.TESTFN)
  233. dev = st.st_dev
  234. self.assertIsInstance(dev, (int, long))
  235. self.assertGreaterEqual(dev, 0)
  236. major = posix.major(dev)
  237. self.assertIsInstance(major, (int, long))
  238. self.assertGreaterEqual(major, 0)
  239. self.assertEqual(posix.major(int(dev)), major)
  240. self.assertEqual(posix.major(long(dev)), major)
  241. self.assertRaises(TypeError, posix.major, float(dev))
  242. self.assertRaises(TypeError, posix.major)
  243. self.assertRaises((ValueError, OverflowError), posix.major, -1)
  244. minor = posix.minor(dev)
  245. self.assertIsInstance(minor, (int, long))
  246. self.assertGreaterEqual(minor, 0)
  247. self.assertEqual(posix.minor(int(dev)), minor)
  248. self.assertEqual(posix.minor(long(dev)), minor)
  249. self.assertRaises(TypeError, posix.minor, float(dev))
  250. self.assertRaises(TypeError, posix.minor)
  251. self.assertRaises((ValueError, OverflowError), posix.minor, -1)
  252. self.assertEqual(posix.makedev(major, minor), dev)
  253. self.assertEqual(posix.makedev(int(major), int(minor)), dev)
  254. self.assertEqual(posix.makedev(long(major), long(minor)), dev)
  255. self.assertRaises(TypeError, posix.makedev, float(major), minor)
  256. self.assertRaises(TypeError, posix.makedev, major, float(minor))
  257. self.assertRaises(TypeError, posix.makedev, major)
  258. self.assertRaises(TypeError, posix.makedev)
  259. def _test_all_chown_common(self, chown_func, first_param, stat_func):
  260. """Common code for chown, fchown and lchown tests."""
  261. def check_stat(uid, gid):
  262. if stat_func is not None:
  263. stat = stat_func(first_param)
  264. self.assertEqual(stat.st_uid, uid)
  265. self.assertEqual(stat.st_gid, gid)
  266. uid = os.getuid()
  267. gid = os.getgid()
  268. # test a successful chown call
  269. chown_func(first_param, uid, gid)
  270. check_stat(uid, gid)
  271. chown_func(first_param, -1, gid)
  272. check_stat(uid, gid)
  273. chown_func(first_param, uid, -1)
  274. check_stat(uid, gid)
  275. if uid == 0:
  276. # Try an amusingly large uid/gid to make sure we handle
  277. # large unsigned values. (chown lets you use any
  278. # uid/gid you like, even if they aren't defined.)
  279. #
  280. # This problem keeps coming up:
  281. # http://bugs.python.org/issue1747858
  282. # http://bugs.python.org/issue4591
  283. # http://bugs.python.org/issue15301
  284. # Hopefully the fix in 4591 fixes it for good!
  285. #
  286. # This part of the test only runs when run as root.
  287. # Only scary people run their tests as root.
  288. big_value = 2**31
  289. chown_func(first_param, big_value, big_value)
  290. check_stat(big_value, big_value)
  291. chown_func(first_param, -1, -1)
  292. check_stat(big_value, big_value)
  293. chown_func(first_param, uid, gid)
  294. check_stat(uid, gid)
  295. elif platform.system() in ('HP-UX', 'SunOS'):
  296. # HP-UX and Solaris can allow a non-root user to chown() to root
  297. # (issue #5113)
  298. raise unittest.SkipTest("Skipping because of non-standard chown() "
  299. "behavior")
  300. else:
  301. # non-root cannot chown to root, raises OSError
  302. self.assertRaises(OSError, chown_func, first_param, 0, 0)
  303. check_stat(uid, gid)
  304. self.assertRaises(OSError, chown_func, first_param, 0, -1)
  305. check_stat(uid, gid)
  306. if 0 not in os.getgroups():
  307. self.assertRaises(OSError, chown_func, first_param, -1, 0)
  308. check_stat(uid, gid)
  309. # test illegal types
  310. for t in str, float:
  311. self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
  312. check_stat(uid, gid)
  313. self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
  314. check_stat(uid, gid)
  315. @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
  316. def test_chown(self):
  317. # raise an OSError if the file does not exist
  318. os.unlink(test_support.TESTFN)
  319. self.assertRaises(OSError, posix.chown, test_support.TESTFN, -1, -1)
  320. # re-create the file
  321. open(test_support.TESTFN, 'w').close()
  322. self._test_all_chown_common(posix.chown, test_support.TESTFN,
  323. getattr(posix, 'stat', None))
  324. @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
  325. def test_fchown(self):
  326. os.unlink(test_support.TESTFN)
  327. # re-create the file
  328. test_file = open(test_support.TESTFN, 'w')
  329. try:
  330. fd = test_file.fileno()
  331. self._test_all_chown_common(posix.fchown, fd,
  332. getattr(posix, 'fstat', None))
  333. finally:
  334. test_file.close()
  335. @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
  336. def test_lchown(self):
  337. os.unlink(test_support.TESTFN)
  338. # create a symlink
  339. os.symlink(_DUMMY_SYMLINK, test_support.TESTFN)
  340. self._test_all_chown_common(posix.lchown, test_support.TESTFN,
  341. getattr(posix, 'lstat', None))
  342. @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
  343. def test_chdir(self):
  344. posix.chdir(os.curdir)
  345. self.assertRaises(OSError, posix.chdir, test_support.TESTFN)
  346. @unittest.skipUnless(hasattr(posix, 'lsdir'), 'test needs posix.lsdir()')
  347. def test_lsdir(self):
  348. self.assertIn(test_support.TESTFN, posix.lsdir(os.curdir))
  349. @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
  350. def test_access(self):
  351. self.assertTrue(posix.access(test_support.TESTFN, os.R_OK))
  352. @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
  353. def test_umask(self):
  354. old_mask = posix.umask(0)
  355. self.assertIsInstance(old_mask, int)
  356. posix.umask(old_mask)
  357. @unittest.skipUnless(hasattr(posix, 'strerror'),
  358. 'test needs posix.strerror()')
  359. def test_strerror(self):
  360. self.assertTrue(posix.strerror(0))
  361. @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
  362. def test_pipe(self):
  363. reader, writer = posix.pipe()
  364. os.close(reader)
  365. os.close(writer)
  366. @unittest.skipUnless(hasattr(posix, 'tempnam'),
  367. 'test needs posix.tempnam()')
  368. def test_tempnam(self):
  369. with warnings.catch_warnings():
  370. warnings.filterwarnings("ignore", "tempnam", DeprecationWarning)
  371. self.assertTrue(posix.tempnam())
  372. self.assertTrue(posix.tempnam(os.curdir))
  373. self.assertTrue(posix.tempnam(os.curdir, 'blah'))
  374. @unittest.skipUnless(hasattr(posix, 'tmpfile'),
  375. 'test needs posix.tmpfile()')
  376. def test_tmpfile(self):
  377. with warnings.catch_warnings():
  378. warnings.filterwarnings("ignore", "tmpfile", DeprecationWarning)
  379. fp = posix.tmpfile()
  380. fp.close()
  381. @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
  382. def test_utime(self):
  383. now = time.time()
  384. posix.utime(test_support.TESTFN, None)
  385. self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (None, None))
  386. self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (now, None))
  387. self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (None, now))
  388. posix.utime(test_support.TESTFN, (int(now), int(now)))
  389. posix.utime(test_support.TESTFN, (now, now))
  390. def _test_chflags_regular_file(self, chflags_func, target_file):
  391. st = os.stat(target_file)
  392. self.assertTrue(hasattr(st, 'st_flags'))
  393. # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
  394. try:
  395. chflags_func(target_file, st.st_flags | stat.UF_IMMUTABLE)
  396. except OSError as err:
  397. if err.errno != errno.EOPNOTSUPP:
  398. raise
  399. msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
  400. self.skipTest(msg)
  401. try:
  402. new_st = os.stat(target_file)
  403. self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
  404. try:
  405. fd = open(target_file, 'w+')
  406. except IOError as e:
  407. self.assertEqual(e.errno, errno.EPERM)
  408. finally:
  409. posix.chflags(target_file, st.st_flags)
  410. @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
  411. def test_chflags(self):
  412. self._test_chflags_regular_file(posix.chflags, test_support.TESTFN)
  413. @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
  414. def test_lchflags_regular_file(self):
  415. self._test_chflags_regular_file(posix.lchflags, test_support.TESTFN)
  416. @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
  417. def test_lchflags_symlink(self):
  418. testfn_st = os.stat(test_support.TESTFN)
  419. self.assertTrue(hasattr(testfn_st, 'st_flags'))
  420. os.symlink(test_support.TESTFN, _DUMMY_SYMLINK)
  421. self.teardown_files.append(_DUMMY_SYMLINK)
  422. dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
  423. # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
  424. try:
  425. posix.lchflags(_DUMMY_SYMLINK,
  426. dummy_symlink_st.st_flags | stat.UF_IMMUTABLE)
  427. except OSError as err:
  428. if err.errno != errno.EOPNOTSUPP:
  429. raise
  430. msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
  431. self.skipTest(msg)
  432. try:
  433. new_testfn_st = os.stat(test_support.TESTFN)
  434. new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
  435. self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
  436. self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
  437. new_dummy_symlink_st.st_flags)
  438. finally:
  439. posix.lchflags(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
  440. @unittest.skipUnless(hasattr(posix, 'getcwd'),
  441. 'test needs posix.getcwd()')
  442. def test_getcwd_long_pathnames(self):
  443. dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
  444. curdir = os.getcwd()
  445. base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'
  446. try:
  447. os.mkdir(base_path)
  448. os.chdir(base_path)
  449. except:
  450. self.skipTest("cannot create directory for testing")
  451. try:
  452. def _create_and_do_getcwd(dirname, current_path_length = 0):
  453. try:
  454. os.mkdir(dirname)
  455. except:
  456. self.skipTest("mkdir cannot create directory sufficiently "
  457. "deep for getcwd test")
  458. os.chdir(dirname)
  459. try:
  460. os.getcwd()
  461. if current_path_length < 4099:
  462. _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
  463. except OSError as e:
  464. expected_errno = errno.ENAMETOOLONG
  465. # The following platforms have quirky getcwd()
  466. # behaviour -- see issue 9185 and 15765 for
  467. # more information.
  468. quirky_platform = (
  469. 'sunos' in sys.platform or
  470. 'netbsd' in sys.platform or
  471. 'openbsd' in sys.platform
  472. )
  473. if quirky_platform:
  474. expected_errno = errno.ERANGE
  475. self.assertEqual(e.errno, expected_errno)
  476. finally:
  477. os.chdir('..')
  478. os.rmdir(dirname)
  479. _create_and_do_getcwd(dirname)
  480. finally:
  481. os.chdir(curdir)
  482. shutil.rmtree(base_path)
  483. @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
  484. def test_getgroups(self):
  485. with os.popen('id -G 2>/dev/null') as idg:
  486. groups = idg.read().strip()
  487. ret = idg.close()
  488. if ret != None or not groups:
  489. raise unittest.SkipTest("need working 'id -G'")
  490. # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
  491. if sys.platform == 'darwin':
  492. import sysconfig
  493. dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
  494. if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
  495. raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
  496. # 'id -G' and 'os.getgroups()' should return the same
  497. # groups, ignoring order and duplicates.
  498. # #10822 - it is implementation defined whether posix.getgroups()
  499. # includes the effective gid so we include it anyway, since id -G does
  500. self.assertEqual(
  501. set([int(x) for x in groups.split()]),
  502. set(posix.getgroups() + [posix.getegid()]))
  503. class PosixGroupsTester(unittest.TestCase):
  504. def setUp(self):
  505. if posix.getuid() != 0:
  506. raise unittest.SkipTest("not enough privileges")
  507. if not hasattr(posix, 'getgroups'):
  508. raise unittest.SkipTest("need posix.getgroups")
  509. if sys.platform == 'darwin':
  510. raise unittest.SkipTest("getgroups(2) is broken on OSX")
  511. self.saved_groups = posix.getgroups()
  512. def tearDown(self):
  513. if hasattr(posix, 'setgroups'):
  514. posix.setgroups(self.saved_groups)
  515. elif hasattr(posix, 'initgroups'):
  516. name = pwd.getpwuid(posix.getuid()).pw_name
  517. posix.initgroups(name, self.saved_groups[0])
  518. @unittest.skipUnless(hasattr(posix, 'initgroups'),
  519. 'test needs posix.initgroups()')
  520. def test_initgroups(self):
  521. # find missing group
  522. g = max(self.saved_groups or [0]) + 1
  523. name = pwd.getpwuid(posix.getuid()).pw_name
  524. posix.initgroups(name, g)
  525. self.assertIn(g, posix.getgroups())
  526. @unittest.skipUnless(hasattr(posix, 'setgroups'),
  527. 'test needs posix.setgroups()')
  528. def test_setgroups(self):
  529. for groups in [[0], range(16)]:
  530. posix.setgroups(groups)
  531. self.assertListEqual(groups, posix.getgroups())
  532. def test_main():
  533. test_support.run_unittest(PosixTester, PosixGroupsTester)
  534. if __name__ == '__main__':
  535. test_main()