Debian Codegraph @

Lib/test/test_os.py

raw
1 # As a test suite for the os module, this is woefully inadequate, but this
2 # does add tests for a few functions which have been determined to be more
3 # portable than they had been thought to be.
4
5 import asyncio
6 import codecs
7 import contextlib
8 import decimal
9 import errno
10 import fnmatch
11 import fractions
12 import itertools
13 import locale
14 import os
15 import pickle
16 import select
17 import selectors
18 import shutil
19 import signal
20 import socket
21 import stat
22 import struct
23 import subprocess
24 import sys
25 import sysconfig
26 import tempfile
27 import textwrap
28 import time
29 import types
30 import unittest
31 import uuid
32 import warnings
33 from test import support
34 from test.support import import_helper
35 from test.support import os_helper
36 from test.support import socket_helper
37 from test.support import infinite_recursion
38 from test.support import warnings_helper
39 from platform import win32_is_iot
40
41 try:
42 import resource
43 except ImportError:
44 resource = None
45 try:
46 import fcntl
47 except ImportError:
48 fcntl = None
49 try:
50 import _winapi
51 except ImportError:
52 _winapi = None
53 try:
54 import pwd
55 all_users = [u.pw_uid for u in pwd.getpwall()]
56 except (ImportError, AttributeError):
57 all_users = []
58 try:
59 import _testcapi
60 from _testcapi import INT_MAX, PY_SSIZE_T_MAX
61 except ImportError:
62 _testcapi = None
63 INT_MAX = PY_SSIZE_T_MAX = sys.maxsize
64
65 try:
66 import mmap
67 except ImportError:
68 mmap = None
69
70 from test.support.script_helper import assert_python_ok
71 from test.support import unix_shell
72 from test.support.os_helper import FakePath
73
74
75 root_in_posix = False
76 if hasattr(os, 'geteuid'):
77 root_in_posix = (os.geteuid() == 0)
78
79 # Detect whether we're on a Linux system that uses the (now outdated
80 # and unmaintained) linuxthreads threading library. There's an issue
81 # when combining linuxthreads with a failed execv call: see
82 # http://bugs.python.org/issue4970.
83 if hasattr(sys, 'thread_info') and sys.thread_info.version:
84 USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
85 else:
86 USING_LINUXTHREADS = False
87
88 # Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
89 HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
90
91
92 def requires_os_func(name):
93 return unittest.skipUnless(hasattr(os, name), 'requires os.%s' % name)
94
95
96 def create_file(filename, content=b'content'):
97 with open(filename, "xb", 0) as fp:
98 fp.write(content)
99
100
101 # bpo-41625: On AIX, splice() only works with a socket, not with a pipe.
102 requires_splice_pipe = unittest.skipIf(sys.platform.startswith("aix"),
103 'on AIX, splice() only accepts sockets')
104
105
106 def tearDownModule():
107 asyncio.set_event_loop_policy(None)
108
109
110 class MiscTests(unittest.TestCase):
111 def test_getcwd(self):
112 cwd = os.getcwd()
113 self.assertIsInstance(cwd, str)
114
115 def test_getcwd_long_path(self):
116 # bpo-37412: On Linux, PATH_MAX is usually around 4096 bytes. On
117 # Windows, MAX_PATH is defined as 260 characters, but Windows supports
118 # longer path if longer paths support is enabled. Internally, the os
119 # module uses MAXPATHLEN which is at least 1024.
120 #
121 # Use a directory name of 200 characters to fit into Windows MAX_PATH
122 # limit.
123 #
124 # On Windows, the test can stop when trying to create a path longer
125 # than MAX_PATH if long paths support is disabled:
126 # see RtlAreLongPathsEnabled().
127 min_len = 2000 # characters
128 # On VxWorks, PATH_MAX is defined as 1024 bytes. Creating a path
129 # longer than PATH_MAX will fail.
130 if sys.platform == 'vxworks':
131 min_len = 1000
132 dirlen = 200 # characters
133 dirname = 'python_test_dir_'
134 dirname = dirname + ('a' * (dirlen - len(dirname)))
135
136 with tempfile.TemporaryDirectory() as tmpdir:
137 with os_helper.change_cwd(tmpdir) as path:
138 expected = path
139
140 while True:
141 cwd = os.getcwd()
142 self.assertEqual(cwd, expected)
143
144 need = min_len - (len(cwd) + len(os.path.sep))
145 if need <= 0:
146 break
147 if len(dirname) > need and need > 0:
148 dirname = dirname[:need]
149
150 path = os.path.join(path, dirname)
151 try:
152 os.mkdir(path)
153 # On Windows, chdir() can fail
154 # even if mkdir() succeeded
155 os.chdir(path)
156 except FileNotFoundError:
157 # On Windows, catch ERROR_PATH_NOT_FOUND (3) and
158 # ERROR_FILENAME_EXCED_RANGE (206) errors
159 # ("The filename or extension is too long")
160 break
161 except OSError as exc:
162 if exc.errno == errno.ENAMETOOLONG:
163 break
164 else:
165 raise
166
167 expected = path
168
169 if support.verbose:
170 print(f"Tested current directory length: {len(cwd)}")
171
172 def test_getcwdb(self):
173 cwd = os.getcwdb()
174 self.assertIsInstance(cwd, bytes)
175 self.assertEqual(os.fsdecode(cwd), os.getcwd())
176
177
178 # Tests creating TESTFN
179 class FileTests(unittest.TestCase):
180 def setUp(self):
181 if os.path.lexists(os_helper.TESTFN):
182 os.unlink(os_helper.TESTFN)
183 tearDown = setUp
184
185 def test_access(self):
186 f = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
187 os.close(f)
188 self.assertTrue(os.access(os_helper.TESTFN, os.W_OK))
189
190 @unittest.skipIf(
191 support.is_emscripten, "Test is unstable under Emscripten."
192 )
193 @unittest.skipIf(
194 support.is_wasi, "WASI does not support dup."
195 )
196 def test_closerange(self):
197 first = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
198 # We must allocate two consecutive file descriptors, otherwise
199 # it will mess up other file descriptors (perhaps even the three
200 # standard ones).
201 second = os.dup(first)
202 try:
203 retries = 0
204 while second != first + 1:
205 os.close(first)
206 retries += 1
207 if retries > 10:
208 # XXX test skipped
209 self.skipTest("couldn't allocate two consecutive fds")
210 first, second = second, os.dup(second)
211 finally:
212 os.close(second)
213 # close a fd that is open, and one that isn't
214 os.closerange(first, first + 2)
215 self.assertRaises(OSError, os.write, first, b"a")
216
217 @support.cpython_only
218 def test_rename(self):
219 path = os_helper.TESTFN
220 old = sys.getrefcount(path)
221 self.assertRaises(TypeError, os.rename, path, 0)
222 new = sys.getrefcount(path)
223 self.assertEqual(old, new)
224
225 def test_read(self):
226 with open(os_helper.TESTFN, "w+b") as fobj:
227 fobj.write(b"spam")
228 fobj.flush()
229 fd = fobj.fileno()
230 os.lseek(fd, 0, 0)
231 s = os.read(fd, 4)
232 self.assertEqual(type(s), bytes)
233 self.assertEqual(s, b"spam")
234
235 @support.cpython_only
236 # Skip the test on 32-bit platforms: the number of bytes must fit in a
237 # Py_ssize_t type
238 @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX,
239 "needs INT_MAX < PY_SSIZE_T_MAX")
240 @support.bigmemtest(size=INT_MAX + 10, memuse=1, dry_run=False)
241 def test_large_read(self, size):
242 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
243 create_file(os_helper.TESTFN, b'test')
244
245 # Issue #21932: Make sure that os.read() does not raise an
246 # OverflowError for size larger than INT_MAX
247 with open(os_helper.TESTFN, "rb") as fp:
248 data = os.read(fp.fileno(), size)
249
250 # The test does not try to read more than 2 GiB at once because the
251 # operating system is free to return less bytes than requested.
252 self.assertEqual(data, b'test')
253
254 def test_write(self):
255 # os.write() accepts bytes- and buffer-like objects but not strings
256 fd = os.open(os_helper.TESTFN, os.O_CREAT | os.O_WRONLY)
257 self.assertRaises(TypeError, os.write, fd, "beans")
258 os.write(fd, b"bacon\n")
259 os.write(fd, bytearray(b"eggs\n"))
260 os.write(fd, memoryview(b"spam\n"))
261 os.close(fd)
262 with open(os_helper.TESTFN, "rb") as fobj:
263 self.assertEqual(fobj.read().splitlines(),
264 [b"bacon", b"eggs", b"spam"])
265
266 def write_windows_console(self, *args):
267 retcode = subprocess.call(args,
268 # use a new console to not flood the test output
269 creationflags=subprocess.CREATE_NEW_CONSOLE,
270 # use a shell to hide the console window (SW_HIDE)
271 shell=True)
272 self.assertEqual(retcode, 0)
273
274 @unittest.skipUnless(sys.platform == 'win32',
275 'test specific to the Windows console')
276 def test_write_windows_console(self):
277 # Issue #11395: the Windows console returns an error (12: not enough
278 # space error) on writing into stdout if stdout mode is binary and the
279 # length is greater than 66,000 bytes (or less, depending on heap
280 # usage).
281 code = "print('x' * 100000)"
282 self.write_windows_console(sys.executable, "-c", code)
283 self.write_windows_console(sys.executable, "-u", "-c", code)
284
285 def fdopen_helper(self, *args):
286 fd = os.open(os_helper.TESTFN, os.O_RDONLY)
287 f = os.fdopen(fd, *args, encoding="utf-8")
288 f.close()
289
290 def test_fdopen(self):
291 fd = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
292 os.close(fd)
293
294 self.fdopen_helper()
295 self.fdopen_helper('r')
296 self.fdopen_helper('r', 100)
297
298 def test_replace(self):
299 TESTFN2 = os_helper.TESTFN + ".2"
300 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
301 self.addCleanup(os_helper.unlink, TESTFN2)
302
303 create_file(os_helper.TESTFN, b"1")
304 create_file(TESTFN2, b"2")
305
306 os.replace(os_helper.TESTFN, TESTFN2)
307 self.assertRaises(FileNotFoundError, os.stat, os_helper.TESTFN)
308 with open(TESTFN2, 'r', encoding='utf-8') as f:
309 self.assertEqual(f.read(), "1")
310
311 def test_open_keywords(self):
312 f = os.open(path=__file__, flags=os.O_RDONLY, mode=0o777,
313 dir_fd=None)
314 os.close(f)
315
316 def test_symlink_keywords(self):
317 symlink = support.get_attribute(os, "symlink")
318 try:
319 symlink(src='target', dst=os_helper.TESTFN,
320 target_is_directory=False, dir_fd=None)
321 except (NotImplementedError, OSError):
322 pass # No OS support or unprivileged user
323
324 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
325 def test_copy_file_range_invalid_values(self):
326 with self.assertRaises(ValueError):
327 os.copy_file_range(0, 1, -10)
328
329 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
330 def test_copy_file_range(self):
331 TESTFN2 = os_helper.TESTFN + ".3"
332 data = b'0123456789'
333
334 create_file(os_helper.TESTFN, data)
335 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
336
337 in_file = open(os_helper.TESTFN, 'rb')
338 self.addCleanup(in_file.close)
339 in_fd = in_file.fileno()
340
341 out_file = open(TESTFN2, 'w+b')
342 self.addCleanup(os_helper.unlink, TESTFN2)
343 self.addCleanup(out_file.close)
344 out_fd = out_file.fileno()
345
346 try:
347 i = os.copy_file_range(in_fd, out_fd, 5)
348 except OSError as e:
349 # Handle the case in which Python was compiled
350 # in a system with the syscall but without support
351 # in the kernel.
352 if e.errno != errno.ENOSYS:
353 raise
354 self.skipTest(e)
355 else:
356 # The number of copied bytes can be less than
357 # the number of bytes originally requested.
358 self.assertIn(i, range(0, 6));
359
360 with open(TESTFN2, 'rb') as in_file:
361 self.assertEqual(in_file.read(), data[:i])
362
363 @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
364 def test_copy_file_range_offset(self):
365 TESTFN4 = os_helper.TESTFN + ".4"
366 data = b'0123456789'
367 bytes_to_copy = 6
368 in_skip = 3
369 out_seek = 5
370
371 create_file(os_helper.TESTFN, data)
372 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
373
374 in_file = open(os_helper.TESTFN, 'rb')
375 self.addCleanup(in_file.close)
376 in_fd = in_file.fileno()
377
378 out_file = open(TESTFN4, 'w+b')
379 self.addCleanup(os_helper.unlink, TESTFN4)
380 self.addCleanup(out_file.close)
381 out_fd = out_file.fileno()
382
383 try:
384 i = os.copy_file_range(in_fd, out_fd, bytes_to_copy,
385 offset_src=in_skip,
386 offset_dst=out_seek)
387 except OSError as e:
388 # Handle the case in which Python was compiled
389 # in a system with the syscall but without support
390 # in the kernel.
391 if e.errno != errno.ENOSYS:
392 raise
393 self.skipTest(e)
394 else:
395 # The number of copied bytes can be less than
396 # the number of bytes originally requested.
397 self.assertIn(i, range(0, bytes_to_copy+1));
398
399 with open(TESTFN4, 'rb') as in_file:
400 read = in_file.read()
401 # seeked bytes (5) are zero'ed
402 self.assertEqual(read[:out_seek], b'\x00'*out_seek)
403 # 012 are skipped (in_skip)
404 # 345678 are copied in the file (in_skip + bytes_to_copy)
405 self.assertEqual(read[out_seek:],
406 data[in_skip:in_skip+i])
407
408 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
409 def test_splice_invalid_values(self):
410 with self.assertRaises(ValueError):
411 os.splice(0, 1, -10)
412
413 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
414 @requires_splice_pipe
415 def test_splice(self):
416 TESTFN2 = os_helper.TESTFN + ".3"
417 data = b'0123456789'
418
419 create_file(os_helper.TESTFN, data)
420 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
421
422 in_file = open(os_helper.TESTFN, 'rb')
423 self.addCleanup(in_file.close)
424 in_fd = in_file.fileno()
425
426 read_fd, write_fd = os.pipe()
427 self.addCleanup(lambda: os.close(read_fd))
428 self.addCleanup(lambda: os.close(write_fd))
429
430 try:
431 i = os.splice(in_fd, write_fd, 5)
432 except OSError as e:
433 # Handle the case in which Python was compiled
434 # in a system with the syscall but without support
435 # in the kernel.
436 if e.errno != errno.ENOSYS:
437 raise
438 self.skipTest(e)
439 else:
440 # The number of copied bytes can be less than
441 # the number of bytes originally requested.
442 self.assertIn(i, range(0, 6));
443
444 self.assertEqual(os.read(read_fd, 100), data[:i])
445
446 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
447 @requires_splice_pipe
448 def test_splice_offset_in(self):
449 TESTFN4 = os_helper.TESTFN + ".4"
450 data = b'0123456789'
451 bytes_to_copy = 6
452 in_skip = 3
453
454 create_file(os_helper.TESTFN, data)
455 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
456
457 in_file = open(os_helper.TESTFN, 'rb')
458 self.addCleanup(in_file.close)
459 in_fd = in_file.fileno()
460
461 read_fd, write_fd = os.pipe()
462 self.addCleanup(lambda: os.close(read_fd))
463 self.addCleanup(lambda: os.close(write_fd))
464
465 try:
466 i = os.splice(in_fd, write_fd, bytes_to_copy, offset_src=in_skip)
467 except OSError as e:
468 # Handle the case in which Python was compiled
469 # in a system with the syscall but without support
470 # in the kernel.
471 if e.errno != errno.ENOSYS:
472 raise
473 self.skipTest(e)
474 else:
475 # The number of copied bytes can be less than
476 # the number of bytes originally requested.
477 self.assertIn(i, range(0, bytes_to_copy+1));
478
479 read = os.read(read_fd, 100)
480 # 012 are skipped (in_skip)
481 # 345678 are copied in the file (in_skip + bytes_to_copy)
482 self.assertEqual(read, data[in_skip:in_skip+i])
483
484 @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
485 @requires_splice_pipe
486 def test_splice_offset_out(self):
487 TESTFN4 = os_helper.TESTFN + ".4"
488 data = b'0123456789'
489 bytes_to_copy = 6
490 out_seek = 3
491
492 create_file(os_helper.TESTFN, data)
493 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
494
495 read_fd, write_fd = os.pipe()
496 self.addCleanup(lambda: os.close(read_fd))
497 self.addCleanup(lambda: os.close(write_fd))
498 os.write(write_fd, data)
499
500 out_file = open(TESTFN4, 'w+b')
501 self.addCleanup(os_helper.unlink, TESTFN4)
502 self.addCleanup(out_file.close)
503 out_fd = out_file.fileno()
504
505 try:
506 i = os.splice(read_fd, out_fd, bytes_to_copy, offset_dst=out_seek)
507 except OSError as e:
508 # Handle the case in which Python was compiled
509 # in a system with the syscall but without support
510 # in the kernel.
511 if e.errno != errno.ENOSYS:
512 raise
513 self.skipTest(e)
514 else:
515 # The number of copied bytes can be less than
516 # the number of bytes originally requested.
517 self.assertIn(i, range(0, bytes_to_copy+1));
518
519 with open(TESTFN4, 'rb') as in_file:
520 read = in_file.read()
521 # seeked bytes (5) are zero'ed
522 self.assertEqual(read[:out_seek], b'\x00'*out_seek)
523 # 012 are skipped (in_skip)
524 # 345678 are copied in the file (in_skip + bytes_to_copy)
525 self.assertEqual(read[out_seek:], data[:i])
526
527
528 # Test attributes on return values from os.*stat* family.
529 class StatAttributeTests(unittest.TestCase):
530 def setUp(self):
531 self.fname = os_helper.TESTFN
532 self.addCleanup(os_helper.unlink, self.fname)
533 create_file(self.fname, b"ABC")
534
535 def check_stat_attributes(self, fname):
536 result = os.stat(fname)
537
538 # Make sure direct access works
539 self.assertEqual(result[stat.ST_SIZE], 3)
540 self.assertEqual(result.st_size, 3)
541
542 # Make sure all the attributes are there
543 members = dir(result)
544 for name in dir(stat):
545 if name[:3] == 'ST_':
546 attr = name.lower()
547 if name.endswith("TIME"):
548 def trunc(x): return int(x)
549 else:
550 def trunc(x): return x
551 self.assertEqual(trunc(getattr(result, attr)),
552 result[getattr(stat, name)])
553 self.assertIn(attr, members)
554
555 # Make sure that the st_?time and st_?time_ns fields roughly agree
556 # (they should always agree up to around tens-of-microseconds)
557 for name in 'st_atime st_mtime st_ctime'.split():
558 floaty = int(getattr(result, name) * 100000)
559 nanosecondy = getattr(result, name + "_ns") // 10000
560 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
561
562 # Ensure both birthtime and birthtime_ns roughly agree, if present
563 try:
564 floaty = int(result.st_birthtime * 100000)
565 nanosecondy = result.st_birthtime_ns // 10000
566 except AttributeError:
567 pass
568 else:
569 self.assertAlmostEqual(floaty, nanosecondy, delta=2)
570
571 try:
572 result[200]
573 self.fail("No exception raised")
574 except IndexError:
575 pass
576
577 # Make sure that assignment fails
578 try:
579 result.st_mode = 1
580 self.fail("No exception raised")
581 except AttributeError:
582 pass
583
584 try:
585 result.st_rdev = 1
586 self.fail("No exception raised")
587 except (AttributeError, TypeError):
588 pass
589
590 try:
591 result.parrot = 1
592 self.fail("No exception raised")
593 except AttributeError:
594 pass
595
596 # Use the stat_result constructor with a too-short tuple.
597 try:
598 result2 = os.stat_result((10,))
599 self.fail("No exception raised")
600 except TypeError:
601 pass
602
603 # Use the constructor with a too-long tuple.
604 try:
605 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
606 except TypeError:
607 pass
608
609 def test_stat_attributes(self):
610 self.check_stat_attributes(self.fname)
611
612 def test_stat_attributes_bytes(self):
613 try:
614 fname = self.fname.encode(sys.getfilesystemencoding())
615 except UnicodeEncodeError:
616 self.skipTest("cannot encode %a for the filesystem" % self.fname)
617 self.check_stat_attributes(fname)
618
619 def test_stat_result_pickle(self):
620 result = os.stat(self.fname)
621 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
622 with self.subTest(f'protocol {proto}'):
623 p = pickle.dumps(result, proto)
624 self.assertIn(b'stat_result', p)
625 if proto < 4:
626 self.assertIn(b'cos\nstat_result\n', p)
627 unpickled = pickle.loads(p)
628 self.assertEqual(result, unpickled)
629
630 @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
631 def test_statvfs_attributes(self):
632 result = os.statvfs(self.fname)
633
634 # Make sure direct access works
635 self.assertEqual(result.f_bfree, result[3])
636
637 # Make sure all the attributes are there.
638 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
639 'ffree', 'favail', 'flag', 'namemax')
640 for value, member in enumerate(members):
641 self.assertEqual(getattr(result, 'f_' + member), result[value])
642
643 self.assertTrue(isinstance(result.f_fsid, int))
644
645 # Test that the size of the tuple doesn't change
646 self.assertEqual(len(result), 10)
647
648 # Make sure that assignment really fails
649 try:
650 result.f_bfree = 1
651 self.fail("No exception raised")
652 except AttributeError:
653 pass
654
655 try:
656 result.parrot = 1
657 self.fail("No exception raised")
658 except AttributeError:
659 pass
660
661 # Use the constructor with a too-short tuple.
662 try:
663 result2 = os.statvfs_result((10,))
664 self.fail("No exception raised")
665 except TypeError:
666 pass
667
668 # Use the constructor with a too-long tuple.
669 try:
670 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
671 except TypeError:
672 pass
673
674 @unittest.skipUnless(hasattr(os, 'statvfs'),
675 "need os.statvfs()")
676 def test_statvfs_result_pickle(self):
677 result = os.statvfs(self.fname)
678
679 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
680 p = pickle.dumps(result, proto)
681 self.assertIn(b'statvfs_result', p)
682 if proto < 4:
683 self.assertIn(b'cos\nstatvfs_result\n', p)
684 unpickled = pickle.loads(p)
685 self.assertEqual(result, unpickled)
686
687 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
688 def test_1686475(self):
689 # Verify that an open file can be stat'ed
690 try:
691 os.stat(r"c:\pagefile.sys")
692 except FileNotFoundError:
693 self.skipTest(r'c:\pagefile.sys does not exist')
694 except OSError as e:
695 self.fail("Could not stat pagefile.sys")
696
697 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
698 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
699 def test_15261(self):
700 # Verify that stat'ing a closed fd does not cause crash
701 r, w = os.pipe()
702 try:
703 os.stat(r) # should not raise error
704 finally:
705 os.close(r)
706 os.close(w)
707 with self.assertRaises(OSError) as ctx:
708 os.stat(r)
709 self.assertEqual(ctx.exception.errno, errno.EBADF)
710
711 def check_file_attributes(self, result):
712 self.assertTrue(hasattr(result, 'st_file_attributes'))
713 self.assertTrue(isinstance(result.st_file_attributes, int))
714 self.assertTrue(0 <= result.st_file_attributes <= 0xFFFFFFFF)
715
716 @unittest.skipUnless(sys.platform == "win32",
717 "st_file_attributes is Win32 specific")
718 def test_file_attributes(self):
719 # test file st_file_attributes (FILE_ATTRIBUTE_DIRECTORY not set)
720 result = os.stat(self.fname)
721 self.check_file_attributes(result)
722 self.assertEqual(
723 result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY,
724 0)
725
726 # test directory st_file_attributes (FILE_ATTRIBUTE_DIRECTORY set)
727 dirname = os_helper.TESTFN + "dir"
728 os.mkdir(dirname)
729 self.addCleanup(os.rmdir, dirname)
730
731 result = os.stat(dirname)
732 self.check_file_attributes(result)
733 self.assertEqual(
734 result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY,
735 stat.FILE_ATTRIBUTE_DIRECTORY)
736
737 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
738 def test_access_denied(self):
739 # Default to FindFirstFile WIN32_FIND_DATA when access is
740 # denied. See issue 28075.
741 # os.environ['TEMP'] should be located on a volume that
742 # supports file ACLs.
743 fname = os.path.join(os.environ['TEMP'], self.fname + "_access")
744 self.addCleanup(os_helper.unlink, fname)
745 create_file(fname, b'ABC')
746 # Deny the right to [S]YNCHRONIZE on the file to
747 # force CreateFile to fail with ERROR_ACCESS_DENIED.
748 DETACHED_PROCESS = 8
749 subprocess.check_call(
750 # bpo-30584: Use security identifier *S-1-5-32-545 instead
751 # of localized "Users" to not depend on the locale.
752 ['icacls.exe', fname, '/deny', '*S-1-5-32-545:(S)'],
753 creationflags=DETACHED_PROCESS
754 )
755 result = os.stat(fname)
756 self.assertNotEqual(result.st_size, 0)
757 self.assertTrue(os.path.isfile(fname))
758
759 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
760 def test_stat_block_device(self):
761 # bpo-38030: os.stat fails for block devices
762 # Test a filename like "//./C:"
763 fname = "//./" + os.path.splitdrive(os.getcwd())[0]
764 result = os.stat(fname)
765 self.assertEqual(result.st_mode, stat.S_IFBLK)
766
767
768 class UtimeTests(unittest.TestCase):
769 def setUp(self):
770 self.dirname = os_helper.TESTFN
771 self.fname = os.path.join(self.dirname, "f1")
772
773 self.addCleanup(os_helper.rmtree, self.dirname)
774 os.mkdir(self.dirname)
775 create_file(self.fname)
776
777 def support_subsecond(self, filename):
778 # Heuristic to check if the filesystem supports timestamp with
779 # subsecond resolution: check if float and int timestamps are different
780 st = os.stat(filename)
781 return ((st.st_atime != st[7])
782 or (st.st_mtime != st[8])
783 or (st.st_ctime != st[9]))
784
785 def _test_utime(self, set_time, filename=None):
786 if not filename:
787 filename = self.fname
788
789 support_subsecond = self.support_subsecond(filename)
790 if support_subsecond:
791 # Timestamp with a resolution of 1 microsecond (10^-6).
792 #
793 # The resolution of the C internal function used by os.utime()
794 # depends on the platform: 1 sec, 1 us, 1 ns. Writing a portable
795 # test with a resolution of 1 ns requires more work:
796 # see the issue #15745.
797 atime_ns = 1002003000 # 1.002003 seconds
798 mtime_ns = 4005006000 # 4.005006 seconds
799 else:
800 # use a resolution of 1 second
801 atime_ns = 5 * 10**9
802 mtime_ns = 8 * 10**9
803
804 set_time(filename, (atime_ns, mtime_ns))
805 st = os.stat(filename)
806
807 if support_subsecond:
808 self.assertAlmostEqual(st.st_atime, atime_ns * 1e-9, delta=1e-6)
809 self.assertAlmostEqual(st.st_mtime, mtime_ns * 1e-9, delta=1e-6)
810 else:
811 self.assertEqual(st.st_atime, atime_ns * 1e-9)
812 self.assertEqual(st.st_mtime, mtime_ns * 1e-9)
813 self.assertEqual(st.st_atime_ns, atime_ns)
814 self.assertEqual(st.st_mtime_ns, mtime_ns)
815
816 def test_utime(self):
817 def set_time(filename, ns):
818 # test the ns keyword parameter
819 os.utime(filename, ns=ns)
820 self._test_utime(set_time)
821
822 @staticmethod
823 def ns_to_sec(ns):
824 # Convert a number of nanosecond (int) to a number of seconds (float).
825 # Round towards infinity by adding 0.5 nanosecond to avoid rounding
826 # issue, os.utime() rounds towards minus infinity.
827 return (ns * 1e-9) + 0.5e-9
828
829 def test_utime_by_indexed(self):
830 # pass times as floating-point seconds as the second indexed parameter
831 def set_time(filename, ns):
832 atime_ns, mtime_ns = ns
833 atime = self.ns_to_sec(atime_ns)
834 mtime = self.ns_to_sec(mtime_ns)
835 # test utimensat(timespec), utimes(timeval), utime(utimbuf)
836 # or utime(time_t)
837 os.utime(filename, (atime, mtime))
838 self._test_utime(set_time)
839
840 def test_utime_by_times(self):
841 def set_time(filename, ns):
842 atime_ns, mtime_ns = ns
843 atime = self.ns_to_sec(atime_ns)
844 mtime = self.ns_to_sec(mtime_ns)
845 # test the times keyword parameter
846 os.utime(filename, times=(atime, mtime))
847 self._test_utime(set_time)
848
849 @unittest.skipUnless(os.utime in os.supports_follow_symlinks,
850 "follow_symlinks support for utime required "
851 "for this test.")
852 def test_utime_nofollow_symlinks(self):
853 def set_time(filename, ns):
854 # use follow_symlinks=False to test utimensat(timespec)
855 # or lutimes(timeval)
856 os.utime(filename, ns=ns, follow_symlinks=False)
857 self._test_utime(set_time)
858
859 @unittest.skipUnless(os.utime in os.supports_fd,
860 "fd support for utime required for this test.")
861 def test_utime_fd(self):
862 def set_time(filename, ns):
863 with open(filename, 'wb', 0) as fp:
864 # use a file descriptor to test futimens(timespec)
865 # or futimes(timeval)
866 os.utime(fp.fileno(), ns=ns)
867 self._test_utime(set_time)
868
869 @unittest.skipUnless(os.utime in os.supports_dir_fd,
870 "dir_fd support for utime required for this test.")
871 def test_utime_dir_fd(self):
872 def set_time(filename, ns):
873 dirname, name = os.path.split(filename)
874 with os_helper.open_dir_fd(dirname) as dirfd:
875 # pass dir_fd to test utimensat(timespec) or futimesat(timeval)
876 os.utime(name, dir_fd=dirfd, ns=ns)
877 self._test_utime(set_time)
878
879 def test_utime_directory(self):
880 def set_time(filename, ns):
881 # test calling os.utime() on a directory
882 os.utime(filename, ns=ns)
883 self._test_utime(set_time, filename=self.dirname)
884
885 def _test_utime_current(self, set_time):
886 # Get the system clock
887 current = time.time()
888
889 # Call os.utime() to set the timestamp to the current system clock
890 set_time(self.fname)
891
892 if not self.support_subsecond(self.fname):
893 delta = 1.0
894 else:
895 # On Windows, the usual resolution of time.time() is 15.6 ms.
896 # bpo-30649: Tolerate 50 ms for slow Windows buildbots.
897 #
898 # x86 Gentoo Refleaks 3.x once failed with dt=20.2 ms. So use
899 # also 50 ms on other platforms.
900 delta = 0.050
901 st = os.stat(self.fname)
902 msg = ("st_time=%r, current=%r, dt=%r"
903 % (st.st_mtime, current, st.st_mtime - current))
904 self.assertAlmostEqual(st.st_mtime, current,
905 delta=delta, msg=msg)
906
907 def test_utime_current(self):
908 def set_time(filename):
909 # Set to the current time in the new way
910 os.utime(self.fname)
911 self._test_utime_current(set_time)
912
913 def test_utime_current_old(self):
914 def set_time(filename):
915 # Set to the current time in the old explicit way.
916 os.utime(self.fname, None)
917 self._test_utime_current(set_time)
918
919 def test_utime_nonexistent(self):
920 now = time.time()
921 filename = 'nonexistent'
922 with self.assertRaises(FileNotFoundError) as cm:
923 os.utime(filename, (now, now))
924 self.assertEqual(cm.exception.filename, filename)
925
926 def get_file_system(self, path):
927 if sys.platform == 'win32':
928 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
929 import ctypes
930 kernel32 = ctypes.windll.kernel32
931 buf = ctypes.create_unicode_buffer("", 100)
932 ok = kernel32.GetVolumeInformationW(root, None, 0,
933 None, None, None,
934 buf, len(buf))
935 if ok:
936 return buf.value
937 # return None if the filesystem is unknown
938
939 def test_large_time(self):
940 # Many filesystems are limited to the year 2038. At least, the test
941 # pass with NTFS filesystem.
942 if self.get_file_system(self.dirname) != "NTFS":
943 self.skipTest("requires NTFS")
944
945 large = 5000000000 # some day in 2128
946 os.utime(self.fname, (large, large))
947 self.assertEqual(os.stat(self.fname).st_mtime, large)
948
949 def test_utime_invalid_arguments(self):
950 # seconds and nanoseconds parameters are mutually exclusive
951 with self.assertRaises(ValueError):
952 os.utime(self.fname, (5, 5), ns=(5, 5))
953 with self.assertRaises(TypeError):
954 os.utime(self.fname, [5, 5])
955 with self.assertRaises(TypeError):
956 os.utime(self.fname, (5,))
957 with self.assertRaises(TypeError):
958 os.utime(self.fname, (5, 5, 5))
959 with self.assertRaises(TypeError):
960 os.utime(self.fname, ns=[5, 5])
961 with self.assertRaises(TypeError):
962 os.utime(self.fname, ns=(5,))
963 with self.assertRaises(TypeError):
964 os.utime(self.fname, ns=(5, 5, 5))
965
966 if os.utime not in os.supports_follow_symlinks:
967 with self.assertRaises(NotImplementedError):
968 os.utime(self.fname, (5, 5), follow_symlinks=False)
969 if os.utime not in os.supports_fd:
970 with open(self.fname, 'wb', 0) as fp:
971 with self.assertRaises(TypeError):
972 os.utime(fp.fileno(), (5, 5))
973 if os.utime not in os.supports_dir_fd:
974 with self.assertRaises(NotImplementedError):
975 os.utime(self.fname, (5, 5), dir_fd=0)
976
977 @support.cpython_only
978 def test_issue31577(self):
979 # The interpreter shouldn't crash in case utime() received a bad
980 # ns argument.
981 def get_bad_int(divmod_ret_val):
982 class BadInt:
983 def __divmod__(*args):
984 return divmod_ret_val
985 return BadInt()
986 with self.assertRaises(TypeError):
987 os.utime(self.fname, ns=(get_bad_int(42), 1))
988 with self.assertRaises(TypeError):
989 os.utime(self.fname, ns=(get_bad_int(()), 1))
990 with self.assertRaises(TypeError):
991 os.utime(self.fname, ns=(get_bad_int((1, 2, 3)), 1))
992
993
994 from test import mapping_tests
995
996 class EnvironTests(mapping_tests.BasicTestMappingProtocol):
997 """check that os.environ object conform to mapping protocol"""
998 type2test = None
999
1000 def setUp(self):
1001 self.__save = dict(os.environ)
1002 if os.supports_bytes_environ:
1003 self.__saveb = dict(os.environb)
1004 for key, value in self._reference().items():
1005 os.environ[key] = value
1006
1007 def tearDown(self):
1008 os.environ.clear()
1009 os.environ.update(self.__save)
1010 if os.supports_bytes_environ:
1011 os.environb.clear()
1012 os.environb.update(self.__saveb)
1013
1014 def _reference(self):
1015 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
1016
1017 def _empty_mapping(self):
1018 os.environ.clear()
1019 return os.environ
1020
1021 # Bug 1110478
1022 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
1023 'requires a shell')
1024 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
1025 @support.requires_subprocess()
1026 def test_update2(self):
1027 os.environ.clear()
1028 os.environ.update(HELLO="World")
1029 with os.popen("%s -c 'echo $HELLO'" % unix_shell) as popen:
1030 value = popen.read().strip()
1031 self.assertEqual(value, "World")
1032
1033 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
1034 'requires a shell')
1035 @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
1036 @support.requires_subprocess()
1037 def test_os_popen_iter(self):
1038 with os.popen("%s -c 'echo \"line1\nline2\nline3\"'"
1039 % unix_shell) as popen:
1040 it = iter(popen)
1041 self.assertEqual(next(it), "line1\n")
1042 self.assertEqual(next(it), "line2\n")
1043 self.assertEqual(next(it), "line3\n")
1044 self.assertRaises(StopIteration, next, it)
1045
1046 # Verify environ keys and values from the OS are of the
1047 # correct str type.
1048 def test_keyvalue_types(self):
1049 for key, val in os.environ.items():
1050 self.assertEqual(type(key), str)
1051 self.assertEqual(type(val), str)
1052
1053 def test_items(self):
1054 for key, value in self._reference().items():
1055 self.assertEqual(os.environ.get(key), value)
1056
1057 # Issue 7310
1058 def test___repr__(self):
1059 """Check that the repr() of os.environ looks like environ({...})."""
1060 env = os.environ
1061 formatted_items = ", ".join(
1062 f"{key!r}: {value!r}"
1063 for key, value in env.items()
1064 )
1065 self.assertEqual(repr(env), f"environ({{{formatted_items}}})")
1066
1067 def test_get_exec_path(self):
1068 defpath_list = os.defpath.split(os.pathsep)
1069 test_path = ['/monty', '/python', '', '/flying/circus']
1070 test_env = {'PATH': os.pathsep.join(test_path)}
1071
1072 saved_environ = os.environ
1073 try:
1074 os.environ = dict(test_env)
1075 # Test that defaulting to os.environ works.
1076 self.assertSequenceEqual(test_path, os.get_exec_path())
1077 self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
1078 finally:
1079 os.environ = saved_environ
1080
1081 # No PATH environment variable
1082 self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
1083 # Empty PATH environment variable
1084 self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
1085 # Supplied PATH environment variable
1086 self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
1087
1088 if os.supports_bytes_environ:
1089 # env cannot contain 'PATH' and b'PATH' keys
1090 try:
1091 # ignore BytesWarning warning
1092 with warnings.catch_warnings(record=True):
1093 mixed_env = {'PATH': '1', b'PATH': b'2'}
1094 except BytesWarning:
1095 # mixed_env cannot be created with python -bb
1096 pass
1097 else:
1098 self.assertRaises(ValueError, os.get_exec_path, mixed_env)
1099
1100 # bytes key and/or value
1101 self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
1102 ['abc'])
1103 self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
1104 ['abc'])
1105 self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
1106 ['abc'])
1107
1108 @unittest.skipUnless(os.supports_bytes_environ,
1109 "os.environb required for this test.")
1110 def test_environb(self):
1111 # os.environ -> os.environb
1112 value = 'euro\u20ac'
1113 try:
1114 value_bytes = value.encode(sys.getfilesystemencoding(),
1115 'surrogateescape')
1116 except UnicodeEncodeError:
1117 msg = "U+20AC character is not encodable to %s" % (
1118 sys.getfilesystemencoding(),)
1119 self.skipTest(msg)
1120 os.environ['unicode'] = value
1121 self.assertEqual(os.environ['unicode'], value)
1122 self.assertEqual(os.environb[b'unicode'], value_bytes)
1123
1124 # os.environb -> os.environ
1125 value = b'\xff'
1126 os.environb[b'bytes'] = value
1127 self.assertEqual(os.environb[b'bytes'], value)
1128 value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
1129 self.assertEqual(os.environ['bytes'], value_str)
1130
1131 @support.requires_subprocess()
1132 def test_putenv_unsetenv(self):
1133 name = "PYTHONTESTVAR"
1134 value = "testvalue"
1135 code = f'import os; print(repr(os.environ.get({name!r})))'
1136
1137 with os_helper.EnvironmentVarGuard() as env:
1138 env.pop(name, None)
1139
1140 os.putenv(name, value)
1141 proc = subprocess.run([sys.executable, '-c', code], check=True,
1142 stdout=subprocess.PIPE, text=True)
1143 self.assertEqual(proc.stdout.rstrip(), repr(value))
1144
1145 os.unsetenv(name)
1146 proc = subprocess.run([sys.executable, '-c', code], check=True,
1147 stdout=subprocess.PIPE, text=True)
1148 self.assertEqual(proc.stdout.rstrip(), repr(None))
1149
1150 # On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415).
1151 @support.requires_mac_ver(10, 6)
1152 def test_putenv_unsetenv_error(self):
1153 # Empty variable name is invalid.
1154 # "=" and null character are not allowed in a variable name.
1155 for name in ('', '=name', 'na=me', 'name='):
1156 self.assertRaises((OSError, ValueError), os.putenv, name, "value")
1157 self.assertRaises((OSError, ValueError), os.unsetenv, name)
1158 for name in ('name\0', 'na\0me'):
1159 self.assertRaises(ValueError, os.putenv, name, "value")
1160 self.assertRaises(ValueError, os.unsetenv, name)
1161
1162 if sys.platform == "win32":
1163 # On Windows, an environment variable string ("name=value" string)
1164 # is limited to 32,767 characters
1165 longstr = 'x' * 32_768
1166 self.assertRaises(ValueError, os.putenv, longstr, "1")
1167 self.assertRaises(ValueError, os.putenv, "X", longstr)
1168 self.assertRaises(ValueError, os.unsetenv, longstr)
1169
1170 def test_key_type(self):
1171 missing = 'missingkey'
1172 self.assertNotIn(missing, os.environ)
1173
1174 with self.assertRaises(KeyError) as cm:
1175 os.environ[missing]
1176 self.assertIs(cm.exception.args[0], missing)
1177 self.assertTrue(cm.exception.__suppress_context__)
1178
1179 with self.assertRaises(KeyError) as cm:
1180 del os.environ[missing]
1181 self.assertIs(cm.exception.args[0], missing)
1182 self.assertTrue(cm.exception.__suppress_context__)
1183
1184 def _test_environ_iteration(self, collection):
1185 iterator = iter(collection)
1186 new_key = "__new_key__"
1187
1188 next(iterator) # start iteration over os.environ.items
1189
1190 # add a new key in os.environ mapping
1191 os.environ[new_key] = "test_environ_iteration"
1192
1193 try:
1194 next(iterator) # force iteration over modified mapping
1195 self.assertEqual(os.environ[new_key], "test_environ_iteration")
1196 finally:
1197 del os.environ[new_key]
1198
1199 def test_iter_error_when_changing_os_environ(self):
1200 self._test_environ_iteration(os.environ)
1201
1202 def test_iter_error_when_changing_os_environ_items(self):
1203 self._test_environ_iteration(os.environ.items())
1204
1205 def test_iter_error_when_changing_os_environ_values(self):
1206 self._test_environ_iteration(os.environ.values())
1207
1208 def _test_underlying_process_env(self, var, expected):
1209 if not (unix_shell and os.path.exists(unix_shell)):
1210 return
1211 elif not support.has_subprocess_support:
1212 return
1213
1214 with os.popen(f"{unix_shell} -c 'echo ${var}'") as popen:
1215 value = popen.read().strip()
1216
1217 self.assertEqual(expected, value)
1218
1219 def test_or_operator(self):
1220 overridden_key = '_TEST_VAR_'
1221 original_value = 'original_value'
1222 os.environ[overridden_key] = original_value
1223
1224 new_vars_dict = {'_A_': '1', '_B_': '2', overridden_key: '3'}
1225 expected = dict(os.environ)
1226 expected.update(new_vars_dict)
1227
1228 actual = os.environ | new_vars_dict
1229 self.assertDictEqual(expected, actual)
1230 self.assertEqual('3', actual[overridden_key])
1231
1232 new_vars_items = new_vars_dict.items()
1233 self.assertIs(NotImplemented, os.environ.__or__(new_vars_items))
1234
1235 self._test_underlying_process_env('_A_', '')
1236 self._test_underlying_process_env(overridden_key, original_value)
1237
1238 def test_ior_operator(self):
1239 overridden_key = '_TEST_VAR_'
1240 os.environ[overridden_key] = 'original_value'
1241
1242 new_vars_dict = {'_A_': '1', '_B_': '2', overridden_key: '3'}
1243 expected = dict(os.environ)
1244 expected.update(new_vars_dict)
1245
1246 os.environ |= new_vars_dict
1247 self.assertEqual(expected, os.environ)
1248 self.assertEqual('3', os.environ[overridden_key])
1249
1250 self._test_underlying_process_env('_A_', '1')
1251 self._test_underlying_process_env(overridden_key, '3')
1252
1253 def test_ior_operator_invalid_dicts(self):
1254 os_environ_copy = os.environ.copy()
1255 with self.assertRaises(TypeError):
1256 dict_with_bad_key = {1: '_A_'}
1257 os.environ |= dict_with_bad_key
1258
1259 with self.assertRaises(TypeError):
1260 dict_with_bad_val = {'_A_': 1}
1261 os.environ |= dict_with_bad_val
1262
1263 # Check nothing was added.
1264 self.assertEqual(os_environ_copy, os.environ)
1265
1266 def test_ior_operator_key_value_iterable(self):
1267 overridden_key = '_TEST_VAR_'
1268 os.environ[overridden_key] = 'original_value'
1269
1270 new_vars_items = (('_A_', '1'), ('_B_', '2'), (overridden_key, '3'))
1271 expected = dict(os.environ)
1272 expected.update(new_vars_items)
1273
1274 os.environ |= new_vars_items
1275 self.assertEqual(expected, os.environ)
1276 self.assertEqual('3', os.environ[overridden_key])
1277
1278 self._test_underlying_process_env('_A_', '1')
1279 self._test_underlying_process_env(overridden_key, '3')
1280
1281 def test_ror_operator(self):
1282 overridden_key = '_TEST_VAR_'
1283 original_value = 'original_value'
1284 os.environ[overridden_key] = original_value
1285
1286 new_vars_dict = {'_A_': '1', '_B_': '2', overridden_key: '3'}
1287 expected = dict(new_vars_dict)
1288 expected.update(os.environ)
1289
1290 actual = new_vars_dict | os.environ
1291 self.assertDictEqual(expected, actual)
1292 self.assertEqual(original_value, actual[overridden_key])
1293
1294 new_vars_items = new_vars_dict.items()
1295 self.assertIs(NotImplemented, os.environ.__ror__(new_vars_items))
1296
1297 self._test_underlying_process_env('_A_', '')
1298 self._test_underlying_process_env(overridden_key, original_value)
1299
1300
1301 class WalkTests(unittest.TestCase):
1302 """Tests for os.walk()."""
1303 is_fwalk = False
1304
1305 # Wrapper to hide minor differences between os.walk and os.fwalk
1306 # to tests both functions with the same code base
1307 def walk(self, top, **kwargs):
1308 if 'follow_symlinks' in kwargs:
1309 kwargs['followlinks'] = kwargs.pop('follow_symlinks')
1310 return os.walk(top, **kwargs)
1311
1312 def setUp(self):
1313 join = os.path.join
1314 self.addCleanup(os_helper.rmtree, os_helper.TESTFN)
1315
1316 # Build:
1317 # TESTFN/
1318 # TEST1/ a file kid and two directory kids
1319 # tmp1
1320 # SUB1/ a file kid and a directory kid
1321 # tmp2
1322 # SUB11/ no kids
1323 # SUB2/ a file kid and a dirsymlink kid
1324 # tmp3
1325 # SUB21/ not readable
1326 # tmp5
1327 # link/ a symlink to TESTFN.2
1328 # broken_link
1329 # broken_link2
1330 # broken_link3
1331 # TEST2/
1332 # tmp4 a lone file
1333 self.walk_path = join(os_helper.TESTFN, "TEST1")
1334 self.sub1_path = join(self.walk_path, "SUB1")
1335 self.sub11_path = join(self.sub1_path, "SUB11")
1336 sub2_path = join(self.walk_path, "SUB2")
1337 sub21_path = join(sub2_path, "SUB21")
1338 self.tmp1_path = join(self.walk_path, "tmp1")
1339 tmp2_path = join(self.sub1_path, "tmp2")
1340 tmp3_path = join(sub2_path, "tmp3")
1341 tmp5_path = join(sub21_path, "tmp3")
1342 self.link_path = join(sub2_path, "link")
1343 t2_path = join(os_helper.TESTFN, "TEST2")
1344 tmp4_path = join(os_helper.TESTFN, "TEST2", "tmp4")
1345 self.broken_link_path = join(sub2_path, "broken_link")
1346 broken_link2_path = join(sub2_path, "broken_link2")
1347 broken_link3_path = join(sub2_path, "broken_link3")
1348
1349 # Create stuff.
1350 os.makedirs(self.sub11_path)
1351 os.makedirs(sub2_path)
1352 os.makedirs(sub21_path)
1353 os.makedirs(t2_path)
1354
1355 for path in self.tmp1_path, tmp2_path, tmp3_path, tmp4_path, tmp5_path:
1356 with open(path, "x", encoding='utf-8') as f:
1357 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
1358
1359 if os_helper.can_symlink():
1360 os.symlink(os.path.abspath(t2_path), self.link_path)
1361 os.symlink('broken', self.broken_link_path, True)
1362 os.symlink(join('tmp3', 'broken'), broken_link2_path, True)
1363 os.symlink(join('SUB21', 'tmp5'), broken_link3_path, True)
1364 self.sub2_tree = (sub2_path, ["SUB21", "link"],
1365 ["broken_link", "broken_link2", "broken_link3",
1366 "tmp3"])
1367 else:
1368 self.sub2_tree = (sub2_path, ["SUB21"], ["tmp3"])
1369
1370 if not support.is_emscripten:
1371 # Emscripten fails with inaccessible directory
1372 os.chmod(sub21_path, 0)
1373 try:
1374 os.listdir(sub21_path)
1375 except PermissionError:
1376 self.addCleanup(os.chmod, sub21_path, stat.S_IRWXU)
1377 else:
1378 os.chmod(sub21_path, stat.S_IRWXU)
1379 os.unlink(tmp5_path)
1380 os.rmdir(sub21_path)
1381 del self.sub2_tree[1][:1]
1382
1383 def test_walk_topdown(self):
1384 # Walk top-down.
1385 all = list(self.walk(self.walk_path))
1386
1387 self.assertEqual(len(all), 4)
1388 # We can't know which order SUB1 and SUB2 will appear in.
1389 # Not flipped: TESTFN, SUB1, SUB11, SUB2
1390 # flipped: TESTFN, SUB2, SUB1, SUB11
1391 flipped = all[0][1][0] != "SUB1"
1392 all[0][1].sort()
1393 all[3 - 2 * flipped][-1].sort()
1394 all[3 - 2 * flipped][1].sort()
1395 self.assertEqual(all[0], (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
1396 self.assertEqual(all[1 + flipped], (self.sub1_path, ["SUB11"], ["tmp2"]))
1397 self.assertEqual(all[2 + flipped], (self.sub11_path, [], []))
1398 self.assertEqual(all[3 - 2 * flipped], self.sub2_tree)
1399
1400 def test_walk_prune(self, walk_path=None):
1401 if walk_path is None:
1402 walk_path = self.walk_path
1403 # Prune the search.
1404 all = []
1405 for root, dirs, files in self.walk(walk_path):
1406 all.append((root, dirs, files))
1407 # Don't descend into SUB1.
1408 if 'SUB1' in dirs:
1409 # Note that this also mutates the dirs we appended to all!
1410 dirs.remove('SUB1')
1411
1412 self.assertEqual(len(all), 2)
1413 self.assertEqual(all[0], (self.walk_path, ["SUB2"], ["tmp1"]))
1414
1415 all[1][-1].sort()
1416 all[1][1].sort()
1417 self.assertEqual(all[1], self.sub2_tree)
1418
1419 def test_file_like_path(self):
1420 self.test_walk_prune(FakePath(self.walk_path))
1421
1422 def test_walk_bottom_up(self):
1423 # Walk bottom-up.
1424 all = list(self.walk(self.walk_path, topdown=False))
1425
1426 self.assertEqual(len(all), 4, all)
1427 # We can't know which order SUB1 and SUB2 will appear in.
1428 # Not flipped: SUB11, SUB1, SUB2, TESTFN
1429 # flipped: SUB2, SUB11, SUB1, TESTFN
1430 flipped = all[3][1][0] != "SUB1"
1431 all[3][1].sort()
1432 all[2 - 2 * flipped][-1].sort()
1433 all[2 - 2 * flipped][1].sort()
1434 self.assertEqual(all[3],
1435 (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
1436 self.assertEqual(all[flipped],
1437 (self.sub11_path, [], []))
1438 self.assertEqual(all[flipped + 1],
1439 (self.sub1_path, ["SUB11"], ["tmp2"]))
1440 self.assertEqual(all[2 - 2 * flipped],
1441 self.sub2_tree)
1442
1443 def test_walk_symlink(self):
1444 if not os_helper.can_symlink():
1445 self.skipTest("need symlink support")
1446
1447 # Walk, following symlinks.
1448 walk_it = self.walk(self.walk_path, follow_symlinks=True)
1449 for root, dirs, files in walk_it:
1450 if root == self.link_path:
1451 self.assertEqual(dirs, [])
1452 self.assertEqual(files, ["tmp4"])
1453 break
1454 else:
1455 self.fail("Didn't follow symlink with followlinks=True")
1456
1457 walk_it = self.walk(self.broken_link_path, follow_symlinks=True)
1458 if self.is_fwalk:
1459 self.assertRaises(FileNotFoundError, next, walk_it)
1460 self.assertRaises(StopIteration, next, walk_it)
1461
1462 def test_walk_bad_dir(self):
1463 # Walk top-down.
1464 errors = []
1465 walk_it = self.walk(self.walk_path, onerror=errors.append)
1466 root, dirs, files = next(walk_it)
1467 self.assertEqual(errors, [])
1468 dir1 = 'SUB1'
1469 path1 = os.path.join(root, dir1)
1470 path1new = os.path.join(root, dir1 + '.new')
1471 os.rename(path1, path1new)
1472 try:
1473 roots = [r for r, d, f in walk_it]
1474 self.assertTrue(errors)
1475 self.assertNotIn(path1, roots)
1476 self.assertNotIn(path1new, roots)
1477 for dir2 in dirs:
1478 if dir2 != dir1:
1479 self.assertIn(os.path.join(root, dir2), roots)
1480 finally:
1481 os.rename(path1new, path1)
1482
1483 def test_walk_bad_dir2(self):
1484 walk_it = self.walk('nonexisting')
1485 if self.is_fwalk:
1486 self.assertRaises(FileNotFoundError, next, walk_it)
1487 self.assertRaises(StopIteration, next, walk_it)
1488
1489 walk_it = self.walk('nonexisting', follow_symlinks=True)
1490 if self.is_fwalk:
1491 self.assertRaises(FileNotFoundError, next, walk_it)
1492 self.assertRaises(StopIteration, next, walk_it)
1493
1494 walk_it = self.walk(self.tmp1_path)
1495 self.assertRaises(StopIteration, next, walk_it)
1496
1497 walk_it = self.walk(self.tmp1_path, follow_symlinks=True)
1498 if self.is_fwalk:
1499 self.assertRaises(NotADirectoryError, next, walk_it)
1500 self.assertRaises(StopIteration, next, walk_it)
1501
1502 @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
1503 @unittest.skipIf(sys.platform == "vxworks",
1504 "fifo requires special path on VxWorks")
1505 def test_walk_named_pipe(self):
1506 path = os_helper.TESTFN + '-pipe'
1507 os.mkfifo(path)
1508 self.addCleanup(os.unlink, path)
1509
1510 walk_it = self.walk(path)
1511 self.assertRaises(StopIteration, next, walk_it)
1512
1513 walk_it = self.walk(path, follow_symlinks=True)
1514 if self.is_fwalk:
1515 self.assertRaises(NotADirectoryError, next, walk_it)
1516 self.assertRaises(StopIteration, next, walk_it)
1517
1518 @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
1519 @unittest.skipIf(sys.platform == "vxworks",
1520 "fifo requires special path on VxWorks")
1521 def test_walk_named_pipe2(self):
1522 path = os_helper.TESTFN + '-dir'
1523 os.mkdir(path)
1524 self.addCleanup(shutil.rmtree, path)
1525 os.mkfifo(os.path.join(path, 'mypipe'))
1526
1527 errors = []
1528 walk_it = self.walk(path, onerror=errors.append)
1529 next(walk_it)
1530 self.assertRaises(StopIteration, next, walk_it)
1531 self.assertEqual(errors, [])
1532
1533 errors = []
1534 walk_it = self.walk(path, onerror=errors.append)
1535 root, dirs, files = next(walk_it)
1536 self.assertEqual(root, path)
1537 self.assertEqual(dirs, [])
1538 self.assertEqual(files, ['mypipe'])
1539 dirs.extend(files)
1540 files.clear()
1541 if self.is_fwalk:
1542 self.assertRaises(NotADirectoryError, next, walk_it)
1543 self.assertRaises(StopIteration, next, walk_it)
1544 if self.is_fwalk:
1545 self.assertEqual(errors, [])
1546 else:
1547 self.assertEqual(len(errors), 1, errors)
1548 self.assertIsInstance(errors[0], NotADirectoryError)
1549
1550 def test_walk_many_open_files(self):
1551 depth = 30
1552 base = os.path.join(os_helper.TESTFN, 'deep')
1553 p = os.path.join(base, *(['d']*depth))
1554 os.makedirs(p)
1555
1556 iters = [self.walk(base, topdown=False) for j in range(100)]
1557 for i in range(depth + 1):
1558 expected = (p, ['d'] if i else [], [])
1559 for it in iters:
1560 self.assertEqual(next(it), expected)
1561 p = os.path.dirname(p)
1562
1563 iters = [self.walk(base, topdown=True) for j in range(100)]
1564 p = base
1565 for i in range(depth + 1):
1566 expected = (p, ['d'] if i < depth else [], [])
1567 for it in iters:
1568 self.assertEqual(next(it), expected)
1569 p = os.path.join(p, 'd')
1570
1571 def test_walk_above_recursion_limit(self):
1572 depth = 50
1573 os.makedirs(os.path.join(self.walk_path, *(['d'] * depth)))
1574 with infinite_recursion(depth - 5):
1575 all = list(self.walk(self.walk_path))
1576
1577 sub2_path = self.sub2_tree[0]
1578 for root, dirs, files in all:
1579 if root == sub2_path:
1580 dirs.sort()
1581 files.sort()
1582
1583 d_entries = []
1584 d_path = self.walk_path
1585 for _ in range(depth):
1586 d_path = os.path.join(d_path, "d")
1587 d_entries.append((d_path, ["d"], []))
1588 d_entries[-1][1].clear()
1589
1590 # Sub-sequences where the order is known
1591 sections = {
1592 "SUB1": [
1593 (self.sub1_path, ["SUB11"], ["tmp2"]),
1594 (self.sub11_path, [], []),
1595 ],
1596 "SUB2": [self.sub2_tree],
1597 "d": d_entries,
1598 }
1599
1600 # The ordering of sub-dirs is arbitrary but determines the order in
1601 # which sub-sequences appear
1602 dirs = all[0][1]
1603 expected = [(self.walk_path, dirs, ["tmp1"])]
1604 for d in dirs:
1605 expected.extend(sections[d])
1606
1607 self.assertEqual(len(all), depth + 4)
1608 self.assertEqual(sorted(dirs), ["SUB1", "SUB2", "d"])
1609 self.assertEqual(all, expected)
1610
1611
1612 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1613 class FwalkTests(WalkTests):
1614 """Tests for os.fwalk()."""
1615 is_fwalk = True
1616
1617 def walk(self, top, **kwargs):
1618 for root, dirs, files, root_fd in self.fwalk(top, **kwargs):
1619 yield (root, dirs, files)
1620
1621 def fwalk(self, *args, **kwargs):
1622 return os.fwalk(*args, **kwargs)
1623
1624 def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
1625 """
1626 compare with walk() results.
1627 """
1628 walk_kwargs = walk_kwargs.copy()
1629 fwalk_kwargs = fwalk_kwargs.copy()
1630 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
1631 walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
1632 fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
1633
1634 expected = {}
1635 for root, dirs, files in os.walk(**walk_kwargs):
1636 expected[root] = (set(dirs), set(files))
1637
1638 for root, dirs, files, rootfd in self.fwalk(**fwalk_kwargs):
1639 self.assertIn(root, expected)
1640 self.assertEqual(expected[root], (set(dirs), set(files)))
1641
1642 def test_compare_to_walk(self):
1643 kwargs = {'top': os_helper.TESTFN}
1644 self._compare_to_walk(kwargs, kwargs)
1645
1646 def test_dir_fd(self):
1647 try:
1648 fd = os.open(".", os.O_RDONLY)
1649 walk_kwargs = {'top': os_helper.TESTFN}
1650 fwalk_kwargs = walk_kwargs.copy()
1651 fwalk_kwargs['dir_fd'] = fd
1652 self._compare_to_walk(walk_kwargs, fwalk_kwargs)
1653 finally:
1654 os.close(fd)
1655
1656 def test_yields_correct_dir_fd(self):
1657 # check returned file descriptors
1658 for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
1659 args = os_helper.TESTFN, topdown, None
1660 for root, dirs, files, rootfd in self.fwalk(*args, follow_symlinks=follow_symlinks):
1661 # check that the FD is valid
1662 os.fstat(rootfd)
1663 # redundant check
1664 os.stat(rootfd)
1665 # check that listdir() returns consistent information
1666 self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
1667
1668 @unittest.skipIf(
1669 support.is_emscripten, "Cannot dup stdout on Emscripten"
1670 )
1671 @unittest.skipIf(
1672 support.is_android, "dup return value is unpredictable on Android"
1673 )
1674 def test_fd_leak(self):
1675 # Since we're opening a lot of FDs, we must be careful to avoid leaks:
1676 # we both check that calling fwalk() a large number of times doesn't
1677 # yield EMFILE, and that the minimum allocated FD hasn't changed.
1678 minfd = os.dup(1)
1679 os.close(minfd)
1680 for i in range(256):
1681 for x in self.fwalk(os_helper.TESTFN):
1682 pass
1683 newfd = os.dup(1)
1684 self.addCleanup(os.close, newfd)
1685 self.assertEqual(newfd, minfd)
1686
1687 @unittest.skipIf(
1688 support.is_emscripten, "Cannot dup stdout on Emscripten"
1689 )
1690 @unittest.skipIf(
1691 support.is_android, "dup return value is unpredictable on Android"
1692 )
1693 def test_fd_finalization(self):
1694 # Check that close()ing the fwalk() generator closes FDs
1695 def getfd():
1696 fd = os.dup(1)
1697 os.close(fd)
1698 return fd
1699 for topdown in (False, True):
1700 old_fd = getfd()
1701 it = self.fwalk(os_helper.TESTFN, topdown=topdown)
1702 self.assertEqual(getfd(), old_fd)
1703 next(it)
1704 self.assertGreater(getfd(), old_fd)
1705 it.close()
1706 self.assertEqual(getfd(), old_fd)
1707
1708 # fwalk() keeps file descriptors open
1709 test_walk_many_open_files = None
1710
1711
1712 class BytesWalkTests(WalkTests):
1713 """Tests for os.walk() with bytes."""
1714 def walk(self, top, **kwargs):
1715 if 'follow_symlinks' in kwargs:
1716 kwargs['followlinks'] = kwargs.pop('follow_symlinks')
1717 for broot, bdirs, bfiles in os.walk(os.fsencode(top), **kwargs):
1718 root = os.fsdecode(broot)
1719 dirs = list(map(os.fsdecode, bdirs))
1720 files = list(map(os.fsdecode, bfiles))
1721 yield (root, dirs, files)
1722 bdirs[:] = list(map(os.fsencode, dirs))
1723 bfiles[:] = list(map(os.fsencode, files))
1724
1725 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
1726 class BytesFwalkTests(FwalkTests):
1727 """Tests for os.walk() with bytes."""
1728 def fwalk(self, top='.', *args, **kwargs):
1729 for broot, bdirs, bfiles, topfd in os.fwalk(os.fsencode(top), *args, **kwargs):
1730 root = os.fsdecode(broot)
1731 dirs = list(map(os.fsdecode, bdirs))
1732 files = list(map(os.fsdecode, bfiles))
1733 yield (root, dirs, files, topfd)
1734 bdirs[:] = list(map(os.fsencode, dirs))
1735 bfiles[:] = list(map(os.fsencode, files))
1736
1737
1738 class MakedirTests(unittest.TestCase):
1739 def setUp(self):
1740 os.mkdir(os_helper.TESTFN)
1741
1742 def test_makedir(self):
1743 base = os_helper.TESTFN
1744 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
1745 os.makedirs(path) # Should work
1746 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
1747 os.makedirs(path)
1748
1749 # Try paths with a '.' in them
1750 self.assertRaises(OSError, os.makedirs, os.curdir)
1751 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
1752 os.makedirs(path)
1753 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
1754 'dir5', 'dir6')
1755 os.makedirs(path)
1756
1757 @unittest.skipIf(
1758 support.is_emscripten or support.is_wasi,
1759 "Emscripten's/WASI's umask is a stub."
1760 )
1761 def test_mode(self):
1762 with os_helper.temp_umask(0o002):
1763 base = os_helper.TESTFN
1764 parent = os.path.join(base, 'dir1')
1765 path = os.path.join(parent, 'dir2')
1766 os.makedirs(path, 0o555)
1767 self.assertTrue(os.path.exists(path))
1768 self.assertTrue(os.path.isdir(path))
1769 if os.name != 'nt':
1770 self.assertEqual(os.stat(path).st_mode & 0o777, 0o555)
1771 self.assertEqual(os.stat(parent).st_mode & 0o777, 0o775)
1772
1773 @unittest.skipIf(
1774 support.is_emscripten or support.is_wasi,
1775 "Emscripten's/WASI's umask is a stub."
1776 )
1777 def test_exist_ok_existing_directory(self):
1778 path = os.path.join(os_helper.TESTFN, 'dir1')
1779 mode = 0o777
1780 old_mask = os.umask(0o022)
1781 os.makedirs(path, mode)
1782 self.assertRaises(OSError, os.makedirs, path, mode)
1783 self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
1784 os.makedirs(path, 0o776, exist_ok=True)
1785 os.makedirs(path, mode=mode, exist_ok=True)
1786 os.umask(old_mask)
1787
1788 # Issue #25583: A drive root could raise PermissionError on Windows
1789 os.makedirs(os.path.abspath('/'), exist_ok=True)
1790
1791 @unittest.skipIf(
1792 support.is_emscripten or support.is_wasi,
1793 "Emscripten's/WASI's umask is a stub."
1794 )
1795 def test_exist_ok_s_isgid_directory(self):
1796 path = os.path.join(os_helper.TESTFN, 'dir1')
1797 S_ISGID = stat.S_ISGID
1798 mode = 0o777
1799 old_mask = os.umask(0o022)
1800 try:
1801 existing_testfn_mode = stat.S_IMODE(
1802 os.lstat(os_helper.TESTFN).st_mode)
1803 try:
1804 os.chmod(os_helper.TESTFN, existing_testfn_mode | S_ISGID)
1805 except PermissionError:
1806 raise unittest.SkipTest('Cannot set S_ISGID for dir.')
1807 if (os.lstat(os_helper.TESTFN).st_mode & S_ISGID != S_ISGID):
1808 raise unittest.SkipTest('No support for S_ISGID dir mode.')
1809 # The os should apply S_ISGID from the parent dir for us, but
1810 # this test need not depend on that behavior. Be explicit.
1811 os.makedirs(path, mode | S_ISGID)
1812 # http://bugs.python.org/issue14992
1813 # Should not fail when the bit is already set.
1814 os.makedirs(path, mode, exist_ok=True)
1815 # remove the bit.
1816 os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
1817 # May work even when the bit is not already set when demanded.
1818 os.makedirs(path, mode | S_ISGID, exist_ok=True)
1819 finally:
1820 os.umask(old_mask)
1821
1822 def test_exist_ok_existing_regular_file(self):
1823 base = os_helper.TESTFN
1824 path = os.path.join(os_helper.TESTFN, 'dir1')
1825 with open(path, 'w', encoding='utf-8') as f:
1826 f.write('abc')
1827 self.assertRaises(OSError, os.makedirs, path)
1828 self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
1829 self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
1830 os.remove(path)
1831
1832 @unittest.skipUnless(os.name == 'nt', "requires Windows")
1833 def test_win32_mkdir_700(self):
1834 base = os_helper.TESTFN
1835 path = os.path.abspath(os.path.join(os_helper.TESTFN, 'dir'))
1836 os.mkdir(path, mode=0o700)
1837 out = subprocess.check_output(["cacls.exe", path, "/s"], encoding="oem")
1838 os.rmdir(path)
1839 out = out.strip().rsplit(" ", 1)[1]
1840 self.assertEqual(
1841 out,
1842 '"D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;OW)"',
1843 )
1844
1845 def tearDown(self):
1846 path = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3',
1847 'dir4', 'dir5', 'dir6')
1848 # If the tests failed, the bottom-most directory ('../dir6')
1849 # may not have been created, so we look for the outermost directory
1850 # that exists.
1851 while not os.path.exists(path) and path != os_helper.TESTFN:
1852 path = os.path.dirname(path)
1853
1854 os.removedirs(path)
1855
1856
1857 @unittest.skipUnless(hasattr(os, "chown"), "requires os.chown()")
1858 class ChownFileTests(unittest.TestCase):
1859
1860 @classmethod
1861 def setUpClass(cls):
1862 os.mkdir(os_helper.TESTFN)
1863
1864 def test_chown_uid_gid_arguments_must_be_index(self):
1865 stat = os.stat(os_helper.TESTFN)
1866 uid = stat.st_uid
1867 gid = stat.st_gid
1868 for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)):
1869 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, value, gid)
1870 self.assertRaises(TypeError, os.chown, os_helper.TESTFN, uid, value)
1871 self.assertIsNone(os.chown(os_helper.TESTFN, uid, gid))
1872 self.assertIsNone(os.chown(os_helper.TESTFN, -1, -1))
1873
1874 @unittest.skipUnless(hasattr(os, 'getgroups'), 'need os.getgroups')
1875 def test_chown_gid(self):
1876 groups = os.getgroups()
1877 if len(groups) < 2:
1878 self.skipTest("test needs at least 2 groups")
1879
1880 gid_1, gid_2 = groups[:2]
1881 uid = os.stat(os_helper.TESTFN).st_uid
1882
1883 os.chown(os_helper.TESTFN, uid, gid_1)
1884 gid = os.stat(os_helper.TESTFN).st_gid
1885 self.assertEqual(gid, gid_1)
1886
1887 os.chown(os_helper.TESTFN, uid, gid_2)
1888 gid = os.stat(os_helper.TESTFN).st_gid
1889 self.assertEqual(gid, gid_2)
1890
1891 @unittest.skipUnless(root_in_posix and len(all_users) > 1,
1892 "test needs root privilege and more than one user")
1893 def test_chown_with_root(self):
1894 uid_1, uid_2 = all_users[:2]
1895 gid = os.stat(os_helper.TESTFN).st_gid
1896 os.chown(os_helper.TESTFN, uid_1, gid)
1897 uid = os.stat(os_helper.TESTFN).st_uid
1898 self.assertEqual(uid, uid_1)
1899 os.chown(os_helper.TESTFN, uid_2, gid)
1900 uid = os.stat(os_helper.TESTFN).st_uid
1901 self.assertEqual(uid, uid_2)
1902
1903 @unittest.skipUnless(not root_in_posix and len(all_users) > 1,
1904 "test needs non-root account and more than one user")
1905 def test_chown_without_permission(self):
1906 uid_1, uid_2 = all_users[:2]
1907 gid = os.stat(os_helper.TESTFN).st_gid
1908 with self.assertRaises(PermissionError):
1909 os.chown(os_helper.TESTFN, uid_1, gid)
1910 os.chown(os_helper.TESTFN, uid_2, gid)
1911
1912 @classmethod
1913 def tearDownClass(cls):
1914 os.rmdir(os_helper.TESTFN)
1915
1916
1917 class RemoveDirsTests(unittest.TestCase):
1918 def setUp(self):
1919 os.makedirs(os_helper.TESTFN)
1920
1921 def tearDown(self):
1922 os_helper.rmtree(os_helper.TESTFN)
1923
1924 def test_remove_all(self):
1925 dira = os.path.join(os_helper.TESTFN, 'dira')
1926 os.mkdir(dira)
1927 dirb = os.path.join(dira, 'dirb')
1928 os.mkdir(dirb)
1929 os.removedirs(dirb)
1930 self.assertFalse(os.path.exists(dirb))
1931 self.assertFalse(os.path.exists(dira))
1932 self.assertFalse(os.path.exists(os_helper.TESTFN))
1933
1934 def test_remove_partial(self):
1935 dira = os.path.join(os_helper.TESTFN, 'dira')
1936 os.mkdir(dira)
1937 dirb = os.path.join(dira, 'dirb')
1938 os.mkdir(dirb)
1939 create_file(os.path.join(dira, 'file.txt'))
1940 os.removedirs(dirb)
1941 self.assertFalse(os.path.exists(dirb))
1942 self.assertTrue(os.path.exists(dira))
1943 self.assertTrue(os.path.exists(os_helper.TESTFN))
1944
1945 def test_remove_nothing(self):
1946 dira = os.path.join(os_helper.TESTFN, 'dira')
1947 os.mkdir(dira)
1948 dirb = os.path.join(dira, 'dirb')
1949 os.mkdir(dirb)
1950 create_file(os.path.join(dirb, 'file.txt'))
1951 with self.assertRaises(OSError):
1952 os.removedirs(dirb)
1953 self.assertTrue(os.path.exists(dirb))
1954 self.assertTrue(os.path.exists(dira))
1955 self.assertTrue(os.path.exists(os_helper.TESTFN))
1956
1957
1958 @unittest.skipIf(support.is_wasi, "WASI has no /dev/null")
1959 class DevNullTests(unittest.TestCase):
1960 def test_devnull(self):
1961 with open(os.devnull, 'wb', 0) as f:
1962 f.write(b'hello')
1963 f.close()
1964 with open(os.devnull, 'rb') as f:
1965 self.assertEqual(f.read(), b'')
1966
1967
1968 class URandomTests(unittest.TestCase):
1969 def test_urandom_length(self):
1970 self.assertEqual(len(os.urandom(0)), 0)
1971 self.assertEqual(len(os.urandom(1)), 1)
1972 self.assertEqual(len(os.urandom(10)), 10)
1973 self.assertEqual(len(os.urandom(100)), 100)
1974 self.assertEqual(len(os.urandom(1000)), 1000)
1975
1976 def test_urandom_value(self):
1977 data1 = os.urandom(16)
1978 self.assertIsInstance(data1, bytes)
1979 data2 = os.urandom(16)
1980 self.assertNotEqual(data1, data2)
1981
1982 def get_urandom_subprocess(self, count):
1983 code = '\n'.join((
1984 'import os, sys',
1985 'data = os.urandom(%s)' % count,
1986 'sys.stdout.buffer.write(data)',
1987 'sys.stdout.buffer.flush()'))
1988 out = assert_python_ok('-c', code)
1989 stdout = out[1]
1990 self.assertEqual(len(stdout), count)
1991 return stdout
1992
1993 def test_urandom_subprocess(self):
1994 data1 = self.get_urandom_subprocess(16)
1995 data2 = self.get_urandom_subprocess(16)
1996 self.assertNotEqual(data1, data2)
1997
1998
1999 @unittest.skipUnless(hasattr(os, 'getrandom'), 'need os.getrandom()')
2000 class GetRandomTests(unittest.TestCase):
2001 @classmethod
2002 def setUpClass(cls):
2003 try:
2004 os.getrandom(1)
2005 except OSError as exc:
2006 if exc.errno == errno.ENOSYS:
2007 # Python compiled on a more recent Linux version
2008 # than the current Linux kernel
2009 raise unittest.SkipTest("getrandom() syscall fails with ENOSYS")
2010 else:
2011 raise
2012
2013 def test_getrandom_type(self):
2014 data = os.getrandom(16)
2015 self.assertIsInstance(data, bytes)
2016 self.assertEqual(len(data), 16)
2017
2018 def test_getrandom0(self):
2019 empty = os.getrandom(0)
2020 self.assertEqual(empty, b'')
2021
2022 def test_getrandom_random(self):
2023 self.assertTrue(hasattr(os, 'GRND_RANDOM'))
2024
2025 # Don't test os.getrandom(1, os.GRND_RANDOM) to not consume the rare
2026 # resource /dev/random
2027
2028 def test_getrandom_nonblock(self):
2029 # The call must not fail. Check also that the flag exists
2030 try:
2031 os.getrandom(1, os.GRND_NONBLOCK)
2032 except BlockingIOError:
2033 # System urandom is not initialized yet
2034 pass
2035
2036 def test_getrandom_value(self):
2037 data1 = os.getrandom(16)
2038 data2 = os.getrandom(16)
2039 self.assertNotEqual(data1, data2)
2040
2041
2042 # os.urandom() doesn't use a file descriptor when it is implemented with the
2043 # getentropy() function, the getrandom() function or the getrandom() syscall
2044 OS_URANDOM_DONT_USE_FD = (
2045 sysconfig.get_config_var('HAVE_GETENTROPY') == 1
2046 or sysconfig.get_config_var('HAVE_GETRANDOM') == 1
2047 or sysconfig.get_config_var('HAVE_GETRANDOM_SYSCALL') == 1)
2048
2049 @unittest.skipIf(OS_URANDOM_DONT_USE_FD ,
2050 "os.random() does not use a file descriptor")
2051 @unittest.skipIf(sys.platform == "vxworks",
2052 "VxWorks can't set RLIMIT_NOFILE to 1")
2053 class URandomFDTests(unittest.TestCase):
2054 @unittest.skipUnless(resource, "test requires the resource module")
2055 def test_urandom_failure(self):
2056 # Check urandom() failing when it is not able to open /dev/random.
2057 # We spawn a new process to make the test more robust (if getrlimit()
2058 # failed to restore the file descriptor limit after this, the whole
2059 # test suite would crash; this actually happened on the OS X Tiger
2060 # buildbot).
2061 code = """if 1:
2062 import errno
2063 import os
2064 import resource
2065
2066 soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
2067 resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
2068 try:
2069 os.urandom(16)
2070 except OSError as e:
2071 assert e.errno == errno.EMFILE, e.errno
2072 else:
2073 raise AssertionError("OSError not raised")
2074 """
2075 assert_python_ok('-c', code)
2076
2077 def test_urandom_fd_closed(self):
2078 # Issue #21207: urandom() should reopen its fd to /dev/urandom if
2079 # closed.
2080 code = """if 1:
2081 import os
2082 import sys
2083 import test.support
2084 os.urandom(4)
2085 with test.support.SuppressCrashReport():
2086 os.closerange(3, 256)
2087 sys.stdout.buffer.write(os.urandom(4))
2088 """
2089 rc, out, err = assert_python_ok('-Sc', code)
2090
2091 def test_urandom_fd_reopened(self):
2092 # Issue #21207: urandom() should detect its fd to /dev/urandom
2093 # changed to something else, and reopen it.
2094 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
2095 create_file(os_helper.TESTFN, b"x" * 256)
2096
2097 code = """if 1:
2098 import os
2099 import sys
2100 import test.support
2101 os.urandom(4)
2102 with test.support.SuppressCrashReport():
2103 for fd in range(3, 256):
2104 try:
2105 os.close(fd)
2106 except OSError:
2107 pass
2108 else:
2109 # Found the urandom fd (XXX hopefully)
2110 break
2111 os.closerange(3, 256)
2112 with open({TESTFN!r}, 'rb') as f:
2113 new_fd = f.fileno()
2114 # Issue #26935: posix allows new_fd and fd to be equal but
2115 # some libc implementations have dup2 return an error in this
2116 # case.
2117 if new_fd != fd:
2118 os.dup2(new_fd, fd)
2119 sys.stdout.buffer.write(os.urandom(4))
2120 sys.stdout.buffer.write(os.urandom(4))
2121 """.format(TESTFN=os_helper.TESTFN)
2122 rc, out, err = assert_python_ok('-Sc', code)
2123 self.assertEqual(len(out), 8)
2124 self.assertNotEqual(out[0:4], out[4:8])
2125 rc, out2, err2 = assert_python_ok('-Sc', code)
2126 self.assertEqual(len(out2), 8)
2127 self.assertNotEqual(out2, out)
2128
2129
2130 @contextlib.contextmanager
2131 def _execvpe_mockup(defpath=None):
2132 """
2133 Stubs out execv and execve functions when used as context manager.
2134 Records exec calls. The mock execv and execve functions always raise an
2135 exception as they would normally never return.
2136 """
2137 # A list of tuples containing (function name, first arg, args)
2138 # of calls to execv or execve that have been made.
2139 calls = []
2140
2141 def mock_execv(name, *args):
2142 calls.append(('execv', name, args))
2143 raise RuntimeError("execv called")
2144
2145 def mock_execve(name, *args):
2146 calls.append(('execve', name, args))
2147 raise OSError(errno.ENOTDIR, "execve called")
2148
2149 try:
2150 orig_execv = os.execv
2151 orig_execve = os.execve
2152 orig_defpath = os.defpath
2153 os.execv = mock_execv
2154 os.execve = mock_execve
2155 if defpath is not None:
2156 os.defpath = defpath
2157 yield calls
2158 finally:
2159 os.execv = orig_execv
2160 os.execve = orig_execve
2161 os.defpath = orig_defpath
2162
2163 @unittest.skipUnless(hasattr(os, 'execv'),
2164 "need os.execv()")
2165 class ExecTests(unittest.TestCase):
2166 @unittest.skipIf(USING_LINUXTHREADS,
2167 "avoid triggering a linuxthreads bug: see issue #4970")
2168 def test_execvpe_with_bad_program(self):
2169 self.assertRaises(OSError, os.execvpe, 'no such app-',
2170 ['no such app-'], None)
2171
2172 def test_execv_with_bad_arglist(self):
2173 self.assertRaises(ValueError, os.execv, 'notepad', ())
2174 self.assertRaises(ValueError, os.execv, 'notepad', [])
2175 self.assertRaises(ValueError, os.execv, 'notepad', ('',))
2176 self.assertRaises(ValueError, os.execv, 'notepad', [''])
2177
2178 def test_execvpe_with_bad_arglist(self):
2179 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
2180 self.assertRaises(ValueError, os.execvpe, 'notepad', [], {})
2181 self.assertRaises(ValueError, os.execvpe, 'notepad', [''], {})
2182
2183 @unittest.skipUnless(hasattr(os, '_execvpe'),
2184 "No internal os._execvpe function to test.")
2185 def _test_internal_execvpe(self, test_type):
2186 program_path = os.sep + 'absolutepath'
2187 if test_type is bytes:
2188 program = b'executable'
2189 fullpath = os.path.join(os.fsencode(program_path), program)
2190 native_fullpath = fullpath
2191 arguments = [b'progname', 'arg1', 'arg2']
2192 else:
2193 program = 'executable'
2194 arguments = ['progname', 'arg1', 'arg2']
2195 fullpath = os.path.join(program_path, program)
2196 if os.name != "nt":
2197 native_fullpath = os.fsencode(fullpath)
2198 else:
2199 native_fullpath = fullpath
2200 env = {'spam': 'beans'}
2201
2202 # test os._execvpe() with an absolute path
2203 with _execvpe_mockup() as calls:
2204 self.assertRaises(RuntimeError,
2205 os._execvpe, fullpath, arguments)
2206 self.assertEqual(len(calls), 1)
2207 self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
2208
2209 # test os._execvpe() with a relative path:
2210 # os.get_exec_path() returns defpath
2211 with _execvpe_mockup(defpath=program_path) as calls:
2212 self.assertRaises(OSError,
2213 os._execvpe, program, arguments, env=env)
2214 self.assertEqual(len(calls), 1)
2215 self.assertSequenceEqual(calls[0],
2216 ('execve', native_fullpath, (arguments, env)))
2217
2218 # test os._execvpe() with a relative path:
2219 # os.get_exec_path() reads the 'PATH' variable
2220 with _execvpe_mockup() as calls:
2221 env_path = env.copy()
2222 if test_type is bytes:
2223 env_path[b'PATH'] = program_path
2224 else:
2225 env_path['PATH'] = program_path
2226 self.assertRaises(OSError,
2227 os._execvpe, program, arguments, env=env_path)
2228 self.assertEqual(len(calls), 1)
2229 self.assertSequenceEqual(calls[0],
2230 ('execve', native_fullpath, (arguments, env_path)))
2231
2232 def test_internal_execvpe_str(self):
2233 self._test_internal_execvpe(str)
2234 if os.name != "nt":
2235 self._test_internal_execvpe(bytes)
2236
2237 def test_execve_invalid_env(self):
2238 args = [sys.executable, '-c', 'pass']
2239
2240 # null character in the environment variable name
2241 newenv = os.environ.copy()
2242 newenv["FRUIT\0VEGETABLE"] = "cabbage"
2243 with self.assertRaises(ValueError):
2244 os.execve(args[0], args, newenv)
2245
2246 # null character in the environment variable value
2247 newenv = os.environ.copy()
2248 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
2249 with self.assertRaises(ValueError):
2250 os.execve(args[0], args, newenv)
2251
2252 # equal character in the environment variable name
2253 newenv = os.environ.copy()
2254 newenv["FRUIT=ORANGE"] = "lemon"
2255 with self.assertRaises(ValueError):
2256 os.execve(args[0], args, newenv)
2257
2258 # See https://github.com/python/cpython/issues/137934 and the other
2259 # related issues for the reason why we cannot test this on Windows.
2260 @unittest.skipIf(os.name == "nt", "POSIX-specific test")
2261 @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
2262 "requires a shell")
2263 def test_execve_env_concurrent_mutation_with_fspath_posix(self):
2264 # Prevent crash when mutating environment during parsing.
2265 # Regression test for https://github.com/python/cpython/issues/143309.
2266
2267 message = "hello from execve"
2268 code = """if 1:
2269 import os, sys
2270
2271 class MyPath:
2272 def __fspath__(self):
2273 mutated.clear()
2274 return b"pwn"
2275
2276 mutated = KEYS = VALUES = [MyPath()]
2277
2278 class MyEnv:
2279 def __getitem__(self): raise RuntimeError("must not be called")
2280 def __len__(self): return 1
2281 def keys(self): return KEYS
2282 def values(self): return VALUES
2283
2284 args = [{unix_shell!r}, '-c', 'echo \"{message!s}\"']
2285 os.execve(args[0], args, MyEnv())
2286 """.format(unix_shell=unix_shell, message=message)
2287
2288 # Make sure to forward "LD_*" variables so that assert_python_ok()
2289 # can run correctly.
2290 minimal = {k: v for k, v in os.environ.items() if k.startswith("LD_")}
2291 with os_helper.EnvironmentVarGuard() as env:
2292 env.clear()
2293 env.update(minimal)
2294 _, out, _ = assert_python_ok('-c', code, **env)
2295 self.assertIn(bytes(message, "ascii"), out)
2296
2297 @unittest.skipUnless(sys.platform == "win32", "Win32-specific test")
2298 def test_execve_with_empty_path(self):
2299 # bpo-32890: Check GetLastError() misuse
2300 try:
2301 os.execve('', ['arg'], {})
2302 except OSError as e:
2303 self.assertTrue(e.winerror is None or e.winerror != 0)
2304 else:
2305 self.fail('No OSError raised')
2306
2307
2308 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2309 class Win32ErrorTests(unittest.TestCase):
2310 def setUp(self):
2311 try:
2312 os.stat(os_helper.TESTFN)
2313 except FileNotFoundError:
2314 exists = False
2315 except OSError as exc:
2316 exists = True
2317 self.fail("file %s must not exist; os.stat failed with %s"
2318 % (os_helper.TESTFN, exc))
2319 else:
2320 self.fail("file %s must not exist" % os_helper.TESTFN)
2321
2322 def test_rename(self):
2323 self.assertRaises(OSError, os.rename, os_helper.TESTFN, os_helper.TESTFN+".bak")
2324
2325 def test_remove(self):
2326 self.assertRaises(OSError, os.remove, os_helper.TESTFN)
2327
2328 def test_chdir(self):
2329 self.assertRaises(OSError, os.chdir, os_helper.TESTFN)
2330
2331 def test_mkdir(self):
2332 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
2333
2334 with open(os_helper.TESTFN, "x") as f:
2335 self.assertRaises(OSError, os.mkdir, os_helper.TESTFN)
2336
2337 def test_utime(self):
2338 self.assertRaises(OSError, os.utime, os_helper.TESTFN, None)
2339
2340 def test_chmod(self):
2341 self.assertRaises(OSError, os.chmod, os_helper.TESTFN, 0)
2342
2343
2344 @unittest.skipIf(support.is_wasi, "Cannot create invalid FD on WASI.")
2345 class TestInvalidFD(unittest.TestCase):
2346 singles = ["fchdir", "dup", "fdatasync", "fstat",
2347 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
2348 singles_fildes = {"fchdir", "fdatasync", "fsync"}
2349 #singles.append("close")
2350 #We omit close because it doesn't raise an exception on some platforms
2351 def get_single(f):
2352 def helper(self):
2353 if hasattr(os, f):
2354 self.check(getattr(os, f))
2355 if f in self.singles_fildes:
2356 self.check_bool(getattr(os, f))
2357 return helper
2358 for f in singles:
2359 locals()["test_"+f] = get_single(f)
2360
2361 def check(self, f, *args, **kwargs):
2362 try:
2363 f(os_helper.make_bad_fd(), *args, **kwargs)
2364 except OSError as e:
2365 self.assertEqual(e.errno, errno.EBADF)
2366 else:
2367 self.fail("%r didn't raise an OSError with a bad file descriptor"
2368 % f)
2369
2370 def check_bool(self, f, *args, **kwargs):
2371 with warnings.catch_warnings():
2372 warnings.simplefilter("error", RuntimeWarning)
2373 for fd in False, True:
2374 with self.assertRaises(RuntimeWarning):
2375 f(fd, *args, **kwargs)
2376
2377 def test_fdopen(self):
2378 self.check(os.fdopen, encoding="utf-8")
2379 self.check_bool(os.fdopen, encoding="utf-8")
2380
2381 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
2382 def test_isatty(self):
2383 self.assertEqual(os.isatty(os_helper.make_bad_fd()), False)
2384
2385 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
2386 def test_closerange(self):
2387 fd = os_helper.make_bad_fd()
2388 # Make sure none of the descriptors we are about to close are
2389 # currently valid (issue 6542).
2390 for i in range(10):
2391 try: os.fstat(fd+i)
2392 except OSError:
2393 pass
2394 else:
2395 break
2396 if i < 2:
2397 raise unittest.SkipTest(
2398 "Unable to acquire a range of invalid file descriptors")
2399 self.assertEqual(os.closerange(fd, fd + i-1), None)
2400
2401 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2402 def test_dup2(self):
2403 self.check(os.dup2, 20)
2404
2405 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2406 @unittest.skipIf(
2407 support.is_emscripten,
2408 "dup2() with negative fds is broken on Emscripten (see gh-102179)"
2409 )
2410 def test_dup2_negative_fd(self):
2411 valid_fd = os.open(__file__, os.O_RDONLY)
2412 self.addCleanup(os.close, valid_fd)
2413 fds = [
2414 valid_fd,
2415 -1,
2416 -2**31,
2417 ]
2418 for fd, fd2 in itertools.product(fds, repeat=2):
2419 if fd != fd2:
2420 with self.subTest(fd=fd, fd2=fd2):
2421 with self.assertRaises(OSError) as ctx:
2422 os.dup2(fd, fd2)
2423 self.assertEqual(ctx.exception.errno, errno.EBADF)
2424
2425 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
2426 def test_fchmod(self):
2427 self.check(os.fchmod, 0)
2428
2429 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
2430 def test_fchown(self):
2431 self.check(os.fchown, -1, -1)
2432
2433 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
2434 @unittest.skipIf(
2435 support.is_emscripten or support.is_wasi,
2436 "musl libc issue on Emscripten/WASI, bpo-46390"
2437 )
2438 def test_fpathconf(self):
2439 self.assertIn("PC_NAME_MAX", os.pathconf_names)
2440 self.check(os.pathconf, "PC_NAME_MAX")
2441 self.check(os.fpathconf, "PC_NAME_MAX")
2442 self.check_bool(os.pathconf, "PC_NAME_MAX")
2443 self.check_bool(os.fpathconf, "PC_NAME_MAX")
2444
2445 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
2446 def test_ftruncate(self):
2447 self.check(os.truncate, 0)
2448 self.check(os.ftruncate, 0)
2449 self.check_bool(os.truncate, 0)
2450
2451 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
2452 def test_lseek(self):
2453 self.check(os.lseek, 0, 0)
2454
2455 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
2456 def test_read(self):
2457 self.check(os.read, 1)
2458
2459 @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()')
2460 def test_readv(self):
2461 buf = bytearray(10)
2462 self.check(os.readv, [buf])
2463
2464 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
2465 def test_tcsetpgrpt(self):
2466 self.check(os.tcsetpgrp, 0)
2467
2468 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
2469 def test_write(self):
2470 self.check(os.write, b" ")
2471
2472 @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()')
2473 def test_writev(self):
2474 self.check(os.writev, [b'abc'])
2475
2476 @support.requires_subprocess()
2477 def test_inheritable(self):
2478 self.check(os.get_inheritable)
2479 self.check(os.set_inheritable, True)
2480
2481 @unittest.skipUnless(hasattr(os, 'get_blocking'),
2482 'needs os.get_blocking() and os.set_blocking()')
2483 def test_blocking(self):
2484 self.check(os.get_blocking)
2485 self.check(os.set_blocking, True)
2486
2487
2488 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
2489 class LinkTests(unittest.TestCase):
2490 def setUp(self):
2491 self.file1 = os_helper.TESTFN
2492 self.file2 = os.path.join(os_helper.TESTFN + "2")
2493
2494 def tearDown(self):
2495 for file in (self.file1, self.file2):
2496 if os.path.exists(file):
2497 os.unlink(file)
2498
2499 def _test_link(self, file1, file2):
2500 create_file(file1)
2501
2502 try:
2503 os.link(file1, file2)
2504 except PermissionError as e:
2505 self.skipTest('os.link(): %s' % e)
2506 with open(file1, "rb") as f1, open(file2, "rb") as f2:
2507 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
2508
2509 def test_link(self):
2510 self._test_link(self.file1, self.file2)
2511
2512 def test_link_bytes(self):
2513 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
2514 bytes(self.file2, sys.getfilesystemencoding()))
2515
2516 def test_unicode_name(self):
2517 try:
2518 os.fsencode("\xf1")
2519 except UnicodeError:
2520 raise unittest.SkipTest("Unable to encode for this platform.")
2521
2522 self.file1 += "\xf1"
2523 self.file2 = self.file1 + "2"
2524 self._test_link(self.file1, self.file2)
2525
2526 @unittest.skipIf(sys.platform == "win32", "Posix specific tests")
2527 class PosixUidGidTests(unittest.TestCase):
2528 # uid_t and gid_t are 32-bit unsigned integers on Linux
2529 UID_OVERFLOW = (1 << 32)
2530 GID_OVERFLOW = (1 << 32)
2531
2532 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
2533 def test_setuid(self):
2534 if os.getuid() != 0:
2535 self.assertRaises(OSError, os.setuid, 0)
2536 self.assertRaises(TypeError, os.setuid, 'not an int')
2537 self.assertRaises(OverflowError, os.setuid, self.UID_OVERFLOW)
2538
2539 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
2540 def test_setgid(self):
2541 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2542 self.assertRaises(OSError, os.setgid, 0)
2543 self.assertRaises(TypeError, os.setgid, 'not an int')
2544 self.assertRaises(OverflowError, os.setgid, self.GID_OVERFLOW)
2545
2546 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
2547 def test_seteuid(self):
2548 if os.getuid() != 0:
2549 self.assertRaises(OSError, os.seteuid, 0)
2550 self.assertRaises(TypeError, os.setegid, 'not an int')
2551 self.assertRaises(OverflowError, os.seteuid, self.UID_OVERFLOW)
2552
2553 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
2554 def test_setegid(self):
2555 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2556 self.assertRaises(OSError, os.setegid, 0)
2557 self.assertRaises(TypeError, os.setegid, 'not an int')
2558 self.assertRaises(OverflowError, os.setegid, self.GID_OVERFLOW)
2559
2560 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2561 def test_setreuid(self):
2562 if os.getuid() != 0:
2563 self.assertRaises(OSError, os.setreuid, 0, 0)
2564 self.assertRaises(TypeError, os.setreuid, 'not an int', 0)
2565 self.assertRaises(TypeError, os.setreuid, 0, 'not an int')
2566 self.assertRaises(OverflowError, os.setreuid, self.UID_OVERFLOW, 0)
2567 self.assertRaises(OverflowError, os.setreuid, 0, self.UID_OVERFLOW)
2568
2569 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2570 @support.requires_subprocess()
2571 def test_setreuid_neg1(self):
2572 # Needs to accept -1. We run this in a subprocess to avoid
2573 # altering the test runner's process state (issue8045).
2574 subprocess.check_call([
2575 sys.executable, '-c',
2576 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
2577
2578 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2579 @support.requires_subprocess()
2580 def test_setregid(self):
2581 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2582 self.assertRaises(OSError, os.setregid, 0, 0)
2583 self.assertRaises(TypeError, os.setregid, 'not an int', 0)
2584 self.assertRaises(TypeError, os.setregid, 0, 'not an int')
2585 self.assertRaises(OverflowError, os.setregid, self.GID_OVERFLOW, 0)
2586 self.assertRaises(OverflowError, os.setregid, 0, self.GID_OVERFLOW)
2587
2588 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2589 @support.requires_subprocess()
2590 def test_setregid_neg1(self):
2591 # Needs to accept -1. We run this in a subprocess to avoid
2592 # altering the test runner's process state (issue8045).
2593 subprocess.check_call([
2594 sys.executable, '-c',
2595 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
2596
2597 @unittest.skipIf(sys.platform == "win32", "Posix specific tests")
2598 class Pep383Tests(unittest.TestCase):
2599 def setUp(self):
2600 if os_helper.TESTFN_UNENCODABLE:
2601 self.dir = os_helper.TESTFN_UNENCODABLE
2602 elif os_helper.TESTFN_NONASCII:
2603 self.dir = os_helper.TESTFN_NONASCII
2604 else:
2605 self.dir = os_helper.TESTFN
2606 self.bdir = os.fsencode(self.dir)
2607
2608 bytesfn = []
2609 def add_filename(fn):
2610 try:
2611 fn = os.fsencode(fn)
2612 except UnicodeEncodeError:
2613 return
2614 bytesfn.append(fn)
2615 add_filename(os_helper.TESTFN_UNICODE)
2616 if os_helper.TESTFN_UNENCODABLE:
2617 add_filename(os_helper.TESTFN_UNENCODABLE)
2618 if os_helper.TESTFN_NONASCII:
2619 add_filename(os_helper.TESTFN_NONASCII)
2620 if not bytesfn:
2621 self.skipTest("couldn't create any non-ascii filename")
2622
2623 self.unicodefn = set()
2624 os.mkdir(self.dir)
2625 try:
2626 for fn in bytesfn:
2627 os_helper.create_empty_file(os.path.join(self.bdir, fn))
2628 fn = os.fsdecode(fn)
2629 if fn in self.unicodefn:
2630 raise ValueError("duplicate filename")
2631 self.unicodefn.add(fn)
2632 except:
2633 shutil.rmtree(self.dir)
2634 raise
2635
2636 def tearDown(self):
2637 shutil.rmtree(self.dir)
2638
2639 def test_listdir(self):
2640 expected = self.unicodefn
2641 found = set(os.listdir(self.dir))
2642 self.assertEqual(found, expected)
2643 # test listdir without arguments
2644 current_directory = os.getcwd()
2645 try:
2646 # The root directory is not readable on Android, so use a directory
2647 # we created ourselves.
2648 os.chdir(self.dir)
2649 self.assertEqual(set(os.listdir()), expected)
2650 finally:
2651 os.chdir(current_directory)
2652
2653 def test_open(self):
2654 for fn in self.unicodefn:
2655 f = open(os.path.join(self.dir, fn), 'rb')
2656 f.close()
2657
2658 @unittest.skipUnless(hasattr(os, 'statvfs'),
2659 "need os.statvfs()")
2660 def test_statvfs(self):
2661 # issue #9645
2662 for fn in self.unicodefn:
2663 # should not fail with file not found error
2664 fullname = os.path.join(self.dir, fn)
2665 os.statvfs(fullname)
2666
2667 def test_stat(self):
2668 for fn in self.unicodefn:
2669 os.stat(os.path.join(self.dir, fn))
2670
2671 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2672 class Win32KillTests(unittest.TestCase):
2673 def _kill(self, sig):
2674 # Start sys.executable as a subprocess and communicate from the
2675 # subprocess to the parent that the interpreter is ready. When it
2676 # becomes ready, send *sig* via os.kill to the subprocess and check
2677 # that the return code is equal to *sig*.
2678 import ctypes
2679 from ctypes import wintypes
2680 import msvcrt
2681
2682 # Since we can't access the contents of the process' stdout until the
2683 # process has exited, use PeekNamedPipe to see what's inside stdout
2684 # without waiting. This is done so we can tell that the interpreter
2685 # is started and running at a point where it could handle a signal.
2686 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
2687 PeekNamedPipe.restype = wintypes.BOOL
2688 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
2689 ctypes.POINTER(ctypes.c_char), # stdout buf
2690 wintypes.DWORD, # Buffer size
2691 ctypes.POINTER(wintypes.DWORD), # bytes read
2692 ctypes.POINTER(wintypes.DWORD), # bytes avail
2693 ctypes.POINTER(wintypes.DWORD)) # bytes left
2694 msg = "running"
2695 proc = subprocess.Popen([sys.executable, "-c",
2696 "import sys;"
2697 "sys.stdout.write('{}');"
2698 "sys.stdout.flush();"
2699 "input()".format(msg)],
2700 stdout=subprocess.PIPE,
2701 stderr=subprocess.PIPE,
2702 stdin=subprocess.PIPE)
2703 self.addCleanup(proc.stdout.close)
2704 self.addCleanup(proc.stderr.close)
2705 self.addCleanup(proc.stdin.close)
2706
2707 count, max = 0, 100
2708 while count < max and proc.poll() is None:
2709 # Create a string buffer to store the result of stdout from the pipe
2710 buf = ctypes.create_string_buffer(len(msg))
2711 # Obtain the text currently in proc.stdout
2712 # Bytes read/avail/left are left as NULL and unused
2713 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
2714 buf, ctypes.sizeof(buf), None, None, None)
2715 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
2716 if buf.value:
2717 self.assertEqual(msg, buf.value.decode())
2718 break
2719 time.sleep(0.1)
2720 count += 1
2721 else:
2722 self.fail("Did not receive communication from the subprocess")
2723
2724 os.kill(proc.pid, sig)
2725 self.assertEqual(proc.wait(), sig)
2726
2727 def test_kill_sigterm(self):
2728 # SIGTERM doesn't mean anything special, but make sure it works
2729 self._kill(signal.SIGTERM)
2730
2731 def test_kill_int(self):
2732 # os.kill on Windows can take an int which gets set as the exit code
2733 self._kill(100)
2734
2735 @unittest.skipIf(mmap is None, "requires mmap")
2736 def _kill_with_event(self, event, name):
2737 tagname = "test_os_%s" % uuid.uuid1()
2738 m = mmap.mmap(-1, 1, tagname)
2739 m[0] = 0
2740
2741 # Run a script which has console control handling enabled.
2742 script = os.path.join(os.path.dirname(__file__),
2743 "win_console_handler.py")
2744 cmd = [sys.executable, script, tagname]
2745 proc = subprocess.Popen(cmd,
2746 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
2747
2748 with proc:
2749 # Let the interpreter startup before we send signals. See #3137.
2750 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
2751 if proc.poll() is None:
2752 break
2753 else:
2754 # Forcefully kill the process if we weren't able to signal it.
2755 proc.kill()
2756 self.fail("Subprocess didn't finish initialization")
2757
2758 os.kill(proc.pid, event)
2759
2760 try:
2761 # proc.send_signal(event) could also be done here.
2762 # Allow time for the signal to be passed and the process to exit.
2763 proc.wait(timeout=support.SHORT_TIMEOUT)
2764 except subprocess.TimeoutExpired:
2765 # Forcefully kill the process if we weren't able to signal it.
2766 proc.kill()
2767 self.fail("subprocess did not stop on {}".format(name))
2768
2769 @unittest.skip("subprocesses aren't inheriting Ctrl+C property")
2770 @support.requires_subprocess()
2771 def test_CTRL_C_EVENT(self):
2772 from ctypes import wintypes
2773 import ctypes
2774
2775 # Make a NULL value by creating a pointer with no argument.
2776 NULL = ctypes.POINTER(ctypes.c_int)()
2777 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
2778 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
2779 wintypes.BOOL)
2780 SetConsoleCtrlHandler.restype = wintypes.BOOL
2781
2782 # Calling this with NULL and FALSE causes the calling process to
2783 # handle Ctrl+C, rather than ignore it. This property is inherited
2784 # by subprocesses.
2785 SetConsoleCtrlHandler(NULL, 0)
2786
2787 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
2788
2789 @support.requires_subprocess()
2790 def test_CTRL_BREAK_EVENT(self):
2791 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
2792
2793
2794 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2795 class Win32ListdirTests(unittest.TestCase):
2796 """Test listdir on Windows."""
2797
2798 def setUp(self):
2799 self.created_paths = []
2800 for i in range(2):
2801 dir_name = 'SUB%d' % i
2802 dir_path = os.path.join(os_helper.TESTFN, dir_name)
2803 file_name = 'FILE%d' % i
2804 file_path = os.path.join(os_helper.TESTFN, file_name)
2805 os.makedirs(dir_path)
2806 with open(file_path, 'w', encoding='utf-8') as f:
2807 f.write("I'm %s and proud of it. Blame test_os.\n" % file_path)
2808 self.created_paths.extend([dir_name, file_name])
2809 self.created_paths.sort()
2810
2811 def tearDown(self):
2812 shutil.rmtree(os_helper.TESTFN)
2813
2814 def test_listdir_no_extended_path(self):
2815 """Test when the path is not an "extended" path."""
2816 # unicode
2817 self.assertEqual(
2818 sorted(os.listdir(os_helper.TESTFN)),
2819 self.created_paths)
2820
2821 # bytes
2822 self.assertEqual(
2823 sorted(os.listdir(os.fsencode(os_helper.TESTFN))),
2824 [os.fsencode(path) for path in self.created_paths])
2825
2826 def test_listdir_extended_path(self):
2827 """Test when the path starts with '\\\\?\\'."""
2828 # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
2829 # unicode
2830 path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN)
2831 self.assertEqual(
2832 sorted(os.listdir(path)),
2833 self.created_paths)
2834
2835 # bytes
2836 path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN))
2837 self.assertEqual(
2838 sorted(os.listdir(path)),
2839 [os.fsencode(path) for path in self.created_paths])
2840
2841
2842 @unittest.skipUnless(os.name == "nt", "NT specific tests")
2843 class Win32ListdriveTests(unittest.TestCase):
2844 """Test listdrive, listmounts and listvolume on Windows."""
2845
2846 def setUp(self):
2847 # Get drives and volumes from fsutil
2848 out = subprocess.check_output(
2849 ["fsutil.exe", "volume", "list"],
2850 cwd=os.path.join(os.getenv("SystemRoot", "\\Windows"), "System32"),
2851 encoding="mbcs",
2852 errors="ignore",
2853 )
2854 lines = out.splitlines()
2855 self.known_volumes = {l for l in lines if l.startswith('\\\\?\\')}
2856 self.known_drives = {l for l in lines if l[1:] == ':\\'}
2857 self.known_mounts = {l for l in lines if l[1:3] == ':\\'}
2858
2859 def test_listdrives(self):
2860 drives = os.listdrives()
2861 self.assertIsInstance(drives, list)
2862 self.assertSetEqual(
2863 self.known_drives,
2864 self.known_drives & set(drives),
2865 )
2866
2867 def test_listvolumes(self):
2868 volumes = os.listvolumes()
2869 self.assertIsInstance(volumes, list)
2870 self.assertSetEqual(
2871 self.known_volumes,
2872 self.known_volumes & set(volumes),
2873 )
2874
2875 def test_listmounts(self):
2876 for volume in os.listvolumes():
2877 try:
2878 mounts = os.listmounts(volume)
2879 except OSError as ex:
2880 if support.verbose:
2881 print("Skipping", volume, "because of", ex)
2882 else:
2883 self.assertIsInstance(mounts, list)
2884 self.assertSetEqual(
2885 set(mounts),
2886 self.known_mounts & set(mounts),
2887 )
2888
2889
2890 @unittest.skipUnless(hasattr(os, 'readlink'), 'needs os.readlink()')
2891 class ReadlinkTests(unittest.TestCase):
2892 filelink = 'readlinktest'
2893 filelink_target = os.path.abspath(__file__)
2894 filelinkb = os.fsencode(filelink)
2895 filelinkb_target = os.fsencode(filelink_target)
2896
2897 def assertPathEqual(self, left, right):
2898 left = os.path.normcase(left)
2899 right = os.path.normcase(right)
2900 if sys.platform == 'win32':
2901 # Bad practice to blindly strip the prefix as it may be required to
2902 # correctly refer to the file, but we're only comparing paths here.
2903 has_prefix = lambda p: p.startswith(
2904 b'\\\\?\\' if isinstance(p, bytes) else '\\\\?\\')
2905 if has_prefix(left):
2906 left = left[4:]
2907 if has_prefix(right):
2908 right = right[4:]
2909 self.assertEqual(left, right)
2910
2911 def setUp(self):
2912 self.assertTrue(os.path.exists(self.filelink_target))
2913 self.assertTrue(os.path.exists(self.filelinkb_target))
2914 self.assertFalse(os.path.exists(self.filelink))
2915 self.assertFalse(os.path.exists(self.filelinkb))
2916
2917 def test_not_symlink(self):
2918 filelink_target = FakePath(self.filelink_target)
2919 self.assertRaises(OSError, os.readlink, self.filelink_target)
2920 self.assertRaises(OSError, os.readlink, filelink_target)
2921
2922 def test_missing_link(self):
2923 self.assertRaises(FileNotFoundError, os.readlink, 'missing-link')
2924 self.assertRaises(FileNotFoundError, os.readlink,
2925 FakePath('missing-link'))
2926
2927 @os_helper.skip_unless_symlink
2928 def test_pathlike(self):
2929 os.symlink(self.filelink_target, self.filelink)
2930 self.addCleanup(os_helper.unlink, self.filelink)
2931 filelink = FakePath(self.filelink)
2932 self.assertPathEqual(os.readlink(filelink), self.filelink_target)
2933
2934 @os_helper.skip_unless_symlink
2935 def test_pathlike_bytes(self):
2936 os.symlink(self.filelinkb_target, self.filelinkb)
2937 self.addCleanup(os_helper.unlink, self.filelinkb)
2938 path = os.readlink(FakePath(self.filelinkb))
2939 self.assertPathEqual(path, self.filelinkb_target)
2940 self.assertIsInstance(path, bytes)
2941
2942 @os_helper.skip_unless_symlink
2943 def test_bytes(self):
2944 os.symlink(self.filelinkb_target, self.filelinkb)
2945 self.addCleanup(os_helper.unlink, self.filelinkb)
2946 path = os.readlink(self.filelinkb)
2947 self.assertPathEqual(path, self.filelinkb_target)
2948 self.assertIsInstance(path, bytes)
2949
2950
2951 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2952 @os_helper.skip_unless_symlink
2953 class Win32SymlinkTests(unittest.TestCase):
2954 filelink = 'filelinktest'
2955 filelink_target = os.path.abspath(__file__)
2956 dirlink = 'dirlinktest'
2957 dirlink_target = os.path.dirname(filelink_target)
2958 missing_link = 'missing link'
2959
2960 def setUp(self):
2961 assert os.path.exists(self.dirlink_target)
2962 assert os.path.exists(self.filelink_target)
2963 assert not os.path.exists(self.dirlink)
2964 assert not os.path.exists(self.filelink)
2965 assert not os.path.exists(self.missing_link)
2966
2967 def tearDown(self):
2968 if os.path.exists(self.filelink):
2969 os.remove(self.filelink)
2970 if os.path.exists(self.dirlink):
2971 os.rmdir(self.dirlink)
2972 if os.path.lexists(self.missing_link):
2973 os.remove(self.missing_link)
2974
2975 def test_directory_link(self):
2976 os.symlink(self.dirlink_target, self.dirlink)
2977 self.assertTrue(os.path.exists(self.dirlink))
2978 self.assertTrue(os.path.isdir(self.dirlink))
2979 self.assertTrue(os.path.islink(self.dirlink))
2980 self.check_stat(self.dirlink, self.dirlink_target)
2981
2982 def test_file_link(self):
2983 os.symlink(self.filelink_target, self.filelink)
2984 self.assertTrue(os.path.exists(self.filelink))
2985 self.assertTrue(os.path.isfile(self.filelink))
2986 self.assertTrue(os.path.islink(self.filelink))
2987 self.check_stat(self.filelink, self.filelink_target)
2988
2989 def _create_missing_dir_link(self):
2990 'Create a "directory" link to a non-existent target'
2991 linkname = self.missing_link
2992 if os.path.lexists(linkname):
2993 os.remove(linkname)
2994 target = r'c:\\target does not exist.29r3c740'
2995 assert not os.path.exists(target)
2996 target_is_dir = True
2997 os.symlink(target, linkname, target_is_dir)
2998
2999 def test_remove_directory_link_to_missing_target(self):
3000 self._create_missing_dir_link()
3001 # For compatibility with Unix, os.remove will check the
3002 # directory status and call RemoveDirectory if the symlink
3003 # was created with target_is_dir==True.
3004 os.remove(self.missing_link)
3005
3006 def test_isdir_on_directory_link_to_missing_target(self):
3007 self._create_missing_dir_link()
3008 self.assertFalse(os.path.isdir(self.missing_link))
3009
3010 def test_rmdir_on_directory_link_to_missing_target(self):
3011 self._create_missing_dir_link()
3012 os.rmdir(self.missing_link)
3013
3014 def check_stat(self, link, target):
3015 self.assertEqual(os.stat(link), os.stat(target))
3016 self.assertNotEqual(os.lstat(link), os.stat(link))
3017
3018 bytes_link = os.fsencode(link)
3019 self.assertEqual(os.stat(bytes_link), os.stat(target))
3020 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
3021
3022 def test_12084(self):
3023 level1 = os.path.abspath(os_helper.TESTFN)
3024 level2 = os.path.join(level1, "level2")
3025 level3 = os.path.join(level2, "level3")
3026 self.addCleanup(os_helper.rmtree, level1)
3027
3028 os.mkdir(level1)
3029 os.mkdir(level2)
3030 os.mkdir(level3)
3031
3032 file1 = os.path.abspath(os.path.join(level1, "file1"))
3033 create_file(file1)
3034
3035 orig_dir = os.getcwd()
3036 try:
3037 os.chdir(level2)
3038 link = os.path.join(level2, "link")
3039 os.symlink(os.path.relpath(file1), "link")
3040 self.assertIn("link", os.listdir(os.getcwd()))
3041
3042 # Check os.stat calls from the same dir as the link
3043 self.assertEqual(os.stat(file1), os.stat("link"))
3044
3045 # Check os.stat calls from a dir below the link
3046 os.chdir(level1)
3047 self.assertEqual(os.stat(file1),
3048 os.stat(os.path.relpath(link)))
3049
3050 # Check os.stat calls from a dir above the link
3051 os.chdir(level3)
3052 self.assertEqual(os.stat(file1),
3053 os.stat(os.path.relpath(link)))
3054 finally:
3055 os.chdir(orig_dir)
3056
3057 @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users')
3058 and os.path.exists(r'C:\ProgramData'),
3059 'Test directories not found')
3060 def test_29248(self):
3061 # os.symlink() calls CreateSymbolicLink, which creates
3062 # the reparse data buffer with the print name stored
3063 # first, so the offset is always 0. CreateSymbolicLink
3064 # stores the "PrintName" DOS path (e.g. "C:\") first,
3065 # with an offset of 0, followed by the "SubstituteName"
3066 # NT path (e.g. "\??\C:\"). The "All Users" link, on
3067 # the other hand, seems to have been created manually
3068 # with an inverted order.
3069 target = os.readlink(r'C:\Users\All Users')
3070 self.assertTrue(os.path.samefile(target, r'C:\ProgramData'))
3071
3072 def test_buffer_overflow(self):
3073 # Older versions would have a buffer overflow when detecting
3074 # whether a link source was a directory. This test ensures we
3075 # no longer crash, but does not otherwise validate the behavior
3076 segment = 'X' * 27
3077 path = os.path.join(*[segment] * 10)
3078 test_cases = [
3079 # overflow with absolute src
3080 ('\\' + path, segment),
3081 # overflow dest with relative src
3082 (segment, path),
3083 # overflow when joining src
3084 (path[:180], path[:180]),
3085 ]
3086 for src, dest in test_cases:
3087 try:
3088 os.symlink(src, dest)
3089 except FileNotFoundError:
3090 pass
3091 else:
3092 try:
3093 os.remove(dest)
3094 except OSError:
3095 pass
3096 # Also test with bytes, since that is a separate code path.
3097 try:
3098 os.symlink(os.fsencode(src), os.fsencode(dest))
3099 except FileNotFoundError:
3100 pass
3101 else:
3102 try:
3103 os.remove(dest)
3104 except OSError:
3105 pass
3106
3107 def test_appexeclink(self):
3108 root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps')
3109 if not os.path.isdir(root):
3110 self.skipTest("test requires a WindowsApps directory")
3111
3112 aliases = [os.path.join(root, a)
3113 for a in fnmatch.filter(os.listdir(root), '*.exe')]
3114
3115 for alias in aliases:
3116 if support.verbose:
3117 print()
3118 print("Testing with", alias)
3119 st = os.lstat(alias)
3120 self.assertEqual(st, os.stat(alias))
3121 self.assertFalse(stat.S_ISLNK(st.st_mode))
3122 self.assertEqual(st.st_reparse_tag, stat.IO_REPARSE_TAG_APPEXECLINK)
3123 self.assertTrue(os.path.isfile(alias))
3124 # testing the first one we see is sufficient
3125 break
3126 else:
3127 self.skipTest("test requires an app execution alias")
3128
3129 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
3130 class Win32JunctionTests(unittest.TestCase):
3131 junction = 'junctiontest'
3132 junction_target = os.path.dirname(os.path.abspath(__file__))
3133
3134 def setUp(self):
3135 assert os.path.exists(self.junction_target)
3136 assert not os.path.lexists(self.junction)
3137
3138 def tearDown(self):
3139 if os.path.lexists(self.junction):
3140 os.unlink(self.junction)
3141
3142 def test_create_junction(self):
3143 _winapi.CreateJunction(self.junction_target, self.junction)
3144 self.assertTrue(os.path.lexists(self.junction))
3145 self.assertTrue(os.path.exists(self.junction))
3146 self.assertTrue(os.path.isdir(self.junction))
3147 self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction))
3148 self.assertEqual(os.stat(self.junction), os.stat(self.junction_target))
3149
3150 # bpo-37834: Junctions are not recognized as links.
3151 self.assertFalse(os.path.islink(self.junction))
3152 self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target),
3153 os.path.normcase(os.readlink(self.junction)))
3154
3155 def test_unlink_removes_junction(self):
3156 _winapi.CreateJunction(self.junction_target, self.junction)
3157 self.assertTrue(os.path.exists(self.junction))
3158 self.assertTrue(os.path.lexists(self.junction))
3159
3160 os.unlink(self.junction)
3161 self.assertFalse(os.path.exists(self.junction))
3162
3163 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
3164 class Win32NtTests(unittest.TestCase):
3165 def test_getfinalpathname_handles(self):
3166 nt = import_helper.import_module('nt')
3167 ctypes = import_helper.import_module('ctypes')
3168 # Ruff false positive -- it thinks we're redefining `ctypes` here
3169 import ctypes.wintypes # noqa: F811
3170
3171 kernel = ctypes.WinDLL('Kernel32.dll', use_last_error=True)
3172 kernel.GetCurrentProcess.restype = ctypes.wintypes.HANDLE
3173
3174 kernel.GetProcessHandleCount.restype = ctypes.wintypes.BOOL
3175 kernel.GetProcessHandleCount.argtypes = (ctypes.wintypes.HANDLE,
3176 ctypes.wintypes.LPDWORD)
3177
3178 # This is a pseudo-handle that doesn't need to be closed
3179 hproc = kernel.GetCurrentProcess()
3180
3181 handle_count = ctypes.wintypes.DWORD()
3182 ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count))
3183 self.assertEqual(1, ok)
3184
3185 before_count = handle_count.value
3186
3187 # The first two test the error path, __file__ tests the success path
3188 filenames = [
3189 r'\\?\C:',
3190 r'\\?\NUL',
3191 r'\\?\CONIN',
3192 __file__,
3193 ]
3194
3195 for _ in range(10):
3196 for name in filenames:
3197 try:
3198 nt._getfinalpathname(name)
3199 except Exception:
3200 # Failure is expected
3201 pass
3202 try:
3203 os.stat(name)
3204 except Exception:
3205 pass
3206
3207 ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count))
3208 self.assertEqual(1, ok)
3209
3210 handle_delta = handle_count.value - before_count
3211
3212 self.assertEqual(0, handle_delta)
3213
3214 @support.requires_subprocess()
3215 def test_stat_unlink_race(self):
3216 # bpo-46785: the implementation of os.stat() falls back to reading
3217 # the parent directory if CreateFileW() fails with a permission
3218 # error. If reading the parent directory fails because the file or
3219 # directory are subsequently unlinked, or because the volume or
3220 # share are no longer available, then the original permission error
3221 # should not be restored.
3222 filename = os_helper.TESTFN
3223 self.addCleanup(os_helper.unlink, filename)
3224 deadline = time.time() + 5
3225 command = textwrap.dedent("""\
3226 import os
3227 import sys
3228 import time
3229
3230 filename = sys.argv[1]
3231 deadline = float(sys.argv[2])
3232
3233 while time.time() < deadline:
3234 try:
3235 with open(filename, "w") as f:
3236 pass
3237 except OSError:
3238 pass
3239 try:
3240 os.remove(filename)
3241 except OSError:
3242 pass
3243 """)
3244
3245 with subprocess.Popen([sys.executable, '-c', command, filename, str(deadline)]) as proc:
3246 while time.time() < deadline:
3247 try:
3248 os.stat(filename)
3249 except FileNotFoundError as e:
3250 assert e.winerror == 2 # ERROR_FILE_NOT_FOUND
3251 try:
3252 proc.wait(1)
3253 except subprocess.TimeoutExpired:
3254 proc.terminate()
3255
3256 @support.requires_subprocess()
3257 def test_stat_inaccessible_file(self):
3258 filename = os_helper.TESTFN
3259 ICACLS = os.path.expandvars(r"%SystemRoot%\System32\icacls.exe")
3260
3261 with open(filename, "wb") as f:
3262 f.write(b'Test data')
3263
3264 stat1 = os.stat(filename)
3265
3266 try:
3267 # Remove all permissions from the file
3268 subprocess.check_output([ICACLS, filename, "/inheritance:r"],
3269 stderr=subprocess.STDOUT)
3270 except subprocess.CalledProcessError as ex:
3271 if support.verbose:
3272 print(ICACLS, filename, "/inheritance:r", "failed.")
3273 print(ex.stdout.decode("oem", "replace").rstrip())
3274 try:
3275 os.unlink(filename)
3276 except OSError:
3277 pass
3278 self.skipTest("Unable to create inaccessible file")
3279
3280 def cleanup():
3281 # Give delete permission to the owner (us)
3282 subprocess.check_output([ICACLS, filename, "/grant", "*WD:(D)"],
3283 stderr=subprocess.STDOUT)
3284 os.unlink(filename)
3285
3286 self.addCleanup(cleanup)
3287
3288 if support.verbose:
3289 print("File:", filename)
3290 print("stat with access:", stat1)
3291
3292 # First test - we shouldn't raise here, because we still have access to
3293 # the directory and can extract enough information from its metadata.
3294 stat2 = os.stat(filename)
3295
3296 if support.verbose:
3297 print(" without access:", stat2)
3298
3299 # We may not get st_dev/st_ino, so ensure those are 0 or match
3300 self.assertIn(stat2.st_dev, (0, stat1.st_dev))
3301 self.assertIn(stat2.st_ino, (0, stat1.st_ino))
3302
3303 # st_mode and st_size should match (for a normal file, at least)
3304 self.assertEqual(stat1.st_mode, stat2.st_mode)
3305 self.assertEqual(stat1.st_size, stat2.st_size)
3306
3307 # st_ctime and st_mtime should be the same
3308 self.assertEqual(stat1.st_ctime, stat2.st_ctime)
3309 self.assertEqual(stat1.st_mtime, stat2.st_mtime)
3310
3311 # st_atime should be the same or later
3312 self.assertGreaterEqual(stat1.st_atime, stat2.st_atime)
3313
3314
3315 @os_helper.skip_unless_symlink
3316 class NonLocalSymlinkTests(unittest.TestCase):
3317
3318 def setUp(self):
3319 r"""
3320 Create this structure:
3321
3322 base
3323 \___ some_dir
3324 """
3325 os.makedirs('base/some_dir')
3326
3327 def tearDown(self):
3328 shutil.rmtree('base')
3329
3330 def test_directory_link_nonlocal(self):
3331 """
3332 The symlink target should resolve relative to the link, not relative
3333 to the current directory.
3334
3335 Then, link base/some_link -> base/some_dir and ensure that some_link
3336 is resolved as a directory.
3337
3338 In issue13772, it was discovered that directory detection failed if
3339 the symlink target was not specified relative to the current
3340 directory, which was a defect in the implementation.
3341 """
3342 src = os.path.join('base', 'some_link')
3343 os.symlink('some_dir', src)
3344 assert os.path.isdir(src)
3345
3346
3347 class FSEncodingTests(unittest.TestCase):
3348 def test_nop(self):
3349 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
3350 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
3351
3352 def test_identity(self):
3353 # assert fsdecode(fsencode(x)) == x
3354 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
3355 try:
3356 bytesfn = os.fsencode(fn)
3357 except UnicodeEncodeError:
3358 continue
3359 self.assertEqual(os.fsdecode(bytesfn), fn)
3360
3361
3362
3363 class DeviceEncodingTests(unittest.TestCase):
3364
3365 def test_bad_fd(self):
3366 # Return None when an fd doesn't actually exist.
3367 self.assertIsNone(os.device_encoding(123456))
3368
3369 @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (sys.platform.startswith('win') or
3370 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
3371 'test requires a tty and either Windows or nl_langinfo(CODESET)')
3372 @unittest.skipIf(
3373 support.is_emscripten, "Cannot get encoding of stdin on Emscripten"
3374 )
3375 def test_device_encoding(self):
3376 encoding = os.device_encoding(0)
3377 self.assertIsNotNone(encoding)
3378 self.assertTrue(codecs.lookup(encoding))
3379
3380
3381 @support.requires_subprocess()
3382 class PidTests(unittest.TestCase):
3383 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
3384 def test_getppid(self):
3385 p = subprocess.Popen([sys._base_executable, '-c',
3386 'import os; print(os.getppid())'],
3387 stdout=subprocess.PIPE,
3388 stderr=subprocess.PIPE)
3389 stdout, error = p.communicate()
3390 # We are the parent of our subprocess
3391 self.assertEqual(error, b'')
3392 self.assertEqual(int(stdout), os.getpid())
3393
3394 def check_waitpid(self, code, exitcode, callback=None):
3395 if sys.platform == 'win32':
3396 # On Windows, os.spawnv() simply joins arguments with spaces:
3397 # arguments need to be quoted
3398 args = [f'"{sys.executable}"', '-c', f'"{code}"']
3399 else:
3400 args = [sys.executable, '-c', code]
3401 pid = os.spawnv(os.P_NOWAIT, sys.executable, args)
3402
3403 if callback is not None:
3404 callback(pid)
3405
3406 # don't use support.wait_process() to test directly os.waitpid()
3407 # and os.waitstatus_to_exitcode()
3408 pid2, status = os.waitpid(pid, 0)
3409 self.assertEqual(os.waitstatus_to_exitcode(status), exitcode)
3410 self.assertEqual(pid2, pid)
3411
3412 def test_waitpid(self):
3413 self.check_waitpid(code='pass', exitcode=0)
3414
3415 def test_waitstatus_to_exitcode(self):
3416 exitcode = 23
3417 code = f'import sys; sys.exit({exitcode})'
3418 self.check_waitpid(code, exitcode=exitcode)
3419
3420 with self.assertRaises(TypeError):
3421 os.waitstatus_to_exitcode(0.0)
3422
3423 @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
3424 def test_waitpid_windows(self):
3425 # bpo-40138: test os.waitpid() and os.waitstatus_to_exitcode()
3426 # with exit code larger than INT_MAX.
3427 STATUS_CONTROL_C_EXIT = 0xC000013A
3428 code = f'import _winapi; _winapi.ExitProcess({STATUS_CONTROL_C_EXIT})'
3429 self.check_waitpid(code, exitcode=STATUS_CONTROL_C_EXIT)
3430
3431 @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
3432 def test_waitstatus_to_exitcode_windows(self):
3433 max_exitcode = 2 ** 32 - 1
3434 for exitcode in (0, 1, 5, max_exitcode):
3435 self.assertEqual(os.waitstatus_to_exitcode(exitcode << 8),
3436 exitcode)
3437
3438 # invalid values
3439 with self.assertRaises(ValueError):
3440 os.waitstatus_to_exitcode((max_exitcode + 1) << 8)
3441 with self.assertRaises(OverflowError):
3442 os.waitstatus_to_exitcode(-1)
3443
3444 # Skip the test on Windows
3445 @unittest.skipUnless(hasattr(signal, 'SIGKILL'), 'need signal.SIGKILL')
3446 def test_waitstatus_to_exitcode_kill(self):
3447 code = f'import time; time.sleep({support.LONG_TIMEOUT})'
3448 signum = signal.SIGKILL
3449
3450 def kill_process(pid):
3451 os.kill(pid, signum)
3452
3453 self.check_waitpid(code, exitcode=-signum, callback=kill_process)
3454
3455
3456 @support.requires_subprocess()
3457 class SpawnTests(unittest.TestCase):
3458 @staticmethod
3459 def quote_args(args):
3460 # On Windows, os.spawn* simply joins arguments with spaces:
3461 # arguments need to be quoted
3462 if os.name != 'nt':
3463 return args
3464 return [f'"{arg}"' if " " in arg.strip() else arg for arg in args]
3465
3466 def create_args(self, *, with_env=False, use_bytes=False):
3467 self.exitcode = 17
3468
3469 filename = os_helper.TESTFN
3470 self.addCleanup(os_helper.unlink, filename)
3471
3472 if not with_env:
3473 code = 'import sys; sys.exit(%s)' % self.exitcode
3474 else:
3475 self.env = dict(os.environ)
3476 # create an unique key
3477 self.key = str(uuid.uuid4())
3478 self.env[self.key] = self.key
3479 # read the variable from os.environ to check that it exists
3480 code = ('import sys, os; magic = os.environ[%r]; sys.exit(%s)'
3481 % (self.key, self.exitcode))
3482
3483 with open(filename, "w", encoding="utf-8") as fp:
3484 fp.write(code)
3485
3486 program = sys.executable
3487 args = self.quote_args([program, filename])
3488 if use_bytes:
3489 program = os.fsencode(program)
3490 args = [os.fsencode(a) for a in args]
3491 self.env = {os.fsencode(k): os.fsencode(v)
3492 for k, v in self.env.items()}
3493
3494 return program, args
3495
3496 @requires_os_func('spawnl')
3497 def test_spawnl(self):
3498 program, args = self.create_args()
3499 exitcode = os.spawnl(os.P_WAIT, program, *args)
3500 self.assertEqual(exitcode, self.exitcode)
3501
3502 @requires_os_func('spawnle')
3503 def test_spawnle(self):
3504 program, args = self.create_args(with_env=True)
3505 exitcode = os.spawnle(os.P_WAIT, program, *args, self.env)
3506 self.assertEqual(exitcode, self.exitcode)
3507
3508 @requires_os_func('spawnlp')
3509 def test_spawnlp(self):
3510 program, args = self.create_args()
3511 exitcode = os.spawnlp(os.P_WAIT, program, *args)
3512 self.assertEqual(exitcode, self.exitcode)
3513
3514 @requires_os_func('spawnlpe')
3515 def test_spawnlpe(self):
3516 program, args = self.create_args(with_env=True)
3517 exitcode = os.spawnlpe(os.P_WAIT, program, *args, self.env)
3518 self.assertEqual(exitcode, self.exitcode)
3519
3520 @requires_os_func('spawnv')
3521 def test_spawnv(self):
3522 program, args = self.create_args()
3523 exitcode = os.spawnv(os.P_WAIT, program, args)
3524 self.assertEqual(exitcode, self.exitcode)
3525
3526 # Test for PyUnicode_FSConverter()
3527 exitcode = os.spawnv(os.P_WAIT, FakePath(program), args)
3528 self.assertEqual(exitcode, self.exitcode)
3529
3530 @requires_os_func('spawnve')
3531 def test_spawnve(self):
3532 program, args = self.create_args(with_env=True)
3533 exitcode = os.spawnve(os.P_WAIT, program, args, self.env)
3534 self.assertEqual(exitcode, self.exitcode)
3535
3536 @requires_os_func('spawnvp')
3537 def test_spawnvp(self):
3538 program, args = self.create_args()
3539 exitcode = os.spawnvp(os.P_WAIT, program, args)
3540 self.assertEqual(exitcode, self.exitcode)
3541
3542 @requires_os_func('spawnvpe')
3543 def test_spawnvpe(self):
3544 program, args = self.create_args(with_env=True)
3545 exitcode = os.spawnvpe(os.P_WAIT, program, args, self.env)
3546 self.assertEqual(exitcode, self.exitcode)
3547
3548 @requires_os_func('spawnv')
3549 def test_nowait(self):
3550 program, args = self.create_args()
3551 pid = os.spawnv(os.P_NOWAIT, program, args)
3552 support.wait_process(pid, exitcode=self.exitcode)
3553
3554 @requires_os_func('spawnve')
3555 def test_spawnve_bytes(self):
3556 # Test bytes handling in parse_arglist and parse_envlist (#28114)
3557 program, args = self.create_args(with_env=True, use_bytes=True)
3558 exitcode = os.spawnve(os.P_WAIT, program, args, self.env)
3559 self.assertEqual(exitcode, self.exitcode)
3560
3561 @requires_os_func('spawnl')
3562 def test_spawnl_noargs(self):
3563 program, __ = self.create_args()
3564 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program)
3565 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program, '')
3566
3567 @requires_os_func('spawnle')
3568 def test_spawnle_noargs(self):
3569 program, __ = self.create_args()
3570 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, {})
3571 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, '', {})
3572
3573 @requires_os_func('spawnv')
3574 def test_spawnv_noargs(self):
3575 program, __ = self.create_args()
3576 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ())
3577 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, [])
3578 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ('',))
3579 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, [''])
3580
3581 @requires_os_func('spawnve')
3582 def test_spawnve_noargs(self):
3583 program, __ = self.create_args()
3584 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, (), {})
3585 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, [], {})
3586 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, ('',), {})
3587 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, [''], {})
3588
3589 def _test_invalid_env(self, spawn):
3590 program = sys.executable
3591 args = self.quote_args([program, '-c', 'pass'])
3592
3593 # null character in the environment variable name
3594 newenv = os.environ.copy()
3595 newenv["FRUIT\0VEGETABLE"] = "cabbage"
3596 try:
3597 exitcode = spawn(os.P_WAIT, program, args, newenv)
3598 except ValueError:
3599 pass
3600 else:
3601 self.assertEqual(exitcode, 127)
3602
3603 # null character in the environment variable value
3604 newenv = os.environ.copy()
3605 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
3606 try:
3607 exitcode = spawn(os.P_WAIT, program, args, newenv)
3608 except ValueError:
3609 pass
3610 else:
3611 self.assertEqual(exitcode, 127)
3612
3613 # equal character in the environment variable name
3614 newenv = os.environ.copy()
3615 newenv["FRUIT=ORANGE"] = "lemon"
3616 try:
3617 exitcode = spawn(os.P_WAIT, program, args, newenv)
3618 except ValueError:
3619 pass
3620 else:
3621 self.assertEqual(exitcode, 127)
3622
3623 # equal character in the environment variable value
3624 filename = os_helper.TESTFN
3625 self.addCleanup(os_helper.unlink, filename)
3626 with open(filename, "w", encoding="utf-8") as fp:
3627 fp.write('import sys, os\n'
3628 'if os.getenv("FRUIT") != "orange=lemon":\n'
3629 ' raise AssertionError')
3630
3631 args = self.quote_args([program, filename])
3632 newenv = os.environ.copy()
3633 newenv["FRUIT"] = "orange=lemon"
3634 exitcode = spawn(os.P_WAIT, program, args, newenv)
3635 self.assertEqual(exitcode, 0)
3636
3637 @requires_os_func('spawnve')
3638 def test_spawnve_invalid_env(self):
3639 self._test_invalid_env(os.spawnve)
3640
3641 @requires_os_func('spawnvpe')
3642 def test_spawnvpe_invalid_env(self):
3643 self._test_invalid_env(os.spawnvpe)
3644
3645
3646 # The introduction of this TestCase caused at least two different errors on
3647 # *nix buildbots. Temporarily skip this to let the buildbots move along.
3648 @unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
3649 @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
3650 class LoginTests(unittest.TestCase):
3651 def test_getlogin(self):
3652 user_name = os.getlogin()
3653 self.assertNotEqual(len(user_name), 0)
3654
3655
3656 @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
3657 "needs os.getpriority and os.setpriority")
3658 class ProgramPriorityTests(unittest.TestCase):
3659 """Tests for os.getpriority() and os.setpriority()."""
3660
3661 def test_set_get_priority(self):
3662 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
3663 code = f"""if 1:
3664 import os
3665 os.setpriority(os.PRIO_PROCESS, os.getpid(), {base} + 1)
3666 print(os.getpriority(os.PRIO_PROCESS, os.getpid()))
3667 """
3668
3669 # Subprocess inherits the current process' priority.
3670 _, out, _ = assert_python_ok("-c", code)
3671 new_prio = int(out)
3672 # nice value cap is 19 for linux and 20 for FreeBSD
3673 if base >= 19 and new_prio <= base:
3674 raise unittest.SkipTest("unable to reliably test setpriority "
3675 "at current nice level of %s" % base)
3676 else:
3677 self.assertEqual(new_prio, base + 1)
3678
3679
3680 @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
3681 class TestSendfile(unittest.IsolatedAsyncioTestCase):
3682
3683 DATA = b"12345abcde" * 16 * 1024 # 160 KiB
3684 SUPPORT_HEADERS_TRAILERS = (
3685 not sys.platform.startswith(("linux", "android", "solaris", "sunos")))
3686 requires_headers_trailers = unittest.skipUnless(SUPPORT_HEADERS_TRAILERS,
3687 'requires headers and trailers support')
3688 requires_32b = unittest.skipUnless(sys.maxsize < 2**32,
3689 'test is only meaningful on 32-bit builds')
3690
3691 @classmethod
3692 def setUpClass(cls):
3693 create_file(os_helper.TESTFN, cls.DATA)
3694
3695 @classmethod
3696 def tearDownClass(cls):
3697 os_helper.unlink(os_helper.TESTFN)
3698
3699 @staticmethod
3700 async def chunks(reader):
3701 while not reader.at_eof():
3702 yield await reader.read()
3703
3704 async def handle_new_client(self, reader, writer):
3705 self.server_buffer = b''.join([x async for x in self.chunks(reader)])
3706 writer.close()
3707 self.server.close() # The test server processes a single client only
3708
3709 async def asyncSetUp(self):
3710 self.server_buffer = b''
3711 self.server = await asyncio.start_server(self.handle_new_client,
3712 socket_helper.HOSTv4)
3713 server_name = self.server.sockets[0].getsockname()
3714 self.client = socket.socket()
3715 self.client.setblocking(False)
3716 await asyncio.get_running_loop().sock_connect(self.client, server_name)
3717 self.sockno = self.client.fileno()
3718 self.file = open(os_helper.TESTFN, 'rb')
3719 self.fileno = self.file.fileno()
3720
3721 async def asyncTearDown(self):
3722 self.file.close()
3723 self.client.close()
3724 await self.server.wait_closed()
3725
3726 # Use the test subject instead of asyncio.loop.sendfile
3727 @staticmethod
3728 async def async_sendfile(*args, **kwargs):
3729 return await asyncio.to_thread(os.sendfile, *args, **kwargs)
3730
3731 @staticmethod
3732 async def sendfile_wrapper(*args, **kwargs):
3733 """A higher level wrapper representing how an application is
3734 supposed to use sendfile().
3735 """
3736 while True:
3737 try:
3738 return await TestSendfile.async_sendfile(*args, **kwargs)
3739 except OSError as err:
3740 if err.errno == errno.ECONNRESET:
3741 # disconnected
3742 raise
3743 elif err.errno in (errno.EAGAIN, errno.EBUSY):
3744 # we have to retry send data
3745 continue
3746 else:
3747 raise
3748
3749 async def test_send_whole_file(self):
3750 # normal send
3751 total_sent = 0
3752 offset = 0
3753 nbytes = 4096
3754 while total_sent < len(self.DATA):
3755 sent = await self.sendfile_wrapper(self.sockno, self.fileno,
3756 offset, nbytes)
3757 if sent == 0:
3758 break
3759 offset += sent
3760 total_sent += sent
3761 self.assertTrue(sent <= nbytes)
3762 self.assertEqual(offset, total_sent)
3763
3764 self.assertEqual(total_sent, len(self.DATA))
3765 self.client.shutdown(socket.SHUT_RDWR)
3766 self.client.close()
3767 await self.server.wait_closed()
3768 self.assertEqual(len(self.server_buffer), len(self.DATA))
3769 self.assertEqual(self.server_buffer, self.DATA)
3770
3771 async def test_send_at_certain_offset(self):
3772 # start sending a file at a certain offset
3773 total_sent = 0
3774 offset = len(self.DATA) // 2
3775 must_send = len(self.DATA) - offset
3776 nbytes = 4096
3777 while total_sent < must_send:
3778 sent = await self.sendfile_wrapper(self.sockno, self.fileno,
3779 offset, nbytes)
3780 if sent == 0:
3781 break
3782 offset += sent
3783 total_sent += sent
3784 self.assertTrue(sent <= nbytes)
3785
3786 self.client.shutdown(socket.SHUT_RDWR)
3787 self.client.close()
3788 await self.server.wait_closed()
3789 expected = self.DATA[len(self.DATA) // 2:]
3790 self.assertEqual(total_sent, len(expected))
3791 self.assertEqual(len(self.server_buffer), len(expected))
3792 self.assertEqual(self.server_buffer, expected)
3793
3794 async def test_offset_overflow(self):
3795 # specify an offset > file size
3796 offset = len(self.DATA) + 4096
3797 try:
3798 sent = await self.async_sendfile(self.sockno, self.fileno,
3799 offset, 4096)
3800 except OSError as e:
3801 # Solaris can raise EINVAL if offset >= file length, ignore.
3802 if e.errno != errno.EINVAL:
3803 raise
3804 else:
3805 self.assertEqual(sent, 0)
3806 self.client.shutdown(socket.SHUT_RDWR)
3807 self.client.close()
3808 await self.server.wait_closed()
3809 self.assertEqual(self.server_buffer, b'')
3810
3811 async def test_invalid_offset(self):
3812 with self.assertRaises(OSError) as cm:
3813 await self.async_sendfile(self.sockno, self.fileno, -1, 4096)
3814 self.assertEqual(cm.exception.errno, errno.EINVAL)
3815
3816 async def test_keywords(self):
3817 # Keyword arguments should be supported
3818 await self.async_sendfile(out_fd=self.sockno, in_fd=self.fileno,
3819 offset=0, count=4096)
3820 if self.SUPPORT_HEADERS_TRAILERS:
3821 await self.async_sendfile(out_fd=self.sockno, in_fd=self.fileno,
3822 offset=0, count=4096,
3823 headers=(), trailers=(), flags=0)
3824
3825 # --- headers / trailers tests
3826
3827 @requires_headers_trailers
3828 async def test_headers(self):
3829 total_sent = 0
3830 expected_data = b"x" * 512 + b"y" * 256 + self.DATA[:-1]
3831 sent = await self.async_sendfile(self.sockno, self.fileno, 0, 4096,
3832 headers=[b"x" * 512, b"y" * 256])
3833 self.assertLessEqual(sent, 512 + 256 + 4096)
3834 total_sent += sent
3835 offset = 4096
3836 while total_sent < len(expected_data):
3837 nbytes = min(len(expected_data) - total_sent, 4096)
3838 sent = await self.sendfile_wrapper(self.sockno, self.fileno,
3839 offset, nbytes)
3840 if sent == 0:
3841 break
3842 self.assertLessEqual(sent, nbytes)
3843 total_sent += sent
3844 offset += sent
3845
3846 self.assertEqual(total_sent, len(expected_data))
3847 self.client.close()
3848 await self.server.wait_closed()
3849 self.assertEqual(hash(self.server_buffer), hash(expected_data))
3850
3851 @requires_headers_trailers
3852 async def test_trailers(self):
3853 TESTFN2 = os_helper.TESTFN + "2"
3854 file_data = b"abcdef"
3855
3856 self.addCleanup(os_helper.unlink, TESTFN2)
3857 create_file(TESTFN2, file_data)
3858
3859 with open(TESTFN2, 'rb') as f:
3860 await self.async_sendfile(self.sockno, f.fileno(), 0, 5,
3861 trailers=[b"123456", b"789"])
3862 self.client.close()
3863 await self.server.wait_closed()
3864 self.assertEqual(self.server_buffer, b"abcde123456789")
3865
3866 @requires_headers_trailers
3867 @requires_32b
3868 async def test_headers_overflow_32bits(self):
3869 self.server.handler_instance.accumulate = False
3870 with self.assertRaises(OSError) as cm:
3871 await self.async_sendfile(self.sockno, self.fileno, 0, 0,
3872 headers=[b"x" * 2**16] * 2**15)
3873 self.assertEqual(cm.exception.errno, errno.EINVAL)
3874
3875 @requires_headers_trailers
3876 @requires_32b
3877 async def test_trailers_overflow_32bits(self):
3878 self.server.handler_instance.accumulate = False
3879 with self.assertRaises(OSError) as cm:
3880 await self.async_sendfile(self.sockno, self.fileno, 0, 0,
3881 trailers=[b"x" * 2**16] * 2**15)
3882 self.assertEqual(cm.exception.errno, errno.EINVAL)
3883
3884 @requires_headers_trailers
3885 @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
3886 'test needs os.SF_NODISKIO')
3887 async def test_flags(self):
3888 try:
3889 await self.async_sendfile(self.sockno, self.fileno, 0, 4096,
3890 flags=os.SF_NODISKIO)
3891 except OSError as err:
3892 if err.errno not in (errno.EBUSY, errno.EAGAIN):
3893 raise
3894
3895
3896 def supports_extended_attributes():
3897 if not hasattr(os, "setxattr"):
3898 return False
3899
3900 try:
3901 with open(os_helper.TESTFN, "xb", 0) as fp:
3902 try:
3903 os.setxattr(fp.fileno(), b"user.test", b"")
3904 except OSError:
3905 return False
3906 finally:
3907 os_helper.unlink(os_helper.TESTFN)
3908
3909 return True
3910
3911
3912 @unittest.skipUnless(supports_extended_attributes(),
3913 "no non-broken extended attribute support")
3914 # Kernels < 2.6.39 don't respect setxattr flags.
3915 @support.requires_linux_version(2, 6, 39)
3916 class ExtendedAttributeTests(unittest.TestCase):
3917
3918 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
3919 fn = os_helper.TESTFN
3920 self.addCleanup(os_helper.unlink, fn)
3921 create_file(fn)
3922
3923 with self.assertRaises(OSError) as cm:
3924 getxattr(fn, s("user.test"), **kwargs)
3925 self.assertEqual(cm.exception.errno, errno.ENODATA)
3926
3927 init_xattr = listxattr(fn)
3928 self.assertIsInstance(init_xattr, list)
3929
3930 setxattr(fn, s("user.test"), b"", **kwargs)
3931 xattr = set(init_xattr)
3932 xattr.add("user.test")
3933 self.assertEqual(set(listxattr(fn)), xattr)
3934 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
3935 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
3936 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
3937
3938 with self.assertRaises(OSError) as cm:
3939 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
3940 self.assertEqual(cm.exception.errno, errno.EEXIST)
3941
3942 with self.assertRaises(OSError) as cm:
3943 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
3944 self.assertEqual(cm.exception.errno, errno.ENODATA)
3945
3946 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
3947 xattr.add("user.test2")
3948 self.assertEqual(set(listxattr(fn)), xattr)
3949 removexattr(fn, s("user.test"), **kwargs)
3950
3951 with self.assertRaises(OSError) as cm:
3952 getxattr(fn, s("user.test"), **kwargs)
3953 self.assertEqual(cm.exception.errno, errno.ENODATA)
3954
3955 xattr.remove("user.test")
3956 self.assertEqual(set(listxattr(fn)), xattr)
3957 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
3958 setxattr(fn, s("user.test"), b"a"*256, **kwargs)
3959 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*256)
3960 removexattr(fn, s("user.test"), **kwargs)
3961 many = sorted("user.test{}".format(i) for i in range(32))
3962 for thing in many:
3963 setxattr(fn, thing, b"x", **kwargs)
3964 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
3965
3966 def _check_xattrs(self, *args, **kwargs):
3967 self._check_xattrs_str(str, *args, **kwargs)
3968 os_helper.unlink(os_helper.TESTFN)
3969
3970 self._check_xattrs_str(os.fsencode, *args, **kwargs)
3971 os_helper.unlink(os_helper.TESTFN)
3972
3973 def test_simple(self):
3974 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3975 os.listxattr)
3976
3977 def test_lpath(self):
3978 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3979 os.listxattr, follow_symlinks=False)
3980
3981 def test_fds(self):
3982 def getxattr(path, *args):
3983 with open(path, "rb") as fp:
3984 return os.getxattr(fp.fileno(), *args)
3985 def setxattr(path, *args):
3986 with open(path, "wb", 0) as fp:
3987 os.setxattr(fp.fileno(), *args)
3988 def removexattr(path, *args):
3989 with open(path, "wb", 0) as fp:
3990 os.removexattr(fp.fileno(), *args)
3991 def listxattr(path, *args):
3992 with open(path, "rb") as fp:
3993 return os.listxattr(fp.fileno(), *args)
3994 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
3995
3996
3997 @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
3998 class TermsizeTests(unittest.TestCase):
3999 def test_does_not_crash(self):
4000 """Check if get_terminal_size() returns a meaningful value.
4001
4002 There's no easy portable way to actually check the size of the
4003 terminal, so let's check if it returns something sensible instead.
4004 """
4005 try:
4006 size = os.get_terminal_size()
4007 except OSError as e:
4008 known_errnos = [errno.EINVAL, errno.ENOTTY]
4009 if sys.platform == "android":
4010 # The Android testbed redirects the native stdout to a pipe,
4011 # which returns a different error code.
4012 known_errnos.append(errno.EACCES)
4013 if sys.platform == "win32" or e.errno in known_errnos:
4014 # Under win32 a generic OSError can be thrown if the
4015 # handle cannot be retrieved
4016 self.skipTest("failed to query terminal size")
4017 raise
4018
4019 self.assertGreaterEqual(size.columns, 0)
4020 self.assertGreaterEqual(size.lines, 0)
4021
4022 @support.requires_subprocess()
4023 def test_stty_match(self):
4024 """Check if stty returns the same results
4025
4026 stty actually tests stdin, so get_terminal_size is invoked on
4027 stdin explicitly. If stty succeeded, then get_terminal_size()
4028 should work too.
4029 """
4030 try:
4031 size = (
4032 subprocess.check_output(
4033 ["stty", "size"], stderr=subprocess.DEVNULL, text=True
4034 ).split()
4035 )
4036 except (FileNotFoundError, subprocess.CalledProcessError,
4037 PermissionError):
4038 self.skipTest("stty invocation failed")
4039 expected = (int(size[1]), int(size[0])) # reversed order
4040
4041 try:
4042 actual = os.get_terminal_size(sys.__stdin__.fileno())
4043 except OSError as e:
4044 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
4045 # Under win32 a generic OSError can be thrown if the
4046 # handle cannot be retrieved
4047 self.skipTest("failed to query terminal size")
4048 raise
4049 self.assertEqual(expected, actual)
4050
4051 @unittest.skipUnless(sys.platform == 'win32', 'Windows specific test')
4052 def test_windows_fd(self):
4053 """Check if get_terminal_size() returns a meaningful value in Windows"""
4054 try:
4055 conout = open('conout$', 'w')
4056 except OSError:
4057 self.skipTest('failed to open conout$')
4058 with conout:
4059 size = os.get_terminal_size(conout.fileno())
4060
4061 self.assertGreaterEqual(size.columns, 0)
4062 self.assertGreaterEqual(size.lines, 0)
4063
4064
4065 @unittest.skipUnless(hasattr(os, 'memfd_create'), 'requires os.memfd_create')
4066 @support.requires_linux_version(3, 17)
4067 class MemfdCreateTests(unittest.TestCase):
4068 def test_memfd_create(self):
4069 fd = os.memfd_create("Hi", os.MFD_CLOEXEC)
4070 self.assertNotEqual(fd, -1)
4071 self.addCleanup(os.close, fd)
4072 self.assertFalse(os.get_inheritable(fd))
4073 with open(fd, "wb", closefd=False) as f:
4074 f.write(b'memfd_create')
4075 self.assertEqual(f.tell(), 12)
4076
4077 fd2 = os.memfd_create("Hi")
4078 self.addCleanup(os.close, fd2)
4079 self.assertFalse(os.get_inheritable(fd2))
4080
4081
4082 @unittest.skipUnless(hasattr(os, 'eventfd'), 'requires os.eventfd')
4083 @support.requires_linux_version(2, 6, 30)
4084 class EventfdTests(unittest.TestCase):
4085 def test_eventfd_initval(self):
4086 def pack(value):
4087 """Pack as native uint64_t
4088 """
4089 return struct.pack("@Q", value)
4090 size = 8 # read/write 8 bytes
4091 initval = 42
4092 fd = os.eventfd(initval)
4093 self.assertNotEqual(fd, -1)
4094 self.addCleanup(os.close, fd)
4095 self.assertFalse(os.get_inheritable(fd))
4096
4097 # test with raw read/write
4098 res = os.read(fd, size)
4099 self.assertEqual(res, pack(initval))
4100
4101 os.write(fd, pack(23))
4102 res = os.read(fd, size)
4103 self.assertEqual(res, pack(23))
4104
4105 os.write(fd, pack(40))
4106 os.write(fd, pack(2))
4107 res = os.read(fd, size)
4108 self.assertEqual(res, pack(42))
4109
4110 # test with eventfd_read/eventfd_write
4111 os.eventfd_write(fd, 20)
4112 os.eventfd_write(fd, 3)
4113 res = os.eventfd_read(fd)
4114 self.assertEqual(res, 23)
4115
4116 def test_eventfd_semaphore(self):
4117 initval = 2
4118 flags = os.EFD_CLOEXEC | os.EFD_SEMAPHORE | os.EFD_NONBLOCK
4119 fd = os.eventfd(initval, flags)
4120 self.assertNotEqual(fd, -1)
4121 self.addCleanup(os.close, fd)
4122
4123 # semaphore starts has initval 2, two reads return '1'
4124 res = os.eventfd_read(fd)
4125 self.assertEqual(res, 1)
4126 res = os.eventfd_read(fd)
4127 self.assertEqual(res, 1)
4128 # third read would block
4129 with self.assertRaises(BlockingIOError):
4130 os.eventfd_read(fd)
4131 with self.assertRaises(BlockingIOError):
4132 os.read(fd, 8)
4133
4134 # increase semaphore counter, read one
4135 os.eventfd_write(fd, 1)
4136 res = os.eventfd_read(fd)
4137 self.assertEqual(res, 1)
4138 # next read would block, too
4139 with self.assertRaises(BlockingIOError):
4140 os.eventfd_read(fd)
4141
4142 def test_eventfd_select(self):
4143 flags = os.EFD_CLOEXEC | os.EFD_NONBLOCK
4144 fd = os.eventfd(0, flags)
4145 self.assertNotEqual(fd, -1)
4146 self.addCleanup(os.close, fd)
4147
4148 # counter is zero, only writeable
4149 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
4150 self.assertEqual((rfd, wfd, xfd), ([], [fd], []))
4151
4152 # counter is non-zero, read and writeable
4153 os.eventfd_write(fd, 23)
4154 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
4155 self.assertEqual((rfd, wfd, xfd), ([fd], [fd], []))
4156 self.assertEqual(os.eventfd_read(fd), 23)
4157
4158 # counter at max, only readable
4159 os.eventfd_write(fd, (2**64) - 2)
4160 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
4161 self.assertEqual((rfd, wfd, xfd), ([fd], [], []))
4162 os.eventfd_read(fd)
4163
4164 @unittest.skipUnless(hasattr(os, 'timerfd_create'), 'requires os.timerfd_create')
4165 @unittest.skipIf(sys.platform == "android", "gh-124873: Test is flaky on Android")
4166 @support.requires_linux_version(2, 6, 30)
4167 class TimerfdTests(unittest.TestCase):
4168 # gh-126112: Use 10 ms to tolerate slow buildbots
4169 CLOCK_RES_PLACES = 2 # 10 ms
4170 CLOCK_RES = 10 ** -CLOCK_RES_PLACES
4171 CLOCK_RES_NS = 10 ** (9 - CLOCK_RES_PLACES)
4172
4173 def timerfd_create(self, *args, **kwargs):
4174 fd = os.timerfd_create(*args, **kwargs)
4175 self.assertGreaterEqual(fd, 0)
4176 self.assertFalse(os.get_inheritable(fd))
4177 self.addCleanup(os.close, fd)
4178 return fd
4179
4180 def read_count_signaled(self, fd):
4181 # read 8 bytes
4182 data = os.read(fd, 8)
4183 return int.from_bytes(data, byteorder=sys.byteorder)
4184
4185 def test_timerfd_initval(self):
4186 fd = self.timerfd_create(time.CLOCK_REALTIME)
4187
4188 initial_expiration = 0.25
4189 interval = 0.125
4190
4191 # 1st call
4192 next_expiration, interval2 = os.timerfd_settime(fd, initial=initial_expiration, interval=interval)
4193 self.assertAlmostEqual(interval2, 0.0, places=self.CLOCK_RES_PLACES)
4194 self.assertAlmostEqual(next_expiration, 0.0, places=self.CLOCK_RES_PLACES)
4195
4196 # 2nd call
4197 next_expiration, interval2 = os.timerfd_settime(fd, initial=initial_expiration, interval=interval)
4198 self.assertAlmostEqual(interval2, interval, places=self.CLOCK_RES_PLACES)
4199 self.assertAlmostEqual(next_expiration, initial_expiration, places=self.CLOCK_RES_PLACES)
4200
4201 # timerfd_gettime
4202 next_expiration, interval2 = os.timerfd_gettime(fd)
4203 self.assertAlmostEqual(interval2, interval, places=self.CLOCK_RES_PLACES)
4204 self.assertAlmostEqual(next_expiration, initial_expiration, places=self.CLOCK_RES_PLACES)
4205
4206 def test_timerfd_non_blocking(self):
4207 fd = self.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)
4208
4209 # 0.1 second later
4210 initial_expiration = 0.1
4211 os.timerfd_settime(fd, initial=initial_expiration, interval=0)
4212
4213 # read() raises OSError with errno is EAGAIN for non-blocking timer.
4214 with self.assertRaises(OSError) as ctx:
4215 self.read_count_signaled(fd)
4216 self.assertEqual(ctx.exception.errno, errno.EAGAIN)
4217
4218 # Wait more than 0.1 seconds
4219 time.sleep(initial_expiration + 0.1)
4220
4221 # confirm if timerfd is readable and read() returns 1 as bytes.
4222 self.assertEqual(self.read_count_signaled(fd), 1)
4223
4224 @unittest.skipIf(sys.platform.startswith('netbsd'),
4225 "gh-131263: Skip on NetBSD due to system freeze "
4226 "with negative timer values")
4227 def test_timerfd_negative(self):
4228 one_sec_in_nsec = 10**9
4229 fd = self.timerfd_create(time.CLOCK_REALTIME)
4230
4231 test_flags = [0, os.TFD_TIMER_ABSTIME]
4232 if hasattr(os, 'TFD_TIMER_CANCEL_ON_SET'):
4233 test_flags.append(os.TFD_TIMER_ABSTIME | os.TFD_TIMER_CANCEL_ON_SET)
4234
4235 # Any of 'initial' and 'interval' is negative value.
4236 for initial, interval in ( (-1, 0), (1, -1), (-1, -1), (-0.1, 0), (1, -0.1), (-0.1, -0.1)):
4237 for flags in test_flags:
4238 with self.subTest(flags=flags, initial=initial, interval=interval):
4239 with self.assertRaises(OSError) as context:
4240 os.timerfd_settime(fd, flags=flags, initial=initial, interval=interval)
4241 self.assertEqual(context.exception.errno, errno.EINVAL)
4242
4243 with self.assertRaises(OSError) as context:
4244 initial_ns = int( one_sec_in_nsec * initial )
4245 interval_ns = int( one_sec_in_nsec * interval )
4246 os.timerfd_settime_ns(fd, flags=flags, initial=initial_ns, interval=interval_ns)
4247 self.assertEqual(context.exception.errno, errno.EINVAL)
4248
4249 def test_timerfd_interval(self):
4250 fd = self.timerfd_create(time.CLOCK_REALTIME)
4251
4252 # 1 second
4253 initial_expiration = 1
4254 # 0.5 second
4255 interval = 0.5
4256
4257 os.timerfd_settime(fd, initial=initial_expiration, interval=interval)
4258
4259 # timerfd_gettime
4260 next_expiration, interval2 = os.timerfd_gettime(fd)
4261 self.assertAlmostEqual(interval2, interval, places=self.CLOCK_RES_PLACES)
4262 self.assertAlmostEqual(next_expiration, initial_expiration, places=self.CLOCK_RES_PLACES)
4263
4264 count = 3
4265 t = time.perf_counter()
4266 for _ in range(count):
4267 self.assertEqual(self.read_count_signaled(fd), 1)
4268 t = time.perf_counter() - t
4269
4270 total_time = initial_expiration + interval * (count - 1)
4271 self.assertGreater(t, total_time - self.CLOCK_RES)
4272
4273 # wait 3.5 time of interval
4274 time.sleep( (count+0.5) * interval)
4275 self.assertEqual(self.read_count_signaled(fd), count)
4276
4277 def test_timerfd_TFD_TIMER_ABSTIME(self):
4278 fd = self.timerfd_create(time.CLOCK_REALTIME)
4279
4280 now = time.clock_gettime(time.CLOCK_REALTIME)
4281
4282 # 1 second later from now.
4283 offset = 1
4284 initial_expiration = now + offset
4285 # not interval timer
4286 interval = 0
4287
4288 os.timerfd_settime(fd, flags=os.TFD_TIMER_ABSTIME, initial=initial_expiration, interval=interval)
4289
4290 # timerfd_gettime
4291 # Note: timerfd_gettime returns relative values even if TFD_TIMER_ABSTIME is specified.
4292 next_expiration, interval2 = os.timerfd_gettime(fd)
4293 self.assertAlmostEqual(interval2, interval, places=self.CLOCK_RES_PLACES)
4294 self.assertAlmostEqual(next_expiration, offset, places=self.CLOCK_RES_PLACES)
4295
4296 t = time.perf_counter()
4297 count_signaled = self.read_count_signaled(fd)
4298 t = time.perf_counter() - t
4299 self.assertEqual(count_signaled, 1)
4300
4301 self.assertGreater(t, offset - self.CLOCK_RES)
4302
4303 def test_timerfd_select(self):
4304 fd = self.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)
4305
4306 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
4307 self.assertEqual((rfd, wfd, xfd), ([], [], []))
4308
4309 # 0.25 second
4310 initial_expiration = 0.25
4311 # every 0.125 second
4312 interval = 0.125
4313
4314 os.timerfd_settime(fd, initial=initial_expiration, interval=interval)
4315
4316 count = 3
4317 t = time.perf_counter()
4318 for _ in range(count):
4319 rfd, wfd, xfd = select.select([fd], [fd], [fd], initial_expiration + interval)
4320 self.assertEqual((rfd, wfd, xfd), ([fd], [], []))
4321 self.assertEqual(self.read_count_signaled(fd), 1)
4322 t = time.perf_counter() - t
4323
4324 total_time = initial_expiration + interval * (count - 1)
4325 self.assertGreater(t, total_time - self.CLOCK_RES)
4326
4327 def check_timerfd_poll(self, nanoseconds):
4328 fd = self.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)
4329
4330 selector = selectors.DefaultSelector()
4331 selector.register(fd, selectors.EVENT_READ)
4332 self.addCleanup(selector.close)
4333
4334 sec_to_nsec = 10 ** 9
4335 # 0.25 second
4336 initial_expiration_ns = sec_to_nsec // 4
4337 # every 0.125 second
4338 interval_ns = sec_to_nsec // 8
4339
4340 if nanoseconds:
4341 os.timerfd_settime_ns(fd,
4342 initial=initial_expiration_ns,
4343 interval=interval_ns)
4344 else:
4345 os.timerfd_settime(fd,
4346 initial=initial_expiration_ns / sec_to_nsec,
4347 interval=interval_ns / sec_to_nsec)
4348
4349 count = 3
4350 if nanoseconds:
4351 t = time.perf_counter_ns()
4352 else:
4353 t = time.perf_counter()
4354 for i in range(count):
4355 timeout_margin_ns = interval_ns
4356 if i == 0:
4357 timeout_ns = initial_expiration_ns + interval_ns + timeout_margin_ns
4358 else:
4359 timeout_ns = interval_ns + timeout_margin_ns
4360
4361 ready = selector.select(timeout_ns / sec_to_nsec)
4362 self.assertEqual(len(ready), 1, ready)
4363 event = ready[0][1]
4364 self.assertEqual(event, selectors.EVENT_READ)
4365
4366 self.assertEqual(self.read_count_signaled(fd), 1)
4367
4368 total_time = initial_expiration_ns + interval_ns * (count - 1)
4369 if nanoseconds:
4370 dt = time.perf_counter_ns() - t
4371 self.assertGreater(dt, total_time - self.CLOCK_RES_NS)
4372 else:
4373 dt = time.perf_counter() - t
4374 self.assertGreater(dt, total_time / sec_to_nsec - self.CLOCK_RES)
4375 selector.unregister(fd)
4376
4377 def test_timerfd_poll(self):
4378 self.check_timerfd_poll(False)
4379
4380 def test_timerfd_ns_poll(self):
4381 self.check_timerfd_poll(True)
4382
4383 def test_timerfd_ns_initval(self):
4384 one_sec_in_nsec = 10**9
4385 limit_error = one_sec_in_nsec // 10**3
4386 fd = self.timerfd_create(time.CLOCK_REALTIME)
4387
4388 # 1st call
4389 initial_expiration_ns = 0
4390 interval_ns = one_sec_in_nsec // 1000
4391 next_expiration_ns, interval_ns2 = os.timerfd_settime_ns(fd, initial=initial_expiration_ns, interval=interval_ns)
4392 self.assertEqual(interval_ns2, 0)
4393 self.assertEqual(next_expiration_ns, 0)
4394
4395 # 2nd call
4396 next_expiration_ns, interval_ns2 = os.timerfd_settime_ns(fd, initial=initial_expiration_ns, interval=interval_ns)
4397 self.assertEqual(interval_ns2, interval_ns)
4398 self.assertEqual(next_expiration_ns, initial_expiration_ns)
4399
4400 # timerfd_gettime
4401 next_expiration_ns, interval_ns2 = os.timerfd_gettime_ns(fd)
4402 self.assertEqual(interval_ns2, interval_ns)
4403 self.assertLessEqual(next_expiration_ns, initial_expiration_ns)
4404
4405 self.assertAlmostEqual(next_expiration_ns, initial_expiration_ns, delta=limit_error)
4406
4407 def test_timerfd_ns_interval(self):
4408 one_sec_in_nsec = 10**9
4409 limit_error = one_sec_in_nsec // 10**3
4410 fd = self.timerfd_create(time.CLOCK_REALTIME)
4411
4412 # 1 second
4413 initial_expiration_ns = one_sec_in_nsec
4414 # every 0.5 second
4415 interval_ns = one_sec_in_nsec // 2
4416
4417 os.timerfd_settime_ns(fd, initial=initial_expiration_ns, interval=interval_ns)
4418
4419 # timerfd_gettime
4420 next_expiration_ns, interval_ns2 = os.timerfd_gettime_ns(fd)
4421 self.assertEqual(interval_ns2, interval_ns)
4422 self.assertLessEqual(next_expiration_ns, initial_expiration_ns)
4423
4424 count = 3
4425 t = time.perf_counter_ns()
4426 for _ in range(count):
4427 self.assertEqual(self.read_count_signaled(fd), 1)
4428 t = time.perf_counter_ns() - t
4429
4430 total_time_ns = initial_expiration_ns + interval_ns * (count - 1)
4431 self.assertGreater(t, total_time_ns - self.CLOCK_RES_NS)
4432
4433 # wait 3.5 time of interval
4434 time.sleep( (count+0.5) * interval_ns / one_sec_in_nsec)
4435 self.assertEqual(self.read_count_signaled(fd), count)
4436
4437
4438 def test_timerfd_ns_TFD_TIMER_ABSTIME(self):
4439 one_sec_in_nsec = 10**9
4440 limit_error = one_sec_in_nsec // 10**3
4441 fd = self.timerfd_create(time.CLOCK_REALTIME)
4442
4443 now_ns = time.clock_gettime_ns(time.CLOCK_REALTIME)
4444
4445 # 1 second later from now.
4446 offset_ns = one_sec_in_nsec
4447 initial_expiration_ns = now_ns + offset_ns
4448 # not interval timer
4449 interval_ns = 0
4450
4451 os.timerfd_settime_ns(fd, flags=os.TFD_TIMER_ABSTIME, initial=initial_expiration_ns, interval=interval_ns)
4452
4453 # timerfd_gettime
4454 # Note: timerfd_gettime returns relative values even if TFD_TIMER_ABSTIME is specified.
4455 next_expiration_ns, interval_ns2 = os.timerfd_gettime_ns(fd)
4456 self.assertLess(abs(interval_ns2 - interval_ns), limit_error)
4457 self.assertLess(abs(next_expiration_ns - offset_ns), limit_error)
4458
4459 t = time.perf_counter_ns()
4460 count_signaled = self.read_count_signaled(fd)
4461 t = time.perf_counter_ns() - t
4462 self.assertEqual(count_signaled, 1)
4463
4464 self.assertGreater(t, offset_ns - self.CLOCK_RES_NS)
4465
4466 def test_timerfd_ns_select(self):
4467 one_sec_in_nsec = 10**9
4468
4469 fd = self.timerfd_create(time.CLOCK_REALTIME, flags=os.TFD_NONBLOCK)
4470
4471 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
4472 self.assertEqual((rfd, wfd, xfd), ([], [], []))
4473
4474 # 0.25 second
4475 initial_expiration_ns = one_sec_in_nsec // 4
4476 # every 0.125 second
4477 interval_ns = one_sec_in_nsec // 8
4478
4479 os.timerfd_settime_ns(fd, initial=initial_expiration_ns, interval=interval_ns)
4480
4481 count = 3
4482 t = time.perf_counter_ns()
4483 for _ in range(count):
4484 rfd, wfd, xfd = select.select([fd], [fd], [fd], (initial_expiration_ns + interval_ns) / 1e9 )
4485 self.assertEqual((rfd, wfd, xfd), ([fd], [], []))
4486 self.assertEqual(self.read_count_signaled(fd), 1)
4487 t = time.perf_counter_ns() - t
4488
4489 total_time_ns = initial_expiration_ns + interval_ns * (count - 1)
4490 self.assertGreater(t, total_time_ns - self.CLOCK_RES_NS)
4491
4492 class OSErrorTests(unittest.TestCase):
4493 def setUp(self):
4494 class Str(str):
4495 pass
4496
4497 self.bytes_filenames = []
4498 self.unicode_filenames = []
4499 if os_helper.TESTFN_UNENCODABLE is not None:
4500 decoded = os_helper.TESTFN_UNENCODABLE
4501 else:
4502 decoded = os_helper.TESTFN
4503 self.unicode_filenames.append(decoded)
4504 self.unicode_filenames.append(Str(decoded))
4505 if os_helper.TESTFN_UNDECODABLE is not None:
4506 encoded = os_helper.TESTFN_UNDECODABLE
4507 else:
4508 encoded = os.fsencode(os_helper.TESTFN)
4509 self.bytes_filenames.append(encoded)
4510
4511 self.filenames = self.bytes_filenames + self.unicode_filenames
4512
4513 def test_oserror_filename(self):
4514 funcs = [
4515 (self.filenames, os.chdir,),
4516 (self.filenames, os.lstat,),
4517 (self.filenames, os.open, os.O_RDONLY),
4518 (self.filenames, os.rmdir,),
4519 (self.filenames, os.stat,),
4520 (self.filenames, os.unlink,),
4521 (self.filenames, os.listdir,),
4522 (self.filenames, os.rename, "dst"),
4523 (self.filenames, os.replace, "dst"),
4524 ]
4525 if os_helper.can_chmod():
4526 funcs.append((self.filenames, os.chmod, 0o777))
4527 if hasattr(os, "chown"):
4528 funcs.append((self.filenames, os.chown, 0, 0))
4529 if hasattr(os, "lchown"):
4530 funcs.append((self.filenames, os.lchown, 0, 0))
4531 if hasattr(os, "truncate"):
4532 funcs.append((self.filenames, os.truncate, 0))
4533 if hasattr(os, "chflags"):
4534 funcs.append((self.filenames, os.chflags, 0))
4535 if hasattr(os, "lchflags"):
4536 funcs.append((self.filenames, os.lchflags, 0))
4537 if hasattr(os, "chroot"):
4538 funcs.append((self.filenames, os.chroot,))
4539 if hasattr(os, "link"):
4540 funcs.append((self.filenames, os.link, "dst"))
4541 if hasattr(os, "listxattr"):
4542 funcs.extend((
4543 (self.filenames, os.listxattr,),
4544 (self.filenames, os.getxattr, "user.test"),
4545 (self.filenames, os.setxattr, "user.test", b'user'),
4546 (self.filenames, os.removexattr, "user.test"),
4547 ))
4548 if hasattr(os, "lchmod"):
4549 funcs.append((self.filenames, os.lchmod, 0o777))
4550 if hasattr(os, "readlink"):
4551 funcs.append((self.filenames, os.readlink,))
4552
4553 for filenames, func, *func_args in funcs:
4554 for name in filenames:
4555 try:
4556 func(name, *func_args)
4557 except OSError as err:
4558 self.assertIs(err.filename, name, str(func))
4559 except UnicodeDecodeError:
4560 pass
4561 else:
4562 self.fail(f"No exception thrown by {func}")
4563
4564 class CPUCountTests(unittest.TestCase):
4565 def check_cpu_count(self, cpus):
4566 if cpus is None:
4567 self.skipTest("Could not determine the number of CPUs")
4568
4569 self.assertIsInstance(cpus, int)
4570 self.assertGreater(cpus, 0)
4571
4572 def test_cpu_count(self):
4573 cpus = os.cpu_count()
4574 self.check_cpu_count(cpus)
4575
4576 def test_process_cpu_count(self):
4577 cpus = os.process_cpu_count()
4578 self.assertLessEqual(cpus, os.cpu_count())
4579 self.check_cpu_count(cpus)
4580
4581 @unittest.skipUnless(hasattr(os, 'sched_setaffinity'),
4582 "don't have sched affinity support")
4583 def test_process_cpu_count_affinity(self):
4584 affinity1 = os.process_cpu_count()
4585 if affinity1 is None:
4586 self.skipTest("Could not determine the number of CPUs")
4587
4588 # Disable one CPU
4589 mask = os.sched_getaffinity(0)
4590 if len(mask) <= 1:
4591 self.skipTest(f"sched_getaffinity() returns less than "
4592 f"2 CPUs: {sorted(mask)}")
4593 self.addCleanup(os.sched_setaffinity, 0, list(mask))
4594 mask.pop()
4595 os.sched_setaffinity(0, mask)
4596
4597 # test process_cpu_count()
4598 affinity2 = os.process_cpu_count()
4599 self.assertEqual(affinity2, affinity1 - 1)
4600
4601
4602 # FD inheritance check is only useful for systems with process support.
4603 @support.requires_subprocess()
4604 class FDInheritanceTests(unittest.TestCase):
4605 def test_get_set_inheritable(self):
4606 fd = os.open(__file__, os.O_RDONLY)
4607 self.addCleanup(os.close, fd)
4608 self.assertEqual(os.get_inheritable(fd), False)
4609
4610 os.set_inheritable(fd, True)
4611 self.assertEqual(os.get_inheritable(fd), True)
4612
4613 @unittest.skipIf(fcntl is None, "need fcntl")
4614 def test_get_inheritable_cloexec(self):
4615 fd = os.open(__file__, os.O_RDONLY)
4616 self.addCleanup(os.close, fd)
4617 self.assertEqual(os.get_inheritable(fd), False)
4618
4619 # clear FD_CLOEXEC flag
4620 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
4621 flags &= ~fcntl.FD_CLOEXEC
4622 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
4623
4624 self.assertEqual(os.get_inheritable(fd), True)
4625
4626 @unittest.skipIf(fcntl is None, "need fcntl")
4627 def test_set_inheritable_cloexec(self):
4628 fd = os.open(__file__, os.O_RDONLY)
4629 self.addCleanup(os.close, fd)
4630 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4631 fcntl.FD_CLOEXEC)
4632
4633 os.set_inheritable(fd, True)
4634 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4635 0)
4636
4637 @unittest.skipUnless(hasattr(os, 'O_PATH'), "need os.O_PATH")
4638 def test_get_set_inheritable_o_path(self):
4639 fd = os.open(__file__, os.O_PATH)
4640 self.addCleanup(os.close, fd)
4641 self.assertEqual(os.get_inheritable(fd), False)
4642
4643 os.set_inheritable(fd, True)
4644 self.assertEqual(os.get_inheritable(fd), True)
4645
4646 os.set_inheritable(fd, False)
4647 self.assertEqual(os.get_inheritable(fd), False)
4648
4649 def test_get_set_inheritable_badf(self):
4650 fd = os_helper.make_bad_fd()
4651
4652 with self.assertRaises(OSError) as ctx:
4653 os.get_inheritable(fd)
4654 self.assertEqual(ctx.exception.errno, errno.EBADF)
4655
4656 with self.assertRaises(OSError) as ctx:
4657 os.set_inheritable(fd, True)
4658 self.assertEqual(ctx.exception.errno, errno.EBADF)
4659
4660 with self.assertRaises(OSError) as ctx:
4661 os.set_inheritable(fd, False)
4662 self.assertEqual(ctx.exception.errno, errno.EBADF)
4663
4664 def test_open(self):
4665 fd = os.open(__file__, os.O_RDONLY)
4666 self.addCleanup(os.close, fd)
4667 self.assertEqual(os.get_inheritable(fd), False)
4668
4669 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
4670 def test_pipe(self):
4671 rfd, wfd = os.pipe()
4672 self.addCleanup(os.close, rfd)
4673 self.addCleanup(os.close, wfd)
4674 self.assertEqual(os.get_inheritable(rfd), False)
4675 self.assertEqual(os.get_inheritable(wfd), False)
4676
4677 def test_dup(self):
4678 fd1 = os.open(__file__, os.O_RDONLY)
4679 self.addCleanup(os.close, fd1)
4680
4681 fd2 = os.dup(fd1)
4682 self.addCleanup(os.close, fd2)
4683 self.assertEqual(os.get_inheritable(fd2), False)
4684
4685 def test_dup_standard_stream(self):
4686 fd = os.dup(1)
4687 self.addCleanup(os.close, fd)
4688 self.assertGreater(fd, 0)
4689
4690 @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
4691 def test_dup_nul(self):
4692 # os.dup() was creating inheritable fds for character files.
4693 fd1 = os.open('NUL', os.O_RDONLY)
4694 self.addCleanup(os.close, fd1)
4695 fd2 = os.dup(fd1)
4696 self.addCleanup(os.close, fd2)
4697 self.assertFalse(os.get_inheritable(fd2))
4698
4699 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
4700 def test_dup2(self):
4701 fd = os.open(__file__, os.O_RDONLY)
4702 self.addCleanup(os.close, fd)
4703
4704 # inheritable by default
4705 fd2 = os.open(__file__, os.O_RDONLY)
4706 self.addCleanup(os.close, fd2)
4707 self.assertEqual(os.dup2(fd, fd2), fd2)
4708 self.assertTrue(os.get_inheritable(fd2))
4709
4710 # force non-inheritable
4711 fd3 = os.open(__file__, os.O_RDONLY)
4712 self.addCleanup(os.close, fd3)
4713 self.assertEqual(os.dup2(fd, fd3, inheritable=False), fd3)
4714 self.assertFalse(os.get_inheritable(fd3))
4715
4716 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
4717 class PseudoterminalTests(unittest.TestCase):
4718 def open_pty(self):
4719 """Open a pty fd-pair, and schedule cleanup for it"""
4720 main_fd, second_fd = os.openpty()
4721 self.addCleanup(os.close, main_fd)
4722 self.addCleanup(os.close, second_fd)
4723 return main_fd, second_fd
4724
4725 def test_openpty(self):
4726 main_fd, second_fd = self.open_pty()
4727 self.assertEqual(os.get_inheritable(main_fd), False)
4728 self.assertEqual(os.get_inheritable(second_fd), False)
4729
4730 @unittest.skipUnless(hasattr(os, 'ptsname'), "need os.ptsname()")
4731 @unittest.skipUnless(hasattr(os, 'O_RDWR'), "need os.O_RDWR")
4732 @unittest.skipUnless(hasattr(os, 'O_NOCTTY'), "need os.O_NOCTTY")
4733 def test_open_via_ptsname(self):
4734 main_fd, second_fd = self.open_pty()
4735 second_path = os.ptsname(main_fd)
4736 reopened_second_fd = os.open(second_path, os.O_RDWR|os.O_NOCTTY)
4737 self.addCleanup(os.close, reopened_second_fd)
4738 os.write(reopened_second_fd, b'foo')
4739 self.assertEqual(os.read(main_fd, 3), b'foo')
4740
4741 @unittest.skipUnless(hasattr(os, 'posix_openpt'), "need os.posix_openpt()")
4742 @unittest.skipUnless(hasattr(os, 'grantpt'), "need os.grantpt()")
4743 @unittest.skipUnless(hasattr(os, 'unlockpt'), "need os.unlockpt()")
4744 @unittest.skipUnless(hasattr(os, 'ptsname'), "need os.ptsname()")
4745 @unittest.skipUnless(hasattr(os, 'O_RDWR'), "need os.O_RDWR")
4746 @unittest.skipUnless(hasattr(os, 'O_NOCTTY'), "need os.O_NOCTTY")
4747 def test_posix_pty_functions(self):
4748 mother_fd = os.posix_openpt(os.O_RDWR|os.O_NOCTTY)
4749 self.addCleanup(os.close, mother_fd)
4750 os.grantpt(mother_fd)
4751 os.unlockpt(mother_fd)
4752 son_path = os.ptsname(mother_fd)
4753 son_fd = os.open(son_path, os.O_RDWR|os.O_NOCTTY)
4754 self.addCleanup(os.close, son_fd)
4755 self.assertEqual(os.ptsname(mother_fd), os.ttyname(son_fd))
4756
4757 @unittest.skipUnless(hasattr(os, 'spawnl'), "need os.spawnl()")
4758 @support.requires_subprocess()
4759 def test_pipe_spawnl(self):
4760 # gh-77046: On Windows, os.pipe() file descriptors must be created with
4761 # _O_NOINHERIT to make them non-inheritable. UCRT has no public API to
4762 # get (_osfile(fd) & _O_NOINHERIT), so use a functional test.
4763 #
4764 # Make sure that fd is not inherited by a child process created by
4765 # os.spawnl(): get_osfhandle() and dup() must fail with EBADF.
4766
4767 fd, fd2 = os.pipe()
4768 self.addCleanup(os.close, fd)
4769 self.addCleanup(os.close, fd2)
4770
4771 code = textwrap.dedent(f"""
4772 import errno
4773 import os
4774 import test.support
4775 try:
4776 import msvcrt
4777 except ImportError:
4778 msvcrt = None
4779
4780 fd = {fd}
4781
4782 with test.support.SuppressCrashReport():
4783 if msvcrt is not None:
4784 try:
4785 handle = msvcrt.get_osfhandle(fd)
4786 except OSError as exc:
4787 if exc.errno != errno.EBADF:
4788 raise
4789 # get_osfhandle(fd) failed with EBADF as expected
4790 else:
4791 raise Exception("get_osfhandle() must fail")
4792
4793 try:
4794 fd3 = os.dup(fd)
4795 except OSError as exc:
4796 if exc.errno != errno.EBADF:
4797 raise
4798 # os.dup(fd) failed with EBADF as expected
4799 else:
4800 os.close(fd3)
4801 raise Exception("dup must fail")
4802 """)
4803
4804 filename = os_helper.TESTFN
4805 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
4806 with open(filename, "w") as fp:
4807 print(code, file=fp, end="")
4808
4809 executable = sys.executable
4810 cmd = [executable, filename]
4811 if os.name == "nt" and " " in cmd[0]:
4812 cmd[0] = f'"{cmd[0]}"'
4813 exitcode = os.spawnl(os.P_WAIT, executable, *cmd)
4814 self.assertEqual(exitcode, 0)
4815
4816
4817 class PathTConverterTests(unittest.TestCase):
4818 # tuples of (function name, allows fd arguments, additional arguments to
4819 # function, cleanup function)
4820 functions = [
4821 ('stat', True, (), None),
4822 ('lstat', False, (), None),
4823 ('access', False, (os.F_OK,), None),
4824 ('chflags', False, (0,), None),
4825 ('lchflags', False, (0,), None),
4826 ('open', False, (os.O_RDONLY,), getattr(os, 'close', None)),
4827 ]
4828
4829 def test_path_t_converter(self):
4830 str_filename = os_helper.TESTFN
4831 if os.name == 'nt':
4832 bytes_fspath = bytes_filename = None
4833 else:
4834 bytes_filename = os.fsencode(os_helper.TESTFN)
4835 bytes_fspath = FakePath(bytes_filename)
4836 fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT)
4837 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
4838 self.addCleanup(os.close, fd)
4839
4840 int_fspath = FakePath(fd)
4841 str_fspath = FakePath(str_filename)
4842
4843 for name, allow_fd, extra_args, cleanup_fn in self.functions:
4844 with self.subTest(name=name):
4845 try:
4846 fn = getattr(os, name)
4847 except AttributeError:
4848 continue
4849
4850 for path in (str_filename, bytes_filename, str_fspath,
4851 bytes_fspath):
4852 if path is None:
4853 continue
4854 with self.subTest(name=name, path=path):
4855 result = fn(path, *extra_args)
4856 if cleanup_fn is not None:
4857 cleanup_fn(result)
4858
4859 with self.assertRaisesRegex(
4860 TypeError, 'to return str or bytes'):
4861 fn(int_fspath, *extra_args)
4862
4863 if allow_fd:
4864 result = fn(fd, *extra_args) # should not fail
4865 if cleanup_fn is not None:
4866 cleanup_fn(result)
4867 else:
4868 with self.assertRaisesRegex(
4869 TypeError,
4870 'os.PathLike'):
4871 fn(fd, *extra_args)
4872
4873 def test_path_t_converter_and_custom_class(self):
4874 msg = r'__fspath__\(\) to return str or bytes, not %s'
4875 with self.assertRaisesRegex(TypeError, msg % r'int'):
4876 os.stat(FakePath(2))
4877 with self.assertRaisesRegex(TypeError, msg % r'float'):
4878 os.stat(FakePath(2.34))
4879 with self.assertRaisesRegex(TypeError, msg % r'object'):
4880 os.stat(FakePath(object()))
4881
4882
4883 @unittest.skipUnless(hasattr(os, 'get_blocking'),
4884 'needs os.get_blocking() and os.set_blocking()')
4885 @unittest.skipIf(support.is_emscripten, "Cannot unset blocking flag")
4886 @unittest.skipIf(sys.platform == 'win32', 'Windows only supports blocking on pipes')
4887 class BlockingTests(unittest.TestCase):
4888 def test_blocking(self):
4889 fd = os.open(__file__, os.O_RDONLY)
4890 self.addCleanup(os.close, fd)
4891 self.assertEqual(os.get_blocking(fd), True)
4892
4893 os.set_blocking(fd, False)
4894 self.assertEqual(os.get_blocking(fd), False)
4895
4896 os.set_blocking(fd, True)
4897 self.assertEqual(os.get_blocking(fd), True)
4898
4899
4900
4901 class ExportsTests(unittest.TestCase):
4902 def test_os_all(self):
4903 self.assertIn('open', os.__all__)
4904 self.assertIn('walk', os.__all__)
4905
4906
4907 class TestDirEntry(unittest.TestCase):
4908 def setUp(self):
4909 self.path = os.path.realpath(os_helper.TESTFN)
4910 self.addCleanup(os_helper.rmtree, self.path)
4911 os.mkdir(self.path)
4912
4913 def test_uninstantiable(self):
4914 self.assertRaises(TypeError, os.DirEntry)
4915
4916 def test_unpickable(self):
4917 filename = create_file(os.path.join(self.path, "file.txt"), b'python')
4918 entry = [entry for entry in os.scandir(self.path)].pop()
4919 self.assertIsInstance(entry, os.DirEntry)
4920 self.assertEqual(entry.name, "file.txt")
4921 import pickle
4922 self.assertRaises(TypeError, pickle.dumps, entry, filename)
4923
4924
4925 class TestScandir(unittest.TestCase):
4926 check_no_resource_warning = warnings_helper.check_no_resource_warning
4927
4928 def setUp(self):
4929 self.path = os.path.realpath(os_helper.TESTFN)
4930 self.bytes_path = os.fsencode(self.path)
4931 self.addCleanup(os_helper.rmtree, self.path)
4932 os.mkdir(self.path)
4933
4934 def create_file(self, name="file.txt"):
4935 path = self.bytes_path if isinstance(name, bytes) else self.path
4936 filename = os.path.join(path, name)
4937 create_file(filename, b'python')
4938 return filename
4939
4940 def get_entries(self, names):
4941 entries = dict((entry.name, entry)
4942 for entry in os.scandir(self.path))
4943 self.assertEqual(sorted(entries.keys()), names)
4944 return entries
4945
4946 def assert_stat_equal(self, stat1, stat2, skip_fields):
4947 if skip_fields:
4948 for attr in dir(stat1):
4949 if not attr.startswith("st_"):
4950 continue
4951 if attr in ("st_dev", "st_ino", "st_nlink", "st_ctime",
4952 "st_ctime_ns"):
4953 continue
4954 self.assertEqual(getattr(stat1, attr),
4955 getattr(stat2, attr),
4956 (stat1, stat2, attr))
4957 else:
4958 self.assertEqual(stat1, stat2)
4959
4960 def test_uninstantiable(self):
4961 scandir_iter = os.scandir(self.path)
4962 self.assertRaises(TypeError, type(scandir_iter))
4963 scandir_iter.close()
4964
4965 def test_unpickable(self):
4966 filename = self.create_file("file.txt")
4967 scandir_iter = os.scandir(self.path)
4968 import pickle
4969 self.assertRaises(TypeError, pickle.dumps, scandir_iter, filename)
4970 scandir_iter.close()
4971
4972 def check_entry(self, entry, name, is_dir, is_file, is_symlink):
4973 self.assertIsInstance(entry, os.DirEntry)
4974 self.assertEqual(entry.name, name)
4975 self.assertEqual(entry.path, os.path.join(self.path, name))
4976 self.assertEqual(entry.inode(),
4977 os.stat(entry.path, follow_symlinks=False).st_ino)
4978
4979 entry_stat = os.stat(entry.path)
4980 self.assertEqual(entry.is_dir(),
4981 stat.S_ISDIR(entry_stat.st_mode))
4982 self.assertEqual(entry.is_file(),
4983 stat.S_ISREG(entry_stat.st_mode))
4984 self.assertEqual(entry.is_symlink(),
4985 os.path.islink(entry.path))
4986
4987 entry_lstat = os.stat(entry.path, follow_symlinks=False)
4988 self.assertEqual(entry.is_dir(follow_symlinks=False),
4989 stat.S_ISDIR(entry_lstat.st_mode))
4990 self.assertEqual(entry.is_file(follow_symlinks=False),
4991 stat.S_ISREG(entry_lstat.st_mode))
4992
4993 self.assertEqual(entry.is_junction(), os.path.isjunction(entry.path))
4994
4995 self.assert_stat_equal(entry.stat(),
4996 entry_stat,
4997 os.name == 'nt' and not is_symlink)
4998 self.assert_stat_equal(entry.stat(follow_symlinks=False),
4999 entry_lstat,
5000 os.name == 'nt')
5001
5002 def test_attributes(self):
5003 link = os_helper.can_hardlink()
5004 symlink = os_helper.can_symlink()
5005
5006 dirname = os.path.join(self.path, "dir")
5007 os.mkdir(dirname)
5008 filename = self.create_file("file.txt")
5009 if link:
5010 try:
5011 os.link(filename, os.path.join(self.path, "link_file.txt"))
5012 except PermissionError as e:
5013 self.skipTest('os.link(): %s' % e)
5014 if symlink:
5015 os.symlink(dirname, os.path.join(self.path, "symlink_dir"),
5016 target_is_directory=True)
5017 os.symlink(filename, os.path.join(self.path, "symlink_file.txt"))
5018
5019 names = ['dir', 'file.txt']
5020 if link:
5021 names.append('link_file.txt')
5022 if symlink:
5023 names.extend(('symlink_dir', 'symlink_file.txt'))
5024 entries = self.get_entries(names)
5025
5026 entry = entries['dir']
5027 self.check_entry(entry, 'dir', True, False, False)
5028
5029 entry = entries['file.txt']
5030 self.check_entry(entry, 'file.txt', False, True, False)
5031
5032 if link:
5033 entry = entries['link_file.txt']
5034 self.check_entry(entry, 'link_file.txt', False, True, False)
5035
5036 if symlink:
5037 entry = entries['symlink_dir']
5038 self.check_entry(entry, 'symlink_dir', True, False, True)
5039
5040 entry = entries['symlink_file.txt']
5041 self.check_entry(entry, 'symlink_file.txt', False, True, True)
5042
5043 @unittest.skipIf(sys.platform != 'win32', "Can only test junctions with creation on win32.")
5044 def test_attributes_junctions(self):
5045 dirname = os.path.join(self.path, "tgtdir")
5046 os.mkdir(dirname)
5047
5048 import _winapi
5049 try:
5050 _winapi.CreateJunction(dirname, os.path.join(self.path, "srcjunc"))
5051 except OSError:
5052 raise unittest.SkipTest('creating the test junction failed')
5053
5054 entries = self.get_entries(['srcjunc', 'tgtdir'])
5055 self.assertEqual(entries['srcjunc'].is_junction(), True)
5056 self.assertEqual(entries['tgtdir'].is_junction(), False)
5057
5058 def get_entry(self, name):
5059 path = self.bytes_path if isinstance(name, bytes) else self.path
5060 entries = list(os.scandir(path))
5061 self.assertEqual(len(entries), 1)
5062
5063 entry = entries[0]
5064 self.assertEqual(entry.name, name)
5065 return entry
5066
5067 def create_file_entry(self, name='file.txt'):
5068 filename = self.create_file(name=name)
5069 return self.get_entry(os.path.basename(filename))
5070
5071 def test_current_directory(self):
5072 filename = self.create_file()
5073 old_dir = os.getcwd()
5074 try:
5075 os.chdir(self.path)
5076
5077 # call scandir() without parameter: it must list the content
5078 # of the current directory
5079 entries = dict((entry.name, entry) for entry in os.scandir())
5080 self.assertEqual(sorted(entries.keys()),
5081 [os.path.basename(filename)])
5082 finally:
5083 os.chdir(old_dir)
5084
5085 def test_repr(self):
5086 entry = self.create_file_entry()
5087 self.assertEqual(repr(entry), "<DirEntry 'file.txt'>")
5088
5089 def test_fspath_protocol(self):
5090 entry = self.create_file_entry()
5091 self.assertEqual(os.fspath(entry), os.path.join(self.path, 'file.txt'))
5092
5093 def test_fspath_protocol_bytes(self):
5094 bytes_filename = os.fsencode('bytesfile.txt')
5095 bytes_entry = self.create_file_entry(name=bytes_filename)
5096 fspath = os.fspath(bytes_entry)
5097 self.assertIsInstance(fspath, bytes)
5098 self.assertEqual(fspath,
5099 os.path.join(os.fsencode(self.path),bytes_filename))
5100
5101 def test_removed_dir(self):
5102 path = os.path.join(self.path, 'dir')
5103
5104 os.mkdir(path)
5105 entry = self.get_entry('dir')
5106 os.rmdir(path)
5107
5108 # On POSIX, is_dir() result depends if scandir() filled d_type or not
5109 if os.name == 'nt':
5110 self.assertTrue(entry.is_dir())
5111 self.assertFalse(entry.is_file())
5112 self.assertFalse(entry.is_symlink())
5113 if os.name == 'nt':
5114 self.assertRaises(FileNotFoundError, entry.inode)
5115 # don't fail
5116 entry.stat()
5117 entry.stat(follow_symlinks=False)
5118 else:
5119 self.assertGreater(entry.inode(), 0)
5120 self.assertRaises(FileNotFoundError, entry.stat)
5121 self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False)
5122
5123 def test_removed_file(self):
5124 entry = self.create_file_entry()
5125 os.unlink(entry.path)
5126
5127 self.assertFalse(entry.is_dir())
5128 # On POSIX, is_dir() result depends if scandir() filled d_type or not
5129 if os.name == 'nt':
5130 self.assertTrue(entry.is_file())
5131 self.assertFalse(entry.is_symlink())
5132 if os.name == 'nt':
5133 self.assertRaises(FileNotFoundError, entry.inode)
5134 # don't fail
5135 entry.stat()
5136 entry.stat(follow_symlinks=False)
5137 else:
5138 self.assertGreater(entry.inode(), 0)
5139 self.assertRaises(FileNotFoundError, entry.stat)
5140 self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False)
5141
5142 def test_broken_symlink(self):
5143 if not os_helper.can_symlink():
5144 return self.skipTest('cannot create symbolic link')
5145
5146 filename = self.create_file("file.txt")
5147 os.symlink(filename,
5148 os.path.join(self.path, "symlink.txt"))
5149 entries = self.get_entries(['file.txt', 'symlink.txt'])
5150 entry = entries['symlink.txt']
5151 os.unlink(filename)
5152
5153 self.assertGreater(entry.inode(), 0)
5154 self.assertFalse(entry.is_dir())
5155 self.assertFalse(entry.is_file()) # broken symlink returns False
5156 self.assertFalse(entry.is_dir(follow_symlinks=False))
5157 self.assertFalse(entry.is_file(follow_symlinks=False))
5158 self.assertTrue(entry.is_symlink())
5159 self.assertRaises(FileNotFoundError, entry.stat)
5160 # don't fail
5161 entry.stat(follow_symlinks=False)
5162
5163 def test_bytes(self):
5164 self.create_file("file.txt")
5165
5166 path_bytes = os.fsencode(self.path)
5167 entries = list(os.scandir(path_bytes))
5168 self.assertEqual(len(entries), 1, entries)
5169 entry = entries[0]
5170
5171 self.assertEqual(entry.name, b'file.txt')
5172 self.assertEqual(entry.path,
5173 os.fsencode(os.path.join(self.path, 'file.txt')))
5174
5175 def test_bytes_like(self):
5176 self.create_file("file.txt")
5177
5178 for cls in bytearray, memoryview:
5179 path_bytes = cls(os.fsencode(self.path))
5180 with self.assertRaises(TypeError):
5181 os.scandir(path_bytes)
5182
5183 @unittest.skipUnless(os.listdir in os.supports_fd,
5184 'fd support for listdir required for this test.')
5185 def test_fd(self):
5186 self.assertIn(os.scandir, os.supports_fd)
5187 self.create_file('file.txt')
5188 expected_names = ['file.txt']
5189 if os_helper.can_symlink():
5190 os.symlink('file.txt', os.path.join(self.path, 'link'))
5191 expected_names.append('link')
5192
5193 with os_helper.open_dir_fd(self.path) as fd:
5194 with os.scandir(fd) as it:
5195 entries = list(it)
5196 names = [entry.name for entry in entries]
5197 self.assertEqual(sorted(names), expected_names)
5198 self.assertEqual(names, os.listdir(fd))
5199 for entry in entries:
5200 self.assertEqual(entry.path, entry.name)
5201 self.assertEqual(os.fspath(entry), entry.name)
5202 self.assertEqual(entry.is_symlink(), entry.name == 'link')
5203 if os.stat in os.supports_dir_fd:
5204 st = os.stat(entry.name, dir_fd=fd)
5205 self.assertEqual(entry.stat(), st)
5206 st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
5207 self.assertEqual(entry.stat(follow_symlinks=False), st)
5208
5209 @unittest.skipIf(support.is_wasi, "WASI maps '' to cwd")
5210 def test_empty_path(self):
5211 self.assertRaises(FileNotFoundError, os.scandir, '')
5212
5213 def test_consume_iterator_twice(self):
5214 self.create_file("file.txt")
5215 iterator = os.scandir(self.path)
5216
5217 entries = list(iterator)
5218 self.assertEqual(len(entries), 1, entries)
5219
5220 # check than consuming the iterator twice doesn't raise exception
5221 entries2 = list(iterator)
5222 self.assertEqual(len(entries2), 0, entries2)
5223
5224 def test_bad_path_type(self):
5225 for obj in [1.234, {}, []]:
5226 self.assertRaises(TypeError, os.scandir, obj)
5227
5228 def test_close(self):
5229 self.create_file("file.txt")
5230 self.create_file("file2.txt")
5231 iterator = os.scandir(self.path)
5232 next(iterator)
5233 iterator.close()
5234 # multiple closes
5235 iterator.close()
5236 with self.check_no_resource_warning():
5237 del iterator
5238
5239 def test_context_manager(self):
5240 self.create_file("file.txt")
5241 self.create_file("file2.txt")
5242 with os.scandir(self.path) as iterator:
5243 next(iterator)
5244 with self.check_no_resource_warning():
5245 del iterator
5246
5247 def test_context_manager_close(self):
5248 self.create_file("file.txt")
5249 self.create_file("file2.txt")
5250 with os.scandir(self.path) as iterator:
5251 next(iterator)
5252 iterator.close()
5253
5254 def test_context_manager_exception(self):
5255 self.create_file("file.txt")
5256 self.create_file("file2.txt")
5257 with self.assertRaises(ZeroDivisionError):
5258 with os.scandir(self.path) as iterator:
5259 next(iterator)
5260 1/0
5261 with self.check_no_resource_warning():
5262 del iterator
5263
5264 def test_resource_warning(self):
5265 self.create_file("file.txt")
5266 self.create_file("file2.txt")
5267 iterator = os.scandir(self.path)
5268 next(iterator)
5269 with self.assertWarns(ResourceWarning):
5270 del iterator
5271 support.gc_collect()
5272 # exhausted iterator
5273 iterator = os.scandir(self.path)
5274 list(iterator)
5275 with self.check_no_resource_warning():
5276 del iterator
5277
5278
5279 class TestPEP519(unittest.TestCase):
5280
5281 # Abstracted so it can be overridden to test pure Python implementation
5282 # if a C version is provided.
5283 fspath = staticmethod(os.fspath)
5284
5285 def test_return_bytes(self):
5286 for b in b'hello', b'goodbye', b'some/path/and/file':
5287 self.assertEqual(b, self.fspath(b))
5288
5289 def test_return_string(self):
5290 for s in 'hello', 'goodbye', 'some/path/and/file':
5291 self.assertEqual(s, self.fspath(s))
5292
5293 def test_fsencode_fsdecode(self):
5294 for p in "path/like/object", b"path/like/object":
5295 pathlike = FakePath(p)
5296
5297 self.assertEqual(p, self.fspath(pathlike))
5298 self.assertEqual(b"path/like/object", os.fsencode(pathlike))
5299 self.assertEqual("path/like/object", os.fsdecode(pathlike))
5300
5301 def test_pathlike(self):
5302 self.assertEqual('#feelthegil', self.fspath(FakePath('#feelthegil')))
5303 self.assertTrue(issubclass(FakePath, os.PathLike))
5304 self.assertTrue(isinstance(FakePath('x'), os.PathLike))
5305
5306 def test_garbage_in_exception_out(self):
5307 vapor = type('blah', (), {})
5308 for o in int, type, os, vapor():
5309 self.assertRaises(TypeError, self.fspath, o)
5310
5311 def test_argument_required(self):
5312 self.assertRaises(TypeError, self.fspath)
5313
5314 def test_bad_pathlike(self):
5315 # __fspath__ returns a value other than str or bytes.
5316 self.assertRaises(TypeError, self.fspath, FakePath(42))
5317 # __fspath__ attribute that is not callable.
5318 c = type('foo', (), {})
5319 c.__fspath__ = 1
5320 self.assertRaises(TypeError, self.fspath, c())
5321 # __fspath__ raises an exception.
5322 self.assertRaises(ZeroDivisionError, self.fspath,
5323 FakePath(ZeroDivisionError()))
5324
5325 def test_pathlike_subclasshook(self):
5326 # bpo-38878: subclasshook causes subclass checks
5327 # true on abstract implementation.
5328 class A(os.PathLike):
5329 pass
5330 self.assertFalse(issubclass(FakePath, A))
5331 self.assertTrue(issubclass(FakePath, os.PathLike))
5332
5333 def test_pathlike_class_getitem(self):
5334 self.assertIsInstance(os.PathLike[bytes], types.GenericAlias)
5335
5336 def test_pathlike_subclass_slots(self):
5337 class A(os.PathLike):
5338 __slots__ = ()
5339 def __fspath__(self):
5340 return ''
5341 self.assertFalse(hasattr(A(), '__dict__'))
5342
5343 def test_fspath_set_to_None(self):
5344 class Foo:
5345 __fspath__ = None
5346
5347 class Bar:
5348 def __fspath__(self):
5349 return 'bar'
5350
5351 class Baz(Bar):
5352 __fspath__ = None
5353
5354 good_error_msg = (
5355 r"expected str, bytes or os.PathLike object, not {}".format
5356 )
5357
5358 with self.assertRaisesRegex(TypeError, good_error_msg("Foo")):
5359 self.fspath(Foo())
5360
5361 self.assertEqual(self.fspath(Bar()), 'bar')
5362
5363 with self.assertRaisesRegex(TypeError, good_error_msg("Baz")):
5364 self.fspath(Baz())
5365
5366 with self.assertRaisesRegex(TypeError, good_error_msg("Foo")):
5367 open(Foo())
5368
5369 with self.assertRaisesRegex(TypeError, good_error_msg("Baz")):
5370 open(Baz())
5371
5372 other_good_error_msg = (
5373 r"should be string, bytes or os.PathLike, not {}".format
5374 )
5375
5376 with self.assertRaisesRegex(TypeError, other_good_error_msg("Foo")):
5377 os.rename(Foo(), "foooo")
5378
5379 with self.assertRaisesRegex(TypeError, other_good_error_msg("Baz")):
5380 os.rename(Baz(), "bazzz")
5381
5382 class TimesTests(unittest.TestCase):
5383 def test_times(self):
5384 times = os.times()
5385 self.assertIsInstance(times, os.times_result)
5386
5387 for field in ('user', 'system', 'children_user', 'children_system',
5388 'elapsed'):
5389 value = getattr(times, field)
5390 self.assertIsInstance(value, float)
5391
5392 if os.name == 'nt':
5393 self.assertEqual(times.children_user, 0)
5394 self.assertEqual(times.children_system, 0)
5395 self.assertEqual(times.elapsed, 0)
5396
5397
5398 @support.requires_fork()
5399 class ForkTests(unittest.TestCase):
5400 def test_fork(self):
5401 # bpo-42540: ensure os.fork() with non-default memory allocator does
5402 # not crash on exit.
5403 code = """if 1:
5404 import os
5405 from test import support
5406 pid = os.fork()
5407 if pid != 0:
5408 support.wait_process(pid, exitcode=0)
5409 """
5410 assert_python_ok("-c", code)
5411 if support.Py_GIL_DISABLED:
5412 assert_python_ok("-c", code, PYTHONMALLOC="mimalloc_debug")
5413 else:
5414 assert_python_ok("-c", code, PYTHONMALLOC="malloc_debug")
5415
5416 @unittest.skipUnless(sys.platform in ("linux", "android", "darwin"),
5417 "Only Linux and macOS detect this today.")
5418 @unittest.skipIf(_testcapi is None, "requires _testcapi")
5419 def test_fork_warns_when_non_python_thread_exists(self):
5420 code = """if 1:
5421 import os, threading, warnings
5422 from _testcapi import _spawn_pthread_waiter, _end_spawned_pthread
5423 _spawn_pthread_waiter()
5424 try:
5425 with warnings.catch_warnings(record=True) as ws:
5426 warnings.filterwarnings(
5427 "always", category=DeprecationWarning)
5428 if os.fork() == 0:
5429 assert not ws, f"unexpected warnings in child: {ws}"
5430 os._exit(0) # child
5431 else:
5432 assert ws[0].category == DeprecationWarning, ws[0]
5433 assert 'fork' in str(ws[0].message), ws[0]
5434 # Waiting allows an error in the child to hit stderr.
5435 exitcode = os.wait()[1]
5436 assert exitcode == 0, f"child exited {exitcode}"
5437 assert threading.active_count() == 1, threading.enumerate()
5438 finally:
5439 _end_spawned_pthread()
5440 """
5441 _, out, err = assert_python_ok("-c", code, PYTHONOPTIMIZE='0')
5442 self.assertEqual(err.decode("utf-8"), "")
5443 self.assertEqual(out.decode("utf-8"), "")
5444
5445 def test_fork_at_finalization(self):
5446 code = """if 1:
5447 import atexit
5448 import os
5449
5450 class AtFinalization:
5451 def __del__(self):
5452 print("OK")
5453 pid = os.fork()
5454 if pid != 0:
5455 print("shouldn't be printed")
5456 at_finalization = AtFinalization()
5457 """
5458 _, out, err = assert_python_ok("-c", code)
5459 self.assertEqual(b"OK\n", out)
5460 self.assertIn(b"can't fork at interpreter shutdown", err)
5461
5462
5463 # Only test if the C version is provided, otherwise TestPEP519 already tested
5464 # the pure Python implementation.
5465 if hasattr(os, "_fspath"):
5466 class TestPEP519PurePython(TestPEP519):
5467
5468 """Explicitly test the pure Python implementation of os.fspath()."""
5469
5470 fspath = staticmethod(os._fspath)
5471
5472
5473 if __name__ == "__main__":
5474 unittest.main()