Debian Codegraph @

lib-python/3/test/test_os.py

raw symbols ◀ ▶ SCIP
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 if f.__name__.endswith('sync'):
2240 return # eatmydata won't raise an OSError
2241 self.fail("%r didn't raise an OSError with a bad file descriptor"
2242 % f)
2243
2244 def test_fdopen(self):
2245 self.check(os.fdopen, encoding="utf-8")
2246
2247 @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
2248 def test_isatty(self):
2249 self.assertEqual(os.isatty(os_helper.make_bad_fd()), False)
2250
2251 @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
2252 def test_closerange(self):
2253 fd = os_helper.make_bad_fd()
2254 # Make sure none of the descriptors we are about to close are
2255 # currently valid (issue 6542).
2256 for i in range(10):
2257 try: os.fstat(fd+i)
2258 except OSError:
2259 pass
2260 else:
2261 break
2262 if i < 2:
2263 raise unittest.SkipTest(
2264 "Unable to acquire a range of invalid file descriptors")
2265 self.assertEqual(os.closerange(fd, fd + i-1), None)
2266
2267 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2268 def test_dup2(self):
2269 self.check(os.dup2, 20)
2270
2271 @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2272 @unittest.skipIf(
2273 support.is_emscripten,
2274 "dup2() with negative fds is broken on Emscripten (see gh-102179)"
2275 )
2276 def test_dup2_negative_fd(self):
2277 valid_fd = os.open(__file__, os.O_RDONLY)
2278 self.addCleanup(os.close, valid_fd)
2279 fds = [
2280 valid_fd,
2281 -1,
2282 -2**31,
2283 ]
2284 for fd, fd2 in itertools.product(fds, repeat=2):
2285 if fd != fd2:
2286 with self.subTest(fd=fd, fd2=fd2):
2287 with self.assertRaises(OSError) as ctx:
2288 os.dup2(fd, fd2)
2289 self.assertEqual(ctx.exception.errno, errno.EBADF)
2290
2291 @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
2292 def test_fchmod(self):
2293 self.check(os.fchmod, 0)
2294
2295 @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
2296 def test_fchown(self):
2297 self.check(os.fchown, -1, -1)
2298
2299 @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
2300 @unittest.skipIf(
2301 support.is_emscripten or support.is_wasi,
2302 "musl libc issue on Emscripten/WASI, bpo-46390"
2303 )
2304 def test_fpathconf(self):
2305 self.check(os.pathconf, "PC_NAME_MAX")
2306 self.check(os.fpathconf, "PC_NAME_MAX")
2307
2308 @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
2309 def test_ftruncate(self):
2310 self.check(os.truncate, 0)
2311 self.check(os.ftruncate, 0)
2312
2313 @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
2314 def test_lseek(self):
2315 self.check(os.lseek, 0, 0)
2316
2317 @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
2318 def test_read(self):
2319 self.check(os.read, 1)
2320
2321 @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()')
2322 def test_readv(self):
2323 buf = bytearray(10)
2324 self.check(os.readv, [buf])
2325
2326 @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
2327 def test_tcsetpgrpt(self):
2328 self.check(os.tcsetpgrp, 0)
2329
2330 @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
2331 def test_write(self):
2332 self.check(os.write, b" ")
2333
2334 @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()')
2335 def test_writev(self):
2336 self.check(os.writev, [b'abc'])
2337
2338 @support.requires_subprocess()
2339 def test_inheritable(self):
2340 self.check(os.get_inheritable)
2341 self.check(os.set_inheritable, True)
2342
2343 @unittest.skipUnless(hasattr(os, 'get_blocking'),
2344 'needs os.get_blocking() and os.set_blocking()')
2345 def test_blocking(self):
2346 self.check(os.get_blocking)
2347 self.check(os.set_blocking, True)
2348
2349
2350 @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
2351 class LinkTests(unittest.TestCase):
2352 def setUp(self):
2353 self.file1 = os_helper.TESTFN
2354 self.file2 = os.path.join(os_helper.TESTFN + "2")
2355
2356 def tearDown(self):
2357 for file in (self.file1, self.file2):
2358 if os.path.exists(file):
2359 os.unlink(file)
2360
2361 def _test_link(self, file1, file2):
2362 create_file(file1)
2363
2364 try:
2365 os.link(file1, file2)
2366 except PermissionError as e:
2367 self.skipTest('os.link(): %s' % e)
2368 with open(file1, "rb") as f1, open(file2, "rb") as f2:
2369 self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
2370
2371 def test_link(self):
2372 self._test_link(self.file1, self.file2)
2373
2374 def test_link_bytes(self):
2375 self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
2376 bytes(self.file2, sys.getfilesystemencoding()))
2377
2378 def test_unicode_name(self):
2379 try:
2380 os.fsencode("\xf1")
2381 except UnicodeError:
2382 raise unittest.SkipTest("Unable to encode for this platform.")
2383
2384 self.file1 += "\xf1"
2385 self.file2 = self.file1 + "2"
2386 self._test_link(self.file1, self.file2)
2387
2388 @unittest.skipIf(sys.platform == "win32", "Posix specific tests")
2389 class PosixUidGidTests(unittest.TestCase):
2390 # uid_t and gid_t are 32-bit unsigned integers on Linux
2391 UID_OVERFLOW = (1 << 32)
2392 GID_OVERFLOW = (1 << 32)
2393
2394 @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
2395 def test_setuid(self):
2396 if os.getuid() != 0:
2397 self.assertRaises(OSError, os.setuid, 0)
2398 self.assertRaises(TypeError, os.setuid, 'not an int')
2399 self.assertRaises(OverflowError, os.setuid, self.UID_OVERFLOW)
2400
2401 @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
2402 def test_setgid(self):
2403 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2404 self.assertRaises(OSError, os.setgid, 0)
2405 self.assertRaises(TypeError, os.setgid, 'not an int')
2406 self.assertRaises(OverflowError, os.setgid, self.GID_OVERFLOW)
2407
2408 @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
2409 def test_seteuid(self):
2410 if os.getuid() != 0:
2411 self.assertRaises(OSError, os.seteuid, 0)
2412 self.assertRaises(TypeError, os.setegid, 'not an int')
2413 self.assertRaises(OverflowError, os.seteuid, self.UID_OVERFLOW)
2414
2415 @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
2416 def test_setegid(self):
2417 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2418 self.assertRaises(OSError, os.setegid, 0)
2419 self.assertRaises(TypeError, os.setegid, 'not an int')
2420 self.assertRaises(OverflowError, os.setegid, self.GID_OVERFLOW)
2421
2422 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2423 def test_setreuid(self):
2424 if os.getuid() != 0:
2425 self.assertRaises(OSError, os.setreuid, 0, 0)
2426 self.assertRaises(TypeError, os.setreuid, 'not an int', 0)
2427 self.assertRaises(TypeError, os.setreuid, 0, 'not an int')
2428 self.assertRaises(OverflowError, os.setreuid, self.UID_OVERFLOW, 0)
2429 self.assertRaises(OverflowError, os.setreuid, 0, self.UID_OVERFLOW)
2430
2431 @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
2432 @support.requires_subprocess()
2433 def test_setreuid_neg1(self):
2434 # Needs to accept -1. We run this in a subprocess to avoid
2435 # altering the test runner's process state (issue8045).
2436 subprocess.check_call([
2437 sys.executable, '-c',
2438 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
2439
2440 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2441 @support.requires_subprocess()
2442 def test_setregid(self):
2443 if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
2444 self.assertRaises(OSError, os.setregid, 0, 0)
2445 self.assertRaises(TypeError, os.setregid, 'not an int', 0)
2446 self.assertRaises(TypeError, os.setregid, 0, 'not an int')
2447 self.assertRaises(OverflowError, os.setregid, self.GID_OVERFLOW, 0)
2448 self.assertRaises(OverflowError, os.setregid, 0, self.GID_OVERFLOW)
2449
2450 @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
2451 @support.requires_subprocess()
2452 def test_setregid_neg1(self):
2453 # Needs to accept -1. We run this in a subprocess to avoid
2454 # altering the test runner's process state (issue8045).
2455 subprocess.check_call([
2456 sys.executable, '-c',
2457 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
2458
2459 @unittest.skipIf(sys.platform == "win32", "Posix specific tests")
2460 class Pep383Tests(unittest.TestCase):
2461 def setUp(self):
2462 if os_helper.TESTFN_UNENCODABLE:
2463 self.dir = os_helper.TESTFN_UNENCODABLE
2464 elif os_helper.TESTFN_NONASCII:
2465 self.dir = os_helper.TESTFN_NONASCII
2466 else:
2467 self.dir = os_helper.TESTFN
2468 self.bdir = os.fsencode(self.dir)
2469
2470 bytesfn = []
2471 def add_filename(fn):
2472 try:
2473 fn = os.fsencode(fn)
2474 except UnicodeEncodeError:
2475 return
2476 bytesfn.append(fn)
2477 add_filename(os_helper.TESTFN_UNICODE)
2478 if os_helper.TESTFN_UNENCODABLE:
2479 add_filename(os_helper.TESTFN_UNENCODABLE)
2480 if os_helper.TESTFN_NONASCII:
2481 add_filename(os_helper.TESTFN_NONASCII)
2482 if not bytesfn:
2483 self.skipTest("couldn't create any non-ascii filename")
2484
2485 self.unicodefn = set()
2486 os.mkdir(self.dir)
2487 try:
2488 for fn in bytesfn:
2489 os_helper.create_empty_file(os.path.join(self.bdir, fn))
2490 fn = os.fsdecode(fn)
2491 if fn in self.unicodefn:
2492 raise ValueError("duplicate filename")
2493 self.unicodefn.add(fn)
2494 except:
2495 shutil.rmtree(self.dir)
2496 raise
2497
2498 def tearDown(self):
2499 shutil.rmtree(self.dir)
2500
2501 def test_listdir(self):
2502 expected = self.unicodefn
2503 found = set(os.listdir(self.dir))
2504 self.assertEqual(found, expected)
2505 # test listdir without arguments
2506 current_directory = os.getcwd()
2507 try:
2508 os.chdir(os.sep)
2509 self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
2510 finally:
2511 os.chdir(current_directory)
2512
2513 def test_open(self):
2514 for fn in self.unicodefn:
2515 f = open(os.path.join(self.dir, fn), 'rb')
2516 f.close()
2517
2518 @unittest.skipUnless(hasattr(os, 'statvfs'),
2519 "need os.statvfs()")
2520 def test_statvfs(self):
2521 # issue #9645
2522 for fn in self.unicodefn:
2523 # should not fail with file not found error
2524 fullname = os.path.join(self.dir, fn)
2525 os.statvfs(fullname)
2526
2527 def test_stat(self):
2528 for fn in self.unicodefn:
2529 os.stat(os.path.join(self.dir, fn))
2530
2531 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2532 class Win32KillTests(unittest.TestCase):
2533 def _kill(self, sig):
2534 # Start sys.executable as a subprocess and communicate from the
2535 # subprocess to the parent that the interpreter is ready. When it
2536 # becomes ready, send *sig* via os.kill to the subprocess and check
2537 # that the return code is equal to *sig*.
2538 import ctypes
2539 from ctypes import wintypes
2540 import msvcrt
2541
2542 # Since we can't access the contents of the process' stdout until the
2543 # process has exited, use PeekNamedPipe to see what's inside stdout
2544 # without waiting. This is done so we can tell that the interpreter
2545 # is started and running at a point where it could handle a signal.
2546 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
2547 PeekNamedPipe.restype = wintypes.BOOL
2548 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
2549 ctypes.POINTER(ctypes.c_char), # stdout buf
2550 wintypes.DWORD, # Buffer size
2551 ctypes.POINTER(wintypes.DWORD), # bytes read
2552 ctypes.POINTER(wintypes.DWORD), # bytes avail
2553 ctypes.POINTER(wintypes.DWORD)) # bytes left
2554 msg = "running"
2555 proc = subprocess.Popen([sys.executable, "-c",
2556 "import sys;"
2557 "sys.stdout.write('{}');"
2558 "sys.stdout.flush();"
2559 "input()".format(msg)],
2560 stdout=subprocess.PIPE,
2561 stderr=subprocess.PIPE,
2562 stdin=subprocess.PIPE)
2563 self.addCleanup(proc.stdout.close)
2564 self.addCleanup(proc.stderr.close)
2565 self.addCleanup(proc.stdin.close)
2566
2567 count, max = 0, 100
2568 while count < max and proc.poll() is None:
2569 # Create a string buffer to store the result of stdout from the pipe
2570 buf = ctypes.create_string_buffer(len(msg))
2571 # Obtain the text currently in proc.stdout
2572 # Bytes read/avail/left are left as NULL and unused
2573 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
2574 buf, ctypes.sizeof(buf), None, None, None)
2575 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
2576 if buf.value:
2577 self.assertEqual(msg, buf.value.decode())
2578 break
2579 time.sleep(0.1)
2580 count += 1
2581 else:
2582 self.fail("Did not receive communication from the subprocess")
2583
2584 os.kill(proc.pid, sig)
2585 self.assertEqual(proc.wait(), sig)
2586
2587 def test_kill_sigterm(self):
2588 # SIGTERM doesn't mean anything special, but make sure it works
2589 self._kill(signal.SIGTERM)
2590
2591 def test_kill_int(self):
2592 # os.kill on Windows can take an int which gets set as the exit code
2593 self._kill(100)
2594
2595 @unittest.skipIf(mmap is None, "requires mmap")
2596 def _kill_with_event(self, event, name):
2597 tagname = "test_os_%s" % uuid.uuid1()
2598 m = mmap.mmap(-1, 1, tagname)
2599 m[0] = 0
2600
2601 # Run a script which has console control handling enabled.
2602 script = os.path.join(os.path.dirname(__file__),
2603 "win_console_handler.py")
2604 cmd = [sys.executable, script, tagname]
2605 proc = subprocess.Popen(cmd,
2606 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
2607
2608 with proc:
2609 # Let the interpreter startup before we send signals. See #3137.
2610 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
2611 if proc.poll() is None:
2612 break
2613 else:
2614 # Forcefully kill the process if we weren't able to signal it.
2615 proc.kill()
2616 self.fail("Subprocess didn't finish initialization")
2617
2618 os.kill(proc.pid, event)
2619
2620 try:
2621 # proc.send_signal(event) could also be done here.
2622 # Allow time for the signal to be passed and the process to exit.
2623 proc.wait(timeout=support.SHORT_TIMEOUT)
2624 except subprocess.TimeoutExpired:
2625 # Forcefully kill the process if we weren't able to signal it.
2626 proc.kill()
2627 self.fail("subprocess did not stop on {}".format(name))
2628
2629 @unittest.skip("subprocesses aren't inheriting Ctrl+C property")
2630 @support.requires_subprocess()
2631 def test_CTRL_C_EVENT(self):
2632 from ctypes import wintypes
2633 import ctypes
2634
2635 # Make a NULL value by creating a pointer with no argument.
2636 NULL = ctypes.POINTER(ctypes.c_int)()
2637 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
2638 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
2639 wintypes.BOOL)
2640 SetConsoleCtrlHandler.restype = wintypes.BOOL
2641
2642 # Calling this with NULL and FALSE causes the calling process to
2643 # handle Ctrl+C, rather than ignore it. This property is inherited
2644 # by subprocesses.
2645 SetConsoleCtrlHandler(NULL, 0)
2646
2647 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
2648
2649 @support.requires_subprocess()
2650 def test_CTRL_BREAK_EVENT(self):
2651 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
2652
2653
2654 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2655 class Win32ListdirTests(unittest.TestCase):
2656 """Test listdir on Windows."""
2657
2658 def setUp(self):
2659 self.created_paths = []
2660 for i in range(2):
2661 dir_name = 'SUB%d' % i
2662 dir_path = os.path.join(os_helper.TESTFN, dir_name)
2663 file_name = 'FILE%d' % i
2664 file_path = os.path.join(os_helper.TESTFN, file_name)
2665 os.makedirs(dir_path)
2666 with open(file_path, 'w', encoding='utf-8') as f:
2667 f.write("I'm %s and proud of it. Blame test_os.\n" % file_path)
2668 self.created_paths.extend([dir_name, file_name])
2669 self.created_paths.sort()
2670
2671 def tearDown(self):
2672 shutil.rmtree(os_helper.TESTFN)
2673
2674 def test_listdir_no_extended_path(self):
2675 """Test when the path is not an "extended" path."""
2676 # unicode
2677 self.assertEqual(
2678 sorted(os.listdir(os_helper.TESTFN)),
2679 self.created_paths)
2680
2681 # bytes
2682 self.assertEqual(
2683 sorted(os.listdir(os.fsencode(os_helper.TESTFN))),
2684 [os.fsencode(path) for path in self.created_paths])
2685
2686 def test_listdir_extended_path(self):
2687 """Test when the path starts with '\\\\?\\'."""
2688 # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
2689 # unicode
2690 path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN)
2691 self.assertEqual(
2692 sorted(os.listdir(path)),
2693 self.created_paths)
2694
2695 # bytes
2696 path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN))
2697 self.assertEqual(
2698 sorted(os.listdir(path)),
2699 [os.fsencode(path) for path in self.created_paths])
2700
2701
2702 @unittest.skipUnless(hasattr(os, 'readlink'), 'needs os.readlink()')
2703 class ReadlinkTests(unittest.TestCase):
2704 filelink = 'readlinktest'
2705 filelink_target = os.path.abspath(__file__)
2706 filelinkb = os.fsencode(filelink)
2707 filelinkb_target = os.fsencode(filelink_target)
2708
2709 def assertPathEqual(self, left, right):
2710 left = os.path.normcase(left)
2711 right = os.path.normcase(right)
2712 if sys.platform == 'win32':
2713 # Bad practice to blindly strip the prefix as it may be required to
2714 # correctly refer to the file, but we're only comparing paths here.
2715 has_prefix = lambda p: p.startswith(
2716 b'\\\\?\\' if isinstance(p, bytes) else '\\\\?\\')
2717 if has_prefix(left):
2718 left = left[4:]
2719 if has_prefix(right):
2720 right = right[4:]
2721 self.assertEqual(left, right)
2722
2723 def setUp(self):
2724 self.assertTrue(os.path.exists(self.filelink_target))
2725 self.assertTrue(os.path.exists(self.filelinkb_target))
2726 self.assertFalse(os.path.exists(self.filelink))
2727 self.assertFalse(os.path.exists(self.filelinkb))
2728
2729 def test_not_symlink(self):
2730 filelink_target = FakePath(self.filelink_target)
2731 self.assertRaises(OSError, os.readlink, self.filelink_target)
2732 self.assertRaises(OSError, os.readlink, filelink_target)
2733
2734 def test_missing_link(self):
2735 self.assertRaises(FileNotFoundError, os.readlink, 'missing-link')
2736 self.assertRaises(FileNotFoundError, os.readlink,
2737 FakePath('missing-link'))
2738
2739 @os_helper.skip_unless_symlink
2740 def test_pathlike(self):
2741 os.symlink(self.filelink_target, self.filelink)
2742 self.addCleanup(os_helper.unlink, self.filelink)
2743 filelink = FakePath(self.filelink)
2744 self.assertPathEqual(os.readlink(filelink), self.filelink_target)
2745
2746 @os_helper.skip_unless_symlink
2747 def test_pathlike_bytes(self):
2748 os.symlink(self.filelinkb_target, self.filelinkb)
2749 self.addCleanup(os_helper.unlink, self.filelinkb)
2750 path = os.readlink(FakePath(self.filelinkb))
2751 self.assertPathEqual(path, self.filelinkb_target)
2752 self.assertIsInstance(path, bytes)
2753
2754 @os_helper.skip_unless_symlink
2755 def test_bytes(self):
2756 os.symlink(self.filelinkb_target, self.filelinkb)
2757 self.addCleanup(os_helper.unlink, self.filelinkb)
2758 path = os.readlink(self.filelinkb)
2759 self.assertPathEqual(path, self.filelinkb_target)
2760 self.assertIsInstance(path, bytes)
2761
2762
2763 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2764 @os_helper.skip_unless_symlink
2765 class Win32SymlinkTests(unittest.TestCase):
2766 filelink = 'filelinktest'
2767 filelink_target = os.path.abspath(__file__)
2768 dirlink = 'dirlinktest'
2769 dirlink_target = os.path.dirname(filelink_target)
2770 missing_link = 'missing link'
2771
2772 def setUp(self):
2773 assert os.path.exists(self.dirlink_target)
2774 assert os.path.exists(self.filelink_target)
2775 assert not os.path.exists(self.dirlink)
2776 assert not os.path.exists(self.filelink)
2777 assert not os.path.exists(self.missing_link)
2778
2779 def tearDown(self):
2780 if os.path.exists(self.filelink):
2781 os.remove(self.filelink)
2782 if os.path.exists(self.dirlink):
2783 os.rmdir(self.dirlink)
2784 if os.path.lexists(self.missing_link):
2785 os.remove(self.missing_link)
2786
2787 def test_directory_link(self):
2788 os.symlink(self.dirlink_target, self.dirlink)
2789 self.assertTrue(os.path.exists(self.dirlink))
2790 self.assertTrue(os.path.isdir(self.dirlink))
2791 self.assertTrue(os.path.islink(self.dirlink))
2792 self.check_stat(self.dirlink, self.dirlink_target)
2793
2794 def test_file_link(self):
2795 os.symlink(self.filelink_target, self.filelink)
2796 self.assertTrue(os.path.exists(self.filelink))
2797 self.assertTrue(os.path.isfile(self.filelink))
2798 self.assertTrue(os.path.islink(self.filelink))
2799 self.check_stat(self.filelink, self.filelink_target)
2800
2801 def _create_missing_dir_link(self):
2802 'Create a "directory" link to a non-existent target'
2803 linkname = self.missing_link
2804 if os.path.lexists(linkname):
2805 os.remove(linkname)
2806 target = r'c:\\target does not exist.29r3c740'
2807 assert not os.path.exists(target)
2808 target_is_dir = True
2809 os.symlink(target, linkname, target_is_dir)
2810
2811 def test_remove_directory_link_to_missing_target(self):
2812 self._create_missing_dir_link()
2813 # For compatibility with Unix, os.remove will check the
2814 # directory status and call RemoveDirectory if the symlink
2815 # was created with target_is_dir==True.
2816 os.remove(self.missing_link)
2817
2818 def test_isdir_on_directory_link_to_missing_target(self):
2819 self._create_missing_dir_link()
2820 self.assertFalse(os.path.isdir(self.missing_link))
2821
2822 def test_rmdir_on_directory_link_to_missing_target(self):
2823 self._create_missing_dir_link()
2824 os.rmdir(self.missing_link)
2825
2826 def check_stat(self, link, target):
2827 self.assertEqual(os.stat(link), os.stat(target))
2828 self.assertNotEqual(os.lstat(link), os.stat(link))
2829
2830 bytes_link = os.fsencode(link)
2831 self.assertEqual(os.stat(bytes_link), os.stat(target))
2832 self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
2833
2834 def test_12084(self):
2835 level1 = os.path.abspath(os_helper.TESTFN)
2836 level2 = os.path.join(level1, "level2")
2837 level3 = os.path.join(level2, "level3")
2838 self.addCleanup(os_helper.rmtree, level1)
2839
2840 os.mkdir(level1)
2841 os.mkdir(level2)
2842 os.mkdir(level3)
2843
2844 file1 = os.path.abspath(os.path.join(level1, "file1"))
2845 create_file(file1)
2846
2847 orig_dir = os.getcwd()
2848 try:
2849 os.chdir(level2)
2850 link = os.path.join(level2, "link")
2851 os.symlink(os.path.relpath(file1), "link")
2852 self.assertIn("link", os.listdir(os.getcwd()))
2853
2854 # Check os.stat calls from the same dir as the link
2855 self.assertEqual(os.stat(file1), os.stat("link"))
2856
2857 # Check os.stat calls from a dir below the link
2858 os.chdir(level1)
2859 self.assertEqual(os.stat(file1),
2860 os.stat(os.path.relpath(link)))
2861
2862 # Check os.stat calls from a dir above the link
2863 os.chdir(level3)
2864 self.assertEqual(os.stat(file1),
2865 os.stat(os.path.relpath(link)))
2866 finally:
2867 os.chdir(orig_dir)
2868
2869 @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users')
2870 and os.path.exists(r'C:\ProgramData'),
2871 'Test directories not found')
2872 def test_29248(self):
2873 # os.symlink() calls CreateSymbolicLink, which creates
2874 # the reparse data buffer with the print name stored
2875 # first, so the offset is always 0. CreateSymbolicLink
2876 # stores the "PrintName" DOS path (e.g. "C:\") first,
2877 # with an offset of 0, followed by the "SubstituteName"
2878 # NT path (e.g. "\??\C:\"). The "All Users" link, on
2879 # the other hand, seems to have been created manually
2880 # with an inverted order.
2881 target = os.readlink(r'C:\Users\All Users')
2882 self.assertTrue(os.path.samefile(target, r'C:\ProgramData'))
2883
2884 def test_buffer_overflow(self):
2885 # Older versions would have a buffer overflow when detecting
2886 # whether a link source was a directory. This test ensures we
2887 # no longer crash, but does not otherwise validate the behavior
2888 segment = 'X' * 27
2889 path = os.path.join(*[segment] * 10)
2890 test_cases = [
2891 # overflow with absolute src
2892 ('\\' + path, segment),
2893 # overflow dest with relative src
2894 (segment, path),
2895 # overflow when joining src
2896 (path[:180], path[:180]),
2897 ]
2898 for src, dest in test_cases:
2899 try:
2900 os.symlink(src, dest)
2901 except FileNotFoundError:
2902 pass
2903 else:
2904 try:
2905 os.remove(dest)
2906 except OSError:
2907 pass
2908 # Also test with bytes, since that is a separate code path.
2909 try:
2910 os.symlink(os.fsencode(src), os.fsencode(dest))
2911 except FileNotFoundError:
2912 pass
2913 else:
2914 try:
2915 os.remove(dest)
2916 except OSError:
2917 pass
2918
2919 def test_appexeclink(self):
2920 root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps')
2921 if not os.path.isdir(root):
2922 self.skipTest("test requires a WindowsApps directory")
2923
2924 aliases = [os.path.join(root, a)
2925 for a in fnmatch.filter(os.listdir(root), '*.exe')]
2926
2927 for alias in aliases:
2928 if support.verbose:
2929 print()
2930 print("Testing with", alias)
2931 st = os.lstat(alias)
2932 self.assertEqual(st, os.stat(alias))
2933 self.assertFalse(stat.S_ISLNK(st.st_mode))
2934 self.assertEqual(st.st_reparse_tag, stat.IO_REPARSE_TAG_APPEXECLINK)
2935 # testing the first one we see is sufficient
2936 break
2937 else:
2938 self.skipTest("test requires an app execution alias")
2939
2940 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2941 class Win32JunctionTests(unittest.TestCase):
2942 junction = 'junctiontest'
2943 junction_target = os.path.dirname(os.path.abspath(__file__))
2944
2945 def setUp(self):
2946 assert os.path.exists(self.junction_target)
2947 assert not os.path.lexists(self.junction)
2948
2949 def tearDown(self):
2950 if os.path.lexists(self.junction):
2951 os.unlink(self.junction)
2952
2953 def test_create_junction(self):
2954 _winapi.CreateJunction(self.junction_target, self.junction)
2955 self.assertTrue(os.path.lexists(self.junction))
2956 self.assertTrue(os.path.exists(self.junction))
2957 self.assertTrue(os.path.isdir(self.junction))
2958 self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction))
2959 self.assertEqual(os.stat(self.junction), os.stat(self.junction_target))
2960
2961 # bpo-37834: Junctions are not recognized as links.
2962 self.assertFalse(os.path.islink(self.junction))
2963 self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target),
2964 os.path.normcase(os.readlink(self.junction)))
2965
2966 def test_unlink_removes_junction(self):
2967 _winapi.CreateJunction(self.junction_target, self.junction)
2968 self.assertTrue(os.path.exists(self.junction))
2969 self.assertTrue(os.path.lexists(self.junction))
2970
2971 os.unlink(self.junction)
2972 self.assertFalse(os.path.exists(self.junction))
2973
2974 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
2975 class Win32NtTests(unittest.TestCase):
2976 def test_getfinalpathname_handles(self):
2977 nt = import_helper.import_module('nt')
2978 ctypes = import_helper.import_module('ctypes')
2979 import ctypes.wintypes
2980
2981 kernel = ctypes.WinDLL('Kernel32.dll', use_last_error=True)
2982 kernel.GetCurrentProcess.restype = ctypes.wintypes.HANDLE
2983
2984 kernel.GetProcessHandleCount.restype = ctypes.wintypes.BOOL
2985 kernel.GetProcessHandleCount.argtypes = (ctypes.wintypes.HANDLE,
2986 ctypes.wintypes.LPDWORD)
2987
2988 # This is a pseudo-handle that doesn't need to be closed
2989 hproc = kernel.GetCurrentProcess()
2990
2991 handle_count = ctypes.wintypes.DWORD()
2992 ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count))
2993 self.assertEqual(1, ok)
2994
2995 before_count = handle_count.value
2996
2997 # The first two test the error path, __file__ tests the success path
2998 filenames = [
2999 r'\\?\C:',
3000 r'\\?\NUL',
3001 r'\\?\CONIN',
3002 __file__,
3003 ]
3004
3005 for _ in range(10):
3006 for name in filenames:
3007 try:
3008 nt._getfinalpathname(name)
3009 except Exception:
3010 # Failure is expected
3011 pass
3012 try:
3013 os.stat(name)
3014 except Exception:
3015 pass
3016
3017 ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count))
3018 self.assertEqual(1, ok)
3019
3020 handle_delta = handle_count.value - before_count
3021
3022 self.assertEqual(0, handle_delta)
3023
3024 @support.requires_subprocess()
3025 def test_stat_unlink_race(self):
3026 # bpo-46785: the implementation of os.stat() falls back to reading
3027 # the parent directory if CreateFileW() fails with a permission
3028 # error. If reading the parent directory fails because the file or
3029 # directory are subsequently unlinked, or because the volume or
3030 # share are no longer available, then the original permission error
3031 # should not be restored.
3032 filename = os_helper.TESTFN
3033 self.addCleanup(os_helper.unlink, filename)
3034 deadline = time.time() + 5
3035 command = textwrap.dedent("""\
3036 import os
3037 import sys
3038 import time
3039
3040 filename = sys.argv[1]
3041 deadline = float(sys.argv[2])
3042
3043 while time.time() < deadline:
3044 try:
3045 with open(filename, "w") as f:
3046 pass
3047 except OSError:
3048 pass
3049 try:
3050 os.remove(filename)
3051 except OSError:
3052 pass
3053 """)
3054
3055 with subprocess.Popen([sys.executable, '-c', command, filename, str(deadline)]) as proc:
3056 while time.time() < deadline:
3057 try:
3058 os.stat(filename)
3059 except FileNotFoundError as e:
3060 assert e.winerror == 2 # ERROR_FILE_NOT_FOUND
3061 try:
3062 proc.wait(1)
3063 except subprocess.TimeoutExpired:
3064 proc.terminate()
3065
3066
3067 @os_helper.skip_unless_symlink
3068 class NonLocalSymlinkTests(unittest.TestCase):
3069
3070 def setUp(self):
3071 r"""
3072 Create this structure:
3073
3074 base
3075 \___ some_dir
3076 """
3077 os.makedirs('base/some_dir')
3078
3079 def tearDown(self):
3080 shutil.rmtree('base')
3081
3082 def test_directory_link_nonlocal(self):
3083 """
3084 The symlink target should resolve relative to the link, not relative
3085 to the current directory.
3086
3087 Then, link base/some_link -> base/some_dir and ensure that some_link
3088 is resolved as a directory.
3089
3090 In issue13772, it was discovered that directory detection failed if
3091 the symlink target was not specified relative to the current
3092 directory, which was a defect in the implementation.
3093 """
3094 src = os.path.join('base', 'some_link')
3095 os.symlink('some_dir', src)
3096 assert os.path.isdir(src)
3097
3098
3099 class FSEncodingTests(unittest.TestCase):
3100 def test_nop(self):
3101 self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
3102 self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
3103
3104 def test_identity(self):
3105 # assert fsdecode(fsencode(x)) == x
3106 for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
3107 try:
3108 bytesfn = os.fsencode(fn)
3109 except UnicodeEncodeError:
3110 continue
3111 self.assertEqual(os.fsdecode(bytesfn), fn)
3112
3113
3114
3115 class DeviceEncodingTests(unittest.TestCase):
3116
3117 def test_bad_fd(self):
3118 # Return None when an fd doesn't actually exist.
3119 self.assertIsNone(os.device_encoding(123456))
3120
3121 @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (sys.platform.startswith('win') or
3122 (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
3123 'test requires a tty and either Windows or nl_langinfo(CODESET)')
3124 @unittest.skipIf(
3125 support.is_emscripten, "Cannot get encoding of stdin on Emscripten"
3126 )
3127 def test_device_encoding(self):
3128 encoding = os.device_encoding(0)
3129 self.assertIsNotNone(encoding)
3130 self.assertTrue(codecs.lookup(encoding))
3131
3132
3133 @support.requires_subprocess()
3134 class PidTests(unittest.TestCase):
3135 @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
3136 def test_getppid(self):
3137 p = subprocess.Popen([sys.executable, '-c',
3138 'import os; print(os.getppid())'],
3139 stdout=subprocess.PIPE)
3140 stdout, _ = p.communicate()
3141 # We are the parent of our subprocess
3142 self.assertEqual(int(stdout), os.getpid())
3143
3144 def check_waitpid(self, code, exitcode, callback=None):
3145 if sys.platform == 'win32':
3146 # On Windows, os.spawnv() simply joins arguments with spaces:
3147 # arguments need to be quoted
3148 args = [f'"{sys.executable}"', '-c', f'"{code}"']
3149 else:
3150 args = [sys.executable, '-c', code]
3151 pid = os.spawnv(os.P_NOWAIT, sys.executable, args)
3152
3153 if callback is not None:
3154 callback(pid)
3155
3156 # don't use support.wait_process() to test directly os.waitpid()
3157 # and os.waitstatus_to_exitcode()
3158 pid2, status = os.waitpid(pid, 0)
3159 self.assertEqual(os.waitstatus_to_exitcode(status), exitcode)
3160 self.assertEqual(pid2, pid)
3161
3162 def test_waitpid(self):
3163 self.check_waitpid(code='pass', exitcode=0)
3164
3165 def test_waitstatus_to_exitcode(self):
3166 exitcode = 23
3167 code = f'import sys; sys.exit({exitcode})'
3168 self.check_waitpid(code, exitcode=exitcode)
3169
3170 with self.assertRaises(TypeError):
3171 os.waitstatus_to_exitcode(0.0)
3172
3173 @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
3174 def test_waitpid_windows(self):
3175 # bpo-40138: test os.waitpid() and os.waitstatus_to_exitcode()
3176 # with exit code larger than INT_MAX.
3177 STATUS_CONTROL_C_EXIT = 0xC000013A
3178 code = f'import _winapi; _winapi.ExitProcess({STATUS_CONTROL_C_EXIT})'
3179 self.check_waitpid(code, exitcode=STATUS_CONTROL_C_EXIT)
3180
3181 @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
3182 def test_waitstatus_to_exitcode_windows(self):
3183 max_exitcode = 2 ** 32 - 1
3184 for exitcode in (0, 1, 5, max_exitcode):
3185 self.assertEqual(os.waitstatus_to_exitcode(exitcode << 8),
3186 exitcode)
3187
3188 # invalid values
3189 with self.assertRaises(ValueError):
3190 os.waitstatus_to_exitcode((max_exitcode + 1) << 8)
3191 with self.assertRaises(OverflowError):
3192 os.waitstatus_to_exitcode(-1)
3193
3194 # Skip the test on Windows
3195 @unittest.skipUnless(hasattr(signal, 'SIGKILL'), 'need signal.SIGKILL')
3196 def test_waitstatus_to_exitcode_kill(self):
3197 code = f'import time; time.sleep({support.LONG_TIMEOUT})'
3198 signum = signal.SIGKILL
3199
3200 def kill_process(pid):
3201 os.kill(pid, signum)
3202
3203 self.check_waitpid(code, exitcode=-signum, callback=kill_process)
3204
3205
3206 @support.requires_subprocess()
3207 class SpawnTests(unittest.TestCase):
3208 @staticmethod
3209 def quote_args(args):
3210 # On Windows, os.spawn* simply joins arguments with spaces:
3211 # arguments need to be quoted
3212 if os.name != 'nt':
3213 return args
3214 return [f'"{arg}"' if " " in arg.strip() else arg for arg in args]
3215
3216 def create_args(self, *, with_env=False, use_bytes=False):
3217 self.exitcode = 17
3218
3219 filename = os_helper.TESTFN
3220 self.addCleanup(os_helper.unlink, filename)
3221
3222 if not with_env:
3223 code = 'import sys; sys.exit(%s)' % self.exitcode
3224 else:
3225 self.env = dict(os.environ)
3226 # create an unique key
3227 self.key = str(uuid.uuid4())
3228 self.env[self.key] = self.key
3229 # read the variable from os.environ to check that it exists
3230 code = ('import sys, os; magic = os.environ[%r]; sys.exit(%s)'
3231 % (self.key, self.exitcode))
3232
3233 with open(filename, "w", encoding="utf-8") as fp:
3234 fp.write(code)
3235
3236 program = sys.executable
3237 args = self.quote_args([program, filename])
3238 if use_bytes:
3239 program = os.fsencode(program)
3240 args = [os.fsencode(a) for a in args]
3241 self.env = {os.fsencode(k): os.fsencode(v)
3242 for k, v in self.env.items()}
3243
3244 return program, args
3245
3246 @requires_os_func('spawnl')
3247 def test_spawnl(self):
3248 program, args = self.create_args()
3249 exitcode = os.spawnl(os.P_WAIT, program, *args)
3250 self.assertEqual(exitcode, self.exitcode)
3251
3252 @requires_os_func('spawnle')
3253 def test_spawnle(self):
3254 program, args = self.create_args(with_env=True)
3255 exitcode = os.spawnle(os.P_WAIT, program, *args, self.env)
3256 self.assertEqual(exitcode, self.exitcode)
3257
3258 @requires_os_func('spawnlp')
3259 def test_spawnlp(self):
3260 program, args = self.create_args()
3261 exitcode = os.spawnlp(os.P_WAIT, program, *args)
3262 self.assertEqual(exitcode, self.exitcode)
3263
3264 @requires_os_func('spawnlpe')
3265 def test_spawnlpe(self):
3266 program, args = self.create_args(with_env=True)
3267 exitcode = os.spawnlpe(os.P_WAIT, program, *args, self.env)
3268 self.assertEqual(exitcode, self.exitcode)
3269
3270 @requires_os_func('spawnv')
3271 def test_spawnv(self):
3272 program, args = self.create_args()
3273 exitcode = os.spawnv(os.P_WAIT, program, args)
3274 self.assertEqual(exitcode, self.exitcode)
3275
3276 # Test for PyUnicode_FSConverter()
3277 exitcode = os.spawnv(os.P_WAIT, FakePath(program), args)
3278 self.assertEqual(exitcode, self.exitcode)
3279
3280 @requires_os_func('spawnve')
3281 def test_spawnve(self):
3282 program, args = self.create_args(with_env=True)
3283 exitcode = os.spawnve(os.P_WAIT, program, args, self.env)
3284 self.assertEqual(exitcode, self.exitcode)
3285
3286 @requires_os_func('spawnvp')
3287 def test_spawnvp(self):
3288 program, args = self.create_args()
3289 exitcode = os.spawnvp(os.P_WAIT, program, args)
3290 self.assertEqual(exitcode, self.exitcode)
3291
3292 @requires_os_func('spawnvpe')
3293 def test_spawnvpe(self):
3294 program, args = self.create_args(with_env=True)
3295 exitcode = os.spawnvpe(os.P_WAIT, program, args, self.env)
3296 self.assertEqual(exitcode, self.exitcode)
3297
3298 @requires_os_func('spawnv')
3299 def test_nowait(self):
3300 program, args = self.create_args()
3301 pid = os.spawnv(os.P_NOWAIT, program, args)
3302 support.wait_process(pid, exitcode=self.exitcode)
3303
3304 @requires_os_func('spawnve')
3305 def test_spawnve_bytes(self):
3306 # Test bytes handling in parse_arglist and parse_envlist (#28114)
3307 program, args = self.create_args(with_env=True, use_bytes=True)
3308 exitcode = os.spawnve(os.P_WAIT, program, args, self.env)
3309 self.assertEqual(exitcode, self.exitcode)
3310
3311 @requires_os_func('spawnl')
3312 def test_spawnl_noargs(self):
3313 program, __ = self.create_args()
3314 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program)
3315 self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program, '')
3316
3317 @requires_os_func('spawnle')
3318 def test_spawnle_noargs(self):
3319 program, __ = self.create_args()
3320 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, {})
3321 self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, '', {})
3322
3323 @requires_os_func('spawnv')
3324 def test_spawnv_noargs(self):
3325 program, __ = self.create_args()
3326 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ())
3327 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, [])
3328 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ('',))
3329 self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, [''])
3330
3331 @requires_os_func('spawnve')
3332 def test_spawnve_noargs(self):
3333 program, __ = self.create_args()
3334 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, (), {})
3335 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, [], {})
3336 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, ('',), {})
3337 self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, [''], {})
3338
3339 def _test_invalid_env(self, spawn):
3340 program = sys.executable
3341 args = self.quote_args([program, '-c', 'pass'])
3342
3343 # null character in the environment variable name
3344 newenv = os.environ.copy()
3345 newenv["FRUIT\0VEGETABLE"] = "cabbage"
3346 try:
3347 exitcode = spawn(os.P_WAIT, program, args, newenv)
3348 except ValueError:
3349 pass
3350 else:
3351 self.assertEqual(exitcode, 127)
3352
3353 # null character in the environment variable value
3354 newenv = os.environ.copy()
3355 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
3356 try:
3357 exitcode = spawn(os.P_WAIT, program, args, newenv)
3358 except ValueError:
3359 pass
3360 else:
3361 self.assertEqual(exitcode, 127)
3362
3363 # equal character in the environment variable name
3364 newenv = os.environ.copy()
3365 newenv["FRUIT=ORANGE"] = "lemon"
3366 try:
3367 exitcode = spawn(os.P_WAIT, program, args, newenv)
3368 except ValueError:
3369 pass
3370 else:
3371 self.assertEqual(exitcode, 127)
3372
3373 # equal character in the environment variable value
3374 filename = os_helper.TESTFN
3375 self.addCleanup(os_helper.unlink, filename)
3376 with open(filename, "w", encoding="utf-8") as fp:
3377 fp.write('import sys, os\n'
3378 'if os.getenv("FRUIT") != "orange=lemon":\n'
3379 ' raise AssertionError')
3380
3381 args = self.quote_args([program, filename])
3382 newenv = os.environ.copy()
3383 newenv["FRUIT"] = "orange=lemon"
3384 exitcode = spawn(os.P_WAIT, program, args, newenv)
3385 self.assertEqual(exitcode, 0)
3386
3387 @requires_os_func('spawnve')
3388 def test_spawnve_invalid_env(self):
3389 self._test_invalid_env(os.spawnve)
3390
3391 @requires_os_func('spawnvpe')
3392 def test_spawnvpe_invalid_env(self):
3393 self._test_invalid_env(os.spawnvpe)
3394
3395
3396 # The introduction of this TestCase caused at least two different errors on
3397 # *nix buildbots. Temporarily skip this to let the buildbots move along.
3398 @unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
3399 @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
3400 class LoginTests(unittest.TestCase):
3401 def test_getlogin(self):
3402 user_name = os.getlogin()
3403 self.assertNotEqual(len(user_name), 0)
3404
3405
3406 @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
3407 "needs os.getpriority and os.setpriority")
3408 class ProgramPriorityTests(unittest.TestCase):
3409 """Tests for os.getpriority() and os.setpriority()."""
3410
3411 def test_set_get_priority(self):
3412 base = os.getpriority(os.PRIO_PROCESS, os.getpid())
3413 code = f"""if 1:
3414 import os
3415 os.setpriority(os.PRIO_PROCESS, os.getpid(), {base} + 1)
3416 print(os.getpriority(os.PRIO_PROCESS, os.getpid()))
3417 """
3418
3419 # Subprocess inherits the current process' priority.
3420 _, out, _ = assert_python_ok("-c", code)
3421 new_prio = int(out)
3422 # nice value cap is 19 for linux and 20 for FreeBSD
3423 if base >= 19 and new_prio <= base:
3424 raise unittest.SkipTest("unable to reliably test setpriority "
3425 "at current nice level of %s" % base)
3426 else:
3427 self.assertEqual(new_prio, base + 1)
3428
3429
3430 @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
3431 class TestSendfile(unittest.IsolatedAsyncioTestCase):
3432
3433 DATA = b"12345abcde" * 16 * 1024 # 160 KiB
3434 SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
3435 not sys.platform.startswith("solaris") and \
3436 not sys.platform.startswith("sunos") and \
3437 not sys.implementation.name == 'pypy'
3438 requires_headers_trailers = unittest.skipUnless(SUPPORT_HEADERS_TRAILERS,
3439 'requires headers and trailers support')
3440 requires_32b = unittest.skipUnless(sys.maxsize < 2**32,
3441 'test is only meaningful on 32-bit builds')
3442
3443 @classmethod
3444 def setUpClass(cls):
3445 create_file(os_helper.TESTFN, cls.DATA)
3446
3447 @classmethod
3448 def tearDownClass(cls):
3449 os_helper.unlink(os_helper.TESTFN)
3450
3451 @staticmethod
3452 async def chunks(reader):
3453 while not reader.at_eof():
3454 yield await reader.read()
3455
3456 async def handle_new_client(self, reader, writer):
3457 self.server_buffer = b''.join([x async for x in self.chunks(reader)])
3458 writer.close()
3459 self.server.close() # The test server processes a single client only
3460
3461 async def asyncSetUp(self):
3462 self.server_buffer = b''
3463 self.server = await asyncio.start_server(self.handle_new_client,
3464 socket_helper.HOSTv4)
3465 server_name = self.server.sockets[0].getsockname()
3466 self.client = socket.socket()
3467 self.client.setblocking(False)
3468 await asyncio.get_running_loop().sock_connect(self.client, server_name)
3469 self.sockno = self.client.fileno()
3470 self.file = open(os_helper.TESTFN, 'rb')
3471 self.fileno = self.file.fileno()
3472
3473 async def asyncTearDown(self):
3474 self.file.close()
3475 self.client.close()
3476 await self.server.wait_closed()
3477
3478 # Use the test subject instead of asyncio.loop.sendfile
3479 @staticmethod
3480 async def async_sendfile(*args, **kwargs):
3481 return await asyncio.to_thread(os.sendfile, *args, **kwargs)
3482
3483 @staticmethod
3484 async def sendfile_wrapper(*args, **kwargs):
3485 """A higher level wrapper representing how an application is
3486 supposed to use sendfile().
3487 """
3488 while True:
3489 try:
3490 return await TestSendfile.async_sendfile(*args, **kwargs)
3491 except OSError as err:
3492 if err.errno == errno.ECONNRESET:
3493 # disconnected
3494 raise
3495 elif err.errno in (errno.EAGAIN, errno.EBUSY):
3496 # we have to retry send data
3497 continue
3498 else:
3499 raise
3500
3501 async def test_send_whole_file(self):
3502 # normal send
3503 total_sent = 0
3504 offset = 0
3505 nbytes = 4096
3506 while total_sent < len(self.DATA):
3507 sent = await self.sendfile_wrapper(self.sockno, self.fileno,
3508 offset, nbytes)
3509 if sent == 0:
3510 break
3511 offset += sent
3512 total_sent += sent
3513 self.assertTrue(sent <= nbytes)
3514 self.assertEqual(offset, total_sent)
3515
3516 self.assertEqual(total_sent, len(self.DATA))
3517 self.client.shutdown(socket.SHUT_RDWR)
3518 self.client.close()
3519 await self.server.wait_closed()
3520 self.assertEqual(len(self.server_buffer), len(self.DATA))
3521 self.assertEqual(self.server_buffer, self.DATA)
3522
3523 async def test_send_at_certain_offset(self):
3524 # start sending a file at a certain offset
3525 total_sent = 0
3526 offset = len(self.DATA) // 2
3527 must_send = len(self.DATA) - offset
3528 nbytes = 4096
3529 while total_sent < must_send:
3530 sent = await self.sendfile_wrapper(self.sockno, self.fileno,
3531 offset, nbytes)
3532 if sent == 0:
3533 break
3534 offset += sent
3535 total_sent += sent
3536 self.assertTrue(sent <= nbytes)
3537
3538 self.client.shutdown(socket.SHUT_RDWR)
3539 self.client.close()
3540 await self.server.wait_closed()
3541 expected = self.DATA[len(self.DATA) // 2:]
3542 self.assertEqual(total_sent, len(expected))
3543 self.assertEqual(len(self.server_buffer), len(expected))
3544 self.assertEqual(self.server_buffer, expected)
3545
3546 async def test_offset_overflow(self):
3547 # specify an offset > file size
3548 offset = len(self.DATA) + 4096
3549 try:
3550 sent = await self.async_sendfile(self.sockno, self.fileno,
3551 offset, 4096)
3552 except OSError as e:
3553 # Solaris can raise EINVAL if offset >= file length, ignore.
3554 if e.errno != errno.EINVAL:
3555 raise
3556 else:
3557 self.assertEqual(sent, 0)
3558 self.client.shutdown(socket.SHUT_RDWR)
3559 self.client.close()
3560 await self.server.wait_closed()
3561 self.assertEqual(self.server_buffer, b'')
3562
3563 async def test_invalid_offset(self):
3564 with self.assertRaises(OSError) as cm:
3565 await self.async_sendfile(self.sockno, self.fileno, -1, 4096)
3566 self.assertEqual(cm.exception.errno, errno.EINVAL)
3567
3568 async def test_keywords(self):
3569 # Keyword arguments should be supported
3570 await self.async_sendfile(out_fd=self.sockno, in_fd=self.fileno,
3571 offset=0, count=4096)
3572 if self.SUPPORT_HEADERS_TRAILERS:
3573 await self.async_sendfile(out_fd=self.sockno, in_fd=self.fileno,
3574 offset=0, count=4096,
3575 headers=(), trailers=(), flags=0)
3576
3577 # --- headers / trailers tests
3578
3579 @requires_headers_trailers
3580 async def test_headers(self):
3581 total_sent = 0
3582 expected_data = b"x" * 512 + b"y" * 256 + self.DATA[:-1]
3583 sent = await self.async_sendfile(self.sockno, self.fileno, 0, 4096,
3584 headers=[b"x" * 512, b"y" * 256])
3585 self.assertLessEqual(sent, 512 + 256 + 4096)
3586 total_sent += sent
3587 offset = 4096
3588 while total_sent < len(expected_data):
3589 nbytes = min(len(expected_data) - total_sent, 4096)
3590 sent = await self.sendfile_wrapper(self.sockno, self.fileno,
3591 offset, nbytes)
3592 if sent == 0:
3593 break
3594 self.assertLessEqual(sent, nbytes)
3595 total_sent += sent
3596 offset += sent
3597
3598 self.assertEqual(total_sent, len(expected_data))
3599 self.client.close()
3600 await self.server.wait_closed()
3601 self.assertEqual(hash(self.server_buffer), hash(expected_data))
3602
3603 @requires_headers_trailers
3604 async def test_trailers(self):
3605 TESTFN2 = os_helper.TESTFN + "2"
3606 file_data = b"abcdef"
3607
3608 self.addCleanup(os_helper.unlink, TESTFN2)
3609 create_file(TESTFN2, file_data)
3610
3611 with open(TESTFN2, 'rb') as f:
3612 await self.async_sendfile(self.sockno, f.fileno(), 0, 5,
3613 trailers=[b"123456", b"789"])
3614 self.client.close()
3615 await self.server.wait_closed()
3616 self.assertEqual(self.server_buffer, b"abcde123456789")
3617
3618 @requires_headers_trailers
3619 @requires_32b
3620 async def test_headers_overflow_32bits(self):
3621 self.server.handler_instance.accumulate = False
3622 with self.assertRaises(OSError) as cm:
3623 await self.async_sendfile(self.sockno, self.fileno, 0, 0,
3624 headers=[b"x" * 2**16] * 2**15)
3625 self.assertEqual(cm.exception.errno, errno.EINVAL)
3626
3627 @requires_headers_trailers
3628 @requires_32b
3629 async def test_trailers_overflow_32bits(self):
3630 self.server.handler_instance.accumulate = False
3631 with self.assertRaises(OSError) as cm:
3632 await self.async_sendfile(self.sockno, self.fileno, 0, 0,
3633 trailers=[b"x" * 2**16] * 2**15)
3634 self.assertEqual(cm.exception.errno, errno.EINVAL)
3635
3636 @requires_headers_trailers
3637 @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
3638 'test needs os.SF_NODISKIO')
3639 async def test_flags(self):
3640 try:
3641 await self.async_sendfile(self.sockno, self.fileno, 0, 4096,
3642 flags=os.SF_NODISKIO)
3643 except OSError as err:
3644 if err.errno not in (errno.EBUSY, errno.EAGAIN):
3645 raise
3646
3647
3648 def supports_extended_attributes():
3649 if not hasattr(os, "setxattr"):
3650 return False
3651
3652 try:
3653 with open(os_helper.TESTFN, "xb", 0) as fp:
3654 try:
3655 os.setxattr(fp.fileno(), b"user.test", b"")
3656 except OSError:
3657 return False
3658 finally:
3659 os_helper.unlink(os_helper.TESTFN)
3660
3661 return True
3662
3663
3664 @unittest.skipUnless(supports_extended_attributes(),
3665 "no non-broken extended attribute support")
3666 # Kernels < 2.6.39 don't respect setxattr flags.
3667 @support.requires_linux_version(2, 6, 39)
3668 class ExtendedAttributeTests(unittest.TestCase):
3669
3670 def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
3671 fn = os_helper.TESTFN
3672 self.addCleanup(os_helper.unlink, fn)
3673 create_file(fn)
3674
3675 with self.assertRaises(OSError) as cm:
3676 getxattr(fn, s("user.test"), **kwargs)
3677 self.assertEqual(cm.exception.errno, errno.ENODATA)
3678
3679 init_xattr = listxattr(fn)
3680 self.assertIsInstance(init_xattr, list)
3681
3682 setxattr(fn, s("user.test"), b"", **kwargs)
3683 xattr = set(init_xattr)
3684 xattr.add("user.test")
3685 self.assertEqual(set(listxattr(fn)), xattr)
3686 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
3687 setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
3688 self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
3689
3690 with self.assertRaises(OSError) as cm:
3691 setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
3692 self.assertEqual(cm.exception.errno, errno.EEXIST)
3693
3694 with self.assertRaises(OSError) as cm:
3695 setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
3696 self.assertEqual(cm.exception.errno, errno.ENODATA)
3697
3698 setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
3699 xattr.add("user.test2")
3700 self.assertEqual(set(listxattr(fn)), xattr)
3701 removexattr(fn, s("user.test"), **kwargs)
3702
3703 with self.assertRaises(OSError) as cm:
3704 getxattr(fn, s("user.test"), **kwargs)
3705 self.assertEqual(cm.exception.errno, errno.ENODATA)
3706
3707 xattr.remove("user.test")
3708 self.assertEqual(set(listxattr(fn)), xattr)
3709 self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
3710 setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
3711 self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
3712 removexattr(fn, s("user.test"), **kwargs)
3713 many = sorted("user.test{}".format(i) for i in range(100))
3714 for thing in many:
3715 setxattr(fn, thing, b"x", **kwargs)
3716 self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
3717
3718 def _check_xattrs(self, *args, **kwargs):
3719 self._check_xattrs_str(str, *args, **kwargs)
3720 os_helper.unlink(os_helper.TESTFN)
3721
3722 self._check_xattrs_str(os.fsencode, *args, **kwargs)
3723 os_helper.unlink(os_helper.TESTFN)
3724
3725 def test_simple(self):
3726 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3727 os.listxattr)
3728
3729 def test_lpath(self):
3730 self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
3731 os.listxattr, follow_symlinks=False)
3732
3733 def test_fds(self):
3734 def getxattr(path, *args):
3735 with open(path, "rb") as fp:
3736 return os.getxattr(fp.fileno(), *args)
3737 def setxattr(path, *args):
3738 with open(path, "wb", 0) as fp:
3739 os.setxattr(fp.fileno(), *args)
3740 def removexattr(path, *args):
3741 with open(path, "wb", 0) as fp:
3742 os.removexattr(fp.fileno(), *args)
3743 def listxattr(path, *args):
3744 with open(path, "rb") as fp:
3745 return os.listxattr(fp.fileno(), *args)
3746 self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
3747
3748
3749 @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
3750 class TermsizeTests(unittest.TestCase):
3751 def test_does_not_crash(self):
3752 """Check if get_terminal_size() returns a meaningful value.
3753
3754 There's no easy portable way to actually check the size of the
3755 terminal, so let's check if it returns something sensible instead.
3756 """
3757 try:
3758 size = os.get_terminal_size()
3759 except OSError as e:
3760 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
3761 # Under win32 a generic OSError can be thrown if the
3762 # handle cannot be retrieved
3763 self.skipTest("failed to query terminal size")
3764 raise
3765
3766 self.assertGreaterEqual(size.columns, 0)
3767 self.assertGreaterEqual(size.lines, 0)
3768
3769 def test_stty_match(self):
3770 """Check if stty returns the same results
3771
3772 stty actually tests stdin, so get_terminal_size is invoked on
3773 stdin explicitly. If stty succeeded, then get_terminal_size()
3774 should work too.
3775 """
3776 try:
3777 size = (
3778 subprocess.check_output(
3779 ["stty", "size"], stderr=subprocess.DEVNULL, text=True
3780 ).split()
3781 )
3782 except (FileNotFoundError, subprocess.CalledProcessError,
3783 PermissionError):
3784 self.skipTest("stty invocation failed")
3785 expected = (int(size[1]), int(size[0])) # reversed order
3786
3787 try:
3788 actual = os.get_terminal_size(sys.__stdin__.fileno())
3789 except OSError as e:
3790 if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
3791 # Under win32 a generic OSError can be thrown if the
3792 # handle cannot be retrieved
3793 self.skipTest("failed to query terminal size")
3794 raise
3795 self.assertEqual(expected, actual)
3796
3797
3798 @unittest.skipUnless(hasattr(os, 'memfd_create'), 'requires os.memfd_create')
3799 @support.requires_linux_version(3, 17)
3800 class MemfdCreateTests(unittest.TestCase):
3801 def test_memfd_create(self):
3802 fd = os.memfd_create("Hi", os.MFD_CLOEXEC)
3803 self.assertNotEqual(fd, -1)
3804 self.addCleanup(os.close, fd)
3805 self.assertFalse(os.get_inheritable(fd))
3806 with open(fd, "wb", closefd=False) as f:
3807 f.write(b'memfd_create')
3808 self.assertEqual(f.tell(), 12)
3809
3810 fd2 = os.memfd_create("Hi")
3811 self.addCleanup(os.close, fd2)
3812 self.assertFalse(os.get_inheritable(fd2))
3813
3814
3815 @unittest.skipUnless(hasattr(os, 'eventfd'), 'requires os.eventfd')
3816 @support.requires_linux_version(2, 6, 30)
3817 class EventfdTests(unittest.TestCase):
3818 def test_eventfd_initval(self):
3819 def pack(value):
3820 """Pack as native uint64_t
3821 """
3822 return struct.pack("@Q", value)
3823 size = 8 # read/write 8 bytes
3824 initval = 42
3825 fd = os.eventfd(initval)
3826 self.assertNotEqual(fd, -1)
3827 self.addCleanup(os.close, fd)
3828 self.assertFalse(os.get_inheritable(fd))
3829
3830 # test with raw read/write
3831 res = os.read(fd, size)
3832 self.assertEqual(res, pack(initval))
3833
3834 os.write(fd, pack(23))
3835 res = os.read(fd, size)
3836 self.assertEqual(res, pack(23))
3837
3838 os.write(fd, pack(40))
3839 os.write(fd, pack(2))
3840 res = os.read(fd, size)
3841 self.assertEqual(res, pack(42))
3842
3843 # test with eventfd_read/eventfd_write
3844 os.eventfd_write(fd, 20)
3845 os.eventfd_write(fd, 3)
3846 res = os.eventfd_read(fd)
3847 self.assertEqual(res, 23)
3848
3849 def test_eventfd_semaphore(self):
3850 initval = 2
3851 flags = os.EFD_CLOEXEC | os.EFD_SEMAPHORE | os.EFD_NONBLOCK
3852 fd = os.eventfd(initval, flags)
3853 self.assertNotEqual(fd, -1)
3854 self.addCleanup(os.close, fd)
3855
3856 # semaphore starts has initval 2, two reads return '1'
3857 res = os.eventfd_read(fd)
3858 self.assertEqual(res, 1)
3859 res = os.eventfd_read(fd)
3860 self.assertEqual(res, 1)
3861 # third read would block
3862 with self.assertRaises(BlockingIOError):
3863 os.eventfd_read(fd)
3864 with self.assertRaises(BlockingIOError):
3865 os.read(fd, 8)
3866
3867 # increase semaphore counter, read one
3868 os.eventfd_write(fd, 1)
3869 res = os.eventfd_read(fd)
3870 self.assertEqual(res, 1)
3871 # next read would block, too
3872 with self.assertRaises(BlockingIOError):
3873 os.eventfd_read(fd)
3874
3875 def test_eventfd_select(self):
3876 flags = os.EFD_CLOEXEC | os.EFD_NONBLOCK
3877 fd = os.eventfd(0, flags)
3878 self.assertNotEqual(fd, -1)
3879 self.addCleanup(os.close, fd)
3880
3881 # counter is zero, only writeable
3882 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
3883 self.assertEqual((rfd, wfd, xfd), ([], [fd], []))
3884
3885 # counter is non-zero, read and writeable
3886 os.eventfd_write(fd, 23)
3887 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
3888 self.assertEqual((rfd, wfd, xfd), ([fd], [fd], []))
3889 self.assertEqual(os.eventfd_read(fd), 23)
3890
3891 # counter at max, only readable
3892 os.eventfd_write(fd, (2**64) - 2)
3893 rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
3894 self.assertEqual((rfd, wfd, xfd), ([fd], [], []))
3895 os.eventfd_read(fd)
3896
3897
3898 class OSErrorTests(unittest.TestCase):
3899 def setUp(self):
3900 class Str(str):
3901 pass
3902
3903 self.bytes_filenames = []
3904 self.unicode_filenames = []
3905 if os_helper.TESTFN_UNENCODABLE is not None:
3906 decoded = os_helper.TESTFN_UNENCODABLE
3907 else:
3908 decoded = os_helper.TESTFN
3909 self.unicode_filenames.append(decoded)
3910 self.unicode_filenames.append(Str(decoded))
3911 if os_helper.TESTFN_UNDECODABLE is not None:
3912 encoded = os_helper.TESTFN_UNDECODABLE
3913 else:
3914 encoded = os.fsencode(os_helper.TESTFN)
3915 self.bytes_filenames.append(encoded)
3916 self.bytes_filenames.append(bytearray(encoded))
3917 self.bytes_filenames.append(memoryview(encoded))
3918
3919 self.filenames = self.bytes_filenames + self.unicode_filenames
3920
3921 def test_oserror_filename(self):
3922 funcs = [
3923 (self.filenames, os.chdir,),
3924 (self.filenames, os.lstat,),
3925 (self.filenames, os.open, os.O_RDONLY),
3926 (self.filenames, os.rmdir,),
3927 (self.filenames, os.stat,),
3928 (self.filenames, os.unlink,),
3929 ]
3930 if sys.platform == "win32":
3931 funcs.extend((
3932 (self.bytes_filenames, os.rename, b"dst"),
3933 (self.bytes_filenames, os.replace, b"dst"),
3934 (self.unicode_filenames, os.rename, "dst"),
3935 (self.unicode_filenames, os.replace, "dst"),
3936 (self.unicode_filenames, os.listdir, ),
3937 ))
3938 else:
3939 funcs.extend((
3940 (self.filenames, os.listdir,),
3941 (self.filenames, os.rename, "dst"),
3942 (self.filenames, os.replace, "dst"),
3943 ))
3944 if os_helper.can_chmod():
3945 funcs.append((self.filenames, os.chmod, 0o777))
3946 if hasattr(os, "chown"):
3947 funcs.append((self.filenames, os.chown, 0, 0))
3948 if hasattr(os, "lchown"):
3949 funcs.append((self.filenames, os.lchown, 0, 0))
3950 if hasattr(os, "truncate"):
3951 funcs.append((self.filenames, os.truncate, 0))
3952 if hasattr(os, "chflags"):
3953 funcs.append((self.filenames, os.chflags, 0))
3954 if hasattr(os, "lchflags"):
3955 funcs.append((self.filenames, os.lchflags, 0))
3956 if hasattr(os, "chroot"):
3957 funcs.append((self.filenames, os.chroot,))
3958 if hasattr(os, "link"):
3959 if sys.platform == "win32":
3960 funcs.append((self.bytes_filenames, os.link, b"dst"))
3961 funcs.append((self.unicode_filenames, os.link, "dst"))
3962 else:
3963 funcs.append((self.filenames, os.link, "dst"))
3964 if hasattr(os, "listxattr"):
3965 funcs.extend((
3966 (self.filenames, os.listxattr,),
3967 (self.filenames, os.getxattr, "user.test"),
3968 (self.filenames, os.setxattr, "user.test", b'user'),
3969 (self.filenames, os.removexattr, "user.test"),
3970 ))
3971 if hasattr(os, "lchmod"):
3972 funcs.append((self.filenames, os.lchmod, 0o777))
3973 if hasattr(os, "readlink"):
3974 funcs.append((self.filenames, os.readlink,))
3975
3976
3977 for filenames, func, *func_args in funcs:
3978 for name in filenames:
3979 try:
3980 if isinstance(name, (str, bytes)):
3981 func(name, *func_args)
3982 else:
3983 with self.assertWarnsRegex(DeprecationWarning, 'should be'):
3984 func(name, *func_args)
3985 except OSError as err:
3986 self.assertIs(err.filename, name, str(func))
3987 except UnicodeDecodeError:
3988 pass
3989 else:
3990 self.fail("No exception thrown by {}".format(func))
3991
3992 class CPUCountTests(unittest.TestCase):
3993 def test_cpu_count(self):
3994 cpus = os.cpu_count()
3995 if cpus is not None:
3996 self.assertIsInstance(cpus, int)
3997 self.assertGreater(cpus, 0)
3998 else:
3999 self.skipTest("Could not determine the number of CPUs")
4000
4001
4002 # FD inheritance check is only useful for systems with process support.
4003 @support.requires_subprocess()
4004 class FDInheritanceTests(unittest.TestCase):
4005 def test_get_set_inheritable(self):
4006 fd = os.open(__file__, os.O_RDONLY)
4007 self.addCleanup(os.close, fd)
4008 self.assertEqual(os.get_inheritable(fd), False)
4009
4010 os.set_inheritable(fd, True)
4011 self.assertEqual(os.get_inheritable(fd), True)
4012
4013 @unittest.skipIf(fcntl is None, "need fcntl")
4014 def test_get_inheritable_cloexec(self):
4015 fd = os.open(__file__, os.O_RDONLY)
4016 self.addCleanup(os.close, fd)
4017 self.assertEqual(os.get_inheritable(fd), False)
4018
4019 # clear FD_CLOEXEC flag
4020 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
4021 flags &= ~fcntl.FD_CLOEXEC
4022 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
4023
4024 self.assertEqual(os.get_inheritable(fd), True)
4025
4026 @unittest.skipIf(fcntl is None, "need fcntl")
4027 def test_set_inheritable_cloexec(self):
4028 fd = os.open(__file__, os.O_RDONLY)
4029 self.addCleanup(os.close, fd)
4030 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4031 fcntl.FD_CLOEXEC)
4032
4033 os.set_inheritable(fd, True)
4034 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4035 0)
4036
4037 @unittest.skipUnless(hasattr(os, 'O_PATH'), "need os.O_PATH")
4038 def test_get_set_inheritable_o_path(self):
4039 fd = os.open(__file__, os.O_PATH)
4040 self.addCleanup(os.close, fd)
4041 self.assertEqual(os.get_inheritable(fd), False)
4042
4043 os.set_inheritable(fd, True)
4044 self.assertEqual(os.get_inheritable(fd), True)
4045
4046 os.set_inheritable(fd, False)
4047 self.assertEqual(os.get_inheritable(fd), False)
4048
4049 def test_get_set_inheritable_badf(self):
4050 fd = os_helper.make_bad_fd()
4051
4052 with self.assertRaises(OSError) as ctx:
4053 os.get_inheritable(fd)
4054 self.assertEqual(ctx.exception.errno, errno.EBADF)
4055
4056 with self.assertRaises(OSError) as ctx:
4057 os.set_inheritable(fd, True)
4058 self.assertEqual(ctx.exception.errno, errno.EBADF)
4059
4060 with self.assertRaises(OSError) as ctx:
4061 os.set_inheritable(fd, False)
4062 self.assertEqual(ctx.exception.errno, errno.EBADF)
4063
4064 def test_open(self):
4065 fd = os.open(__file__, os.O_RDONLY)
4066 self.addCleanup(os.close, fd)
4067 self.assertEqual(os.get_inheritable(fd), False)
4068
4069 @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
4070 def test_pipe(self):
4071 rfd, wfd = os.pipe()
4072 self.addCleanup(os.close, rfd)
4073 self.addCleanup(os.close, wfd)
4074 self.assertEqual(os.get_inheritable(rfd), False)
4075 self.assertEqual(os.get_inheritable(wfd), False)
4076
4077 def test_dup(self):
4078 fd1 = os.open(__file__, os.O_RDONLY)
4079 self.addCleanup(os.close, fd1)
4080
4081 fd2 = os.dup(fd1)
4082 self.addCleanup(os.close, fd2)
4083 self.assertEqual(os.get_inheritable(fd2), False)
4084
4085 def test_dup_standard_stream(self):
4086 fd = os.dup(1)
4087 self.addCleanup(os.close, fd)
4088 self.assertGreater(fd, 0)
4089
4090 @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
4091 def test_dup_nul(self):
4092 # os.dup() was creating inheritable fds for character files.
4093 fd1 = os.open('NUL', os.O_RDONLY)
4094 self.addCleanup(os.close, fd1)
4095 fd2 = os.dup(fd1)
4096 self.addCleanup(os.close, fd2)
4097 self.assertFalse(os.get_inheritable(fd2))
4098
4099 @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
4100 def test_dup2(self):
4101 fd = os.open(__file__, os.O_RDONLY)
4102 self.addCleanup(os.close, fd)
4103
4104 # inheritable by default
4105 fd2 = os.open(__file__, os.O_RDONLY)
4106 self.addCleanup(os.close, fd2)
4107 self.assertEqual(os.dup2(fd, fd2), fd2)
4108 self.assertTrue(os.get_inheritable(fd2))
4109
4110 # force non-inheritable
4111 fd3 = os.open(__file__, os.O_RDONLY)
4112 self.addCleanup(os.close, fd3)
4113 self.assertEqual(os.dup2(fd, fd3, inheritable=False), fd3)
4114 self.assertFalse(os.get_inheritable(fd3))
4115
4116 @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
4117 def test_openpty(self):
4118 master_fd, slave_fd = os.openpty()
4119 self.addCleanup(os.close, master_fd)
4120 self.addCleanup(os.close, slave_fd)
4121 self.assertEqual(os.get_inheritable(master_fd), False)
4122 self.assertEqual(os.get_inheritable(slave_fd), False)
4123
4124
4125 class PathTConverterTests(unittest.TestCase):
4126 # tuples of (function name, allows fd arguments, additional arguments to
4127 # function, cleanup function)
4128 functions = [
4129 ('stat', True, (), None),
4130 ('lstat', False, (), None),
4131 ('access', False, (os.F_OK,), None),
4132 ('chflags', False, (0,), None),
4133 ('lchflags', False, (0,), None),
4134 ('open', False, (os.O_RDONLY,), getattr(os, 'close', None)),
4135 ]
4136
4137 def test_path_t_converter(self):
4138 str_filename = os_helper.TESTFN
4139 if os.name == 'nt':
4140 bytes_fspath = bytes_filename = None
4141 else:
4142 bytes_filename = os.fsencode(os_helper.TESTFN)
4143 bytes_fspath = FakePath(bytes_filename)
4144 fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT)
4145 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
4146 self.addCleanup(os.close, fd)
4147
4148 int_fspath = FakePath(fd)
4149 str_fspath = FakePath(str_filename)
4150
4151 for name, allow_fd, extra_args, cleanup_fn in self.functions:
4152 with self.subTest(name=name):
4153 try:
4154 fn = getattr(os, name)
4155 except AttributeError:
4156 continue
4157
4158 for path in (str_filename, bytes_filename, str_fspath,
4159 bytes_fspath):
4160 if path is None:
4161 continue
4162 with self.subTest(name=name, path=path):
4163 result = fn(path, *extra_args)
4164 if cleanup_fn is not None:
4165 cleanup_fn(result)
4166
4167 with self.assertRaisesRegex(
4168 TypeError, 'to return str or bytes'):
4169 fn(int_fspath, *extra_args)
4170
4171 if allow_fd:
4172 result = fn(fd, *extra_args) # should not fail
4173 if cleanup_fn is not None:
4174 cleanup_fn(result)
4175 else:
4176 with self.assertRaisesRegex(
4177 TypeError,
4178 'os.PathLike'):
4179 fn(fd, *extra_args)
4180
4181 def test_path_t_converter_and_custom_class(self):
4182 msg = r'__fspath__\(\) to return str or bytes, not %s'
4183 with self.assertRaisesRegex(TypeError, msg % r'int'):
4184 os.stat(FakePath(2))
4185 with self.assertRaisesRegex(TypeError, msg % r'float'):
4186 os.stat(FakePath(2.34))
4187 with self.assertRaisesRegex(TypeError, msg % r'object'):
4188 os.stat(FakePath(object()))
4189
4190
4191 @unittest.skipUnless(hasattr(os, 'get_blocking'),
4192 'needs os.get_blocking() and os.set_blocking()')
4193 @unittest.skipIf(support.is_emscripten, "Cannot unset blocking flag")
4194 class BlockingTests(unittest.TestCase):
4195 def test_blocking(self):
4196 fd = os.open(__file__, os.O_RDONLY)
4197 self.addCleanup(os.close, fd)
4198 self.assertEqual(os.get_blocking(fd), True)
4199
4200 os.set_blocking(fd, False)
4201 self.assertEqual(os.get_blocking(fd), False)
4202
4203 os.set_blocking(fd, True)
4204 self.assertEqual(os.get_blocking(fd), True)
4205
4206
4207
4208 class ExportsTests(unittest.TestCase):
4209 def test_os_all(self):
4210 self.assertIn('open', os.__all__)
4211 self.assertIn('walk', os.__all__)
4212
4213
4214 class TestDirEntry(unittest.TestCase):
4215 def setUp(self):
4216 self.path = os.path.realpath(os_helper.TESTFN)
4217 self.addCleanup(os_helper.rmtree, self.path)
4218 os.mkdir(self.path)
4219
4220 def test_uninstantiable(self):
4221 self.assertRaises(TypeError, os.DirEntry)
4222
4223 def test_unpickable(self):
4224 filename = create_file(os.path.join(self.path, "file.txt"), b'python')
4225 entry = [entry for entry in os.scandir(self.path)].pop()
4226 self.assertIsInstance(entry, os.DirEntry)
4227 self.assertEqual(entry.name, "file.txt")
4228 import pickle
4229 self.assertRaises(TypeError, pickle.dumps, entry, filename)
4230
4231
4232 class TestScandir(unittest.TestCase):
4233 check_no_resource_warning = warnings_helper.check_no_resource_warning
4234
4235 def setUp(self):
4236 self.path = os.path.realpath(os_helper.TESTFN)
4237 self.bytes_path = os.fsencode(self.path)
4238 self.addCleanup(os_helper.rmtree, self.path)
4239 os.mkdir(self.path)
4240
4241 def create_file(self, name="file.txt"):
4242 path = self.bytes_path if isinstance(name, bytes) else self.path
4243 filename = os.path.join(path, name)
4244 create_file(filename, b'python')
4245 return filename
4246
4247 def get_entries(self, names):
4248 entries = dict((entry.name, entry)
4249 for entry in os.scandir(self.path))
4250 self.assertEqual(sorted(entries.keys()), names)
4251 return entries
4252
4253 def assert_stat_equal(self, stat1, stat2, skip_fields):
4254 if skip_fields:
4255 for attr in dir(stat1):
4256 if not attr.startswith("st_"):
4257 continue
4258 if attr in ("st_dev", "st_ino", "st_nlink"):
4259 continue
4260 self.assertEqual(getattr(stat1, attr),
4261 getattr(stat2, attr),
4262 (stat1, stat2, attr))
4263 else:
4264 self.assertEqual(stat1, stat2)
4265
4266 def test_uninstantiable(self):
4267 scandir_iter = os.scandir(self.path)
4268 self.assertRaises(TypeError, type(scandir_iter))
4269 scandir_iter.close()
4270
4271 def test_unpickable(self):
4272 filename = self.create_file("file.txt")
4273 scandir_iter = os.scandir(self.path)
4274 import pickle
4275 self.assertRaises(TypeError, pickle.dumps, scandir_iter, filename)
4276 scandir_iter.close()
4277
4278 def check_entry(self, entry, name, is_dir, is_file, is_symlink):
4279 self.assertIsInstance(entry, os.DirEntry)
4280 self.assertEqual(entry.name, name)
4281 self.assertEqual(entry.path, os.path.join(self.path, name))
4282 self.assertEqual(entry.inode(),
4283 os.stat(entry.path, follow_symlinks=False).st_ino)
4284
4285 entry_stat = os.stat(entry.path)
4286 self.assertEqual(entry.is_dir(),
4287 stat.S_ISDIR(entry_stat.st_mode))
4288 self.assertEqual(entry.is_file(),
4289 stat.S_ISREG(entry_stat.st_mode))
4290 self.assertEqual(entry.is_symlink(),
4291 os.path.islink(entry.path))
4292
4293 entry_lstat = os.stat(entry.path, follow_symlinks=False)
4294 self.assertEqual(entry.is_dir(follow_symlinks=False),
4295 stat.S_ISDIR(entry_lstat.st_mode))
4296 self.assertEqual(entry.is_file(follow_symlinks=False),
4297 stat.S_ISREG(entry_lstat.st_mode))
4298
4299 self.assert_stat_equal(entry.stat(),
4300 entry_stat,
4301 os.name == 'nt' and not is_symlink)
4302 self.assert_stat_equal(entry.stat(follow_symlinks=False),
4303 entry_lstat,
4304 os.name == 'nt')
4305
4306 def test_attributes(self):
4307 link = hasattr(os, 'link')
4308 symlink = os_helper.can_symlink()
4309
4310 dirname = os.path.join(self.path, "dir")
4311 os.mkdir(dirname)
4312 filename = self.create_file("file.txt")
4313 if link:
4314 try:
4315 os.link(filename, os.path.join(self.path, "link_file.txt"))
4316 except PermissionError as e:
4317 self.skipTest('os.link(): %s' % e)
4318 if symlink:
4319 os.symlink(dirname, os.path.join(self.path, "symlink_dir"),
4320 target_is_directory=True)
4321 os.symlink(filename, os.path.join(self.path, "symlink_file.txt"))
4322
4323 names = ['dir', 'file.txt']
4324 if link:
4325 names.append('link_file.txt')
4326 if symlink:
4327 names.extend(('symlink_dir', 'symlink_file.txt'))
4328 entries = self.get_entries(names)
4329
4330 entry = entries['dir']
4331 self.check_entry(entry, 'dir', True, False, False)
4332
4333 entry = entries['file.txt']
4334 self.check_entry(entry, 'file.txt', False, True, False)
4335
4336 if link:
4337 entry = entries['link_file.txt']
4338 self.check_entry(entry, 'link_file.txt', False, True, False)
4339
4340 if symlink:
4341 entry = entries['symlink_dir']
4342 self.check_entry(entry, 'symlink_dir', True, False, True)
4343
4344 entry = entries['symlink_file.txt']
4345 self.check_entry(entry, 'symlink_file.txt', False, True, True)
4346
4347 def get_entry(self, name):
4348 path = self.bytes_path if isinstance(name, bytes) else self.path
4349 entries = list(os.scandir(path))
4350 self.assertEqual(len(entries), 1)
4351
4352 entry = entries[0]
4353 self.assertEqual(entry.name, name)
4354 return entry
4355
4356 def create_file_entry(self, name='file.txt'):
4357 filename = self.create_file(name=name)
4358 return self.get_entry(os.path.basename(filename))
4359
4360 def test_current_directory(self):
4361 filename = self.create_file()
4362 old_dir = os.getcwd()
4363 try:
4364 os.chdir(self.path)
4365
4366 # call scandir() without parameter: it must list the content
4367 # of the current directory
4368 entries = dict((entry.name, entry) for entry in os.scandir())
4369 self.assertEqual(sorted(entries.keys()),
4370 [os.path.basename(filename)])
4371 finally:
4372 os.chdir(old_dir)
4373
4374 def test_repr(self):
4375 entry = self.create_file_entry()
4376 self.assertEqual(repr(entry), "<DirEntry 'file.txt'>")
4377
4378 def test_fspath_protocol(self):
4379 entry = self.create_file_entry()
4380 self.assertEqual(os.fspath(entry), os.path.join(self.path, 'file.txt'))
4381
4382 def test_fspath_protocol_bytes(self):
4383 bytes_filename = os.fsencode('bytesfile.txt')
4384 bytes_entry = self.create_file_entry(name=bytes_filename)
4385 fspath = os.fspath(bytes_entry)
4386 self.assertIsInstance(fspath, bytes)
4387 self.assertEqual(fspath,
4388 os.path.join(os.fsencode(self.path),bytes_filename))
4389
4390 def test_removed_dir(self):
4391 path = os.path.join(self.path, 'dir')
4392
4393 os.mkdir(path)
4394 entry = self.get_entry('dir')
4395 os.rmdir(path)
4396
4397 # On POSIX, is_dir() result depends if scandir() filled d_type or not
4398 if os.name == 'nt':
4399 self.assertTrue(entry.is_dir())
4400 self.assertFalse(entry.is_file())
4401 self.assertFalse(entry.is_symlink())
4402 if os.name == 'nt':
4403 self.assertRaises(FileNotFoundError, entry.inode)
4404 # don't fail
4405 entry.stat()
4406 entry.stat(follow_symlinks=False)
4407 else:
4408 self.assertGreater(entry.inode(), 0)
4409 self.assertRaises(FileNotFoundError, entry.stat)
4410 self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False)
4411
4412 def test_removed_file(self):
4413 entry = self.create_file_entry()
4414 os.unlink(entry.path)
4415
4416 self.assertFalse(entry.is_dir())
4417 # On POSIX, is_dir() result depends if scandir() filled d_type or not
4418 if os.name == 'nt':
4419 self.assertTrue(entry.is_file())
4420 self.assertFalse(entry.is_symlink())
4421 if os.name == 'nt':
4422 self.assertRaises(FileNotFoundError, entry.inode)
4423 # don't fail
4424 entry.stat()
4425 entry.stat(follow_symlinks=False)
4426 else:
4427 self.assertGreater(entry.inode(), 0)
4428 self.assertRaises(FileNotFoundError, entry.stat)
4429 self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False)
4430
4431 def test_broken_symlink(self):
4432 if not os_helper.can_symlink():
4433 return self.skipTest('cannot create symbolic link')
4434
4435 filename = self.create_file("file.txt")
4436 os.symlink(filename,
4437 os.path.join(self.path, "symlink.txt"))
4438 entries = self.get_entries(['file.txt', 'symlink.txt'])
4439 entry = entries['symlink.txt']
4440 os.unlink(filename)
4441
4442 self.assertGreater(entry.inode(), 0)
4443 self.assertFalse(entry.is_dir())
4444 self.assertFalse(entry.is_file()) # broken symlink returns False
4445 self.assertFalse(entry.is_dir(follow_symlinks=False))
4446 self.assertFalse(entry.is_file(follow_symlinks=False))
4447 self.assertTrue(entry.is_symlink())
4448 self.assertRaises(FileNotFoundError, entry.stat)
4449 # don't fail
4450 entry.stat(follow_symlinks=False)
4451
4452 def test_bytes(self):
4453 self.create_file("file.txt")
4454
4455 path_bytes = os.fsencode(self.path)
4456 entries = list(os.scandir(path_bytes))
4457 self.assertEqual(len(entries), 1, entries)
4458 entry = entries[0]
4459
4460 self.assertEqual(entry.name, b'file.txt')
4461 self.assertEqual(entry.path,
4462 os.fsencode(os.path.join(self.path, 'file.txt')))
4463
4464 def test_bytes_like(self):
4465 self.create_file("file.txt")
4466
4467 for cls in bytearray, memoryview:
4468 path_bytes = cls(os.fsencode(self.path))
4469 with self.assertWarns(DeprecationWarning):
4470 entries = list(os.scandir(path_bytes))
4471 self.assertEqual(len(entries), 1, entries)
4472 entry = entries[0]
4473
4474 self.assertEqual(entry.name, b'file.txt')
4475 self.assertEqual(entry.path,
4476 os.fsencode(os.path.join(self.path, 'file.txt')))
4477 self.assertIs(type(entry.name), bytes)
4478 self.assertIs(type(entry.path), bytes)
4479
4480 @unittest.skipUnless(os.listdir in os.supports_fd,
4481 'fd support for listdir required for this test.')
4482 def test_fd(self):
4483 self.assertIn(os.scandir, os.supports_fd)
4484 self.create_file('file.txt')
4485 expected_names = ['file.txt']
4486 if os_helper.can_symlink():
4487 os.symlink('file.txt', os.path.join(self.path, 'link'))
4488 expected_names.append('link')
4489
4490 with os_helper.open_dir_fd(self.path) as fd:
4491 with os.scandir(fd) as it:
4492 entries = list(it)
4493 names = [entry.name for entry in entries]
4494 self.assertEqual(sorted(names), expected_names)
4495 self.assertEqual(names, os.listdir(fd))
4496 for entry in entries:
4497 self.assertEqual(entry.path, entry.name)
4498 self.assertEqual(os.fspath(entry), entry.name)
4499 self.assertEqual(entry.is_symlink(), entry.name == 'link')
4500 if os.stat in os.supports_dir_fd:
4501 st = os.stat(entry.name, dir_fd=fd)
4502 self.assertEqual(entry.stat(), st)
4503 st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
4504 self.assertEqual(entry.stat(follow_symlinks=False), st)
4505
4506 @unittest.skipIf(support.is_wasi, "WASI maps '' to cwd")
4507 def test_empty_path(self):
4508 self.assertRaises(FileNotFoundError, os.scandir, '')
4509
4510 def test_consume_iterator_twice(self):
4511 self.create_file("file.txt")
4512 iterator = os.scandir(self.path)
4513
4514 entries = list(iterator)
4515 self.assertEqual(len(entries), 1, entries)
4516
4517 # check than consuming the iterator twice doesn't raise exception
4518 entries2 = list(iterator)
4519 self.assertEqual(len(entries2), 0, entries2)
4520
4521 def test_bad_path_type(self):
4522 for obj in [1.234, {}, []]:
4523 self.assertRaises(TypeError, os.scandir, obj)
4524
4525 def test_close(self):
4526 self.create_file("file.txt")
4527 self.create_file("file2.txt")
4528 iterator = os.scandir(self.path)
4529 next(iterator)
4530 iterator.close()
4531 # multiple closes
4532 iterator.close()
4533 with self.check_no_resource_warning():
4534 del iterator
4535
4536 def test_context_manager(self):
4537 self.create_file("file.txt")
4538 self.create_file("file2.txt")
4539 with os.scandir(self.path) as iterator:
4540 next(iterator)
4541 with self.check_no_resource_warning():
4542 del iterator
4543
4544 def test_context_manager_close(self):
4545 self.create_file("file.txt")
4546 self.create_file("file2.txt")
4547 with os.scandir(self.path) as iterator:
4548 next(iterator)
4549 iterator.close()
4550
4551 def test_context_manager_exception(self):
4552 self.create_file("file.txt")
4553 self.create_file("file2.txt")
4554 with self.assertRaises(ZeroDivisionError):
4555 with os.scandir(self.path) as iterator:
4556 next(iterator)
4557 1/0
4558 with self.check_no_resource_warning():
4559 del iterator
4560
4561 def test_resource_warning(self):
4562 self.create_file("file.txt")
4563 self.create_file("file2.txt")
4564 iterator = os.scandir(self.path)
4565 next(iterator)
4566 with self.assertWarns(ResourceWarning):
4567 del iterator
4568 support.gc_collect()
4569 # exhausted iterator
4570 iterator = os.scandir(self.path)
4571 list(iterator)
4572 with self.check_no_resource_warning():
4573 del iterator
4574
4575
4576 class TestPEP519(unittest.TestCase):
4577
4578 # Abstracted so it can be overridden to test pure Python implementation
4579 # if a C version is provided.
4580 fspath = staticmethod(os.fspath)
4581
4582 def test_return_bytes(self):
4583 for b in b'hello', b'goodbye', b'some/path/and/file':
4584 self.assertEqual(b, self.fspath(b))
4585
4586 def test_return_string(self):
4587 for s in 'hello', 'goodbye', 'some/path/and/file':
4588 self.assertEqual(s, self.fspath(s))
4589
4590 def test_fsencode_fsdecode(self):
4591 for p in "path/like/object", b"path/like/object":
4592 pathlike = FakePath(p)
4593
4594 self.assertEqual(p, self.fspath(pathlike))
4595 self.assertEqual(b"path/like/object", os.fsencode(pathlike))
4596 self.assertEqual("path/like/object", os.fsdecode(pathlike))
4597
4598 def test_pathlike(self):
4599 self.assertEqual('#feelthegil', self.fspath(FakePath('#feelthegil')))
4600 self.assertTrue(issubclass(FakePath, os.PathLike))
4601 self.assertTrue(isinstance(FakePath('x'), os.PathLike))
4602
4603 def test_garbage_in_exception_out(self):
4604 vapor = type('blah', (), {})
4605 for o in int, type, os, vapor():
4606 self.assertRaises(TypeError, self.fspath, o)
4607
4608 def test_argument_required(self):
4609 self.assertRaises(TypeError, self.fspath)
4610
4611 def test_bad_pathlike(self):
4612 # __fspath__ returns a value other than str or bytes.
4613 self.assertRaises(TypeError, self.fspath, FakePath(42))
4614 # __fspath__ attribute that is not callable.
4615 c = type('foo', (), {})
4616 c.__fspath__ = 1
4617 self.assertRaises(TypeError, self.fspath, c())
4618 # __fspath__ raises an exception.
4619 self.assertRaises(ZeroDivisionError, self.fspath,
4620 FakePath(ZeroDivisionError()))
4621
4622 def test_pathlike_subclasshook(self):
4623 # bpo-38878: subclasshook causes subclass checks
4624 # true on abstract implementation.
4625 class A(os.PathLike):
4626 pass
4627 self.assertFalse(issubclass(FakePath, A))
4628 self.assertTrue(issubclass(FakePath, os.PathLike))
4629
4630 def test_pathlike_class_getitem(self):
4631 self.assertIsInstance(os.PathLike[bytes], types.GenericAlias)
4632
4633
4634 class TimesTests(unittest.TestCase):
4635 def test_times(self):
4636 times = os.times()
4637 self.assertIsInstance(times, os.times_result)
4638
4639 for field in ('user', 'system', 'children_user', 'children_system',
4640 'elapsed'):
4641 value = getattr(times, field)
4642 self.assertIsInstance(value, float)
4643
4644 if os.name == 'nt':
4645 self.assertEqual(times.children_user, 0)
4646 self.assertEqual(times.children_system, 0)
4647 self.assertEqual(times.elapsed, 0)
4648
4649
4650 @support.requires_fork()
4651 class ForkTests(unittest.TestCase):
4652 def test_fork(self):
4653 # bpo-42540: ensure os.fork() with non-default memory allocator does
4654 # not crash on exit.
4655 code = """if 1:
4656 import os
4657 from test import support
4658 pid = os.fork()
4659 if pid != 0:
4660 support.wait_process(pid, exitcode=0)
4661 """
4662 assert_python_ok("-c", code)
4663 assert_python_ok("-c", code, PYTHONMALLOC="malloc_debug")
4664
4665
4666 # Only test if the C version is provided, otherwise TestPEP519 already tested
4667 # the pure Python implementation.
4668 if hasattr(os, "_fspath"):
4669 class TestPEP519PurePython(TestPEP519):
4670
4671 """Explicitly test the pure Python implementation of os.fspath()."""
4672
4673 fspath = staticmethod(os._fspath)
4674
4675
4676 if __name__ == "__main__":
4677 unittest.main()