blob: 49f554c6056fabc22eb4b0d941a4157bb2db17f2 [file] [log] [blame]
Fred Drake38c2ef02001-07-17 20:52:51 +00001# 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örwaldf0dfc7a2003-10-20 14:01:56 +00003# portable than they had been thought to be.
Fred Drake38c2ef02001-07-17 20:52:51 +00004
5import os
Benjamin Peterson1de05e92009-01-31 01:42:55 +00006import errno
Fred Drake38c2ef02001-07-17 20:52:51 +00007import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00008import warnings
Martin v. Löwis8e0d4942006-05-04 10:08:42 +00009import sys
Brian Curtine5aa8862010-04-02 23:26:06 +000010import signal
11import subprocess
12import time
Walter Dörwald21d3a322003-05-01 17:45:56 +000013from test import test_support
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +000014import mmap
15import uuid
Fred Drake38c2ef02001-07-17 20:52:51 +000016
Barry Warsaw60f01882001-08-22 19:24:42 +000017warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
18warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
19
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000020# Tests creating TESTFN
21class FileTests(unittest.TestCase):
22 def setUp(self):
23 if os.path.exists(test_support.TESTFN):
24 os.unlink(test_support.TESTFN)
25 tearDown = setUp
26
27 def test_access(self):
28 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
29 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000030 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000031
Georg Brandl309501a2008-01-19 20:22:13 +000032 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000033 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
34 # We must allocate two consecutive file descriptors, otherwise
35 # it will mess up other file descriptors (perhaps even the three
36 # standard ones).
37 second = os.dup(first)
38 try:
39 retries = 0
40 while second != first + 1:
41 os.close(first)
42 retries += 1
43 if retries > 10:
44 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000045 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000046 first, second = second, os.dup(second)
47 finally:
48 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000049 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000050 os.closerange(first, first + 2)
51 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000052
Benjamin Peterson10947a62010-06-30 17:11:08 +000053 @test_support.cpython_only
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000054 def test_rename(self):
55 path = unicode(test_support.TESTFN)
56 old = sys.getrefcount(path)
57 self.assertRaises(TypeError, os.rename, path, 0)
58 new = sys.getrefcount(path)
59 self.assertEqual(old, new)
60
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000061
Fred Drake38c2ef02001-07-17 20:52:51 +000062class TemporaryFileTests(unittest.TestCase):
63 def setUp(self):
64 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000065 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000066
67 def tearDown(self):
68 for name in self.files:
69 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000070 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000071
72 def check_tempfile(self, name):
73 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000074 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000075 "file already exists for temporary file")
76 # make sure we can create the file
77 open(name, "w")
78 self.files.append(name)
79
80 def test_tempnam(self):
81 if not hasattr(os, "tempnam"):
82 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000083 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000084 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000085 self.check_tempfile(os.tempnam())
86
Walter Dörwald21d3a322003-05-01 17:45:56 +000087 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000088 self.check_tempfile(name)
89
Walter Dörwald21d3a322003-05-01 17:45:56 +000090 name = os.tempnam(test_support.TESTFN, "pfx")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000091 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000092 self.check_tempfile(name)
93
94 def test_tmpfile(self):
95 if not hasattr(os, "tmpfile"):
96 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000097 # As with test_tmpnam() below, the Windows implementation of tmpfile()
98 # attempts to create a file in the root directory of the current drive.
99 # On Vista and Server 2008, this test will always fail for normal users
100 # as writing to the root directory requires elevated privileges. With
101 # XP and below, the semantics of tmpfile() are the same, but the user
102 # running the test is more likely to have administrative privileges on
103 # their account already. If that's the case, then os.tmpfile() should
104 # work. In order to make this test as useful as possible, rather than
105 # trying to detect Windows versions or whether or not the user has the
106 # right permissions, just try and create a file in the root directory
107 # and see if it raises a 'Permission denied' OSError. If it does, then
108 # test that a subsequent call to os.tmpfile() raises the same error. If
109 # it doesn't, assume we're on XP or below and the user running the test
110 # has administrative privileges, and proceed with the test as normal.
111 if sys.platform == 'win32':
112 name = '\\python_test_os_test_tmpfile.txt'
113 if os.path.exists(name):
114 os.remove(name)
115 try:
116 fp = open(name, 'w')
117 except IOError, first:
118 # open() failed, assert tmpfile() fails in the same way.
119 # Although open() raises an IOError and os.tmpfile() raises an
120 # OSError(), 'args' will be (13, 'Permission denied') in both
121 # cases.
122 try:
123 fp = os.tmpfile()
124 except OSError, second:
125 self.assertEqual(first.args, second.args)
126 else:
127 self.fail("expected os.tmpfile() to raise OSError")
128 return
129 else:
130 # open() worked, therefore, tmpfile() should work. Close our
131 # dummy file and proceed with the test as normal.
132 fp.close()
133 os.remove(name)
134
Fred Drake38c2ef02001-07-17 20:52:51 +0000135 fp = os.tmpfile()
136 fp.write("foobar")
137 fp.seek(0,0)
138 s = fp.read()
139 fp.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000140 self.assertTrue(s == "foobar")
Fred Drake38c2ef02001-07-17 20:52:51 +0000141
142 def test_tmpnam(self):
143 if not hasattr(os, "tmpnam"):
144 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000145 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000146 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000147 name = os.tmpnam()
148 if sys.platform in ("win32",):
149 # The Windows tmpnam() seems useless. From the MS docs:
150 #
151 # The character string that tmpnam creates consists of
152 # the path prefix, defined by the entry P_tmpdir in the
153 # file STDIO.H, followed by a sequence consisting of the
154 # digit characters '0' through '9'; the numerical value
155 # of this string is in the range 1 - 65,535. Changing the
156 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
157 # change the operation of tmpnam.
158 #
159 # The really bizarre part is that, at least under MSVC6,
160 # P_tmpdir is "\\". That is, the path returned refers to
161 # the root of the current drive. That's a terrible place to
162 # put temp files, and, depending on privileges, the user
163 # may not even be able to open a file in the root directory.
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000164 self.assertFalse(os.path.exists(name),
Tim Peters5501b5e2003-04-28 03:13:03 +0000165 "file already exists for temporary file")
166 else:
167 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000168
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000169# Test attributes on return values from os.*stat* family.
170class StatAttributeTests(unittest.TestCase):
171 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000172 os.mkdir(test_support.TESTFN)
173 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000174 f = open(self.fname, 'wb')
175 f.write("ABC")
176 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000177
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000178 def tearDown(self):
179 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000180 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000181
182 def test_stat_attributes(self):
183 if not hasattr(os, "stat"):
184 return
185
186 import stat
187 result = os.stat(self.fname)
188
189 # Make sure direct access works
190 self.assertEquals(result[stat.ST_SIZE], 3)
191 self.assertEquals(result.st_size, 3)
192
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000193 # Make sure all the attributes are there
194 members = dir(result)
195 for name in dir(stat):
196 if name[:3] == 'ST_':
197 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000198 if name.endswith("TIME"):
199 def trunc(x): return int(x)
200 else:
201 def trunc(x): return x
202 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000203 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000204 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000205
206 try:
207 result[200]
208 self.fail("No exception thrown")
209 except IndexError:
210 pass
211
212 # Make sure that assignment fails
213 try:
214 result.st_mode = 1
215 self.fail("No exception thrown")
Benjamin Petersonc262a692010-06-30 18:41:08 +0000216 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000217 pass
218
219 try:
220 result.st_rdev = 1
221 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000222 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000223 pass
224
225 try:
226 result.parrot = 1
227 self.fail("No exception thrown")
228 except AttributeError:
229 pass
230
231 # Use the stat_result constructor with a too-short tuple.
232 try:
233 result2 = os.stat_result((10,))
234 self.fail("No exception thrown")
235 except TypeError:
236 pass
237
238 # Use the constructr with a too-long tuple.
239 try:
240 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
241 except TypeError:
242 pass
243
Tim Peterse0c446b2001-10-18 21:57:37 +0000244
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000245 def test_statvfs_attributes(self):
246 if not hasattr(os, "statvfs"):
247 return
248
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000249 try:
250 result = os.statvfs(self.fname)
251 except OSError, e:
252 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000253 if e.errno == errno.ENOSYS:
254 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000255
256 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000257 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000258
Brett Cannon90f2cb42008-05-16 00:37:42 +0000259 # Make sure all the attributes are there.
260 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
261 'ffree', 'favail', 'flag', 'namemax')
262 for value, member in enumerate(members):
263 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000264
265 # Make sure that assignment really fails
266 try:
267 result.f_bfree = 1
268 self.fail("No exception thrown")
269 except TypeError:
270 pass
271
272 try:
273 result.parrot = 1
274 self.fail("No exception thrown")
275 except AttributeError:
276 pass
277
278 # Use the constructor with a too-short tuple.
279 try:
280 result2 = os.statvfs_result((10,))
281 self.fail("No exception thrown")
282 except TypeError:
283 pass
284
285 # Use the constructr with a too-long tuple.
286 try:
287 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
288 except TypeError:
289 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000290
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000291 def test_utime_dir(self):
292 delta = 1000000
293 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000294 # round to int, because some systems may support sub-second
295 # time stamps in stat, but not in utime.
296 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000297 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000298 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000299
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000300 # Restrict test to Win32, since there is no guarantee other
301 # systems support centiseconds
302 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000303 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000304 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000305 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000306 kernel32 = ctypes.windll.kernel32
307 buf = ctypes.create_string_buffer("", 100)
308 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000309 return buf.value
310
311 if get_file_system(test_support.TESTFN) == "NTFS":
312 def test_1565150(self):
313 t1 = 1159195039.25
314 os.utime(self.fname, (t1, t1))
315 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000316
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000317 def test_1686475(self):
318 # Verify that an open file can be stat'ed
319 try:
320 os.stat(r"c:\pagefile.sys")
321 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000322 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000323 return
324 self.fail("Could not stat pagefile.sys")
325
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000326from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000327
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000328class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000329 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000330 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000331 def _reference(self):
332 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
333 def _empty_mapping(self):
334 os.environ.clear()
335 return os.environ
336 def setUp(self):
337 self.__save = dict(os.environ)
338 os.environ.clear()
339 def tearDown(self):
340 os.environ.clear()
341 os.environ.update(self.__save)
342
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000343 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000344 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000345 if os.path.exists("/bin/sh"):
346 os.environ.update(HELLO="World")
Brian Curtinfcbf5d02010-10-30 21:29:52 +0000347 with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
348 value = popen.read().strip()
349 self.assertEquals(value, "World")
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000350
Tim Petersc4e09402003-04-25 07:11:48 +0000351class WalkTests(unittest.TestCase):
352 """Tests for os.walk()."""
353
354 def test_traversal(self):
355 import os
356 from os.path import join
357
358 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000359 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000360 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000361 # tmp1
362 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000363 # tmp2
364 # SUB11/ no kids
365 # SUB2/ a file kid and a dirsymlink kid
366 # tmp3
367 # link/ a symlink to TESTFN.2
368 # TEST2/
369 # tmp4 a lone file
370 walk_path = join(test_support.TESTFN, "TEST1")
371 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000372 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000373 sub2_path = join(walk_path, "SUB2")
374 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000375 tmp2_path = join(sub1_path, "tmp2")
376 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000377 link_path = join(sub2_path, "link")
378 t2_path = join(test_support.TESTFN, "TEST2")
379 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000380
381 # Create stuff.
382 os.makedirs(sub11_path)
383 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000384 os.makedirs(t2_path)
385 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000386 f = file(path, "w")
387 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
388 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000389 if hasattr(os, "symlink"):
390 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000391 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000392 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000393 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000394
395 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000396 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000397 self.assertEqual(len(all), 4)
398 # We can't know which order SUB1 and SUB2 will appear in.
399 # Not flipped: TESTFN, SUB1, SUB11, SUB2
400 # flipped: TESTFN, SUB2, SUB1, SUB11
401 flipped = all[0][1][0] != "SUB1"
402 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000403 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000404 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
405 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000406 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000407
408 # Prune the search.
409 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000410 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000411 all.append((root, dirs, files))
412 # Don't descend into SUB1.
413 if 'SUB1' in dirs:
414 # Note that this also mutates the dirs we appended to all!
415 dirs.remove('SUB1')
416 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000417 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000418 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000419
420 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000421 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000422 self.assertEqual(len(all), 4)
423 # We can't know which order SUB1 and SUB2 will appear in.
424 # Not flipped: SUB11, SUB1, SUB2, TESTFN
425 # flipped: SUB2, SUB11, SUB1, TESTFN
426 flipped = all[3][1][0] != "SUB1"
427 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000428 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000429 self.assertEqual(all[flipped], (sub11_path, [], []))
430 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000431 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000432
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000433 if hasattr(os, "symlink"):
434 # Walk, following symlinks.
435 for root, dirs, files in os.walk(walk_path, followlinks=True):
436 if root == link_path:
437 self.assertEqual(dirs, [])
438 self.assertEqual(files, ["tmp4"])
439 break
440 else:
441 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000442
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000443 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000444 # Tear everything down. This is a decent use for bottom-up on
445 # Windows, which doesn't have a recursive delete command. The
446 # (not so) subtlety is that rmdir will fail unless the dir's
447 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000448 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000449 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000450 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000451 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000452 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000453 if not os.path.islink(dirname):
454 os.rmdir(dirname)
455 else:
456 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000457 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000458
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000459class MakedirTests (unittest.TestCase):
460 def setUp(self):
461 os.mkdir(test_support.TESTFN)
462
463 def test_makedir(self):
464 base = test_support.TESTFN
465 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
466 os.makedirs(path) # Should work
467 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
468 os.makedirs(path)
469
470 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000471 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000472 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
473 os.makedirs(path)
474 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
475 'dir5', 'dir6')
476 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000477
Tim Peters58eb11c2004-01-18 20:29:55 +0000478
479
480
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000481 def tearDown(self):
482 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
483 'dir4', 'dir5', 'dir6')
484 # If the tests failed, the bottom-most directory ('../dir6')
485 # may not have been created, so we look for the outermost directory
486 # that exists.
487 while not os.path.exists(path) and path != test_support.TESTFN:
488 path = os.path.dirname(path)
489
490 os.removedirs(path)
491
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000492class DevNullTests (unittest.TestCase):
493 def test_devnull(self):
494 f = file(os.devnull, 'w')
495 f.write('hello')
496 f.close()
497 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000498 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000499 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000500
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000501class URandomTests (unittest.TestCase):
502 def test_urandom(self):
503 try:
504 self.assertEqual(len(os.urandom(1)), 1)
505 self.assertEqual(len(os.urandom(10)), 10)
506 self.assertEqual(len(os.urandom(100)), 100)
507 self.assertEqual(len(os.urandom(1000)), 1000)
Gregory P. Smithd7122032008-09-02 05:36:11 +0000508 # see http://bugs.python.org/issue3708
Mark Dickinson1b34d252010-01-01 17:27:30 +0000509 self.assertRaises(TypeError, os.urandom, 0.9)
510 self.assertRaises(TypeError, os.urandom, 1.1)
511 self.assertRaises(TypeError, os.urandom, 2.0)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000512 except NotImplementedError:
513 pass
514
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000515 def test_execvpe_with_bad_arglist(self):
516 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
517
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000518class Win32ErrorTests(unittest.TestCase):
519 def test_rename(self):
520 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
521
522 def test_remove(self):
523 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
524
525 def test_chdir(self):
526 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
527
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000528 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000529 f = open(test_support.TESTFN, "w")
530 try:
531 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
532 finally:
533 f.close()
534 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000535
536 def test_utime(self):
537 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
538
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000539 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000540 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000541
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000542class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000543 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000544 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000545 #singles.append("close")
546 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000547 def get_single(f):
548 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000549 if hasattr(os, f):
550 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000551 return helper
552 for f in singles:
553 locals()["test_"+f] = get_single(f)
554
Benjamin Peterson5539c782009-01-19 17:37:42 +0000555 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000556 try:
557 f(test_support.make_bad_fd(), *args)
558 except OSError as e:
559 self.assertEqual(e.errno, errno.EBADF)
560 else:
561 self.fail("%r didn't raise a OSError with a bad file descriptor"
562 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000563
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000564 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000565 if hasattr(os, "isatty"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000566 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000567
568 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000569 if hasattr(os, "closerange"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000570 fd = test_support.make_bad_fd()
R. David Murray46ca2f22009-07-22 17:22:58 +0000571 # Make sure none of the descriptors we are about to close are
572 # currently valid (issue 6542).
573 for i in range(10):
574 try: os.fstat(fd+i)
575 except OSError:
576 pass
577 else:
578 break
579 if i < 2:
580 raise unittest.SkipTest(
581 "Unable to acquire a range of invalid file descriptors")
582 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000583
584 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000585 if hasattr(os, "dup2"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000586 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000587
588 def test_fchmod(self):
589 if hasattr(os, "fchmod"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000590 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000591
592 def test_fchown(self):
593 if hasattr(os, "fchown"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000594 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000595
596 def test_fpathconf(self):
597 if hasattr(os, "fpathconf"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000598 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000599
600 def test_ftruncate(self):
601 if hasattr(os, "ftruncate"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000602 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000603
604 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000605 if hasattr(os, "lseek"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000606 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000607
608 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000609 if hasattr(os, "read"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000610 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000611
612 def test_tcsetpgrpt(self):
613 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000614 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000615
616 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000617 if hasattr(os, "write"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000618 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000619
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000620if sys.platform != 'win32':
621 class Win32ErrorTests(unittest.TestCase):
622 pass
623
Gregory P. Smith6d307932009-04-05 23:43:58 +0000624 class PosixUidGidTests(unittest.TestCase):
625 if hasattr(os, 'setuid'):
626 def test_setuid(self):
627 if os.getuid() != 0:
628 self.assertRaises(os.error, os.setuid, 0)
629 self.assertRaises(OverflowError, os.setuid, 1<<32)
630
631 if hasattr(os, 'setgid'):
632 def test_setgid(self):
633 if os.getuid() != 0:
634 self.assertRaises(os.error, os.setgid, 0)
635 self.assertRaises(OverflowError, os.setgid, 1<<32)
636
637 if hasattr(os, 'seteuid'):
638 def test_seteuid(self):
639 if os.getuid() != 0:
640 self.assertRaises(os.error, os.seteuid, 0)
641 self.assertRaises(OverflowError, os.seteuid, 1<<32)
642
643 if hasattr(os, 'setegid'):
644 def test_setegid(self):
645 if os.getuid() != 0:
646 self.assertRaises(os.error, os.setegid, 0)
647 self.assertRaises(OverflowError, os.setegid, 1<<32)
648
649 if hasattr(os, 'setreuid'):
650 def test_setreuid(self):
651 if os.getuid() != 0:
652 self.assertRaises(os.error, os.setreuid, 0, 0)
653 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
654 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000655
656 def test_setreuid_neg1(self):
657 # Needs to accept -1. We run this in a subprocess to avoid
658 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000659 subprocess.check_call([
660 sys.executable, '-c',
661 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000662
663 if hasattr(os, 'setregid'):
664 def test_setregid(self):
665 if os.getuid() != 0:
666 self.assertRaises(os.error, os.setregid, 0, 0)
667 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
668 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000669
670 def test_setregid_neg1(self):
671 # Needs to accept -1. We run this in a subprocess to avoid
672 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000673 subprocess.check_call([
674 sys.executable, '-c',
675 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000676else:
677 class PosixUidGidTests(unittest.TestCase):
678 pass
679
Brian Curtine5aa8862010-04-02 23:26:06 +0000680@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
681class Win32KillTests(unittest.TestCase):
Brian Curtinb3dde132010-04-15 00:40:40 +0000682 def _kill(self, sig):
683 # Start sys.executable as a subprocess and communicate from the
684 # subprocess to the parent that the interpreter is ready. When it
685 # becomes ready, send *sig* via os.kill to the subprocess and check
686 # that the return code is equal to *sig*.
687 import ctypes
688 from ctypes import wintypes
689 import msvcrt
690
691 # Since we can't access the contents of the process' stdout until the
692 # process has exited, use PeekNamedPipe to see what's inside stdout
693 # without waiting. This is done so we can tell that the interpreter
694 # is started and running at a point where it could handle a signal.
695 PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
696 PeekNamedPipe.restype = wintypes.BOOL
697 PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
698 ctypes.POINTER(ctypes.c_char), # stdout buf
699 wintypes.DWORD, # Buffer size
700 ctypes.POINTER(wintypes.DWORD), # bytes read
701 ctypes.POINTER(wintypes.DWORD), # bytes avail
702 ctypes.POINTER(wintypes.DWORD)) # bytes left
703 msg = "running"
704 proc = subprocess.Popen([sys.executable, "-c",
705 "import sys;"
706 "sys.stdout.write('{}');"
707 "sys.stdout.flush();"
708 "input()".format(msg)],
709 stdout=subprocess.PIPE,
710 stderr=subprocess.PIPE,
711 stdin=subprocess.PIPE)
712
Brian Curtin83cba052010-05-28 15:49:21 +0000713 count, max = 0, 100
714 while count < max and proc.poll() is None:
715 # Create a string buffer to store the result of stdout from the pipe
716 buf = ctypes.create_string_buffer(len(msg))
717 # Obtain the text currently in proc.stdout
718 # Bytes read/avail/left are left as NULL and unused
719 rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
720 buf, ctypes.sizeof(buf), None, None, None)
721 self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
722 if buf.value:
723 self.assertEqual(msg, buf.value)
724 break
725 time.sleep(0.1)
726 count += 1
727 else:
728 self.fail("Did not receive communication from the subprocess")
Brian Curtinb3dde132010-04-15 00:40:40 +0000729
Brian Curtine5aa8862010-04-02 23:26:06 +0000730 os.kill(proc.pid, sig)
731 self.assertEqual(proc.wait(), sig)
732
733 def test_kill_sigterm(self):
734 # SIGTERM doesn't mean anything special, but make sure it works
Brian Curtinb3dde132010-04-15 00:40:40 +0000735 self._kill(signal.SIGTERM)
Brian Curtine5aa8862010-04-02 23:26:06 +0000736
737 def test_kill_int(self):
738 # os.kill on Windows can take an int which gets set as the exit code
Brian Curtinb3dde132010-04-15 00:40:40 +0000739 self._kill(100)
Brian Curtine5aa8862010-04-02 23:26:06 +0000740
741 def _kill_with_event(self, event, name):
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000742 tagname = "test_os_%s" % uuid.uuid1()
743 m = mmap.mmap(-1, 1, tagname)
744 m[0] = '0'
Brian Curtine5aa8862010-04-02 23:26:06 +0000745 # Run a script which has console control handling enabled.
746 proc = subprocess.Popen([sys.executable,
747 os.path.join(os.path.dirname(__file__),
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000748 "win_console_handler.py"), tagname],
Brian Curtine5aa8862010-04-02 23:26:06 +0000749 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
750 # Let the interpreter startup before we send signals. See #3137.
Hirokazu Yamamoto1f504f12010-10-08 09:41:13 +0000751 count, max = 0, 20
752 while count < max and proc.poll() is None:
753 if m[0] == '0':
754 break
755 time.sleep(0.5)
756 count += 1
757 else:
758 self.fail("Subprocess didn't finish initialization")
Brian Curtine5aa8862010-04-02 23:26:06 +0000759 os.kill(proc.pid, event)
760 # proc.send_signal(event) could also be done here.
761 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000762 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000763 if not proc.poll():
764 # Forcefully kill the process if we weren't able to signal it.
765 os.kill(proc.pid, signal.SIGINT)
766 self.fail("subprocess did not stop on {}".format(name))
767
768 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
769 def test_CTRL_C_EVENT(self):
770 from ctypes import wintypes
771 import ctypes
772
773 # Make a NULL value by creating a pointer with no argument.
774 NULL = ctypes.POINTER(ctypes.c_int)()
775 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
776 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
777 wintypes.BOOL)
778 SetConsoleCtrlHandler.restype = wintypes.BOOL
779
780 # Calling this with NULL and FALSE causes the calling process to
781 # handle CTRL+C, rather than ignore it. This property is inherited
782 # by subprocesses.
783 SetConsoleCtrlHandler(NULL, 0)
784
785 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
786
787 def test_CTRL_BREAK_EVENT(self):
788 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
789
790
Fred Drake2e2be372001-09-20 21:33:42 +0000791def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000792 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000793 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000794 TemporaryFileTests,
795 StatAttributeTests,
796 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000797 WalkTests,
798 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000799 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000800 URandomTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000801 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000802 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000803 PosixUidGidTests,
804 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000805 )
Fred Drake2e2be372001-09-20 21:33:42 +0000806
807if __name__ == "__main__":
808 test_main()