Fred Drake | 38c2ef0 | 2001-07-17 20:52:51 +0000 | [diff] [blame] | 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 |
Walter Dörwald | f0dfc7a | 2003-10-20 14:01:56 +0000 | [diff] [blame] | 3 | # portable than they had been thought to be. |
Fred Drake | 38c2ef0 | 2001-07-17 20:52:51 +0000 | [diff] [blame] | 4 | |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 5 | import asynchat |
| 6 | import asyncore |
| 7 | import codecs |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 8 | import contextlib |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 9 | import decimal |
| 10 | import errno |
| 11 | import fractions |
| 12 | import getpass |
| 13 | import itertools |
| 14 | import locale |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 15 | import mmap |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 16 | import os |
| 17 | import pickle |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 18 | import shutil |
| 19 | import signal |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 20 | import socket |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 21 | import stat |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 22 | import subprocess |
| 23 | import sys |
Victor Stinner | 4d6a3d6 | 2014-12-21 01:16:38 +0100 | [diff] [blame] | 24 | import sysconfig |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 25 | import threading |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 26 | import time |
| 27 | import unittest |
| 28 | import uuid |
| 29 | import warnings |
| 30 | from test import support |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 31 | |
Antoine Pitrou | ec34ab5 | 2013-08-16 20:44:38 +0200 | [diff] [blame] | 32 | try: |
| 33 | import resource |
| 34 | except ImportError: |
| 35 | resource = None |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 36 | try: |
| 37 | import fcntl |
| 38 | except ImportError: |
| 39 | fcntl = None |
Tim Golden | 0321cf2 | 2014-05-05 19:46:17 +0100 | [diff] [blame] | 40 | try: |
| 41 | import _winapi |
| 42 | except ImportError: |
| 43 | _winapi = None |
Victor Stinner | b28ed92 | 2014-07-11 17:04:41 +0200 | [diff] [blame] | 44 | try: |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 45 | import grp |
| 46 | groups = [g.gr_gid for g in grp.getgrall() if getpass.getuser() in g.gr_mem] |
| 47 | if hasattr(os, 'getgid'): |
| 48 | process_gid = os.getgid() |
| 49 | if process_gid not in groups: |
| 50 | groups.append(process_gid) |
| 51 | except ImportError: |
| 52 | groups = [] |
| 53 | try: |
| 54 | import pwd |
| 55 | all_users = [u.pw_uid for u in pwd.getpwall()] |
Xavier de Gaye | 2106010 | 2016-11-16 08:05:27 +0100 | [diff] [blame] | 56 | except (ImportError, AttributeError): |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 57 | all_users = [] |
| 58 | try: |
Victor Stinner | 5c6e6fc | 2014-07-12 11:03:53 +0200 | [diff] [blame] | 59 | from _testcapi import INT_MAX, PY_SSIZE_T_MAX |
Victor Stinner | b28ed92 | 2014-07-11 17:04:41 +0200 | [diff] [blame] | 60 | except ImportError: |
Victor Stinner | 5c6e6fc | 2014-07-12 11:03:53 +0200 | [diff] [blame] | 61 | INT_MAX = PY_SSIZE_T_MAX = sys.maxsize |
Antoine Pitrou | ec34ab5 | 2013-08-16 20:44:38 +0200 | [diff] [blame] | 62 | |
Berker Peksag | ce64391 | 2015-05-06 06:33:17 +0300 | [diff] [blame] | 63 | from test.support.script_helper import assert_python_ok |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame] | 64 | from test.support import unix_shell |
Fred Drake | 38c2ef0 | 2001-07-17 20:52:51 +0000 | [diff] [blame] | 65 | |
Victor Stinner | 923590e | 2016-03-24 09:11:48 +0100 | [diff] [blame] | 66 | |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 67 | root_in_posix = False |
| 68 | if hasattr(os, 'geteuid'): |
| 69 | root_in_posix = (os.geteuid() == 0) |
| 70 | |
Mark Dickinson | 7cf0389 | 2010-04-16 13:45:35 +0000 | [diff] [blame] | 71 | # Detect whether we're on a Linux system that uses the (now outdated |
| 72 | # and unmaintained) linuxthreads threading library. There's an issue |
| 73 | # when combining linuxthreads with a failed execv call: see |
| 74 | # http://bugs.python.org/issue4970. |
Victor Stinner | d5c355c | 2011-04-30 14:53:09 +0200 | [diff] [blame] | 75 | if hasattr(sys, 'thread_info') and sys.thread_info.version: |
| 76 | USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads") |
| 77 | else: |
| 78 | USING_LINUXTHREADS = False |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 79 | |
Stefan Krah | ebee49a | 2013-01-17 15:31:00 +0100 | [diff] [blame] | 80 | # Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group. |
| 81 | HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0 |
| 82 | |
Victor Stinner | 923590e | 2016-03-24 09:11:48 +0100 | [diff] [blame] | 83 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 84 | def requires_os_func(name): |
| 85 | return unittest.skipUnless(hasattr(os, name), 'requires os.%s' % name) |
| 86 | |
| 87 | |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 88 | class _PathLike(os.PathLike): |
| 89 | |
| 90 | def __init__(self, path=""): |
| 91 | self.path = path |
| 92 | |
| 93 | def __str__(self): |
| 94 | return str(self.path) |
| 95 | |
| 96 | def __fspath__(self): |
| 97 | if isinstance(self.path, BaseException): |
| 98 | raise self.path |
| 99 | else: |
| 100 | return self.path |
| 101 | |
| 102 | |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 103 | def create_file(filename, content=b'content'): |
| 104 | with open(filename, "xb", 0) as fp: |
| 105 | fp.write(content) |
| 106 | |
| 107 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 108 | # Tests creating TESTFN |
| 109 | class FileTests(unittest.TestCase): |
| 110 | def setUp(self): |
Martin Panter | bf19d16 | 2015-09-09 01:01:13 +0000 | [diff] [blame] | 111 | if os.path.lexists(support.TESTFN): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 112 | os.unlink(support.TESTFN) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 113 | tearDown = setUp |
| 114 | |
| 115 | def test_access(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 116 | f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 117 | os.close(f) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 118 | self.assertTrue(os.access(support.TESTFN, os.W_OK)) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 119 | |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 120 | def test_closerange(self): |
Antoine Pitrou | b9ee06c | 2008-08-16 22:03:17 +0000 | [diff] [blame] | 121 | first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) |
| 122 | # We must allocate two consecutive file descriptors, otherwise |
| 123 | # it will mess up other file descriptors (perhaps even the three |
| 124 | # standard ones). |
| 125 | second = os.dup(first) |
| 126 | try: |
| 127 | retries = 0 |
| 128 | while second != first + 1: |
| 129 | os.close(first) |
| 130 | retries += 1 |
| 131 | if retries > 10: |
| 132 | # XXX test skipped |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 133 | self.skipTest("couldn't allocate two consecutive fds") |
Antoine Pitrou | b9ee06c | 2008-08-16 22:03:17 +0000 | [diff] [blame] | 134 | first, second = second, os.dup(second) |
| 135 | finally: |
| 136 | os.close(second) |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 137 | # close a fd that is open, and one that isn't |
Antoine Pitrou | b9ee06c | 2008-08-16 22:03:17 +0000 | [diff] [blame] | 138 | os.closerange(first, first + 2) |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 139 | self.assertRaises(OSError, os.write, first, b"a") |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 140 | |
Benjamin Peterson | 1cc6df9 | 2010-06-30 17:39:45 +0000 | [diff] [blame] | 141 | @support.cpython_only |
Hirokazu Yamamoto | 4c19e6e | 2008-09-08 23:41:21 +0000 | [diff] [blame] | 142 | def test_rename(self): |
| 143 | path = support.TESTFN |
| 144 | old = sys.getrefcount(path) |
| 145 | self.assertRaises(TypeError, os.rename, path, 0) |
| 146 | new = sys.getrefcount(path) |
| 147 | self.assertEqual(old, new) |
| 148 | |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 149 | def test_read(self): |
| 150 | with open(support.TESTFN, "w+b") as fobj: |
| 151 | fobj.write(b"spam") |
| 152 | fobj.flush() |
| 153 | fd = fobj.fileno() |
| 154 | os.lseek(fd, 0, 0) |
| 155 | s = os.read(fd, 4) |
| 156 | self.assertEqual(type(s), bytes) |
| 157 | self.assertEqual(s, b"spam") |
| 158 | |
Victor Stinner | 6e1ccfe | 2014-07-11 17:35:06 +0200 | [diff] [blame] | 159 | @support.cpython_only |
Victor Stinner | 5c6e6fc | 2014-07-12 11:03:53 +0200 | [diff] [blame] | 160 | # Skip the test on 32-bit platforms: the number of bytes must fit in a |
| 161 | # Py_ssize_t type |
| 162 | @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, |
| 163 | "needs INT_MAX < PY_SSIZE_T_MAX") |
Victor Stinner | 6e1ccfe | 2014-07-11 17:35:06 +0200 | [diff] [blame] | 164 | @support.bigmemtest(size=INT_MAX + 10, memuse=1, dry_run=False) |
| 165 | def test_large_read(self, size): |
Victor Stinner | b28ed92 | 2014-07-11 17:04:41 +0200 | [diff] [blame] | 166 | self.addCleanup(support.unlink, support.TESTFN) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 167 | create_file(support.TESTFN, b'test') |
Victor Stinner | b28ed92 | 2014-07-11 17:04:41 +0200 | [diff] [blame] | 168 | |
| 169 | # Issue #21932: Make sure that os.read() does not raise an |
| 170 | # OverflowError for size larger than INT_MAX |
Victor Stinner | b28ed92 | 2014-07-11 17:04:41 +0200 | [diff] [blame] | 171 | with open(support.TESTFN, "rb") as fp: |
| 172 | data = os.read(fp.fileno(), size) |
| 173 | |
Victor Stinner | 8c663fd | 2017-11-08 14:44:44 -0800 | [diff] [blame] | 174 | # The test does not try to read more than 2 GiB at once because the |
Victor Stinner | b28ed92 | 2014-07-11 17:04:41 +0200 | [diff] [blame] | 175 | # operating system is free to return less bytes than requested. |
| 176 | self.assertEqual(data, b'test') |
| 177 | |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 178 | def test_write(self): |
| 179 | # os.write() accepts bytes- and buffer-like objects but not strings |
| 180 | fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY) |
| 181 | self.assertRaises(TypeError, os.write, fd, "beans") |
| 182 | os.write(fd, b"bacon\n") |
| 183 | os.write(fd, bytearray(b"eggs\n")) |
| 184 | os.write(fd, memoryview(b"spam\n")) |
| 185 | os.close(fd) |
| 186 | with open(support.TESTFN, "rb") as fobj: |
Antoine Pitrou | d62269f | 2008-09-15 23:54:52 +0000 | [diff] [blame] | 187 | self.assertEqual(fobj.read().splitlines(), |
| 188 | [b"bacon", b"eggs", b"spam"]) |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 189 | |
Victor Stinner | e0daff1 | 2011-03-20 23:36:35 +0100 | [diff] [blame] | 190 | def write_windows_console(self, *args): |
| 191 | retcode = subprocess.call(args, |
| 192 | # use a new console to not flood the test output |
| 193 | creationflags=subprocess.CREATE_NEW_CONSOLE, |
| 194 | # use a shell to hide the console window (SW_HIDE) |
| 195 | shell=True) |
| 196 | self.assertEqual(retcode, 0) |
| 197 | |
| 198 | @unittest.skipUnless(sys.platform == 'win32', |
| 199 | 'test specific to the Windows console') |
| 200 | def test_write_windows_console(self): |
| 201 | # Issue #11395: the Windows console returns an error (12: not enough |
| 202 | # space error) on writing into stdout if stdout mode is binary and the |
| 203 | # length is greater than 66,000 bytes (or less, depending on heap |
| 204 | # usage). |
| 205 | code = "print('x' * 100000)" |
| 206 | self.write_windows_console(sys.executable, "-c", code) |
| 207 | self.write_windows_console(sys.executable, "-u", "-c", code) |
| 208 | |
Amaury Forgeot d'Arc | e2e36ba | 2008-08-01 00:14:22 +0000 | [diff] [blame] | 209 | def fdopen_helper(self, *args): |
| 210 | fd = os.open(support.TESTFN, os.O_RDONLY) |
Victor Stinner | bef7fdf | 2011-07-01 13:45:30 +0200 | [diff] [blame] | 211 | f = os.fdopen(fd, *args) |
| 212 | f.close() |
Amaury Forgeot d'Arc | e2e36ba | 2008-08-01 00:14:22 +0000 | [diff] [blame] | 213 | |
| 214 | def test_fdopen(self): |
Victor Stinner | bef7fdf | 2011-07-01 13:45:30 +0200 | [diff] [blame] | 215 | fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) |
| 216 | os.close(fd) |
| 217 | |
Amaury Forgeot d'Arc | e2e36ba | 2008-08-01 00:14:22 +0000 | [diff] [blame] | 218 | self.fdopen_helper() |
| 219 | self.fdopen_helper('r') |
| 220 | self.fdopen_helper('r', 100) |
| 221 | |
Antoine Pitrou | f3b2d88 | 2012-01-30 22:08:52 +0100 | [diff] [blame] | 222 | def test_replace(self): |
| 223 | TESTFN2 = support.TESTFN + ".2" |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 224 | self.addCleanup(support.unlink, support.TESTFN) |
| 225 | self.addCleanup(support.unlink, TESTFN2) |
| 226 | |
| 227 | create_file(support.TESTFN, b"1") |
| 228 | create_file(TESTFN2, b"2") |
| 229 | |
Antoine Pitrou | f3b2d88 | 2012-01-30 22:08:52 +0100 | [diff] [blame] | 230 | os.replace(support.TESTFN, TESTFN2) |
| 231 | self.assertRaises(FileNotFoundError, os.stat, support.TESTFN) |
| 232 | with open(TESTFN2, 'r') as f: |
| 233 | self.assertEqual(f.read(), "1") |
| 234 | |
Martin Panter | bf19d16 | 2015-09-09 01:01:13 +0000 | [diff] [blame] | 235 | def test_open_keywords(self): |
| 236 | f = os.open(path=__file__, flags=os.O_RDONLY, mode=0o777, |
| 237 | dir_fd=None) |
| 238 | os.close(f) |
| 239 | |
| 240 | def test_symlink_keywords(self): |
| 241 | symlink = support.get_attribute(os, "symlink") |
| 242 | try: |
| 243 | symlink(src='target', dst=support.TESTFN, |
| 244 | target_is_directory=False, dir_fd=None) |
| 245 | except (NotImplementedError, OSError): |
| 246 | pass # No OS support or unprivileged user |
| 247 | |
Victor Stinner | bef7fdf | 2011-07-01 13:45:30 +0200 | [diff] [blame] | 248 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 249 | # Test attributes on return values from os.*stat* family. |
| 250 | class StatAttributeTests(unittest.TestCase): |
| 251 | def setUp(self): |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 252 | self.fname = support.TESTFN |
| 253 | self.addCleanup(support.unlink, self.fname) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 254 | create_file(self.fname, b"ABC") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 255 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 256 | @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') |
Antoine Pitrou | 3842529 | 2010-09-21 18:19:07 +0000 | [diff] [blame] | 257 | def check_stat_attributes(self, fname): |
Antoine Pitrou | 3842529 | 2010-09-21 18:19:07 +0000 | [diff] [blame] | 258 | result = os.stat(fname) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 259 | |
| 260 | # Make sure direct access works |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 261 | self.assertEqual(result[stat.ST_SIZE], 3) |
| 262 | self.assertEqual(result.st_size, 3) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 263 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 264 | # Make sure all the attributes are there |
| 265 | members = dir(result) |
| 266 | for name in dir(stat): |
| 267 | if name[:3] == 'ST_': |
| 268 | attr = name.lower() |
Martin v. Löwis | 4d394df | 2005-01-23 09:19:22 +0000 | [diff] [blame] | 269 | if name.endswith("TIME"): |
| 270 | def trunc(x): return int(x) |
| 271 | else: |
| 272 | def trunc(x): return x |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 273 | self.assertEqual(trunc(getattr(result, attr)), |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 274 | result[getattr(stat, name)]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 275 | self.assertIn(attr, members) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 276 | |
Larry Hastings | 6fe20b3 | 2012-04-19 15:07:49 -0700 | [diff] [blame] | 277 | # Make sure that the st_?time and st_?time_ns fields roughly agree |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 278 | # (they should always agree up to around tens-of-microseconds) |
Larry Hastings | 6fe20b3 | 2012-04-19 15:07:49 -0700 | [diff] [blame] | 279 | for name in 'st_atime st_mtime st_ctime'.split(): |
| 280 | floaty = int(getattr(result, name) * 100000) |
| 281 | nanosecondy = getattr(result, name + "_ns") // 10000 |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 282 | self.assertAlmostEqual(floaty, nanosecondy, delta=2) |
Larry Hastings | 6fe20b3 | 2012-04-19 15:07:49 -0700 | [diff] [blame] | 283 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 284 | try: |
| 285 | result[200] |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 286 | self.fail("No exception raised") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 287 | except IndexError: |
| 288 | pass |
| 289 | |
| 290 | # Make sure that assignment fails |
| 291 | try: |
| 292 | result.st_mode = 1 |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 293 | self.fail("No exception raised") |
Collin Winter | 42dae6a | 2007-03-28 21:44:53 +0000 | [diff] [blame] | 294 | except AttributeError: |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 295 | pass |
| 296 | |
| 297 | try: |
| 298 | result.st_rdev = 1 |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 299 | self.fail("No exception raised") |
Guido van Rossum | 1fff878 | 2001-10-18 21:19:31 +0000 | [diff] [blame] | 300 | except (AttributeError, TypeError): |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 301 | pass |
| 302 | |
| 303 | try: |
| 304 | result.parrot = 1 |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 305 | self.fail("No exception raised") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 306 | except AttributeError: |
| 307 | pass |
| 308 | |
| 309 | # Use the stat_result constructor with a too-short tuple. |
| 310 | try: |
| 311 | result2 = os.stat_result((10,)) |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 312 | self.fail("No exception raised") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 313 | except TypeError: |
| 314 | pass |
| 315 | |
Ezio Melotti | 42da663 | 2011-03-15 05:18:48 +0200 | [diff] [blame] | 316 | # Use the constructor with a too-long tuple. |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 317 | try: |
| 318 | result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14)) |
| 319 | except TypeError: |
| 320 | pass |
| 321 | |
Antoine Pitrou | 3842529 | 2010-09-21 18:19:07 +0000 | [diff] [blame] | 322 | def test_stat_attributes(self): |
| 323 | self.check_stat_attributes(self.fname) |
| 324 | |
| 325 | def test_stat_attributes_bytes(self): |
| 326 | try: |
| 327 | fname = self.fname.encode(sys.getfilesystemencoding()) |
| 328 | except UnicodeEncodeError: |
| 329 | self.skipTest("cannot encode %a for the filesystem" % self.fname) |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 330 | self.check_stat_attributes(fname) |
Tim Peters | e0c446b | 2001-10-18 21:57:37 +0000 | [diff] [blame] | 331 | |
Christian Heimes | 2582762 | 2013-10-12 01:27:08 +0200 | [diff] [blame] | 332 | def test_stat_result_pickle(self): |
| 333 | result = os.stat(self.fname) |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 334 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 335 | p = pickle.dumps(result, proto) |
| 336 | self.assertIn(b'stat_result', p) |
| 337 | if proto < 4: |
| 338 | self.assertIn(b'cos\nstat_result\n', p) |
| 339 | unpickled = pickle.loads(p) |
| 340 | self.assertEqual(result, unpickled) |
Christian Heimes | 2582762 | 2013-10-12 01:27:08 +0200 | [diff] [blame] | 341 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 342 | @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()') |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 343 | def test_statvfs_attributes(self): |
Benjamin Peterson | 4eaf7f9 | 2017-10-25 23:55:14 -0700 | [diff] [blame] | 344 | result = os.statvfs(self.fname) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 345 | |
| 346 | # Make sure direct access works |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 347 | self.assertEqual(result.f_bfree, result[3]) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 348 | |
Brett Cannon | cfaf10c | 2008-05-16 00:45:35 +0000 | [diff] [blame] | 349 | # Make sure all the attributes are there. |
| 350 | members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files', |
| 351 | 'ffree', 'favail', 'flag', 'namemax') |
| 352 | for value, member in enumerate(members): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 353 | self.assertEqual(getattr(result, 'f_' + member), result[value]) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 354 | |
Giuseppe Scrivano | 96a5e50 | 2017-12-14 23:46:46 +0100 | [diff] [blame] | 355 | self.assertTrue(isinstance(result.f_fsid, int)) |
| 356 | |
| 357 | # Test that the size of the tuple doesn't change |
| 358 | self.assertEqual(len(result), 10) |
| 359 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 360 | # Make sure that assignment really fails |
| 361 | try: |
| 362 | result.f_bfree = 1 |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 363 | self.fail("No exception raised") |
Collin Winter | 42dae6a | 2007-03-28 21:44:53 +0000 | [diff] [blame] | 364 | except AttributeError: |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 365 | pass |
| 366 | |
| 367 | try: |
| 368 | result.parrot = 1 |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 369 | self.fail("No exception raised") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 370 | except AttributeError: |
| 371 | pass |
| 372 | |
| 373 | # Use the constructor with a too-short tuple. |
| 374 | try: |
| 375 | result2 = os.statvfs_result((10,)) |
Andrew Svetlov | 737fb89 | 2012-12-18 21:14:22 +0200 | [diff] [blame] | 376 | self.fail("No exception raised") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 377 | except TypeError: |
| 378 | pass |
| 379 | |
Ezio Melotti | 42da663 | 2011-03-15 05:18:48 +0200 | [diff] [blame] | 380 | # Use the constructor with a too-long tuple. |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 381 | try: |
| 382 | result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14)) |
| 383 | except TypeError: |
| 384 | pass |
Fred Drake | 38c2ef0 | 2001-07-17 20:52:51 +0000 | [diff] [blame] | 385 | |
Christian Heimes | 2582762 | 2013-10-12 01:27:08 +0200 | [diff] [blame] | 386 | @unittest.skipUnless(hasattr(os, 'statvfs'), |
| 387 | "need os.statvfs()") |
| 388 | def test_statvfs_result_pickle(self): |
Benjamin Peterson | 4eaf7f9 | 2017-10-25 23:55:14 -0700 | [diff] [blame] | 389 | result = os.statvfs(self.fname) |
Victor Stinner | 370cb25 | 2013-10-12 01:33:54 +0200 | [diff] [blame] | 390 | |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 391 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 392 | p = pickle.dumps(result, proto) |
| 393 | self.assertIn(b'statvfs_result', p) |
| 394 | if proto < 4: |
| 395 | self.assertIn(b'cos\nstatvfs_result\n', p) |
| 396 | unpickled = pickle.loads(p) |
| 397 | self.assertEqual(result, unpickled) |
Christian Heimes | 2582762 | 2013-10-12 01:27:08 +0200 | [diff] [blame] | 398 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 399 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
| 400 | def test_1686475(self): |
| 401 | # Verify that an open file can be stat'ed |
| 402 | try: |
| 403 | os.stat(r"c:\pagefile.sys") |
| 404 | except FileNotFoundError: |
Zachary Ware | 101d9e7 | 2013-12-08 00:44:27 -0600 | [diff] [blame] | 405 | self.skipTest(r'c:\pagefile.sys does not exist') |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 406 | except OSError as e: |
| 407 | self.fail("Could not stat pagefile.sys") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 408 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 409 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
| 410 | @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") |
| 411 | def test_15261(self): |
| 412 | # Verify that stat'ing a closed fd does not cause crash |
| 413 | r, w = os.pipe() |
| 414 | try: |
| 415 | os.stat(r) # should not raise error |
| 416 | finally: |
| 417 | os.close(r) |
| 418 | os.close(w) |
| 419 | with self.assertRaises(OSError) as ctx: |
| 420 | os.stat(r) |
| 421 | self.assertEqual(ctx.exception.errno, errno.EBADF) |
Richard Oudkerk | 2240ac1 | 2012-07-06 12:05:32 +0100 | [diff] [blame] | 422 | |
Zachary Ware | 63f277b | 2014-06-19 09:46:37 -0500 | [diff] [blame] | 423 | def check_file_attributes(self, result): |
| 424 | self.assertTrue(hasattr(result, 'st_file_attributes')) |
| 425 | self.assertTrue(isinstance(result.st_file_attributes, int)) |
| 426 | self.assertTrue(0 <= result.st_file_attributes <= 0xFFFFFFFF) |
| 427 | |
| 428 | @unittest.skipUnless(sys.platform == "win32", |
| 429 | "st_file_attributes is Win32 specific") |
| 430 | def test_file_attributes(self): |
| 431 | # test file st_file_attributes (FILE_ATTRIBUTE_DIRECTORY not set) |
| 432 | result = os.stat(self.fname) |
| 433 | self.check_file_attributes(result) |
| 434 | self.assertEqual( |
| 435 | result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY, |
| 436 | 0) |
| 437 | |
| 438 | # test directory st_file_attributes (FILE_ATTRIBUTE_DIRECTORY set) |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 439 | dirname = support.TESTFN + "dir" |
| 440 | os.mkdir(dirname) |
| 441 | self.addCleanup(os.rmdir, dirname) |
| 442 | |
| 443 | result = os.stat(dirname) |
Zachary Ware | 63f277b | 2014-06-19 09:46:37 -0500 | [diff] [blame] | 444 | self.check_file_attributes(result) |
| 445 | self.assertEqual( |
| 446 | result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY, |
| 447 | stat.FILE_ATTRIBUTE_DIRECTORY) |
| 448 | |
Berker Peksag | 0b4dc48 | 2016-09-17 15:49:59 +0300 | [diff] [blame] | 449 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
| 450 | def test_access_denied(self): |
| 451 | # Default to FindFirstFile WIN32_FIND_DATA when access is |
| 452 | # denied. See issue 28075. |
| 453 | # os.environ['TEMP'] should be located on a volume that |
| 454 | # supports file ACLs. |
| 455 | fname = os.path.join(os.environ['TEMP'], self.fname) |
| 456 | self.addCleanup(support.unlink, fname) |
| 457 | create_file(fname, b'ABC') |
| 458 | # Deny the right to [S]YNCHRONIZE on the file to |
| 459 | # force CreateFile to fail with ERROR_ACCESS_DENIED. |
| 460 | DETACHED_PROCESS = 8 |
| 461 | subprocess.check_call( |
Denis Osipov | 897bba7 | 2017-06-07 22:15:26 +0500 | [diff] [blame] | 462 | # bpo-30584: Use security identifier *S-1-5-32-545 instead |
| 463 | # of localized "Users" to not depend on the locale. |
| 464 | ['icacls.exe', fname, '/deny', '*S-1-5-32-545:(S)'], |
Berker Peksag | 0b4dc48 | 2016-09-17 15:49:59 +0300 | [diff] [blame] | 465 | creationflags=DETACHED_PROCESS |
| 466 | ) |
| 467 | result = os.stat(fname) |
| 468 | self.assertNotEqual(result.st_size, 0) |
| 469 | |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 470 | |
| 471 | class UtimeTests(unittest.TestCase): |
| 472 | def setUp(self): |
| 473 | self.dirname = support.TESTFN |
| 474 | self.fname = os.path.join(self.dirname, "f1") |
| 475 | |
| 476 | self.addCleanup(support.rmtree, self.dirname) |
| 477 | os.mkdir(self.dirname) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 478 | create_file(self.fname) |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 479 | |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 480 | def support_subsecond(self, filename): |
| 481 | # Heuristic to check if the filesystem supports timestamp with |
| 482 | # subsecond resolution: check if float and int timestamps are different |
| 483 | st = os.stat(filename) |
| 484 | return ((st.st_atime != st[7]) |
| 485 | or (st.st_mtime != st[8]) |
| 486 | or (st.st_ctime != st[9])) |
| 487 | |
| 488 | def _test_utime(self, set_time, filename=None): |
| 489 | if not filename: |
| 490 | filename = self.fname |
| 491 | |
| 492 | support_subsecond = self.support_subsecond(filename) |
| 493 | if support_subsecond: |
| 494 | # Timestamp with a resolution of 1 microsecond (10^-6). |
| 495 | # |
| 496 | # The resolution of the C internal function used by os.utime() |
| 497 | # depends on the platform: 1 sec, 1 us, 1 ns. Writing a portable |
| 498 | # test with a resolution of 1 ns requires more work: |
| 499 | # see the issue #15745. |
| 500 | atime_ns = 1002003000 # 1.002003 seconds |
| 501 | mtime_ns = 4005006000 # 4.005006 seconds |
| 502 | else: |
| 503 | # use a resolution of 1 second |
| 504 | atime_ns = 5 * 10**9 |
| 505 | mtime_ns = 8 * 10**9 |
| 506 | |
| 507 | set_time(filename, (atime_ns, mtime_ns)) |
| 508 | st = os.stat(filename) |
| 509 | |
| 510 | if support_subsecond: |
| 511 | self.assertAlmostEqual(st.st_atime, atime_ns * 1e-9, delta=1e-6) |
| 512 | self.assertAlmostEqual(st.st_mtime, mtime_ns * 1e-9, delta=1e-6) |
| 513 | else: |
| 514 | self.assertEqual(st.st_atime, atime_ns * 1e-9) |
| 515 | self.assertEqual(st.st_mtime, mtime_ns * 1e-9) |
| 516 | self.assertEqual(st.st_atime_ns, atime_ns) |
| 517 | self.assertEqual(st.st_mtime_ns, mtime_ns) |
| 518 | |
| 519 | def test_utime(self): |
| 520 | def set_time(filename, ns): |
| 521 | # test the ns keyword parameter |
| 522 | os.utime(filename, ns=ns) |
| 523 | self._test_utime(set_time) |
| 524 | |
| 525 | @staticmethod |
| 526 | def ns_to_sec(ns): |
| 527 | # Convert a number of nanosecond (int) to a number of seconds (float). |
| 528 | # Round towards infinity by adding 0.5 nanosecond to avoid rounding |
| 529 | # issue, os.utime() rounds towards minus infinity. |
| 530 | return (ns * 1e-9) + 0.5e-9 |
| 531 | |
| 532 | def test_utime_by_indexed(self): |
| 533 | # pass times as floating point seconds as the second indexed parameter |
| 534 | def set_time(filename, ns): |
| 535 | atime_ns, mtime_ns = ns |
| 536 | atime = self.ns_to_sec(atime_ns) |
| 537 | mtime = self.ns_to_sec(mtime_ns) |
| 538 | # test utimensat(timespec), utimes(timeval), utime(utimbuf) |
| 539 | # or utime(time_t) |
| 540 | os.utime(filename, (atime, mtime)) |
| 541 | self._test_utime(set_time) |
| 542 | |
| 543 | def test_utime_by_times(self): |
| 544 | def set_time(filename, ns): |
| 545 | atime_ns, mtime_ns = ns |
| 546 | atime = self.ns_to_sec(atime_ns) |
| 547 | mtime = self.ns_to_sec(mtime_ns) |
| 548 | # test the times keyword parameter |
| 549 | os.utime(filename, times=(atime, mtime)) |
| 550 | self._test_utime(set_time) |
| 551 | |
| 552 | @unittest.skipUnless(os.utime in os.supports_follow_symlinks, |
| 553 | "follow_symlinks support for utime required " |
| 554 | "for this test.") |
| 555 | def test_utime_nofollow_symlinks(self): |
| 556 | def set_time(filename, ns): |
| 557 | # use follow_symlinks=False to test utimensat(timespec) |
| 558 | # or lutimes(timeval) |
| 559 | os.utime(filename, ns=ns, follow_symlinks=False) |
| 560 | self._test_utime(set_time) |
| 561 | |
| 562 | @unittest.skipUnless(os.utime in os.supports_fd, |
| 563 | "fd support for utime required for this test.") |
| 564 | def test_utime_fd(self): |
| 565 | def set_time(filename, ns): |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 566 | with open(filename, 'wb', 0) as fp: |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 567 | # use a file descriptor to test futimens(timespec) |
| 568 | # or futimes(timeval) |
| 569 | os.utime(fp.fileno(), ns=ns) |
| 570 | self._test_utime(set_time) |
| 571 | |
| 572 | @unittest.skipUnless(os.utime in os.supports_dir_fd, |
| 573 | "dir_fd support for utime required for this test.") |
| 574 | def test_utime_dir_fd(self): |
| 575 | def set_time(filename, ns): |
| 576 | dirname, name = os.path.split(filename) |
| 577 | dirfd = os.open(dirname, os.O_RDONLY) |
| 578 | try: |
| 579 | # pass dir_fd to test utimensat(timespec) or futimesat(timeval) |
| 580 | os.utime(name, dir_fd=dirfd, ns=ns) |
| 581 | finally: |
| 582 | os.close(dirfd) |
| 583 | self._test_utime(set_time) |
| 584 | |
| 585 | def test_utime_directory(self): |
| 586 | def set_time(filename, ns): |
| 587 | # test calling os.utime() on a directory |
| 588 | os.utime(filename, ns=ns) |
| 589 | self._test_utime(set_time, filename=self.dirname) |
| 590 | |
| 591 | def _test_utime_current(self, set_time): |
| 592 | # Get the system clock |
| 593 | current = time.time() |
| 594 | |
| 595 | # Call os.utime() to set the timestamp to the current system clock |
| 596 | set_time(self.fname) |
| 597 | |
| 598 | if not self.support_subsecond(self.fname): |
| 599 | delta = 1.0 |
Victor Stinner | a8e7d90 | 2017-09-18 08:49:45 -0700 | [diff] [blame] | 600 | else: |
Victor Stinner | c94caca | 2017-06-13 23:48:27 +0200 | [diff] [blame] | 601 | # On Windows, the usual resolution of time.time() is 15.6 ms. |
| 602 | # bpo-30649: Tolerate 50 ms for slow Windows buildbots. |
Victor Stinner | a8e7d90 | 2017-09-18 08:49:45 -0700 | [diff] [blame] | 603 | # |
| 604 | # x86 Gentoo Refleaks 3.x once failed with dt=20.2 ms. So use |
| 605 | # also 50 ms on other platforms. |
Victor Stinner | c94caca | 2017-06-13 23:48:27 +0200 | [diff] [blame] | 606 | delta = 0.050 |
Victor Stinner | 47aacc8 | 2015-06-12 17:26:23 +0200 | [diff] [blame] | 607 | st = os.stat(self.fname) |
| 608 | msg = ("st_time=%r, current=%r, dt=%r" |
| 609 | % (st.st_mtime, current, st.st_mtime - current)) |
| 610 | self.assertAlmostEqual(st.st_mtime, current, |
| 611 | delta=delta, msg=msg) |
| 612 | |
| 613 | def test_utime_current(self): |
| 614 | def set_time(filename): |
| 615 | # Set to the current time in the new way |
| 616 | os.utime(self.fname) |
| 617 | self._test_utime_current(set_time) |
| 618 | |
| 619 | def test_utime_current_old(self): |
| 620 | def set_time(filename): |
| 621 | # Set to the current time in the old explicit way. |
| 622 | os.utime(self.fname, None) |
| 623 | self._test_utime_current(set_time) |
| 624 | |
| 625 | def get_file_system(self, path): |
| 626 | if sys.platform == 'win32': |
| 627 | root = os.path.splitdrive(os.path.abspath(path))[0] + '\\' |
| 628 | import ctypes |
| 629 | kernel32 = ctypes.windll.kernel32 |
| 630 | buf = ctypes.create_unicode_buffer("", 100) |
| 631 | ok = kernel32.GetVolumeInformationW(root, None, 0, |
| 632 | None, None, None, |
| 633 | buf, len(buf)) |
| 634 | if ok: |
| 635 | return buf.value |
| 636 | # return None if the filesystem is unknown |
| 637 | |
| 638 | def test_large_time(self): |
| 639 | # Many filesystems are limited to the year 2038. At least, the test |
| 640 | # pass with NTFS filesystem. |
| 641 | if self.get_file_system(self.dirname) != "NTFS": |
| 642 | self.skipTest("requires NTFS") |
| 643 | |
| 644 | large = 5000000000 # some day in 2128 |
| 645 | os.utime(self.fname, (large, large)) |
| 646 | self.assertEqual(os.stat(self.fname).st_mtime, large) |
| 647 | |
| 648 | def test_utime_invalid_arguments(self): |
| 649 | # seconds and nanoseconds parameters are mutually exclusive |
| 650 | with self.assertRaises(ValueError): |
| 651 | os.utime(self.fname, (5, 5), ns=(5, 5)) |
| 652 | |
| 653 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 654 | from test import mapping_tests |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 655 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 656 | class EnvironTests(mapping_tests.BasicTestMappingProtocol): |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 657 | """check that os.environ object conform to mapping protocol""" |
Walter Dörwald | 118f931 | 2004-06-02 18:42:25 +0000 | [diff] [blame] | 658 | type2test = None |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 659 | |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 660 | def setUp(self): |
| 661 | self.__save = dict(os.environ) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 662 | if os.supports_bytes_environ: |
Victor Stinner | 208d28c | 2010-05-07 00:54:14 +0000 | [diff] [blame] | 663 | self.__saveb = dict(os.environb) |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 664 | for key, value in self._reference().items(): |
| 665 | os.environ[key] = value |
| 666 | |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 667 | def tearDown(self): |
| 668 | os.environ.clear() |
| 669 | os.environ.update(self.__save) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 670 | if os.supports_bytes_environ: |
Victor Stinner | 208d28c | 2010-05-07 00:54:14 +0000 | [diff] [blame] | 671 | os.environb.clear() |
| 672 | os.environb.update(self.__saveb) |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 673 | |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 674 | def _reference(self): |
| 675 | return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"} |
| 676 | |
| 677 | def _empty_mapping(self): |
| 678 | os.environ.clear() |
| 679 | return os.environ |
| 680 | |
Martin v. Löwis | 1d11de6 | 2005-01-29 13:29:23 +0000 | [diff] [blame] | 681 | # Bug 1110478 |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame] | 682 | @unittest.skipUnless(unix_shell and os.path.exists(unix_shell), |
| 683 | 'requires a shell') |
Martin v. Löwis | 5510f65 | 2005-02-17 21:23:20 +0000 | [diff] [blame] | 684 | def test_update2(self): |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 685 | os.environ.clear() |
Ezio Melotti | c7e139b | 2012-09-26 20:01:34 +0300 | [diff] [blame] | 686 | os.environ.update(HELLO="World") |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame] | 687 | with os.popen("%s -c 'echo $HELLO'" % unix_shell) as popen: |
Ezio Melotti | c7e139b | 2012-09-26 20:01:34 +0300 | [diff] [blame] | 688 | value = popen.read().strip() |
| 689 | self.assertEqual(value, "World") |
Martin v. Löwis | 1d11de6 | 2005-01-29 13:29:23 +0000 | [diff] [blame] | 690 | |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame] | 691 | @unittest.skipUnless(unix_shell and os.path.exists(unix_shell), |
| 692 | 'requires a shell') |
Christian Heimes | 1a13d59 | 2007-11-08 14:16:55 +0000 | [diff] [blame] | 693 | def test_os_popen_iter(self): |
Xavier de Gaye | d141531 | 2016-07-22 12:15:29 +0200 | [diff] [blame] | 694 | with os.popen("%s -c 'echo \"line1\nline2\nline3\"'" |
| 695 | % unix_shell) as popen: |
Ezio Melotti | c7e139b | 2012-09-26 20:01:34 +0300 | [diff] [blame] | 696 | it = iter(popen) |
| 697 | self.assertEqual(next(it), "line1\n") |
| 698 | self.assertEqual(next(it), "line2\n") |
| 699 | self.assertEqual(next(it), "line3\n") |
| 700 | self.assertRaises(StopIteration, next, it) |
Christian Heimes | 1a13d59 | 2007-11-08 14:16:55 +0000 | [diff] [blame] | 701 | |
Guido van Rossum | 67aca9e | 2007-06-13 21:51:27 +0000 | [diff] [blame] | 702 | # Verify environ keys and values from the OS are of the |
| 703 | # correct str type. |
| 704 | def test_keyvalue_types(self): |
| 705 | for key, val in os.environ.items(): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 706 | self.assertEqual(type(key), str) |
| 707 | self.assertEqual(type(val), str) |
Guido van Rossum | 67aca9e | 2007-06-13 21:51:27 +0000 | [diff] [blame] | 708 | |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 709 | def test_items(self): |
| 710 | for key, value in self._reference().items(): |
| 711 | self.assertEqual(os.environ.get(key), value) |
| 712 | |
Ezio Melotti | 19e4acf | 2010-02-22 15:59:01 +0000 | [diff] [blame] | 713 | # Issue 7310 |
| 714 | def test___repr__(self): |
| 715 | """Check that the repr() of os.environ looks like environ({...}).""" |
| 716 | env = os.environ |
Victor Stinner | 96f0de9 | 2010-07-29 00:29:00 +0000 | [diff] [blame] | 717 | self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join( |
| 718 | '{!r}: {!r}'.format(key, value) |
| 719 | for key, value in env.items()))) |
Ezio Melotti | 19e4acf | 2010-02-22 15:59:01 +0000 | [diff] [blame] | 720 | |
Gregory P. Smith | b6e8c7e | 2010-02-27 07:22:22 +0000 | [diff] [blame] | 721 | def test_get_exec_path(self): |
| 722 | defpath_list = os.defpath.split(os.pathsep) |
| 723 | test_path = ['/monty', '/python', '', '/flying/circus'] |
| 724 | test_env = {'PATH': os.pathsep.join(test_path)} |
| 725 | |
| 726 | saved_environ = os.environ |
| 727 | try: |
| 728 | os.environ = dict(test_env) |
| 729 | # Test that defaulting to os.environ works. |
| 730 | self.assertSequenceEqual(test_path, os.get_exec_path()) |
| 731 | self.assertSequenceEqual(test_path, os.get_exec_path(env=None)) |
| 732 | finally: |
| 733 | os.environ = saved_environ |
| 734 | |
| 735 | # No PATH environment variable |
| 736 | self.assertSequenceEqual(defpath_list, os.get_exec_path({})) |
| 737 | # Empty PATH environment variable |
| 738 | self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''})) |
| 739 | # Supplied PATH environment variable |
| 740 | self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) |
| 741 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 742 | if os.supports_bytes_environ: |
| 743 | # env cannot contain 'PATH' and b'PATH' keys |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 744 | try: |
Victor Stinner | 6f35eda | 2010-10-29 00:38:58 +0000 | [diff] [blame] | 745 | # ignore BytesWarning warning |
| 746 | with warnings.catch_warnings(record=True): |
| 747 | mixed_env = {'PATH': '1', b'PATH': b'2'} |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 748 | except BytesWarning: |
Victor Stinner | 6f35eda | 2010-10-29 00:38:58 +0000 | [diff] [blame] | 749 | # mixed_env cannot be created with python -bb |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 750 | pass |
| 751 | else: |
| 752 | self.assertRaises(ValueError, os.get_exec_path, mixed_env) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 753 | |
| 754 | # bytes key and/or value |
| 755 | self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}), |
| 756 | ['abc']) |
| 757 | self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}), |
| 758 | ['abc']) |
| 759 | self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}), |
| 760 | ['abc']) |
| 761 | |
| 762 | @unittest.skipUnless(os.supports_bytes_environ, |
| 763 | "os.environb required for this test.") |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 764 | def test_environb(self): |
| 765 | # os.environ -> os.environb |
| 766 | value = 'euro\u20ac' |
| 767 | try: |
Benjamin Peterson | 180799d | 2010-05-06 22:25:42 +0000 | [diff] [blame] | 768 | value_bytes = value.encode(sys.getfilesystemencoding(), |
| 769 | 'surrogateescape') |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 770 | except UnicodeEncodeError: |
Benjamin Peterson | 180799d | 2010-05-06 22:25:42 +0000 | [diff] [blame] | 771 | msg = "U+20AC character is not encodable to %s" % ( |
| 772 | sys.getfilesystemencoding(),) |
Benjamin Peterson | 932d3f4 | 2010-05-06 22:26:31 +0000 | [diff] [blame] | 773 | self.skipTest(msg) |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 774 | os.environ['unicode'] = value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 775 | self.assertEqual(os.environ['unicode'], value) |
| 776 | self.assertEqual(os.environb[b'unicode'], value_bytes) |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 777 | |
| 778 | # os.environb -> os.environ |
| 779 | value = b'\xff' |
| 780 | os.environb[b'bytes'] = value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 781 | self.assertEqual(os.environb[b'bytes'], value) |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 782 | value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 783 | self.assertEqual(os.environ['bytes'], value_str) |
Ezio Melotti | 19e4acf | 2010-02-22 15:59:01 +0000 | [diff] [blame] | 784 | |
Victor Stinner | 13ff245 | 2018-01-22 18:32:50 +0100 | [diff] [blame^] | 785 | # On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415). |
Charles-François Natali | 2966f10 | 2011-11-26 11:32:46 +0100 | [diff] [blame] | 786 | @support.requires_mac_ver(10, 6) |
Victor Stinner | 60b385e | 2011-11-22 22:01:28 +0100 | [diff] [blame] | 787 | def test_unset_error(self): |
| 788 | if sys.platform == "win32": |
| 789 | # an environment variable is limited to 32,767 characters |
| 790 | key = 'x' * 50000 |
Victor Stinner | b3f8268 | 2011-11-22 22:30:19 +0100 | [diff] [blame] | 791 | self.assertRaises(ValueError, os.environ.__delitem__, key) |
Victor Stinner | 60b385e | 2011-11-22 22:01:28 +0100 | [diff] [blame] | 792 | else: |
| 793 | # "=" is not allowed in a variable name |
| 794 | key = 'key=' |
Victor Stinner | b3f8268 | 2011-11-22 22:30:19 +0100 | [diff] [blame] | 795 | self.assertRaises(OSError, os.environ.__delitem__, key) |
Victor Stinner | 60b385e | 2011-11-22 22:01:28 +0100 | [diff] [blame] | 796 | |
Victor Stinner | 6d10139 | 2013-04-14 16:35:04 +0200 | [diff] [blame] | 797 | def test_key_type(self): |
| 798 | missing = 'missingkey' |
| 799 | self.assertNotIn(missing, os.environ) |
| 800 | |
Victor Stinner | 839e5ea | 2013-04-14 16:43:03 +0200 | [diff] [blame] | 801 | with self.assertRaises(KeyError) as cm: |
Victor Stinner | 6d10139 | 2013-04-14 16:35:04 +0200 | [diff] [blame] | 802 | os.environ[missing] |
Victor Stinner | 839e5ea | 2013-04-14 16:43:03 +0200 | [diff] [blame] | 803 | self.assertIs(cm.exception.args[0], missing) |
Victor Stinner | 0c2dd0c | 2013-08-23 19:19:15 +0200 | [diff] [blame] | 804 | self.assertTrue(cm.exception.__suppress_context__) |
Victor Stinner | 6d10139 | 2013-04-14 16:35:04 +0200 | [diff] [blame] | 805 | |
Victor Stinner | 839e5ea | 2013-04-14 16:43:03 +0200 | [diff] [blame] | 806 | with self.assertRaises(KeyError) as cm: |
Victor Stinner | 6d10139 | 2013-04-14 16:35:04 +0200 | [diff] [blame] | 807 | del os.environ[missing] |
Victor Stinner | 839e5ea | 2013-04-14 16:43:03 +0200 | [diff] [blame] | 808 | self.assertIs(cm.exception.args[0], missing) |
Victor Stinner | 0c2dd0c | 2013-08-23 19:19:15 +0200 | [diff] [blame] | 809 | self.assertTrue(cm.exception.__suppress_context__) |
| 810 | |
Osvaldo Santana Neto | 8a8d285 | 2017-07-01 14:34:45 -0300 | [diff] [blame] | 811 | def _test_environ_iteration(self, collection): |
| 812 | iterator = iter(collection) |
| 813 | new_key = "__new_key__" |
| 814 | |
| 815 | next(iterator) # start iteration over os.environ.items |
| 816 | |
| 817 | # add a new key in os.environ mapping |
| 818 | os.environ[new_key] = "test_environ_iteration" |
| 819 | |
| 820 | try: |
| 821 | next(iterator) # force iteration over modified mapping |
| 822 | self.assertEqual(os.environ[new_key], "test_environ_iteration") |
| 823 | finally: |
| 824 | del os.environ[new_key] |
| 825 | |
| 826 | def test_iter_error_when_changing_os_environ(self): |
| 827 | self._test_environ_iteration(os.environ) |
| 828 | |
| 829 | def test_iter_error_when_changing_os_environ_items(self): |
| 830 | self._test_environ_iteration(os.environ.items()) |
| 831 | |
| 832 | def test_iter_error_when_changing_os_environ_values(self): |
| 833 | self._test_environ_iteration(os.environ.values()) |
| 834 | |
Victor Stinner | 6d10139 | 2013-04-14 16:35:04 +0200 | [diff] [blame] | 835 | |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 836 | class WalkTests(unittest.TestCase): |
| 837 | """Tests for os.walk().""" |
| 838 | |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 839 | # Wrapper to hide minor differences between os.walk and os.fwalk |
| 840 | # to tests both functions with the same code base |
Serhiy Storchaka | 5f6a0b4 | 2016-02-08 16:23:28 +0200 | [diff] [blame] | 841 | def walk(self, top, **kwargs): |
Serhiy Storchaka | a17ca19 | 2015-12-23 00:37:34 +0200 | [diff] [blame] | 842 | if 'follow_symlinks' in kwargs: |
| 843 | kwargs['followlinks'] = kwargs.pop('follow_symlinks') |
Serhiy Storchaka | 5f6a0b4 | 2016-02-08 16:23:28 +0200 | [diff] [blame] | 844 | return os.walk(top, **kwargs) |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 845 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 846 | def setUp(self): |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 847 | join = os.path.join |
Victor Stinner | 3899b54 | 2016-03-24 17:21:17 +0100 | [diff] [blame] | 848 | self.addCleanup(support.rmtree, support.TESTFN) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 849 | |
| 850 | # Build: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 851 | # TESTFN/ |
| 852 | # TEST1/ a file kid and two directory kids |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 853 | # tmp1 |
| 854 | # SUB1/ a file kid and a directory kid |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 855 | # tmp2 |
| 856 | # SUB11/ no kids |
| 857 | # SUB2/ a file kid and a dirsymlink kid |
| 858 | # tmp3 |
Serhiy Storchaka | 42babab | 2016-10-25 14:28:38 +0300 | [diff] [blame] | 859 | # SUB21/ not readable |
| 860 | # tmp5 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 861 | # link/ a symlink to TESTFN.2 |
Hynek Schlawack | 66bfcc1 | 2012-05-15 16:32:21 +0200 | [diff] [blame] | 862 | # broken_link |
Serhiy Storchaka | 42babab | 2016-10-25 14:28:38 +0300 | [diff] [blame] | 863 | # broken_link2 |
| 864 | # broken_link3 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 865 | # TEST2/ |
| 866 | # tmp4 a lone file |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 867 | self.walk_path = join(support.TESTFN, "TEST1") |
| 868 | self.sub1_path = join(self.walk_path, "SUB1") |
| 869 | self.sub11_path = join(self.sub1_path, "SUB11") |
| 870 | sub2_path = join(self.walk_path, "SUB2") |
Serhiy Storchaka | af4e474 | 2016-10-25 14:34:38 +0300 | [diff] [blame] | 871 | sub21_path = join(sub2_path, "SUB21") |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 872 | tmp1_path = join(self.walk_path, "tmp1") |
| 873 | tmp2_path = join(self.sub1_path, "tmp2") |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 874 | tmp3_path = join(sub2_path, "tmp3") |
Serhiy Storchaka | af4e474 | 2016-10-25 14:34:38 +0300 | [diff] [blame] | 875 | tmp5_path = join(sub21_path, "tmp3") |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 876 | self.link_path = join(sub2_path, "link") |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 877 | t2_path = join(support.TESTFN, "TEST2") |
| 878 | tmp4_path = join(support.TESTFN, "TEST2", "tmp4") |
Hynek Schlawack | 66bfcc1 | 2012-05-15 16:32:21 +0200 | [diff] [blame] | 879 | broken_link_path = join(sub2_path, "broken_link") |
Serhiy Storchaka | 42babab | 2016-10-25 14:28:38 +0300 | [diff] [blame] | 880 | broken_link2_path = join(sub2_path, "broken_link2") |
| 881 | broken_link3_path = join(sub2_path, "broken_link3") |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 882 | |
| 883 | # Create stuff. |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 884 | os.makedirs(self.sub11_path) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 885 | os.makedirs(sub2_path) |
Serhiy Storchaka | af4e474 | 2016-10-25 14:34:38 +0300 | [diff] [blame] | 886 | os.makedirs(sub21_path) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 887 | os.makedirs(t2_path) |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 888 | |
Serhiy Storchaka | 42babab | 2016-10-25 14:28:38 +0300 | [diff] [blame] | 889 | for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path, tmp5_path: |
Victor Stinner | e77c974 | 2016-03-25 10:28:23 +0100 | [diff] [blame] | 890 | with open(path, "x") as f: |
| 891 | f.write("I'm " + path + " and proud of it. Blame test_os.\n") |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 892 | |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 893 | if support.can_symlink(): |
| 894 | os.symlink(os.path.abspath(t2_path), self.link_path) |
| 895 | os.symlink('broken', broken_link_path, True) |
Serhiy Storchaka | 42babab | 2016-10-25 14:28:38 +0300 | [diff] [blame] | 896 | os.symlink(join('tmp3', 'broken'), broken_link2_path, True) |
| 897 | os.symlink(join('SUB21', 'tmp5'), broken_link3_path, True) |
Serhiy Storchaka | 28f9820 | 2016-10-25 19:01:41 +0300 | [diff] [blame] | 898 | self.sub2_tree = (sub2_path, ["SUB21", "link"], |
Serhiy Storchaka | 42babab | 2016-10-25 14:28:38 +0300 | [diff] [blame] | 899 | ["broken_link", "broken_link2", "broken_link3", |
| 900 | "tmp3"]) |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 901 | else: |
| 902 | self.sub2_tree = (sub2_path, [], ["tmp3"]) |
| 903 | |
Serhiy Storchaka | af4e474 | 2016-10-25 14:34:38 +0300 | [diff] [blame] | 904 | os.chmod(sub21_path, 0) |
Serhiy Storchaka | 28f9820 | 2016-10-25 19:01:41 +0300 | [diff] [blame] | 905 | try: |
| 906 | os.listdir(sub21_path) |
| 907 | except PermissionError: |
| 908 | self.addCleanup(os.chmod, sub21_path, stat.S_IRWXU) |
| 909 | else: |
| 910 | os.chmod(sub21_path, stat.S_IRWXU) |
| 911 | os.unlink(tmp5_path) |
| 912 | os.rmdir(sub21_path) |
| 913 | del self.sub2_tree[1][:1] |
Serhiy Storchaka | 42babab | 2016-10-25 14:28:38 +0300 | [diff] [blame] | 914 | |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 915 | def test_walk_topdown(self): |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 916 | # Walk top-down. |
Serhiy Storchaka | a07ab29 | 2016-04-16 17:51:00 +0300 | [diff] [blame] | 917 | all = list(self.walk(self.walk_path)) |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 918 | |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 919 | self.assertEqual(len(all), 4) |
| 920 | # We can't know which order SUB1 and SUB2 will appear in. |
| 921 | # Not flipped: TESTFN, SUB1, SUB11, SUB2 |
| 922 | # flipped: TESTFN, SUB2, SUB1, SUB11 |
| 923 | flipped = all[0][1][0] != "SUB1" |
| 924 | all[0][1].sort() |
Hynek Schlawack | c96f5a0 | 2012-05-15 17:55:38 +0200 | [diff] [blame] | 925 | all[3 - 2 * flipped][-1].sort() |
Serhiy Storchaka | 28f9820 | 2016-10-25 19:01:41 +0300 | [diff] [blame] | 926 | all[3 - 2 * flipped][1].sort() |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 927 | self.assertEqual(all[0], (self.walk_path, ["SUB1", "SUB2"], ["tmp1"])) |
| 928 | self.assertEqual(all[1 + flipped], (self.sub1_path, ["SUB11"], ["tmp2"])) |
| 929 | self.assertEqual(all[2 + flipped], (self.sub11_path, [], [])) |
| 930 | self.assertEqual(all[3 - 2 * flipped], self.sub2_tree) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 931 | |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 932 | def test_walk_prune(self, walk_path=None): |
| 933 | if walk_path is None: |
| 934 | walk_path = self.walk_path |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 935 | # Prune the search. |
| 936 | all = [] |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 937 | for root, dirs, files in self.walk(walk_path): |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 938 | all.append((root, dirs, files)) |
| 939 | # Don't descend into SUB1. |
| 940 | if 'SUB1' in dirs: |
| 941 | # Note that this also mutates the dirs we appended to all! |
| 942 | dirs.remove('SUB1') |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 943 | |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 944 | self.assertEqual(len(all), 2) |
| 945 | self.assertEqual(all[0], |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 946 | (str(walk_path), ["SUB2"], ["tmp1"])) |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 947 | |
| 948 | all[1][-1].sort() |
Serhiy Storchaka | 28f9820 | 2016-10-25 19:01:41 +0300 | [diff] [blame] | 949 | all[1][1].sort() |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 950 | self.assertEqual(all[1], self.sub2_tree) |
| 951 | |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 952 | def test_file_like_path(self): |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 953 | self.test_walk_prune(_PathLike(self.walk_path)) |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 954 | |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 955 | def test_walk_bottom_up(self): |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 956 | # Walk bottom-up. |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 957 | all = list(self.walk(self.walk_path, topdown=False)) |
| 958 | |
Victor Stinner | 53b0a41 | 2016-03-26 01:12:36 +0100 | [diff] [blame] | 959 | self.assertEqual(len(all), 4, all) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 960 | # We can't know which order SUB1 and SUB2 will appear in. |
| 961 | # Not flipped: SUB11, SUB1, SUB2, TESTFN |
| 962 | # flipped: SUB2, SUB11, SUB1, TESTFN |
| 963 | flipped = all[3][1][0] != "SUB1" |
| 964 | all[3][1].sort() |
Hynek Schlawack | 39bf90d | 2012-05-15 18:40:17 +0200 | [diff] [blame] | 965 | all[2 - 2 * flipped][-1].sort() |
Serhiy Storchaka | 28f9820 | 2016-10-25 19:01:41 +0300 | [diff] [blame] | 966 | all[2 - 2 * flipped][1].sort() |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 967 | self.assertEqual(all[3], |
| 968 | (self.walk_path, ["SUB1", "SUB2"], ["tmp1"])) |
| 969 | self.assertEqual(all[flipped], |
| 970 | (self.sub11_path, [], [])) |
| 971 | self.assertEqual(all[flipped + 1], |
| 972 | (self.sub1_path, ["SUB11"], ["tmp2"])) |
| 973 | self.assertEqual(all[2 - 2 * flipped], |
| 974 | self.sub2_tree) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 975 | |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 976 | def test_walk_symlink(self): |
| 977 | if not support.can_symlink(): |
| 978 | self.skipTest("need symlink support") |
| 979 | |
| 980 | # Walk, following symlinks. |
| 981 | walk_it = self.walk(self.walk_path, follow_symlinks=True) |
| 982 | for root, dirs, files in walk_it: |
| 983 | if root == self.link_path: |
| 984 | self.assertEqual(dirs, []) |
| 985 | self.assertEqual(files, ["tmp4"]) |
| 986 | break |
| 987 | else: |
| 988 | self.fail("Didn't follow symlink with followlinks=True") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 989 | |
Serhiy Storchaka | 0bddc9e | 2015-12-23 00:08:24 +0200 | [diff] [blame] | 990 | def test_walk_bad_dir(self): |
| 991 | # Walk top-down. |
| 992 | errors = [] |
| 993 | walk_it = self.walk(self.walk_path, onerror=errors.append) |
| 994 | root, dirs, files = next(walk_it) |
Serhiy Storchaka | 7865dff | 2016-10-28 09:17:38 +0300 | [diff] [blame] | 995 | self.assertEqual(errors, []) |
| 996 | dir1 = 'SUB1' |
| 997 | path1 = os.path.join(root, dir1) |
| 998 | path1new = os.path.join(root, dir1 + '.new') |
| 999 | os.rename(path1, path1new) |
| 1000 | try: |
| 1001 | roots = [r for r, d, f in walk_it] |
| 1002 | self.assertTrue(errors) |
| 1003 | self.assertNotIn(path1, roots) |
| 1004 | self.assertNotIn(path1new, roots) |
| 1005 | for dir2 in dirs: |
| 1006 | if dir2 != dir1: |
| 1007 | self.assertIn(os.path.join(root, dir2), roots) |
| 1008 | finally: |
| 1009 | os.rename(path1new, path1) |
Serhiy Storchaka | 0bddc9e | 2015-12-23 00:08:24 +0200 | [diff] [blame] | 1010 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1011 | |
| 1012 | @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()") |
| 1013 | class FwalkTests(WalkTests): |
| 1014 | """Tests for os.fwalk().""" |
| 1015 | |
Serhiy Storchaka | 5f6a0b4 | 2016-02-08 16:23:28 +0200 | [diff] [blame] | 1016 | def walk(self, top, **kwargs): |
Serhiy Storchaka | 8f6b344 | 2017-03-07 14:33:21 +0200 | [diff] [blame] | 1017 | for root, dirs, files, root_fd in self.fwalk(top, **kwargs): |
Victor Stinner | 0561c53 | 2015-03-12 10:28:24 +0100 | [diff] [blame] | 1018 | yield (root, dirs, files) |
| 1019 | |
Serhiy Storchaka | 8f6b344 | 2017-03-07 14:33:21 +0200 | [diff] [blame] | 1020 | def fwalk(self, *args, **kwargs): |
| 1021 | return os.fwalk(*args, **kwargs) |
| 1022 | |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 1023 | def _compare_to_walk(self, walk_kwargs, fwalk_kwargs): |
| 1024 | """ |
| 1025 | compare with walk() results. |
| 1026 | """ |
Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 1027 | walk_kwargs = walk_kwargs.copy() |
| 1028 | fwalk_kwargs = fwalk_kwargs.copy() |
| 1029 | for topdown, follow_symlinks in itertools.product((True, False), repeat=2): |
| 1030 | walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks) |
| 1031 | fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks) |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 1032 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1033 | expected = {} |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 1034 | for root, dirs, files in os.walk(**walk_kwargs): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1035 | expected[root] = (set(dirs), set(files)) |
| 1036 | |
Serhiy Storchaka | 8f6b344 | 2017-03-07 14:33:21 +0200 | [diff] [blame] | 1037 | for root, dirs, files, rootfd in self.fwalk(**fwalk_kwargs): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1038 | self.assertIn(root, expected) |
| 1039 | self.assertEqual(expected[root], (set(dirs), set(files))) |
| 1040 | |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 1041 | def test_compare_to_walk(self): |
| 1042 | kwargs = {'top': support.TESTFN} |
| 1043 | self._compare_to_walk(kwargs, kwargs) |
| 1044 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1045 | def test_dir_fd(self): |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 1046 | try: |
| 1047 | fd = os.open(".", os.O_RDONLY) |
| 1048 | walk_kwargs = {'top': support.TESTFN} |
| 1049 | fwalk_kwargs = walk_kwargs.copy() |
| 1050 | fwalk_kwargs['dir_fd'] = fd |
| 1051 | self._compare_to_walk(walk_kwargs, fwalk_kwargs) |
| 1052 | finally: |
| 1053 | os.close(fd) |
| 1054 | |
| 1055 | def test_yields_correct_dir_fd(self): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1056 | # check returned file descriptors |
Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 1057 | for topdown, follow_symlinks in itertools.product((True, False), repeat=2): |
| 1058 | args = support.TESTFN, topdown, None |
Serhiy Storchaka | 8f6b344 | 2017-03-07 14:33:21 +0200 | [diff] [blame] | 1059 | for root, dirs, files, rootfd in self.fwalk(*args, follow_symlinks=follow_symlinks): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1060 | # check that the FD is valid |
| 1061 | os.fstat(rootfd) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1062 | # redundant check |
| 1063 | os.stat(rootfd) |
| 1064 | # check that listdir() returns consistent information |
| 1065 | self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files)) |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1066 | |
| 1067 | def test_fd_leak(self): |
| 1068 | # Since we're opening a lot of FDs, we must be careful to avoid leaks: |
| 1069 | # we both check that calling fwalk() a large number of times doesn't |
| 1070 | # yield EMFILE, and that the minimum allocated FD hasn't changed. |
| 1071 | minfd = os.dup(1) |
| 1072 | os.close(minfd) |
| 1073 | for i in range(256): |
Serhiy Storchaka | 8f6b344 | 2017-03-07 14:33:21 +0200 | [diff] [blame] | 1074 | for x in self.fwalk(support.TESTFN): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1075 | pass |
| 1076 | newfd = os.dup(1) |
| 1077 | self.addCleanup(os.close, newfd) |
| 1078 | self.assertEqual(newfd, minfd) |
| 1079 | |
Serhiy Storchaka | 5f6a0b4 | 2016-02-08 16:23:28 +0200 | [diff] [blame] | 1080 | class BytesWalkTests(WalkTests): |
| 1081 | """Tests for os.walk() with bytes.""" |
| 1082 | def walk(self, top, **kwargs): |
| 1083 | if 'follow_symlinks' in kwargs: |
| 1084 | kwargs['followlinks'] = kwargs.pop('follow_symlinks') |
| 1085 | for broot, bdirs, bfiles in os.walk(os.fsencode(top), **kwargs): |
| 1086 | root = os.fsdecode(broot) |
| 1087 | dirs = list(map(os.fsdecode, bdirs)) |
| 1088 | files = list(map(os.fsdecode, bfiles)) |
| 1089 | yield (root, dirs, files) |
| 1090 | bdirs[:] = list(map(os.fsencode, dirs)) |
| 1091 | bfiles[:] = list(map(os.fsencode, files)) |
| 1092 | |
Serhiy Storchaka | 8f6b344 | 2017-03-07 14:33:21 +0200 | [diff] [blame] | 1093 | @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()") |
| 1094 | class BytesFwalkTests(FwalkTests): |
| 1095 | """Tests for os.walk() with bytes.""" |
| 1096 | def fwalk(self, top='.', *args, **kwargs): |
| 1097 | for broot, bdirs, bfiles, topfd in os.fwalk(os.fsencode(top), *args, **kwargs): |
| 1098 | root = os.fsdecode(broot) |
| 1099 | dirs = list(map(os.fsdecode, bdirs)) |
| 1100 | files = list(map(os.fsdecode, bfiles)) |
| 1101 | yield (root, dirs, files, topfd) |
| 1102 | bdirs[:] = list(map(os.fsencode, dirs)) |
| 1103 | bfiles[:] = list(map(os.fsencode, files)) |
| 1104 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 1105 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1106 | class MakedirTests(unittest.TestCase): |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1107 | def setUp(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1108 | os.mkdir(support.TESTFN) |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1109 | |
| 1110 | def test_makedir(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1111 | base = support.TESTFN |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1112 | path = os.path.join(base, 'dir1', 'dir2', 'dir3') |
| 1113 | os.makedirs(path) # Should work |
| 1114 | path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4') |
| 1115 | os.makedirs(path) |
| 1116 | |
| 1117 | # Try paths with a '.' in them |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1118 | self.assertRaises(OSError, os.makedirs, os.curdir) |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1119 | path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir) |
| 1120 | os.makedirs(path) |
| 1121 | path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4', |
| 1122 | 'dir5', 'dir6') |
| 1123 | os.makedirs(path) |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1124 | |
Serhiy Storchaka | e304e33 | 2017-03-24 13:27:42 +0200 | [diff] [blame] | 1125 | def test_mode(self): |
| 1126 | with support.temp_umask(0o002): |
| 1127 | base = support.TESTFN |
| 1128 | parent = os.path.join(base, 'dir1') |
| 1129 | path = os.path.join(parent, 'dir2') |
| 1130 | os.makedirs(path, 0o555) |
| 1131 | self.assertTrue(os.path.exists(path)) |
| 1132 | self.assertTrue(os.path.isdir(path)) |
| 1133 | if os.name != 'nt': |
| 1134 | self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o555) |
| 1135 | self.assertEqual(stat.S_IMODE(os.stat(parent).st_mode), 0o775) |
| 1136 | |
Terry Reedy | 5a22b65 | 2010-12-02 07:05:56 +0000 | [diff] [blame] | 1137 | def test_exist_ok_existing_directory(self): |
| 1138 | path = os.path.join(support.TESTFN, 'dir1') |
| 1139 | mode = 0o777 |
| 1140 | old_mask = os.umask(0o022) |
| 1141 | os.makedirs(path, mode) |
| 1142 | self.assertRaises(OSError, os.makedirs, path, mode) |
| 1143 | self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False) |
Benjamin Peterson | 4717e21 | 2014-04-01 19:17:57 -0400 | [diff] [blame] | 1144 | os.makedirs(path, 0o776, exist_ok=True) |
Terry Reedy | 5a22b65 | 2010-12-02 07:05:56 +0000 | [diff] [blame] | 1145 | os.makedirs(path, mode=mode, exist_ok=True) |
| 1146 | os.umask(old_mask) |
| 1147 | |
Martin Panter | a82642f | 2015-11-19 04:48:44 +0000 | [diff] [blame] | 1148 | # Issue #25583: A drive root could raise PermissionError on Windows |
| 1149 | os.makedirs(os.path.abspath('/'), exist_ok=True) |
| 1150 | |
Gregory P. Smith | a81c856 | 2012-06-03 14:30:44 -0700 | [diff] [blame] | 1151 | def test_exist_ok_s_isgid_directory(self): |
| 1152 | path = os.path.join(support.TESTFN, 'dir1') |
| 1153 | S_ISGID = stat.S_ISGID |
| 1154 | mode = 0o777 |
| 1155 | old_mask = os.umask(0o022) |
| 1156 | try: |
| 1157 | existing_testfn_mode = stat.S_IMODE( |
| 1158 | os.lstat(support.TESTFN).st_mode) |
Ned Deily | c622f42 | 2012-08-08 20:57:24 -0700 | [diff] [blame] | 1159 | try: |
| 1160 | os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID) |
Ned Deily | 3a2b97e | 2012-08-08 21:03:02 -0700 | [diff] [blame] | 1161 | except PermissionError: |
Ned Deily | c622f42 | 2012-08-08 20:57:24 -0700 | [diff] [blame] | 1162 | raise unittest.SkipTest('Cannot set S_ISGID for dir.') |
Gregory P. Smith | a81c856 | 2012-06-03 14:30:44 -0700 | [diff] [blame] | 1163 | if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID): |
| 1164 | raise unittest.SkipTest('No support for S_ISGID dir mode.') |
| 1165 | # The os should apply S_ISGID from the parent dir for us, but |
| 1166 | # this test need not depend on that behavior. Be explicit. |
| 1167 | os.makedirs(path, mode | S_ISGID) |
| 1168 | # http://bugs.python.org/issue14992 |
| 1169 | # Should not fail when the bit is already set. |
| 1170 | os.makedirs(path, mode, exist_ok=True) |
| 1171 | # remove the bit. |
| 1172 | os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID) |
Benjamin Peterson | ee5f1c1 | 2014-04-01 19:13:18 -0400 | [diff] [blame] | 1173 | # May work even when the bit is not already set when demanded. |
| 1174 | os.makedirs(path, mode | S_ISGID, exist_ok=True) |
Gregory P. Smith | a81c856 | 2012-06-03 14:30:44 -0700 | [diff] [blame] | 1175 | finally: |
| 1176 | os.umask(old_mask) |
Terry Reedy | 5a22b65 | 2010-12-02 07:05:56 +0000 | [diff] [blame] | 1177 | |
| 1178 | def test_exist_ok_existing_regular_file(self): |
| 1179 | base = support.TESTFN |
| 1180 | path = os.path.join(support.TESTFN, 'dir1') |
| 1181 | f = open(path, 'w') |
| 1182 | f.write('abc') |
| 1183 | f.close() |
| 1184 | self.assertRaises(OSError, os.makedirs, path) |
| 1185 | self.assertRaises(OSError, os.makedirs, path, exist_ok=False) |
| 1186 | self.assertRaises(OSError, os.makedirs, path, exist_ok=True) |
| 1187 | os.remove(path) |
| 1188 | |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1189 | def tearDown(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1190 | path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3', |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1191 | 'dir4', 'dir5', 'dir6') |
| 1192 | # If the tests failed, the bottom-most directory ('../dir6') |
| 1193 | # may not have been created, so we look for the outermost directory |
| 1194 | # that exists. |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1195 | while not os.path.exists(path) and path != support.TESTFN: |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1196 | path = os.path.dirname(path) |
| 1197 | |
| 1198 | os.removedirs(path) |
| 1199 | |
Andrew Svetlov | 405faed | 2012-12-25 12:18:09 +0200 | [diff] [blame] | 1200 | |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 1201 | @unittest.skipUnless(hasattr(os, 'chown'), "Test needs chown") |
| 1202 | class ChownFileTests(unittest.TestCase): |
| 1203 | |
Berker Peksag | 036a71b | 2015-07-21 09:29:48 +0300 | [diff] [blame] | 1204 | @classmethod |
| 1205 | def setUpClass(cls): |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 1206 | os.mkdir(support.TESTFN) |
| 1207 | |
| 1208 | def test_chown_uid_gid_arguments_must_be_index(self): |
| 1209 | stat = os.stat(support.TESTFN) |
| 1210 | uid = stat.st_uid |
| 1211 | gid = stat.st_gid |
| 1212 | for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)): |
| 1213 | self.assertRaises(TypeError, os.chown, support.TESTFN, value, gid) |
| 1214 | self.assertRaises(TypeError, os.chown, support.TESTFN, uid, value) |
| 1215 | self.assertIsNone(os.chown(support.TESTFN, uid, gid)) |
| 1216 | self.assertIsNone(os.chown(support.TESTFN, -1, -1)) |
| 1217 | |
| 1218 | @unittest.skipUnless(len(groups) > 1, "test needs more than one group") |
| 1219 | def test_chown(self): |
| 1220 | gid_1, gid_2 = groups[:2] |
| 1221 | uid = os.stat(support.TESTFN).st_uid |
| 1222 | os.chown(support.TESTFN, uid, gid_1) |
| 1223 | gid = os.stat(support.TESTFN).st_gid |
| 1224 | self.assertEqual(gid, gid_1) |
| 1225 | os.chown(support.TESTFN, uid, gid_2) |
| 1226 | gid = os.stat(support.TESTFN).st_gid |
| 1227 | self.assertEqual(gid, gid_2) |
| 1228 | |
| 1229 | @unittest.skipUnless(root_in_posix and len(all_users) > 1, |
| 1230 | "test needs root privilege and more than one user") |
| 1231 | def test_chown_with_root(self): |
| 1232 | uid_1, uid_2 = all_users[:2] |
| 1233 | gid = os.stat(support.TESTFN).st_gid |
| 1234 | os.chown(support.TESTFN, uid_1, gid) |
| 1235 | uid = os.stat(support.TESTFN).st_uid |
| 1236 | self.assertEqual(uid, uid_1) |
| 1237 | os.chown(support.TESTFN, uid_2, gid) |
| 1238 | uid = os.stat(support.TESTFN).st_uid |
| 1239 | self.assertEqual(uid, uid_2) |
| 1240 | |
| 1241 | @unittest.skipUnless(not root_in_posix and len(all_users) > 1, |
| 1242 | "test needs non-root account and more than one user") |
| 1243 | def test_chown_without_permission(self): |
| 1244 | uid_1, uid_2 = all_users[:2] |
| 1245 | gid = os.stat(support.TESTFN).st_gid |
Serhiy Storchaka | a9e00d1 | 2015-02-16 08:35:18 +0200 | [diff] [blame] | 1246 | with self.assertRaises(PermissionError): |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 1247 | os.chown(support.TESTFN, uid_1, gid) |
| 1248 | os.chown(support.TESTFN, uid_2, gid) |
| 1249 | |
Berker Peksag | 036a71b | 2015-07-21 09:29:48 +0300 | [diff] [blame] | 1250 | @classmethod |
| 1251 | def tearDownClass(cls): |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 1252 | os.rmdir(support.TESTFN) |
| 1253 | |
| 1254 | |
Andrew Svetlov | 405faed | 2012-12-25 12:18:09 +0200 | [diff] [blame] | 1255 | class RemoveDirsTests(unittest.TestCase): |
| 1256 | def setUp(self): |
| 1257 | os.makedirs(support.TESTFN) |
| 1258 | |
| 1259 | def tearDown(self): |
| 1260 | support.rmtree(support.TESTFN) |
| 1261 | |
| 1262 | def test_remove_all(self): |
| 1263 | dira = os.path.join(support.TESTFN, 'dira') |
| 1264 | os.mkdir(dira) |
| 1265 | dirb = os.path.join(dira, 'dirb') |
| 1266 | os.mkdir(dirb) |
| 1267 | os.removedirs(dirb) |
| 1268 | self.assertFalse(os.path.exists(dirb)) |
| 1269 | self.assertFalse(os.path.exists(dira)) |
| 1270 | self.assertFalse(os.path.exists(support.TESTFN)) |
| 1271 | |
| 1272 | def test_remove_partial(self): |
| 1273 | dira = os.path.join(support.TESTFN, 'dira') |
| 1274 | os.mkdir(dira) |
| 1275 | dirb = os.path.join(dira, 'dirb') |
| 1276 | os.mkdir(dirb) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 1277 | create_file(os.path.join(dira, 'file.txt')) |
Andrew Svetlov | 405faed | 2012-12-25 12:18:09 +0200 | [diff] [blame] | 1278 | os.removedirs(dirb) |
| 1279 | self.assertFalse(os.path.exists(dirb)) |
| 1280 | self.assertTrue(os.path.exists(dira)) |
| 1281 | self.assertTrue(os.path.exists(support.TESTFN)) |
| 1282 | |
| 1283 | def test_remove_nothing(self): |
| 1284 | dira = os.path.join(support.TESTFN, 'dira') |
| 1285 | os.mkdir(dira) |
| 1286 | dirb = os.path.join(dira, 'dirb') |
| 1287 | os.mkdir(dirb) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 1288 | create_file(os.path.join(dirb, 'file.txt')) |
Andrew Svetlov | 405faed | 2012-12-25 12:18:09 +0200 | [diff] [blame] | 1289 | with self.assertRaises(OSError): |
| 1290 | os.removedirs(dirb) |
| 1291 | self.assertTrue(os.path.exists(dirb)) |
| 1292 | self.assertTrue(os.path.exists(dira)) |
| 1293 | self.assertTrue(os.path.exists(support.TESTFN)) |
| 1294 | |
| 1295 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1296 | class DevNullTests(unittest.TestCase): |
Martin v. Löwis | bdec50f | 2004-06-08 08:29:33 +0000 | [diff] [blame] | 1297 | def test_devnull(self): |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 1298 | with open(os.devnull, 'wb', 0) as f: |
Victor Stinner | a6d2c76 | 2011-06-30 18:20:11 +0200 | [diff] [blame] | 1299 | f.write(b'hello') |
| 1300 | f.close() |
| 1301 | with open(os.devnull, 'rb') as f: |
| 1302 | self.assertEqual(f.read(), b'') |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 1303 | |
Andrew Svetlov | 405faed | 2012-12-25 12:18:09 +0200 | [diff] [blame] | 1304 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1305 | class URandomTests(unittest.TestCase): |
Georg Brandl | 2daf6ae | 2012-02-20 19:54:16 +0100 | [diff] [blame] | 1306 | def test_urandom_length(self): |
| 1307 | self.assertEqual(len(os.urandom(0)), 0) |
| 1308 | self.assertEqual(len(os.urandom(1)), 1) |
| 1309 | self.assertEqual(len(os.urandom(10)), 10) |
| 1310 | self.assertEqual(len(os.urandom(100)), 100) |
| 1311 | self.assertEqual(len(os.urandom(1000)), 1000) |
| 1312 | |
| 1313 | def test_urandom_value(self): |
| 1314 | data1 = os.urandom(16) |
Victor Stinner | 9b1f474 | 2016-09-06 16:18:52 -0700 | [diff] [blame] | 1315 | self.assertIsInstance(data1, bytes) |
Georg Brandl | 2daf6ae | 2012-02-20 19:54:16 +0100 | [diff] [blame] | 1316 | data2 = os.urandom(16) |
| 1317 | self.assertNotEqual(data1, data2) |
| 1318 | |
| 1319 | def get_urandom_subprocess(self, count): |
| 1320 | code = '\n'.join(( |
| 1321 | 'import os, sys', |
| 1322 | 'data = os.urandom(%s)' % count, |
| 1323 | 'sys.stdout.buffer.write(data)', |
| 1324 | 'sys.stdout.buffer.flush()')) |
| 1325 | out = assert_python_ok('-c', code) |
| 1326 | stdout = out[1] |
Pablo Galindo | fb77e0d | 2017-12-07 06:55:44 +0000 | [diff] [blame] | 1327 | self.assertEqual(len(stdout), count) |
Georg Brandl | 2daf6ae | 2012-02-20 19:54:16 +0100 | [diff] [blame] | 1328 | return stdout |
| 1329 | |
| 1330 | def test_urandom_subprocess(self): |
| 1331 | data1 = self.get_urandom_subprocess(16) |
| 1332 | data2 = self.get_urandom_subprocess(16) |
| 1333 | self.assertNotEqual(data1, data2) |
Martin v. Löwis | dc3883f | 2004-08-29 15:46:35 +0000 | [diff] [blame] | 1334 | |
Victor Stinner | 4d6a3d6 | 2014-12-21 01:16:38 +0100 | [diff] [blame] | 1335 | |
Victor Stinner | 9b1f474 | 2016-09-06 16:18:52 -0700 | [diff] [blame] | 1336 | @unittest.skipUnless(hasattr(os, 'getrandom'), 'need os.getrandom()') |
| 1337 | class GetRandomTests(unittest.TestCase): |
Victor Stinner | 173a1f3 | 2016-09-06 19:57:40 -0700 | [diff] [blame] | 1338 | @classmethod |
| 1339 | def setUpClass(cls): |
| 1340 | try: |
| 1341 | os.getrandom(1) |
| 1342 | except OSError as exc: |
| 1343 | if exc.errno == errno.ENOSYS: |
| 1344 | # Python compiled on a more recent Linux version |
| 1345 | # than the current Linux kernel |
| 1346 | raise unittest.SkipTest("getrandom() syscall fails with ENOSYS") |
| 1347 | else: |
| 1348 | raise |
| 1349 | |
Victor Stinner | 9b1f474 | 2016-09-06 16:18:52 -0700 | [diff] [blame] | 1350 | def test_getrandom_type(self): |
| 1351 | data = os.getrandom(16) |
| 1352 | self.assertIsInstance(data, bytes) |
| 1353 | self.assertEqual(len(data), 16) |
| 1354 | |
| 1355 | def test_getrandom0(self): |
| 1356 | empty = os.getrandom(0) |
| 1357 | self.assertEqual(empty, b'') |
| 1358 | |
| 1359 | def test_getrandom_random(self): |
| 1360 | self.assertTrue(hasattr(os, 'GRND_RANDOM')) |
| 1361 | |
| 1362 | # Don't test os.getrandom(1, os.GRND_RANDOM) to not consume the rare |
| 1363 | # resource /dev/random |
| 1364 | |
| 1365 | def test_getrandom_nonblock(self): |
| 1366 | # The call must not fail. Check also that the flag exists |
| 1367 | try: |
| 1368 | os.getrandom(1, os.GRND_NONBLOCK) |
| 1369 | except BlockingIOError: |
| 1370 | # System urandom is not initialized yet |
| 1371 | pass |
| 1372 | |
| 1373 | def test_getrandom_value(self): |
| 1374 | data1 = os.getrandom(16) |
| 1375 | data2 = os.getrandom(16) |
| 1376 | self.assertNotEqual(data1, data2) |
| 1377 | |
| 1378 | |
Victor Stinner | d8f432a | 2015-09-18 16:24:31 +0200 | [diff] [blame] | 1379 | # os.urandom() doesn't use a file descriptor when it is implemented with the |
| 1380 | # getentropy() function, the getrandom() function or the getrandom() syscall |
| 1381 | OS_URANDOM_DONT_USE_FD = ( |
| 1382 | sysconfig.get_config_var('HAVE_GETENTROPY') == 1 |
| 1383 | or sysconfig.get_config_var('HAVE_GETRANDOM') == 1 |
| 1384 | or sysconfig.get_config_var('HAVE_GETRANDOM_SYSCALL') == 1) |
Victor Stinner | 4d6a3d6 | 2014-12-21 01:16:38 +0100 | [diff] [blame] | 1385 | |
Victor Stinner | d8f432a | 2015-09-18 16:24:31 +0200 | [diff] [blame] | 1386 | @unittest.skipIf(OS_URANDOM_DONT_USE_FD , |
| 1387 | "os.random() does not use a file descriptor") |
Victor Stinner | 4d6a3d6 | 2014-12-21 01:16:38 +0100 | [diff] [blame] | 1388 | class URandomFDTests(unittest.TestCase): |
Antoine Pitrou | ec34ab5 | 2013-08-16 20:44:38 +0200 | [diff] [blame] | 1389 | @unittest.skipUnless(resource, "test requires the resource module") |
| 1390 | def test_urandom_failure(self): |
Antoine Pitrou | eba25ba | 2013-08-24 20:52:27 +0200 | [diff] [blame] | 1391 | # Check urandom() failing when it is not able to open /dev/random. |
| 1392 | # We spawn a new process to make the test more robust (if getrlimit() |
| 1393 | # failed to restore the file descriptor limit after this, the whole |
| 1394 | # test suite would crash; this actually happened on the OS X Tiger |
| 1395 | # buildbot). |
| 1396 | code = """if 1: |
| 1397 | import errno |
| 1398 | import os |
| 1399 | import resource |
| 1400 | |
| 1401 | soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE) |
| 1402 | resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit)) |
| 1403 | try: |
Antoine Pitrou | ec34ab5 | 2013-08-16 20:44:38 +0200 | [diff] [blame] | 1404 | os.urandom(16) |
Antoine Pitrou | eba25ba | 2013-08-24 20:52:27 +0200 | [diff] [blame] | 1405 | except OSError as e: |
| 1406 | assert e.errno == errno.EMFILE, e.errno |
| 1407 | else: |
| 1408 | raise AssertionError("OSError not raised") |
| 1409 | """ |
| 1410 | assert_python_ok('-c', code) |
Antoine Pitrou | ec34ab5 | 2013-08-16 20:44:38 +0200 | [diff] [blame] | 1411 | |
Antoine Pitrou | e472aea | 2014-04-26 14:33:03 +0200 | [diff] [blame] | 1412 | def test_urandom_fd_closed(self): |
| 1413 | # Issue #21207: urandom() should reopen its fd to /dev/urandom if |
| 1414 | # closed. |
| 1415 | code = """if 1: |
| 1416 | import os |
| 1417 | import sys |
Steve Dower | d5a0be6 | 2015-03-07 21:25:54 -0800 | [diff] [blame] | 1418 | import test.support |
Antoine Pitrou | e472aea | 2014-04-26 14:33:03 +0200 | [diff] [blame] | 1419 | os.urandom(4) |
Steve Dower | d5a0be6 | 2015-03-07 21:25:54 -0800 | [diff] [blame] | 1420 | with test.support.SuppressCrashReport(): |
| 1421 | os.closerange(3, 256) |
Antoine Pitrou | e472aea | 2014-04-26 14:33:03 +0200 | [diff] [blame] | 1422 | sys.stdout.buffer.write(os.urandom(4)) |
| 1423 | """ |
| 1424 | rc, out, err = assert_python_ok('-Sc', code) |
| 1425 | |
| 1426 | def test_urandom_fd_reopened(self): |
| 1427 | # Issue #21207: urandom() should detect its fd to /dev/urandom |
| 1428 | # changed to something else, and reopen it. |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 1429 | self.addCleanup(support.unlink, support.TESTFN) |
| 1430 | create_file(support.TESTFN, b"x" * 256) |
| 1431 | |
Antoine Pitrou | e472aea | 2014-04-26 14:33:03 +0200 | [diff] [blame] | 1432 | code = """if 1: |
| 1433 | import os |
| 1434 | import sys |
Steve Dower | d5a0be6 | 2015-03-07 21:25:54 -0800 | [diff] [blame] | 1435 | import test.support |
Antoine Pitrou | e472aea | 2014-04-26 14:33:03 +0200 | [diff] [blame] | 1436 | os.urandom(4) |
Steve Dower | d5a0be6 | 2015-03-07 21:25:54 -0800 | [diff] [blame] | 1437 | with test.support.SuppressCrashReport(): |
| 1438 | for fd in range(3, 256): |
| 1439 | try: |
| 1440 | os.close(fd) |
| 1441 | except OSError: |
| 1442 | pass |
| 1443 | else: |
| 1444 | # Found the urandom fd (XXX hopefully) |
| 1445 | break |
| 1446 | os.closerange(3, 256) |
Antoine Pitrou | e472aea | 2014-04-26 14:33:03 +0200 | [diff] [blame] | 1447 | with open({TESTFN!r}, 'rb') as f: |
Xavier de Gaye | 2106010 | 2016-11-16 08:05:27 +0100 | [diff] [blame] | 1448 | new_fd = f.fileno() |
| 1449 | # Issue #26935: posix allows new_fd and fd to be equal but |
| 1450 | # some libc implementations have dup2 return an error in this |
| 1451 | # case. |
| 1452 | if new_fd != fd: |
| 1453 | os.dup2(new_fd, fd) |
Antoine Pitrou | e472aea | 2014-04-26 14:33:03 +0200 | [diff] [blame] | 1454 | sys.stdout.buffer.write(os.urandom(4)) |
| 1455 | sys.stdout.buffer.write(os.urandom(4)) |
| 1456 | """.format(TESTFN=support.TESTFN) |
| 1457 | rc, out, err = assert_python_ok('-Sc', code) |
| 1458 | self.assertEqual(len(out), 8) |
| 1459 | self.assertNotEqual(out[0:4], out[4:8]) |
| 1460 | rc, out2, err2 = assert_python_ok('-Sc', code) |
| 1461 | self.assertEqual(len(out2), 8) |
| 1462 | self.assertNotEqual(out2, out) |
| 1463 | |
Antoine Pitrou | ec34ab5 | 2013-08-16 20:44:38 +0200 | [diff] [blame] | 1464 | |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1465 | @contextlib.contextmanager |
| 1466 | def _execvpe_mockup(defpath=None): |
| 1467 | """ |
| 1468 | Stubs out execv and execve functions when used as context manager. |
| 1469 | Records exec calls. The mock execv and execve functions always raise an |
| 1470 | exception as they would normally never return. |
| 1471 | """ |
| 1472 | # A list of tuples containing (function name, first arg, args) |
| 1473 | # of calls to execv or execve that have been made. |
| 1474 | calls = [] |
| 1475 | |
| 1476 | def mock_execv(name, *args): |
| 1477 | calls.append(('execv', name, args)) |
| 1478 | raise RuntimeError("execv called") |
| 1479 | |
| 1480 | def mock_execve(name, *args): |
| 1481 | calls.append(('execve', name, args)) |
| 1482 | raise OSError(errno.ENOTDIR, "execve called") |
| 1483 | |
| 1484 | try: |
| 1485 | orig_execv = os.execv |
| 1486 | orig_execve = os.execve |
| 1487 | orig_defpath = os.defpath |
| 1488 | os.execv = mock_execv |
| 1489 | os.execve = mock_execve |
| 1490 | if defpath is not None: |
| 1491 | os.defpath = defpath |
| 1492 | yield calls |
| 1493 | finally: |
| 1494 | os.execv = orig_execv |
| 1495 | os.execve = orig_execve |
| 1496 | os.defpath = orig_defpath |
| 1497 | |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 1498 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1499 | class ExecTests(unittest.TestCase): |
Mark Dickinson | 7cf0389 | 2010-04-16 13:45:35 +0000 | [diff] [blame] | 1500 | @unittest.skipIf(USING_LINUXTHREADS, |
| 1501 | "avoid triggering a linuxthreads bug: see issue #4970") |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1502 | def test_execvpe_with_bad_program(self): |
Mark Dickinson | 7cf0389 | 2010-04-16 13:45:35 +0000 | [diff] [blame] | 1503 | self.assertRaises(OSError, os.execvpe, 'no such app-', |
| 1504 | ['no such app-'], None) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1505 | |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 1506 | def test_execv_with_bad_arglist(self): |
| 1507 | self.assertRaises(ValueError, os.execv, 'notepad', ()) |
| 1508 | self.assertRaises(ValueError, os.execv, 'notepad', []) |
| 1509 | self.assertRaises(ValueError, os.execv, 'notepad', ('',)) |
| 1510 | self.assertRaises(ValueError, os.execv, 'notepad', ['']) |
| 1511 | |
Thomas Heller | 6790d60 | 2007-08-30 17:15:14 +0000 | [diff] [blame] | 1512 | def test_execvpe_with_bad_arglist(self): |
| 1513 | self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 1514 | self.assertRaises(ValueError, os.execvpe, 'notepad', [], {}) |
| 1515 | self.assertRaises(ValueError, os.execvpe, 'notepad', [''], {}) |
Thomas Heller | 6790d60 | 2007-08-30 17:15:14 +0000 | [diff] [blame] | 1516 | |
Gregory P. Smith | 4ae3777 | 2010-05-08 18:05:46 +0000 | [diff] [blame] | 1517 | @unittest.skipUnless(hasattr(os, '_execvpe'), |
| 1518 | "No internal os._execvpe function to test.") |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1519 | def _test_internal_execvpe(self, test_type): |
| 1520 | program_path = os.sep + 'absolutepath' |
| 1521 | if test_type is bytes: |
| 1522 | program = b'executable' |
| 1523 | fullpath = os.path.join(os.fsencode(program_path), program) |
| 1524 | native_fullpath = fullpath |
| 1525 | arguments = [b'progname', 'arg1', 'arg2'] |
| 1526 | else: |
| 1527 | program = 'executable' |
| 1528 | arguments = ['progname', 'arg1', 'arg2'] |
| 1529 | fullpath = os.path.join(program_path, program) |
| 1530 | if os.name != "nt": |
| 1531 | native_fullpath = os.fsencode(fullpath) |
| 1532 | else: |
| 1533 | native_fullpath = fullpath |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1534 | env = {'spam': 'beans'} |
| 1535 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1536 | # test os._execvpe() with an absolute path |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1537 | with _execvpe_mockup() as calls: |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1538 | self.assertRaises(RuntimeError, |
| 1539 | os._execvpe, fullpath, arguments) |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1540 | self.assertEqual(len(calls), 1) |
| 1541 | self.assertEqual(calls[0], ('execv', fullpath, (arguments,))) |
| 1542 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1543 | # test os._execvpe() with a relative path: |
| 1544 | # os.get_exec_path() returns defpath |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1545 | with _execvpe_mockup(defpath=program_path) as calls: |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1546 | self.assertRaises(OSError, |
| 1547 | os._execvpe, program, arguments, env=env) |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1548 | self.assertEqual(len(calls), 1) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1549 | self.assertSequenceEqual(calls[0], |
| 1550 | ('execve', native_fullpath, (arguments, env))) |
| 1551 | |
| 1552 | # test os._execvpe() with a relative path: |
| 1553 | # os.get_exec_path() reads the 'PATH' variable |
| 1554 | with _execvpe_mockup() as calls: |
| 1555 | env_path = env.copy() |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 1556 | if test_type is bytes: |
| 1557 | env_path[b'PATH'] = program_path |
| 1558 | else: |
| 1559 | env_path['PATH'] = program_path |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1560 | self.assertRaises(OSError, |
| 1561 | os._execvpe, program, arguments, env=env_path) |
| 1562 | self.assertEqual(len(calls), 1) |
| 1563 | self.assertSequenceEqual(calls[0], |
| 1564 | ('execve', native_fullpath, (arguments, env_path))) |
| 1565 | |
| 1566 | def test_internal_execvpe_str(self): |
| 1567 | self._test_internal_execvpe(str) |
| 1568 | if os.name != "nt": |
| 1569 | self._test_internal_execvpe(bytes) |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1570 | |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 1571 | def test_execve_invalid_env(self): |
| 1572 | args = [sys.executable, '-c', 'pass'] |
| 1573 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 1574 | # null character in the environment variable name |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 1575 | newenv = os.environ.copy() |
| 1576 | newenv["FRUIT\0VEGETABLE"] = "cabbage" |
| 1577 | with self.assertRaises(ValueError): |
| 1578 | os.execve(args[0], args, newenv) |
| 1579 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 1580 | # null character in the environment variable value |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 1581 | newenv = os.environ.copy() |
| 1582 | newenv["FRUIT"] = "orange\0VEGETABLE=cabbage" |
| 1583 | with self.assertRaises(ValueError): |
| 1584 | os.execve(args[0], args, newenv) |
| 1585 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 1586 | # equal character in the environment variable name |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 1587 | newenv = os.environ.copy() |
| 1588 | newenv["FRUIT=ORANGE"] = "lemon" |
| 1589 | with self.assertRaises(ValueError): |
| 1590 | os.execve(args[0], args, newenv) |
| 1591 | |
Gregory P. Smith | 4ae3777 | 2010-05-08 18:05:46 +0000 | [diff] [blame] | 1592 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1593 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1594 | class Win32ErrorTests(unittest.TestCase): |
Victor Stinner | e77c974 | 2016-03-25 10:28:23 +0100 | [diff] [blame] | 1595 | def setUp(self): |
Victor Stinner | 3283014 | 2016-03-25 15:12:08 +0100 | [diff] [blame] | 1596 | try: |
| 1597 | os.stat(support.TESTFN) |
| 1598 | except FileNotFoundError: |
| 1599 | exists = False |
| 1600 | except OSError as exc: |
| 1601 | exists = True |
| 1602 | self.fail("file %s must not exist; os.stat failed with %s" |
| 1603 | % (support.TESTFN, exc)) |
| 1604 | else: |
| 1605 | self.fail("file %s must not exist" % support.TESTFN) |
Victor Stinner | e77c974 | 2016-03-25 10:28:23 +0100 | [diff] [blame] | 1606 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1607 | def test_rename(self): |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 1608 | self.assertRaises(OSError, os.rename, support.TESTFN, support.TESTFN+".bak") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1609 | |
| 1610 | def test_remove(self): |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 1611 | self.assertRaises(OSError, os.remove, support.TESTFN) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1612 | |
| 1613 | def test_chdir(self): |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 1614 | self.assertRaises(OSError, os.chdir, support.TESTFN) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1615 | |
| 1616 | def test_mkdir(self): |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 1617 | self.addCleanup(support.unlink, support.TESTFN) |
| 1618 | |
Victor Stinner | e77c974 | 2016-03-25 10:28:23 +0100 | [diff] [blame] | 1619 | with open(support.TESTFN, "x") as f: |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 1620 | self.assertRaises(OSError, os.mkdir, support.TESTFN) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1621 | |
| 1622 | def test_utime(self): |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 1623 | self.assertRaises(OSError, os.utime, support.TESTFN, None) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1624 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1625 | def test_chmod(self): |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 1626 | self.assertRaises(OSError, os.chmod, support.TESTFN, 0) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1627 | |
Victor Stinner | e77c974 | 2016-03-25 10:28:23 +0100 | [diff] [blame] | 1628 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1629 | class TestInvalidFD(unittest.TestCase): |
Benjamin Peterson | 05e782f | 2009-01-19 15:15:02 +0000 | [diff] [blame] | 1630 | singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat", |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1631 | "fstatvfs", "fsync", "tcgetpgrp", "ttyname"] |
| 1632 | #singles.append("close") |
Steve Dower | 3929499 | 2016-08-30 21:22:36 -0700 | [diff] [blame] | 1633 | #We omit close because it doesn't raise an exception on some platforms |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1634 | def get_single(f): |
| 1635 | def helper(self): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1636 | if hasattr(os, f): |
| 1637 | self.check(getattr(os, f)) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1638 | return helper |
| 1639 | for f in singles: |
| 1640 | locals()["test_"+f] = get_single(f) |
| 1641 | |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1642 | def check(self, f, *args): |
Benjamin Peterson | 5c6d787 | 2009-02-06 02:40:07 +0000 | [diff] [blame] | 1643 | try: |
| 1644 | f(support.make_bad_fd(), *args) |
| 1645 | except OSError as e: |
| 1646 | self.assertEqual(e.errno, errno.EBADF) |
| 1647 | else: |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 1648 | self.fail("%r didn't raise an OSError with a bad file descriptor" |
Benjamin Peterson | 5c6d787 | 2009-02-06 02:40:07 +0000 | [diff] [blame] | 1649 | % f) |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1650 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1651 | @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1652 | def test_isatty(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1653 | self.assertEqual(os.isatty(support.make_bad_fd()), False) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1654 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1655 | @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1656 | def test_closerange(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1657 | fd = support.make_bad_fd() |
| 1658 | # Make sure none of the descriptors we are about to close are |
| 1659 | # currently valid (issue 6542). |
| 1660 | for i in range(10): |
| 1661 | try: os.fstat(fd+i) |
| 1662 | except OSError: |
| 1663 | pass |
| 1664 | else: |
| 1665 | break |
| 1666 | if i < 2: |
| 1667 | raise unittest.SkipTest( |
| 1668 | "Unable to acquire a range of invalid file descriptors") |
| 1669 | self.assertEqual(os.closerange(fd, fd + i-1), None) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1670 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1671 | @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1672 | def test_dup2(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1673 | self.check(os.dup2, 20) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1674 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1675 | @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1676 | def test_fchmod(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1677 | self.check(os.fchmod, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1678 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1679 | @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1680 | def test_fchown(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1681 | self.check(os.fchown, -1, -1) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1682 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1683 | @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1684 | def test_fpathconf(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1685 | self.check(os.pathconf, "PC_NAME_MAX") |
| 1686 | self.check(os.fpathconf, "PC_NAME_MAX") |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1687 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1688 | @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1689 | def test_ftruncate(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1690 | self.check(os.truncate, 0) |
| 1691 | self.check(os.ftruncate, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1692 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1693 | @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1694 | def test_lseek(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1695 | self.check(os.lseek, 0, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1696 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1697 | @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1698 | def test_read(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1699 | self.check(os.read, 1) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1700 | |
Victor Stinner | 57ddf78 | 2014-01-08 15:21:28 +0100 | [diff] [blame] | 1701 | @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()') |
| 1702 | def test_readv(self): |
| 1703 | buf = bytearray(10) |
| 1704 | self.check(os.readv, [buf]) |
| 1705 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1706 | @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1707 | def test_tcsetpgrpt(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1708 | self.check(os.tcsetpgrp, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1709 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1710 | @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()') |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1711 | def test_write(self): |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1712 | self.check(os.write, b" ") |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1713 | |
Victor Stinner | 57ddf78 | 2014-01-08 15:21:28 +0100 | [diff] [blame] | 1714 | @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()') |
| 1715 | def test_writev(self): |
| 1716 | self.check(os.writev, [b'abc']) |
| 1717 | |
Victor Stinner | 1db9e7b | 2014-07-29 22:32:47 +0200 | [diff] [blame] | 1718 | def test_inheritable(self): |
| 1719 | self.check(os.get_inheritable) |
| 1720 | self.check(os.set_inheritable, True) |
| 1721 | |
| 1722 | @unittest.skipUnless(hasattr(os, 'get_blocking'), |
| 1723 | 'needs os.get_blocking() and os.set_blocking()') |
| 1724 | def test_blocking(self): |
| 1725 | self.check(os.get_blocking) |
| 1726 | self.check(os.set_blocking, True) |
| 1727 | |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1728 | |
| 1729 | class LinkTests(unittest.TestCase): |
| 1730 | def setUp(self): |
| 1731 | self.file1 = support.TESTFN |
| 1732 | self.file2 = os.path.join(support.TESTFN + "2") |
| 1733 | |
Brian Curtin | c0abc4e | 2010-11-30 23:46:54 +0000 | [diff] [blame] | 1734 | def tearDown(self): |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1735 | for file in (self.file1, self.file2): |
| 1736 | if os.path.exists(file): |
| 1737 | os.unlink(file) |
| 1738 | |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1739 | def _test_link(self, file1, file2): |
Victor Stinner | e77c974 | 2016-03-25 10:28:23 +0100 | [diff] [blame] | 1740 | create_file(file1) |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1741 | |
xdegaye | 6a55d09 | 2017-11-12 17:57:04 +0100 | [diff] [blame] | 1742 | try: |
| 1743 | os.link(file1, file2) |
| 1744 | except PermissionError as e: |
| 1745 | self.skipTest('os.link(): %s' % e) |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1746 | with open(file1, "r") as f1, open(file2, "r") as f2: |
| 1747 | self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno())) |
| 1748 | |
| 1749 | def test_link(self): |
| 1750 | self._test_link(self.file1, self.file2) |
| 1751 | |
| 1752 | def test_link_bytes(self): |
| 1753 | self._test_link(bytes(self.file1, sys.getfilesystemencoding()), |
| 1754 | bytes(self.file2, sys.getfilesystemencoding())) |
| 1755 | |
Brian Curtin | f498b75 | 2010-11-30 15:54:04 +0000 | [diff] [blame] | 1756 | def test_unicode_name(self): |
Brian Curtin | 43f0c27 | 2010-11-30 15:40:04 +0000 | [diff] [blame] | 1757 | try: |
Brian Curtin | f498b75 | 2010-11-30 15:54:04 +0000 | [diff] [blame] | 1758 | os.fsencode("\xf1") |
Brian Curtin | 43f0c27 | 2010-11-30 15:40:04 +0000 | [diff] [blame] | 1759 | except UnicodeError: |
| 1760 | raise unittest.SkipTest("Unable to encode for this platform.") |
| 1761 | |
Brian Curtin | f498b75 | 2010-11-30 15:54:04 +0000 | [diff] [blame] | 1762 | self.file1 += "\xf1" |
Brian Curtin | fc889c4 | 2010-11-28 23:59:46 +0000 | [diff] [blame] | 1763 | self.file2 = self.file1 + "2" |
| 1764 | self._test_link(self.file1, self.file2) |
| 1765 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1766 | @unittest.skipIf(sys.platform == "win32", "Posix specific tests") |
| 1767 | class PosixUidGidTests(unittest.TestCase): |
| 1768 | @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()') |
| 1769 | def test_setuid(self): |
| 1770 | if os.getuid() != 0: |
| 1771 | self.assertRaises(OSError, os.setuid, 0) |
| 1772 | self.assertRaises(OverflowError, os.setuid, 1<<32) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1773 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1774 | @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()') |
| 1775 | def test_setgid(self): |
| 1776 | if os.getuid() != 0 and not HAVE_WHEEL_GROUP: |
| 1777 | self.assertRaises(OSError, os.setgid, 0) |
| 1778 | self.assertRaises(OverflowError, os.setgid, 1<<32) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1779 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1780 | @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()') |
| 1781 | def test_seteuid(self): |
| 1782 | if os.getuid() != 0: |
| 1783 | self.assertRaises(OSError, os.seteuid, 0) |
| 1784 | self.assertRaises(OverflowError, os.seteuid, 1<<32) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1785 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1786 | @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()') |
| 1787 | def test_setegid(self): |
| 1788 | if os.getuid() != 0 and not HAVE_WHEEL_GROUP: |
| 1789 | self.assertRaises(OSError, os.setegid, 0) |
| 1790 | self.assertRaises(OverflowError, os.setegid, 1<<32) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1791 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1792 | @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()') |
| 1793 | def test_setreuid(self): |
| 1794 | if os.getuid() != 0: |
| 1795 | self.assertRaises(OSError, os.setreuid, 0, 0) |
| 1796 | self.assertRaises(OverflowError, os.setreuid, 1<<32, 0) |
| 1797 | self.assertRaises(OverflowError, os.setreuid, 0, 1<<32) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1798 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1799 | @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()') |
| 1800 | def test_setreuid_neg1(self): |
| 1801 | # Needs to accept -1. We run this in a subprocess to avoid |
| 1802 | # altering the test runner's process state (issue8045). |
| 1803 | subprocess.check_call([ |
| 1804 | sys.executable, '-c', |
| 1805 | 'import os,sys;os.setreuid(-1,-1);sys.exit(0)']) |
Benjamin Peterson | ebe87ba | 2010-03-06 20:34:24 +0000 | [diff] [blame] | 1806 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1807 | @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()') |
| 1808 | def test_setregid(self): |
| 1809 | if os.getuid() != 0 and not HAVE_WHEEL_GROUP: |
| 1810 | self.assertRaises(OSError, os.setregid, 0, 0) |
| 1811 | self.assertRaises(OverflowError, os.setregid, 1<<32, 0) |
| 1812 | self.assertRaises(OverflowError, os.setregid, 0, 1<<32) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1813 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1814 | @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()') |
| 1815 | def test_setregid_neg1(self): |
| 1816 | # Needs to accept -1. We run this in a subprocess to avoid |
| 1817 | # altering the test runner's process state (issue8045). |
| 1818 | subprocess.check_call([ |
| 1819 | sys.executable, '-c', |
| 1820 | 'import os,sys;os.setregid(-1,-1);sys.exit(0)']) |
Benjamin Peterson | ebe87ba | 2010-03-06 20:34:24 +0000 | [diff] [blame] | 1821 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1822 | @unittest.skipIf(sys.platform == "win32", "Posix specific tests") |
| 1823 | class Pep383Tests(unittest.TestCase): |
| 1824 | def setUp(self): |
| 1825 | if support.TESTFN_UNENCODABLE: |
| 1826 | self.dir = support.TESTFN_UNENCODABLE |
| 1827 | elif support.TESTFN_NONASCII: |
| 1828 | self.dir = support.TESTFN_NONASCII |
| 1829 | else: |
| 1830 | self.dir = support.TESTFN |
| 1831 | self.bdir = os.fsencode(self.dir) |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1832 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1833 | bytesfn = [] |
| 1834 | def add_filename(fn): |
Victor Stinner | d91df1a | 2010-08-18 10:56:19 +0000 | [diff] [blame] | 1835 | try: |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1836 | fn = os.fsencode(fn) |
| 1837 | except UnicodeEncodeError: |
| 1838 | return |
| 1839 | bytesfn.append(fn) |
| 1840 | add_filename(support.TESTFN_UNICODE) |
| 1841 | if support.TESTFN_UNENCODABLE: |
| 1842 | add_filename(support.TESTFN_UNENCODABLE) |
| 1843 | if support.TESTFN_NONASCII: |
| 1844 | add_filename(support.TESTFN_NONASCII) |
| 1845 | if not bytesfn: |
| 1846 | self.skipTest("couldn't create any non-ascii filename") |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1847 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1848 | self.unicodefn = set() |
| 1849 | os.mkdir(self.dir) |
| 1850 | try: |
| 1851 | for fn in bytesfn: |
| 1852 | support.create_empty_file(os.path.join(self.bdir, fn)) |
| 1853 | fn = os.fsdecode(fn) |
| 1854 | if fn in self.unicodefn: |
| 1855 | raise ValueError("duplicate filename") |
| 1856 | self.unicodefn.add(fn) |
| 1857 | except: |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1858 | shutil.rmtree(self.dir) |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1859 | raise |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1860 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1861 | def tearDown(self): |
| 1862 | shutil.rmtree(self.dir) |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1863 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1864 | def test_listdir(self): |
| 1865 | expected = self.unicodefn |
| 1866 | found = set(os.listdir(self.dir)) |
| 1867 | self.assertEqual(found, expected) |
| 1868 | # test listdir without arguments |
| 1869 | current_directory = os.getcwd() |
| 1870 | try: |
| 1871 | os.chdir(os.sep) |
| 1872 | self.assertEqual(set(os.listdir()), set(os.listdir(os.sep))) |
| 1873 | finally: |
| 1874 | os.chdir(current_directory) |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1875 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1876 | def test_open(self): |
| 1877 | for fn in self.unicodefn: |
| 1878 | f = open(os.path.join(self.dir, fn), 'rb') |
| 1879 | f.close() |
Victor Stinner | e4110dc | 2013-01-01 23:05:55 +0100 | [diff] [blame] | 1880 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1881 | @unittest.skipUnless(hasattr(os, 'statvfs'), |
| 1882 | "need os.statvfs()") |
| 1883 | def test_statvfs(self): |
| 1884 | # issue #9645 |
| 1885 | for fn in self.unicodefn: |
| 1886 | # should not fail with file not found error |
| 1887 | fullname = os.path.join(self.dir, fn) |
| 1888 | os.statvfs(fullname) |
| 1889 | |
| 1890 | def test_stat(self): |
| 1891 | for fn in self.unicodefn: |
| 1892 | os.stat(os.path.join(self.dir, fn)) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1893 | |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1894 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
| 1895 | class Win32KillTests(unittest.TestCase): |
Brian Curtin | c3acbc3 | 2010-05-28 16:08:40 +0000 | [diff] [blame] | 1896 | def _kill(self, sig): |
| 1897 | # Start sys.executable as a subprocess and communicate from the |
| 1898 | # subprocess to the parent that the interpreter is ready. When it |
| 1899 | # becomes ready, send *sig* via os.kill to the subprocess and check |
| 1900 | # that the return code is equal to *sig*. |
| 1901 | import ctypes |
| 1902 | from ctypes import wintypes |
| 1903 | import msvcrt |
| 1904 | |
| 1905 | # Since we can't access the contents of the process' stdout until the |
| 1906 | # process has exited, use PeekNamedPipe to see what's inside stdout |
| 1907 | # without waiting. This is done so we can tell that the interpreter |
| 1908 | # is started and running at a point where it could handle a signal. |
| 1909 | PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe |
| 1910 | PeekNamedPipe.restype = wintypes.BOOL |
| 1911 | PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle |
| 1912 | ctypes.POINTER(ctypes.c_char), # stdout buf |
| 1913 | wintypes.DWORD, # Buffer size |
| 1914 | ctypes.POINTER(wintypes.DWORD), # bytes read |
| 1915 | ctypes.POINTER(wintypes.DWORD), # bytes avail |
| 1916 | ctypes.POINTER(wintypes.DWORD)) # bytes left |
| 1917 | msg = "running" |
| 1918 | proc = subprocess.Popen([sys.executable, "-c", |
| 1919 | "import sys;" |
| 1920 | "sys.stdout.write('{}');" |
| 1921 | "sys.stdout.flush();" |
| 1922 | "input()".format(msg)], |
| 1923 | stdout=subprocess.PIPE, |
| 1924 | stderr=subprocess.PIPE, |
| 1925 | stdin=subprocess.PIPE) |
Brian Curtin | 43ec577 | 2010-11-05 15:17:11 +0000 | [diff] [blame] | 1926 | self.addCleanup(proc.stdout.close) |
| 1927 | self.addCleanup(proc.stderr.close) |
| 1928 | self.addCleanup(proc.stdin.close) |
Brian Curtin | c3acbc3 | 2010-05-28 16:08:40 +0000 | [diff] [blame] | 1929 | |
| 1930 | count, max = 0, 100 |
| 1931 | while count < max and proc.poll() is None: |
| 1932 | # Create a string buffer to store the result of stdout from the pipe |
| 1933 | buf = ctypes.create_string_buffer(len(msg)) |
| 1934 | # Obtain the text currently in proc.stdout |
| 1935 | # Bytes read/avail/left are left as NULL and unused |
| 1936 | rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), |
| 1937 | buf, ctypes.sizeof(buf), None, None, None) |
| 1938 | self.assertNotEqual(rslt, 0, "PeekNamedPipe failed") |
| 1939 | if buf.value: |
| 1940 | self.assertEqual(msg, buf.value.decode()) |
| 1941 | break |
| 1942 | time.sleep(0.1) |
| 1943 | count += 1 |
| 1944 | else: |
| 1945 | self.fail("Did not receive communication from the subprocess") |
| 1946 | |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1947 | os.kill(proc.pid, sig) |
| 1948 | self.assertEqual(proc.wait(), sig) |
| 1949 | |
| 1950 | def test_kill_sigterm(self): |
| 1951 | # SIGTERM doesn't mean anything special, but make sure it works |
Brian Curtin | c3acbc3 | 2010-05-28 16:08:40 +0000 | [diff] [blame] | 1952 | self._kill(signal.SIGTERM) |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1953 | |
| 1954 | def test_kill_int(self): |
| 1955 | # os.kill on Windows can take an int which gets set as the exit code |
Brian Curtin | c3acbc3 | 2010-05-28 16:08:40 +0000 | [diff] [blame] | 1956 | self._kill(100) |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1957 | |
| 1958 | def _kill_with_event(self, event, name): |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1959 | tagname = "test_os_%s" % uuid.uuid1() |
| 1960 | m = mmap.mmap(-1, 1, tagname) |
| 1961 | m[0] = 0 |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1962 | # Run a script which has console control handling enabled. |
| 1963 | proc = subprocess.Popen([sys.executable, |
| 1964 | os.path.join(os.path.dirname(__file__), |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1965 | "win_console_handler.py"), tagname], |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1966 | creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) |
| 1967 | # Let the interpreter startup before we send signals. See #3137. |
Hirokazu Yamamoto | 8e9fe9f | 2010-12-05 02:41:46 +0000 | [diff] [blame] | 1968 | count, max = 0, 100 |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1969 | while count < max and proc.poll() is None: |
Brian Curtin | f668df5 | 2010-10-15 14:21:06 +0000 | [diff] [blame] | 1970 | if m[0] == 1: |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1971 | break |
Hirokazu Yamamoto | 8e9fe9f | 2010-12-05 02:41:46 +0000 | [diff] [blame] | 1972 | time.sleep(0.1) |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1973 | count += 1 |
| 1974 | else: |
Hirokazu Yamamoto | 8e9fe9f | 2010-12-05 02:41:46 +0000 | [diff] [blame] | 1975 | # Forcefully kill the process if we weren't able to signal it. |
| 1976 | os.kill(proc.pid, signal.SIGINT) |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1977 | self.fail("Subprocess didn't finish initialization") |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1978 | os.kill(proc.pid, event) |
| 1979 | # proc.send_signal(event) could also be done here. |
| 1980 | # Allow time for the signal to be passed and the process to exit. |
| 1981 | time.sleep(0.5) |
| 1982 | if not proc.poll(): |
| 1983 | # Forcefully kill the process if we weren't able to signal it. |
| 1984 | os.kill(proc.pid, signal.SIGINT) |
| 1985 | self.fail("subprocess did not stop on {}".format(name)) |
| 1986 | |
Serhiy Storchaka | 0424eaf | 2015-09-12 17:45:25 +0300 | [diff] [blame] | 1987 | @unittest.skip("subprocesses aren't inheriting Ctrl+C property") |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1988 | def test_CTRL_C_EVENT(self): |
| 1989 | from ctypes import wintypes |
| 1990 | import ctypes |
| 1991 | |
| 1992 | # Make a NULL value by creating a pointer with no argument. |
| 1993 | NULL = ctypes.POINTER(ctypes.c_int)() |
| 1994 | SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler |
| 1995 | SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int), |
| 1996 | wintypes.BOOL) |
| 1997 | SetConsoleCtrlHandler.restype = wintypes.BOOL |
| 1998 | |
| 1999 | # Calling this with NULL and FALSE causes the calling process to |
Serhiy Storchaka | 0424eaf | 2015-09-12 17:45:25 +0300 | [diff] [blame] | 2000 | # handle Ctrl+C, rather than ignore it. This property is inherited |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 2001 | # by subprocesses. |
| 2002 | SetConsoleCtrlHandler(NULL, 0) |
| 2003 | |
| 2004 | self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT") |
| 2005 | |
| 2006 | def test_CTRL_BREAK_EVENT(self): |
| 2007 | self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") |
| 2008 | |
| 2009 | |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 2010 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
Tim Golden | 781bbeb | 2013-10-25 20:24:06 +0100 | [diff] [blame] | 2011 | class Win32ListdirTests(unittest.TestCase): |
| 2012 | """Test listdir on Windows.""" |
| 2013 | |
| 2014 | def setUp(self): |
| 2015 | self.created_paths = [] |
| 2016 | for i in range(2): |
| 2017 | dir_name = 'SUB%d' % i |
| 2018 | dir_path = os.path.join(support.TESTFN, dir_name) |
| 2019 | file_name = 'FILE%d' % i |
| 2020 | file_path = os.path.join(support.TESTFN, file_name) |
| 2021 | os.makedirs(dir_path) |
| 2022 | with open(file_path, 'w') as f: |
| 2023 | f.write("I'm %s and proud of it. Blame test_os.\n" % file_path) |
| 2024 | self.created_paths.extend([dir_name, file_name]) |
| 2025 | self.created_paths.sort() |
| 2026 | |
| 2027 | def tearDown(self): |
| 2028 | shutil.rmtree(support.TESTFN) |
| 2029 | |
| 2030 | def test_listdir_no_extended_path(self): |
| 2031 | """Test when the path is not an "extended" path.""" |
| 2032 | # unicode |
| 2033 | self.assertEqual( |
| 2034 | sorted(os.listdir(support.TESTFN)), |
| 2035 | self.created_paths) |
Victor Stinner | 923590e | 2016-03-24 09:11:48 +0100 | [diff] [blame] | 2036 | |
Tim Golden | 781bbeb | 2013-10-25 20:24:06 +0100 | [diff] [blame] | 2037 | # bytes |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 2038 | self.assertEqual( |
| 2039 | sorted(os.listdir(os.fsencode(support.TESTFN))), |
| 2040 | [os.fsencode(path) for path in self.created_paths]) |
Tim Golden | 781bbeb | 2013-10-25 20:24:06 +0100 | [diff] [blame] | 2041 | |
| 2042 | def test_listdir_extended_path(self): |
| 2043 | """Test when the path starts with '\\\\?\\'.""" |
Tim Golden | 1cc3540 | 2013-10-25 21:26:06 +0100 | [diff] [blame] | 2044 | # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath |
Tim Golden | 781bbeb | 2013-10-25 20:24:06 +0100 | [diff] [blame] | 2045 | # unicode |
| 2046 | path = '\\\\?\\' + os.path.abspath(support.TESTFN) |
| 2047 | self.assertEqual( |
| 2048 | sorted(os.listdir(path)), |
| 2049 | self.created_paths) |
Victor Stinner | 923590e | 2016-03-24 09:11:48 +0100 | [diff] [blame] | 2050 | |
Tim Golden | 781bbeb | 2013-10-25 20:24:06 +0100 | [diff] [blame] | 2051 | # bytes |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 2052 | path = b'\\\\?\\' + os.fsencode(os.path.abspath(support.TESTFN)) |
| 2053 | self.assertEqual( |
| 2054 | sorted(os.listdir(path)), |
| 2055 | [os.fsencode(path) for path in self.created_paths]) |
Tim Golden | 781bbeb | 2013-10-25 20:24:06 +0100 | [diff] [blame] | 2056 | |
| 2057 | |
| 2058 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 2059 | @support.skip_unless_symlink |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 2060 | class Win32SymlinkTests(unittest.TestCase): |
| 2061 | filelink = 'filelinktest' |
| 2062 | filelink_target = os.path.abspath(__file__) |
| 2063 | dirlink = 'dirlinktest' |
| 2064 | dirlink_target = os.path.dirname(filelink_target) |
| 2065 | missing_link = 'missing link' |
| 2066 | |
| 2067 | def setUp(self): |
| 2068 | assert os.path.exists(self.dirlink_target) |
| 2069 | assert os.path.exists(self.filelink_target) |
| 2070 | assert not os.path.exists(self.dirlink) |
| 2071 | assert not os.path.exists(self.filelink) |
| 2072 | assert not os.path.exists(self.missing_link) |
| 2073 | |
| 2074 | def tearDown(self): |
| 2075 | if os.path.exists(self.filelink): |
| 2076 | os.remove(self.filelink) |
| 2077 | if os.path.exists(self.dirlink): |
| 2078 | os.rmdir(self.dirlink) |
| 2079 | if os.path.lexists(self.missing_link): |
| 2080 | os.remove(self.missing_link) |
| 2081 | |
| 2082 | def test_directory_link(self): |
Jason R. Coombs | 3a09286 | 2013-05-27 23:21:28 -0400 | [diff] [blame] | 2083 | os.symlink(self.dirlink_target, self.dirlink) |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 2084 | self.assertTrue(os.path.exists(self.dirlink)) |
| 2085 | self.assertTrue(os.path.isdir(self.dirlink)) |
| 2086 | self.assertTrue(os.path.islink(self.dirlink)) |
| 2087 | self.check_stat(self.dirlink, self.dirlink_target) |
| 2088 | |
| 2089 | def test_file_link(self): |
| 2090 | os.symlink(self.filelink_target, self.filelink) |
| 2091 | self.assertTrue(os.path.exists(self.filelink)) |
| 2092 | self.assertTrue(os.path.isfile(self.filelink)) |
| 2093 | self.assertTrue(os.path.islink(self.filelink)) |
| 2094 | self.check_stat(self.filelink, self.filelink_target) |
| 2095 | |
| 2096 | def _create_missing_dir_link(self): |
| 2097 | 'Create a "directory" link to a non-existent target' |
| 2098 | linkname = self.missing_link |
| 2099 | if os.path.lexists(linkname): |
| 2100 | os.remove(linkname) |
| 2101 | target = r'c:\\target does not exist.29r3c740' |
| 2102 | assert not os.path.exists(target) |
| 2103 | target_is_dir = True |
| 2104 | os.symlink(target, linkname, target_is_dir) |
| 2105 | |
| 2106 | def test_remove_directory_link_to_missing_target(self): |
| 2107 | self._create_missing_dir_link() |
| 2108 | # For compatibility with Unix, os.remove will check the |
| 2109 | # directory status and call RemoveDirectory if the symlink |
| 2110 | # was created with target_is_dir==True. |
| 2111 | os.remove(self.missing_link) |
| 2112 | |
| 2113 | @unittest.skip("currently fails; consider for improvement") |
| 2114 | def test_isdir_on_directory_link_to_missing_target(self): |
| 2115 | self._create_missing_dir_link() |
| 2116 | # consider having isdir return true for directory links |
| 2117 | self.assertTrue(os.path.isdir(self.missing_link)) |
| 2118 | |
| 2119 | @unittest.skip("currently fails; consider for improvement") |
| 2120 | def test_rmdir_on_directory_link_to_missing_target(self): |
| 2121 | self._create_missing_dir_link() |
| 2122 | # consider allowing rmdir to remove directory links |
| 2123 | os.rmdir(self.missing_link) |
| 2124 | |
| 2125 | def check_stat(self, link, target): |
| 2126 | self.assertEqual(os.stat(link), os.stat(target)) |
| 2127 | self.assertNotEqual(os.lstat(link), os.stat(link)) |
| 2128 | |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2129 | bytes_link = os.fsencode(link) |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 2130 | self.assertEqual(os.stat(bytes_link), os.stat(target)) |
| 2131 | self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link)) |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2132 | |
| 2133 | def test_12084(self): |
| 2134 | level1 = os.path.abspath(support.TESTFN) |
| 2135 | level2 = os.path.join(level1, "level2") |
| 2136 | level3 = os.path.join(level2, "level3") |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2137 | self.addCleanup(support.rmtree, level1) |
| 2138 | |
| 2139 | os.mkdir(level1) |
| 2140 | os.mkdir(level2) |
| 2141 | os.mkdir(level3) |
| 2142 | |
| 2143 | file1 = os.path.abspath(os.path.join(level1, "file1")) |
| 2144 | create_file(file1) |
| 2145 | |
| 2146 | orig_dir = os.getcwd() |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2147 | try: |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2148 | os.chdir(level2) |
| 2149 | link = os.path.join(level2, "link") |
| 2150 | os.symlink(os.path.relpath(file1), "link") |
| 2151 | self.assertIn("link", os.listdir(os.getcwd())) |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2152 | |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2153 | # Check os.stat calls from the same dir as the link |
| 2154 | self.assertEqual(os.stat(file1), os.stat("link")) |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2155 | |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2156 | # Check os.stat calls from a dir below the link |
| 2157 | os.chdir(level1) |
| 2158 | self.assertEqual(os.stat(file1), |
| 2159 | os.stat(os.path.relpath(link))) |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2160 | |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2161 | # Check os.stat calls from a dir above the link |
| 2162 | os.chdir(level3) |
| 2163 | self.assertEqual(os.stat(file1), |
| 2164 | os.stat(os.path.relpath(link))) |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2165 | finally: |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2166 | os.chdir(orig_dir) |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 2167 | |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 2168 | |
Tim Golden | 0321cf2 | 2014-05-05 19:46:17 +0100 | [diff] [blame] | 2169 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
| 2170 | class Win32JunctionTests(unittest.TestCase): |
| 2171 | junction = 'junctiontest' |
| 2172 | junction_target = os.path.dirname(os.path.abspath(__file__)) |
| 2173 | |
| 2174 | def setUp(self): |
| 2175 | assert os.path.exists(self.junction_target) |
| 2176 | assert not os.path.exists(self.junction) |
| 2177 | |
| 2178 | def tearDown(self): |
| 2179 | if os.path.exists(self.junction): |
| 2180 | # os.rmdir delegates to Windows' RemoveDirectoryW, |
| 2181 | # which removes junction points safely. |
| 2182 | os.rmdir(self.junction) |
| 2183 | |
| 2184 | def test_create_junction(self): |
| 2185 | _winapi.CreateJunction(self.junction_target, self.junction) |
| 2186 | self.assertTrue(os.path.exists(self.junction)) |
| 2187 | self.assertTrue(os.path.isdir(self.junction)) |
| 2188 | |
| 2189 | # Junctions are not recognized as links. |
| 2190 | self.assertFalse(os.path.islink(self.junction)) |
| 2191 | |
| 2192 | def test_unlink_removes_junction(self): |
| 2193 | _winapi.CreateJunction(self.junction_target, self.junction) |
| 2194 | self.assertTrue(os.path.exists(self.junction)) |
| 2195 | |
| 2196 | os.unlink(self.junction) |
| 2197 | self.assertFalse(os.path.exists(self.junction)) |
| 2198 | |
| 2199 | |
Jason R. Coombs | 3a09286 | 2013-05-27 23:21:28 -0400 | [diff] [blame] | 2200 | @support.skip_unless_symlink |
| 2201 | class NonLocalSymlinkTests(unittest.TestCase): |
| 2202 | |
| 2203 | def setUp(self): |
R David Murray | 44b548d | 2016-09-08 13:59:53 -0400 | [diff] [blame] | 2204 | r""" |
Jason R. Coombs | 3a09286 | 2013-05-27 23:21:28 -0400 | [diff] [blame] | 2205 | Create this structure: |
| 2206 | |
| 2207 | base |
| 2208 | \___ some_dir |
| 2209 | """ |
| 2210 | os.makedirs('base/some_dir') |
| 2211 | |
| 2212 | def tearDown(self): |
| 2213 | shutil.rmtree('base') |
| 2214 | |
| 2215 | def test_directory_link_nonlocal(self): |
| 2216 | """ |
| 2217 | The symlink target should resolve relative to the link, not relative |
| 2218 | to the current directory. |
| 2219 | |
| 2220 | Then, link base/some_link -> base/some_dir and ensure that some_link |
| 2221 | is resolved as a directory. |
| 2222 | |
| 2223 | In issue13772, it was discovered that directory detection failed if |
| 2224 | the symlink target was not specified relative to the current |
| 2225 | directory, which was a defect in the implementation. |
| 2226 | """ |
| 2227 | src = os.path.join('base', 'some_link') |
| 2228 | os.symlink('some_dir', src) |
| 2229 | assert os.path.isdir(src) |
| 2230 | |
| 2231 | |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 2232 | class FSEncodingTests(unittest.TestCase): |
| 2233 | def test_nop(self): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2234 | self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff') |
| 2235 | self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141') |
Benjamin Peterson | 31191a9 | 2010-05-09 03:22:58 +0000 | [diff] [blame] | 2236 | |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 2237 | def test_identity(self): |
| 2238 | # assert fsdecode(fsencode(x)) == x |
| 2239 | for fn in ('unicode\u0141', 'latin\xe9', 'ascii'): |
| 2240 | try: |
| 2241 | bytesfn = os.fsencode(fn) |
| 2242 | except UnicodeEncodeError: |
| 2243 | continue |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 2244 | self.assertEqual(os.fsdecode(bytesfn), fn) |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 2245 | |
Victor Stinner | bf9bcab | 2010-05-09 03:15:33 +0000 | [diff] [blame] | 2246 | |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 2247 | |
| 2248 | class DeviceEncodingTests(unittest.TestCase): |
| 2249 | |
| 2250 | def test_bad_fd(self): |
| 2251 | # Return None when an fd doesn't actually exist. |
| 2252 | self.assertIsNone(os.device_encoding(123456)) |
| 2253 | |
Philip Jenvey | e308b7c | 2012-02-29 16:16:15 -0800 | [diff] [blame] | 2254 | @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or |
| 2255 | (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))), |
Philip Jenvey | d7aff2d | 2012-02-29 16:21:25 -0800 | [diff] [blame] | 2256 | 'test requires a tty and either Windows or nl_langinfo(CODESET)') |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 2257 | def test_device_encoding(self): |
| 2258 | encoding = os.device_encoding(0) |
| 2259 | self.assertIsNotNone(encoding) |
| 2260 | self.assertTrue(codecs.lookup(encoding)) |
| 2261 | |
| 2262 | |
Amaury Forgeot d'Arc | 4b6fdf3 | 2010-09-07 21:31:17 +0000 | [diff] [blame] | 2263 | class PidTests(unittest.TestCase): |
| 2264 | @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid") |
| 2265 | def test_getppid(self): |
| 2266 | p = subprocess.Popen([sys.executable, '-c', |
| 2267 | 'import os; print(os.getppid())'], |
| 2268 | stdout=subprocess.PIPE) |
| 2269 | stdout, _ = p.communicate() |
| 2270 | # We are the parent of our subprocess |
| 2271 | self.assertEqual(int(stdout), os.getpid()) |
| 2272 | |
Victor Stinner | d3ffd32 | 2015-09-15 10:11:03 +0200 | [diff] [blame] | 2273 | def test_waitpid(self): |
| 2274 | args = [sys.executable, '-c', 'pass'] |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 2275 | # Add an implicit test for PyUnicode_FSConverter(). |
| 2276 | pid = os.spawnv(os.P_NOWAIT, _PathLike(args[0]), args) |
Victor Stinner | d3ffd32 | 2015-09-15 10:11:03 +0200 | [diff] [blame] | 2277 | status = os.waitpid(pid, 0) |
| 2278 | self.assertEqual(status, (pid, 0)) |
| 2279 | |
Amaury Forgeot d'Arc | 4b6fdf3 | 2010-09-07 21:31:17 +0000 | [diff] [blame] | 2280 | |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2281 | class SpawnTests(unittest.TestCase): |
Berker Peksag | 47e7062 | 2016-09-15 20:23:55 +0300 | [diff] [blame] | 2282 | def create_args(self, *, with_env=False, use_bytes=False): |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2283 | self.exitcode = 17 |
| 2284 | |
| 2285 | filename = support.TESTFN |
| 2286 | self.addCleanup(support.unlink, filename) |
| 2287 | |
| 2288 | if not with_env: |
| 2289 | code = 'import sys; sys.exit(%s)' % self.exitcode |
| 2290 | else: |
| 2291 | self.env = dict(os.environ) |
| 2292 | # create an unique key |
| 2293 | self.key = str(uuid.uuid4()) |
| 2294 | self.env[self.key] = self.key |
| 2295 | # read the variable from os.environ to check that it exists |
| 2296 | code = ('import sys, os; magic = os.environ[%r]; sys.exit(%s)' |
| 2297 | % (self.key, self.exitcode)) |
| 2298 | |
| 2299 | with open(filename, "w") as fp: |
| 2300 | fp.write(code) |
| 2301 | |
Berker Peksag | 8181646 | 2016-09-15 20:19:47 +0300 | [diff] [blame] | 2302 | args = [sys.executable, filename] |
| 2303 | if use_bytes: |
| 2304 | args = [os.fsencode(a) for a in args] |
| 2305 | self.env = {os.fsencode(k): os.fsencode(v) |
| 2306 | for k, v in self.env.items()} |
| 2307 | |
| 2308 | return args |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2309 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2310 | @requires_os_func('spawnl') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2311 | def test_spawnl(self): |
| 2312 | args = self.create_args() |
| 2313 | exitcode = os.spawnl(os.P_WAIT, args[0], *args) |
| 2314 | self.assertEqual(exitcode, self.exitcode) |
| 2315 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2316 | @requires_os_func('spawnle') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2317 | def test_spawnle(self): |
Berker Peksag | 47e7062 | 2016-09-15 20:23:55 +0300 | [diff] [blame] | 2318 | args = self.create_args(with_env=True) |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2319 | exitcode = os.spawnle(os.P_WAIT, args[0], *args, self.env) |
| 2320 | self.assertEqual(exitcode, self.exitcode) |
| 2321 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2322 | @requires_os_func('spawnlp') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2323 | def test_spawnlp(self): |
| 2324 | args = self.create_args() |
| 2325 | exitcode = os.spawnlp(os.P_WAIT, args[0], *args) |
| 2326 | self.assertEqual(exitcode, self.exitcode) |
| 2327 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2328 | @requires_os_func('spawnlpe') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2329 | def test_spawnlpe(self): |
Berker Peksag | 47e7062 | 2016-09-15 20:23:55 +0300 | [diff] [blame] | 2330 | args = self.create_args(with_env=True) |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2331 | exitcode = os.spawnlpe(os.P_WAIT, args[0], *args, self.env) |
| 2332 | self.assertEqual(exitcode, self.exitcode) |
| 2333 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2334 | @requires_os_func('spawnv') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2335 | def test_spawnv(self): |
| 2336 | args = self.create_args() |
| 2337 | exitcode = os.spawnv(os.P_WAIT, args[0], args) |
| 2338 | self.assertEqual(exitcode, self.exitcode) |
| 2339 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2340 | @requires_os_func('spawnve') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2341 | def test_spawnve(self): |
Berker Peksag | 47e7062 | 2016-09-15 20:23:55 +0300 | [diff] [blame] | 2342 | args = self.create_args(with_env=True) |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2343 | exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env) |
| 2344 | self.assertEqual(exitcode, self.exitcode) |
| 2345 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2346 | @requires_os_func('spawnvp') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2347 | def test_spawnvp(self): |
| 2348 | args = self.create_args() |
| 2349 | exitcode = os.spawnvp(os.P_WAIT, args[0], args) |
| 2350 | self.assertEqual(exitcode, self.exitcode) |
| 2351 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2352 | @requires_os_func('spawnvpe') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2353 | def test_spawnvpe(self): |
Berker Peksag | 47e7062 | 2016-09-15 20:23:55 +0300 | [diff] [blame] | 2354 | args = self.create_args(with_env=True) |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2355 | exitcode = os.spawnvpe(os.P_WAIT, args[0], args, self.env) |
| 2356 | self.assertEqual(exitcode, self.exitcode) |
| 2357 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2358 | @requires_os_func('spawnv') |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2359 | def test_nowait(self): |
| 2360 | args = self.create_args() |
| 2361 | pid = os.spawnv(os.P_NOWAIT, args[0], args) |
| 2362 | result = os.waitpid(pid, 0) |
| 2363 | self.assertEqual(result[0], pid) |
| 2364 | status = result[1] |
| 2365 | if hasattr(os, 'WIFEXITED'): |
| 2366 | self.assertTrue(os.WIFEXITED(status)) |
| 2367 | self.assertEqual(os.WEXITSTATUS(status), self.exitcode) |
| 2368 | else: |
| 2369 | self.assertEqual(status, self.exitcode << 8) |
| 2370 | |
Berker Peksag | 4af23d7 | 2016-09-15 20:32:44 +0300 | [diff] [blame] | 2371 | @requires_os_func('spawnve') |
Berker Peksag | 8181646 | 2016-09-15 20:19:47 +0300 | [diff] [blame] | 2372 | def test_spawnve_bytes(self): |
| 2373 | # Test bytes handling in parse_arglist and parse_envlist (#28114) |
| 2374 | args = self.create_args(with_env=True, use_bytes=True) |
| 2375 | exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env) |
| 2376 | self.assertEqual(exitcode, self.exitcode) |
| 2377 | |
Steve Dower | 859fd7b | 2016-11-19 18:53:19 -0800 | [diff] [blame] | 2378 | @requires_os_func('spawnl') |
| 2379 | def test_spawnl_noargs(self): |
| 2380 | args = self.create_args() |
| 2381 | self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0]) |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 2382 | self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0], '') |
Steve Dower | 859fd7b | 2016-11-19 18:53:19 -0800 | [diff] [blame] | 2383 | |
| 2384 | @requires_os_func('spawnle') |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 2385 | def test_spawnle_noargs(self): |
Steve Dower | 859fd7b | 2016-11-19 18:53:19 -0800 | [diff] [blame] | 2386 | args = self.create_args() |
| 2387 | self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], {}) |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 2388 | self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], '', {}) |
Steve Dower | 859fd7b | 2016-11-19 18:53:19 -0800 | [diff] [blame] | 2389 | |
| 2390 | @requires_os_func('spawnv') |
| 2391 | def test_spawnv_noargs(self): |
| 2392 | args = self.create_args() |
| 2393 | self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ()) |
| 2394 | self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], []) |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 2395 | self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ('',)) |
| 2396 | self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ['']) |
Steve Dower | 859fd7b | 2016-11-19 18:53:19 -0800 | [diff] [blame] | 2397 | |
| 2398 | @requires_os_func('spawnve') |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 2399 | def test_spawnve_noargs(self): |
Steve Dower | 859fd7b | 2016-11-19 18:53:19 -0800 | [diff] [blame] | 2400 | args = self.create_args() |
| 2401 | self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], (), {}) |
| 2402 | self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [], {}) |
Steve Dower | bce2626 | 2016-11-19 19:17:26 -0800 | [diff] [blame] | 2403 | self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], ('',), {}) |
| 2404 | self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [''], {}) |
Victor Stinner | 4659ccf | 2016-09-14 10:57:00 +0200 | [diff] [blame] | 2405 | |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 2406 | def _test_invalid_env(self, spawn): |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2407 | args = [sys.executable, '-c', 'pass'] |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 2408 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 2409 | # null character in the environment variable name |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2410 | newenv = os.environ.copy() |
| 2411 | newenv["FRUIT\0VEGETABLE"] = "cabbage" |
| 2412 | try: |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 2413 | exitcode = spawn(os.P_WAIT, args[0], args, newenv) |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2414 | except ValueError: |
| 2415 | pass |
| 2416 | else: |
| 2417 | self.assertEqual(exitcode, 127) |
| 2418 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 2419 | # null character in the environment variable value |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2420 | newenv = os.environ.copy() |
| 2421 | newenv["FRUIT"] = "orange\0VEGETABLE=cabbage" |
| 2422 | try: |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 2423 | exitcode = spawn(os.P_WAIT, args[0], args, newenv) |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2424 | except ValueError: |
| 2425 | pass |
| 2426 | else: |
| 2427 | self.assertEqual(exitcode, 127) |
| 2428 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 2429 | # equal character in the environment variable name |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2430 | newenv = os.environ.copy() |
| 2431 | newenv["FRUIT=ORANGE"] = "lemon" |
| 2432 | try: |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 2433 | exitcode = spawn(os.P_WAIT, args[0], args, newenv) |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2434 | except ValueError: |
| 2435 | pass |
| 2436 | else: |
| 2437 | self.assertEqual(exitcode, 127) |
| 2438 | |
Ville Skyttä | 49b2734 | 2017-08-03 09:00:59 +0300 | [diff] [blame] | 2439 | # equal character in the environment variable value |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2440 | filename = support.TESTFN |
| 2441 | self.addCleanup(support.unlink, filename) |
| 2442 | with open(filename, "w") as fp: |
| 2443 | fp.write('import sys, os\n' |
| 2444 | 'if os.getenv("FRUIT") != "orange=lemon":\n' |
| 2445 | ' raise AssertionError') |
| 2446 | args = [sys.executable, filename] |
| 2447 | newenv = os.environ.copy() |
| 2448 | newenv["FRUIT"] = "orange=lemon" |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 2449 | exitcode = spawn(os.P_WAIT, args[0], args, newenv) |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2450 | self.assertEqual(exitcode, 0) |
| 2451 | |
Serhiy Storchaka | af5392f | 2017-06-25 09:48:54 +0300 | [diff] [blame] | 2452 | @requires_os_func('spawnve') |
| 2453 | def test_spawnve_invalid_env(self): |
| 2454 | self._test_invalid_env(os.spawnve) |
| 2455 | |
| 2456 | @requires_os_func('spawnvpe') |
| 2457 | def test_spawnvpe_invalid_env(self): |
| 2458 | self._test_invalid_env(os.spawnvpe) |
| 2459 | |
Serhiy Storchaka | 7770394 | 2017-06-25 07:33:01 +0300 | [diff] [blame] | 2460 | |
Brian Curtin | 0151b8e | 2010-09-24 13:43:43 +0000 | [diff] [blame] | 2461 | # The introduction of this TestCase caused at least two different errors on |
| 2462 | # *nix buildbots. Temporarily skip this to let the buildbots move along. |
| 2463 | @unittest.skip("Skip due to platform/environment differences on *NIX buildbots") |
Brian Curtin | e8e4b3b | 2010-09-23 20:04:14 +0000 | [diff] [blame] | 2464 | @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin") |
| 2465 | class LoginTests(unittest.TestCase): |
| 2466 | def test_getlogin(self): |
| 2467 | user_name = os.getlogin() |
| 2468 | self.assertNotEqual(len(user_name), 0) |
| 2469 | |
| 2470 | |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 2471 | @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'), |
| 2472 | "needs os.getpriority and os.setpriority") |
| 2473 | class ProgramPriorityTests(unittest.TestCase): |
| 2474 | """Tests for os.getpriority() and os.setpriority().""" |
| 2475 | |
| 2476 | def test_set_get_priority(self): |
Giampaolo Rodolà | cfbcec3 | 2011-02-28 19:27:16 +0000 | [diff] [blame] | 2477 | |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 2478 | base = os.getpriority(os.PRIO_PROCESS, os.getpid()) |
| 2479 | os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1) |
| 2480 | try: |
Giampaolo Rodolà | cfbcec3 | 2011-02-28 19:27:16 +0000 | [diff] [blame] | 2481 | new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid()) |
| 2482 | if base >= 19 and new_prio <= 19: |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2483 | raise unittest.SkipTest("unable to reliably test setpriority " |
| 2484 | "at current nice level of %s" % base) |
Giampaolo Rodolà | cfbcec3 | 2011-02-28 19:27:16 +0000 | [diff] [blame] | 2485 | else: |
| 2486 | self.assertEqual(new_prio, base + 1) |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 2487 | finally: |
| 2488 | try: |
| 2489 | os.setpriority(os.PRIO_PROCESS, os.getpid(), base) |
| 2490 | except OSError as err: |
Antoine Pitrou | 692f038 | 2011-02-26 00:22:25 +0000 | [diff] [blame] | 2491 | if err.errno != errno.EACCES: |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 2492 | raise |
| 2493 | |
| 2494 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2495 | class SendfileTestServer(asyncore.dispatcher, threading.Thread): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2496 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2497 | class Handler(asynchat.async_chat): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2498 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2499 | def __init__(self, conn): |
| 2500 | asynchat.async_chat.__init__(self, conn) |
| 2501 | self.in_buffer = [] |
| 2502 | self.closed = False |
| 2503 | self.push(b"220 ready\r\n") |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2504 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2505 | def handle_read(self): |
| 2506 | data = self.recv(4096) |
| 2507 | self.in_buffer.append(data) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2508 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2509 | def get_data(self): |
| 2510 | return b''.join(self.in_buffer) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2511 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2512 | def handle_close(self): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2513 | self.close() |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2514 | self.closed = True |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2515 | |
| 2516 | def handle_error(self): |
| 2517 | raise |
| 2518 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2519 | def __init__(self, address): |
| 2520 | threading.Thread.__init__(self) |
| 2521 | asyncore.dispatcher.__init__(self) |
| 2522 | self.create_socket(socket.AF_INET, socket.SOCK_STREAM) |
| 2523 | self.bind(address) |
| 2524 | self.listen(5) |
| 2525 | self.host, self.port = self.socket.getsockname()[:2] |
| 2526 | self.handler_instance = None |
| 2527 | self._active = False |
| 2528 | self._active_lock = threading.Lock() |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2529 | |
Antoine Pitrou | a6a4dc8 | 2017-09-07 18:56:24 +0200 | [diff] [blame] | 2530 | # --- public API |
| 2531 | |
| 2532 | @property |
| 2533 | def running(self): |
| 2534 | return self._active |
| 2535 | |
| 2536 | def start(self): |
| 2537 | assert not self.running |
| 2538 | self.__flag = threading.Event() |
| 2539 | threading.Thread.start(self) |
| 2540 | self.__flag.wait() |
| 2541 | |
| 2542 | def stop(self): |
| 2543 | assert self.running |
| 2544 | self._active = False |
| 2545 | self.join() |
| 2546 | |
| 2547 | def wait(self): |
| 2548 | # wait for handler connection to be closed, then stop the server |
| 2549 | while not getattr(self.handler_instance, "closed", False): |
| 2550 | time.sleep(0.001) |
| 2551 | self.stop() |
| 2552 | |
| 2553 | # --- internals |
| 2554 | |
| 2555 | def run(self): |
| 2556 | self._active = True |
| 2557 | self.__flag.set() |
| 2558 | while self._active and asyncore.socket_map: |
| 2559 | self._active_lock.acquire() |
| 2560 | asyncore.loop(timeout=0.001, count=1) |
| 2561 | self._active_lock.release() |
| 2562 | asyncore.close_all() |
| 2563 | |
| 2564 | def handle_accept(self): |
| 2565 | conn, addr = self.accept() |
| 2566 | self.handler_instance = self.Handler(conn) |
| 2567 | |
| 2568 | def handle_connect(self): |
| 2569 | self.close() |
| 2570 | handle_read = handle_connect |
| 2571 | |
| 2572 | def writable(self): |
| 2573 | return 0 |
| 2574 | |
| 2575 | def handle_error(self): |
| 2576 | raise |
| 2577 | |
| 2578 | |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2579 | @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()") |
| 2580 | class TestSendfile(unittest.TestCase): |
| 2581 | |
Victor Stinner | 8c663fd | 2017-11-08 14:44:44 -0800 | [diff] [blame] | 2582 | DATA = b"12345abcde" * 16 * 1024 # 160 KiB |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2583 | SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \ |
Giampaolo Rodolà | 4bc6857 | 2011-02-25 21:46:01 +0000 | [diff] [blame] | 2584 | not sys.platform.startswith("solaris") and \ |
| 2585 | not sys.platform.startswith("sunos") |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 2586 | requires_headers_trailers = unittest.skipUnless(SUPPORT_HEADERS_TRAILERS, |
| 2587 | 'requires headers and trailers support') |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2588 | |
| 2589 | @classmethod |
| 2590 | def setUpClass(cls): |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 2591 | cls.key = support.threading_setup() |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2592 | create_file(support.TESTFN, cls.DATA) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2593 | |
| 2594 | @classmethod |
| 2595 | def tearDownClass(cls): |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 2596 | support.threading_cleanup(*cls.key) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2597 | support.unlink(support.TESTFN) |
| 2598 | |
| 2599 | def setUp(self): |
| 2600 | self.server = SendfileTestServer((support.HOST, 0)) |
| 2601 | self.server.start() |
| 2602 | self.client = socket.socket() |
| 2603 | self.client.connect((self.server.host, self.server.port)) |
| 2604 | self.client.settimeout(1) |
| 2605 | # synchronize by waiting for "220 ready" response |
| 2606 | self.client.recv(1024) |
| 2607 | self.sockno = self.client.fileno() |
| 2608 | self.file = open(support.TESTFN, 'rb') |
| 2609 | self.fileno = self.file.fileno() |
| 2610 | |
| 2611 | def tearDown(self): |
| 2612 | self.file.close() |
| 2613 | self.client.close() |
| 2614 | if self.server.running: |
| 2615 | self.server.stop() |
Victor Stinner | d1cc037 | 2017-07-12 16:05:43 +0200 | [diff] [blame] | 2616 | self.server = None |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2617 | |
| 2618 | def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]): |
| 2619 | """A higher level wrapper representing how an application is |
| 2620 | supposed to use sendfile(). |
| 2621 | """ |
| 2622 | while 1: |
| 2623 | try: |
| 2624 | if self.SUPPORT_HEADERS_TRAILERS: |
| 2625 | return os.sendfile(sock, file, offset, nbytes, headers, |
| 2626 | trailers) |
| 2627 | else: |
| 2628 | return os.sendfile(sock, file, offset, nbytes) |
| 2629 | except OSError as err: |
| 2630 | if err.errno == errno.ECONNRESET: |
| 2631 | # disconnected |
| 2632 | raise |
| 2633 | elif err.errno in (errno.EAGAIN, errno.EBUSY): |
| 2634 | # we have to retry send data |
| 2635 | continue |
| 2636 | else: |
| 2637 | raise |
| 2638 | |
| 2639 | def test_send_whole_file(self): |
| 2640 | # normal send |
| 2641 | total_sent = 0 |
| 2642 | offset = 0 |
| 2643 | nbytes = 4096 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 2644 | while total_sent < len(self.DATA): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2645 | sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes) |
| 2646 | if sent == 0: |
| 2647 | break |
| 2648 | offset += sent |
| 2649 | total_sent += sent |
| 2650 | self.assertTrue(sent <= nbytes) |
| 2651 | self.assertEqual(offset, total_sent) |
| 2652 | |
| 2653 | self.assertEqual(total_sent, len(self.DATA)) |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 2654 | self.client.shutdown(socket.SHUT_RDWR) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2655 | self.client.close() |
| 2656 | self.server.wait() |
| 2657 | data = self.server.handler_instance.get_data() |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 2658 | self.assertEqual(len(data), len(self.DATA)) |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 2659 | self.assertEqual(data, self.DATA) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2660 | |
| 2661 | def test_send_at_certain_offset(self): |
| 2662 | # start sending a file at a certain offset |
| 2663 | total_sent = 0 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 2664 | offset = len(self.DATA) // 2 |
| 2665 | must_send = len(self.DATA) - offset |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2666 | nbytes = 4096 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 2667 | while total_sent < must_send: |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2668 | sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes) |
| 2669 | if sent == 0: |
| 2670 | break |
| 2671 | offset += sent |
| 2672 | total_sent += sent |
| 2673 | self.assertTrue(sent <= nbytes) |
| 2674 | |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 2675 | self.client.shutdown(socket.SHUT_RDWR) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2676 | self.client.close() |
| 2677 | self.server.wait() |
| 2678 | data = self.server.handler_instance.get_data() |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 2679 | expected = self.DATA[len(self.DATA) // 2:] |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2680 | self.assertEqual(total_sent, len(expected)) |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 2681 | self.assertEqual(len(data), len(expected)) |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 2682 | self.assertEqual(data, expected) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2683 | |
| 2684 | def test_offset_overflow(self): |
| 2685 | # specify an offset > file size |
| 2686 | offset = len(self.DATA) + 4096 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 2687 | try: |
| 2688 | sent = os.sendfile(self.sockno, self.fileno, offset, 4096) |
| 2689 | except OSError as e: |
| 2690 | # Solaris can raise EINVAL if offset >= file length, ignore. |
| 2691 | if e.errno != errno.EINVAL: |
| 2692 | raise |
| 2693 | else: |
| 2694 | self.assertEqual(sent, 0) |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 2695 | self.client.shutdown(socket.SHUT_RDWR) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2696 | self.client.close() |
| 2697 | self.server.wait() |
| 2698 | data = self.server.handler_instance.get_data() |
| 2699 | self.assertEqual(data, b'') |
| 2700 | |
| 2701 | def test_invalid_offset(self): |
| 2702 | with self.assertRaises(OSError) as cm: |
| 2703 | os.sendfile(self.sockno, self.fileno, -1, 4096) |
| 2704 | self.assertEqual(cm.exception.errno, errno.EINVAL) |
| 2705 | |
Martin Panter | bf19d16 | 2015-09-09 01:01:13 +0000 | [diff] [blame] | 2706 | def test_keywords(self): |
| 2707 | # Keyword arguments should be supported |
| 2708 | os.sendfile(out=self.sockno, offset=0, count=4096, |
| 2709 | **{'in': self.fileno}) |
| 2710 | if self.SUPPORT_HEADERS_TRAILERS: |
| 2711 | os.sendfile(self.sockno, self.fileno, offset=0, count=4096, |
Martin Panter | 9499413 | 2015-09-09 05:29:24 +0000 | [diff] [blame] | 2712 | headers=(), trailers=(), flags=0) |
Martin Panter | bf19d16 | 2015-09-09 01:01:13 +0000 | [diff] [blame] | 2713 | |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2714 | # --- headers / trailers tests |
| 2715 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 2716 | @requires_headers_trailers |
| 2717 | def test_headers(self): |
| 2718 | total_sent = 0 |
| 2719 | sent = os.sendfile(self.sockno, self.fileno, 0, 4096, |
| 2720 | headers=[b"x" * 512]) |
| 2721 | total_sent += sent |
| 2722 | offset = 4096 |
| 2723 | nbytes = 4096 |
| 2724 | while 1: |
| 2725 | sent = self.sendfile_wrapper(self.sockno, self.fileno, |
| 2726 | offset, nbytes) |
| 2727 | if sent == 0: |
| 2728 | break |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2729 | total_sent += sent |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 2730 | offset += sent |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2731 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 2732 | expected_data = b"x" * 512 + self.DATA |
| 2733 | self.assertEqual(total_sent, len(expected_data)) |
| 2734 | self.client.close() |
| 2735 | self.server.wait() |
| 2736 | data = self.server.handler_instance.get_data() |
| 2737 | self.assertEqual(hash(data), hash(expected_data)) |
| 2738 | |
| 2739 | @requires_headers_trailers |
| 2740 | def test_trailers(self): |
| 2741 | TESTFN2 = support.TESTFN + "2" |
| 2742 | file_data = b"abcdef" |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2743 | |
| 2744 | self.addCleanup(support.unlink, TESTFN2) |
| 2745 | create_file(TESTFN2, file_data) |
| 2746 | |
| 2747 | with open(TESTFN2, 'rb') as f: |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 2748 | os.sendfile(self.sockno, f.fileno(), 0, len(file_data), |
| 2749 | trailers=[b"1234"]) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2750 | self.client.close() |
| 2751 | self.server.wait() |
| 2752 | data = self.server.handler_instance.get_data() |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 2753 | self.assertEqual(data, b"abcdef1234") |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2754 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 2755 | @requires_headers_trailers |
| 2756 | @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'), |
| 2757 | 'test needs os.SF_NODISKIO') |
| 2758 | def test_flags(self): |
| 2759 | try: |
| 2760 | os.sendfile(self.sockno, self.fileno, 0, 4096, |
| 2761 | flags=os.SF_NODISKIO) |
| 2762 | except OSError as err: |
| 2763 | if err.errno not in (errno.EBUSY, errno.EAGAIN): |
| 2764 | raise |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2765 | |
| 2766 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2767 | def supports_extended_attributes(): |
| 2768 | if not hasattr(os, "setxattr"): |
| 2769 | return False |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2770 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2771 | try: |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2772 | with open(support.TESTFN, "xb", 0) as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2773 | try: |
| 2774 | os.setxattr(fp.fileno(), b"user.test", b"") |
| 2775 | except OSError: |
| 2776 | return False |
| 2777 | finally: |
| 2778 | support.unlink(support.TESTFN) |
Victor Stinner | f95a19b | 2016-03-24 16:50:41 +0100 | [diff] [blame] | 2779 | |
| 2780 | return True |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2781 | |
| 2782 | |
| 2783 | @unittest.skipUnless(supports_extended_attributes(), |
| 2784 | "no non-broken extended attribute support") |
Victor Stinner | f95a19b | 2016-03-24 16:50:41 +0100 | [diff] [blame] | 2785 | # Kernels < 2.6.39 don't respect setxattr flags. |
| 2786 | @support.requires_linux_version(2, 6, 39) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2787 | class ExtendedAttributeTests(unittest.TestCase): |
| 2788 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2789 | def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs): |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2790 | fn = support.TESTFN |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2791 | self.addCleanup(support.unlink, fn) |
| 2792 | create_file(fn) |
| 2793 | |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2794 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2795 | getxattr(fn, s("user.test"), **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2796 | self.assertEqual(cm.exception.errno, errno.ENODATA) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2797 | |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 2798 | init_xattr = listxattr(fn) |
| 2799 | self.assertIsInstance(init_xattr, list) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2800 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2801 | setxattr(fn, s("user.test"), b"", **kwargs) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 2802 | xattr = set(init_xattr) |
| 2803 | xattr.add("user.test") |
| 2804 | self.assertEqual(set(listxattr(fn)), xattr) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2805 | self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"") |
| 2806 | setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs) |
| 2807 | self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello") |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2808 | |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2809 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2810 | setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2811 | self.assertEqual(cm.exception.errno, errno.EEXIST) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2812 | |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2813 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2814 | setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2815 | self.assertEqual(cm.exception.errno, errno.ENODATA) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2816 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2817 | setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 2818 | xattr.add("user.test2") |
| 2819 | self.assertEqual(set(listxattr(fn)), xattr) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2820 | removexattr(fn, s("user.test"), **kwargs) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2821 | |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2822 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2823 | getxattr(fn, s("user.test"), **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2824 | self.assertEqual(cm.exception.errno, errno.ENODATA) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2825 | |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 2826 | xattr.remove("user.test") |
| 2827 | self.assertEqual(set(listxattr(fn)), xattr) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2828 | self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo") |
| 2829 | setxattr(fn, s("user.test"), b"a"*1024, **kwargs) |
| 2830 | self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024) |
| 2831 | removexattr(fn, s("user.test"), **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2832 | many = sorted("user.test{}".format(i) for i in range(100)) |
| 2833 | for thing in many: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2834 | setxattr(fn, thing, b"x", **kwargs) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 2835 | self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many)) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2836 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2837 | def _check_xattrs(self, *args, **kwargs): |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2838 | self._check_xattrs_str(str, *args, **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2839 | support.unlink(support.TESTFN) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2840 | |
| 2841 | self._check_xattrs_str(os.fsencode, *args, **kwargs) |
| 2842 | support.unlink(support.TESTFN) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2843 | |
| 2844 | def test_simple(self): |
| 2845 | self._check_xattrs(os.getxattr, os.setxattr, os.removexattr, |
| 2846 | os.listxattr) |
| 2847 | |
| 2848 | def test_lpath(self): |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2849 | self._check_xattrs(os.getxattr, os.setxattr, os.removexattr, |
| 2850 | os.listxattr, follow_symlinks=False) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2851 | |
| 2852 | def test_fds(self): |
| 2853 | def getxattr(path, *args): |
| 2854 | with open(path, "rb") as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2855 | return os.getxattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2856 | def setxattr(path, *args): |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2857 | with open(path, "wb", 0) as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2858 | os.setxattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2859 | def removexattr(path, *args): |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 2860 | with open(path, "wb", 0) as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2861 | os.removexattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2862 | def listxattr(path, *args): |
| 2863 | with open(path, "rb") as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 2864 | return os.listxattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2865 | self._check_xattrs(getxattr, setxattr, removexattr, listxattr) |
| 2866 | |
| 2867 | |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2868 | @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size") |
| 2869 | class TermsizeTests(unittest.TestCase): |
| 2870 | def test_does_not_crash(self): |
| 2871 | """Check if get_terminal_size() returns a meaningful value. |
| 2872 | |
| 2873 | There's no easy portable way to actually check the size of the |
| 2874 | terminal, so let's check if it returns something sensible instead. |
| 2875 | """ |
| 2876 | try: |
| 2877 | size = os.get_terminal_size() |
| 2878 | except OSError as e: |
Antoine Pitrou | 81a1fa5 | 2012-02-09 00:11:00 +0100 | [diff] [blame] | 2879 | if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2880 | # Under win32 a generic OSError can be thrown if the |
| 2881 | # handle cannot be retrieved |
| 2882 | self.skipTest("failed to query terminal size") |
| 2883 | raise |
| 2884 | |
Antoine Pitrou | cfade36 | 2012-02-08 23:48:59 +0100 | [diff] [blame] | 2885 | self.assertGreaterEqual(size.columns, 0) |
| 2886 | self.assertGreaterEqual(size.lines, 0) |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2887 | |
| 2888 | def test_stty_match(self): |
| 2889 | """Check if stty returns the same results |
| 2890 | |
| 2891 | stty actually tests stdin, so get_terminal_size is invoked on |
| 2892 | stdin explicitly. If stty succeeded, then get_terminal_size() |
| 2893 | should work too. |
| 2894 | """ |
| 2895 | try: |
| 2896 | size = subprocess.check_output(['stty', 'size']).decode().split() |
xdegaye | 6a55d09 | 2017-11-12 17:57:04 +0100 | [diff] [blame] | 2897 | except (FileNotFoundError, subprocess.CalledProcessError, |
| 2898 | PermissionError): |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2899 | self.skipTest("stty invocation failed") |
| 2900 | expected = (int(size[1]), int(size[0])) # reversed order |
| 2901 | |
Antoine Pitrou | 81a1fa5 | 2012-02-09 00:11:00 +0100 | [diff] [blame] | 2902 | try: |
| 2903 | actual = os.get_terminal_size(sys.__stdin__.fileno()) |
| 2904 | except OSError as e: |
| 2905 | if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): |
| 2906 | # Under win32 a generic OSError can be thrown if the |
| 2907 | # handle cannot be retrieved |
| 2908 | self.skipTest("failed to query terminal size") |
| 2909 | raise |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2910 | self.assertEqual(expected, actual) |
| 2911 | |
| 2912 | |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2913 | class OSErrorTests(unittest.TestCase): |
| 2914 | def setUp(self): |
| 2915 | class Str(str): |
| 2916 | pass |
| 2917 | |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2918 | self.bytes_filenames = [] |
| 2919 | self.unicode_filenames = [] |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2920 | if support.TESTFN_UNENCODABLE is not None: |
| 2921 | decoded = support.TESTFN_UNENCODABLE |
| 2922 | else: |
| 2923 | decoded = support.TESTFN |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2924 | self.unicode_filenames.append(decoded) |
| 2925 | self.unicode_filenames.append(Str(decoded)) |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2926 | if support.TESTFN_UNDECODABLE is not None: |
| 2927 | encoded = support.TESTFN_UNDECODABLE |
| 2928 | else: |
| 2929 | encoded = os.fsencode(support.TESTFN) |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2930 | self.bytes_filenames.append(encoded) |
Serhiy Storchaka | d73c318 | 2016-08-06 23:22:08 +0300 | [diff] [blame] | 2931 | self.bytes_filenames.append(bytearray(encoded)) |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2932 | self.bytes_filenames.append(memoryview(encoded)) |
| 2933 | |
| 2934 | self.filenames = self.bytes_filenames + self.unicode_filenames |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2935 | |
| 2936 | def test_oserror_filename(self): |
| 2937 | funcs = [ |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2938 | (self.filenames, os.chdir,), |
| 2939 | (self.filenames, os.chmod, 0o777), |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2940 | (self.filenames, os.lstat,), |
| 2941 | (self.filenames, os.open, os.O_RDONLY), |
| 2942 | (self.filenames, os.rmdir,), |
| 2943 | (self.filenames, os.stat,), |
| 2944 | (self.filenames, os.unlink,), |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2945 | ] |
| 2946 | if sys.platform == "win32": |
| 2947 | funcs.extend(( |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2948 | (self.bytes_filenames, os.rename, b"dst"), |
| 2949 | (self.bytes_filenames, os.replace, b"dst"), |
| 2950 | (self.unicode_filenames, os.rename, "dst"), |
| 2951 | (self.unicode_filenames, os.replace, "dst"), |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 2952 | (self.unicode_filenames, os.listdir, ), |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2953 | )) |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2954 | else: |
| 2955 | funcs.extend(( |
Victor Stinner | 64e039a | 2012-11-07 00:10:14 +0100 | [diff] [blame] | 2956 | (self.filenames, os.listdir,), |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2957 | (self.filenames, os.rename, "dst"), |
| 2958 | (self.filenames, os.replace, "dst"), |
| 2959 | )) |
| 2960 | if hasattr(os, "chown"): |
| 2961 | funcs.append((self.filenames, os.chown, 0, 0)) |
| 2962 | if hasattr(os, "lchown"): |
| 2963 | funcs.append((self.filenames, os.lchown, 0, 0)) |
| 2964 | if hasattr(os, "truncate"): |
| 2965 | funcs.append((self.filenames, os.truncate, 0)) |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2966 | if hasattr(os, "chflags"): |
Victor Stinner | ee36c24 | 2012-11-13 09:31:51 +0100 | [diff] [blame] | 2967 | funcs.append((self.filenames, os.chflags, 0)) |
| 2968 | if hasattr(os, "lchflags"): |
| 2969 | funcs.append((self.filenames, os.lchflags, 0)) |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2970 | if hasattr(os, "chroot"): |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2971 | funcs.append((self.filenames, os.chroot,)) |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2972 | if hasattr(os, "link"): |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2973 | if sys.platform == "win32": |
| 2974 | funcs.append((self.bytes_filenames, os.link, b"dst")) |
| 2975 | funcs.append((self.unicode_filenames, os.link, "dst")) |
| 2976 | else: |
| 2977 | funcs.append((self.filenames, os.link, "dst")) |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2978 | if hasattr(os, "listxattr"): |
| 2979 | funcs.extend(( |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2980 | (self.filenames, os.listxattr,), |
| 2981 | (self.filenames, os.getxattr, "user.test"), |
| 2982 | (self.filenames, os.setxattr, "user.test", b'user'), |
| 2983 | (self.filenames, os.removexattr, "user.test"), |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2984 | )) |
| 2985 | if hasattr(os, "lchmod"): |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2986 | funcs.append((self.filenames, os.lchmod, 0o777)) |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2987 | if hasattr(os, "readlink"): |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2988 | if sys.platform == "win32": |
| 2989 | funcs.append((self.unicode_filenames, os.readlink,)) |
| 2990 | else: |
| 2991 | funcs.append((self.filenames, os.readlink,)) |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2992 | |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 2993 | |
Victor Stinner | afe1706 | 2012-10-31 22:47:43 +0100 | [diff] [blame] | 2994 | for filenames, func, *func_args in funcs: |
| 2995 | for name in filenames: |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 2996 | try: |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 2997 | if isinstance(name, (str, bytes)): |
Victor Stinner | 923590e | 2016-03-24 09:11:48 +0100 | [diff] [blame] | 2998 | func(name, *func_args) |
Serhiy Storchaka | d73c318 | 2016-08-06 23:22:08 +0300 | [diff] [blame] | 2999 | else: |
| 3000 | with self.assertWarnsRegex(DeprecationWarning, 'should be'): |
| 3001 | func(name, *func_args) |
Victor Stinner | bd54f0e | 2012-10-31 01:12:55 +0100 | [diff] [blame] | 3002 | except OSError as err: |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 3003 | self.assertIs(err.filename, name, str(func)) |
Steve Dower | 78057b4 | 2016-11-06 19:35:08 -0800 | [diff] [blame] | 3004 | except UnicodeDecodeError: |
| 3005 | pass |
Victor Stinner | 292c835 | 2012-10-30 02:17:38 +0100 | [diff] [blame] | 3006 | else: |
| 3007 | self.fail("No exception thrown by {}".format(func)) |
| 3008 | |
Charles-Francois Natali | 44feda3 | 2013-05-20 14:40:46 +0200 | [diff] [blame] | 3009 | class CPUCountTests(unittest.TestCase): |
| 3010 | def test_cpu_count(self): |
| 3011 | cpus = os.cpu_count() |
| 3012 | if cpus is not None: |
| 3013 | self.assertIsInstance(cpus, int) |
| 3014 | self.assertGreater(cpus, 0) |
| 3015 | else: |
| 3016 | self.skipTest("Could not determine the number of CPUs") |
| 3017 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 3018 | |
| 3019 | class FDInheritanceTests(unittest.TestCase): |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 3020 | def test_get_set_inheritable(self): |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 3021 | fd = os.open(__file__, os.O_RDONLY) |
| 3022 | self.addCleanup(os.close, fd) |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 3023 | self.assertEqual(os.get_inheritable(fd), False) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 3024 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 3025 | os.set_inheritable(fd, True) |
| 3026 | self.assertEqual(os.get_inheritable(fd), True) |
| 3027 | |
Victor Stinner | 4f7a36f | 2013-09-08 14:14:38 +0200 | [diff] [blame] | 3028 | @unittest.skipIf(fcntl is None, "need fcntl") |
| 3029 | def test_get_inheritable_cloexec(self): |
| 3030 | fd = os.open(__file__, os.O_RDONLY) |
| 3031 | self.addCleanup(os.close, fd) |
| 3032 | self.assertEqual(os.get_inheritable(fd), False) |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 3033 | |
Victor Stinner | 4f7a36f | 2013-09-08 14:14:38 +0200 | [diff] [blame] | 3034 | # clear FD_CLOEXEC flag |
| 3035 | flags = fcntl.fcntl(fd, fcntl.F_GETFD) |
| 3036 | flags &= ~fcntl.FD_CLOEXEC |
| 3037 | fcntl.fcntl(fd, fcntl.F_SETFD, flags) |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 3038 | |
Victor Stinner | 4f7a36f | 2013-09-08 14:14:38 +0200 | [diff] [blame] | 3039 | self.assertEqual(os.get_inheritable(fd), True) |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 3040 | |
Victor Stinner | 4f7a36f | 2013-09-08 14:14:38 +0200 | [diff] [blame] | 3041 | @unittest.skipIf(fcntl is None, "need fcntl") |
| 3042 | def test_set_inheritable_cloexec(self): |
| 3043 | fd = os.open(__file__, os.O_RDONLY) |
| 3044 | self.addCleanup(os.close, fd) |
| 3045 | self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC, |
| 3046 | fcntl.FD_CLOEXEC) |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 3047 | |
Victor Stinner | 4f7a36f | 2013-09-08 14:14:38 +0200 | [diff] [blame] | 3048 | os.set_inheritable(fd, True) |
| 3049 | self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC, |
| 3050 | 0) |
Victor Stinner | 7ba6b0f | 2013-09-08 11:47:54 +0200 | [diff] [blame] | 3051 | |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 3052 | def test_open(self): |
| 3053 | fd = os.open(__file__, os.O_RDONLY) |
| 3054 | self.addCleanup(os.close, fd) |
| 3055 | self.assertEqual(os.get_inheritable(fd), False) |
| 3056 | |
| 3057 | @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()") |
| 3058 | def test_pipe(self): |
| 3059 | rfd, wfd = os.pipe() |
| 3060 | self.addCleanup(os.close, rfd) |
| 3061 | self.addCleanup(os.close, wfd) |
| 3062 | self.assertEqual(os.get_inheritable(rfd), False) |
| 3063 | self.assertEqual(os.get_inheritable(wfd), False) |
| 3064 | |
| 3065 | def test_dup(self): |
| 3066 | fd1 = os.open(__file__, os.O_RDONLY) |
| 3067 | self.addCleanup(os.close, fd1) |
| 3068 | |
| 3069 | fd2 = os.dup(fd1) |
| 3070 | self.addCleanup(os.close, fd2) |
| 3071 | self.assertEqual(os.get_inheritable(fd2), False) |
| 3072 | |
| 3073 | @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()") |
| 3074 | def test_dup2(self): |
| 3075 | fd = os.open(__file__, os.O_RDONLY) |
| 3076 | self.addCleanup(os.close, fd) |
| 3077 | |
| 3078 | # inheritable by default |
| 3079 | fd2 = os.open(__file__, os.O_RDONLY) |
Benjamin Peterson | bbdb17d | 2017-12-29 13:13:06 -0800 | [diff] [blame] | 3080 | self.addCleanup(os.close, fd2) |
| 3081 | self.assertEqual(os.dup2(fd, fd2), fd2) |
| 3082 | self.assertTrue(os.get_inheritable(fd2)) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 3083 | |
| 3084 | # force non-inheritable |
| 3085 | fd3 = os.open(__file__, os.O_RDONLY) |
Benjamin Peterson | bbdb17d | 2017-12-29 13:13:06 -0800 | [diff] [blame] | 3086 | self.addCleanup(os.close, fd3) |
| 3087 | self.assertEqual(os.dup2(fd, fd3, inheritable=False), fd3) |
| 3088 | self.assertFalse(os.get_inheritable(fd3)) |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 3089 | |
| 3090 | @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()") |
| 3091 | def test_openpty(self): |
| 3092 | master_fd, slave_fd = os.openpty() |
| 3093 | self.addCleanup(os.close, master_fd) |
| 3094 | self.addCleanup(os.close, slave_fd) |
| 3095 | self.assertEqual(os.get_inheritable(master_fd), False) |
| 3096 | self.assertEqual(os.get_inheritable(slave_fd), False) |
| 3097 | |
| 3098 | |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3099 | class PathTConverterTests(unittest.TestCase): |
| 3100 | # tuples of (function name, allows fd arguments, additional arguments to |
| 3101 | # function, cleanup function) |
| 3102 | functions = [ |
| 3103 | ('stat', True, (), None), |
| 3104 | ('lstat', False, (), None), |
Benjamin Peterson | a9ab165 | 2016-09-05 15:40:59 -0700 | [diff] [blame] | 3105 | ('access', False, (os.F_OK,), None), |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3106 | ('chflags', False, (0,), None), |
| 3107 | ('lchflags', False, (0,), None), |
| 3108 | ('open', False, (0,), getattr(os, 'close', None)), |
| 3109 | ] |
| 3110 | |
| 3111 | def test_path_t_converter(self): |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3112 | str_filename = support.TESTFN |
Brett Cannon | 3ce2fd4 | 2016-08-27 09:42:40 -0700 | [diff] [blame] | 3113 | if os.name == 'nt': |
| 3114 | bytes_fspath = bytes_filename = None |
| 3115 | else: |
| 3116 | bytes_filename = support.TESTFN.encode('ascii') |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 3117 | bytes_fspath = _PathLike(bytes_filename) |
| 3118 | fd = os.open(_PathLike(str_filename), os.O_WRONLY|os.O_CREAT) |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3119 | self.addCleanup(support.unlink, support.TESTFN) |
Berker Peksag | d0f5bab | 2016-08-27 21:26:35 +0300 | [diff] [blame] | 3120 | self.addCleanup(os.close, fd) |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3121 | |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 3122 | int_fspath = _PathLike(fd) |
| 3123 | str_fspath = _PathLike(str_filename) |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3124 | |
| 3125 | for name, allow_fd, extra_args, cleanup_fn in self.functions: |
| 3126 | with self.subTest(name=name): |
| 3127 | try: |
| 3128 | fn = getattr(os, name) |
| 3129 | except AttributeError: |
| 3130 | continue |
| 3131 | |
Brett Cannon | 8f96a30 | 2016-08-26 19:30:11 -0700 | [diff] [blame] | 3132 | for path in (str_filename, bytes_filename, str_fspath, |
| 3133 | bytes_fspath): |
Brett Cannon | 3ce2fd4 | 2016-08-27 09:42:40 -0700 | [diff] [blame] | 3134 | if path is None: |
| 3135 | continue |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3136 | with self.subTest(name=name, path=path): |
| 3137 | result = fn(path, *extra_args) |
| 3138 | if cleanup_fn is not None: |
| 3139 | cleanup_fn(result) |
| 3140 | |
| 3141 | with self.assertRaisesRegex( |
| 3142 | TypeError, 'should be string, bytes'): |
| 3143 | fn(int_fspath, *extra_args) |
Brett Cannon | 3f9183b | 2016-08-26 14:44:48 -0700 | [diff] [blame] | 3144 | |
| 3145 | if allow_fd: |
| 3146 | result = fn(fd, *extra_args) # should not fail |
| 3147 | if cleanup_fn is not None: |
| 3148 | cleanup_fn(result) |
| 3149 | else: |
| 3150 | with self.assertRaisesRegex( |
| 3151 | TypeError, |
| 3152 | 'os.PathLike'): |
| 3153 | fn(fd, *extra_args) |
| 3154 | |
| 3155 | |
Victor Stinner | 1db9e7b | 2014-07-29 22:32:47 +0200 | [diff] [blame] | 3156 | @unittest.skipUnless(hasattr(os, 'get_blocking'), |
| 3157 | 'needs os.get_blocking() and os.set_blocking()') |
| 3158 | class BlockingTests(unittest.TestCase): |
| 3159 | def test_blocking(self): |
| 3160 | fd = os.open(__file__, os.O_RDONLY) |
| 3161 | self.addCleanup(os.close, fd) |
| 3162 | self.assertEqual(os.get_blocking(fd), True) |
| 3163 | |
| 3164 | os.set_blocking(fd, False) |
| 3165 | self.assertEqual(os.get_blocking(fd), False) |
| 3166 | |
| 3167 | os.set_blocking(fd, True) |
| 3168 | self.assertEqual(os.get_blocking(fd), True) |
| 3169 | |
| 3170 | |
Yury Selivanov | 97e2e06 | 2014-09-26 12:33:06 -0400 | [diff] [blame] | 3171 | |
| 3172 | class ExportsTests(unittest.TestCase): |
| 3173 | def test_os_all(self): |
| 3174 | self.assertIn('open', os.__all__) |
| 3175 | self.assertIn('walk', os.__all__) |
| 3176 | |
| 3177 | |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3178 | class TestScandir(unittest.TestCase): |
Serhiy Storchaka | ffe96ae | 2016-02-11 13:21:30 +0200 | [diff] [blame] | 3179 | check_no_resource_warning = support.check_no_resource_warning |
| 3180 | |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3181 | def setUp(self): |
| 3182 | self.path = os.path.realpath(support.TESTFN) |
Brett Cannon | 96881cd | 2016-06-10 14:37:21 -0700 | [diff] [blame] | 3183 | self.bytes_path = os.fsencode(self.path) |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3184 | self.addCleanup(support.rmtree, self.path) |
| 3185 | os.mkdir(self.path) |
| 3186 | |
| 3187 | def create_file(self, name="file.txt"): |
Brett Cannon | 96881cd | 2016-06-10 14:37:21 -0700 | [diff] [blame] | 3188 | path = self.bytes_path if isinstance(name, bytes) else self.path |
| 3189 | filename = os.path.join(path, name) |
Victor Stinner | ae39d23 | 2016-03-24 17:12:55 +0100 | [diff] [blame] | 3190 | create_file(filename, b'python') |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3191 | return filename |
| 3192 | |
| 3193 | def get_entries(self, names): |
| 3194 | entries = dict((entry.name, entry) |
| 3195 | for entry in os.scandir(self.path)) |
| 3196 | self.assertEqual(sorted(entries.keys()), names) |
| 3197 | return entries |
| 3198 | |
| 3199 | def assert_stat_equal(self, stat1, stat2, skip_fields): |
| 3200 | if skip_fields: |
| 3201 | for attr in dir(stat1): |
| 3202 | if not attr.startswith("st_"): |
| 3203 | continue |
| 3204 | if attr in ("st_dev", "st_ino", "st_nlink"): |
| 3205 | continue |
| 3206 | self.assertEqual(getattr(stat1, attr), |
| 3207 | getattr(stat2, attr), |
| 3208 | (stat1, stat2, attr)) |
| 3209 | else: |
| 3210 | self.assertEqual(stat1, stat2) |
| 3211 | |
| 3212 | def check_entry(self, entry, name, is_dir, is_file, is_symlink): |
Brett Cannon | a32c4d0 | 2016-06-24 14:14:44 -0700 | [diff] [blame] | 3213 | self.assertIsInstance(entry, os.DirEntry) |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3214 | self.assertEqual(entry.name, name) |
| 3215 | self.assertEqual(entry.path, os.path.join(self.path, name)) |
| 3216 | self.assertEqual(entry.inode(), |
| 3217 | os.stat(entry.path, follow_symlinks=False).st_ino) |
| 3218 | |
| 3219 | entry_stat = os.stat(entry.path) |
| 3220 | self.assertEqual(entry.is_dir(), |
| 3221 | stat.S_ISDIR(entry_stat.st_mode)) |
| 3222 | self.assertEqual(entry.is_file(), |
| 3223 | stat.S_ISREG(entry_stat.st_mode)) |
| 3224 | self.assertEqual(entry.is_symlink(), |
| 3225 | os.path.islink(entry.path)) |
| 3226 | |
| 3227 | entry_lstat = os.stat(entry.path, follow_symlinks=False) |
| 3228 | self.assertEqual(entry.is_dir(follow_symlinks=False), |
| 3229 | stat.S_ISDIR(entry_lstat.st_mode)) |
| 3230 | self.assertEqual(entry.is_file(follow_symlinks=False), |
| 3231 | stat.S_ISREG(entry_lstat.st_mode)) |
| 3232 | |
| 3233 | self.assert_stat_equal(entry.stat(), |
| 3234 | entry_stat, |
| 3235 | os.name == 'nt' and not is_symlink) |
| 3236 | self.assert_stat_equal(entry.stat(follow_symlinks=False), |
| 3237 | entry_lstat, |
| 3238 | os.name == 'nt') |
| 3239 | |
| 3240 | def test_attributes(self): |
| 3241 | link = hasattr(os, 'link') |
| 3242 | symlink = support.can_symlink() |
| 3243 | |
| 3244 | dirname = os.path.join(self.path, "dir") |
| 3245 | os.mkdir(dirname) |
| 3246 | filename = self.create_file("file.txt") |
| 3247 | if link: |
xdegaye | 6a55d09 | 2017-11-12 17:57:04 +0100 | [diff] [blame] | 3248 | try: |
| 3249 | os.link(filename, os.path.join(self.path, "link_file.txt")) |
| 3250 | except PermissionError as e: |
| 3251 | self.skipTest('os.link(): %s' % e) |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3252 | if symlink: |
| 3253 | os.symlink(dirname, os.path.join(self.path, "symlink_dir"), |
| 3254 | target_is_directory=True) |
| 3255 | os.symlink(filename, os.path.join(self.path, "symlink_file.txt")) |
| 3256 | |
| 3257 | names = ['dir', 'file.txt'] |
| 3258 | if link: |
| 3259 | names.append('link_file.txt') |
| 3260 | if symlink: |
| 3261 | names.extend(('symlink_dir', 'symlink_file.txt')) |
| 3262 | entries = self.get_entries(names) |
| 3263 | |
| 3264 | entry = entries['dir'] |
| 3265 | self.check_entry(entry, 'dir', True, False, False) |
| 3266 | |
| 3267 | entry = entries['file.txt'] |
| 3268 | self.check_entry(entry, 'file.txt', False, True, False) |
| 3269 | |
| 3270 | if link: |
| 3271 | entry = entries['link_file.txt'] |
| 3272 | self.check_entry(entry, 'link_file.txt', False, True, False) |
| 3273 | |
| 3274 | if symlink: |
| 3275 | entry = entries['symlink_dir'] |
| 3276 | self.check_entry(entry, 'symlink_dir', True, False, True) |
| 3277 | |
| 3278 | entry = entries['symlink_file.txt'] |
| 3279 | self.check_entry(entry, 'symlink_file.txt', False, True, True) |
| 3280 | |
| 3281 | def get_entry(self, name): |
Brett Cannon | 96881cd | 2016-06-10 14:37:21 -0700 | [diff] [blame] | 3282 | path = self.bytes_path if isinstance(name, bytes) else self.path |
| 3283 | entries = list(os.scandir(path)) |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3284 | self.assertEqual(len(entries), 1) |
| 3285 | |
| 3286 | entry = entries[0] |
| 3287 | self.assertEqual(entry.name, name) |
| 3288 | return entry |
| 3289 | |
Brett Cannon | 96881cd | 2016-06-10 14:37:21 -0700 | [diff] [blame] | 3290 | def create_file_entry(self, name='file.txt'): |
| 3291 | filename = self.create_file(name=name) |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3292 | return self.get_entry(os.path.basename(filename)) |
| 3293 | |
| 3294 | def test_current_directory(self): |
| 3295 | filename = self.create_file() |
| 3296 | old_dir = os.getcwd() |
| 3297 | try: |
| 3298 | os.chdir(self.path) |
| 3299 | |
| 3300 | # call scandir() without parameter: it must list the content |
| 3301 | # of the current directory |
| 3302 | entries = dict((entry.name, entry) for entry in os.scandir()) |
| 3303 | self.assertEqual(sorted(entries.keys()), |
| 3304 | [os.path.basename(filename)]) |
| 3305 | finally: |
| 3306 | os.chdir(old_dir) |
| 3307 | |
| 3308 | def test_repr(self): |
| 3309 | entry = self.create_file_entry() |
| 3310 | self.assertEqual(repr(entry), "<DirEntry 'file.txt'>") |
| 3311 | |
Brett Cannon | 96881cd | 2016-06-10 14:37:21 -0700 | [diff] [blame] | 3312 | def test_fspath_protocol(self): |
| 3313 | entry = self.create_file_entry() |
| 3314 | self.assertEqual(os.fspath(entry), os.path.join(self.path, 'file.txt')) |
| 3315 | |
| 3316 | def test_fspath_protocol_bytes(self): |
| 3317 | bytes_filename = os.fsencode('bytesfile.txt') |
| 3318 | bytes_entry = self.create_file_entry(name=bytes_filename) |
| 3319 | fspath = os.fspath(bytes_entry) |
| 3320 | self.assertIsInstance(fspath, bytes) |
| 3321 | self.assertEqual(fspath, |
| 3322 | os.path.join(os.fsencode(self.path),bytes_filename)) |
| 3323 | |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3324 | def test_removed_dir(self): |
| 3325 | path = os.path.join(self.path, 'dir') |
| 3326 | |
| 3327 | os.mkdir(path) |
| 3328 | entry = self.get_entry('dir') |
| 3329 | os.rmdir(path) |
| 3330 | |
| 3331 | # On POSIX, is_dir() result depends if scandir() filled d_type or not |
| 3332 | if os.name == 'nt': |
| 3333 | self.assertTrue(entry.is_dir()) |
| 3334 | self.assertFalse(entry.is_file()) |
| 3335 | self.assertFalse(entry.is_symlink()) |
| 3336 | if os.name == 'nt': |
| 3337 | self.assertRaises(FileNotFoundError, entry.inode) |
| 3338 | # don't fail |
| 3339 | entry.stat() |
| 3340 | entry.stat(follow_symlinks=False) |
| 3341 | else: |
| 3342 | self.assertGreater(entry.inode(), 0) |
| 3343 | self.assertRaises(FileNotFoundError, entry.stat) |
| 3344 | self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False) |
| 3345 | |
| 3346 | def test_removed_file(self): |
| 3347 | entry = self.create_file_entry() |
| 3348 | os.unlink(entry.path) |
| 3349 | |
| 3350 | self.assertFalse(entry.is_dir()) |
| 3351 | # On POSIX, is_dir() result depends if scandir() filled d_type or not |
| 3352 | if os.name == 'nt': |
| 3353 | self.assertTrue(entry.is_file()) |
| 3354 | self.assertFalse(entry.is_symlink()) |
| 3355 | if os.name == 'nt': |
| 3356 | self.assertRaises(FileNotFoundError, entry.inode) |
| 3357 | # don't fail |
| 3358 | entry.stat() |
| 3359 | entry.stat(follow_symlinks=False) |
| 3360 | else: |
| 3361 | self.assertGreater(entry.inode(), 0) |
| 3362 | self.assertRaises(FileNotFoundError, entry.stat) |
| 3363 | self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False) |
| 3364 | |
| 3365 | def test_broken_symlink(self): |
| 3366 | if not support.can_symlink(): |
| 3367 | return self.skipTest('cannot create symbolic link') |
| 3368 | |
| 3369 | filename = self.create_file("file.txt") |
| 3370 | os.symlink(filename, |
| 3371 | os.path.join(self.path, "symlink.txt")) |
| 3372 | entries = self.get_entries(['file.txt', 'symlink.txt']) |
| 3373 | entry = entries['symlink.txt'] |
| 3374 | os.unlink(filename) |
| 3375 | |
| 3376 | self.assertGreater(entry.inode(), 0) |
| 3377 | self.assertFalse(entry.is_dir()) |
| 3378 | self.assertFalse(entry.is_file()) # broken symlink returns False |
| 3379 | self.assertFalse(entry.is_dir(follow_symlinks=False)) |
| 3380 | self.assertFalse(entry.is_file(follow_symlinks=False)) |
| 3381 | self.assertTrue(entry.is_symlink()) |
| 3382 | self.assertRaises(FileNotFoundError, entry.stat) |
| 3383 | # don't fail |
| 3384 | entry.stat(follow_symlinks=False) |
| 3385 | |
| 3386 | def test_bytes(self): |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3387 | self.create_file("file.txt") |
| 3388 | |
| 3389 | path_bytes = os.fsencode(self.path) |
| 3390 | entries = list(os.scandir(path_bytes)) |
| 3391 | self.assertEqual(len(entries), 1, entries) |
| 3392 | entry = entries[0] |
| 3393 | |
| 3394 | self.assertEqual(entry.name, b'file.txt') |
| 3395 | self.assertEqual(entry.path, |
| 3396 | os.fsencode(os.path.join(self.path, 'file.txt'))) |
| 3397 | |
Serhiy Storchaka | 1180e5a | 2017-07-11 06:36:46 +0300 | [diff] [blame] | 3398 | def test_bytes_like(self): |
| 3399 | self.create_file("file.txt") |
| 3400 | |
| 3401 | for cls in bytearray, memoryview: |
| 3402 | path_bytes = cls(os.fsencode(self.path)) |
| 3403 | with self.assertWarns(DeprecationWarning): |
| 3404 | entries = list(os.scandir(path_bytes)) |
| 3405 | self.assertEqual(len(entries), 1, entries) |
| 3406 | entry = entries[0] |
| 3407 | |
| 3408 | self.assertEqual(entry.name, b'file.txt') |
| 3409 | self.assertEqual(entry.path, |
| 3410 | os.fsencode(os.path.join(self.path, 'file.txt'))) |
| 3411 | self.assertIs(type(entry.name), bytes) |
| 3412 | self.assertIs(type(entry.path), bytes) |
| 3413 | |
Serhiy Storchaka | ea720fe | 2017-03-30 09:12:31 +0300 | [diff] [blame] | 3414 | @unittest.skipUnless(os.listdir in os.supports_fd, |
| 3415 | 'fd support for listdir required for this test.') |
| 3416 | def test_fd(self): |
| 3417 | self.assertIn(os.scandir, os.supports_fd) |
| 3418 | self.create_file('file.txt') |
| 3419 | expected_names = ['file.txt'] |
| 3420 | if support.can_symlink(): |
| 3421 | os.symlink('file.txt', os.path.join(self.path, 'link')) |
| 3422 | expected_names.append('link') |
| 3423 | |
| 3424 | fd = os.open(self.path, os.O_RDONLY) |
| 3425 | try: |
| 3426 | with os.scandir(fd) as it: |
| 3427 | entries = list(it) |
| 3428 | names = [entry.name for entry in entries] |
| 3429 | self.assertEqual(sorted(names), expected_names) |
| 3430 | self.assertEqual(names, os.listdir(fd)) |
| 3431 | for entry in entries: |
| 3432 | self.assertEqual(entry.path, entry.name) |
| 3433 | self.assertEqual(os.fspath(entry), entry.name) |
| 3434 | self.assertEqual(entry.is_symlink(), entry.name == 'link') |
| 3435 | if os.stat in os.supports_dir_fd: |
| 3436 | st = os.stat(entry.name, dir_fd=fd) |
| 3437 | self.assertEqual(entry.stat(), st) |
| 3438 | st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False) |
| 3439 | self.assertEqual(entry.stat(follow_symlinks=False), st) |
| 3440 | finally: |
| 3441 | os.close(fd) |
| 3442 | |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3443 | def test_empty_path(self): |
| 3444 | self.assertRaises(FileNotFoundError, os.scandir, '') |
| 3445 | |
| 3446 | def test_consume_iterator_twice(self): |
| 3447 | self.create_file("file.txt") |
| 3448 | iterator = os.scandir(self.path) |
| 3449 | |
| 3450 | entries = list(iterator) |
| 3451 | self.assertEqual(len(entries), 1, entries) |
| 3452 | |
| 3453 | # check than consuming the iterator twice doesn't raise exception |
| 3454 | entries2 = list(iterator) |
| 3455 | self.assertEqual(len(entries2), 0, entries2) |
| 3456 | |
| 3457 | def test_bad_path_type(self): |
Serhiy Storchaka | ea720fe | 2017-03-30 09:12:31 +0300 | [diff] [blame] | 3458 | for obj in [1.234, {}, []]: |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3459 | self.assertRaises(TypeError, os.scandir, obj) |
| 3460 | |
Serhiy Storchaka | ffe96ae | 2016-02-11 13:21:30 +0200 | [diff] [blame] | 3461 | def test_close(self): |
| 3462 | self.create_file("file.txt") |
| 3463 | self.create_file("file2.txt") |
| 3464 | iterator = os.scandir(self.path) |
| 3465 | next(iterator) |
| 3466 | iterator.close() |
| 3467 | # multiple closes |
| 3468 | iterator.close() |
| 3469 | with self.check_no_resource_warning(): |
| 3470 | del iterator |
| 3471 | |
| 3472 | def test_context_manager(self): |
| 3473 | self.create_file("file.txt") |
| 3474 | self.create_file("file2.txt") |
| 3475 | with os.scandir(self.path) as iterator: |
| 3476 | next(iterator) |
| 3477 | with self.check_no_resource_warning(): |
| 3478 | del iterator |
| 3479 | |
| 3480 | def test_context_manager_close(self): |
| 3481 | self.create_file("file.txt") |
| 3482 | self.create_file("file2.txt") |
| 3483 | with os.scandir(self.path) as iterator: |
| 3484 | next(iterator) |
| 3485 | iterator.close() |
| 3486 | |
| 3487 | def test_context_manager_exception(self): |
| 3488 | self.create_file("file.txt") |
| 3489 | self.create_file("file2.txt") |
| 3490 | with self.assertRaises(ZeroDivisionError): |
| 3491 | with os.scandir(self.path) as iterator: |
| 3492 | next(iterator) |
| 3493 | 1/0 |
| 3494 | with self.check_no_resource_warning(): |
| 3495 | del iterator |
| 3496 | |
| 3497 | def test_resource_warning(self): |
| 3498 | self.create_file("file.txt") |
| 3499 | self.create_file("file2.txt") |
| 3500 | iterator = os.scandir(self.path) |
| 3501 | next(iterator) |
| 3502 | with self.assertWarns(ResourceWarning): |
| 3503 | del iterator |
| 3504 | support.gc_collect() |
| 3505 | # exhausted iterator |
| 3506 | iterator = os.scandir(self.path) |
| 3507 | list(iterator) |
| 3508 | with self.check_no_resource_warning(): |
| 3509 | del iterator |
| 3510 | |
Victor Stinner | 6036e44 | 2015-03-08 01:58:04 +0100 | [diff] [blame] | 3511 | |
Ethan Furman | cdc0879 | 2016-06-02 15:06:09 -0700 | [diff] [blame] | 3512 | class TestPEP519(unittest.TestCase): |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3513 | |
| 3514 | # Abstracted so it can be overridden to test pure Python implementation |
| 3515 | # if a C version is provided. |
| 3516 | fspath = staticmethod(os.fspath) |
| 3517 | |
Ethan Furman | cdc0879 | 2016-06-02 15:06:09 -0700 | [diff] [blame] | 3518 | def test_return_bytes(self): |
| 3519 | for b in b'hello', b'goodbye', b'some/path/and/file': |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3520 | self.assertEqual(b, self.fspath(b)) |
Ethan Furman | cdc0879 | 2016-06-02 15:06:09 -0700 | [diff] [blame] | 3521 | |
| 3522 | def test_return_string(self): |
| 3523 | for s in 'hello', 'goodbye', 'some/path/and/file': |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3524 | self.assertEqual(s, self.fspath(s)) |
Ethan Furman | cdc0879 | 2016-06-02 15:06:09 -0700 | [diff] [blame] | 3525 | |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3526 | def test_fsencode_fsdecode(self): |
Ethan Furman | c1cbeed | 2016-06-04 10:19:27 -0700 | [diff] [blame] | 3527 | for p in "path/like/object", b"path/like/object": |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 3528 | pathlike = _PathLike(p) |
Ethan Furman | c1cbeed | 2016-06-04 10:19:27 -0700 | [diff] [blame] | 3529 | |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3530 | self.assertEqual(p, self.fspath(pathlike)) |
Ethan Furman | c1cbeed | 2016-06-04 10:19:27 -0700 | [diff] [blame] | 3531 | self.assertEqual(b"path/like/object", os.fsencode(pathlike)) |
| 3532 | self.assertEqual("path/like/object", os.fsdecode(pathlike)) |
| 3533 | |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3534 | def test_pathlike(self): |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 3535 | self.assertEqual('#feelthegil', self.fspath(_PathLike('#feelthegil'))) |
| 3536 | self.assertTrue(issubclass(_PathLike, os.PathLike)) |
| 3537 | self.assertTrue(isinstance(_PathLike(), os.PathLike)) |
Ethan Furman | 410ef8e | 2016-06-04 12:06:26 -0700 | [diff] [blame] | 3538 | |
Ethan Furman | cdc0879 | 2016-06-02 15:06:09 -0700 | [diff] [blame] | 3539 | def test_garbage_in_exception_out(self): |
| 3540 | vapor = type('blah', (), {}) |
| 3541 | for o in int, type, os, vapor(): |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3542 | self.assertRaises(TypeError, self.fspath, o) |
Ethan Furman | cdc0879 | 2016-06-02 15:06:09 -0700 | [diff] [blame] | 3543 | |
| 3544 | def test_argument_required(self): |
Brett Cannon | 044283a | 2016-07-15 10:41:49 -0700 | [diff] [blame] | 3545 | self.assertRaises(TypeError, self.fspath) |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3546 | |
Brett Cannon | 044283a | 2016-07-15 10:41:49 -0700 | [diff] [blame] | 3547 | def test_bad_pathlike(self): |
| 3548 | # __fspath__ returns a value other than str or bytes. |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 3549 | self.assertRaises(TypeError, self.fspath, _PathLike(42)) |
Brett Cannon | 044283a | 2016-07-15 10:41:49 -0700 | [diff] [blame] | 3550 | # __fspath__ attribute that is not callable. |
| 3551 | c = type('foo', (), {}) |
| 3552 | c.__fspath__ = 1 |
| 3553 | self.assertRaises(TypeError, self.fspath, c()) |
| 3554 | # __fspath__ raises an exception. |
Brett Cannon | 044283a | 2016-07-15 10:41:49 -0700 | [diff] [blame] | 3555 | self.assertRaises(ZeroDivisionError, self.fspath, |
Brett Cannon | ec6ce87 | 2016-09-06 15:50:29 -0700 | [diff] [blame] | 3556 | _PathLike(ZeroDivisionError())) |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3557 | |
Victor Stinner | c29b585 | 2017-11-02 07:28:27 -0700 | [diff] [blame] | 3558 | |
| 3559 | class TimesTests(unittest.TestCase): |
| 3560 | def test_times(self): |
| 3561 | times = os.times() |
| 3562 | self.assertIsInstance(times, os.times_result) |
| 3563 | |
| 3564 | for field in ('user', 'system', 'children_user', 'children_system', |
| 3565 | 'elapsed'): |
| 3566 | value = getattr(times, field) |
| 3567 | self.assertIsInstance(value, float) |
| 3568 | |
| 3569 | if os.name == 'nt': |
| 3570 | self.assertEqual(times.children_user, 0) |
| 3571 | self.assertEqual(times.children_system, 0) |
| 3572 | self.assertEqual(times.elapsed, 0) |
| 3573 | |
| 3574 | |
Brett Cannon | c78ca1e | 2016-06-24 12:03:43 -0700 | [diff] [blame] | 3575 | # Only test if the C version is provided, otherwise TestPEP519 already tested |
| 3576 | # the pure Python implementation. |
| 3577 | if hasattr(os, "_fspath"): |
| 3578 | class TestPEP519PurePython(TestPEP519): |
| 3579 | |
| 3580 | """Explicitly test the pure Python implementation of os.fspath().""" |
| 3581 | |
| 3582 | fspath = staticmethod(os._fspath) |
Ethan Furman | cdc0879 | 2016-06-02 15:06:09 -0700 | [diff] [blame] | 3583 | |
| 3584 | |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 3585 | if __name__ == "__main__": |
R David Murray | f2ad173 | 2014-12-25 18:36:56 -0500 | [diff] [blame] | 3586 | unittest.main() |