blob: 088101fd2b2bc71015528b346ebc086514d7ba0a [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
6import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00007import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +00008import sys
Walter Dörwald21d3a322003-05-01 17:45:56 +00009from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +000010
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011# Tests creating TESTFN
12class FileTests(unittest.TestCase):
13 def setUp(self):
14 if os.path.exists(test_support.TESTFN):
15 os.unlink(test_support.TESTFN)
16 tearDown = setUp
17
18 def test_access(self):
19 f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
20 os.close(f)
21 self.assert_(os.access(test_support.TESTFN, os.W_OK))
22
23
Guido van Rossum98bf58f2001-10-18 20:34:25 +000024# Test attributes on return values from os.*stat* family.
25class StatAttributeTests(unittest.TestCase):
26 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +000027 os.mkdir(test_support.TESTFN)
28 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +000029 f = open(self.fname, 'wb')
Guido van Rossum26d95c32007-08-27 23:18:54 +000030 f.write(b"ABC")
Guido van Rossum98bf58f2001-10-18 20:34:25 +000031 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +000032
Guido van Rossum98bf58f2001-10-18 20:34:25 +000033 def tearDown(self):
34 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +000035 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +000036
37 def test_stat_attributes(self):
38 if not hasattr(os, "stat"):
39 return
40
41 import stat
42 result = os.stat(self.fname)
43
44 # Make sure direct access works
45 self.assertEquals(result[stat.ST_SIZE], 3)
46 self.assertEquals(result.st_size, 3)
47
48 import sys
49
50 # Make sure all the attributes are there
51 members = dir(result)
52 for name in dir(stat):
53 if name[:3] == 'ST_':
54 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +000055 if name.endswith("TIME"):
56 def trunc(x): return int(x)
57 else:
58 def trunc(x): return x
59 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +000060 result[getattr(stat, name)])
61 self.assert_(attr in members)
62
63 try:
64 result[200]
65 self.fail("No exception thrown")
66 except IndexError:
67 pass
68
69 # Make sure that assignment fails
70 try:
71 result.st_mode = 1
72 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +000073 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +000074 pass
75
76 try:
77 result.st_rdev = 1
78 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +000079 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +000080 pass
81
82 try:
83 result.parrot = 1
84 self.fail("No exception thrown")
85 except AttributeError:
86 pass
87
88 # Use the stat_result constructor with a too-short tuple.
89 try:
90 result2 = os.stat_result((10,))
91 self.fail("No exception thrown")
92 except TypeError:
93 pass
94
95 # Use the constructr with a too-long tuple.
96 try:
97 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
98 except TypeError:
99 pass
100
Tim Peterse0c446b2001-10-18 21:57:37 +0000101
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000102 def test_statvfs_attributes(self):
103 if not hasattr(os, "statvfs"):
104 return
105
106 import statvfs
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000107 try:
108 result = os.statvfs(self.fname)
Guido van Rossumb940e112007-01-10 16:19:56 +0000109 except OSError as e:
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000110 # On AtheOS, glibc always returns ENOSYS
111 import errno
112 if e.errno == errno.ENOSYS:
113 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000114
115 # Make sure direct access works
116 self.assertEquals(result.f_bfree, result[statvfs.F_BFREE])
117
118 # Make sure all the attributes are there
119 members = dir(result)
120 for name in dir(statvfs):
121 if name[:2] == 'F_':
122 attr = name.lower()
123 self.assertEquals(getattr(result, attr),
124 result[getattr(statvfs, name)])
125 self.assert_(attr in members)
126
127 # Make sure that assignment really fails
128 try:
129 result.f_bfree = 1
130 self.fail("No exception thrown")
Collin Winter42dae6a2007-03-28 21:44:53 +0000131 except AttributeError:
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000132 pass
133
134 try:
135 result.parrot = 1
136 self.fail("No exception thrown")
137 except AttributeError:
138 pass
139
140 # Use the constructor with a too-short tuple.
141 try:
142 result2 = os.statvfs_result((10,))
143 self.fail("No exception thrown")
144 except TypeError:
145 pass
146
147 # Use the constructr with a too-long tuple.
148 try:
149 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
150 except TypeError:
151 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000152
Thomas Wouters89f507f2006-12-13 04:49:30 +0000153 def test_utime_dir(self):
154 delta = 1000000
155 st = os.stat(test_support.TESTFN)
156 # round to int, because some systems may support sub-second
157 # time stamps in stat, but not in utime.
158 os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
159 st2 = os.stat(test_support.TESTFN)
160 self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
161
162 # Restrict test to Win32, since there is no guarantee other
163 # systems support centiseconds
164 if sys.platform == 'win32':
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000165 def get_file_system(path):
166 import os
167 root = os.path.splitdrive(os.path.realpath("."))[0] + '\\'
168 import ctypes
169 kernel32 = ctypes.windll.kernel32
170 buf = ctypes.create_string_buffer("", 100)
171 if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
172 return buf.value
173
174 if get_file_system(test_support.TESTFN) == "NTFS":
175 def test_1565150(self):
176 t1 = 1159195039.25
177 os.utime(self.fname, (t1, t1))
178 self.assertEquals(os.stat(self.fname).st_mtime, t1)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000179
Guido van Rossumd8faa362007-04-27 19:54:29 +0000180 def test_1686475(self):
181 # Verify that an open file can be stat'ed
182 try:
183 os.stat(r"c:\pagefile.sys")
184 except WindowsError as e:
185 if e == 2: # file does not exist; cannot run test
186 return
187 self.fail("Could not stat pagefile.sys")
188
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000189from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000190
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000191class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000192 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000193 type2test = None
Christian Heimes90333392007-11-01 19:08:42 +0000194
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000195 def setUp(self):
196 self.__save = dict(os.environ)
Christian Heimes90333392007-11-01 19:08:42 +0000197 for key, value in self._reference().items():
198 os.environ[key] = value
199
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000200 def tearDown(self):
201 os.environ.clear()
202 os.environ.update(self.__save)
203
Christian Heimes90333392007-11-01 19:08:42 +0000204 def _reference(self):
205 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
206
207 def _empty_mapping(self):
208 os.environ.clear()
209 return os.environ
210
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000211 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000212 def test_update2(self):
Christian Heimes90333392007-11-01 19:08:42 +0000213 os.environ.clear()
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000214 if os.path.exists("/bin/sh"):
215 os.environ.update(HELLO="World")
216 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
217 self.assertEquals(value, "World")
218
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000219 # Verify environ keys and values from the OS are of the
220 # correct str type.
221 def test_keyvalue_types(self):
222 for key, val in os.environ.items():
223 self.assertEquals(type(key), str)
224 self.assertEquals(type(val), str)
225
Christian Heimes90333392007-11-01 19:08:42 +0000226 def test_items(self):
227 for key, value in self._reference().items():
228 self.assertEqual(os.environ.get(key), value)
229
Tim Petersc4e09402003-04-25 07:11:48 +0000230class WalkTests(unittest.TestCase):
231 """Tests for os.walk()."""
232
233 def test_traversal(self):
234 import os
235 from os.path import join
236
237 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238 # TESTFN/
239 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000240 # tmp1
241 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000242 # tmp2
243 # SUB11/ no kids
244 # SUB2/ a file kid and a dirsymlink kid
245 # tmp3
246 # link/ a symlink to TESTFN.2
247 # TEST2/
248 # tmp4 a lone file
249 walk_path = join(test_support.TESTFN, "TEST1")
250 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000251 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252 sub2_path = join(walk_path, "SUB2")
253 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000254 tmp2_path = join(sub1_path, "tmp2")
255 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256 link_path = join(sub2_path, "link")
257 t2_path = join(test_support.TESTFN, "TEST2")
258 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000259
260 # Create stuff.
261 os.makedirs(sub11_path)
262 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263 os.makedirs(t2_path)
264 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000265 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000266 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
267 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268 if hasattr(os, "symlink"):
269 os.symlink(os.path.abspath(t2_path), link_path)
270 sub2_tree = (sub2_path, ["link"], ["tmp3"])
271 else:
272 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000273
274 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000276 self.assertEqual(len(all), 4)
277 # We can't know which order SUB1 and SUB2 will appear in.
278 # Not flipped: TESTFN, SUB1, SUB11, SUB2
279 # flipped: TESTFN, SUB2, SUB1, SUB11
280 flipped = all[0][1][0] != "SUB1"
281 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000282 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000283 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
284 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000285 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000286
287 # Prune the search.
288 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000289 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000290 all.append((root, dirs, files))
291 # Don't descend into SUB1.
292 if 'SUB1' in dirs:
293 # Note that this also mutates the dirs we appended to all!
294 dirs.remove('SUB1')
295 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000296 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
297 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000298
299 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000300 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000301 self.assertEqual(len(all), 4)
302 # We can't know which order SUB1 and SUB2 will appear in.
303 # Not flipped: SUB11, SUB1, SUB2, TESTFN
304 # flipped: SUB2, SUB11, SUB1, TESTFN
305 flipped = all[3][1][0] != "SUB1"
306 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000307 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000308 self.assertEqual(all[flipped], (sub11_path, [], []))
309 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000310 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000311
Guido van Rossumd8faa362007-04-27 19:54:29 +0000312 if hasattr(os, "symlink"):
313 # Walk, following symlinks.
314 for root, dirs, files in os.walk(walk_path, followlinks=True):
315 if root == link_path:
316 self.assertEqual(dirs, [])
317 self.assertEqual(files, ["tmp4"])
318 break
319 else:
320 self.fail("Didn't follow symlink with followlinks=True")
321
322 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000323 # Tear everything down. This is a decent use for bottom-up on
324 # Windows, which doesn't have a recursive delete command. The
325 # (not so) subtlety is that rmdir will fail unless the dir's
326 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000327 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000328 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000329 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000330 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331 dirname = os.path.join(root, name)
332 if not os.path.islink(dirname):
333 os.rmdir(dirname)
334 else:
335 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000336 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000337
Guido van Rossume7ba4952007-06-06 23:52:48 +0000338class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000339 def setUp(self):
340 os.mkdir(test_support.TESTFN)
341
342 def test_makedir(self):
343 base = test_support.TESTFN
344 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
345 os.makedirs(path) # Should work
346 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
347 os.makedirs(path)
348
349 # Try paths with a '.' in them
350 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
351 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
352 os.makedirs(path)
353 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
354 'dir5', 'dir6')
355 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000356
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000357 def tearDown(self):
358 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
359 'dir4', 'dir5', 'dir6')
360 # If the tests failed, the bottom-most directory ('../dir6')
361 # may not have been created, so we look for the outermost directory
362 # that exists.
363 while not os.path.exists(path) and path != test_support.TESTFN:
364 path = os.path.dirname(path)
365
366 os.removedirs(path)
367
Guido van Rossume7ba4952007-06-06 23:52:48 +0000368class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000369 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000370 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000371 f.write('hello')
372 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000373 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000374 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000375 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000376
Guido van Rossume7ba4952007-06-06 23:52:48 +0000377class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000378 def test_urandom(self):
379 try:
380 self.assertEqual(len(os.urandom(1)), 1)
381 self.assertEqual(len(os.urandom(10)), 10)
382 self.assertEqual(len(os.urandom(100)), 100)
383 self.assertEqual(len(os.urandom(1000)), 1000)
384 except NotImplementedError:
385 pass
386
Guido van Rossume7ba4952007-06-06 23:52:48 +0000387class ExecTests(unittest.TestCase):
388 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000389 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000390
Thomas Heller6790d602007-08-30 17:15:14 +0000391 def test_execvpe_with_bad_arglist(self):
392 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
393
Thomas Wouters477c8d52006-05-27 19:21:47 +0000394class Win32ErrorTests(unittest.TestCase):
395 def test_rename(self):
396 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
397
398 def test_remove(self):
399 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
400
401 def test_chdir(self):
402 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
403
404 def test_mkdir(self):
405 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
406
407 def test_utime(self):
408 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
409
410 def test_access(self):
411 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
412
413 def test_chmod(self):
414 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
415
416if sys.platform != 'win32':
417 class Win32ErrorTests(unittest.TestCase):
418 pass
419
Fred Drake2e2be372001-09-20 21:33:42 +0000420def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000421 test_support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000422 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000423 StatAttributeTests,
424 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000425 WalkTests,
426 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000427 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000428 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000429 ExecTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000430 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000431 )
Fred Drake2e2be372001-09-20 21:33:42 +0000432
433if __name__ == "__main__":
434 test_main()