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 | |
| 5 | import os |
Benjamin Peterson | 5c6d787 | 2009-02-06 02:40:07 +0000 | [diff] [blame] | 6 | import errno |
Fred Drake | 38c2ef0 | 2001-07-17 20:52:51 +0000 | [diff] [blame] | 7 | import unittest |
Jeremy Hylton | a7fc21b | 2001-08-20 20:10:01 +0000 | [diff] [blame] | 8 | import warnings |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 9 | import sys |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 10 | import signal |
| 11 | import subprocess |
| 12 | import time |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 13 | import shutil |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 14 | from test import support |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 15 | import contextlib |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 16 | import mmap |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 17 | import platform |
| 18 | import re |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 19 | import uuid |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 20 | import asyncore |
| 21 | import asynchat |
| 22 | import socket |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 23 | import itertools |
| 24 | import stat |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 25 | import locale |
| 26 | import codecs |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 27 | try: |
| 28 | import threading |
| 29 | except ImportError: |
| 30 | threading = None |
Georg Brandl | 2daf6ae | 2012-02-20 19:54:16 +0100 | [diff] [blame] | 31 | from test.script_helper import assert_python_ok |
Fred Drake | 38c2ef0 | 2001-07-17 20:52:51 +0000 | [diff] [blame] | 32 | |
Victor Stinner | 034d0aa | 2012-06-05 01:22:15 +0200 | [diff] [blame] | 33 | with warnings.catch_warnings(): |
| 34 | warnings.simplefilter("ignore", DeprecationWarning) |
| 35 | os.stat_float_times(True) |
Victor Stinner | 1aa54a4 | 2012-02-08 04:09:37 +0100 | [diff] [blame] | 36 | st = os.stat(__file__) |
| 37 | stat_supports_subsecond = ( |
| 38 | # check if float and int timestamps are different |
| 39 | (st.st_atime != st[7]) |
| 40 | or (st.st_mtime != st[8]) |
| 41 | or (st.st_ctime != st[9])) |
| 42 | |
Mark Dickinson | 7cf0389 | 2010-04-16 13:45:35 +0000 | [diff] [blame] | 43 | # Detect whether we're on a Linux system that uses the (now outdated |
| 44 | # and unmaintained) linuxthreads threading library. There's an issue |
| 45 | # when combining linuxthreads with a failed execv call: see |
| 46 | # http://bugs.python.org/issue4970. |
Victor Stinner | d5c355c | 2011-04-30 14:53:09 +0200 | [diff] [blame] | 47 | if hasattr(sys, 'thread_info') and sys.thread_info.version: |
| 48 | USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads") |
| 49 | else: |
| 50 | USING_LINUXTHREADS = False |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 51 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 52 | # Tests creating TESTFN |
| 53 | class FileTests(unittest.TestCase): |
| 54 | def setUp(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 55 | if os.path.exists(support.TESTFN): |
| 56 | os.unlink(support.TESTFN) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 57 | tearDown = setUp |
| 58 | |
| 59 | def test_access(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 60 | f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 61 | os.close(f) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 62 | self.assertTrue(os.access(support.TESTFN, os.W_OK)) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 63 | |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 64 | def test_closerange(self): |
Antoine Pitrou | b9ee06c | 2008-08-16 22:03:17 +0000 | [diff] [blame] | 65 | first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) |
| 66 | # We must allocate two consecutive file descriptors, otherwise |
| 67 | # it will mess up other file descriptors (perhaps even the three |
| 68 | # standard ones). |
| 69 | second = os.dup(first) |
| 70 | try: |
| 71 | retries = 0 |
| 72 | while second != first + 1: |
| 73 | os.close(first) |
| 74 | retries += 1 |
| 75 | if retries > 10: |
| 76 | # XXX test skipped |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 77 | self.skipTest("couldn't allocate two consecutive fds") |
Antoine Pitrou | b9ee06c | 2008-08-16 22:03:17 +0000 | [diff] [blame] | 78 | first, second = second, os.dup(second) |
| 79 | finally: |
| 80 | os.close(second) |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 81 | # close a fd that is open, and one that isn't |
Antoine Pitrou | b9ee06c | 2008-08-16 22:03:17 +0000 | [diff] [blame] | 82 | os.closerange(first, first + 2) |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 83 | self.assertRaises(OSError, os.write, first, b"a") |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 84 | |
Benjamin Peterson | 1cc6df9 | 2010-06-30 17:39:45 +0000 | [diff] [blame] | 85 | @support.cpython_only |
Hirokazu Yamamoto | 4c19e6e | 2008-09-08 23:41:21 +0000 | [diff] [blame] | 86 | def test_rename(self): |
| 87 | path = support.TESTFN |
| 88 | old = sys.getrefcount(path) |
| 89 | self.assertRaises(TypeError, os.rename, path, 0) |
| 90 | new = sys.getrefcount(path) |
| 91 | self.assertEqual(old, new) |
| 92 | |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 93 | def test_read(self): |
| 94 | with open(support.TESTFN, "w+b") as fobj: |
| 95 | fobj.write(b"spam") |
| 96 | fobj.flush() |
| 97 | fd = fobj.fileno() |
| 98 | os.lseek(fd, 0, 0) |
| 99 | s = os.read(fd, 4) |
| 100 | self.assertEqual(type(s), bytes) |
| 101 | self.assertEqual(s, b"spam") |
| 102 | |
| 103 | def test_write(self): |
| 104 | # os.write() accepts bytes- and buffer-like objects but not strings |
| 105 | fd = os.open(support.TESTFN, os.O_CREAT | os.O_WRONLY) |
| 106 | self.assertRaises(TypeError, os.write, fd, "beans") |
| 107 | os.write(fd, b"bacon\n") |
| 108 | os.write(fd, bytearray(b"eggs\n")) |
| 109 | os.write(fd, memoryview(b"spam\n")) |
| 110 | os.close(fd) |
| 111 | with open(support.TESTFN, "rb") as fobj: |
Antoine Pitrou | d62269f | 2008-09-15 23:54:52 +0000 | [diff] [blame] | 112 | self.assertEqual(fobj.read().splitlines(), |
| 113 | [b"bacon", b"eggs", b"spam"]) |
Antoine Pitrou | 9cadb1b | 2008-09-15 23:02:56 +0000 | [diff] [blame] | 114 | |
Victor Stinner | e0daff1 | 2011-03-20 23:36:35 +0100 | [diff] [blame] | 115 | def write_windows_console(self, *args): |
| 116 | retcode = subprocess.call(args, |
| 117 | # use a new console to not flood the test output |
| 118 | creationflags=subprocess.CREATE_NEW_CONSOLE, |
| 119 | # use a shell to hide the console window (SW_HIDE) |
| 120 | shell=True) |
| 121 | self.assertEqual(retcode, 0) |
| 122 | |
| 123 | @unittest.skipUnless(sys.platform == 'win32', |
| 124 | 'test specific to the Windows console') |
| 125 | def test_write_windows_console(self): |
| 126 | # Issue #11395: the Windows console returns an error (12: not enough |
| 127 | # space error) on writing into stdout if stdout mode is binary and the |
| 128 | # length is greater than 66,000 bytes (or less, depending on heap |
| 129 | # usage). |
| 130 | code = "print('x' * 100000)" |
| 131 | self.write_windows_console(sys.executable, "-c", code) |
| 132 | self.write_windows_console(sys.executable, "-u", "-c", code) |
| 133 | |
Amaury Forgeot d'Arc | e2e36ba | 2008-08-01 00:14:22 +0000 | [diff] [blame] | 134 | def fdopen_helper(self, *args): |
| 135 | fd = os.open(support.TESTFN, os.O_RDONLY) |
Victor Stinner | bef7fdf | 2011-07-01 13:45:30 +0200 | [diff] [blame] | 136 | f = os.fdopen(fd, *args) |
| 137 | f.close() |
Amaury Forgeot d'Arc | e2e36ba | 2008-08-01 00:14:22 +0000 | [diff] [blame] | 138 | |
| 139 | def test_fdopen(self): |
Victor Stinner | bef7fdf | 2011-07-01 13:45:30 +0200 | [diff] [blame] | 140 | fd = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR) |
| 141 | os.close(fd) |
| 142 | |
Amaury Forgeot d'Arc | e2e36ba | 2008-08-01 00:14:22 +0000 | [diff] [blame] | 143 | self.fdopen_helper() |
| 144 | self.fdopen_helper('r') |
| 145 | self.fdopen_helper('r', 100) |
| 146 | |
Antoine Pitrou | f3b2d88 | 2012-01-30 22:08:52 +0100 | [diff] [blame] | 147 | def test_replace(self): |
| 148 | TESTFN2 = support.TESTFN + ".2" |
| 149 | with open(support.TESTFN, 'w') as f: |
| 150 | f.write("1") |
| 151 | with open(TESTFN2, 'w') as f: |
| 152 | f.write("2") |
| 153 | self.addCleanup(os.unlink, TESTFN2) |
| 154 | os.replace(support.TESTFN, TESTFN2) |
| 155 | self.assertRaises(FileNotFoundError, os.stat, support.TESTFN) |
| 156 | with open(TESTFN2, 'r') as f: |
| 157 | self.assertEqual(f.read(), "1") |
| 158 | |
Victor Stinner | bef7fdf | 2011-07-01 13:45:30 +0200 | [diff] [blame] | 159 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 160 | # Test attributes on return values from os.*stat* family. |
| 161 | class StatAttributeTests(unittest.TestCase): |
| 162 | def setUp(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 163 | os.mkdir(support.TESTFN) |
| 164 | self.fname = os.path.join(support.TESTFN, "f1") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 165 | f = open(self.fname, 'wb') |
Guido van Rossum | 26d95c3 | 2007-08-27 23:18:54 +0000 | [diff] [blame] | 166 | f.write(b"ABC") |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 167 | f.close() |
Tim Peters | e0c446b | 2001-10-18 21:57:37 +0000 | [diff] [blame] | 168 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 169 | def tearDown(self): |
| 170 | os.unlink(self.fname) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 171 | os.rmdir(support.TESTFN) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 172 | |
Antoine Pitrou | 3842529 | 2010-09-21 18:19:07 +0000 | [diff] [blame] | 173 | def check_stat_attributes(self, fname): |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 174 | if not hasattr(os, "stat"): |
| 175 | return |
| 176 | |
Antoine Pitrou | 3842529 | 2010-09-21 18:19:07 +0000 | [diff] [blame] | 177 | result = os.stat(fname) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 178 | |
| 179 | # Make sure direct access works |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 180 | self.assertEqual(result[stat.ST_SIZE], 3) |
| 181 | self.assertEqual(result.st_size, 3) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 182 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 183 | # Make sure all the attributes are there |
| 184 | members = dir(result) |
| 185 | for name in dir(stat): |
| 186 | if name[:3] == 'ST_': |
| 187 | attr = name.lower() |
Martin v. Löwis | 4d394df | 2005-01-23 09:19:22 +0000 | [diff] [blame] | 188 | if name.endswith("TIME"): |
| 189 | def trunc(x): return int(x) |
| 190 | else: |
| 191 | def trunc(x): return x |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 192 | self.assertEqual(trunc(getattr(result, attr)), |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 193 | result[getattr(stat, name)]) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 194 | self.assertIn(attr, members) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 195 | |
Larry Hastings | 6fe20b3 | 2012-04-19 15:07:49 -0700 | [diff] [blame] | 196 | # 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] | 197 | # (they should always agree up to around tens-of-microseconds) |
Larry Hastings | 6fe20b3 | 2012-04-19 15:07:49 -0700 | [diff] [blame] | 198 | for name in 'st_atime st_mtime st_ctime'.split(): |
| 199 | floaty = int(getattr(result, name) * 100000) |
| 200 | nanosecondy = getattr(result, name + "_ns") // 10000 |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 201 | self.assertAlmostEqual(floaty, nanosecondy, delta=2) |
Larry Hastings | 6fe20b3 | 2012-04-19 15:07:49 -0700 | [diff] [blame] | 202 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 203 | try: |
| 204 | result[200] |
| 205 | self.fail("No exception thrown") |
| 206 | except IndexError: |
| 207 | pass |
| 208 | |
| 209 | # Make sure that assignment fails |
| 210 | try: |
| 211 | result.st_mode = 1 |
| 212 | self.fail("No exception thrown") |
Collin Winter | 42dae6a | 2007-03-28 21:44:53 +0000 | [diff] [blame] | 213 | except AttributeError: |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 214 | pass |
| 215 | |
| 216 | try: |
| 217 | result.st_rdev = 1 |
| 218 | self.fail("No exception thrown") |
Guido van Rossum | 1fff878 | 2001-10-18 21:19:31 +0000 | [diff] [blame] | 219 | except (AttributeError, TypeError): |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 220 | pass |
| 221 | |
| 222 | try: |
| 223 | result.parrot = 1 |
| 224 | self.fail("No exception thrown") |
| 225 | except AttributeError: |
| 226 | pass |
| 227 | |
| 228 | # Use the stat_result constructor with a too-short tuple. |
| 229 | try: |
| 230 | result2 = os.stat_result((10,)) |
| 231 | self.fail("No exception thrown") |
| 232 | except TypeError: |
| 233 | pass |
| 234 | |
Ezio Melotti | 42da663 | 2011-03-15 05:18:48 +0200 | [diff] [blame] | 235 | # Use the constructor with a too-long tuple. |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 236 | try: |
| 237 | result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14)) |
| 238 | except TypeError: |
| 239 | pass |
| 240 | |
Antoine Pitrou | 3842529 | 2010-09-21 18:19:07 +0000 | [diff] [blame] | 241 | def test_stat_attributes(self): |
| 242 | self.check_stat_attributes(self.fname) |
| 243 | |
| 244 | def test_stat_attributes_bytes(self): |
| 245 | try: |
| 246 | fname = self.fname.encode(sys.getfilesystemencoding()) |
| 247 | except UnicodeEncodeError: |
| 248 | self.skipTest("cannot encode %a for the filesystem" % self.fname) |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 249 | with warnings.catch_warnings(): |
| 250 | warnings.simplefilter("ignore", DeprecationWarning) |
| 251 | self.check_stat_attributes(fname) |
Tim Peters | e0c446b | 2001-10-18 21:57:37 +0000 | [diff] [blame] | 252 | |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 253 | def test_statvfs_attributes(self): |
| 254 | if not hasattr(os, "statvfs"): |
| 255 | return |
| 256 | |
Martin v. Löwis | f90ae20 | 2002-06-11 06:22:31 +0000 | [diff] [blame] | 257 | try: |
| 258 | result = os.statvfs(self.fname) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 259 | except OSError as e: |
Martin v. Löwis | f90ae20 | 2002-06-11 06:22:31 +0000 | [diff] [blame] | 260 | # On AtheOS, glibc always returns ENOSYS |
Martin v. Löwis | f90ae20 | 2002-06-11 06:22:31 +0000 | [diff] [blame] | 261 | if e.errno == errno.ENOSYS: |
| 262 | return |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 263 | |
| 264 | # Make sure direct access works |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 265 | self.assertEqual(result.f_bfree, result[3]) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 266 | |
Brett Cannon | cfaf10c | 2008-05-16 00:45:35 +0000 | [diff] [blame] | 267 | # Make sure all the attributes are there. |
| 268 | members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files', |
| 269 | 'ffree', 'favail', 'flag', 'namemax') |
| 270 | for value, member in enumerate(members): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 271 | self.assertEqual(getattr(result, 'f_' + member), result[value]) |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 272 | |
| 273 | # Make sure that assignment really fails |
| 274 | try: |
| 275 | result.f_bfree = 1 |
| 276 | self.fail("No exception thrown") |
Collin Winter | 42dae6a | 2007-03-28 21:44:53 +0000 | [diff] [blame] | 277 | except AttributeError: |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 278 | pass |
| 279 | |
| 280 | try: |
| 281 | result.parrot = 1 |
| 282 | self.fail("No exception thrown") |
| 283 | except AttributeError: |
| 284 | pass |
| 285 | |
| 286 | # Use the constructor with a too-short tuple. |
| 287 | try: |
| 288 | result2 = os.statvfs_result((10,)) |
| 289 | self.fail("No exception thrown") |
| 290 | except TypeError: |
| 291 | pass |
| 292 | |
Ezio Melotti | 42da663 | 2011-03-15 05:18:48 +0200 | [diff] [blame] | 293 | # Use the constructor with a too-long tuple. |
Guido van Rossum | 98bf58f | 2001-10-18 20:34:25 +0000 | [diff] [blame] | 294 | try: |
| 295 | result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14)) |
| 296 | except TypeError: |
| 297 | pass |
Fred Drake | 38c2ef0 | 2001-07-17 20:52:51 +0000 | [diff] [blame] | 298 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 299 | def test_utime_dir(self): |
| 300 | delta = 1000000 |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 301 | st = os.stat(support.TESTFN) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 302 | # round to int, because some systems may support sub-second |
| 303 | # time stamps in stat, but not in utime. |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 304 | os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta))) |
| 305 | st2 = os.stat(support.TESTFN) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 306 | self.assertEqual(st2.st_mtime, int(st.st_mtime-delta)) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 307 | |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 308 | def _test_utime(self, filename, attr, utime, delta): |
Brian Curtin | 0277aa3 | 2011-11-06 13:50:15 -0600 | [diff] [blame] | 309 | # Issue #13327 removed the requirement to pass None as the |
Brian Curtin | 52fbea1 | 2011-11-06 13:41:17 -0600 | [diff] [blame] | 310 | # second argument. Check that the previous methods of passing |
| 311 | # a time tuple or None work in addition to no argument. |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 312 | st0 = os.stat(filename) |
Brian Curtin | 52fbea1 | 2011-11-06 13:41:17 -0600 | [diff] [blame] | 313 | # Doesn't set anything new, but sets the time tuple way |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 314 | utime(filename, (attr(st0, "st_atime"), attr(st0, "st_mtime"))) |
| 315 | # Setting the time to the time you just read, then reading again, |
| 316 | # should always return exactly the same times. |
| 317 | st1 = os.stat(filename) |
| 318 | self.assertEqual(attr(st0, "st_mtime"), attr(st1, "st_mtime")) |
| 319 | self.assertEqual(attr(st0, "st_atime"), attr(st1, "st_atime")) |
Brian Curtin | 52fbea1 | 2011-11-06 13:41:17 -0600 | [diff] [blame] | 320 | # Set to the current time in the old explicit way. |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 321 | os.utime(filename, None) |
Brian Curtin | 52fbea1 | 2011-11-06 13:41:17 -0600 | [diff] [blame] | 322 | st2 = os.stat(support.TESTFN) |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 323 | # Set to the current time in the new way |
| 324 | os.utime(filename) |
| 325 | st3 = os.stat(filename) |
| 326 | self.assertAlmostEqual(attr(st2, "st_mtime"), attr(st3, "st_mtime"), delta=delta) |
| 327 | |
| 328 | def test_utime(self): |
| 329 | def utime(file, times): |
| 330 | return os.utime(file, times) |
| 331 | self._test_utime(self.fname, getattr, utime, 10) |
| 332 | self._test_utime(support.TESTFN, getattr, utime, 10) |
| 333 | |
| 334 | |
| 335 | def _test_utime_ns(self, set_times_ns, test_dir=True): |
| 336 | def getattr_ns(o, attr): |
| 337 | return getattr(o, attr + "_ns") |
| 338 | ten_s = 10 * 1000 * 1000 * 1000 |
| 339 | self._test_utime(self.fname, getattr_ns, set_times_ns, ten_s) |
| 340 | if test_dir: |
| 341 | self._test_utime(support.TESTFN, getattr_ns, set_times_ns, ten_s) |
| 342 | |
| 343 | def test_utime_ns(self): |
| 344 | def utime_ns(file, times): |
| 345 | return os.utime(file, ns=times) |
| 346 | self._test_utime_ns(utime_ns) |
| 347 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 348 | requires_utime_dir_fd = unittest.skipUnless( |
| 349 | os.utime in os.supports_dir_fd, |
| 350 | "dir_fd support for utime required for this test.") |
| 351 | requires_utime_fd = unittest.skipUnless( |
| 352 | os.utime in os.supports_fd, |
| 353 | "fd support for utime required for this test.") |
| 354 | requires_utime_nofollow_symlinks = unittest.skipUnless( |
| 355 | os.utime in os.supports_follow_symlinks, |
| 356 | "follow_symlinks support for utime required for this test.") |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 357 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 358 | @requires_utime_nofollow_symlinks |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 359 | def test_lutimes_ns(self): |
| 360 | def lutimes_ns(file, times): |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 361 | return os.utime(file, ns=times, follow_symlinks=False) |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 362 | self._test_utime_ns(lutimes_ns) |
| 363 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 364 | @requires_utime_fd |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 365 | def test_futimes_ns(self): |
| 366 | def futimes_ns(file, times): |
| 367 | with open(file, "wb") as f: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 368 | os.utime(f.fileno(), ns=times) |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 369 | self._test_utime_ns(futimes_ns, test_dir=False) |
| 370 | |
| 371 | def _utime_invalid_arguments(self, name, arg): |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 372 | with self.assertRaises(ValueError): |
Larry Hastings | 76ad59b | 2012-05-03 00:30:07 -0700 | [diff] [blame] | 373 | getattr(os, name)(arg, (5, 5), ns=(5, 5)) |
| 374 | |
| 375 | def test_utime_invalid_arguments(self): |
| 376 | self._utime_invalid_arguments('utime', self.fname) |
| 377 | |
Brian Curtin | 52fbea1 | 2011-11-06 13:41:17 -0600 | [diff] [blame] | 378 | |
Victor Stinner | 1aa54a4 | 2012-02-08 04:09:37 +0100 | [diff] [blame] | 379 | @unittest.skipUnless(stat_supports_subsecond, |
| 380 | "os.stat() doesn't has a subsecond resolution") |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 381 | def _test_utime_subsecond(self, set_time_func): |
Victor Stinner | be557de | 2012-02-08 03:01:11 +0100 | [diff] [blame] | 382 | asec, amsec = 1, 901 |
| 383 | atime = asec + amsec * 1e-3 |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 384 | msec, mmsec = 2, 901 |
Victor Stinner | be557de | 2012-02-08 03:01:11 +0100 | [diff] [blame] | 385 | mtime = msec + mmsec * 1e-3 |
| 386 | filename = self.fname |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 387 | os.utime(filename, (0, 0)) |
| 388 | set_time_func(filename, atime, mtime) |
Victor Stinner | 034d0aa | 2012-06-05 01:22:15 +0200 | [diff] [blame] | 389 | with warnings.catch_warnings(): |
| 390 | warnings.simplefilter("ignore", DeprecationWarning) |
| 391 | os.stat_float_times(True) |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 392 | st = os.stat(filename) |
| 393 | self.assertAlmostEqual(st.st_atime, atime, places=3) |
| 394 | self.assertAlmostEqual(st.st_mtime, mtime, places=3) |
Victor Stinner | be557de | 2012-02-08 03:01:11 +0100 | [diff] [blame] | 395 | |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 396 | def test_utime_subsecond(self): |
| 397 | def set_time(filename, atime, mtime): |
| 398 | os.utime(filename, (atime, mtime)) |
| 399 | self._test_utime_subsecond(set_time) |
| 400 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 401 | @requires_utime_fd |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 402 | def test_futimes_subsecond(self): |
| 403 | def set_time(filename, atime, mtime): |
| 404 | with open(filename, "wb") as f: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 405 | os.utime(f.fileno(), times=(atime, mtime)) |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 406 | self._test_utime_subsecond(set_time) |
| 407 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 408 | @requires_utime_fd |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 409 | def test_futimens_subsecond(self): |
| 410 | def set_time(filename, atime, mtime): |
| 411 | with open(filename, "wb") as f: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 412 | os.utime(f.fileno(), times=(atime, mtime)) |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 413 | self._test_utime_subsecond(set_time) |
| 414 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 415 | @requires_utime_dir_fd |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 416 | def test_futimesat_subsecond(self): |
| 417 | def set_time(filename, atime, mtime): |
| 418 | dirname = os.path.dirname(filename) |
| 419 | dirfd = os.open(dirname, os.O_RDONLY) |
| 420 | try: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 421 | os.utime(os.path.basename(filename), dir_fd=dirfd, |
| 422 | times=(atime, mtime)) |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 423 | finally: |
| 424 | os.close(dirfd) |
| 425 | self._test_utime_subsecond(set_time) |
| 426 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 427 | @requires_utime_nofollow_symlinks |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 428 | def test_lutimes_subsecond(self): |
| 429 | def set_time(filename, atime, mtime): |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 430 | os.utime(filename, (atime, mtime), follow_symlinks=False) |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 431 | self._test_utime_subsecond(set_time) |
| 432 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 433 | @requires_utime_dir_fd |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 434 | def test_utimensat_subsecond(self): |
| 435 | def set_time(filename, atime, mtime): |
| 436 | dirname = os.path.dirname(filename) |
| 437 | dirfd = os.open(dirname, os.O_RDONLY) |
| 438 | try: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 439 | os.utime(os.path.basename(filename), dir_fd=dirfd, |
| 440 | times=(atime, mtime)) |
Victor Stinner | a2f7c00 | 2012-02-08 03:36:25 +0100 | [diff] [blame] | 441 | finally: |
| 442 | os.close(dirfd) |
| 443 | self._test_utime_subsecond(set_time) |
Victor Stinner | be557de | 2012-02-08 03:01:11 +0100 | [diff] [blame] | 444 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 445 | # Restrict test to Win32, since there is no guarantee other |
| 446 | # systems support centiseconds |
| 447 | if sys.platform == 'win32': |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 448 | def get_file_system(path): |
Hirokazu Yamamoto | 5ef6d18 | 2008-08-20 04:17:24 +0000 | [diff] [blame] | 449 | root = os.path.splitdrive(os.path.abspath(path))[0] + '\\' |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 450 | import ctypes |
Hirokazu Yamamoto | ca765d5 | 2008-08-20 16:18:19 +0000 | [diff] [blame] | 451 | kernel32 = ctypes.windll.kernel32 |
Hirokazu Yamamoto | 5ef6d18 | 2008-08-20 04:17:24 +0000 | [diff] [blame] | 452 | buf = ctypes.create_unicode_buffer("", 100) |
Hirokazu Yamamoto | ca765d5 | 2008-08-20 16:18:19 +0000 | [diff] [blame] | 453 | if kernel32.GetVolumeInformationW(root, None, 0, None, None, None, buf, len(buf)): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 454 | return buf.value |
| 455 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 456 | if get_file_system(support.TESTFN) == "NTFS": |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 457 | def test_1565150(self): |
| 458 | t1 = 1159195039.25 |
| 459 | os.utime(self.fname, (t1, t1)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 460 | self.assertEqual(os.stat(self.fname).st_mtime, t1) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 461 | |
Amaury Forgeot d'Arc | a251a85 | 2011-01-03 00:19:11 +0000 | [diff] [blame] | 462 | def test_large_time(self): |
| 463 | t1 = 5000000000 # some day in 2128 |
| 464 | os.utime(self.fname, (t1, t1)) |
| 465 | self.assertEqual(os.stat(self.fname).st_mtime, t1) |
| 466 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 467 | def test_1686475(self): |
| 468 | # Verify that an open file can be stat'ed |
| 469 | try: |
| 470 | os.stat(r"c:\pagefile.sys") |
| 471 | except WindowsError as e: |
Benjamin Peterson | c4fe6f3 | 2008-08-19 18:57:56 +0000 | [diff] [blame] | 472 | if e.errno == 2: # file does not exist; cannot run test |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 473 | return |
| 474 | self.fail("Could not stat pagefile.sys") |
| 475 | |
Richard Oudkerk | 2240ac1 | 2012-07-06 12:05:32 +0100 | [diff] [blame] | 476 | @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") |
| 477 | def test_15261(self): |
| 478 | # Verify that stat'ing a closed fd does not cause crash |
| 479 | r, w = os.pipe() |
| 480 | try: |
| 481 | os.stat(r) # should not raise error |
| 482 | finally: |
| 483 | os.close(r) |
| 484 | os.close(w) |
| 485 | with self.assertRaises(OSError) as ctx: |
| 486 | os.stat(r) |
| 487 | self.assertEqual(ctx.exception.errno, errno.EBADF) |
| 488 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 489 | from test import mapping_tests |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 490 | |
Walter Dörwald | 0a6d0ff | 2004-05-31 16:29:04 +0000 | [diff] [blame] | 491 | class EnvironTests(mapping_tests.BasicTestMappingProtocol): |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 492 | """check that os.environ object conform to mapping protocol""" |
Walter Dörwald | 118f931 | 2004-06-02 18:42:25 +0000 | [diff] [blame] | 493 | type2test = None |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 494 | |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 495 | def setUp(self): |
| 496 | self.__save = dict(os.environ) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 497 | if os.supports_bytes_environ: |
Victor Stinner | 208d28c | 2010-05-07 00:54:14 +0000 | [diff] [blame] | 498 | self.__saveb = dict(os.environb) |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 499 | for key, value in self._reference().items(): |
| 500 | os.environ[key] = value |
| 501 | |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 502 | def tearDown(self): |
| 503 | os.environ.clear() |
| 504 | os.environ.update(self.__save) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 505 | if os.supports_bytes_environ: |
Victor Stinner | 208d28c | 2010-05-07 00:54:14 +0000 | [diff] [blame] | 506 | os.environb.clear() |
| 507 | os.environb.update(self.__saveb) |
Raymond Hettinger | 2c2d322 | 2003-03-09 07:05:43 +0000 | [diff] [blame] | 508 | |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 509 | def _reference(self): |
| 510 | return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"} |
| 511 | |
| 512 | def _empty_mapping(self): |
| 513 | os.environ.clear() |
| 514 | return os.environ |
| 515 | |
Martin v. Löwis | 1d11de6 | 2005-01-29 13:29:23 +0000 | [diff] [blame] | 516 | # Bug 1110478 |
Martin v. Löwis | 5510f65 | 2005-02-17 21:23:20 +0000 | [diff] [blame] | 517 | def test_update2(self): |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 518 | os.environ.clear() |
Martin v. Löwis | 1d11de6 | 2005-01-29 13:29:23 +0000 | [diff] [blame] | 519 | if os.path.exists("/bin/sh"): |
| 520 | os.environ.update(HELLO="World") |
Brian Curtin | 810921b | 2010-10-30 21:24:21 +0000 | [diff] [blame] | 521 | with os.popen("/bin/sh -c 'echo $HELLO'") as popen: |
| 522 | value = popen.read().strip() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 523 | self.assertEqual(value, "World") |
Martin v. Löwis | 1d11de6 | 2005-01-29 13:29:23 +0000 | [diff] [blame] | 524 | |
Christian Heimes | 1a13d59 | 2007-11-08 14:16:55 +0000 | [diff] [blame] | 525 | def test_os_popen_iter(self): |
| 526 | if os.path.exists("/bin/sh"): |
Brian Curtin | 810921b | 2010-10-30 21:24:21 +0000 | [diff] [blame] | 527 | with os.popen( |
| 528 | "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen: |
| 529 | it = iter(popen) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 530 | self.assertEqual(next(it), "line1\n") |
| 531 | self.assertEqual(next(it), "line2\n") |
| 532 | self.assertEqual(next(it), "line3\n") |
Brian Curtin | 810921b | 2010-10-30 21:24:21 +0000 | [diff] [blame] | 533 | self.assertRaises(StopIteration, next, it) |
Christian Heimes | 1a13d59 | 2007-11-08 14:16:55 +0000 | [diff] [blame] | 534 | |
Guido van Rossum | 67aca9e | 2007-06-13 21:51:27 +0000 | [diff] [blame] | 535 | # Verify environ keys and values from the OS are of the |
| 536 | # correct str type. |
| 537 | def test_keyvalue_types(self): |
| 538 | for key, val in os.environ.items(): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 539 | self.assertEqual(type(key), str) |
| 540 | self.assertEqual(type(val), str) |
Guido van Rossum | 67aca9e | 2007-06-13 21:51:27 +0000 | [diff] [blame] | 541 | |
Christian Heimes | 9033339 | 2007-11-01 19:08:42 +0000 | [diff] [blame] | 542 | def test_items(self): |
| 543 | for key, value in self._reference().items(): |
| 544 | self.assertEqual(os.environ.get(key), value) |
| 545 | |
Ezio Melotti | 19e4acf | 2010-02-22 15:59:01 +0000 | [diff] [blame] | 546 | # Issue 7310 |
| 547 | def test___repr__(self): |
| 548 | """Check that the repr() of os.environ looks like environ({...}).""" |
| 549 | env = os.environ |
Victor Stinner | 96f0de9 | 2010-07-29 00:29:00 +0000 | [diff] [blame] | 550 | self.assertEqual(repr(env), 'environ({{{}}})'.format(', '.join( |
| 551 | '{!r}: {!r}'.format(key, value) |
| 552 | for key, value in env.items()))) |
Ezio Melotti | 19e4acf | 2010-02-22 15:59:01 +0000 | [diff] [blame] | 553 | |
Gregory P. Smith | b6e8c7e | 2010-02-27 07:22:22 +0000 | [diff] [blame] | 554 | def test_get_exec_path(self): |
| 555 | defpath_list = os.defpath.split(os.pathsep) |
| 556 | test_path = ['/monty', '/python', '', '/flying/circus'] |
| 557 | test_env = {'PATH': os.pathsep.join(test_path)} |
| 558 | |
| 559 | saved_environ = os.environ |
| 560 | try: |
| 561 | os.environ = dict(test_env) |
| 562 | # Test that defaulting to os.environ works. |
| 563 | self.assertSequenceEqual(test_path, os.get_exec_path()) |
| 564 | self.assertSequenceEqual(test_path, os.get_exec_path(env=None)) |
| 565 | finally: |
| 566 | os.environ = saved_environ |
| 567 | |
| 568 | # No PATH environment variable |
| 569 | self.assertSequenceEqual(defpath_list, os.get_exec_path({})) |
| 570 | # Empty PATH environment variable |
| 571 | self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''})) |
| 572 | # Supplied PATH environment variable |
| 573 | self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) |
| 574 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 575 | if os.supports_bytes_environ: |
| 576 | # env cannot contain 'PATH' and b'PATH' keys |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 577 | try: |
Victor Stinner | 6f35eda | 2010-10-29 00:38:58 +0000 | [diff] [blame] | 578 | # ignore BytesWarning warning |
| 579 | with warnings.catch_warnings(record=True): |
| 580 | mixed_env = {'PATH': '1', b'PATH': b'2'} |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 581 | except BytesWarning: |
Victor Stinner | 6f35eda | 2010-10-29 00:38:58 +0000 | [diff] [blame] | 582 | # mixed_env cannot be created with python -bb |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 583 | pass |
| 584 | else: |
| 585 | self.assertRaises(ValueError, os.get_exec_path, mixed_env) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 586 | |
| 587 | # bytes key and/or value |
| 588 | self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}), |
| 589 | ['abc']) |
| 590 | self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}), |
| 591 | ['abc']) |
| 592 | self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}), |
| 593 | ['abc']) |
| 594 | |
| 595 | @unittest.skipUnless(os.supports_bytes_environ, |
| 596 | "os.environb required for this test.") |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 597 | def test_environb(self): |
| 598 | # os.environ -> os.environb |
| 599 | value = 'euro\u20ac' |
| 600 | try: |
Benjamin Peterson | 180799d | 2010-05-06 22:25:42 +0000 | [diff] [blame] | 601 | value_bytes = value.encode(sys.getfilesystemencoding(), |
| 602 | 'surrogateescape') |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 603 | except UnicodeEncodeError: |
Benjamin Peterson | 180799d | 2010-05-06 22:25:42 +0000 | [diff] [blame] | 604 | msg = "U+20AC character is not encodable to %s" % ( |
| 605 | sys.getfilesystemencoding(),) |
Benjamin Peterson | 932d3f4 | 2010-05-06 22:26:31 +0000 | [diff] [blame] | 606 | self.skipTest(msg) |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 607 | os.environ['unicode'] = value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 608 | self.assertEqual(os.environ['unicode'], value) |
| 609 | self.assertEqual(os.environb[b'unicode'], value_bytes) |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 610 | |
| 611 | # os.environb -> os.environ |
| 612 | value = b'\xff' |
| 613 | os.environb[b'bytes'] = value |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 614 | self.assertEqual(os.environb[b'bytes'], value) |
Victor Stinner | 84ae118 | 2010-05-06 22:05:07 +0000 | [diff] [blame] | 615 | value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 616 | self.assertEqual(os.environ['bytes'], value_str) |
Ezio Melotti | 19e4acf | 2010-02-22 15:59:01 +0000 | [diff] [blame] | 617 | |
Charles-François Natali | 2966f10 | 2011-11-26 11:32:46 +0100 | [diff] [blame] | 618 | # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue |
| 619 | # #13415). |
| 620 | @support.requires_freebsd_version(7) |
| 621 | @support.requires_mac_ver(10, 6) |
Victor Stinner | 60b385e | 2011-11-22 22:01:28 +0100 | [diff] [blame] | 622 | def test_unset_error(self): |
| 623 | if sys.platform == "win32": |
| 624 | # an environment variable is limited to 32,767 characters |
| 625 | key = 'x' * 50000 |
Victor Stinner | b3f8268 | 2011-11-22 22:30:19 +0100 | [diff] [blame] | 626 | self.assertRaises(ValueError, os.environ.__delitem__, key) |
Victor Stinner | 60b385e | 2011-11-22 22:01:28 +0100 | [diff] [blame] | 627 | else: |
| 628 | # "=" is not allowed in a variable name |
| 629 | key = 'key=' |
Victor Stinner | b3f8268 | 2011-11-22 22:30:19 +0100 | [diff] [blame] | 630 | self.assertRaises(OSError, os.environ.__delitem__, key) |
Victor Stinner | 60b385e | 2011-11-22 22:01:28 +0100 | [diff] [blame] | 631 | |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 632 | class WalkTests(unittest.TestCase): |
| 633 | """Tests for os.walk().""" |
| 634 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 635 | def setUp(self): |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 636 | import os |
| 637 | from os.path import join |
| 638 | |
| 639 | # Build: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 640 | # TESTFN/ |
| 641 | # TEST1/ a file kid and two directory kids |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 642 | # tmp1 |
| 643 | # SUB1/ a file kid and a directory kid |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 644 | # tmp2 |
| 645 | # SUB11/ no kids |
| 646 | # SUB2/ a file kid and a dirsymlink kid |
| 647 | # tmp3 |
| 648 | # link/ a symlink to TESTFN.2 |
Hynek Schlawack | 66bfcc1 | 2012-05-15 16:32:21 +0200 | [diff] [blame] | 649 | # broken_link |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 650 | # TEST2/ |
| 651 | # tmp4 a lone file |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 652 | walk_path = join(support.TESTFN, "TEST1") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 653 | sub1_path = join(walk_path, "SUB1") |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 654 | sub11_path = join(sub1_path, "SUB11") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 655 | sub2_path = join(walk_path, "SUB2") |
| 656 | tmp1_path = join(walk_path, "tmp1") |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 657 | tmp2_path = join(sub1_path, "tmp2") |
| 658 | tmp3_path = join(sub2_path, "tmp3") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 659 | link_path = join(sub2_path, "link") |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 660 | t2_path = join(support.TESTFN, "TEST2") |
| 661 | tmp4_path = join(support.TESTFN, "TEST2", "tmp4") |
Hynek Schlawack | 66bfcc1 | 2012-05-15 16:32:21 +0200 | [diff] [blame] | 662 | link_path = join(sub2_path, "link") |
| 663 | broken_link_path = join(sub2_path, "broken_link") |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 664 | |
| 665 | # Create stuff. |
| 666 | os.makedirs(sub11_path) |
| 667 | os.makedirs(sub2_path) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 668 | os.makedirs(t2_path) |
| 669 | for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path: |
Alex Martelli | 01c77c6 | 2006-08-24 02:58:11 +0000 | [diff] [blame] | 670 | f = open(path, "w") |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 671 | f.write("I'm " + path + " and proud of it. Blame test_os.\n") |
| 672 | f.close() |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 673 | if support.can_symlink(): |
Antoine Pitrou | 5311c1d | 2012-01-24 08:59:28 +0100 | [diff] [blame] | 674 | if os.name == 'nt': |
| 675 | def symlink_to_dir(src, dest): |
| 676 | os.symlink(src, dest, True) |
| 677 | else: |
| 678 | symlink_to_dir = os.symlink |
| 679 | symlink_to_dir(os.path.abspath(t2_path), link_path) |
Hynek Schlawack | 66bfcc1 | 2012-05-15 16:32:21 +0200 | [diff] [blame] | 680 | symlink_to_dir('broken', broken_link_path) |
| 681 | sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"]) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 682 | else: |
| 683 | sub2_tree = (sub2_path, [], ["tmp3"]) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 684 | |
| 685 | # Walk top-down. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 686 | all = list(os.walk(walk_path)) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 687 | self.assertEqual(len(all), 4) |
| 688 | # We can't know which order SUB1 and SUB2 will appear in. |
| 689 | # Not flipped: TESTFN, SUB1, SUB11, SUB2 |
| 690 | # flipped: TESTFN, SUB2, SUB1, SUB11 |
| 691 | flipped = all[0][1][0] != "SUB1" |
| 692 | all[0][1].sort() |
Hynek Schlawack | c96f5a0 | 2012-05-15 17:55:38 +0200 | [diff] [blame] | 693 | all[3 - 2 * flipped][-1].sort() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 694 | self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"])) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 695 | self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"])) |
| 696 | self.assertEqual(all[2 + flipped], (sub11_path, [], [])) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 697 | self.assertEqual(all[3 - 2 * flipped], sub2_tree) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 698 | |
| 699 | # Prune the search. |
| 700 | all = [] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 701 | for root, dirs, files in os.walk(walk_path): |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 702 | all.append((root, dirs, files)) |
| 703 | # Don't descend into SUB1. |
| 704 | if 'SUB1' in dirs: |
| 705 | # Note that this also mutates the dirs we appended to all! |
| 706 | dirs.remove('SUB1') |
| 707 | self.assertEqual(len(all), 2) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 708 | self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"])) |
Hynek Schlawack | 39bf90d | 2012-05-15 18:40:17 +0200 | [diff] [blame] | 709 | all[1][-1].sort() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 710 | self.assertEqual(all[1], sub2_tree) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 711 | |
| 712 | # Walk bottom-up. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 713 | all = list(os.walk(walk_path, topdown=False)) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 714 | self.assertEqual(len(all), 4) |
| 715 | # We can't know which order SUB1 and SUB2 will appear in. |
| 716 | # Not flipped: SUB11, SUB1, SUB2, TESTFN |
| 717 | # flipped: SUB2, SUB11, SUB1, TESTFN |
| 718 | flipped = all[3][1][0] != "SUB1" |
| 719 | all[3][1].sort() |
Hynek Schlawack | 39bf90d | 2012-05-15 18:40:17 +0200 | [diff] [blame] | 720 | all[2 - 2 * flipped][-1].sort() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 721 | self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"])) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 722 | self.assertEqual(all[flipped], (sub11_path, [], [])) |
| 723 | self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"])) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 724 | self.assertEqual(all[2 - 2 * flipped], sub2_tree) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 725 | |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 726 | if support.can_symlink(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 727 | # Walk, following symlinks. |
| 728 | for root, dirs, files in os.walk(walk_path, followlinks=True): |
| 729 | if root == link_path: |
| 730 | self.assertEqual(dirs, []) |
| 731 | self.assertEqual(files, ["tmp4"]) |
| 732 | break |
| 733 | else: |
| 734 | self.fail("Didn't follow symlink with followlinks=True") |
| 735 | |
| 736 | def tearDown(self): |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 737 | # Tear everything down. This is a decent use for bottom-up on |
| 738 | # Windows, which doesn't have a recursive delete command. The |
| 739 | # (not so) subtlety is that rmdir will fail unless the dir's |
| 740 | # kids are removed first, so bottom up is essential. |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 741 | for root, dirs, files in os.walk(support.TESTFN, topdown=False): |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 742 | for name in files: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 743 | os.remove(os.path.join(root, name)) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 744 | for name in dirs: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 745 | dirname = os.path.join(root, name) |
| 746 | if not os.path.islink(dirname): |
| 747 | os.rmdir(dirname) |
| 748 | else: |
| 749 | os.remove(dirname) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 750 | os.rmdir(support.TESTFN) |
Tim Peters | c4e0940 | 2003-04-25 07:11:48 +0000 | [diff] [blame] | 751 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 752 | |
| 753 | @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()") |
| 754 | class FwalkTests(WalkTests): |
| 755 | """Tests for os.fwalk().""" |
| 756 | |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 757 | def _compare_to_walk(self, walk_kwargs, fwalk_kwargs): |
| 758 | """ |
| 759 | compare with walk() results. |
| 760 | """ |
Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 761 | walk_kwargs = walk_kwargs.copy() |
| 762 | fwalk_kwargs = fwalk_kwargs.copy() |
| 763 | for topdown, follow_symlinks in itertools.product((True, False), repeat=2): |
| 764 | walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks) |
| 765 | fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks) |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 766 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 767 | expected = {} |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 768 | for root, dirs, files in os.walk(**walk_kwargs): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 769 | expected[root] = (set(dirs), set(files)) |
| 770 | |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 771 | for root, dirs, files, rootfd in os.fwalk(**fwalk_kwargs): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 772 | self.assertIn(root, expected) |
| 773 | self.assertEqual(expected[root], (set(dirs), set(files))) |
| 774 | |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 775 | def test_compare_to_walk(self): |
| 776 | kwargs = {'top': support.TESTFN} |
| 777 | self._compare_to_walk(kwargs, kwargs) |
| 778 | |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 779 | def test_dir_fd(self): |
Larry Hastings | c48fe98 | 2012-06-25 04:49:05 -0700 | [diff] [blame] | 780 | try: |
| 781 | fd = os.open(".", os.O_RDONLY) |
| 782 | walk_kwargs = {'top': support.TESTFN} |
| 783 | fwalk_kwargs = walk_kwargs.copy() |
| 784 | fwalk_kwargs['dir_fd'] = fd |
| 785 | self._compare_to_walk(walk_kwargs, fwalk_kwargs) |
| 786 | finally: |
| 787 | os.close(fd) |
| 788 | |
| 789 | def test_yields_correct_dir_fd(self): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 790 | # check returned file descriptors |
Larry Hastings | b403806 | 2012-07-15 10:57:38 -0700 | [diff] [blame] | 791 | for topdown, follow_symlinks in itertools.product((True, False), repeat=2): |
| 792 | args = support.TESTFN, topdown, None |
| 793 | for root, dirs, files, rootfd in os.fwalk(*args, follow_symlinks=follow_symlinks): |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 794 | # check that the FD is valid |
| 795 | os.fstat(rootfd) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 796 | # redundant check |
| 797 | os.stat(rootfd) |
| 798 | # check that listdir() returns consistent information |
| 799 | self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files)) |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 800 | |
| 801 | def test_fd_leak(self): |
| 802 | # Since we're opening a lot of FDs, we must be careful to avoid leaks: |
| 803 | # we both check that calling fwalk() a large number of times doesn't |
| 804 | # yield EMFILE, and that the minimum allocated FD hasn't changed. |
| 805 | minfd = os.dup(1) |
| 806 | os.close(minfd) |
| 807 | for i in range(256): |
| 808 | for x in os.fwalk(support.TESTFN): |
| 809 | pass |
| 810 | newfd = os.dup(1) |
| 811 | self.addCleanup(os.close, newfd) |
| 812 | self.assertEqual(newfd, minfd) |
| 813 | |
| 814 | def tearDown(self): |
| 815 | # cleanup |
| 816 | for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False): |
| 817 | for name in files: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 818 | os.unlink(name, dir_fd=rootfd) |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 819 | for name in dirs: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 820 | st = os.stat(name, dir_fd=rootfd, follow_symlinks=False) |
Larry Hastings | b698d8e | 2012-06-23 16:55:07 -0700 | [diff] [blame] | 821 | if stat.S_ISDIR(st.st_mode): |
| 822 | os.rmdir(name, dir_fd=rootfd) |
| 823 | else: |
| 824 | os.unlink(name, dir_fd=rootfd) |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 825 | os.rmdir(support.TESTFN) |
| 826 | |
| 827 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 828 | class MakedirTests(unittest.TestCase): |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 829 | def setUp(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 830 | os.mkdir(support.TESTFN) |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 831 | |
| 832 | def test_makedir(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 833 | base = support.TESTFN |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 834 | path = os.path.join(base, 'dir1', 'dir2', 'dir3') |
| 835 | os.makedirs(path) # Should work |
| 836 | path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4') |
| 837 | os.makedirs(path) |
| 838 | |
| 839 | # Try paths with a '.' in them |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 840 | self.assertRaises(OSError, os.makedirs, os.curdir) |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 841 | path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir) |
| 842 | os.makedirs(path) |
| 843 | path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4', |
| 844 | 'dir5', 'dir6') |
| 845 | os.makedirs(path) |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 846 | |
Terry Reedy | 5a22b65 | 2010-12-02 07:05:56 +0000 | [diff] [blame] | 847 | def test_exist_ok_existing_directory(self): |
| 848 | path = os.path.join(support.TESTFN, 'dir1') |
| 849 | mode = 0o777 |
| 850 | old_mask = os.umask(0o022) |
| 851 | os.makedirs(path, mode) |
| 852 | self.assertRaises(OSError, os.makedirs, path, mode) |
| 853 | self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False) |
| 854 | self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True) |
| 855 | os.makedirs(path, mode=mode, exist_ok=True) |
| 856 | os.umask(old_mask) |
| 857 | |
Gregory P. Smith | a81c856 | 2012-06-03 14:30:44 -0700 | [diff] [blame] | 858 | def test_exist_ok_s_isgid_directory(self): |
| 859 | path = os.path.join(support.TESTFN, 'dir1') |
| 860 | S_ISGID = stat.S_ISGID |
| 861 | mode = 0o777 |
| 862 | old_mask = os.umask(0o022) |
| 863 | try: |
| 864 | existing_testfn_mode = stat.S_IMODE( |
| 865 | os.lstat(support.TESTFN).st_mode) |
| 866 | os.chmod(support.TESTFN, existing_testfn_mode | S_ISGID) |
| 867 | if (os.lstat(support.TESTFN).st_mode & S_ISGID != S_ISGID): |
| 868 | raise unittest.SkipTest('No support for S_ISGID dir mode.') |
| 869 | # The os should apply S_ISGID from the parent dir for us, but |
| 870 | # this test need not depend on that behavior. Be explicit. |
| 871 | os.makedirs(path, mode | S_ISGID) |
| 872 | # http://bugs.python.org/issue14992 |
| 873 | # Should not fail when the bit is already set. |
| 874 | os.makedirs(path, mode, exist_ok=True) |
| 875 | # remove the bit. |
| 876 | os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID) |
| 877 | with self.assertRaises(OSError): |
| 878 | # Should fail when the bit is not already set when demanded. |
| 879 | os.makedirs(path, mode | S_ISGID, exist_ok=True) |
| 880 | finally: |
| 881 | os.umask(old_mask) |
Terry Reedy | 5a22b65 | 2010-12-02 07:05:56 +0000 | [diff] [blame] | 882 | |
| 883 | def test_exist_ok_existing_regular_file(self): |
| 884 | base = support.TESTFN |
| 885 | path = os.path.join(support.TESTFN, 'dir1') |
| 886 | f = open(path, 'w') |
| 887 | f.write('abc') |
| 888 | f.close() |
| 889 | self.assertRaises(OSError, os.makedirs, path) |
| 890 | self.assertRaises(OSError, os.makedirs, path, exist_ok=False) |
| 891 | self.assertRaises(OSError, os.makedirs, path, exist_ok=True) |
| 892 | os.remove(path) |
| 893 | |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 894 | def tearDown(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 895 | path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3', |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 896 | 'dir4', 'dir5', 'dir6') |
| 897 | # If the tests failed, the bottom-most directory ('../dir6') |
| 898 | # may not have been created, so we look for the outermost directory |
| 899 | # that exists. |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 900 | while not os.path.exists(path) and path != support.TESTFN: |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 901 | path = os.path.dirname(path) |
| 902 | |
| 903 | os.removedirs(path) |
| 904 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 905 | class DevNullTests(unittest.TestCase): |
Martin v. Löwis | bdec50f | 2004-06-08 08:29:33 +0000 | [diff] [blame] | 906 | def test_devnull(self): |
Victor Stinner | a6d2c76 | 2011-06-30 18:20:11 +0200 | [diff] [blame] | 907 | with open(os.devnull, 'wb') as f: |
| 908 | f.write(b'hello') |
| 909 | f.close() |
| 910 | with open(os.devnull, 'rb') as f: |
| 911 | self.assertEqual(f.read(), b'') |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 912 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 913 | class URandomTests(unittest.TestCase): |
Georg Brandl | 2daf6ae | 2012-02-20 19:54:16 +0100 | [diff] [blame] | 914 | def test_urandom_length(self): |
| 915 | self.assertEqual(len(os.urandom(0)), 0) |
| 916 | self.assertEqual(len(os.urandom(1)), 1) |
| 917 | self.assertEqual(len(os.urandom(10)), 10) |
| 918 | self.assertEqual(len(os.urandom(100)), 100) |
| 919 | self.assertEqual(len(os.urandom(1000)), 1000) |
| 920 | |
| 921 | def test_urandom_value(self): |
| 922 | data1 = os.urandom(16) |
| 923 | data2 = os.urandom(16) |
| 924 | self.assertNotEqual(data1, data2) |
| 925 | |
| 926 | def get_urandom_subprocess(self, count): |
| 927 | code = '\n'.join(( |
| 928 | 'import os, sys', |
| 929 | 'data = os.urandom(%s)' % count, |
| 930 | 'sys.stdout.buffer.write(data)', |
| 931 | 'sys.stdout.buffer.flush()')) |
| 932 | out = assert_python_ok('-c', code) |
| 933 | stdout = out[1] |
| 934 | self.assertEqual(len(stdout), 16) |
| 935 | return stdout |
| 936 | |
| 937 | def test_urandom_subprocess(self): |
| 938 | data1 = self.get_urandom_subprocess(16) |
| 939 | data2 = self.get_urandom_subprocess(16) |
| 940 | self.assertNotEqual(data1, data2) |
Martin v. Löwis | dc3883f | 2004-08-29 15:46:35 +0000 | [diff] [blame] | 941 | |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 942 | @contextlib.contextmanager |
| 943 | def _execvpe_mockup(defpath=None): |
| 944 | """ |
| 945 | Stubs out execv and execve functions when used as context manager. |
| 946 | Records exec calls. The mock execv and execve functions always raise an |
| 947 | exception as they would normally never return. |
| 948 | """ |
| 949 | # A list of tuples containing (function name, first arg, args) |
| 950 | # of calls to execv or execve that have been made. |
| 951 | calls = [] |
| 952 | |
| 953 | def mock_execv(name, *args): |
| 954 | calls.append(('execv', name, args)) |
| 955 | raise RuntimeError("execv called") |
| 956 | |
| 957 | def mock_execve(name, *args): |
| 958 | calls.append(('execve', name, args)) |
| 959 | raise OSError(errno.ENOTDIR, "execve called") |
| 960 | |
| 961 | try: |
| 962 | orig_execv = os.execv |
| 963 | orig_execve = os.execve |
| 964 | orig_defpath = os.defpath |
| 965 | os.execv = mock_execv |
| 966 | os.execve = mock_execve |
| 967 | if defpath is not None: |
| 968 | os.defpath = defpath |
| 969 | yield calls |
| 970 | finally: |
| 971 | os.execv = orig_execv |
| 972 | os.execve = orig_execve |
| 973 | os.defpath = orig_defpath |
| 974 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 975 | class ExecTests(unittest.TestCase): |
Mark Dickinson | 7cf0389 | 2010-04-16 13:45:35 +0000 | [diff] [blame] | 976 | @unittest.skipIf(USING_LINUXTHREADS, |
| 977 | "avoid triggering a linuxthreads bug: see issue #4970") |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 978 | def test_execvpe_with_bad_program(self): |
Mark Dickinson | 7cf0389 | 2010-04-16 13:45:35 +0000 | [diff] [blame] | 979 | self.assertRaises(OSError, os.execvpe, 'no such app-', |
| 980 | ['no such app-'], None) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 981 | |
Thomas Heller | 6790d60 | 2007-08-30 17:15:14 +0000 | [diff] [blame] | 982 | def test_execvpe_with_bad_arglist(self): |
| 983 | self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) |
| 984 | |
Gregory P. Smith | 4ae3777 | 2010-05-08 18:05:46 +0000 | [diff] [blame] | 985 | @unittest.skipUnless(hasattr(os, '_execvpe'), |
| 986 | "No internal os._execvpe function to test.") |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 987 | def _test_internal_execvpe(self, test_type): |
| 988 | program_path = os.sep + 'absolutepath' |
| 989 | if test_type is bytes: |
| 990 | program = b'executable' |
| 991 | fullpath = os.path.join(os.fsencode(program_path), program) |
| 992 | native_fullpath = fullpath |
| 993 | arguments = [b'progname', 'arg1', 'arg2'] |
| 994 | else: |
| 995 | program = 'executable' |
| 996 | arguments = ['progname', 'arg1', 'arg2'] |
| 997 | fullpath = os.path.join(program_path, program) |
| 998 | if os.name != "nt": |
| 999 | native_fullpath = os.fsencode(fullpath) |
| 1000 | else: |
| 1001 | native_fullpath = fullpath |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1002 | env = {'spam': 'beans'} |
| 1003 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1004 | # test os._execvpe() with an absolute path |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1005 | with _execvpe_mockup() as calls: |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1006 | self.assertRaises(RuntimeError, |
| 1007 | os._execvpe, fullpath, arguments) |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1008 | self.assertEqual(len(calls), 1) |
| 1009 | self.assertEqual(calls[0], ('execv', fullpath, (arguments,))) |
| 1010 | |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1011 | # test os._execvpe() with a relative path: |
| 1012 | # os.get_exec_path() returns defpath |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1013 | with _execvpe_mockup(defpath=program_path) as calls: |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1014 | self.assertRaises(OSError, |
| 1015 | os._execvpe, program, arguments, env=env) |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1016 | self.assertEqual(len(calls), 1) |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1017 | self.assertSequenceEqual(calls[0], |
| 1018 | ('execve', native_fullpath, (arguments, env))) |
| 1019 | |
| 1020 | # test os._execvpe() with a relative path: |
| 1021 | # os.get_exec_path() reads the 'PATH' variable |
| 1022 | with _execvpe_mockup() as calls: |
| 1023 | env_path = env.copy() |
Victor Stinner | 38430e2 | 2010-08-19 17:10:18 +0000 | [diff] [blame] | 1024 | if test_type is bytes: |
| 1025 | env_path[b'PATH'] = program_path |
| 1026 | else: |
| 1027 | env_path['PATH'] = program_path |
Victor Stinner | b745a74 | 2010-05-18 17:17:23 +0000 | [diff] [blame] | 1028 | self.assertRaises(OSError, |
| 1029 | os._execvpe, program, arguments, env=env_path) |
| 1030 | self.assertEqual(len(calls), 1) |
| 1031 | self.assertSequenceEqual(calls[0], |
| 1032 | ('execve', native_fullpath, (arguments, env_path))) |
| 1033 | |
| 1034 | def test_internal_execvpe_str(self): |
| 1035 | self._test_internal_execvpe(str) |
| 1036 | if os.name != "nt": |
| 1037 | self._test_internal_execvpe(bytes) |
Victor Stinner | c2d095f | 2010-05-17 00:14:53 +0000 | [diff] [blame] | 1038 | |
Gregory P. Smith | 4ae3777 | 2010-05-08 18:05:46 +0000 | [diff] [blame] | 1039 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1040 | class Win32ErrorTests(unittest.TestCase): |
| 1041 | def test_rename(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1042 | self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1043 | |
| 1044 | def test_remove(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1045 | self.assertRaises(WindowsError, os.remove, support.TESTFN) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1046 | |
| 1047 | def test_chdir(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1048 | self.assertRaises(WindowsError, os.chdir, support.TESTFN) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1049 | |
| 1050 | def test_mkdir(self): |
Amaury Forgeot d'Arc | 2fc224f | 2009-02-19 23:23:47 +0000 | [diff] [blame] | 1051 | f = open(support.TESTFN, "w") |
Benjamin Peterson | f91df04 | 2009-02-13 02:50:59 +0000 | [diff] [blame] | 1052 | try: |
| 1053 | self.assertRaises(WindowsError, os.mkdir, support.TESTFN) |
| 1054 | finally: |
| 1055 | f.close() |
Amaury Forgeot d'Arc | 2fc224f | 2009-02-19 23:23:47 +0000 | [diff] [blame] | 1056 | os.unlink(support.TESTFN) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1057 | |
| 1058 | def test_utime(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1059 | self.assertRaises(WindowsError, os.utime, support.TESTFN, None) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1060 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1061 | def test_chmod(self): |
Benjamin Peterson | f91df04 | 2009-02-13 02:50:59 +0000 | [diff] [blame] | 1062 | self.assertRaises(WindowsError, os.chmod, support.TESTFN, 0) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1063 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1064 | class TestInvalidFD(unittest.TestCase): |
Benjamin Peterson | 05e782f | 2009-01-19 15:15:02 +0000 | [diff] [blame] | 1065 | singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat", |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1066 | "fstatvfs", "fsync", "tcgetpgrp", "ttyname"] |
| 1067 | #singles.append("close") |
| 1068 | #We omit close because it doesn'r raise an exception on some platforms |
| 1069 | def get_single(f): |
| 1070 | def helper(self): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1071 | if hasattr(os, f): |
| 1072 | self.check(getattr(os, f)) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1073 | return helper |
| 1074 | for f in singles: |
| 1075 | locals()["test_"+f] = get_single(f) |
| 1076 | |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1077 | def check(self, f, *args): |
Benjamin Peterson | 5c6d787 | 2009-02-06 02:40:07 +0000 | [diff] [blame] | 1078 | try: |
| 1079 | f(support.make_bad_fd(), *args) |
| 1080 | except OSError as e: |
| 1081 | self.assertEqual(e.errno, errno.EBADF) |
| 1082 | else: |
| 1083 | self.fail("%r didn't raise a OSError with a bad file descriptor" |
| 1084 | % f) |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1085 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1086 | def test_isatty(self): |
| 1087 | if hasattr(os, "isatty"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1088 | self.assertEqual(os.isatty(support.make_bad_fd()), False) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1089 | |
| 1090 | def test_closerange(self): |
| 1091 | if hasattr(os, "closerange"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1092 | fd = support.make_bad_fd() |
R. David Murray | 630cc48 | 2009-07-22 15:20:27 +0000 | [diff] [blame] | 1093 | # Make sure none of the descriptors we are about to close are |
| 1094 | # currently valid (issue 6542). |
| 1095 | for i in range(10): |
| 1096 | try: os.fstat(fd+i) |
| 1097 | except OSError: |
| 1098 | pass |
| 1099 | else: |
| 1100 | break |
| 1101 | if i < 2: |
| 1102 | raise unittest.SkipTest( |
| 1103 | "Unable to acquire a range of invalid file descriptors") |
| 1104 | self.assertEqual(os.closerange(fd, fd + i-1), None) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1105 | |
| 1106 | def test_dup2(self): |
| 1107 | if hasattr(os, "dup2"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1108 | self.check(os.dup2, 20) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1109 | |
| 1110 | def test_fchmod(self): |
| 1111 | if hasattr(os, "fchmod"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1112 | self.check(os.fchmod, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1113 | |
| 1114 | def test_fchown(self): |
| 1115 | if hasattr(os, "fchown"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1116 | self.check(os.fchown, -1, -1) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1117 | |
| 1118 | def test_fpathconf(self): |
| 1119 | if hasattr(os, "fpathconf"): |
Georg Brandl | 306336b | 2012-06-24 12:55:33 +0200 | [diff] [blame] | 1120 | self.check(os.pathconf, "PC_NAME_MAX") |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1121 | self.check(os.fpathconf, "PC_NAME_MAX") |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1122 | |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1123 | def test_ftruncate(self): |
| 1124 | if hasattr(os, "ftruncate"): |
Georg Brandl | 306336b | 2012-06-24 12:55:33 +0200 | [diff] [blame] | 1125 | self.check(os.truncate, 0) |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1126 | self.check(os.ftruncate, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1127 | |
| 1128 | def test_lseek(self): |
| 1129 | if hasattr(os, "lseek"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1130 | self.check(os.lseek, 0, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1131 | |
| 1132 | def test_read(self): |
| 1133 | if hasattr(os, "read"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1134 | self.check(os.read, 1) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1135 | |
| 1136 | def test_tcsetpgrpt(self): |
| 1137 | if hasattr(os, "tcsetpgrp"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1138 | self.check(os.tcsetpgrp, 0) |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1139 | |
| 1140 | def test_write(self): |
| 1141 | if hasattr(os, "write"): |
Benjamin Peterson | 7522c74 | 2009-01-19 21:00:09 +0000 | [diff] [blame] | 1142 | self.check(os.write, b" ") |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 1143 | |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1144 | |
| 1145 | class LinkTests(unittest.TestCase): |
| 1146 | def setUp(self): |
| 1147 | self.file1 = support.TESTFN |
| 1148 | self.file2 = os.path.join(support.TESTFN + "2") |
| 1149 | |
Brian Curtin | c0abc4e | 2010-11-30 23:46:54 +0000 | [diff] [blame] | 1150 | def tearDown(self): |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1151 | for file in (self.file1, self.file2): |
| 1152 | if os.path.exists(file): |
| 1153 | os.unlink(file) |
| 1154 | |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1155 | def _test_link(self, file1, file2): |
| 1156 | with open(file1, "w") as f1: |
| 1157 | f1.write("test") |
| 1158 | |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 1159 | with warnings.catch_warnings(): |
| 1160 | warnings.simplefilter("ignore", DeprecationWarning) |
| 1161 | os.link(file1, file2) |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 1162 | with open(file1, "r") as f1, open(file2, "r") as f2: |
| 1163 | self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno())) |
| 1164 | |
| 1165 | def test_link(self): |
| 1166 | self._test_link(self.file1, self.file2) |
| 1167 | |
| 1168 | def test_link_bytes(self): |
| 1169 | self._test_link(bytes(self.file1, sys.getfilesystemencoding()), |
| 1170 | bytes(self.file2, sys.getfilesystemencoding())) |
| 1171 | |
Brian Curtin | f498b75 | 2010-11-30 15:54:04 +0000 | [diff] [blame] | 1172 | def test_unicode_name(self): |
Brian Curtin | 43f0c27 | 2010-11-30 15:40:04 +0000 | [diff] [blame] | 1173 | try: |
Brian Curtin | f498b75 | 2010-11-30 15:54:04 +0000 | [diff] [blame] | 1174 | os.fsencode("\xf1") |
Brian Curtin | 43f0c27 | 2010-11-30 15:40:04 +0000 | [diff] [blame] | 1175 | except UnicodeError: |
| 1176 | raise unittest.SkipTest("Unable to encode for this platform.") |
| 1177 | |
Brian Curtin | f498b75 | 2010-11-30 15:54:04 +0000 | [diff] [blame] | 1178 | self.file1 += "\xf1" |
Brian Curtin | fc889c4 | 2010-11-28 23:59:46 +0000 | [diff] [blame] | 1179 | self.file2 = self.file1 + "2" |
| 1180 | self._test_link(self.file1, self.file2) |
| 1181 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1182 | if sys.platform != 'win32': |
| 1183 | class Win32ErrorTests(unittest.TestCase): |
| 1184 | pass |
| 1185 | |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1186 | class PosixUidGidTests(unittest.TestCase): |
| 1187 | if hasattr(os, 'setuid'): |
| 1188 | def test_setuid(self): |
| 1189 | if os.getuid() != 0: |
| 1190 | self.assertRaises(os.error, os.setuid, 0) |
| 1191 | self.assertRaises(OverflowError, os.setuid, 1<<32) |
| 1192 | |
| 1193 | if hasattr(os, 'setgid'): |
| 1194 | def test_setgid(self): |
| 1195 | if os.getuid() != 0: |
| 1196 | self.assertRaises(os.error, os.setgid, 0) |
| 1197 | self.assertRaises(OverflowError, os.setgid, 1<<32) |
| 1198 | |
| 1199 | if hasattr(os, 'seteuid'): |
| 1200 | def test_seteuid(self): |
| 1201 | if os.getuid() != 0: |
| 1202 | self.assertRaises(os.error, os.seteuid, 0) |
| 1203 | self.assertRaises(OverflowError, os.seteuid, 1<<32) |
| 1204 | |
| 1205 | if hasattr(os, 'setegid'): |
| 1206 | def test_setegid(self): |
| 1207 | if os.getuid() != 0: |
| 1208 | self.assertRaises(os.error, os.setegid, 0) |
| 1209 | self.assertRaises(OverflowError, os.setegid, 1<<32) |
| 1210 | |
| 1211 | if hasattr(os, 'setreuid'): |
| 1212 | def test_setreuid(self): |
| 1213 | if os.getuid() != 0: |
| 1214 | self.assertRaises(os.error, os.setreuid, 0, 0) |
| 1215 | self.assertRaises(OverflowError, os.setreuid, 1<<32, 0) |
| 1216 | self.assertRaises(OverflowError, os.setreuid, 0, 1<<32) |
Benjamin Peterson | ebe87ba | 2010-03-06 20:34:24 +0000 | [diff] [blame] | 1217 | |
| 1218 | def test_setreuid_neg1(self): |
| 1219 | # Needs to accept -1. We run this in a subprocess to avoid |
| 1220 | # altering the test runner's process state (issue8045). |
Benjamin Peterson | ebe87ba | 2010-03-06 20:34:24 +0000 | [diff] [blame] | 1221 | subprocess.check_call([ |
| 1222 | sys.executable, '-c', |
| 1223 | 'import os,sys;os.setreuid(-1,-1);sys.exit(0)']) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1224 | |
| 1225 | if hasattr(os, 'setregid'): |
| 1226 | def test_setregid(self): |
| 1227 | if os.getuid() != 0: |
| 1228 | self.assertRaises(os.error, os.setregid, 0, 0) |
| 1229 | self.assertRaises(OverflowError, os.setregid, 1<<32, 0) |
| 1230 | self.assertRaises(OverflowError, os.setregid, 0, 1<<32) |
Benjamin Peterson | ebe87ba | 2010-03-06 20:34:24 +0000 | [diff] [blame] | 1231 | |
| 1232 | def test_setregid_neg1(self): |
| 1233 | # Needs to accept -1. We run this in a subprocess to avoid |
| 1234 | # altering the test runner's process state (issue8045). |
Benjamin Peterson | ebe87ba | 2010-03-06 20:34:24 +0000 | [diff] [blame] | 1235 | subprocess.check_call([ |
| 1236 | sys.executable, '-c', |
| 1237 | 'import os,sys;os.setregid(-1,-1);sys.exit(0)']) |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1238 | |
| 1239 | class Pep383Tests(unittest.TestCase): |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1240 | def setUp(self): |
Victor Stinner | d91df1a | 2010-08-18 10:56:19 +0000 | [diff] [blame] | 1241 | if support.TESTFN_UNENCODABLE: |
| 1242 | self.dir = support.TESTFN_UNENCODABLE |
| 1243 | else: |
| 1244 | self.dir = support.TESTFN |
| 1245 | self.bdir = os.fsencode(self.dir) |
| 1246 | |
| 1247 | bytesfn = [] |
| 1248 | def add_filename(fn): |
| 1249 | try: |
| 1250 | fn = os.fsencode(fn) |
| 1251 | except UnicodeEncodeError: |
| 1252 | return |
| 1253 | bytesfn.append(fn) |
| 1254 | add_filename(support.TESTFN_UNICODE) |
| 1255 | if support.TESTFN_UNENCODABLE: |
| 1256 | add_filename(support.TESTFN_UNENCODABLE) |
| 1257 | if not bytesfn: |
| 1258 | self.skipTest("couldn't create any non-ascii filename") |
| 1259 | |
| 1260 | self.unicodefn = set() |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1261 | os.mkdir(self.dir) |
Victor Stinner | d91df1a | 2010-08-18 10:56:19 +0000 | [diff] [blame] | 1262 | try: |
| 1263 | for fn in bytesfn: |
Victor Stinner | bf81622 | 2011-06-30 23:25:47 +0200 | [diff] [blame] | 1264 | support.create_empty_file(os.path.join(self.bdir, fn)) |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 1265 | fn = os.fsdecode(fn) |
Victor Stinner | d91df1a | 2010-08-18 10:56:19 +0000 | [diff] [blame] | 1266 | if fn in self.unicodefn: |
| 1267 | raise ValueError("duplicate filename") |
| 1268 | self.unicodefn.add(fn) |
| 1269 | except: |
| 1270 | shutil.rmtree(self.dir) |
| 1271 | raise |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1272 | |
| 1273 | def tearDown(self): |
| 1274 | shutil.rmtree(self.dir) |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1275 | |
| 1276 | def test_listdir(self): |
Victor Stinner | d91df1a | 2010-08-18 10:56:19 +0000 | [diff] [blame] | 1277 | expected = self.unicodefn |
| 1278 | found = set(os.listdir(self.dir)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1279 | self.assertEqual(found, expected) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1280 | # test listdir without arguments |
| 1281 | current_directory = os.getcwd() |
| 1282 | try: |
| 1283 | os.chdir(os.sep) |
| 1284 | self.assertEqual(set(os.listdir()), set(os.listdir(os.sep))) |
| 1285 | finally: |
| 1286 | os.chdir(current_directory) |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1287 | |
| 1288 | def test_open(self): |
| 1289 | for fn in self.unicodefn: |
Victor Stinner | a6d2c76 | 2011-06-30 18:20:11 +0200 | [diff] [blame] | 1290 | f = open(os.path.join(self.dir, fn), 'rb') |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1291 | f.close() |
| 1292 | |
| 1293 | def test_stat(self): |
| 1294 | for fn in self.unicodefn: |
| 1295 | os.stat(os.path.join(self.dir, fn)) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1296 | else: |
| 1297 | class PosixUidGidTests(unittest.TestCase): |
| 1298 | pass |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 1299 | class Pep383Tests(unittest.TestCase): |
| 1300 | pass |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 1301 | |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1302 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
| 1303 | class Win32KillTests(unittest.TestCase): |
Brian Curtin | c3acbc3 | 2010-05-28 16:08:40 +0000 | [diff] [blame] | 1304 | def _kill(self, sig): |
| 1305 | # Start sys.executable as a subprocess and communicate from the |
| 1306 | # subprocess to the parent that the interpreter is ready. When it |
| 1307 | # becomes ready, send *sig* via os.kill to the subprocess and check |
| 1308 | # that the return code is equal to *sig*. |
| 1309 | import ctypes |
| 1310 | from ctypes import wintypes |
| 1311 | import msvcrt |
| 1312 | |
| 1313 | # Since we can't access the contents of the process' stdout until the |
| 1314 | # process has exited, use PeekNamedPipe to see what's inside stdout |
| 1315 | # without waiting. This is done so we can tell that the interpreter |
| 1316 | # is started and running at a point where it could handle a signal. |
| 1317 | PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe |
| 1318 | PeekNamedPipe.restype = wintypes.BOOL |
| 1319 | PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle |
| 1320 | ctypes.POINTER(ctypes.c_char), # stdout buf |
| 1321 | wintypes.DWORD, # Buffer size |
| 1322 | ctypes.POINTER(wintypes.DWORD), # bytes read |
| 1323 | ctypes.POINTER(wintypes.DWORD), # bytes avail |
| 1324 | ctypes.POINTER(wintypes.DWORD)) # bytes left |
| 1325 | msg = "running" |
| 1326 | proc = subprocess.Popen([sys.executable, "-c", |
| 1327 | "import sys;" |
| 1328 | "sys.stdout.write('{}');" |
| 1329 | "sys.stdout.flush();" |
| 1330 | "input()".format(msg)], |
| 1331 | stdout=subprocess.PIPE, |
| 1332 | stderr=subprocess.PIPE, |
| 1333 | stdin=subprocess.PIPE) |
Brian Curtin | 43ec577 | 2010-11-05 15:17:11 +0000 | [diff] [blame] | 1334 | self.addCleanup(proc.stdout.close) |
| 1335 | self.addCleanup(proc.stderr.close) |
| 1336 | self.addCleanup(proc.stdin.close) |
Brian Curtin | c3acbc3 | 2010-05-28 16:08:40 +0000 | [diff] [blame] | 1337 | |
| 1338 | count, max = 0, 100 |
| 1339 | while count < max and proc.poll() is None: |
| 1340 | # Create a string buffer to store the result of stdout from the pipe |
| 1341 | buf = ctypes.create_string_buffer(len(msg)) |
| 1342 | # Obtain the text currently in proc.stdout |
| 1343 | # Bytes read/avail/left are left as NULL and unused |
| 1344 | rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), |
| 1345 | buf, ctypes.sizeof(buf), None, None, None) |
| 1346 | self.assertNotEqual(rslt, 0, "PeekNamedPipe failed") |
| 1347 | if buf.value: |
| 1348 | self.assertEqual(msg, buf.value.decode()) |
| 1349 | break |
| 1350 | time.sleep(0.1) |
| 1351 | count += 1 |
| 1352 | else: |
| 1353 | self.fail("Did not receive communication from the subprocess") |
| 1354 | |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1355 | os.kill(proc.pid, sig) |
| 1356 | self.assertEqual(proc.wait(), sig) |
| 1357 | |
| 1358 | def test_kill_sigterm(self): |
| 1359 | # SIGTERM doesn't mean anything special, but make sure it works |
Brian Curtin | c3acbc3 | 2010-05-28 16:08:40 +0000 | [diff] [blame] | 1360 | self._kill(signal.SIGTERM) |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1361 | |
| 1362 | def test_kill_int(self): |
| 1363 | # 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] | 1364 | self._kill(100) |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1365 | |
| 1366 | def _kill_with_event(self, event, name): |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1367 | tagname = "test_os_%s" % uuid.uuid1() |
| 1368 | m = mmap.mmap(-1, 1, tagname) |
| 1369 | m[0] = 0 |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1370 | # Run a script which has console control handling enabled. |
| 1371 | proc = subprocess.Popen([sys.executable, |
| 1372 | os.path.join(os.path.dirname(__file__), |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1373 | "win_console_handler.py"), tagname], |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1374 | creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) |
| 1375 | # Let the interpreter startup before we send signals. See #3137. |
Hirokazu Yamamoto | 8e9fe9f | 2010-12-05 02:41:46 +0000 | [diff] [blame] | 1376 | count, max = 0, 100 |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1377 | while count < max and proc.poll() is None: |
Brian Curtin | f668df5 | 2010-10-15 14:21:06 +0000 | [diff] [blame] | 1378 | if m[0] == 1: |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1379 | break |
Hirokazu Yamamoto | 8e9fe9f | 2010-12-05 02:41:46 +0000 | [diff] [blame] | 1380 | time.sleep(0.1) |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1381 | count += 1 |
| 1382 | else: |
Hirokazu Yamamoto | 8e9fe9f | 2010-12-05 02:41:46 +0000 | [diff] [blame] | 1383 | # Forcefully kill the process if we weren't able to signal it. |
| 1384 | os.kill(proc.pid, signal.SIGINT) |
Hirokazu Yamamoto | 54c950f | 2010-10-08 08:38:15 +0000 | [diff] [blame] | 1385 | self.fail("Subprocess didn't finish initialization") |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 1386 | os.kill(proc.pid, event) |
| 1387 | # proc.send_signal(event) could also be done here. |
| 1388 | # Allow time for the signal to be passed and the process to exit. |
| 1389 | time.sleep(0.5) |
| 1390 | if not proc.poll(): |
| 1391 | # Forcefully kill the process if we weren't able to signal it. |
| 1392 | os.kill(proc.pid, signal.SIGINT) |
| 1393 | self.fail("subprocess did not stop on {}".format(name)) |
| 1394 | |
| 1395 | @unittest.skip("subprocesses aren't inheriting CTRL+C property") |
| 1396 | def test_CTRL_C_EVENT(self): |
| 1397 | from ctypes import wintypes |
| 1398 | import ctypes |
| 1399 | |
| 1400 | # Make a NULL value by creating a pointer with no argument. |
| 1401 | NULL = ctypes.POINTER(ctypes.c_int)() |
| 1402 | SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler |
| 1403 | SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int), |
| 1404 | wintypes.BOOL) |
| 1405 | SetConsoleCtrlHandler.restype = wintypes.BOOL |
| 1406 | |
| 1407 | # Calling this with NULL and FALSE causes the calling process to |
| 1408 | # handle CTRL+C, rather than ignore it. This property is inherited |
| 1409 | # by subprocesses. |
| 1410 | SetConsoleCtrlHandler(NULL, 0) |
| 1411 | |
| 1412 | self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT") |
| 1413 | |
| 1414 | def test_CTRL_BREAK_EVENT(self): |
| 1415 | self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") |
| 1416 | |
| 1417 | |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 1418 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
Brian Curtin | 3b4499c | 2010-12-28 14:31:47 +0000 | [diff] [blame] | 1419 | @support.skip_unless_symlink |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 1420 | class Win32SymlinkTests(unittest.TestCase): |
| 1421 | filelink = 'filelinktest' |
| 1422 | filelink_target = os.path.abspath(__file__) |
| 1423 | dirlink = 'dirlinktest' |
| 1424 | dirlink_target = os.path.dirname(filelink_target) |
| 1425 | missing_link = 'missing link' |
| 1426 | |
| 1427 | def setUp(self): |
| 1428 | assert os.path.exists(self.dirlink_target) |
| 1429 | assert os.path.exists(self.filelink_target) |
| 1430 | assert not os.path.exists(self.dirlink) |
| 1431 | assert not os.path.exists(self.filelink) |
| 1432 | assert not os.path.exists(self.missing_link) |
| 1433 | |
| 1434 | def tearDown(self): |
| 1435 | if os.path.exists(self.filelink): |
| 1436 | os.remove(self.filelink) |
| 1437 | if os.path.exists(self.dirlink): |
| 1438 | os.rmdir(self.dirlink) |
| 1439 | if os.path.lexists(self.missing_link): |
| 1440 | os.remove(self.missing_link) |
| 1441 | |
| 1442 | def test_directory_link(self): |
Antoine Pitrou | 5311c1d | 2012-01-24 08:59:28 +0100 | [diff] [blame] | 1443 | os.symlink(self.dirlink_target, self.dirlink, True) |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 1444 | self.assertTrue(os.path.exists(self.dirlink)) |
| 1445 | self.assertTrue(os.path.isdir(self.dirlink)) |
| 1446 | self.assertTrue(os.path.islink(self.dirlink)) |
| 1447 | self.check_stat(self.dirlink, self.dirlink_target) |
| 1448 | |
| 1449 | def test_file_link(self): |
| 1450 | os.symlink(self.filelink_target, self.filelink) |
| 1451 | self.assertTrue(os.path.exists(self.filelink)) |
| 1452 | self.assertTrue(os.path.isfile(self.filelink)) |
| 1453 | self.assertTrue(os.path.islink(self.filelink)) |
| 1454 | self.check_stat(self.filelink, self.filelink_target) |
| 1455 | |
| 1456 | def _create_missing_dir_link(self): |
| 1457 | 'Create a "directory" link to a non-existent target' |
| 1458 | linkname = self.missing_link |
| 1459 | if os.path.lexists(linkname): |
| 1460 | os.remove(linkname) |
| 1461 | target = r'c:\\target does not exist.29r3c740' |
| 1462 | assert not os.path.exists(target) |
| 1463 | target_is_dir = True |
| 1464 | os.symlink(target, linkname, target_is_dir) |
| 1465 | |
| 1466 | def test_remove_directory_link_to_missing_target(self): |
| 1467 | self._create_missing_dir_link() |
| 1468 | # For compatibility with Unix, os.remove will check the |
| 1469 | # directory status and call RemoveDirectory if the symlink |
| 1470 | # was created with target_is_dir==True. |
| 1471 | os.remove(self.missing_link) |
| 1472 | |
| 1473 | @unittest.skip("currently fails; consider for improvement") |
| 1474 | def test_isdir_on_directory_link_to_missing_target(self): |
| 1475 | self._create_missing_dir_link() |
| 1476 | # consider having isdir return true for directory links |
| 1477 | self.assertTrue(os.path.isdir(self.missing_link)) |
| 1478 | |
| 1479 | @unittest.skip("currently fails; consider for improvement") |
| 1480 | def test_rmdir_on_directory_link_to_missing_target(self): |
| 1481 | self._create_missing_dir_link() |
| 1482 | # consider allowing rmdir to remove directory links |
| 1483 | os.rmdir(self.missing_link) |
| 1484 | |
| 1485 | def check_stat(self, link, target): |
| 1486 | self.assertEqual(os.stat(link), os.stat(target)) |
| 1487 | self.assertNotEqual(os.lstat(link), os.stat(link)) |
| 1488 | |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 1489 | bytes_link = os.fsencode(link) |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 1490 | with warnings.catch_warnings(): |
| 1491 | warnings.simplefilter("ignore", DeprecationWarning) |
| 1492 | self.assertEqual(os.stat(bytes_link), os.stat(target)) |
| 1493 | self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link)) |
Brian Curtin | d25aef5 | 2011-06-13 15:16:04 -0500 | [diff] [blame] | 1494 | |
| 1495 | def test_12084(self): |
| 1496 | level1 = os.path.abspath(support.TESTFN) |
| 1497 | level2 = os.path.join(level1, "level2") |
| 1498 | level3 = os.path.join(level2, "level3") |
| 1499 | try: |
| 1500 | os.mkdir(level1) |
| 1501 | os.mkdir(level2) |
| 1502 | os.mkdir(level3) |
| 1503 | |
| 1504 | file1 = os.path.abspath(os.path.join(level1, "file1")) |
| 1505 | |
| 1506 | with open(file1, "w") as f: |
| 1507 | f.write("file1") |
| 1508 | |
| 1509 | orig_dir = os.getcwd() |
| 1510 | try: |
| 1511 | os.chdir(level2) |
| 1512 | link = os.path.join(level2, "link") |
| 1513 | os.symlink(os.path.relpath(file1), "link") |
| 1514 | self.assertIn("link", os.listdir(os.getcwd())) |
| 1515 | |
| 1516 | # Check os.stat calls from the same dir as the link |
| 1517 | self.assertEqual(os.stat(file1), os.stat("link")) |
| 1518 | |
| 1519 | # Check os.stat calls from a dir below the link |
| 1520 | os.chdir(level1) |
| 1521 | self.assertEqual(os.stat(file1), |
| 1522 | os.stat(os.path.relpath(link))) |
| 1523 | |
| 1524 | # Check os.stat calls from a dir above the link |
| 1525 | os.chdir(level3) |
| 1526 | self.assertEqual(os.stat(file1), |
| 1527 | os.stat(os.path.relpath(link))) |
| 1528 | finally: |
| 1529 | os.chdir(orig_dir) |
| 1530 | except OSError as err: |
| 1531 | self.fail(err) |
| 1532 | finally: |
| 1533 | os.remove(file1) |
| 1534 | shutil.rmtree(level1) |
| 1535 | |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 1536 | |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 1537 | class FSEncodingTests(unittest.TestCase): |
| 1538 | def test_nop(self): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1539 | self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff') |
| 1540 | self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141') |
Benjamin Peterson | 31191a9 | 2010-05-09 03:22:58 +0000 | [diff] [blame] | 1541 | |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 1542 | def test_identity(self): |
| 1543 | # assert fsdecode(fsencode(x)) == x |
| 1544 | for fn in ('unicode\u0141', 'latin\xe9', 'ascii'): |
| 1545 | try: |
| 1546 | bytesfn = os.fsencode(fn) |
| 1547 | except UnicodeEncodeError: |
| 1548 | continue |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1549 | self.assertEqual(os.fsdecode(bytesfn), fn) |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 1550 | |
Victor Stinner | bf9bcab | 2010-05-09 03:15:33 +0000 | [diff] [blame] | 1551 | |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 1552 | |
| 1553 | class DeviceEncodingTests(unittest.TestCase): |
| 1554 | |
| 1555 | def test_bad_fd(self): |
| 1556 | # Return None when an fd doesn't actually exist. |
| 1557 | self.assertIsNone(os.device_encoding(123456)) |
| 1558 | |
Philip Jenvey | e308b7c | 2012-02-29 16:16:15 -0800 | [diff] [blame] | 1559 | @unittest.skipUnless(os.isatty(0) and (sys.platform.startswith('win') or |
| 1560 | (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))), |
Philip Jenvey | d7aff2d | 2012-02-29 16:21:25 -0800 | [diff] [blame] | 1561 | 'test requires a tty and either Windows or nl_langinfo(CODESET)') |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 1562 | def test_device_encoding(self): |
| 1563 | encoding = os.device_encoding(0) |
| 1564 | self.assertIsNotNone(encoding) |
| 1565 | self.assertTrue(codecs.lookup(encoding)) |
| 1566 | |
| 1567 | |
Amaury Forgeot d'Arc | 4b6fdf3 | 2010-09-07 21:31:17 +0000 | [diff] [blame] | 1568 | class PidTests(unittest.TestCase): |
| 1569 | @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid") |
| 1570 | def test_getppid(self): |
| 1571 | p = subprocess.Popen([sys.executable, '-c', |
| 1572 | 'import os; print(os.getppid())'], |
| 1573 | stdout=subprocess.PIPE) |
| 1574 | stdout, _ = p.communicate() |
| 1575 | # We are the parent of our subprocess |
| 1576 | self.assertEqual(int(stdout), os.getpid()) |
| 1577 | |
| 1578 | |
Brian Curtin | 0151b8e | 2010-09-24 13:43:43 +0000 | [diff] [blame] | 1579 | # The introduction of this TestCase caused at least two different errors on |
| 1580 | # *nix buildbots. Temporarily skip this to let the buildbots move along. |
| 1581 | @unittest.skip("Skip due to platform/environment differences on *NIX buildbots") |
Brian Curtin | e8e4b3b | 2010-09-23 20:04:14 +0000 | [diff] [blame] | 1582 | @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin") |
| 1583 | class LoginTests(unittest.TestCase): |
| 1584 | def test_getlogin(self): |
| 1585 | user_name = os.getlogin() |
| 1586 | self.assertNotEqual(len(user_name), 0) |
| 1587 | |
| 1588 | |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 1589 | @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'), |
| 1590 | "needs os.getpriority and os.setpriority") |
| 1591 | class ProgramPriorityTests(unittest.TestCase): |
| 1592 | """Tests for os.getpriority() and os.setpriority().""" |
| 1593 | |
| 1594 | def test_set_get_priority(self): |
Giampaolo Rodolà | cfbcec3 | 2011-02-28 19:27:16 +0000 | [diff] [blame] | 1595 | |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 1596 | base = os.getpriority(os.PRIO_PROCESS, os.getpid()) |
| 1597 | os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1) |
| 1598 | try: |
Giampaolo Rodolà | cfbcec3 | 2011-02-28 19:27:16 +0000 | [diff] [blame] | 1599 | new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid()) |
| 1600 | if base >= 19 and new_prio <= 19: |
| 1601 | raise unittest.SkipTest( |
| 1602 | "unable to reliably test setpriority at current nice level of %s" % base) |
| 1603 | else: |
| 1604 | self.assertEqual(new_prio, base + 1) |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 1605 | finally: |
| 1606 | try: |
| 1607 | os.setpriority(os.PRIO_PROCESS, os.getpid(), base) |
| 1608 | except OSError as err: |
Antoine Pitrou | 692f038 | 2011-02-26 00:22:25 +0000 | [diff] [blame] | 1609 | if err.errno != errno.EACCES: |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 1610 | raise |
| 1611 | |
| 1612 | |
Giampaolo Rodola' | 566f8a6 | 2011-05-18 21:28:39 +0200 | [diff] [blame] | 1613 | if threading is not None: |
| 1614 | class SendfileTestServer(asyncore.dispatcher, threading.Thread): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1615 | |
Giampaolo Rodola' | 566f8a6 | 2011-05-18 21:28:39 +0200 | [diff] [blame] | 1616 | class Handler(asynchat.async_chat): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1617 | |
Giampaolo Rodola' | 566f8a6 | 2011-05-18 21:28:39 +0200 | [diff] [blame] | 1618 | def __init__(self, conn): |
| 1619 | asynchat.async_chat.__init__(self, conn) |
| 1620 | self.in_buffer = [] |
| 1621 | self.closed = False |
| 1622 | self.push(b"220 ready\r\n") |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1623 | |
Giampaolo Rodola' | 566f8a6 | 2011-05-18 21:28:39 +0200 | [diff] [blame] | 1624 | def handle_read(self): |
| 1625 | data = self.recv(4096) |
| 1626 | self.in_buffer.append(data) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1627 | |
Giampaolo Rodola' | 566f8a6 | 2011-05-18 21:28:39 +0200 | [diff] [blame] | 1628 | def get_data(self): |
| 1629 | return b''.join(self.in_buffer) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1630 | |
Giampaolo Rodola' | 566f8a6 | 2011-05-18 21:28:39 +0200 | [diff] [blame] | 1631 | def handle_close(self): |
| 1632 | self.close() |
| 1633 | self.closed = True |
| 1634 | |
| 1635 | def handle_error(self): |
| 1636 | raise |
| 1637 | |
| 1638 | def __init__(self, address): |
| 1639 | threading.Thread.__init__(self) |
| 1640 | asyncore.dispatcher.__init__(self) |
| 1641 | self.create_socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1642 | self.bind(address) |
| 1643 | self.listen(5) |
| 1644 | self.host, self.port = self.socket.getsockname()[:2] |
| 1645 | self.handler_instance = None |
| 1646 | self._active = False |
| 1647 | self._active_lock = threading.Lock() |
| 1648 | |
| 1649 | # --- public API |
| 1650 | |
| 1651 | @property |
| 1652 | def running(self): |
| 1653 | return self._active |
| 1654 | |
| 1655 | def start(self): |
| 1656 | assert not self.running |
| 1657 | self.__flag = threading.Event() |
| 1658 | threading.Thread.start(self) |
| 1659 | self.__flag.wait() |
| 1660 | |
| 1661 | def stop(self): |
| 1662 | assert self.running |
| 1663 | self._active = False |
| 1664 | self.join() |
| 1665 | |
| 1666 | def wait(self): |
| 1667 | # wait for handler connection to be closed, then stop the server |
| 1668 | while not getattr(self.handler_instance, "closed", False): |
| 1669 | time.sleep(0.001) |
| 1670 | self.stop() |
| 1671 | |
| 1672 | # --- internals |
| 1673 | |
| 1674 | def run(self): |
| 1675 | self._active = True |
| 1676 | self.__flag.set() |
| 1677 | while self._active and asyncore.socket_map: |
| 1678 | self._active_lock.acquire() |
| 1679 | asyncore.loop(timeout=0.001, count=1) |
| 1680 | self._active_lock.release() |
| 1681 | asyncore.close_all() |
| 1682 | |
| 1683 | def handle_accept(self): |
| 1684 | conn, addr = self.accept() |
| 1685 | self.handler_instance = self.Handler(conn) |
| 1686 | |
| 1687 | def handle_connect(self): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1688 | self.close() |
Giampaolo Rodola' | 566f8a6 | 2011-05-18 21:28:39 +0200 | [diff] [blame] | 1689 | handle_read = handle_connect |
| 1690 | |
| 1691 | def writable(self): |
| 1692 | return 0 |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1693 | |
| 1694 | def handle_error(self): |
| 1695 | raise |
| 1696 | |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1697 | |
Giampaolo Rodolà | 4613464 | 2011-02-25 20:01:05 +0000 | [diff] [blame] | 1698 | @unittest.skipUnless(threading is not None, "test needs threading module") |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1699 | @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()") |
| 1700 | class TestSendfile(unittest.TestCase): |
| 1701 | |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1702 | DATA = b"12345abcde" * 16 * 1024 # 160 KB |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1703 | SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \ |
Giampaolo Rodolà | 4bc6857 | 2011-02-25 21:46:01 +0000 | [diff] [blame] | 1704 | not sys.platform.startswith("solaris") and \ |
| 1705 | not sys.platform.startswith("sunos") |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1706 | |
| 1707 | @classmethod |
| 1708 | def setUpClass(cls): |
| 1709 | with open(support.TESTFN, "wb") as f: |
| 1710 | f.write(cls.DATA) |
| 1711 | |
| 1712 | @classmethod |
| 1713 | def tearDownClass(cls): |
| 1714 | support.unlink(support.TESTFN) |
| 1715 | |
| 1716 | def setUp(self): |
| 1717 | self.server = SendfileTestServer((support.HOST, 0)) |
| 1718 | self.server.start() |
| 1719 | self.client = socket.socket() |
| 1720 | self.client.connect((self.server.host, self.server.port)) |
| 1721 | self.client.settimeout(1) |
| 1722 | # synchronize by waiting for "220 ready" response |
| 1723 | self.client.recv(1024) |
| 1724 | self.sockno = self.client.fileno() |
| 1725 | self.file = open(support.TESTFN, 'rb') |
| 1726 | self.fileno = self.file.fileno() |
| 1727 | |
| 1728 | def tearDown(self): |
| 1729 | self.file.close() |
| 1730 | self.client.close() |
| 1731 | if self.server.running: |
| 1732 | self.server.stop() |
| 1733 | |
| 1734 | def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]): |
| 1735 | """A higher level wrapper representing how an application is |
| 1736 | supposed to use sendfile(). |
| 1737 | """ |
| 1738 | while 1: |
| 1739 | try: |
| 1740 | if self.SUPPORT_HEADERS_TRAILERS: |
| 1741 | return os.sendfile(sock, file, offset, nbytes, headers, |
| 1742 | trailers) |
| 1743 | else: |
| 1744 | return os.sendfile(sock, file, offset, nbytes) |
| 1745 | except OSError as err: |
| 1746 | if err.errno == errno.ECONNRESET: |
| 1747 | # disconnected |
| 1748 | raise |
| 1749 | elif err.errno in (errno.EAGAIN, errno.EBUSY): |
| 1750 | # we have to retry send data |
| 1751 | continue |
| 1752 | else: |
| 1753 | raise |
| 1754 | |
| 1755 | def test_send_whole_file(self): |
| 1756 | # normal send |
| 1757 | total_sent = 0 |
| 1758 | offset = 0 |
| 1759 | nbytes = 4096 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1760 | while total_sent < len(self.DATA): |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1761 | sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes) |
| 1762 | if sent == 0: |
| 1763 | break |
| 1764 | offset += sent |
| 1765 | total_sent += sent |
| 1766 | self.assertTrue(sent <= nbytes) |
| 1767 | self.assertEqual(offset, total_sent) |
| 1768 | |
| 1769 | self.assertEqual(total_sent, len(self.DATA)) |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 1770 | self.client.shutdown(socket.SHUT_RDWR) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1771 | self.client.close() |
| 1772 | self.server.wait() |
| 1773 | data = self.server.handler_instance.get_data() |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 1774 | self.assertEqual(len(data), len(self.DATA)) |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1775 | self.assertEqual(data, self.DATA) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1776 | |
| 1777 | def test_send_at_certain_offset(self): |
| 1778 | # start sending a file at a certain offset |
| 1779 | total_sent = 0 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1780 | offset = len(self.DATA) // 2 |
| 1781 | must_send = len(self.DATA) - offset |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1782 | nbytes = 4096 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1783 | while total_sent < must_send: |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1784 | sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes) |
| 1785 | if sent == 0: |
| 1786 | break |
| 1787 | offset += sent |
| 1788 | total_sent += sent |
| 1789 | self.assertTrue(sent <= nbytes) |
| 1790 | |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 1791 | self.client.shutdown(socket.SHUT_RDWR) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1792 | self.client.close() |
| 1793 | self.server.wait() |
| 1794 | data = self.server.handler_instance.get_data() |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1795 | expected = self.DATA[len(self.DATA) // 2:] |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1796 | self.assertEqual(total_sent, len(expected)) |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 1797 | self.assertEqual(len(data), len(expected)) |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1798 | self.assertEqual(data, expected) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1799 | |
| 1800 | def test_offset_overflow(self): |
| 1801 | # specify an offset > file size |
| 1802 | offset = len(self.DATA) + 4096 |
Antoine Pitrou | 18dd0df | 2011-02-26 14:29:24 +0000 | [diff] [blame] | 1803 | try: |
| 1804 | sent = os.sendfile(self.sockno, self.fileno, offset, 4096) |
| 1805 | except OSError as e: |
| 1806 | # Solaris can raise EINVAL if offset >= file length, ignore. |
| 1807 | if e.errno != errno.EINVAL: |
| 1808 | raise |
| 1809 | else: |
| 1810 | self.assertEqual(sent, 0) |
Antoine Pitrou | 2de51ff | 2011-02-26 17:52:50 +0000 | [diff] [blame] | 1811 | self.client.shutdown(socket.SHUT_RDWR) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1812 | self.client.close() |
| 1813 | self.server.wait() |
| 1814 | data = self.server.handler_instance.get_data() |
| 1815 | self.assertEqual(data, b'') |
| 1816 | |
| 1817 | def test_invalid_offset(self): |
| 1818 | with self.assertRaises(OSError) as cm: |
| 1819 | os.sendfile(self.sockno, self.fileno, -1, 4096) |
| 1820 | self.assertEqual(cm.exception.errno, errno.EINVAL) |
| 1821 | |
| 1822 | # --- headers / trailers tests |
| 1823 | |
| 1824 | if SUPPORT_HEADERS_TRAILERS: |
| 1825 | |
| 1826 | def test_headers(self): |
| 1827 | total_sent = 0 |
| 1828 | sent = os.sendfile(self.sockno, self.fileno, 0, 4096, |
| 1829 | headers=[b"x" * 512]) |
| 1830 | total_sent += sent |
| 1831 | offset = 4096 |
| 1832 | nbytes = 4096 |
| 1833 | while 1: |
| 1834 | sent = self.sendfile_wrapper(self.sockno, self.fileno, |
| 1835 | offset, nbytes) |
| 1836 | if sent == 0: |
| 1837 | break |
| 1838 | total_sent += sent |
| 1839 | offset += sent |
| 1840 | |
| 1841 | expected_data = b"x" * 512 + self.DATA |
| 1842 | self.assertEqual(total_sent, len(expected_data)) |
| 1843 | self.client.close() |
| 1844 | self.server.wait() |
| 1845 | data = self.server.handler_instance.get_data() |
| 1846 | self.assertEqual(hash(data), hash(expected_data)) |
| 1847 | |
| 1848 | def test_trailers(self): |
| 1849 | TESTFN2 = support.TESTFN + "2" |
Brett Cannon | b637680 | 2011-03-15 17:38:22 -0400 | [diff] [blame] | 1850 | with open(TESTFN2, 'wb') as f: |
| 1851 | f.write(b"abcde") |
| 1852 | with open(TESTFN2, 'rb')as f: |
| 1853 | self.addCleanup(os.remove, TESTFN2) |
| 1854 | os.sendfile(self.sockno, f.fileno(), 0, 4096, |
| 1855 | trailers=[b"12345"]) |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1856 | self.client.close() |
| 1857 | self.server.wait() |
| 1858 | data = self.server.handler_instance.get_data() |
| 1859 | self.assertEqual(data, b"abcde12345") |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 1860 | |
| 1861 | if hasattr(os, "SF_NODISKIO"): |
| 1862 | def test_flags(self): |
| 1863 | try: |
| 1864 | os.sendfile(self.sockno, self.fileno, 0, 4096, |
| 1865 | flags=os.SF_NODISKIO) |
| 1866 | except OSError as err: |
| 1867 | if err.errno not in (errno.EBUSY, errno.EAGAIN): |
| 1868 | raise |
| 1869 | |
| 1870 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1871 | def supports_extended_attributes(): |
| 1872 | if not hasattr(os, "setxattr"): |
| 1873 | return False |
| 1874 | try: |
| 1875 | with open(support.TESTFN, "wb") as fp: |
| 1876 | try: |
| 1877 | os.setxattr(fp.fileno(), b"user.test", b"") |
| 1878 | except OSError: |
| 1879 | return False |
| 1880 | finally: |
| 1881 | support.unlink(support.TESTFN) |
| 1882 | # Kernels < 2.6.39 don't respect setxattr flags. |
| 1883 | kernel_version = platform.release() |
| 1884 | m = re.match("2.6.(\d{1,2})", kernel_version) |
| 1885 | return m is None or int(m.group(1)) >= 39 |
| 1886 | |
| 1887 | |
| 1888 | @unittest.skipUnless(supports_extended_attributes(), |
| 1889 | "no non-broken extended attribute support") |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1890 | class ExtendedAttributeTests(unittest.TestCase): |
| 1891 | |
| 1892 | def tearDown(self): |
| 1893 | support.unlink(support.TESTFN) |
| 1894 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1895 | def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs): |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1896 | fn = support.TESTFN |
| 1897 | open(fn, "wb").close() |
| 1898 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1899 | getxattr(fn, s("user.test"), **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1900 | self.assertEqual(cm.exception.errno, errno.ENODATA) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 1901 | init_xattr = listxattr(fn) |
| 1902 | self.assertIsInstance(init_xattr, list) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1903 | setxattr(fn, s("user.test"), b"", **kwargs) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 1904 | xattr = set(init_xattr) |
| 1905 | xattr.add("user.test") |
| 1906 | self.assertEqual(set(listxattr(fn)), xattr) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1907 | self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"") |
| 1908 | setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs) |
| 1909 | self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello") |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1910 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1911 | setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1912 | self.assertEqual(cm.exception.errno, errno.EEXIST) |
| 1913 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1914 | setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1915 | self.assertEqual(cm.exception.errno, errno.ENODATA) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1916 | setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 1917 | xattr.add("user.test2") |
| 1918 | self.assertEqual(set(listxattr(fn)), xattr) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1919 | removexattr(fn, s("user.test"), **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1920 | with self.assertRaises(OSError) as cm: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1921 | getxattr(fn, s("user.test"), **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1922 | self.assertEqual(cm.exception.errno, errno.ENODATA) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 1923 | xattr.remove("user.test") |
| 1924 | self.assertEqual(set(listxattr(fn)), xattr) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1925 | self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo") |
| 1926 | setxattr(fn, s("user.test"), b"a"*1024, **kwargs) |
| 1927 | self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024) |
| 1928 | removexattr(fn, s("user.test"), **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1929 | many = sorted("user.test{}".format(i) for i in range(100)) |
| 1930 | for thing in many: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1931 | setxattr(fn, thing, b"x", **kwargs) |
Victor Stinner | f12e506 | 2011-10-16 22:12:03 +0200 | [diff] [blame] | 1932 | self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many)) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1933 | |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1934 | def _check_xattrs(self, *args, **kwargs): |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1935 | def make_bytes(s): |
| 1936 | return bytes(s, "ascii") |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1937 | self._check_xattrs_str(str, *args, **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1938 | support.unlink(support.TESTFN) |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1939 | self._check_xattrs_str(make_bytes, *args, **kwargs) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1940 | |
| 1941 | def test_simple(self): |
| 1942 | self._check_xattrs(os.getxattr, os.setxattr, os.removexattr, |
| 1943 | os.listxattr) |
| 1944 | |
| 1945 | def test_lpath(self): |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1946 | self._check_xattrs(os.getxattr, os.setxattr, os.removexattr, |
| 1947 | os.listxattr, follow_symlinks=False) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1948 | |
| 1949 | def test_fds(self): |
| 1950 | def getxattr(path, *args): |
| 1951 | with open(path, "rb") as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1952 | return os.getxattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1953 | def setxattr(path, *args): |
| 1954 | with open(path, "wb") as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1955 | os.setxattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1956 | def removexattr(path, *args): |
| 1957 | with open(path, "wb") as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1958 | os.removexattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1959 | def listxattr(path, *args): |
| 1960 | with open(path, "rb") as fp: |
Larry Hastings | 9cf065c | 2012-06-22 16:30:09 -0700 | [diff] [blame] | 1961 | return os.listxattr(fp.fileno(), *args) |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 1962 | self._check_xattrs(getxattr, setxattr, removexattr, listxattr) |
| 1963 | |
| 1964 | |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 1965 | @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") |
| 1966 | class Win32DeprecatedBytesAPI(unittest.TestCase): |
| 1967 | def test_deprecated(self): |
| 1968 | import nt |
| 1969 | filename = os.fsencode(support.TESTFN) |
| 1970 | with warnings.catch_warnings(): |
| 1971 | warnings.simplefilter("error", DeprecationWarning) |
| 1972 | for func, *args in ( |
| 1973 | (nt._getfullpathname, filename), |
| 1974 | (nt._isdir, filename), |
| 1975 | (os.access, filename, os.R_OK), |
| 1976 | (os.chdir, filename), |
| 1977 | (os.chmod, filename, 0o777), |
Victor Stinner | f7c5ae2 | 2011-11-16 23:43:07 +0100 | [diff] [blame] | 1978 | (os.getcwdb,), |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 1979 | (os.link, filename, filename), |
| 1980 | (os.listdir, filename), |
| 1981 | (os.lstat, filename), |
| 1982 | (os.mkdir, filename), |
| 1983 | (os.open, filename, os.O_RDONLY), |
| 1984 | (os.rename, filename, filename), |
| 1985 | (os.rmdir, filename), |
| 1986 | (os.startfile, filename), |
| 1987 | (os.stat, filename), |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 1988 | (os.unlink, filename), |
| 1989 | (os.utime, filename), |
| 1990 | ): |
| 1991 | self.assertRaises(DeprecationWarning, func, *args) |
| 1992 | |
Victor Stinner | 2821644 | 2011-11-16 00:34:44 +0100 | [diff] [blame] | 1993 | @support.skip_unless_symlink |
| 1994 | def test_symlink(self): |
| 1995 | filename = os.fsencode(support.TESTFN) |
| 1996 | with warnings.catch_warnings(): |
| 1997 | warnings.simplefilter("error", DeprecationWarning) |
| 1998 | self.assertRaises(DeprecationWarning, |
| 1999 | os.symlink, filename, filename) |
| 2000 | |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 2001 | |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2002 | @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size") |
| 2003 | class TermsizeTests(unittest.TestCase): |
| 2004 | def test_does_not_crash(self): |
| 2005 | """Check if get_terminal_size() returns a meaningful value. |
| 2006 | |
| 2007 | There's no easy portable way to actually check the size of the |
| 2008 | terminal, so let's check if it returns something sensible instead. |
| 2009 | """ |
| 2010 | try: |
| 2011 | size = os.get_terminal_size() |
| 2012 | except OSError as e: |
Antoine Pitrou | 81a1fa5 | 2012-02-09 00:11:00 +0100 | [diff] [blame] | 2013 | if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2014 | # Under win32 a generic OSError can be thrown if the |
| 2015 | # handle cannot be retrieved |
| 2016 | self.skipTest("failed to query terminal size") |
| 2017 | raise |
| 2018 | |
Antoine Pitrou | cfade36 | 2012-02-08 23:48:59 +0100 | [diff] [blame] | 2019 | self.assertGreaterEqual(size.columns, 0) |
| 2020 | self.assertGreaterEqual(size.lines, 0) |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2021 | |
| 2022 | def test_stty_match(self): |
| 2023 | """Check if stty returns the same results |
| 2024 | |
| 2025 | stty actually tests stdin, so get_terminal_size is invoked on |
| 2026 | stdin explicitly. If stty succeeded, then get_terminal_size() |
| 2027 | should work too. |
| 2028 | """ |
| 2029 | try: |
| 2030 | size = subprocess.check_output(['stty', 'size']).decode().split() |
| 2031 | except (FileNotFoundError, subprocess.CalledProcessError): |
| 2032 | self.skipTest("stty invocation failed") |
| 2033 | expected = (int(size[1]), int(size[0])) # reversed order |
| 2034 | |
Antoine Pitrou | 81a1fa5 | 2012-02-09 00:11:00 +0100 | [diff] [blame] | 2035 | try: |
| 2036 | actual = os.get_terminal_size(sys.__stdin__.fileno()) |
| 2037 | except OSError as e: |
| 2038 | if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): |
| 2039 | # Under win32 a generic OSError can be thrown if the |
| 2040 | # handle cannot be retrieved |
| 2041 | self.skipTest("failed to query terminal size") |
| 2042 | raise |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2043 | self.assertEqual(expected, actual) |
| 2044 | |
| 2045 | |
Antoine Pitrou | f26ad71 | 2011-07-15 23:00:56 +0200 | [diff] [blame] | 2046 | @support.reap_threads |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 2047 | def test_main(): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 2048 | support.run_unittest( |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 2049 | FileTests, |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 2050 | StatAttributeTests, |
| 2051 | EnvironTests, |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 2052 | WalkTests, |
Charles-François Natali | 7372b06 | 2012-02-05 15:15:38 +0100 | [diff] [blame] | 2053 | FwalkTests, |
Andrew M. Kuchling | b386f6a | 2003-12-23 16:36:11 +0000 | [diff] [blame] | 2054 | MakedirTests, |
Martin v. Löwis | bdec50f | 2004-06-08 08:29:33 +0000 | [diff] [blame] | 2055 | DevNullTests, |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2056 | URandomTests, |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 2057 | ExecTests, |
Benjamin Peterson | e1cdfd7 | 2009-01-18 21:02:37 +0000 | [diff] [blame] | 2058 | Win32ErrorTests, |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 2059 | TestInvalidFD, |
Martin v. Löwis | 011e842 | 2009-05-05 04:43:17 +0000 | [diff] [blame] | 2060 | PosixUidGidTests, |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 2061 | Pep383Tests, |
Victor Stinner | bf9bcab | 2010-05-09 03:15:33 +0000 | [diff] [blame] | 2062 | Win32KillTests, |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 2063 | Win32SymlinkTests, |
Victor Stinner | e8d5145 | 2010-08-19 01:05:19 +0000 | [diff] [blame] | 2064 | FSEncodingTests, |
Brett Cannon | efb00c0 | 2012-02-29 18:31:31 -0500 | [diff] [blame] | 2065 | DeviceEncodingTests, |
Amaury Forgeot d'Arc | 4b6fdf3 | 2010-09-07 21:31:17 +0000 | [diff] [blame] | 2066 | PidTests, |
Brian Curtin | e8e4b3b | 2010-09-23 20:04:14 +0000 | [diff] [blame] | 2067 | LoginTests, |
Brian Curtin | 1b9df39 | 2010-11-24 20:24:31 +0000 | [diff] [blame] | 2068 | LinkTests, |
Giampaolo Rodolà | c9c2c8b | 2011-02-25 14:39:16 +0000 | [diff] [blame] | 2069 | TestSendfile, |
Giampaolo Rodolà | 18e8bcb | 2011-02-25 20:57:54 +0000 | [diff] [blame] | 2070 | ProgramPriorityTests, |
Benjamin Peterson | 799bd80 | 2011-08-31 22:15:17 -0400 | [diff] [blame] | 2071 | ExtendedAttributeTests, |
Victor Stinner | 1ab6c2d | 2011-11-15 22:27:41 +0100 | [diff] [blame] | 2072 | Win32DeprecatedBytesAPI, |
Antoine Pitrou | bcf2b59 | 2012-02-08 23:28:36 +0100 | [diff] [blame] | 2073 | TermsizeTests, |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 2074 | ) |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 2075 | |
| 2076 | if __name__ == "__main__": |
| 2077 | test_main() |