blob: 15ed5578f9a2756b70927cf1f6926574786be6ea [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
Christian Heimes1a13d592007-11-08 14:16:55 +0000219 def test_os_popen_iter(self):
220 if os.path.exists("/bin/sh"):
221 popen = os.popen("/bin/sh -c 'echo \"line1\nline2\nline3\"'")
222 it = iter(popen)
223 self.assertEquals(next(it), "line1\n")
224 self.assertEquals(next(it), "line2\n")
225 self.assertEquals(next(it), "line3\n")
226 self.assertRaises(StopIteration, next, it)
227
Guido van Rossum67aca9e2007-06-13 21:51:27 +0000228 # Verify environ keys and values from the OS are of the
229 # correct str type.
230 def test_keyvalue_types(self):
231 for key, val in os.environ.items():
232 self.assertEquals(type(key), str)
233 self.assertEquals(type(val), str)
234
Christian Heimes90333392007-11-01 19:08:42 +0000235 def test_items(self):
236 for key, value in self._reference().items():
237 self.assertEqual(os.environ.get(key), value)
238
Tim Petersc4e09402003-04-25 07:11:48 +0000239class WalkTests(unittest.TestCase):
240 """Tests for os.walk()."""
241
242 def test_traversal(self):
243 import os
244 from os.path import join
245
246 # Build:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247 # TESTFN/
248 # TEST1/ a file kid and two directory kids
Tim Petersc4e09402003-04-25 07:11:48 +0000249 # tmp1
250 # SUB1/ a file kid and a directory kid
Guido van Rossumd8faa362007-04-27 19:54:29 +0000251 # tmp2
252 # SUB11/ no kids
253 # SUB2/ a file kid and a dirsymlink kid
254 # tmp3
255 # link/ a symlink to TESTFN.2
256 # TEST2/
257 # tmp4 a lone file
258 walk_path = join(test_support.TESTFN, "TEST1")
259 sub1_path = join(walk_path, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000260 sub11_path = join(sub1_path, "SUB11")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261 sub2_path = join(walk_path, "SUB2")
262 tmp1_path = join(walk_path, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000263 tmp2_path = join(sub1_path, "tmp2")
264 tmp3_path = join(sub2_path, "tmp3")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265 link_path = join(sub2_path, "link")
266 t2_path = join(test_support.TESTFN, "TEST2")
267 tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
Tim Petersc4e09402003-04-25 07:11:48 +0000268
269 # Create stuff.
270 os.makedirs(sub11_path)
271 os.makedirs(sub2_path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272 os.makedirs(t2_path)
273 for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
Alex Martelli01c77c62006-08-24 02:58:11 +0000274 f = open(path, "w")
Tim Petersc4e09402003-04-25 07:11:48 +0000275 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
276 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 if hasattr(os, "symlink"):
278 os.symlink(os.path.abspath(t2_path), link_path)
279 sub2_tree = (sub2_path, ["link"], ["tmp3"])
280 else:
281 sub2_tree = (sub2_path, [], ["tmp3"])
Tim Petersc4e09402003-04-25 07:11:48 +0000282
283 # Walk top-down.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000284 all = list(os.walk(walk_path))
Tim Petersc4e09402003-04-25 07:11:48 +0000285 self.assertEqual(len(all), 4)
286 # We can't know which order SUB1 and SUB2 will appear in.
287 # Not flipped: TESTFN, SUB1, SUB11, SUB2
288 # flipped: TESTFN, SUB2, SUB1, SUB11
289 flipped = all[0][1][0] != "SUB1"
290 all[0][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000291 self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000292 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
293 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000294 self.assertEqual(all[3 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000295
296 # Prune the search.
297 all = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000298 for root, dirs, files in os.walk(walk_path):
Tim Petersc4e09402003-04-25 07:11:48 +0000299 all.append((root, dirs, files))
300 # Don't descend into SUB1.
301 if 'SUB1' in dirs:
302 # Note that this also mutates the dirs we appended to all!
303 dirs.remove('SUB1')
304 self.assertEqual(len(all), 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000305 self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
306 self.assertEqual(all[1], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000307
308 # Walk bottom-up.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000309 all = list(os.walk(walk_path, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000310 self.assertEqual(len(all), 4)
311 # We can't know which order SUB1 and SUB2 will appear in.
312 # Not flipped: SUB11, SUB1, SUB2, TESTFN
313 # flipped: SUB2, SUB11, SUB1, TESTFN
314 flipped = all[3][1][0] != "SUB1"
315 all[3][1].sort()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000316 self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000317 self.assertEqual(all[flipped], (sub11_path, [], []))
318 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000319 self.assertEqual(all[2 - 2 * flipped], sub2_tree)
Tim Petersc4e09402003-04-25 07:11:48 +0000320
Guido van Rossumd8faa362007-04-27 19:54:29 +0000321 if hasattr(os, "symlink"):
322 # Walk, following symlinks.
323 for root, dirs, files in os.walk(walk_path, followlinks=True):
324 if root == link_path:
325 self.assertEqual(dirs, [])
326 self.assertEqual(files, ["tmp4"])
327 break
328 else:
329 self.fail("Didn't follow symlink with followlinks=True")
330
331 def tearDown(self):
Tim Petersc4e09402003-04-25 07:11:48 +0000332 # Tear everything down. This is a decent use for bottom-up on
333 # Windows, which doesn't have a recursive delete command. The
334 # (not so) subtlety is that rmdir will fail unless the dir's
335 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000336 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000337 for name in files:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 os.remove(os.path.join(root, name))
Tim Petersc4e09402003-04-25 07:11:48 +0000339 for name in dirs:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 dirname = os.path.join(root, name)
341 if not os.path.islink(dirname):
342 os.rmdir(dirname)
343 else:
344 os.remove(dirname)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000345 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000346
Guido van Rossume7ba4952007-06-06 23:52:48 +0000347class MakedirTests(unittest.TestCase):
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000348 def setUp(self):
349 os.mkdir(test_support.TESTFN)
350
351 def test_makedir(self):
352 base = test_support.TESTFN
353 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
354 os.makedirs(path) # Should work
355 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
356 os.makedirs(path)
357
358 # Try paths with a '.' in them
359 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
360 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
361 os.makedirs(path)
362 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
363 'dir5', 'dir6')
364 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000365
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000366 def tearDown(self):
367 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
368 'dir4', 'dir5', 'dir6')
369 # If the tests failed, the bottom-most directory ('../dir6')
370 # may not have been created, so we look for the outermost directory
371 # that exists.
372 while not os.path.exists(path) and path != test_support.TESTFN:
373 path = os.path.dirname(path)
374
375 os.removedirs(path)
376
Guido van Rossume7ba4952007-06-06 23:52:48 +0000377class DevNullTests(unittest.TestCase):
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000378 def test_devnull(self):
Alex Martelli01c77c62006-08-24 02:58:11 +0000379 f = open(os.devnull, 'w')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000380 f.write('hello')
381 f.close()
Alex Martelli01c77c62006-08-24 02:58:11 +0000382 f = open(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000383 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000384 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000385
Guido van Rossume7ba4952007-06-06 23:52:48 +0000386class URandomTests(unittest.TestCase):
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000387 def test_urandom(self):
388 try:
389 self.assertEqual(len(os.urandom(1)), 1)
390 self.assertEqual(len(os.urandom(10)), 10)
391 self.assertEqual(len(os.urandom(100)), 100)
392 self.assertEqual(len(os.urandom(1000)), 1000)
393 except NotImplementedError:
394 pass
395
Guido van Rossume7ba4952007-06-06 23:52:48 +0000396class ExecTests(unittest.TestCase):
397 def test_execvpe_with_bad_program(self):
Thomas Hellerbd315c52007-08-30 17:57:21 +0000398 self.assertRaises(OSError, os.execvpe, 'no such app-', ['no such app-'], None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000399
Thomas Heller6790d602007-08-30 17:15:14 +0000400 def test_execvpe_with_bad_arglist(self):
401 self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
402
Thomas Wouters477c8d52006-05-27 19:21:47 +0000403class Win32ErrorTests(unittest.TestCase):
404 def test_rename(self):
405 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
406
407 def test_remove(self):
408 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
409
410 def test_chdir(self):
411 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
412
413 def test_mkdir(self):
414 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
415
416 def test_utime(self):
417 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
418
419 def test_access(self):
420 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
421
422 def test_chmod(self):
423 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
424
425if sys.platform != 'win32':
426 class Win32ErrorTests(unittest.TestCase):
427 pass
428
Fred Drake2e2be372001-09-20 21:33:42 +0000429def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000430 test_support.run_unittest(
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000431 FileTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000432 StatAttributeTests,
433 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000434 WalkTests,
435 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000436 DevNullTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437 URandomTests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000438 ExecTests,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000440 )
Fred Drake2e2be372001-09-20 21:33:42 +0000441
442if __name__ == "__main__":
443 test_main()