blob: 042665b58c985e5e4130c532861dbcd060a8247d [file] [log] [blame]
Neal Norwitze241ce82003-02-17 18:17:05 +00001"Test posix functions"
2
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
R. David Murrayeb3615d2009-04-22 02:24:39 +00004
5# Skip these tests if there is no posix module.
6posix = support.import_module('posix')
Neal Norwitze241ce82003-02-17 18:17:05 +00007
Antoine Pitroub7572f02009-12-02 20:46:48 +00008import errno
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00009import sys
Neal Norwitze241ce82003-02-17 18:17:05 +000010import time
11import os
Charles-François Nataliab2d58e2012-04-17 19:48:35 +020012import platform
Christian Heimesd5e2b6f2008-03-19 21:50:51 +000013import pwd
Benjamin Petersondcf97b92008-07-02 17:30:14 +000014import shutil
Benjamin Peterson052a02b2010-08-17 01:27:09 +000015import stat
Ned Deilyba2eab22011-07-26 13:53:55 -070016import tempfile
Neal Norwitze241ce82003-02-17 18:17:05 +000017import unittest
18import warnings
R. David Murraya21e4ca2009-03-31 23:16:50 +000019
Ned Deilyba2eab22011-07-26 13:53:55 -070020_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
21 support.TESTFN + '-dummy-symlink')
Neal Norwitze241ce82003-02-17 18:17:05 +000022
23class PosixTester(unittest.TestCase):
24
25 def setUp(self):
26 # create empty file
Benjamin Petersonee8712c2008-05-20 21:35:26 +000027 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +000028 fp.close()
Ned Deily3eb67d52011-06-28 00:00:28 -070029 self.teardown_files = [ support.TESTFN ]
Brett Cannonc8d502e2010-03-20 21:53:28 +000030 self._warnings_manager = support.check_warnings()
31 self._warnings_manager.__enter__()
32 warnings.filterwarnings('ignore', '.* potential security risk .*',
33 RuntimeWarning)
Neal Norwitze241ce82003-02-17 18:17:05 +000034
35 def tearDown(self):
Ned Deily3eb67d52011-06-28 00:00:28 -070036 for teardown_file in self.teardown_files:
37 support.unlink(teardown_file)
Brett Cannonc8d502e2010-03-20 21:53:28 +000038 self._warnings_manager.__exit__(None, None, None)
Neal Norwitze241ce82003-02-17 18:17:05 +000039
40 def testNoArgFunctions(self):
41 # test posix functions which take no arguments and have
42 # no side-effects which we need to cleanup (e.g., fork, wait, abort)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000043 NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
Guido van Rossum687b9c02007-10-25 23:18:51 +000044 "times", "getloadavg",
Neal Norwitze241ce82003-02-17 18:17:05 +000045 "getegid", "geteuid", "getgid", "getgroups",
46 "getpid", "getpgrp", "getppid", "getuid",
47 ]
Neal Norwitz71b13e82003-02-23 22:12:24 +000048
Neal Norwitze241ce82003-02-17 18:17:05 +000049 for name in NO_ARG_FUNCTIONS:
50 posix_func = getattr(posix, name, None)
51 if posix_func is not None:
52 posix_func()
Neal Norwitz2ff51a82003-02-17 22:40:31 +000053 self.assertRaises(TypeError, posix_func, 1)
Neal Norwitze241ce82003-02-17 18:17:05 +000054
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000055 if hasattr(posix, 'getresuid'):
56 def test_getresuid(self):
57 user_ids = posix.getresuid()
58 self.assertEqual(len(user_ids), 3)
59 for val in user_ids:
60 self.assertGreaterEqual(val, 0)
61
62 if hasattr(posix, 'getresgid'):
63 def test_getresgid(self):
64 group_ids = posix.getresgid()
65 self.assertEqual(len(group_ids), 3)
66 for val in group_ids:
67 self.assertGreaterEqual(val, 0)
68
69 if hasattr(posix, 'setresuid'):
70 def test_setresuid(self):
71 current_user_ids = posix.getresuid()
72 self.assertIsNone(posix.setresuid(*current_user_ids))
73 # -1 means don't change that value.
74 self.assertIsNone(posix.setresuid(-1, -1, -1))
75
76 def test_setresuid_exception(self):
77 # Don't do this test if someone is silly enough to run us as root.
78 current_user_ids = posix.getresuid()
79 if 0 not in current_user_ids:
80 new_user_ids = (current_user_ids[0]+1, -1, -1)
81 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
82
83 if hasattr(posix, 'setresgid'):
84 def test_setresgid(self):
85 current_group_ids = posix.getresgid()
86 self.assertIsNone(posix.setresgid(*current_group_ids))
87 # -1 means don't change that value.
88 self.assertIsNone(posix.setresgid(-1, -1, -1))
89
90 def test_setresgid_exception(self):
91 # Don't do this test if someone is silly enough to run us as root.
92 current_group_ids = posix.getresgid()
93 if 0 not in current_group_ids:
94 new_group_ids = (current_group_ids[0]+1, -1, -1)
95 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
96
Antoine Pitroub7572f02009-12-02 20:46:48 +000097 @unittest.skipUnless(hasattr(posix, 'initgroups'),
98 "test needs os.initgroups()")
99 def test_initgroups(self):
100 # It takes a string and an integer; check that it raises a TypeError
101 # for other argument lists.
102 self.assertRaises(TypeError, posix.initgroups)
103 self.assertRaises(TypeError, posix.initgroups, None)
104 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
105 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
106
107 # If a non-privileged user invokes it, it should fail with OSError
108 # EPERM.
109 if os.getuid() != 0:
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200110 try:
111 name = pwd.getpwuid(posix.getuid()).pw_name
112 except KeyError:
113 # the current UID may not have a pwd entry
114 raise unittest.SkipTest("need a pwd entry")
Antoine Pitroub7572f02009-12-02 20:46:48 +0000115 try:
116 posix.initgroups(name, 13)
117 except OSError as e:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000118 self.assertEqual(e.errno, errno.EPERM)
Antoine Pitroub7572f02009-12-02 20:46:48 +0000119 else:
120 self.fail("Expected OSError to be raised by initgroups")
121
Neal Norwitze241ce82003-02-17 18:17:05 +0000122 def test_statvfs(self):
123 if hasattr(posix, 'statvfs'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000124 self.assertTrue(posix.statvfs(os.curdir))
Neal Norwitze241ce82003-02-17 18:17:05 +0000125
126 def test_fstatvfs(self):
127 if hasattr(posix, 'fstatvfs'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000128 fp = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000129 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000130 self.assertTrue(posix.fstatvfs(fp.fileno()))
Neal Norwitze241ce82003-02-17 18:17:05 +0000131 finally:
132 fp.close()
133
134 def test_ftruncate(self):
135 if hasattr(posix, 'ftruncate'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000136 fp = open(support.TESTFN, 'w+')
Neal Norwitze241ce82003-02-17 18:17:05 +0000137 try:
138 # we need to have some data to truncate
139 fp.write('test')
140 fp.flush()
141 posix.ftruncate(fp.fileno(), 0)
142 finally:
143 fp.close()
144
145 def test_dup(self):
146 if hasattr(posix, 'dup'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000147 fp = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000148 try:
149 fd = posix.dup(fp.fileno())
Ezio Melottie9615932010-01-24 19:26:24 +0000150 self.assertIsInstance(fd, int)
Neal Norwitze241ce82003-02-17 18:17:05 +0000151 os.close(fd)
152 finally:
153 fp.close()
154
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000155 def test_confstr(self):
156 if hasattr(posix, 'confstr'):
157 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
158 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
159
Neal Norwitze241ce82003-02-17 18:17:05 +0000160 def test_dup2(self):
161 if hasattr(posix, 'dup2'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000162 fp1 = open(support.TESTFN)
163 fp2 = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000164 try:
165 posix.dup2(fp1.fileno(), fp2.fileno())
166 finally:
167 fp1.close()
168 fp2.close()
169
Skip Montanaro98470002005-06-17 01:14:49 +0000170 def test_osexlock(self):
171 if hasattr(posix, "O_EXLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000172 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000173 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000174 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000175 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
176 os.close(fd)
177
178 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000179 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000180 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000181 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000182 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
183 os.close(fd)
184
185 def test_osshlock(self):
186 if hasattr(posix, "O_SHLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000187 fd1 = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000188 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000189 fd2 = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000190 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
191 os.close(fd2)
192 os.close(fd1)
193
194 if hasattr(posix, "O_EXLOCK"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000195 fd = os.open(support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000196 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000197 self.assertRaises(OSError, os.open, support.TESTFN,
Skip Montanaro98470002005-06-17 01:14:49 +0000198 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
199 os.close(fd)
200
Neal Norwitze241ce82003-02-17 18:17:05 +0000201 def test_fstat(self):
202 if hasattr(posix, 'fstat'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000203 fp = open(support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000204 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000205 self.assertTrue(posix.fstat(fp.fileno()))
Neal Norwitze241ce82003-02-17 18:17:05 +0000206 finally:
207 fp.close()
208
209 def test_stat(self):
210 if hasattr(posix, 'stat'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000211 self.assertTrue(posix.stat(support.TESTFN))
Neal Norwitze241ce82003-02-17 18:17:05 +0000212
Benjamin Peterson052a02b2010-08-17 01:27:09 +0000213 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
214 def test_mkfifo(self):
215 support.unlink(support.TESTFN)
216 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
217 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
218
219 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
220 "don't have mknod()/S_IFIFO")
221 def test_mknod(self):
222 # Test using mknod() to create a FIFO (the only use specified
223 # by POSIX).
224 support.unlink(support.TESTFN)
225 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
226 try:
227 posix.mknod(support.TESTFN, mode, 0)
228 except OSError as e:
229 # Some old systems don't allow unprivileged users to use
230 # mknod(), or only support creating device nodes.
231 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
232 else:
233 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
234
Serhiy Storchakae4ad8aa2013-02-12 09:24:16 +0200235 def _test_all_chown_common(self, chown_func, first_param, stat_func):
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000236 """Common code for chown, fchown and lchown tests."""
Serhiy Storchakae4ad8aa2013-02-12 09:24:16 +0200237 def check_stat():
238 if stat_func is not None:
239 stat = stat_func(first_param)
240 self.assertEqual(stat.st_uid, os.getuid())
241 self.assertEqual(stat.st_gid, os.getgid())
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200242 # test a successful chown call
243 chown_func(first_param, os.getuid(), os.getgid())
Serhiy Storchakae4ad8aa2013-02-12 09:24:16 +0200244 check_stat()
245 chown_func(first_param, -1, os.getgid())
246 check_stat()
247 chown_func(first_param, os.getuid(), -1)
248 check_stat()
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200249
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000250 if os.getuid() == 0:
251 try:
252 # Many linux distros have a nfsnobody user as MAX_UID-2
253 # that makes a good test case for signedness issues.
254 # http://bugs.python.org/issue1747858
255 # This part of the test only runs when run as root.
256 # Only scary people run their tests as root.
257 ent = pwd.getpwnam('nfsnobody')
258 chown_func(first_param, ent.pw_uid, ent.pw_gid)
259 except KeyError:
260 pass
Charles-François Nataliab2d58e2012-04-17 19:48:35 +0200261 elif platform.system() in ('HP-UX', 'SunOS'):
262 # HP-UX and Solaris can allow a non-root user to chown() to root
263 # (issue #5113)
264 raise unittest.SkipTest("Skipping because of non-standard chown() "
265 "behavior")
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000266 else:
267 # non-root cannot chown to root, raises OSError
Serhiy Storchakae4ad8aa2013-02-12 09:24:16 +0200268 self.assertRaises(OSError, chown_func, first_param, 0, 0)
269 check_stat()
270 self.assertRaises(OSError, chown_func, first_param, -1, 0)
271 check_stat()
272 self.assertRaises(OSError, chown_func, first_param, 0, -1)
273 check_stat()
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000274
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000275 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
276 def test_chown(self):
277 # raise an OSError if the file does not exist
278 os.unlink(support.TESTFN)
279 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000280
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000281 # re-create the file
282 open(support.TESTFN, 'w').close()
Serhiy Storchakae4ad8aa2013-02-12 09:24:16 +0200283 self._test_all_chown_common(posix.chown, support.TESTFN,
284 getattr(posix, 'stat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000285
286 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
287 def test_fchown(self):
288 os.unlink(support.TESTFN)
289
290 # re-create the file
291 test_file = open(support.TESTFN, 'w')
292 try:
293 fd = test_file.fileno()
Serhiy Storchakae4ad8aa2013-02-12 09:24:16 +0200294 self._test_all_chown_common(posix.fchown, fd,
295 getattr(posix, 'fstat', None))
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000296 finally:
297 test_file.close()
298
299 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
300 def test_lchown(self):
301 os.unlink(support.TESTFN)
302 # create a symlink
Ned Deily3eb67d52011-06-28 00:00:28 -0700303 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
Serhiy Storchakae4ad8aa2013-02-12 09:24:16 +0200304 self._test_all_chown_common(posix.lchown, support.TESTFN,
305 getattr(posix, 'lstat', None))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000306
Neal Norwitze241ce82003-02-17 18:17:05 +0000307 def test_chdir(self):
308 if hasattr(posix, 'chdir'):
309 posix.chdir(os.curdir)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000310 self.assertRaises(OSError, posix.chdir, support.TESTFN)
Neal Norwitze241ce82003-02-17 18:17:05 +0000311
Martin v. Löwisc9e1c7d2010-07-23 12:16:41 +0000312 def test_listdir(self):
313 if hasattr(posix, 'listdir'):
314 self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
315
316 def test_listdir_default(self):
317 # When listdir is called without argument, it's the same as listdir(os.curdir)
318 if hasattr(posix, 'listdir'):
319 self.assertTrue(support.TESTFN in posix.listdir())
Neal Norwitze241ce82003-02-17 18:17:05 +0000320
321 def test_access(self):
322 if hasattr(posix, 'access'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000323 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
Neal Norwitze241ce82003-02-17 18:17:05 +0000324
325 def test_umask(self):
326 if hasattr(posix, 'umask'):
327 old_mask = posix.umask(0)
Ezio Melottie9615932010-01-24 19:26:24 +0000328 self.assertIsInstance(old_mask, int)
Neal Norwitze241ce82003-02-17 18:17:05 +0000329 posix.umask(old_mask)
330
331 def test_strerror(self):
332 if hasattr(posix, 'strerror'):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000333 self.assertTrue(posix.strerror(0))
Neal Norwitze241ce82003-02-17 18:17:05 +0000334
335 def test_pipe(self):
336 if hasattr(posix, 'pipe'):
337 reader, writer = posix.pipe()
338 os.close(reader)
339 os.close(writer)
340
Neal Norwitze241ce82003-02-17 18:17:05 +0000341 def test_utime(self):
342 if hasattr(posix, 'utime'):
343 now = time.time()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000344 posix.utime(support.TESTFN, None)
345 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
346 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
347 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
348 posix.utime(support.TESTFN, (int(now), int(now)))
349 posix.utime(support.TESTFN, (now, now))
Neal Norwitze241ce82003-02-17 18:17:05 +0000350
Ned Deily3eb67d52011-06-28 00:00:28 -0700351 def _test_chflags_regular_file(self, chflags_func, target_file):
352 st = os.stat(target_file)
353 self.assertTrue(hasattr(st, 'st_flags'))
Trent Nelsonee253eb2012-08-21 23:41:43 +0000354
355 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
356 try:
357 chflags_func(target_file, st.st_flags | stat.UF_IMMUTABLE)
358 except OSError as err:
359 if err.errno != errno.EOPNOTSUPP:
360 raise
361 msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
362 self.skipTest(msg)
363
Ned Deily3eb67d52011-06-28 00:00:28 -0700364 try:
365 new_st = os.stat(target_file)
366 self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
367 try:
368 fd = open(target_file, 'w+')
369 except IOError as e:
370 self.assertEqual(e.errno, errno.EPERM)
371 finally:
372 posix.chflags(target_file, st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000373
Ned Deily3eb67d52011-06-28 00:00:28 -0700374 @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
375 def test_chflags(self):
376 self._test_chflags_regular_file(posix.chflags, support.TESTFN)
377
378 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
379 def test_lchflags_regular_file(self):
380 self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
381
382 @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
383 def test_lchflags_symlink(self):
384 testfn_st = os.stat(support.TESTFN)
385
386 self.assertTrue(hasattr(testfn_st, 'st_flags'))
387
388 os.symlink(support.TESTFN, _DUMMY_SYMLINK)
389 self.teardown_files.append(_DUMMY_SYMLINK)
390 dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
391
Trent Nelsonee253eb2012-08-21 23:41:43 +0000392 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
393 try:
394 posix.lchflags(_DUMMY_SYMLINK,
395 dummy_symlink_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
Ned Deily3eb67d52011-06-28 00:00:28 -0700402 try:
403 new_testfn_st = os.stat(support.TESTFN)
404 new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
405
406 self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
407 self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
408 new_dummy_symlink_st.st_flags)
409 finally:
410 posix.lchflags(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000411
Guido van Rossum98297ee2007-11-06 21:34:58 +0000412 def test_environ(self):
Victor Stinner17b490d2010-05-06 22:19:30 +0000413 if os.name == "nt":
414 item_type = str
415 else:
416 item_type = bytes
Guido van Rossum98297ee2007-11-06 21:34:58 +0000417 for k, v in posix.environ.items():
Victor Stinner17b490d2010-05-06 22:19:30 +0000418 self.assertEqual(type(k), item_type)
419 self.assertEqual(type(v), item_type)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000420
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000421 def test_getcwd_long_pathnames(self):
422 if hasattr(posix, 'getcwd'):
423 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
424 curdir = os.getcwd()
425 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
426
427 try:
428 os.mkdir(base_path)
429 os.chdir(base_path)
430 except:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000431# Just returning nothing instead of the SkipTest exception,
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000432# because the test results in Error in that case.
433# Is that ok?
Benjamin Petersone549ead2009-03-28 21:42:05 +0000434# raise unittest.SkipTest("cannot create directory for testing")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000435 return
436
437 def _create_and_do_getcwd(dirname, current_path_length = 0):
438 try:
439 os.mkdir(dirname)
440 except:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000441 raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000442
443 os.chdir(dirname)
444 try:
445 os.getcwd()
446 if current_path_length < 1027:
447 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
448 finally:
449 os.chdir('..')
450 os.rmdir(dirname)
451
452 _create_and_do_getcwd(dirname)
453
454 finally:
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000455 os.chdir(curdir)
R. David Murray414c91f2009-07-09 20:12:31 +0000456 support.rmtree(base_path)
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000457
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000458 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000459 def test_getgroups(self):
460 with os.popen('id -G') as idg:
461 groups = idg.read().strip()
Charles-François Natalie8a255a2012-05-02 20:01:38 +0200462 ret = idg.close()
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000463
Charles-François Natali39687ee2012-05-02 20:49:14 +0200464 if ret != None or not groups:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000465 raise unittest.SkipTest("need working 'id -G'")
466
Ned Deily028915e2013-02-02 15:08:52 -0800467 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
468 if sys.platform == 'darwin':
469 import sysconfig
470 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
471 if float(dt) < 10.6:
472 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
473
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000474 # 'id -G' and 'os.getgroups()' should return the same
475 # groups, ignoring order and duplicates.
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000476 # #10822 - it is implementation defined whether posix.getgroups()
477 # includes the effective gid so we include it anyway, since id -G does
Ronald Oussorencb615e62010-07-24 14:15:19 +0000478 self.assertEqual(
Ronald Oussoren7fb6f512010-08-01 19:18:13 +0000479 set([int(x) for x in groups.split()]),
Antoine Pitrou318b8f32011-01-12 18:45:27 +0000480 set(posix.getgroups() + [posix.getegid()]))
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000481
482class PosixGroupsTester(unittest.TestCase):
483
484 def setUp(self):
485 if posix.getuid() != 0:
486 raise unittest.SkipTest("not enough privileges")
487 if not hasattr(posix, 'getgroups'):
488 raise unittest.SkipTest("need posix.getgroups")
489 if sys.platform == 'darwin':
490 raise unittest.SkipTest("getgroups(2) is broken on OSX")
491 self.saved_groups = posix.getgroups()
492
493 def tearDown(self):
494 if hasattr(posix, 'setgroups'):
495 posix.setgroups(self.saved_groups)
496 elif hasattr(posix, 'initgroups'):
497 name = pwd.getpwuid(posix.getuid()).pw_name
498 posix.initgroups(name, self.saved_groups[0])
499
500 @unittest.skipUnless(hasattr(posix, 'initgroups'),
501 "test needs posix.initgroups()")
502 def test_initgroups(self):
503 # find missing group
504
Antoine Pitroue5a91012010-09-04 17:32:06 +0000505 g = max(self.saved_groups) + 1
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000506 name = pwd.getpwuid(posix.getuid()).pw_name
507 posix.initgroups(name, g)
508 self.assertIn(g, posix.getgroups())
509
510 @unittest.skipUnless(hasattr(posix, 'setgroups'),
511 "test needs posix.setgroups()")
512 def test_setgroups(self):
Antoine Pitroue5a91012010-09-04 17:32:06 +0000513 for groups in [[0], list(range(16))]:
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000514 posix.setgroups(groups)
515 self.assertListEqual(groups, posix.getgroups())
516
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000517
Neal Norwitze241ce82003-02-17 18:17:05 +0000518def test_main():
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +0000519 support.run_unittest(PosixTester, PosixGroupsTester)
Neal Norwitze241ce82003-02-17 18:17:05 +0000520
521if __name__ == '__main__':
522 test_main()