ยปCore Development>Code coverage>Lib/test/test_posix.py

Python code coverage for Lib/test/test_posix.py

#countcontent
1n/a"Test posix functions"
2n/a
3n/afrom test import support
4n/aandroid_not_root = support.android_not_root
5n/a
6n/a# Skip these tests if there is no posix module.
7n/aposix = support.import_module('posix')
8n/a
9n/aimport errno
10n/aimport sys
11n/aimport time
12n/aimport os
13n/aimport platform
14n/aimport pwd
15n/aimport stat
16n/aimport tempfile
17n/aimport unittest
18n/aimport warnings
19n/a
20n/a_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
21n/a support.TESTFN + '-dummy-symlink')
22n/a
23n/aclass PosixTester(unittest.TestCase):
24n/a
25n/a def setUp(self):
26n/a # create empty file
27n/a fp = open(support.TESTFN, 'w+')
28n/a fp.close()
29n/a self.teardown_files = [ support.TESTFN ]
30n/a self._warnings_manager = support.check_warnings()
31n/a self._warnings_manager.__enter__()
32n/a warnings.filterwarnings('ignore', '.* potential security risk .*',
33n/a RuntimeWarning)
34n/a
35n/a def tearDown(self):
36n/a for teardown_file in self.teardown_files:
37n/a support.unlink(teardown_file)
38n/a self._warnings_manager.__exit__(None, None, None)
39n/a
40n/a def testNoArgFunctions(self):
41n/a # test posix functions which take no arguments and have
42n/a # no side-effects which we need to cleanup (e.g., fork, wait, abort)
43n/a NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
44n/a "times", "getloadavg",
45n/a "getegid", "geteuid", "getgid", "getgroups",
46n/a "getpid", "getpgrp", "getppid", "getuid", "sync",
47n/a ]
48n/a
49n/a for name in NO_ARG_FUNCTIONS:
50n/a posix_func = getattr(posix, name, None)
51n/a if posix_func is not None:
52n/a posix_func()
53n/a self.assertRaises(TypeError, posix_func, 1)
54n/a
55n/a @unittest.skipUnless(hasattr(posix, 'getresuid'),
56n/a 'test needs posix.getresuid()')
57n/a def test_getresuid(self):
58n/a user_ids = posix.getresuid()
59n/a self.assertEqual(len(user_ids), 3)
60n/a for val in user_ids:
61n/a self.assertGreaterEqual(val, 0)
62n/a
63n/a @unittest.skipUnless(hasattr(posix, 'getresgid'),
64n/a 'test needs posix.getresgid()')
65n/a def test_getresgid(self):
66n/a group_ids = posix.getresgid()
67n/a self.assertEqual(len(group_ids), 3)
68n/a for val in group_ids:
69n/a self.assertGreaterEqual(val, 0)
70n/a
71n/a @unittest.skipUnless(hasattr(posix, 'setresuid'),
72n/a 'test needs posix.setresuid()')
73n/a def test_setresuid(self):
74n/a current_user_ids = posix.getresuid()
75n/a self.assertIsNone(posix.setresuid(*current_user_ids))
76n/a # -1 means don't change that value.
77n/a self.assertIsNone(posix.setresuid(-1, -1, -1))
78n/a
79n/a @unittest.skipUnless(hasattr(posix, 'setresuid'),
80n/a 'test needs posix.setresuid()')
81n/a def test_setresuid_exception(self):
82n/a # Don't do this test if someone is silly enough to run us as root.
83n/a current_user_ids = posix.getresuid()
84n/a if 0 not in current_user_ids:
85n/a new_user_ids = (current_user_ids[0]+1, -1, -1)
86n/a self.assertRaises(OSError, posix.setresuid, *new_user_ids)
87n/a
88n/a @unittest.skipUnless(hasattr(posix, 'setresgid'),
89n/a 'test needs posix.setresgid()')
90n/a def test_setresgid(self):
91n/a current_group_ids = posix.getresgid()
92n/a self.assertIsNone(posix.setresgid(*current_group_ids))
93n/a # -1 means don't change that value.
94n/a self.assertIsNone(posix.setresgid(-1, -1, -1))
95n/a
96n/a @unittest.skipUnless(hasattr(posix, 'setresgid'),
97n/a 'test needs posix.setresgid()')
98n/a def test_setresgid_exception(self):
99n/a # Don't do this test if someone is silly enough to run us as root.
100n/a current_group_ids = posix.getresgid()
101n/a if 0 not in current_group_ids:
102n/a new_group_ids = (current_group_ids[0]+1, -1, -1)
103n/a self.assertRaises(OSError, posix.setresgid, *new_group_ids)
104n/a
105n/a @unittest.skipUnless(hasattr(posix, 'initgroups'),
106n/a "test needs os.initgroups()")
107n/a def test_initgroups(self):
108n/a # It takes a string and an integer; check that it raises a TypeError
109n/a # for other argument lists.
110n/a self.assertRaises(TypeError, posix.initgroups)
111n/a self.assertRaises(TypeError, posix.initgroups, None)
112n/a self.assertRaises(TypeError, posix.initgroups, 3, "foo")
113n/a self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
114n/a
115n/a # If a non-privileged user invokes it, it should fail with OSError
116n/a # EPERM.
117n/a if os.getuid() != 0:
118n/a try:
119n/a name = pwd.getpwuid(posix.getuid()).pw_name
120n/a except KeyError:
121n/a # the current UID may not have a pwd entry
122n/a raise unittest.SkipTest("need a pwd entry")
123n/a try:
124n/a posix.initgroups(name, 13)
125n/a except OSError as e:
126n/a self.assertEqual(e.errno, errno.EPERM)
127n/a else:
128n/a self.fail("Expected OSError to be raised by initgroups")
129n/a
130n/a @unittest.skipUnless(hasattr(posix, 'statvfs'),
131n/a 'test needs posix.statvfs()')
132n/a def test_statvfs(self):
133n/a self.assertTrue(posix.statvfs(os.curdir))
134n/a
135n/a @unittest.skipUnless(hasattr(posix, 'fstatvfs'),
136n/a 'test needs posix.fstatvfs()')
137n/a def test_fstatvfs(self):
138n/a fp = open(support.TESTFN)
139n/a try:
140n/a self.assertTrue(posix.fstatvfs(fp.fileno()))
141n/a self.assertTrue(posix.statvfs(fp.fileno()))
142n/a finally:
143n/a fp.close()
144n/a
145n/a @unittest.skipUnless(hasattr(posix, 'ftruncate'),
146n/a 'test needs posix.ftruncate()')
147n/a def test_ftruncate(self):
148n/a fp = open(support.TESTFN, 'w+')
149n/a try:
150n/a # we need to have some data to truncate
151n/a fp.write('test')
152n/a fp.flush()
153n/a posix.ftruncate(fp.fileno(), 0)
154n/a finally:
155n/a fp.close()
156n/a
157n/a @unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
158n/a def test_truncate(self):
159n/a with open(support.TESTFN, 'w') as fp:
160n/a fp.write('test')
161n/a fp.flush()
162n/a posix.truncate(support.TESTFN, 0)
163n/a
164n/a @unittest.skipUnless(getattr(os, 'execve', None) in os.supports_fd, "test needs execve() to support the fd parameter")
165n/a @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
166n/a @unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
167n/a def test_fexecve(self):
168n/a fp = os.open(sys.executable, os.O_RDONLY)
169n/a try:
170n/a pid = os.fork()
171n/a if pid == 0:
172n/a os.chdir(os.path.split(sys.executable)[0])
173n/a posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
174n/a else:
175n/a self.assertEqual(os.waitpid(pid, 0), (pid, 0))
176n/a finally:
177n/a os.close(fp)
178n/a
179n/a @unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
180n/a @unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
181n/a def test_waitid(self):
182n/a pid = os.fork()
183n/a if pid == 0:
184n/a os.chdir(os.path.split(sys.executable)[0])
185n/a posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
186n/a else:
187n/a res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
188n/a self.assertEqual(pid, res.si_pid)
189n/a
190n/a @unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
191n/a def test_lockf(self):
192n/a fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
193n/a try:
194n/a os.write(fd, b'test')
195n/a os.lseek(fd, 0, os.SEEK_SET)
196n/a posix.lockf(fd, posix.F_LOCK, 4)
197n/a # section is locked
198n/a posix.lockf(fd, posix.F_ULOCK, 4)
199n/a finally:
200n/a os.close(fd)
201n/a
202n/a @unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
203n/a def test_pread(self):
204n/a fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
205n/a try:
206n/a os.write(fd, b'test')
207n/a os.lseek(fd, 0, os.SEEK_SET)
208n/a self.assertEqual(b'es', posix.pread(fd, 2, 1))
209n/a # the first pread() shouldn't disturb the file offset
210n/a self.assertEqual(b'te', posix.read(fd, 2))
211n/a finally:
212n/a os.close(fd)
213n/a
214n/a @unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
215n/a def test_pwrite(self):
216n/a fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
217n/a try:
218n/a os.write(fd, b'test')
219n/a os.lseek(fd, 0, os.SEEK_SET)
220n/a posix.pwrite(fd, b'xx', 1)
221n/a self.assertEqual(b'txxt', posix.read(fd, 4))
222n/a finally:
223n/a os.close(fd)
224n/a
225n/a @unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
226n/a "test needs posix.posix_fallocate()")
227n/a def test_posix_fallocate(self):
228n/a fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
229n/a try:
230n/a posix.posix_fallocate(fd, 0, 10)
231n/a except OSError as inst:
232n/a # issue10812, ZFS doesn't appear to support posix_fallocate,
233n/a # so skip Solaris-based since they are likely to have ZFS.
234n/a if inst.errno != errno.EINVAL or not sys.platform.startswith("sunos"):
235n/a raise
236n/a finally:
237n/a os.close(fd)
238n/a
239n/a @unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
240n/a "test needs posix.posix_fadvise()")
241n/a def test_posix_fadvise(self):
242n/a fd = os.open(support.TESTFN, os.O_RDONLY)
243n/a try:
244n/a posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
245n/a finally:
246n/a os.close(fd)
247n/a
248n/a @unittest.skipUnless(os.utime in os.supports_fd, "test needs fd support in os.utime")
249n/a def test_utime_with_fd(self):
250n/a now = time.time()
251n/a fd = os.open(support.TESTFN, os.O_RDONLY)
252n/a try:
253n/a posix.utime(fd)
254n/a posix.utime(fd, None)
255n/a self.assertRaises(TypeError, posix.utime, fd, (None, None))
256n/a self.assertRaises(TypeError, posix.utime, fd, (now, None))
257n/a self.assertRaises(TypeError, posix.utime, fd, (None, now))
258n/a posix.utime(fd, (int(now), int(now)))
259n/a posix.utime(fd, (now, now))
260n/a self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
261n/a self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(None, None))
262n/a self.assertRaises(ValueError, posix.utime, fd, (None, None), ns=(now, 0))
263n/a posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
264n/a posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
265n/a
266n/a finally:
267n/a os.close(fd)
268n/a
269n/a @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "test needs follow_symlinks support in os.utime")
270n/a def test_utime_nofollow_symlinks(self):
271n/a now = time.time()
272n/a posix.utime(support.TESTFN, None, follow_symlinks=False)
273n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), follow_symlinks=False)
274n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), follow_symlinks=False)
275n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), follow_symlinks=False)
276n/a posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=False)
277n/a posix.utime(support.TESTFN, (now, now), follow_symlinks=False)
278n/a posix.utime(support.TESTFN, follow_symlinks=False)
279n/a
280n/a @unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
281n/a def test_writev(self):
282n/a fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
283n/a try:
284n/a n = os.writev(fd, (b'test1', b'tt2', b't3'))
285n/a self.assertEqual(n, 10)
286n/a
287n/a os.lseek(fd, 0, os.SEEK_SET)
288n/a self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
289n/a
290n/a # Issue #20113: empty list of buffers should not crash
291n/a try:
292n/a size = posix.writev(fd, [])
293n/a except OSError:
294n/a # writev(fd, []) raises OSError(22, "Invalid argument")
295n/a # on OpenIndiana
296n/a pass
297n/a else:
298n/a self.assertEqual(size, 0)
299n/a finally:
300n/a os.close(fd)
301n/a
302n/a @unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
303n/a def test_readv(self):
304n/a fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
305n/a try:
306n/a os.write(fd, b'test1tt2t3')
307n/a os.lseek(fd, 0, os.SEEK_SET)
308n/a buf = [bytearray(i) for i in [5, 3, 2]]
309n/a self.assertEqual(posix.readv(fd, buf), 10)
310n/a self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) for i in buf])
311n/a
312n/a # Issue #20113: empty list of buffers should not crash
313n/a try:
314n/a size = posix.readv(fd, [])
315n/a except OSError:
316n/a # readv(fd, []) raises OSError(22, "Invalid argument")
317n/a # on OpenIndiana
318n/a pass
319n/a else:
320n/a self.assertEqual(size, 0)
321n/a finally:
322n/a os.close(fd)
323n/a
324n/a @unittest.skipUnless(hasattr(posix, 'dup'),
325n/a 'test needs posix.dup()')
326n/a def test_dup(self):
327n/a fp = open(support.TESTFN)
328n/a try:
329n/a fd = posix.dup(fp.fileno())
330n/a self.assertIsInstance(fd, int)
331n/a os.close(fd)
332n/a finally:
333n/a fp.close()
334n/a
335n/a @unittest.skipUnless(hasattr(posix, 'confstr'),
336n/a 'test needs posix.confstr()')
337n/a def test_confstr(self):
338n/a self.assertRaises(ValueError, posix.confstr, "CS_garbage")
339n/a self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True)
340n/a
341n/a @unittest.skipUnless(hasattr(posix, 'dup2'),
342n/a 'test needs posix.dup2()')
343n/a def test_dup2(self):
344n/a fp1 = open(support.TESTFN)
345n/a fp2 = open(support.TESTFN)
346n/a try:
347n/a posix.dup2(fp1.fileno(), fp2.fileno())
348n/a finally:
349n/a fp1.close()
350n/a fp2.close()
351n/a
352n/a @unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
353n/a @support.requires_linux_version(2, 6, 23)
354n/a def test_oscloexec(self):
355n/a fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
356n/a self.addCleanup(os.close, fd)
357n/a self.assertFalse(os.get_inheritable(fd))
358n/a
359n/a @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
360n/a 'test needs posix.O_EXLOCK')
361n/a def test_osexlock(self):
362n/a fd = os.open(support.TESTFN,
363n/a os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
364n/a self.assertRaises(OSError, os.open, support.TESTFN,
365n/a os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
366n/a os.close(fd)
367n/a
368n/a if hasattr(posix, "O_SHLOCK"):
369n/a fd = os.open(support.TESTFN,
370n/a os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
371n/a self.assertRaises(OSError, os.open, support.TESTFN,
372n/a os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
373n/a os.close(fd)
374n/a
375n/a @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
376n/a 'test needs posix.O_SHLOCK')
377n/a def test_osshlock(self):
378n/a fd1 = os.open(support.TESTFN,
379n/a os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
380n/a fd2 = os.open(support.TESTFN,
381n/a os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
382n/a os.close(fd2)
383n/a os.close(fd1)
384n/a
385n/a if hasattr(posix, "O_EXLOCK"):
386n/a fd = os.open(support.TESTFN,
387n/a os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
388n/a self.assertRaises(OSError, os.open, support.TESTFN,
389n/a os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
390n/a os.close(fd)
391n/a
392n/a @unittest.skipUnless(hasattr(posix, 'fstat'),
393n/a 'test needs posix.fstat()')
394n/a def test_fstat(self):
395n/a fp = open(support.TESTFN)
396n/a try:
397n/a self.assertTrue(posix.fstat(fp.fileno()))
398n/a self.assertTrue(posix.stat(fp.fileno()))
399n/a
400n/a self.assertRaisesRegex(TypeError,
401n/a 'should be string, bytes, os.PathLike or integer, not',
402n/a posix.stat, float(fp.fileno()))
403n/a finally:
404n/a fp.close()
405n/a
406n/a @unittest.skipUnless(hasattr(posix, 'stat'),
407n/a 'test needs posix.stat()')
408n/a def test_stat(self):
409n/a self.assertTrue(posix.stat(support.TESTFN))
410n/a self.assertTrue(posix.stat(os.fsencode(support.TESTFN)))
411n/a
412n/a self.assertWarnsRegex(DeprecationWarning,
413n/a 'should be string, bytes, os.PathLike or integer, not',
414n/a posix.stat, bytearray(os.fsencode(support.TESTFN)))
415n/a self.assertRaisesRegex(TypeError,
416n/a 'should be string, bytes, os.PathLike or integer, not',
417n/a posix.stat, None)
418n/a self.assertRaisesRegex(TypeError,
419n/a 'should be string, bytes, os.PathLike or integer, not',
420n/a posix.stat, list(support.TESTFN))
421n/a self.assertRaisesRegex(TypeError,
422n/a 'should be string, bytes, os.PathLike or integer, not',
423n/a posix.stat, list(os.fsencode(support.TESTFN)))
424n/a
425n/a @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
426n/a @unittest.skipIf(android_not_root, "mkfifo not allowed, non root user")
427n/a def test_mkfifo(self):
428n/a support.unlink(support.TESTFN)
429n/a posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
430n/a self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
431n/a
432n/a @unittest.skipUnless(hasattr(posix, 'mknod') and hasattr(stat, 'S_IFIFO'),
433n/a "don't have mknod()/S_IFIFO")
434n/a @unittest.skipIf(android_not_root, "mknod not allowed, non root user")
435n/a def test_mknod(self):
436n/a # Test using mknod() to create a FIFO (the only use specified
437n/a # by POSIX).
438n/a support.unlink(support.TESTFN)
439n/a mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
440n/a try:
441n/a posix.mknod(support.TESTFN, mode, 0)
442n/a except OSError as e:
443n/a # Some old systems don't allow unprivileged users to use
444n/a # mknod(), or only support creating device nodes.
445n/a self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
446n/a else:
447n/a self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
448n/a
449n/a # Keyword arguments are also supported
450n/a support.unlink(support.TESTFN)
451n/a try:
452n/a posix.mknod(path=support.TESTFN, mode=mode, device=0,
453n/a dir_fd=None)
454n/a except OSError as e:
455n/a self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
456n/a
457n/a @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
458n/a @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
459n/a def test_makedev(self):
460n/a st = posix.stat(support.TESTFN)
461n/a dev = st.st_dev
462n/a self.assertIsInstance(dev, int)
463n/a self.assertGreaterEqual(dev, 0)
464n/a
465n/a major = posix.major(dev)
466n/a self.assertIsInstance(major, int)
467n/a self.assertGreaterEqual(major, 0)
468n/a self.assertEqual(posix.major(dev), major)
469n/a self.assertRaises(TypeError, posix.major, float(dev))
470n/a self.assertRaises(TypeError, posix.major)
471n/a self.assertRaises((ValueError, OverflowError), posix.major, -1)
472n/a
473n/a minor = posix.minor(dev)
474n/a self.assertIsInstance(minor, int)
475n/a self.assertGreaterEqual(minor, 0)
476n/a self.assertEqual(posix.minor(dev), minor)
477n/a self.assertRaises(TypeError, posix.minor, float(dev))
478n/a self.assertRaises(TypeError, posix.minor)
479n/a self.assertRaises((ValueError, OverflowError), posix.minor, -1)
480n/a
481n/a self.assertEqual(posix.makedev(major, minor), dev)
482n/a self.assertRaises(TypeError, posix.makedev, float(major), minor)
483n/a self.assertRaises(TypeError, posix.makedev, major, float(minor))
484n/a self.assertRaises(TypeError, posix.makedev, major)
485n/a self.assertRaises(TypeError, posix.makedev)
486n/a
487n/a def _test_all_chown_common(self, chown_func, first_param, stat_func):
488n/a """Common code for chown, fchown and lchown tests."""
489n/a def check_stat(uid, gid):
490n/a if stat_func is not None:
491n/a stat = stat_func(first_param)
492n/a self.assertEqual(stat.st_uid, uid)
493n/a self.assertEqual(stat.st_gid, gid)
494n/a uid = os.getuid()
495n/a gid = os.getgid()
496n/a # test a successful chown call
497n/a chown_func(first_param, uid, gid)
498n/a check_stat(uid, gid)
499n/a chown_func(first_param, -1, gid)
500n/a check_stat(uid, gid)
501n/a chown_func(first_param, uid, -1)
502n/a check_stat(uid, gid)
503n/a
504n/a if uid == 0:
505n/a # Try an amusingly large uid/gid to make sure we handle
506n/a # large unsigned values. (chown lets you use any
507n/a # uid/gid you like, even if they aren't defined.)
508n/a #
509n/a # This problem keeps coming up:
510n/a # http://bugs.python.org/issue1747858
511n/a # http://bugs.python.org/issue4591
512n/a # http://bugs.python.org/issue15301
513n/a # Hopefully the fix in 4591 fixes it for good!
514n/a #
515n/a # This part of the test only runs when run as root.
516n/a # Only scary people run their tests as root.
517n/a
518n/a big_value = 2**31
519n/a chown_func(first_param, big_value, big_value)
520n/a check_stat(big_value, big_value)
521n/a chown_func(first_param, -1, -1)
522n/a check_stat(big_value, big_value)
523n/a chown_func(first_param, uid, gid)
524n/a check_stat(uid, gid)
525n/a elif platform.system() in ('HP-UX', 'SunOS'):
526n/a # HP-UX and Solaris can allow a non-root user to chown() to root
527n/a # (issue #5113)
528n/a raise unittest.SkipTest("Skipping because of non-standard chown() "
529n/a "behavior")
530n/a else:
531n/a # non-root cannot chown to root, raises OSError
532n/a self.assertRaises(OSError, chown_func, first_param, 0, 0)
533n/a check_stat(uid, gid)
534n/a self.assertRaises(OSError, chown_func, first_param, 0, -1)
535n/a check_stat(uid, gid)
536n/a if 0 not in os.getgroups():
537n/a self.assertRaises(OSError, chown_func, first_param, -1, 0)
538n/a check_stat(uid, gid)
539n/a # test illegal types
540n/a for t in str, float:
541n/a self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
542n/a check_stat(uid, gid)
543n/a self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
544n/a check_stat(uid, gid)
545n/a
546n/a @unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
547n/a def test_chown(self):
548n/a # raise an OSError if the file does not exist
549n/a os.unlink(support.TESTFN)
550n/a self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
551n/a
552n/a # re-create the file
553n/a support.create_empty_file(support.TESTFN)
554n/a self._test_all_chown_common(posix.chown, support.TESTFN,
555n/a getattr(posix, 'stat', None))
556n/a
557n/a @unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
558n/a def test_fchown(self):
559n/a os.unlink(support.TESTFN)
560n/a
561n/a # re-create the file
562n/a test_file = open(support.TESTFN, 'w')
563n/a try:
564n/a fd = test_file.fileno()
565n/a self._test_all_chown_common(posix.fchown, fd,
566n/a getattr(posix, 'fstat', None))
567n/a finally:
568n/a test_file.close()
569n/a
570n/a @unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
571n/a def test_lchown(self):
572n/a os.unlink(support.TESTFN)
573n/a # create a symlink
574n/a os.symlink(_DUMMY_SYMLINK, support.TESTFN)
575n/a self._test_all_chown_common(posix.lchown, support.TESTFN,
576n/a getattr(posix, 'lstat', None))
577n/a
578n/a @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
579n/a def test_chdir(self):
580n/a posix.chdir(os.curdir)
581n/a self.assertRaises(OSError, posix.chdir, support.TESTFN)
582n/a
583n/a def test_listdir(self):
584n/a self.assertTrue(support.TESTFN in posix.listdir(os.curdir))
585n/a
586n/a def test_listdir_default(self):
587n/a # When listdir is called without argument,
588n/a # it's the same as listdir(os.curdir).
589n/a self.assertTrue(support.TESTFN in posix.listdir())
590n/a
591n/a def test_listdir_bytes(self):
592n/a # When listdir is called with a bytes object,
593n/a # the returned strings are of type bytes.
594n/a self.assertTrue(os.fsencode(support.TESTFN) in posix.listdir(b'.'))
595n/a
596n/a @unittest.skipUnless(posix.listdir in os.supports_fd,
597n/a "test needs fd support for posix.listdir()")
598n/a def test_listdir_fd(self):
599n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
600n/a self.addCleanup(posix.close, f)
601n/a self.assertEqual(
602n/a sorted(posix.listdir('.')),
603n/a sorted(posix.listdir(f))
604n/a )
605n/a # Check that the fd offset was reset (issue #13739)
606n/a self.assertEqual(
607n/a sorted(posix.listdir('.')),
608n/a sorted(posix.listdir(f))
609n/a )
610n/a
611n/a @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
612n/a def test_access(self):
613n/a self.assertTrue(posix.access(support.TESTFN, os.R_OK))
614n/a
615n/a @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
616n/a def test_umask(self):
617n/a old_mask = posix.umask(0)
618n/a self.assertIsInstance(old_mask, int)
619n/a posix.umask(old_mask)
620n/a
621n/a @unittest.skipUnless(hasattr(posix, 'strerror'),
622n/a 'test needs posix.strerror()')
623n/a def test_strerror(self):
624n/a self.assertTrue(posix.strerror(0))
625n/a
626n/a @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
627n/a def test_pipe(self):
628n/a reader, writer = posix.pipe()
629n/a os.close(reader)
630n/a os.close(writer)
631n/a
632n/a @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
633n/a @support.requires_linux_version(2, 6, 27)
634n/a def test_pipe2(self):
635n/a self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
636n/a self.assertRaises(TypeError, os.pipe2, 0, 0)
637n/a
638n/a # try calling with flags = 0, like os.pipe()
639n/a r, w = os.pipe2(0)
640n/a os.close(r)
641n/a os.close(w)
642n/a
643n/a # test flags
644n/a r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
645n/a self.addCleanup(os.close, r)
646n/a self.addCleanup(os.close, w)
647n/a self.assertFalse(os.get_inheritable(r))
648n/a self.assertFalse(os.get_inheritable(w))
649n/a self.assertFalse(os.get_blocking(r))
650n/a self.assertFalse(os.get_blocking(w))
651n/a # try reading from an empty pipe: this should fail, not block
652n/a self.assertRaises(OSError, os.read, r, 1)
653n/a # try a write big enough to fill-up the pipe: this should either
654n/a # fail or perform a partial write, not block
655n/a try:
656n/a os.write(w, b'x' * support.PIPE_MAX_SIZE)
657n/a except OSError:
658n/a pass
659n/a
660n/a @support.cpython_only
661n/a @unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
662n/a @support.requires_linux_version(2, 6, 27)
663n/a def test_pipe2_c_limits(self):
664n/a # Issue 15989
665n/a import _testcapi
666n/a self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
667n/a self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
668n/a
669n/a @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
670n/a def test_utime(self):
671n/a now = time.time()
672n/a posix.utime(support.TESTFN, None)
673n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None))
674n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None))
675n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now))
676n/a posix.utime(support.TESTFN, (int(now), int(now)))
677n/a posix.utime(support.TESTFN, (now, now))
678n/a
679n/a def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
680n/a st = os.stat(target_file)
681n/a self.assertTrue(hasattr(st, 'st_flags'))
682n/a
683n/a # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
684n/a flags = st.st_flags | stat.UF_IMMUTABLE
685n/a try:
686n/a chflags_func(target_file, flags, **kwargs)
687n/a except OSError as err:
688n/a if err.errno != errno.EOPNOTSUPP:
689n/a raise
690n/a msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
691n/a self.skipTest(msg)
692n/a
693n/a try:
694n/a new_st = os.stat(target_file)
695n/a self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
696n/a try:
697n/a fd = open(target_file, 'w+')
698n/a except OSError as e:
699n/a self.assertEqual(e.errno, errno.EPERM)
700n/a finally:
701n/a posix.chflags(target_file, st.st_flags)
702n/a
703n/a @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
704n/a def test_chflags(self):
705n/a self._test_chflags_regular_file(posix.chflags, support.TESTFN)
706n/a
707n/a @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
708n/a def test_lchflags_regular_file(self):
709n/a self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
710n/a self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=False)
711n/a
712n/a @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
713n/a def test_lchflags_symlink(self):
714n/a testfn_st = os.stat(support.TESTFN)
715n/a
716n/a self.assertTrue(hasattr(testfn_st, 'st_flags'))
717n/a
718n/a os.symlink(support.TESTFN, _DUMMY_SYMLINK)
719n/a self.teardown_files.append(_DUMMY_SYMLINK)
720n/a dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
721n/a
722n/a def chflags_nofollow(path, flags):
723n/a return posix.chflags(path, flags, follow_symlinks=False)
724n/a
725n/a for fn in (posix.lchflags, chflags_nofollow):
726n/a # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
727n/a flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
728n/a try:
729n/a fn(_DUMMY_SYMLINK, flags)
730n/a except OSError as err:
731n/a if err.errno != errno.EOPNOTSUPP:
732n/a raise
733n/a msg = 'chflag UF_IMMUTABLE not supported by underlying fs'
734n/a self.skipTest(msg)
735n/a try:
736n/a new_testfn_st = os.stat(support.TESTFN)
737n/a new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
738n/a
739n/a self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
740n/a self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
741n/a new_dummy_symlink_st.st_flags)
742n/a finally:
743n/a fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
744n/a
745n/a def test_environ(self):
746n/a if os.name == "nt":
747n/a item_type = str
748n/a else:
749n/a item_type = bytes
750n/a for k, v in posix.environ.items():
751n/a self.assertEqual(type(k), item_type)
752n/a self.assertEqual(type(v), item_type)
753n/a
754n/a @unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
755n/a def test_getcwd_long_pathnames(self):
756n/a dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
757n/a curdir = os.getcwd()
758n/a base_path = os.path.abspath(support.TESTFN) + '.getcwd'
759n/a
760n/a try:
761n/a os.mkdir(base_path)
762n/a os.chdir(base_path)
763n/a except:
764n/a # Just returning nothing instead of the SkipTest exception, because
765n/a # the test results in Error in that case. Is that ok?
766n/a # raise unittest.SkipTest("cannot create directory for testing")
767n/a return
768n/a
769n/a def _create_and_do_getcwd(dirname, current_path_length = 0):
770n/a try:
771n/a os.mkdir(dirname)
772n/a except:
773n/a raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")
774n/a
775n/a os.chdir(dirname)
776n/a try:
777n/a os.getcwd()
778n/a if current_path_length < 1027:
779n/a _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
780n/a finally:
781n/a os.chdir('..')
782n/a os.rmdir(dirname)
783n/a
784n/a _create_and_do_getcwd(dirname)
785n/a
786n/a finally:
787n/a os.chdir(curdir)
788n/a support.rmtree(base_path)
789n/a
790n/a @unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
791n/a @unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
792n/a @unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
793n/a def test_getgrouplist(self):
794n/a user = pwd.getpwuid(os.getuid())[0]
795n/a group = pwd.getpwuid(os.getuid())[3]
796n/a self.assertIn(group, posix.getgrouplist(user, group))
797n/a
798n/a
799n/a @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
800n/a def test_getgroups(self):
801n/a with os.popen('id -G 2>/dev/null') as idg:
802n/a groups = idg.read().strip()
803n/a ret = idg.close()
804n/a
805n/a try:
806n/a idg_groups = set(int(g) for g in groups.split())
807n/a except ValueError:
808n/a idg_groups = set()
809n/a if ret is not None or not idg_groups:
810n/a raise unittest.SkipTest("need working 'id -G'")
811n/a
812n/a # Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
813n/a if sys.platform == 'darwin':
814n/a import sysconfig
815n/a dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') or '10.0'
816n/a if tuple(int(n) for n in dt.split('.')[0:2]) < (10, 6):
817n/a raise unittest.SkipTest("getgroups(2) is broken prior to 10.6")
818n/a
819n/a # 'id -G' and 'os.getgroups()' should return the same
820n/a # groups, ignoring order, duplicates, and the effective gid.
821n/a # #10822/#26944 - It is implementation defined whether
822n/a # posix.getgroups() includes the effective gid.
823n/a symdiff = idg_groups.symmetric_difference(posix.getgroups())
824n/a self.assertTrue(not symdiff or symdiff == {posix.getegid()})
825n/a
826n/a # tests for the posix *at functions follow
827n/a
828n/a @unittest.skipUnless(os.access in os.supports_dir_fd, "test needs dir_fd support for os.access()")
829n/a def test_access_dir_fd(self):
830n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
831n/a try:
832n/a self.assertTrue(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
833n/a finally:
834n/a posix.close(f)
835n/a
836n/a @unittest.skipUnless(os.chmod in os.supports_dir_fd, "test needs dir_fd support in os.chmod()")
837n/a def test_chmod_dir_fd(self):
838n/a os.chmod(support.TESTFN, stat.S_IRUSR)
839n/a
840n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
841n/a try:
842n/a posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
843n/a
844n/a s = posix.stat(support.TESTFN)
845n/a self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
846n/a finally:
847n/a posix.close(f)
848n/a
849n/a @unittest.skipUnless(os.chown in os.supports_dir_fd, "test needs dir_fd support in os.chown()")
850n/a def test_chown_dir_fd(self):
851n/a support.unlink(support.TESTFN)
852n/a support.create_empty_file(support.TESTFN)
853n/a
854n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
855n/a try:
856n/a posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
857n/a finally:
858n/a posix.close(f)
859n/a
860n/a @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()")
861n/a def test_stat_dir_fd(self):
862n/a support.unlink(support.TESTFN)
863n/a with open(support.TESTFN, 'w') as outfile:
864n/a outfile.write("testline\n")
865n/a
866n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
867n/a try:
868n/a s1 = posix.stat(support.TESTFN)
869n/a s2 = posix.stat(support.TESTFN, dir_fd=f)
870n/a self.assertEqual(s1, s2)
871n/a s2 = posix.stat(support.TESTFN, dir_fd=None)
872n/a self.assertEqual(s1, s2)
873n/a self.assertRaisesRegex(TypeError, 'should be integer or None, not',
874n/a posix.stat, support.TESTFN, dir_fd=posix.getcwd())
875n/a self.assertRaisesRegex(TypeError, 'should be integer or None, not',
876n/a posix.stat, support.TESTFN, dir_fd=float(f))
877n/a self.assertRaises(OverflowError,
878n/a posix.stat, support.TESTFN, dir_fd=10**20)
879n/a finally:
880n/a posix.close(f)
881n/a
882n/a @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
883n/a def test_utime_dir_fd(self):
884n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
885n/a try:
886n/a now = time.time()
887n/a posix.utime(support.TESTFN, None, dir_fd=f)
888n/a posix.utime(support.TESTFN, dir_fd=f)
889n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
890n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, None), dir_fd=f)
891n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, None), dir_fd=f)
892n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (None, now), dir_fd=f)
893n/a self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
894n/a posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
895n/a posix.utime(support.TESTFN, (now, now), dir_fd=f)
896n/a posix.utime(support.TESTFN,
897n/a (int(now), int((now - int(now)) * 1e9)), dir_fd=f)
898n/a posix.utime(support.TESTFN, dir_fd=f,
899n/a times=(int(now), int((now - int(now)) * 1e9)))
900n/a
901n/a # try dir_fd and follow_symlinks together
902n/a if os.utime in os.supports_follow_symlinks:
903n/a try:
904n/a posix.utime(support.TESTFN, follow_symlinks=False, dir_fd=f)
905n/a except ValueError:
906n/a # whoops! using both together not supported on this platform.
907n/a pass
908n/a
909n/a finally:
910n/a posix.close(f)
911n/a
912n/a @unittest.skipUnless(os.link in os.supports_dir_fd, "test needs dir_fd support in os.link()")
913n/a @unittest.skipIf(android_not_root, "hard link not allowed, non root user")
914n/a def test_link_dir_fd(self):
915n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
916n/a try:
917n/a posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
918n/a # should have same inodes
919n/a self.assertEqual(posix.stat(support.TESTFN)[1],
920n/a posix.stat(support.TESTFN + 'link')[1])
921n/a finally:
922n/a posix.close(f)
923n/a support.unlink(support.TESTFN + 'link')
924n/a
925n/a @unittest.skipUnless(os.mkdir in os.supports_dir_fd, "test needs dir_fd support in os.mkdir()")
926n/a def test_mkdir_dir_fd(self):
927n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
928n/a try:
929n/a posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
930n/a posix.stat(support.TESTFN + 'dir') # should not raise exception
931n/a finally:
932n/a posix.close(f)
933n/a support.rmtree(support.TESTFN + 'dir')
934n/a
935n/a @unittest.skipUnless((os.mknod in os.supports_dir_fd) and hasattr(stat, 'S_IFIFO'),
936n/a "test requires both stat.S_IFIFO and dir_fd support for os.mknod()")
937n/a @unittest.skipIf(android_not_root, "mknod not allowed, non root user")
938n/a def test_mknod_dir_fd(self):
939n/a # Test using mknodat() to create a FIFO (the only use specified
940n/a # by POSIX).
941n/a support.unlink(support.TESTFN)
942n/a mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
943n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
944n/a try:
945n/a posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
946n/a except OSError as e:
947n/a # Some old systems don't allow unprivileged users to use
948n/a # mknod(), or only support creating device nodes.
949n/a self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
950n/a else:
951n/a self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
952n/a finally:
953n/a posix.close(f)
954n/a
955n/a @unittest.skipUnless(os.open in os.supports_dir_fd, "test needs dir_fd support in os.open()")
956n/a def test_open_dir_fd(self):
957n/a support.unlink(support.TESTFN)
958n/a with open(support.TESTFN, 'w') as outfile:
959n/a outfile.write("testline\n")
960n/a a = posix.open(posix.getcwd(), posix.O_RDONLY)
961n/a b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
962n/a try:
963n/a res = posix.read(b, 9).decode(encoding="utf-8")
964n/a self.assertEqual("testline\n", res)
965n/a finally:
966n/a posix.close(a)
967n/a posix.close(b)
968n/a
969n/a @unittest.skipUnless(os.readlink in os.supports_dir_fd, "test needs dir_fd support in os.readlink()")
970n/a def test_readlink_dir_fd(self):
971n/a os.symlink(support.TESTFN, support.TESTFN + 'link')
972n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
973n/a try:
974n/a self.assertEqual(posix.readlink(support.TESTFN + 'link'),
975n/a posix.readlink(support.TESTFN + 'link', dir_fd=f))
976n/a finally:
977n/a support.unlink(support.TESTFN + 'link')
978n/a posix.close(f)
979n/a
980n/a @unittest.skipUnless(os.rename in os.supports_dir_fd, "test needs dir_fd support in os.rename()")
981n/a def test_rename_dir_fd(self):
982n/a support.unlink(support.TESTFN)
983n/a support.create_empty_file(support.TESTFN + 'ren')
984n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
985n/a try:
986n/a posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
987n/a except:
988n/a posix.rename(support.TESTFN + 'ren', support.TESTFN)
989n/a raise
990n/a else:
991n/a posix.stat(support.TESTFN) # should not raise exception
992n/a finally:
993n/a posix.close(f)
994n/a
995n/a @unittest.skipUnless(os.symlink in os.supports_dir_fd, "test needs dir_fd support in os.symlink()")
996n/a def test_symlink_dir_fd(self):
997n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
998n/a try:
999n/a posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
1000n/a self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
1001n/a finally:
1002n/a posix.close(f)
1003n/a support.unlink(support.TESTFN + 'link')
1004n/a
1005n/a @unittest.skipUnless(os.unlink in os.supports_dir_fd, "test needs dir_fd support in os.unlink()")
1006n/a def test_unlink_dir_fd(self):
1007n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
1008n/a support.create_empty_file(support.TESTFN + 'del')
1009n/a posix.stat(support.TESTFN + 'del') # should not raise exception
1010n/a try:
1011n/a posix.unlink(support.TESTFN + 'del', dir_fd=f)
1012n/a except:
1013n/a support.unlink(support.TESTFN + 'del')
1014n/a raise
1015n/a else:
1016n/a self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
1017n/a finally:
1018n/a posix.close(f)
1019n/a
1020n/a @unittest.skipUnless(os.mkfifo in os.supports_dir_fd, "test needs dir_fd support in os.mkfifo()")
1021n/a @unittest.skipIf(android_not_root, "mkfifo not allowed, non root user")
1022n/a def test_mkfifo_dir_fd(self):
1023n/a support.unlink(support.TESTFN)
1024n/a f = posix.open(posix.getcwd(), posix.O_RDONLY)
1025n/a try:
1026n/a posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
1027n/a self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
1028n/a finally:
1029n/a posix.close(f)
1030n/a
1031n/a requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_yield'),
1032n/a "don't have scheduling support")
1033n/a requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
1034n/a "don't have sched affinity support")
1035n/a
1036n/a @requires_sched_h
1037n/a def test_sched_yield(self):
1038n/a # This has no error conditions (at least on Linux).
1039n/a posix.sched_yield()
1040n/a
1041n/a @requires_sched_h
1042n/a @unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
1043n/a "requires sched_get_priority_max()")
1044n/a def test_sched_priority(self):
1045n/a # Round-robin usually has interesting priorities.
1046n/a pol = posix.SCHED_RR
1047n/a lo = posix.sched_get_priority_min(pol)
1048n/a hi = posix.sched_get_priority_max(pol)
1049n/a self.assertIsInstance(lo, int)
1050n/a self.assertIsInstance(hi, int)
1051n/a self.assertGreaterEqual(hi, lo)
1052n/a # OSX evidently just returns 15 without checking the argument.
1053n/a if sys.platform != "darwin":
1054n/a self.assertRaises(OSError, posix.sched_get_priority_min, -23)
1055n/a self.assertRaises(OSError, posix.sched_get_priority_max, -23)
1056n/a
1057n/a @unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
1058n/a def test_get_and_set_scheduler_and_param(self):
1059n/a possible_schedulers = [sched for name, sched in posix.__dict__.items()
1060n/a if name.startswith("SCHED_")]
1061n/a mine = posix.sched_getscheduler(0)
1062n/a self.assertIn(mine, possible_schedulers)
1063n/a try:
1064n/a parent = posix.sched_getscheduler(os.getppid())
1065n/a except OSError as e:
1066n/a if e.errno != errno.EPERM:
1067n/a raise
1068n/a else:
1069n/a self.assertIn(parent, possible_schedulers)
1070n/a self.assertRaises(OSError, posix.sched_getscheduler, -1)
1071n/a self.assertRaises(OSError, posix.sched_getparam, -1)
1072n/a param = posix.sched_getparam(0)
1073n/a self.assertIsInstance(param.sched_priority, int)
1074n/a
1075n/a # POSIX states that calling sched_setparam() or sched_setscheduler() on
1076n/a # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
1077n/a # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
1078n/a if not sys.platform.startswith(('freebsd', 'netbsd')):
1079n/a try:
1080n/a posix.sched_setscheduler(0, mine, param)
1081n/a posix.sched_setparam(0, param)
1082n/a except OSError as e:
1083n/a if e.errno != errno.EPERM:
1084n/a raise
1085n/a self.assertRaises(OSError, posix.sched_setparam, -1, param)
1086n/a
1087n/a self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
1088n/a self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, None)
1089n/a self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
1090n/a param = posix.sched_param(None)
1091n/a self.assertRaises(TypeError, posix.sched_setparam, 0, param)
1092n/a large = 214748364700
1093n/a param = posix.sched_param(large)
1094n/a self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1095n/a param = posix.sched_param(sched_priority=-large)
1096n/a self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
1097n/a
1098n/a @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
1099n/a def test_sched_rr_get_interval(self):
1100n/a try:
1101n/a interval = posix.sched_rr_get_interval(0)
1102n/a except OSError as e:
1103n/a # This likely means that sched_rr_get_interval is only valid for
1104n/a # processes with the SCHED_RR scheduler in effect.
1105n/a if e.errno != errno.EINVAL:
1106n/a raise
1107n/a self.skipTest("only works on SCHED_RR processes")
1108n/a self.assertIsInstance(interval, float)
1109n/a # Reasonable constraints, I think.
1110n/a self.assertGreaterEqual(interval, 0.)
1111n/a self.assertLess(interval, 1.)
1112n/a
1113n/a @requires_sched_affinity
1114n/a def test_sched_getaffinity(self):
1115n/a mask = posix.sched_getaffinity(0)
1116n/a self.assertIsInstance(mask, set)
1117n/a self.assertGreaterEqual(len(mask), 1)
1118n/a self.assertRaises(OSError, posix.sched_getaffinity, -1)
1119n/a for cpu in mask:
1120n/a self.assertIsInstance(cpu, int)
1121n/a self.assertGreaterEqual(cpu, 0)
1122n/a self.assertLess(cpu, 1 << 32)
1123n/a
1124n/a @requires_sched_affinity
1125n/a def test_sched_setaffinity(self):
1126n/a mask = posix.sched_getaffinity(0)
1127n/a if len(mask) > 1:
1128n/a # Empty masks are forbidden
1129n/a mask.pop()
1130n/a posix.sched_setaffinity(0, mask)
1131n/a self.assertEqual(posix.sched_getaffinity(0), mask)
1132n/a self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
1133n/a self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
1134n/a self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
1135n/a self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
1136n/a
1137n/a def test_rtld_constants(self):
1138n/a # check presence of major RTLD_* constants
1139n/a posix.RTLD_LAZY
1140n/a posix.RTLD_NOW
1141n/a posix.RTLD_GLOBAL
1142n/a posix.RTLD_LOCAL
1143n/a
1144n/a @unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
1145n/a "test needs an OS that reports file holes")
1146n/a def test_fs_holes(self):
1147n/a # Even if the filesystem doesn't report holes,
1148n/a # if the OS supports it the SEEK_* constants
1149n/a # will be defined and will have a consistent
1150n/a # behaviour:
1151n/a # os.SEEK_DATA = current position
1152n/a # os.SEEK_HOLE = end of file position
1153n/a with open(support.TESTFN, 'r+b') as fp:
1154n/a fp.write(b"hello")
1155n/a fp.flush()
1156n/a size = fp.tell()
1157n/a fno = fp.fileno()
1158n/a try :
1159n/a for i in range(size):
1160n/a self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
1161n/a self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
1162n/a self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
1163n/a self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
1164n/a except OSError :
1165n/a # Some OSs claim to support SEEK_HOLE/SEEK_DATA
1166n/a # but it is not true.
1167n/a # For instance:
1168n/a # http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
1169n/a raise unittest.SkipTest("OSError raised!")
1170n/a
1171n/a def test_path_error2(self):
1172n/a """
1173n/a Test functions that call path_error2(), providing two filenames in their exceptions.
1174n/a """
1175n/a for name in ("rename", "replace", "link"):
1176n/a function = getattr(os, name, None)
1177n/a if function is None:
1178n/a continue
1179n/a
1180n/a for dst in ("noodly2", support.TESTFN):
1181n/a try:
1182n/a function('doesnotexistfilename', dst)
1183n/a except OSError as e:
1184n/a self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
1185n/a break
1186n/a else:
1187n/a self.fail("No valid path_error2() test for os." + name)
1188n/a
1189n/a def test_path_with_null_character(self):
1190n/a fn = support.TESTFN
1191n/a fn_with_NUL = fn + '\0'
1192n/a self.addCleanup(support.unlink, fn)
1193n/a support.unlink(fn)
1194n/a fd = None
1195n/a try:
1196n/a with self.assertRaises(ValueError):
1197n/a fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1198n/a finally:
1199n/a if fd is not None:
1200n/a os.close(fd)
1201n/a self.assertFalse(os.path.exists(fn))
1202n/a self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1203n/a self.assertFalse(os.path.exists(fn))
1204n/a open(fn, 'wb').close()
1205n/a self.assertRaises(ValueError, os.stat, fn_with_NUL)
1206n/a
1207n/a def test_path_with_null_byte(self):
1208n/a fn = os.fsencode(support.TESTFN)
1209n/a fn_with_NUL = fn + b'\0'
1210n/a self.addCleanup(support.unlink, fn)
1211n/a support.unlink(fn)
1212n/a fd = None
1213n/a try:
1214n/a with self.assertRaises(ValueError):
1215n/a fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # raises
1216n/a finally:
1217n/a if fd is not None:
1218n/a os.close(fd)
1219n/a self.assertFalse(os.path.exists(fn))
1220n/a self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
1221n/a self.assertFalse(os.path.exists(fn))
1222n/a open(fn, 'wb').close()
1223n/a self.assertRaises(ValueError, os.stat, fn_with_NUL)
1224n/a
1225n/aclass PosixGroupsTester(unittest.TestCase):
1226n/a
1227n/a def setUp(self):
1228n/a if posix.getuid() != 0:
1229n/a raise unittest.SkipTest("not enough privileges")
1230n/a if not hasattr(posix, 'getgroups'):
1231n/a raise unittest.SkipTest("need posix.getgroups")
1232n/a if sys.platform == 'darwin':
1233n/a raise unittest.SkipTest("getgroups(2) is broken on OSX")
1234n/a self.saved_groups = posix.getgroups()
1235n/a
1236n/a def tearDown(self):
1237n/a if hasattr(posix, 'setgroups'):
1238n/a posix.setgroups(self.saved_groups)
1239n/a elif hasattr(posix, 'initgroups'):
1240n/a name = pwd.getpwuid(posix.getuid()).pw_name
1241n/a posix.initgroups(name, self.saved_groups[0])
1242n/a
1243n/a @unittest.skipUnless(hasattr(posix, 'initgroups'),
1244n/a "test needs posix.initgroups()")
1245n/a def test_initgroups(self):
1246n/a # find missing group
1247n/a
1248n/a g = max(self.saved_groups or [0]) + 1
1249n/a name = pwd.getpwuid(posix.getuid()).pw_name
1250n/a posix.initgroups(name, g)
1251n/a self.assertIn(g, posix.getgroups())
1252n/a
1253n/a @unittest.skipUnless(hasattr(posix, 'setgroups'),
1254n/a "test needs posix.setgroups()")
1255n/a def test_setgroups(self):
1256n/a for groups in [[0], list(range(16))]:
1257n/a posix.setgroups(groups)
1258n/a self.assertListEqual(groups, posix.getgroups())
1259n/a
1260n/adef test_main():
1261n/a try:
1262n/a support.run_unittest(PosixTester, PosixGroupsTester)
1263n/a finally:
1264n/a support.reap_children()
1265n/a
1266n/aif __name__ == '__main__':
1267n/a test_main()