blob: d13a2eba68e9adc89f9dcd27328342d3cb2d59fc [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
Fred Drake38c2ef02001-07-17 20:52:51 +000014
Barry Warsaw60f01882001-08-22 19:24:42 +000015warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
16warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
17
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000018# Tests creating TESTFN
19class FileTests(unittest.TestCase):
20 def setUp(self):
21 if os.path.exists(test_support.TESTFN):
22 os.unlink(test_support.TESTFN)
23 tearDown = setUp
24
25 def test_access(self):
26 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
27 os.close(f)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000028 self.assertTrue(os.access(test_support.TESTFN, os.W_OK))
Tim Peters16a39322006-07-03 08:23:19 +000029
Georg Brandl309501a2008-01-19 20:22:13 +000030 def test_closerange(self):
Antoine Pitroubebb18b2008-08-17 14:43:41 +000031 first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
32 # We must allocate two consecutive file descriptors, otherwise
33 # it will mess up other file descriptors (perhaps even the three
34 # standard ones).
35 second = os.dup(first)
36 try:
37 retries = 0
38 while second != first + 1:
39 os.close(first)
40 retries += 1
41 if retries > 10:
42 # XXX test skipped
Benjamin Peterson757b3c92009-05-16 18:44:34 +000043 self.skipTest("couldn't allocate two consecutive fds")
Antoine Pitroubebb18b2008-08-17 14:43:41 +000044 first, second = second, os.dup(second)
45 finally:
46 os.close(second)
Georg Brandl309501a2008-01-19 20:22:13 +000047 # close a fd that is open, and one that isn't
Antoine Pitroubebb18b2008-08-17 14:43:41 +000048 os.closerange(first, first + 2)
49 self.assertRaises(OSError, os.write, first, "a")
Georg Brandl309501a2008-01-19 20:22:13 +000050
Hirokazu Yamamoto74ce88f2008-09-08 23:03:47 +000051 def test_rename(self):
52 path = unicode(test_support.TESTFN)
53 old = sys.getrefcount(path)
54 self.assertRaises(TypeError, os.rename, path, 0)
55 new = sys.getrefcount(path)
56 self.assertEqual(old, new)
57
Martin v. Löwisee1e06d2006-07-02 18:44:00 +000058
Fred Drake38c2ef02001-07-17 20:52:51 +000059class TemporaryFileTests(unittest.TestCase):
60 def setUp(self):
61 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000062 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000063
64 def tearDown(self):
65 for name in self.files:
66 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000067 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000068
69 def check_tempfile(self, name):
70 # make sure it doesn't already exist:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000071 self.assertFalse(os.path.exists(name),
Fred Drake38c2ef02001-07-17 20:52:51 +000072 "file already exists for temporary file")
73 # make sure we can create the file
74 open(name, "w")
75 self.files.append(name)
76
77 def test_tempnam(self):
78 if not hasattr(os, "tempnam"):
79 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000080 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000081 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000082 self.check_tempfile(os.tempnam())
83
Walter Dörwald21d3a322003-05-01 17:45:56 +000084 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000085 self.check_tempfile(name)
86
Walter Dörwald21d3a322003-05-01 17:45:56 +000087 name = os.tempnam(test_support.TESTFN, "pfx")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000088 self.assertTrue(os.path.basename(name)[:3] == "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000089 self.check_tempfile(name)
90
91 def test_tmpfile(self):
92 if not hasattr(os, "tmpfile"):
93 return
Martin v. Löwisd2bbe522008-03-06 06:55:22 +000094 # As with test_tmpnam() below, the Windows implementation of tmpfile()
95 # attempts to create a file in the root directory of the current drive.
96 # On Vista and Server 2008, this test will always fail for normal users
97 # as writing to the root directory requires elevated privileges. With
98 # XP and below, the semantics of tmpfile() are the same, but the user
99 # running the test is more likely to have administrative privileges on
100 # their account already. If that's the case, then os.tmpfile() should
101 # work. In order to make this test as useful as possible, rather than
102 # trying to detect Windows versions or whether or not the user has the
103 # right permissions, just try and create a file in the root directory
104 # and see if it raises a 'Permission denied' OSError. If it does, then
105 # test that a subsequent call to os.tmpfile() raises the same error. If
106 # it doesn't, assume we're on XP or below and the user running the test
107 # has administrative privileges, and proceed with the test as normal.
108 if sys.platform == 'win32':
109 name = '\\python_test_os_test_tmpfile.txt'
110 if os.path.exists(name):
111 os.remove(name)
112 try:
113 fp = open(name, 'w')
114 except IOError, first:
115 # open() failed, assert tmpfile() fails in the same way.
116 # Although open() raises an IOError and os.tmpfile() raises an
117 # OSError(), 'args' will be (13, 'Permission denied') in both
118 # cases.
119 try:
120 fp = os.tmpfile()
121 except OSError, second:
122 self.assertEqual(first.args, second.args)
123 else:
124 self.fail("expected os.tmpfile() to raise OSError")
125 return
126 else:
127 # open() worked, therefore, tmpfile() should work. Close our
128 # dummy file and proceed with the test as normal.
129 fp.close()
130 os.remove(name)
131
Fred Drake38c2ef02001-07-17 20:52:51 +0000132 fp = os.tmpfile()
133 fp.write("foobar")
134 fp.seek(0,0)
135 s = fp.read()
136 fp.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000137 self.assertTrue(s == "foobar")
Fred Drake38c2ef02001-07-17 20:52:51 +0000138
139 def test_tmpnam(self):
140 if not hasattr(os, "tmpnam"):
141 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +0000142 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +0000143 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +0000144 name = os.tmpnam()
145 if sys.platform in ("win32",):
146 # The Windows tmpnam() seems useless. From the MS docs:
147 #
148 # The character string that tmpnam creates consists of
149 # the path prefix, defined by the entry P_tmpdir in the
150 # file STDIO.H, followed by a sequence consisting of the
151 # digit characters '0' through '9'; the numerical value
152 # of this string is in the range 1 - 65,535. Changing the
153 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
154 # change the operation of tmpnam.
155 #
156 # The really bizarre part is that, at least under MSVC6,
157 # P_tmpdir is "\\". That is, the path returned refers to
158 # the root of the current drive. That's a terrible place to
159 # put temp files, and, depending on privileges, the user
160 # may not even be able to open a file in the root directory.
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000161 self.assertFalse(os.path.exists(name),
Tim Peters5501b5e2003-04-28 03:13:03 +0000162 "file already exists for temporary file")
163 else:
164 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +0000165
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000166# Test attributes on return values from os.*stat* family.
167class StatAttributeTests(unittest.TestCase):
168 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +0000169 os.mkdir(test_support.TESTFN)
170 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000171 f = open(self.fname, 'wb')
172 f.write("ABC")
173 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +0000174
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000175 def tearDown(self):
176 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000177 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000178
179 def test_stat_attributes(self):
180 if not hasattr(os, "stat"):
181 return
182
183 import stat
184 result = os.stat(self.fname)
185
186 # Make sure direct access works
187 self.assertEquals(result[stat.ST_SIZE], 3)
188 self.assertEquals(result.st_size, 3)
189
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000190 # Make sure all the attributes are there
191 members = dir(result)
192 for name in dir(stat):
193 if name[:3] == 'ST_':
194 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000195 if name.endswith("TIME"):
196 def trunc(x): return int(x)
197 else:
198 def trunc(x): return x
199 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000200 result[getattr(stat, name)])
Ezio Melottiaa980582010-01-23 23:04:36 +0000201 self.assertIn(attr, members)
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000202
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")
213 except TypeError:
214 pass
215
216 try:
217 result.st_rdev = 1
218 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000219 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000220 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
235 # Use the constructr with a too-long tuple.
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
Tim Peterse0c446b2001-10-18 21:57:37 +0000241
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000242 def test_statvfs_attributes(self):
243 if not hasattr(os, "statvfs"):
244 return
245
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000246 try:
247 result = os.statvfs(self.fname)
248 except OSError, e:
249 # On AtheOS, glibc always returns ENOSYS
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000250 if e.errno == errno.ENOSYS:
251 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000252
253 # Make sure direct access works
Brett Cannon90f2cb42008-05-16 00:37:42 +0000254 self.assertEquals(result.f_bfree, result[3])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000255
Brett Cannon90f2cb42008-05-16 00:37:42 +0000256 # Make sure all the attributes are there.
257 members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
258 'ffree', 'favail', 'flag', 'namemax')
259 for value, member in enumerate(members):
260 self.assertEquals(getattr(result, 'f_' + member), result[value])
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000261
262 # Make sure that assignment really fails
263 try:
264 result.f_bfree = 1
265 self.fail("No exception thrown")
266 except TypeError:
267 pass
268
269 try:
270 result.parrot = 1
271 self.fail("No exception thrown")
272 except AttributeError:
273 pass
274
275 # Use the constructor with a too-short tuple.
276 try:
277 result2 = os.statvfs_result((10,))
278 self.fail("No exception thrown")
279 except TypeError:
280 pass
281
282 # Use the constructr with a too-long tuple.
283 try:
284 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
285 except TypeError:
286 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000287
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000288 def test_utime_dir(self):
289 delta = 1000000
290 st = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000291 # round to int, because some systems may support sub-second
292 # time stamps in stat, but not in utime.
293 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000294 st2 = os.stat(test_support.TESTFN)
Martin v. Löwisa97e06d2006-10-15 11:02:07 +0000295 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
Martin v. Löwis18aaa562006-10-15 08:43:33 +0000296
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000297 # Restrict test to Win32, since there is no guarantee other
298 # systems support centiseconds
299 if sys.platform == 'win32':
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000300 def get_file_system(path):
Hirokazu Yamamotoccfdcd02008-08-20 04:13:28 +0000301 root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000302 import ctypes
Hirokazu Yamamotocd3b74d2008-08-20 16:15:28 +0000303 kernel32 = ctypes.windll.kernel32
304 buf = ctypes.create_string_buffer("", 100)
305 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
Martin v. Löwis7dcb83c2007-08-30 19:04:09 +0000306 return buf.value
307
308 if get_file_system(test_support.TESTFN) == "NTFS":
309 def test_1565150(self):
310 t1 = 1159195039.25
311 os.utime(self.fname, (t1, t1))
312 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Martin v. Löwisf43893a2006-10-09 20:44:25 +0000313
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000314 def test_1686475(self):
315 # Verify that an open file can be stat'ed
316 try:
317 os.stat(r"c:\pagefile.sys")
318 except WindowsError, e:
Antoine Pitrou954ea642008-08-17 20:15:07 +0000319 if e.errno == 2: # file does not exist; cannot run test
Martin v. Löwis3bf573f2007-04-04 18:30:36 +0000320 return
321 self.fail("Could not stat pagefile.sys")
322
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000323from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000324
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000325class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000326 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000327 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000328 def _reference(self):
329 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
330 def _empty_mapping(self):
331 os.environ.clear()
332 return os.environ
333 def setUp(self):
334 self.__save = dict(os.environ)
335 os.environ.clear()
336 def tearDown(self):
337 os.environ.clear()
338 os.environ.update(self.__save)
339
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000340 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000341 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000342 if os.path.exists("/bin/sh"):
343 os.environ.update(HELLO="World")
344 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
345 self.assertEquals(value, "World")
346
Tim Petersc4e09402003-04-25 07:11:48 +0000347class WalkTests(unittest.TestCase):
348 """Tests for os.walk()."""
349
350 def test_traversal(self):
351 import os
352 from os.path import join
353
354 # Build:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000355 # TESTFN/
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000356 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000357 # tmp1
358 # SUB1/ a file kid and a directory kid
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000359 # tmp2
360 # SUB11/ no kids
361 # SUB2/ a file kid and a dirsymlink kid
362 # tmp3
363 # link/ a symlink to TESTFN.2
364 # TEST2/
365 # tmp4 a lone file
366 walk_path = join(test_support.TESTFN, "TEST1")
367 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000368 sub11_path = join(sub1_path, "SUB11")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000369 sub2_path = join(walk_path, "SUB2")
370 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000371 tmp2_path = join(sub1_path, "tmp2")
372 tmp3_path = join(sub2_path, "tmp3")
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000373 link_path = join(sub2_path, "link")
374 t2_path = join(test_support.TESTFN, "TEST2")
375 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000376
377 # Create stuff.
378 os.makedirs(sub11_path)
379 os.makedirs(sub2_path)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000380 os.makedirs(t2_path)
381 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Tim Petersc4e09402003-04-25 07:11:48 +0000382 f = file(path, "w")
383 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
384 f.close()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000385 if hasattr(os, "symlink"):
386 os.symlink(os.path.abspath(t2_path), link_path)
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000387 sub2_tree = (sub2_path, ["link"], ["tmp3"])
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000388 else:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000389 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000390
391 # Walk top-down.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000392 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000393 self.assertEqual(len(all), 4)
394 # We can't know which order SUB1 and SUB2 will appear in.
395 # Not flipped: TESTFN, SUB1, SUB11, SUB2
396 # flipped: TESTFN, SUB2, SUB1, SUB11
397 flipped = all[0][1][0] != "SUB1"
398 all[0][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000399 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000400 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
401 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000402 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000403
404 # Prune the search.
405 all = []
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000406 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000407 all.append((root, dirs, files))
408 # Don't descend into SUB1.
409 if 'SUB1' in dirs:
410 # Note that this also mutates the dirs we appended to all!
411 dirs.remove('SUB1')
412 self.assertEqual(len(all), 2)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000413 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000414 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000415
416 # Walk bottom-up.
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000417 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000418 self.assertEqual(len(all), 4)
419 # We can't know which order SUB1 and SUB2 will appear in.
420 # Not flipped: SUB11, SUB1, SUB2, TESTFN
421 # flipped: SUB2, SUB11, SUB1, TESTFN
422 flipped = all[3][1][0] != "SUB1"
423 all[3][1].sort()
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000424 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000425 self.assertEqual(all[flipped], (sub11_path, [], []))
426 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000427 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000428
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000429 if hasattr(os, "symlink"):
430 # Walk, following symlinks.
431 for root, dirs, files in os.walk(walk_path, followlinks=True):
432 if root == link_path:
433 self.assertEqual(dirs, [])
434 self.assertEqual(files, ["tmp4"])
435 break
436 else:
437 self.fail("Didn't follow symlink with followlinks=True")
Tim Petersc4e09402003-04-25 07:11:48 +0000438
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000439 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000440 # Tear everything down. This is a decent use for bottom-up on
441 # Windows, which doesn't have a recursive delete command. The
442 # (not so) subtlety is that rmdir will fail unless the dir's
443 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000444 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000445 for name in files:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000446 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000447 for name in dirs:
Žiga Seilnacht18ffe422007-04-04 18:38:47 +0000448 dirname = os.path.join(root, name)
Georg Brandlcae9f3d2007-03-21 09:10:29 +0000449 if not os.path.islink(dirname):
450 os.rmdir(dirname)
451 else:
452 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000453 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000454
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000455class MakedirTests (unittest.TestCase):
456 def setUp(self):
457 os.mkdir(test_support.TESTFN)
458
459 def test_makedir(self):
460 base = test_support.TESTFN
461 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
462 os.makedirs(path) # Should work
463 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
464 os.makedirs(path)
465
466 # Try paths with a '.' in them
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000467 self.assertRaises(OSError, os.makedirs, os.curdir)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000468 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
469 os.makedirs(path)
470 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
471 'dir5', 'dir6')
472 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000473
Tim Peters58eb11c2004-01-18 20:29:55 +0000474
475
476
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000477 def tearDown(self):
478 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
479 'dir4', 'dir5', 'dir6')
480 # If the tests failed, the bottom-most directory ('../dir6')
481 # may not have been created, so we look for the outermost directory
482 # that exists.
483 while not os.path.exists(path) and path != test_support.TESTFN:
484 path = os.path.dirname(path)
485
486 os.removedirs(path)
487
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000488class DevNullTests (unittest.TestCase):
489 def test_devnull(self):
490 f = file(os.devnull, 'w')
491 f.write('hello')
492 f.close()
493 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000494 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000495 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000496
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000497class URandomTests (unittest.TestCase):
498 def test_urandom(self):
499 try:
500 self.assertEqual(len(os.urandom(1)), 1)
501 self.assertEqual(len(os.urandom(10)), 10)
502 self.assertEqual(len(os.urandom(100)), 100)
503 self.assertEqual(len(os.urandom(1000)), 1000)
Gregory P. Smithd7122032008-09-02 05:36:11 +0000504 # see http://bugs.python.org/issue3708
Mark Dickinson1b34d252010-01-01 17:27:30 +0000505 self.assertRaises(TypeError, os.urandom, 0.9)
506 self.assertRaises(TypeError, os.urandom, 1.1)
507 self.assertRaises(TypeError, os.urandom, 2.0)
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000508 except NotImplementedError:
509 pass
510
Matthias Klosee9fbf2b2010-03-19 14:45:06 +0000511 def test_execvpe_with_bad_arglist(self):
512 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
513
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000514class Win32ErrorTests(unittest.TestCase):
515 def test_rename(self):
516 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
517
518 def test_remove(self):
519 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
520
521 def test_chdir(self):
522 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
523
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000524 def test_mkdir(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000525 f = open(test_support.TESTFN, "w")
526 try:
527 self.assertRaises(WindowsError, os.mkdir, test_support.TESTFN)
528 finally:
529 f.close()
530 os.unlink(test_support.TESTFN)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000531
532 def test_utime(self):
533 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
534
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000535 def test_chmod(self):
Kristján Valur Jónssone20f54f2009-02-06 10:17:34 +0000536 self.assertRaises(WindowsError, os.chmod, test_support.TESTFN, 0)
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000537
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000538class TestInvalidFD(unittest.TestCase):
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000539 singles = ["fchdir", "fdopen", "dup", "fdatasync", "fstat",
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000540 "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
Kristján Valur Jónsson71ba2152009-01-15 22:40:03 +0000541 #singles.append("close")
542 #We omit close because it doesn'r raise an exception on some platforms
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000543 def get_single(f):
544 def helper(self):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000545 if hasattr(os, f):
546 self.check(getattr(os, f))
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000547 return helper
548 for f in singles:
549 locals()["test_"+f] = get_single(f)
550
Benjamin Peterson5539c782009-01-19 17:37:42 +0000551 def check(self, f, *args):
Benjamin Peterson1de05e92009-01-31 01:42:55 +0000552 try:
553 f(test_support.make_bad_fd(), *args)
554 except OSError as e:
555 self.assertEqual(e.errno, errno.EBADF)
556 else:
557 self.fail("%r didn't raise a OSError with a bad file descriptor"
558 % f)
Benjamin Peterson5539c782009-01-19 17:37:42 +0000559
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000560 def test_isatty(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000561 if hasattr(os, "isatty"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000562 self.assertEqual(os.isatty(test_support.make_bad_fd()), False)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000563
564 def test_closerange(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000565 if hasattr(os, "closerange"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000566 fd = test_support.make_bad_fd()
R. David Murray46ca2f22009-07-22 17:22:58 +0000567 # Make sure none of the descriptors we are about to close are
568 # currently valid (issue 6542).
569 for i in range(10):
570 try: os.fstat(fd+i)
571 except OSError:
572 pass
573 else:
574 break
575 if i < 2:
576 raise unittest.SkipTest(
577 "Unable to acquire a range of invalid file descriptors")
578 self.assertEqual(os.closerange(fd, fd + i-1), None)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000579
580 def test_dup2(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000581 if hasattr(os, "dup2"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000582 self.check(os.dup2, 20)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000583
584 def test_fchmod(self):
585 if hasattr(os, "fchmod"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000586 self.check(os.fchmod, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000587
588 def test_fchown(self):
589 if hasattr(os, "fchown"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000590 self.check(os.fchown, -1, -1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000591
592 def test_fpathconf(self):
593 if hasattr(os, "fpathconf"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000594 self.check(os.fpathconf, "PC_NAME_MAX")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000595
596 def test_ftruncate(self):
597 if hasattr(os, "ftruncate"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000598 self.check(os.ftruncate, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000599
600 def test_lseek(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000601 if hasattr(os, "lseek"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000602 self.check(os.lseek, 0, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000603
604 def test_read(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000605 if hasattr(os, "read"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000606 self.check(os.read, 1)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000607
608 def test_tcsetpgrpt(self):
609 if hasattr(os, "tcsetpgrp"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000610 self.check(os.tcsetpgrp, 0)
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000611
612 def test_write(self):
Kristján Valur Jónsson4f69b7e2009-01-15 22:46:26 +0000613 if hasattr(os, "write"):
Benjamin Peterson5539c782009-01-19 17:37:42 +0000614 self.check(os.write, " ")
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000615
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000616if sys.platform != 'win32':
617 class Win32ErrorTests(unittest.TestCase):
618 pass
619
Gregory P. Smith6d307932009-04-05 23:43:58 +0000620 class PosixUidGidTests(unittest.TestCase):
621 if hasattr(os, 'setuid'):
622 def test_setuid(self):
623 if os.getuid() != 0:
624 self.assertRaises(os.error, os.setuid, 0)
625 self.assertRaises(OverflowError, os.setuid, 1<<32)
626
627 if hasattr(os, 'setgid'):
628 def test_setgid(self):
629 if os.getuid() != 0:
630 self.assertRaises(os.error, os.setgid, 0)
631 self.assertRaises(OverflowError, os.setgid, 1<<32)
632
633 if hasattr(os, 'seteuid'):
634 def test_seteuid(self):
635 if os.getuid() != 0:
636 self.assertRaises(os.error, os.seteuid, 0)
637 self.assertRaises(OverflowError, os.seteuid, 1<<32)
638
639 if hasattr(os, 'setegid'):
640 def test_setegid(self):
641 if os.getuid() != 0:
642 self.assertRaises(os.error, os.setegid, 0)
643 self.assertRaises(OverflowError, os.setegid, 1<<32)
644
645 if hasattr(os, 'setreuid'):
646 def test_setreuid(self):
647 if os.getuid() != 0:
648 self.assertRaises(os.error, os.setreuid, 0, 0)
649 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
650 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000651
652 def test_setreuid_neg1(self):
653 # Needs to accept -1. We run this in a subprocess to avoid
654 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000655 subprocess.check_call([
656 sys.executable, '-c',
657 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000658
659 if hasattr(os, 'setregid'):
660 def test_setregid(self):
661 if os.getuid() != 0:
662 self.assertRaises(os.error, os.setregid, 0, 0)
663 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
664 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
Gregory P. Smith467298c2010-03-06 07:35:19 +0000665
666 def test_setregid_neg1(self):
667 # Needs to accept -1. We run this in a subprocess to avoid
668 # altering the test runner's process state (issue8045).
Gregory P. Smith467298c2010-03-06 07:35:19 +0000669 subprocess.check_call([
670 sys.executable, '-c',
671 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
Gregory P. Smith6d307932009-04-05 23:43:58 +0000672else:
673 class PosixUidGidTests(unittest.TestCase):
674 pass
675
Brian Curtine5aa8862010-04-02 23:26:06 +0000676@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
677class Win32KillTests(unittest.TestCase):
678 def _kill(self, sig, *args):
679 # Send a subprocess a signal (or in some cases, just an int to be
680 # the return value)
681 proc = subprocess.Popen(*args)
Brian Curtin235350a2010-04-14 02:24:24 +0000682 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000683 os.kill(proc.pid, sig)
684 self.assertEqual(proc.wait(), sig)
685
686 def test_kill_sigterm(self):
687 # SIGTERM doesn't mean anything special, but make sure it works
688 self._kill(signal.SIGTERM, [sys.executable])
689
690 def test_kill_int(self):
691 # os.kill on Windows can take an int which gets set as the exit code
692 self._kill(100, [sys.executable])
693
694 def _kill_with_event(self, event, name):
695 # Run a script which has console control handling enabled.
696 proc = subprocess.Popen([sys.executable,
697 os.path.join(os.path.dirname(__file__),
698 "win_console_handler.py")],
699 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
700 # Let the interpreter startup before we send signals. See #3137.
Brian Curtinfce1d312010-04-05 19:04:23 +0000701 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000702 os.kill(proc.pid, event)
703 # proc.send_signal(event) could also be done here.
704 # Allow time for the signal to be passed and the process to exit.
Brian Curtinfce1d312010-04-05 19:04:23 +0000705 time.sleep(0.5)
Brian Curtine5aa8862010-04-02 23:26:06 +0000706 if not proc.poll():
707 # Forcefully kill the process if we weren't able to signal it.
708 os.kill(proc.pid, signal.SIGINT)
709 self.fail("subprocess did not stop on {}".format(name))
710
711 @unittest.skip("subprocesses aren't inheriting CTRL+C property")
712 def test_CTRL_C_EVENT(self):
713 from ctypes import wintypes
714 import ctypes
715
716 # Make a NULL value by creating a pointer with no argument.
717 NULL = ctypes.POINTER(ctypes.c_int)()
718 SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
719 SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
720 wintypes.BOOL)
721 SetConsoleCtrlHandler.restype = wintypes.BOOL
722
723 # Calling this with NULL and FALSE causes the calling process to
724 # handle CTRL+C, rather than ignore it. This property is inherited
725 # by subprocesses.
726 SetConsoleCtrlHandler(NULL, 0)
727
728 self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
729
730 def test_CTRL_BREAK_EVENT(self):
731 self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
732
733
Fred Drake2e2be372001-09-20 21:33:42 +0000734def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000735 test_support.run_unittest(
Martin v. Löwisee1e06d2006-07-02 18:44:00 +0000736 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000737 TemporaryFileTests,
738 StatAttributeTests,
739 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000740 WalkTests,
741 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000742 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000743 URandomTests,
Kristján Valur Jónsson1c62b652009-01-12 18:09:27 +0000744 Win32ErrorTests,
Gregory P. Smith6d307932009-04-05 23:43:58 +0000745 TestInvalidFD,
Brian Curtine5aa8862010-04-02 23:26:06 +0000746 PosixUidGidTests,
747 Win32KillTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000748 )
Fred Drake2e2be372001-09-20 21:33:42 +0000749
750if __name__ == "__main__":
751 test_main()