Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(8)

## Delta Between Two Patch Sets: Lib/test/test_posix.py

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 6 years, 9 months ago
Right Patch Set: Created 6 years, 3 months ago
 Left: Base Patch Set 1: None Patch Set 2: None Patch Set 3: None Patch Set 4: None Patch Set 5: None Right: Patch Set 1: None Patch Set 2: None Patch Set 3: None Patch Set 4: None Patch Set 5: None
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_platform.py ('k') | Lib/test/test_property.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Hide Comments ('s')
LEFTRIGHT
1 "Test posix functions" 1 "Test posix functions"
2 2
3 from test import support 3 from test import support
4 4
5 # Skip these tests if there is no posix module. 5 # Skip these tests if there is no posix module.
6 posix = support.import_module('posix') 6 posix = support.import_module('posix')
7 7
8 import errno 8 import errno
9 import sys 9 import sys
10 import time 10 import time
11 import os 11 import os
12 import fcntl 12 import fcntl
13 import platform 13 import platform
14 import pwd 14 import pwd
15 import shutil 15 import shutil
16 import stat 16 import stat
17 import tempfile 17 import tempfile
18 import unittest 18 import unittest
19 import warnings 19 import warnings
20 import _testcapi
21 20
22 _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(), 21 _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
23 support.TESTFN + '-dummy-symlink') 22 support.TESTFN + '-dummy-symlink')
24 23
25 class PosixTester(unittest.TestCase): 24 class PosixTester(unittest.TestCase):
26 25
27 def setUp(self): 26 def setUp(self):
28 # create empty file 27 # create empty file
29 fp = open(support.TESTFN, 'w+') 28 fp = open(support.TESTFN, 'w+')
30 fp.close() 29 fp.close()
(...skipping 16 matching lines...) Expand all
47 "getegid", "geteuid", "getgid", "getgroups", 46 "getegid", "geteuid", "getgid", "getgroups",
48 "getpid", "getpgrp", "getppid", "getuid", "sync", 47 "getpid", "getpgrp", "getppid", "getuid", "sync",
49 ] 48 ]
50 49
51 for name in NO_ARG_FUNCTIONS: 50 for name in NO_ARG_FUNCTIONS:
52 posix_func = getattr(posix, name, None) 51 posix_func = getattr(posix, name, None)
53 if posix_func is not None: 52 if posix_func is not None:
54 posix_func() 53 posix_func()
55 self.assertRaises(TypeError, posix_func, 1) 54 self.assertRaises(TypeError, posix_func, 1)
56 55
57 if hasattr(posix, 'getresuid'): 56 @unittest.skipUnless(hasattr(posix, 'getresuid'),
58 def test_getresuid(self): 57 'test needs posix.getresuid()')
59 user_ids = posix.getresuid() 58 def test_getresuid(self):
60 self.assertEqual(len(user_ids), 3) 59 user_ids = posix.getresuid()
61 for val in user_ids: 60 self.assertEqual(len(user_ids), 3)
62 self.assertGreaterEqual(val, 0) 61 for val in user_ids:
63 62 self.assertGreaterEqual(val, 0)
64 if hasattr(posix, 'getresgid'): 63
65 def test_getresgid(self): 64 @unittest.skipUnless(hasattr(posix, 'getresgid'),
66 group_ids = posix.getresgid() 65 'test needs posix.getresgid()')
67 self.assertEqual(len(group_ids), 3) 66 def test_getresgid(self):
68 for val in group_ids: 67 group_ids = posix.getresgid()
69 self.assertGreaterEqual(val, 0) 68 self.assertEqual(len(group_ids), 3)
70 69 for val in group_ids:
71 if hasattr(posix, 'setresuid'): 70 self.assertGreaterEqual(val, 0)
72 def test_setresuid(self): 71
73 current_user_ids = posix.getresuid() 72 @unittest.skipUnless(hasattr(posix, 'setresuid'),
74 self.assertIsNone(posix.setresuid(*current_user_ids)) 73 'test needs posix.setresuid()')
75 # -1 means don't change that value. 74 def test_setresuid(self):
76 self.assertIsNone(posix.setresuid(-1, -1, -1)) 75 current_user_ids = posix.getresuid()
77 76 self.assertIsNone(posix.setresuid(*current_user_ids))
78 def test_setresuid_exception(self): 77 # -1 means don't change that value.
79 # Don't do this test if someone is silly enough to run us as root. 78 self.assertIsNone(posix.setresuid(-1, -1, -1))
80 current_user_ids = posix.getresuid() 79
81 if 0 not in current_user_ids: 80 @unittest.skipUnless(hasattr(posix, 'setresuid'),
82 new_user_ids = (current_user_ids[0]+1, -1, -1) 81 'test needs posix.setresuid()')
83 self.assertRaises(OSError, posix.setresuid, *new_user_ids) 82 def test_setresuid_exception(self):
84 83 # Don't do this test if someone is silly enough to run us as root.
85 if hasattr(posix, 'setresgid'): 84 current_user_ids = posix.getresuid()
86 def test_setresgid(self): 85 if 0 not in current_user_ids:
87 current_group_ids = posix.getresgid() 86 new_user_ids = (current_user_ids[0]+1, -1, -1)
88 self.assertIsNone(posix.setresgid(*current_group_ids)) 87 self.assertRaises(OSError, posix.setresuid, *new_user_ids)
89 # -1 means don't change that value. 88
90 self.assertIsNone(posix.setresgid(-1, -1, -1)) 89 @unittest.skipUnless(hasattr(posix, 'setresgid'),
91 90 'test needs posix.setresgid()')
92 def test_setresgid_exception(self): 91 def test_setresgid(self):
93 # Don't do this test if someone is silly enough to run us as root. 92 current_group_ids = posix.getresgid()
94 current_group_ids = posix.getresgid() 93 self.assertIsNone(posix.setresgid(*current_group_ids))
95 if 0 not in current_group_ids: 94 # -1 means don't change that value.
96 new_group_ids = (current_group_ids[0]+1, -1, -1) 95 self.assertIsNone(posix.setresgid(-1, -1, -1))
97 self.assertRaises(OSError, posix.setresgid, *new_group_ids) 96
97 @unittest.skipUnless(hasattr(posix, 'setresgid'),
98 'test needs posix.setresgid()')
99 def test_setresgid_exception(self):
100 # Don't do this test if someone is silly enough to run us as root.
101 current_group_ids = posix.getresgid()
102 if 0 not in current_group_ids:
103 new_group_ids = (current_group_ids[0]+1, -1, -1)
104 self.assertRaises(OSError, posix.setresgid, *new_group_ids)
98 105
99 @unittest.skipUnless(hasattr(posix, 'initgroups'), 106 @unittest.skipUnless(hasattr(posix, 'initgroups'),
100 "test needs os.initgroups()") 107 "test needs os.initgroups()")
101 def test_initgroups(self): 108 def test_initgroups(self):
102 # It takes a string and an integer; check that it raises a TypeError 109 # It takes a string and an integer; check that it raises a TypeError
103 # for other argument lists. 110 # for other argument lists.
104 self.assertRaises(TypeError, posix.initgroups) 111 self.assertRaises(TypeError, posix.initgroups)
105 self.assertRaises(TypeError, posix.initgroups, None) 112 self.assertRaises(TypeError, posix.initgroups, None)
106 self.assertRaises(TypeError, posix.initgroups, 3, "foo") 113 self.assertRaises(TypeError, posix.initgroups, 3, "foo")
107 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object()) 114 self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
108 115
109 # If a non-privileged user invokes it, it should fail with OSError 116 # If a non-privileged user invokes it, it should fail with OSError
110 # EPERM. 117 # EPERM.
111 if os.getuid() != 0: 118 if os.getuid() != 0:
112 try: 119 try:
113 name = pwd.getpwuid(posix.getuid()).pw_name 120 name = pwd.getpwuid(posix.getuid()).pw_name
114 except KeyError: 121 except KeyError:
115 # the current UID may not have a pwd entry 122 # the current UID may not have a pwd entry
116 raise unittest.SkipTest("need a pwd entry") 123 raise unittest.SkipTest("need a pwd entry")
117 try: 124 try:
118 posix.initgroups(name, 13) 125 posix.initgroups(name, 13)
119 except OSError as e: 126 except OSError as e:
120 self.assertEqual(e.errno, errno.EPERM) 127 self.assertEqual(e.errno, errno.EPERM)
121 else: 128 else:
122 self.fail("Expected OSError to be raised by initgroups") 129 self.fail("Expected OSError to be raised by initgroups")
123 130
131 @unittest.skipUnless(hasattr(posix, 'statvfs'),
132 'test needs posix.statvfs()')
124 def test_statvfs(self): 133 def test_statvfs(self):
125 if hasattr(posix, 'statvfs'): 134 self.assertTrue(posix.statvfs(os.curdir))
126 self.assertTrue(posix.statvfs(os.curdir)) 135
127 136 @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
137 'test needs posix.fstatvfs()')
128 def test_fstatvfs(self): 138 def test_fstatvfs(self):
129 if hasattr(posix, 'fstatvfs'): 139 fp = open(support.TESTFN)
130 fp = open(support.TESTFN) 140 try:
131 try: 141 self.assertTrue(posix.fstatvfs(fp.fileno()))
132 self.assertTrue(posix.fstatvfs(fp.fileno())) 142 self.assertTrue(posix.statvfs(fp.fileno()))
133 self.assertTrue(posix.statvfs(fp.fileno())) 143 finally:
134 finally: 144 fp.close()
135 fp.close() 145
136 146 @unittest.skipUnless(hasattr(posix, 'ftruncate'),
147 'test needs posix.ftruncate()')
137 def test_ftruncate(self): 148 def test_ftruncate(self):
138 if hasattr(posix, 'ftruncate'): 149 fp = open(support.TESTFN, 'w+')
139 fp = open(support.TESTFN, 'w+') 150 try:
140 try: 151 # we need to have some data to truncate
141 # we need to have some data to truncate 152 fp.write('test')
142 fp.write('test') 153 fp.flush()
143 fp.flush() 154 posix.ftruncate(fp.fileno(), 0)
144 posix.ftruncate(fp.fileno(), 0) 155 finally:
145 finally: 156 fp.close()
146 fp.close()
147 157
148 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate( )") 158 @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate( )")
149 def test_truncate(self): 159 def test_truncate(self):
150 with open(support.TESTFN, 'w') as fp: 160 with open(support.TESTFN, 'w') as fp:
151 fp.write('test') 161 fp.write('test')
152 fp.flush() 162 fp.flush()
153 posix.truncate(support.TESTFN, 0) 163 posix.truncate(support.TESTFN, 0)
154 164
155 @unittest.skipUnless(getattr(os, 'execve', None) in os.supports_fd, "test ne eds execve() to support the fd parameter") 165 @unittest.skipUnless(getattr(os, 'execve', None) in os.supports_fd, "test ne eds execve() to support the fd parameter")
156 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()") 166 @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
(...skipping 108 matching lines...)
265 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), f ollow_symlinks=False) 275 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), f ollow_symlinks=False)
266 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), f ollow_symlinks=False) 276 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), f ollow_symlinks=False)
267 posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False) 277 posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False)
268 posix.utime(support.TESTFN, (now, now), follow_symlinks=False) 278 posix.utime(support.TESTFN, (now, now), follow_symlinks=False)
269 posix.utime(support.TESTFN, follow_symlinks=False) 279 posix.utime(support.TESTFN, follow_symlinks=False)
270 280
271 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()") 281 @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
272 def test_writev(self): 282 def test_writev(self):
273 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) 283 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
274 try: 284 try:
275 os.writev(fd, (b'test1', b'tt2', b't3')) 285 n = os.writev(fd, (b'test1', b'tt2', b't3'))
286 self.assertEqual(n, 10)
287
276 os.lseek(fd, 0, os.SEEK_SET) 288 os.lseek(fd, 0, os.SEEK_SET)
277 self.assertEqual(b'test1tt2t3', posix.read(fd, 10)) 289 self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
290
291 # Issue #20113: empty list of buffers should not crash
292 try:
293 size = posix.writev(fd, [])
294 except OSError:
295 # writev(fd, []) raises OSError(22, "Invalid argument")
296 # on OpenIndiana
297 pass
298 else:
299 self.assertEqual(size, 0)
278 finally: 300 finally:
279 os.close(fd) 301 os.close(fd)
280 302
281 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()") 303 @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
282 def test_readv(self): 304 def test_readv(self):
283 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT) 305 fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
284 try: 306 try:
285 os.write(fd, b'test1tt2t3') 307 os.write(fd, b'test1tt2t3')
286 os.lseek(fd, 0, os.SEEK_SET) 308 os.lseek(fd, 0, os.SEEK_SET)
287 buf = [bytearray(i) for i in [5, 3, 2]] 309 buf = [bytearray(i) for i in [5, 3, 2]]
288 self.assertEqual(posix.readv(fd, buf), 10) 310 self.assertEqual(posix.readv(fd, buf), 10)
289 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf]) 311 self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
312
313 # Issue #20113: empty list of buffers should not crash
314 try:
315 size = posix.readv(fd, [])
316 except OSError:
317 # readv(fd, []) raises OSError(22, "Invalid argument")
318 # on OpenIndiana
319 pass
320 else:
321 self.assertEqual(size, 0)
290 finally: 322 finally:
291 os.close(fd) 323 os.close(fd)
292 324
325 @unittest.skipUnless(hasattr(posix, 'dup'),
326 'test needs posix.dup()')
293 def test_dup(self): 327 def test_dup(self):
294 if hasattr(posix, 'dup'): 328 fp = open(support.TESTFN)
295 fp = open(support.TESTFN) 329 try:
296 try: 330 fd = posix.dup(fp.fileno())
297 fd = posix.dup(fp.fileno()) 331 self.assertIsInstance(fd, int)
298 self.assertIsInstance(fd, int) 332 os.close(fd)
299 os.close(fd) 333 finally:
300 finally: 334 fp.close()
301 fp.close() 335
302 336 @unittest.skipUnless(hasattr(posix, 'confstr'),
337 'test needs posix.confstr()')
303 def test_confstr(self): 338 def test_confstr(self):
304 if hasattr(posix, 'confstr'): 339 self.assertRaises(ValueError, posix.confstr, "CS_garbage")
305 self.assertRaises(ValueError, posix.confstr, "CS_garbage") 340 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
306 self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True) 341
307 342 @unittest.skipUnless(hasattr(posix, 'dup2'),
343 'test needs posix.dup2()')
308 def test_dup2(self): 344 def test_dup2(self):
309 if hasattr(posix, 'dup2'): 345 fp1 = open(support.TESTFN)
310 fp1 = open(support.TESTFN) 346 fp2 = open(support.TESTFN)
311 fp2 = open(support.TESTFN) 347 try:
312 try: 348 posix.dup2(fp1.fileno(), fp2.fileno())
313 posix.dup2(fp1.fileno(), fp2.fileno()) 349 finally:
314 finally: 350 fp1.close()
315 fp1.close() 351 fp2.close()
316 fp2.close()
317 352
318 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC") 353 @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
319 @support.requires_linux_version(2, 6, 23) 354 @support.requires_linux_version(2, 6, 23)
320 def test_oscloexec(self): 355 def test_oscloexec(self):
321 fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC) 356 fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
322 self.addCleanup(os.close, fd) 357 self.addCleanup(os.close, fd)
323 self.assertTrue(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC) 358 self.assertTrue(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
324 359
360 @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
361 'test needs posix.O_EXLOCK')
325 def test_osexlock(self): 362 def test_osexlock(self):
326 if hasattr(posix, "O_EXLOCK"): 363 fd = os.open(support.TESTFN,
364 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
365 self.assertRaises(OSError, os.open, support.TESTFN,
366 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
367 os.close(fd)
368
369 if hasattr(posix, "O_SHLOCK"):
327 fd = os.open(support.TESTFN, 370 fd = os.open(support.TESTFN,
328 os.O_WRONLY|os.O_EXLOCK|os.O_CREAT) 371 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
329 self.assertRaises(OSError, os.open, support.TESTFN, 372 self.assertRaises(OSError, os.open, support.TESTFN,
330 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK) 373 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
331 os.close(fd) 374 os.close(fd)
332 375
333 if hasattr(posix, "O_SHLOCK"): 376 @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
334 fd = os.open(support.TESTFN, 377 'test needs posix.O_SHLOCK')
335 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
336 self.assertRaises(OSError, os.open, support.TESTFN,
337 os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
338 os.close(fd)
339
340 def test_osshlock(self): 378 def test_osshlock(self):
341 if hasattr(posix, "O_SHLOCK"): 379 fd1 = os.open(support.TESTFN,
342 fd1 = os.open(support.TESTFN, 380 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
381 fd2 = os.open(support.TESTFN,
382 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
383 os.close(fd2)
384 os.close(fd1)
385
386 if hasattr(posix, "O_EXLOCK"):
387 fd = os.open(support.TESTFN,
343 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) 388 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
344 fd2 = os.open(support.TESTFN, 389 self.assertRaises(OSError, os.open, support.TESTFN,
345 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) 390 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
346 os.close(fd2) 391 os.close(fd)
347 os.close(fd1) 392
348 393 @unittest.skipUnless(hasattr(posix, 'fstat'),
349 if hasattr(posix, "O_EXLOCK"): 394 'test needs posix.fstat()')
350 fd = os.open(support.TESTFN,
351 os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
352 self.assertRaises(OSError, os.open, support.TESTFN,
353 os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
354 os.close(fd)
355
356 def test_fstat(self): 395 def test_fstat(self):
357 if hasattr(posix, 'fstat'): 396 fp = open(support.TESTFN)
358 fp = open(support.TESTFN) 397 try:
359 try: 398 self.assertTrue(posix.fstat(fp.fileno()))
360 self.assertTrue(posix.fstat(fp.fileno())) 399 self.assertTrue(posix.stat(fp.fileno()))
361 self.assertTrue(posix.stat(fp.fileno())) 400
362
363 self.assertRaisesRegex(TypeError,
364 'should be string, bytes or integer, not',
365 posix.stat, float(fp.fileno()))
366 finally:
367 fp.close()
368
369 def test_stat(self):
370 if hasattr(posix, 'stat'):
371 self.assertTrue(posix.stat(support.TESTFN))
372 self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
373 self.assertTrue(posix.stat(bytearray(os.fsencode(support.TESTFN))))
374
375 self.assertRaisesRegex(TypeError,
376 'can\'t specify None for path argument',
377 posix.stat, None)
378 self.assertRaisesRegex(TypeError, 401 self.assertRaisesRegex(TypeError,
379 'should be string, bytes or integer, not', 402 'should be string, bytes or integer, not',
380 posix.stat, list(support.TESTFN)) 403 posix.stat, float(fp.fileno()))
381 self.assertRaisesRegex(TypeError, 404 finally:
382 'should be string, bytes or integer, not', 405 fp.close()
383 posix.stat, list(os.fsencode(support.TESTFN))) 406
407 @unittest.skipUnless(hasattr(posix, 'stat'),
408 'test needs posix.stat()')
409 def test_stat(self):
410 self.assertTrue(posix.stat(support.TESTFN))
411 self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
412 self.assertTrue(posix.stat(bytearray(os.fsencode(support.TESTFN))))
413
414 self.assertRaisesRegex(TypeError,
415 'can\'t specify None for path argument',
416 posix.stat, None)
417 self.assertRaisesRegex(TypeError,
418 'should be string, bytes or integer, not',
419 posix.stat, list(support.TESTFN))
420 self.assertRaisesRegex(TypeError,
421 'should be string, bytes or integer, not',
422 posix.stat, list(os.fsencode(support.TESTFN)))
384 423
385 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()") 424 @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
386 def test_mkfifo(self): 425 def test_mkfifo(self):
387 support.unlink(support.TESTFN) 426 support.unlink(support.TESTFN)
388 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR) 427 posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
389 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode)) 428 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
390 429
391 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'), 430 @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
392 "don't have mknod()/S_IFIFO") 431 "don't have mknod()/S_IFIFO")
393 def test_mknod(self): 432 def test_mknod(self):
394 # Test using mknod() to create a FIFO (the only use specified 433 # Test using mknod() to create a FIFO (the only use specified
395 # by POSIX). 434 # by POSIX).
396 support.unlink(support.TESTFN) 435 support.unlink(support.TESTFN)
397 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR 436 mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
398 try: 437 try:
399 posix.mknod(support.TESTFN, mode, 0) 438 posix.mknod(support.TESTFN, mode, 0)
400 except OSError as e: 439 except OSError as e:
401 # Some old systems don't allow unprivileged users to use 440 # Some old systems don't allow unprivileged users to use
402 # mknod(), or only support creating device nodes. 441 # mknod(), or only support creating device nodes.
403 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL)) 442 self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
404 else: 443 else:
405 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode)) 444 self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
406 445
407 def _test_all_chown_common(self, chown_func, first_param): 446 def _test_all_chown_common(self, chown_func, first_param, stat_func):
408 """Common code for chown, fchown and lchown tests.""" 447 """Common code for chown, fchown and lchown tests."""
448 def check_stat(uid, gid):
449 if stat_func is not None:
450 stat = stat_func(first_param)
451 self.assertEqual(stat.st_uid, uid)
452 self.assertEqual(stat.st_gid, gid)
453 uid = os.getuid()
454 gid = os.getgid()
409 # test a successful chown call 455 # test a successful chown call
410 chown_func(first_param, os.getuid(), os.getgid()) 456 chown_func(first_param, uid, gid)
411 457 check_stat(uid, gid)
412 if os.getuid() == 0: 458 chown_func(first_param, -1, gid)
413 try: 459 check_stat(uid, gid)
414 # Many linux distros have a nfsnobody user as MAX_UID-2 460 chown_func(first_param, uid, -1)
415 # that makes a good test case for signedness issues. 461 check_stat(uid, gid)
416 # http://bugs.python.org/issue1747858 462
417 # This part of the test only runs when run as root. 463 if uid == 0:
418 # Only scary people run their tests as root. 464 # Try an amusingly large uid/gid to make sure we handle
419 ent = pwd.getpwnam('nfsnobody') 465 # large unsigned values. (chown lets you use any
420 chown_func(first_param, ent.pw_uid, ent.pw_gid) 466 # uid/gid you like, even if they aren't defined.)
421 except KeyError: 467 #
422 pass 468 # This problem keeps coming up:
469 # http://bugs.python.org/issue1747858
470 # http://bugs.python.org/issue4591
471 # http://bugs.python.org/issue15301
472 # Hopefully the fix in 4591 fixes it for good!
473 #
474 # This part of the test only runs when run as root.
475 # Only scary people run their tests as root.
476
477 big_value = 2**31
478 chown_func(first_param, big_value, big_value)
479 check_stat(big_value, big_value)
480 chown_func(first_param, -1, -1)
481 check_stat(big_value, big_value)
482 chown_func(first_param, uid, gid)
483 check_stat(uid, gid)
423 elif platform.system() in ('HP-UX', 'SunOS'): 484 elif platform.system() in ('HP-UX', 'SunOS'):
424 # HP-UX and Solaris can allow a non-root user to chown() to root 485 # HP-UX and Solaris can allow a non-root user to chown() to root
425 # (issue #5113) 486 # (issue #5113)
426 raise unittest.SkipTest("Skipping because of non-standard chown() " 487 raise unittest.SkipTest("Skipping because of non-standard chown() "
427 "behavior") 488 "behavior")
428 else: 489 else:
429 # non-root cannot chown to root, raises OSError 490 # non-root cannot chown to root, raises OSError
430 self.assertRaises(OSError, chown_func, 491 self.assertRaises(OSError, chown_func, first_param, 0, 0)
431 first_param, 0, 0) 492 check_stat(uid, gid)
493 self.assertRaises(OSError, chown_func, first_param, 0, -1)
494 check_stat(uid, gid)
495 if 0 not in os.getgroups():
496 self.assertRaises(OSError, chown_func, first_param, -1, 0)
497 check_stat(uid, gid)
498 # test illegal types
499 for t in str, float:
500 self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
501 check_stat(uid, gid)
502 self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
503 check_stat(uid, gid)
432 504
433 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()") 505 @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
434 def test_chown(self): 506 def test_chown(self):
435 # raise an OSError if the file does not exist 507 # raise an OSError if the file does not exist
436 os.unlink(support.TESTFN) 508 os.unlink(support.TESTFN)
437 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1) 509 self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
438 510
439 # re-create the file 511 # re-create the file
440 support.create_empty_file(support.TESTFN) 512 support.create_empty_file(support.TESTFN)
441 self._test_all_chown_common(posix.chown, support.TESTFN) 513 self._test_all_chown_common(posix.chown, support.TESTFN,
514 getattr(posix, 'stat', None))
442 515
443 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()") 516 @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
444 def test_fchown(self): 517 def test_fchown(self):
445 os.unlink(support.TESTFN) 518 os.unlink(support.TESTFN)
446 519
447 # re-create the file 520 # re-create the file
448 test_file = open(support.TESTFN, 'w') 521 test_file = open(support.TESTFN, 'w')
449 try: 522 try:
450 fd = test_file.fileno() 523 fd = test_file.fileno()
451 self._test_all_chown_common(posix.fchown, fd) 524 self._test_all_chown_common(posix.fchown, fd,
525 getattr(posix, 'fstat', None))
452 finally: 526 finally:
453 test_file.close() 527 test_file.close()
454 528
455 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()") 529 @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
456 def test_lchown(self): 530 def test_lchown(self):
457 os.unlink(support.TESTFN) 531 os.unlink(support.TESTFN)
458 # create a symlink 532 # create a symlink
459 os.symlink(_DUMMY_SYMLINK, support.TESTFN) 533 os.symlink(_DUMMY_SYMLINK, support.TESTFN)
460 self._test_all_chown_common(posix.lchown, support.TESTFN) 534 self._test_all_chown_common(posix.lchown, support.TESTFN,
461 535 getattr(posix, 'lstat', None))
536
537 @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
462 def test_chdir(self): 538 def test_chdir(self):
463 if hasattr(posix, 'chdir'): 539 posix.chdir(os.curdir)
464 posix.chdir(os.curdir) 540 self.assertRaises(OSError, posix.chdir, support.TESTFN)
465 self.assertRaises(OSError, posix.chdir, support.TESTFN)
466 541
467 def test_listdir(self): 542 def test_listdir(self):
468 self.assertIn(support.TESTFN, posix.listdir(os.curdir)) 543 self.assertIn(support.TESTFN, posix.listdir(os.curdir))
469 544
470 def test_listdir_default(self): 545 def test_listdir_default(self):
471 # When listdir is called without argument, 546 # When listdir is called without argument,
472 # it's the same as listdir(os.curdir). 547 # it's the same as listdir(os.curdir).
473 self.assertIn(support.TESTFN, posix.listdir()) 548 self.assertIn(support.TESTFN, posix.listdir())
474 549
475 def test_listdir_bytes(self): 550 def test_listdir_bytes(self):
476 # When listdir is called with a bytes object, 551 # When listdir is called with a bytes object,
477 # the returned strings are of type bytes. 552 # the returned strings are of type bytes.
478 self.assertIn(os.fsencode(support.TESTFN), posix.listdir(b'.')) 553 self.assertIn(os.fsencode(support.TESTFN), posix.listdir(b'.'))
479 554
480 @unittest.skipUnless(posix.listdir in os.supports_fd, 555 @unittest.skipUnless(posix.listdir in os.supports_fd,
481 "test needs fd support for posix.listdir()") 556 "test needs fd support for posix.listdir()")
482 def test_listdir_fd(self): 557 def test_listdir_fd(self):
483 f = posix.open(posix.getcwd(), posix.O_RDONLY) 558 f = posix.open(posix.getcwd(), posix.O_RDONLY)
484 self.addCleanup(posix.close, f) 559 self.addCleanup(posix.close, f)
485 self.assertEqual( 560 self.assertEqual(
486 sorted(posix.listdir('.')), 561 sorted(posix.listdir('.')),
487 sorted(posix.listdir(f)) 562 sorted(posix.listdir(f))
488 ) 563 )
489 # Check that the fd offset was reset (issue #13739) 564 # Check that the fd offset was reset (issue #13739)
490 self.assertEqual( 565 self.assertEqual(
491 sorted(posix.listdir('.')), 566 sorted(posix.listdir('.')),
492 sorted(posix.listdir(f)) 567 sorted(posix.listdir(f))
493 ) 568 )
494 569
570 @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
495 def test_access(self): 571 def test_access(self):
496 if hasattr(posix, 'access'): 572 self.assertTrue(posix.access(support.TESTFN, os.R_OK))
497 self.assertTrue(posix.access(support.TESTFN, os.R_OK)) 573
498 574 @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
499 def test_umask(self): 575 def test_umask(self):
500 if hasattr(posix, 'umask'): 576 old_mask = posix.umask(0)
501 old_mask = posix.umask(0) 577 self.assertIsInstance(old_mask, int)
502 self.assertIsInstance(old_mask, int) 578 posix.umask(old_mask)
503 posix.umask(old_mask) 579
504 580 @unittest.skipUnless(hasattr(posix, 'strerror'),
581 'test needs posix.strerror()')
505 def test_strerror(self): 582 def test_strerror(self):
506 if hasattr(posix, 'strerror'): 583 self.assertTrue(posix.strerror(0))
507 self.assertTrue(posix.strerror(0)) 584
508 585 @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
509 def test_pipe(self): 586 def test_pipe(self):
510 if hasattr(posix, 'pipe'): 587 reader, writer = posix.pipe()
511 reader, writer = posix.pipe() 588 os.close(reader)
512 os.close(reader) 589 os.close(writer)
513 os.close(writer)
514 590
515 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()") 591 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
516 @support.requires_linux_version(2, 6, 27) 592 @support.requires_linux_version(2, 6, 27)
517 def test_pipe2(self): 593 def test_pipe2(self):
518 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF') 594 self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
519 self.assertRaises(TypeError, os.pipe2, 0, 0) 595 self.assertRaises(TypeError, os.pipe2, 0, 0)
520 596
521 # try calling with flags = 0, like os.pipe() 597 # try calling with flags = 0, like os.pipe()
522 r, w = os.pipe2(0) 598 r, w = os.pipe2(0)
523 os.close(r) 599 os.close(r)
524 os.close(w) 600 os.close(w)
525 601
526 # test flags 602 # test flags
527 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK) 603 r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
528 self.addCleanup(os.close, r) 604 self.addCleanup(os.close, r)
529 self.addCleanup(os.close, w) 605 self.addCleanup(os.close, w)
530 self.assertTrue(fcntl.fcntl(r, fcntl.F_GETFD) & fcntl.FD_CLOEXEC) 606 self.assertFalse(os.get_inheritable(r))
531 self.assertTrue(fcntl.fcntl(w, fcntl.F_GETFD) & fcntl.FD_CLOEXEC) 607 self.assertFalse(os.get_inheritable(w))
608 self.assertTrue(fcntl.fcntl(r, fcntl.F_GETFL) & os.O_NONBLOCK)
609 self.assertTrue(fcntl.fcntl(w, fcntl.F_GETFL) & os.O_NONBLOCK)
532 # try reading from an empty pipe: this should fail, not block 610 # try reading from an empty pipe: this should fail, not block
533 self.assertRaises(OSError, os.read, r, 1) 611 self.assertRaises(OSError, os.read, r, 1)
534 # try a write big enough to fill-up the pipe: this should either 612 # try a write big enough to fill-up the pipe: this should either
535 # fail or perform a partial write, not block 613 # fail or perform a partial write, not block
536 try: 614 try:
537 os.write(w, b'x' * support.PIPE_MAX_SIZE) 615 os.write(w, b'x' * support.PIPE_MAX_SIZE)
538 except OSError: 616 except OSError:
539 pass 617 pass
540 618
619 @support.cpython_only
620 @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
621 @support.requires_linux_version(2, 6, 27)
622 def test_pipe2_c_limits(self):
541 # Issue 15989 623 # Issue 15989
624 import _testcapi
542 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1) 625 self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
543 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1) 626 self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
544 627
628 @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
545 def test_utime(self): 629 def test_utime(self):
546 if hasattr(posix, 'utime'): 630 now = time.time()
547 now = time.time() 631 posix.utime(support.TESTFN, None)
548 posix.utime(support.TESTFN, None) 632 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
549 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, Non e)) 633 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
550 self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None )) 634 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
551 self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now )) 635 posix.utime(support.TESTFN, (int(now), int(now)))
552 posix.utime(support.TESTFN, (int(now), int(now))) 636 posix.utime(support.TESTFN, (now, now))
553 posix.utime(support.TESTFN, (now, now))
554 637
555 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs): 638 def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
556 st = os.stat(target_file) 639 st = os.stat(target_file)
557 self.assertTrue(hasattr(st, 'st_flags')) 640 self.assertTrue(hasattr(st, 'st_flags'))
558 641
559 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE. 642 # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
560 flags = st.st_flags | stat.UF_IMMUTABLE 643 flags = st.st_flags | stat.UF_IMMUTABLE
561 try: 644 try:
562 chflags_func(target_file, flags, **kwargs) 645 chflags_func(target_file, flags, **kwargs)
563 except OSError as err: 646 except OSError as err:
(...skipping 56 matching lines...)
620 703
621 def test_environ(self): 704 def test_environ(self):
622 if os.name == "nt": 705 if os.name == "nt":
623 item_type = str 706 item_type = str
624 else: 707 else:
625 item_type = bytes 708 item_type = bytes
626 for k, v in posix.environ.items(): 709 for k, v in posix.environ.items():
627 self.assertEqual(type(k), item_type) 710 self.assertEqual(type(k), item_type)
628 self.assertEqual(type(v), item_type) 711 self.assertEqual(type(v), item_type)
629 712
713 @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
630 def test_getcwd_long_pathnames(self): 714 def test_getcwd_long_pathnames(self):
631 if hasattr(posix, 'getcwd'): 715 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
632 dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef' 716 curdir = os.getcwd()
633 curdir = os.getcwd() 717 base_path = os.path.abspath(support.TESTFN) + '.getcwd'
634 base_path = os.path.abspath(support.TESTFN) + '.getcwd' 718
635 719 try:
636 try: 720 os.mkdir(base_path)
637 os.mkdir(base_path) 721 os.chdir(base_path)
638 os.chdir(base_path) 722 except:
639 except: 723 # Just returning nothing instead of the SkipTest exception, because
640 # Just returning nothing instead of the SkipTest exception, 724 # the test results in Error in that case. Is that ok?
641 # because the test results in Error in that case. 725 # raise unittest.SkipTest("cannot create directory for testing")
642 # Is that ok? 726 return
643 # raise unittest.SkipTest("cannot create directory for testing") 727
644 return 728 def _create_and_do_getcwd(dirname, current_path_length = 0):
645 729 try:
646 def _create_and_do_getcwd(dirname, current_path_length = 0): 730 os.mkdir(dirname)
647 try: 731 except:
648 os.mkdir(dirname) 732 raise unittest.SkipTest("mkdir cannot create directory suffi ciently deep for getcwd test")
649 except: 733
650 raise unittest.SkipTest("mkdir cannot create directory s ufficiently deep for getcwd test") 734 os.chdir(dirname)
651 735 try:
652 os.chdir(dirname) 736 os.getcwd()
653 try: 737 if current_path_length < 1027:
654 os.getcwd() 738 _create_and_do_getcwd(dirname, current_path_length + len (dirname) + 1)
655 if current_path_length < 1027: 739 finally:
656 _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1) 740 os.chdir('..')
657 finally: 741 os.rmdir(dirname)
658 os.chdir('..') 742
659 os.rmdir(dirname) 743 _create_and_do_getcwd(dirname)
660 744
661 _create_and_do_getcwd(dirname) 745 finally:
662 746 os.chdir(curdir)
663 finally: 747 support.rmtree(base_path)
664 os.chdir(curdir)
665 support.rmtree(base_path)
666 748
667 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgr ouplist()") 749 @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgr ouplist()")
668 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()") 750 @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
669 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()") 751 @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
670 def test_getgrouplist(self): 752 def test_getgrouplist(self):
671 user = pwd.getpwuid(os.getuid())[0] 753 user = pwd.getpwuid(os.getuid())[0]
672 group = pwd.getpwuid(os.getuid())[3] 754 group = pwd.getpwuid(os.getuid())[3]
673 self.assertIn(group, posix.getgrouplist(user, group)) 755 self.assertIn(group, posix.getgrouplist(user, group))
674 756
675 757
676 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()") 758 @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
677 def test_getgroups(self): 759 def test_getgroups(self):
678 with os.popen('id -G') as idg: 760 with os.popen('id -G') as idg:
679 groups = idg.read().strip() 761 groups = idg.read().strip()
680 ret = idg.close() 762 ret = idg.close()
681 763
682 if ret is not None or not groups: 764 if ret is not None or not groups:
683 raise unittest.SkipTest("need working 'id -G'") 765 raise unittest.SkipTest("need working 'id -G'")
766
767 # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
768 if sys.platform == 'darwin':
769 import sysconfig
770 dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
771 if float(dt) < 10.6:
772 raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
684 773
685 # 'id -G' and 'os.getgroups()' should return the same 774 # 'id -G' and 'os.getgroups()' should return the same
686 # groups, ignoring order and duplicates. 775 # groups, ignoring order and duplicates.
687 # #10822 - it is implementation defined whether posix.getgroups() 776 # #10822 - it is implementation defined whether posix.getgroups()
688 # includes the effective gid so we include it anyway, since id -G does 777 # includes the effective gid so we include it anyway, since id -G does
689 self.assertEqual( 778 self.assertEqual(
690 set([int(x) for x in groups.split()]), 779 set([int(x) for x in groups.split()]),
691 set(posix.getgroups() + [posix.getegid()])) 780 set(posix.getgroups() + [posix.getegid()]))
692 781
693 # tests for the posix *at functions follow 782 # tests for the posix *at functions follow
(...skipping 374 matching lines...)
1068 self.assertListEqual(groups, posix.getgroups()) 1157 self.assertListEqual(groups, posix.getgroups())
1069 1158
1070 def test_main(): 1159 def test_main():
1071 try: 1160 try:
1072 support.run_unittest(PosixTester, PosixGroupsTester) 1161 support.run_unittest(PosixTester, PosixGroupsTester)
1073 finally: 1162 finally:
1074 support.reap_children() 1163 support.reap_children()
1075 1164
1076 if __name__ == '__main__': 1165 if __name__ == '__main__':
1077 test_main() 1166 test_main()
LEFTRIGHT

This is Rietveld 894c83f36cb7+