Debian Codegraph @

lib-python/3/test/test_os.py

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