blob: ffc9420ec3dfeac9a1517a1c749ad13c9873a2bc [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
Martin v. Löwis8e0d4942006-05-04 10:08:42 +00008import sys
Walter Dörwald21d3a322003-05-01 17:45:56 +00009from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +000010
Barry Warsaw60f01882001-08-22 19:24:42 +000011warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
12warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
13
Fred Drake38c2ef02001-07-17 20:52:51 +000014class TemporaryFileTests(unittest.TestCase):
15 def setUp(self):
16 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000017 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000018
19 def tearDown(self):
20 for name in self.files:
21 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000022 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000023
24 def check_tempfile(self, name):
25 # make sure it doesn't already exist:
26 self.failIf(os.path.exists(name),
27 "file already exists for temporary file")
28 # make sure we can create the file
29 open(name, "w")
30 self.files.append(name)
31
32 def test_tempnam(self):
33 if not hasattr(os, "tempnam"):
34 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000035 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000036 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000037 self.check_tempfile(os.tempnam())
38
Walter Dörwald21d3a322003-05-01 17:45:56 +000039 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000040 self.check_tempfile(name)
41
Walter Dörwald21d3a322003-05-01 17:45:56 +000042 name = os.tempnam(test_support.TESTFN, "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000043 self.assert_(os.path.basename(name)[:3] == "pfx")
44 self.check_tempfile(name)
45
46 def test_tmpfile(self):
47 if not hasattr(os, "tmpfile"):
48 return
49 fp = os.tmpfile()
50 fp.write("foobar")
51 fp.seek(0,0)
52 s = fp.read()
53 fp.close()
54 self.assert_(s == "foobar")
55
56 def test_tmpnam(self):
Tim Peters5501b5e2003-04-28 03:13:03 +000057 import sys
Fred Drake38c2ef02001-07-17 20:52:51 +000058 if not hasattr(os, "tmpnam"):
59 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000060 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000061 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +000062 name = os.tmpnam()
63 if sys.platform in ("win32",):
64 # The Windows tmpnam() seems useless. From the MS docs:
65 #
66 # The character string that tmpnam creates consists of
67 # the path prefix, defined by the entry P_tmpdir in the
68 # file STDIO.H, followed by a sequence consisting of the
69 # digit characters '0' through '9'; the numerical value
70 # of this string is in the range 1 - 65,535. Changing the
71 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
72 # change the operation of tmpnam.
73 #
74 # The really bizarre part is that, at least under MSVC6,
75 # P_tmpdir is "\\". That is, the path returned refers to
76 # the root of the current drive. That's a terrible place to
77 # put temp files, and, depending on privileges, the user
78 # may not even be able to open a file in the root directory.
79 self.failIf(os.path.exists(name),
80 "file already exists for temporary file")
81 else:
82 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +000083
Guido van Rossum98bf58f2001-10-18 20:34:25 +000084# Test attributes on return values from os.*stat* family.
85class StatAttributeTests(unittest.TestCase):
86 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +000087 os.mkdir(test_support.TESTFN)
88 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +000089 f = open(self.fname, 'wb')
90 f.write("ABC")
91 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +000092
Guido van Rossum98bf58f2001-10-18 20:34:25 +000093 def tearDown(self):
94 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +000095 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +000096
97 def test_stat_attributes(self):
98 if not hasattr(os, "stat"):
99 return
100
101 import stat
102 result = os.stat(self.fname)
103
104 # Make sure direct access works
105 self.assertEquals(result[stat.ST_SIZE], 3)
106 self.assertEquals(result.st_size, 3)
107
108 import sys
109
110 # Make sure all the attributes are there
111 members = dir(result)
112 for name in dir(stat):
113 if name[:3] == 'ST_':
114 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000115 if name.endswith("TIME"):
116 def trunc(x): return int(x)
117 else:
118 def trunc(x): return x
119 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000120 result[getattr(stat, name)])
121 self.assert_(attr in members)
122
123 try:
124 result[200]
125 self.fail("No exception thrown")
126 except IndexError:
127 pass
128
129 # Make sure that assignment fails
130 try:
131 result.st_mode = 1
132 self.fail("No exception thrown")
133 except TypeError:
134 pass
135
136 try:
137 result.st_rdev = 1
138 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000139 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000140 pass
141
142 try:
143 result.parrot = 1
144 self.fail("No exception thrown")
145 except AttributeError:
146 pass
147
148 # Use the stat_result constructor with a too-short tuple.
149 try:
150 result2 = os.stat_result((10,))
151 self.fail("No exception thrown")
152 except TypeError:
153 pass
154
155 # Use the constructr with a too-long tuple.
156 try:
157 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
158 except TypeError:
159 pass
160
Tim Peterse0c446b2001-10-18 21:57:37 +0000161
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000162 def test_statvfs_attributes(self):
163 if not hasattr(os, "statvfs"):
164 return
165
166 import statvfs
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000167 try:
168 result = os.statvfs(self.fname)
169 except OSError, e:
170 # On AtheOS, glibc always returns ENOSYS
171 import errno
172 if e.errno == errno.ENOSYS:
173 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000174
175 # Make sure direct access works
176 self.assertEquals(result.f_bfree, result[statvfs.F_BFREE])
177
178 # Make sure all the attributes are there
179 members = dir(result)
180 for name in dir(statvfs):
181 if name[:2] == 'F_':
182 attr = name.lower()
183 self.assertEquals(getattr(result, attr),
184 result[getattr(statvfs, name)])
185 self.assert_(attr in members)
186
187 # Make sure that assignment really fails
188 try:
189 result.f_bfree = 1
190 self.fail("No exception thrown")
191 except TypeError:
192 pass
193
194 try:
195 result.parrot = 1
196 self.fail("No exception thrown")
197 except AttributeError:
198 pass
199
200 # Use the constructor with a too-short tuple.
201 try:
202 result2 = os.statvfs_result((10,))
203 self.fail("No exception thrown")
204 except TypeError:
205 pass
206
207 # Use the constructr with a too-long tuple.
208 try:
209 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
210 except TypeError:
211 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000212
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000213from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000214
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000215class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000216 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000217 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000218 def _reference(self):
219 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
220 def _empty_mapping(self):
221 os.environ.clear()
222 return os.environ
223 def setUp(self):
224 self.__save = dict(os.environ)
225 os.environ.clear()
226 def tearDown(self):
227 os.environ.clear()
228 os.environ.update(self.__save)
229
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000230 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000231 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000232 if os.path.exists("/bin/sh"):
233 os.environ.update(HELLO="World")
234 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
235 self.assertEquals(value, "World")
236
Tim Petersc4e09402003-04-25 07:11:48 +0000237class WalkTests(unittest.TestCase):
238 """Tests for os.walk()."""
239
240 def test_traversal(self):
241 import os
242 from os.path import join
243
244 # Build:
245 # TESTFN/ a file kid and two directory kids
246 # tmp1
247 # SUB1/ a file kid and a directory kid
248 # tmp2
249 # SUB11/ no kids
250 # SUB2/ just a file kid
251 # tmp3
Walter Dörwald21d3a322003-05-01 17:45:56 +0000252 sub1_path = join(test_support.TESTFN, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000253 sub11_path = join(sub1_path, "SUB11")
Walter Dörwald21d3a322003-05-01 17:45:56 +0000254 sub2_path = join(test_support.TESTFN, "SUB2")
255 tmp1_path = join(test_support.TESTFN, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000256 tmp2_path = join(sub1_path, "tmp2")
257 tmp3_path = join(sub2_path, "tmp3")
258
259 # Create stuff.
260 os.makedirs(sub11_path)
261 os.makedirs(sub2_path)
262 for path in tmp1_path, tmp2_path, tmp3_path:
263 f = file(path, "w")
264 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
265 f.close()
266
267 # Walk top-down.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000268 all = list(os.walk(test_support.TESTFN))
Tim Petersc4e09402003-04-25 07:11:48 +0000269 self.assertEqual(len(all), 4)
270 # We can't know which order SUB1 and SUB2 will appear in.
271 # Not flipped: TESTFN, SUB1, SUB11, SUB2
272 # flipped: TESTFN, SUB2, SUB1, SUB11
273 flipped = all[0][1][0] != "SUB1"
274 all[0][1].sort()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000275 self.assertEqual(all[0], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000276 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
277 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
278 self.assertEqual(all[3 - 2 * flipped], (sub2_path, [], ["tmp3"]))
279
280 # Prune the search.
281 all = []
Walter Dörwald21d3a322003-05-01 17:45:56 +0000282 for root, dirs, files in os.walk(test_support.TESTFN):
Tim Petersc4e09402003-04-25 07:11:48 +0000283 all.append((root, dirs, files))
284 # Don't descend into SUB1.
285 if 'SUB1' in dirs:
286 # Note that this also mutates the dirs we appended to all!
287 dirs.remove('SUB1')
288 self.assertEqual(len(all), 2)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000289 self.assertEqual(all[0], (test_support.TESTFN, ["SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000290 self.assertEqual(all[1], (sub2_path, [], ["tmp3"]))
291
292 # Walk bottom-up.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000293 all = list(os.walk(test_support.TESTFN, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000294 self.assertEqual(len(all), 4)
295 # We can't know which order SUB1 and SUB2 will appear in.
296 # Not flipped: SUB11, SUB1, SUB2, TESTFN
297 # flipped: SUB2, SUB11, SUB1, TESTFN
298 flipped = all[3][1][0] != "SUB1"
299 all[3][1].sort()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000300 self.assertEqual(all[3], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000301 self.assertEqual(all[flipped], (sub11_path, [], []))
302 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
303 self.assertEqual(all[2 - 2 * flipped], (sub2_path, [], ["tmp3"]))
304
305 # Tear everything down. This is a decent use for bottom-up on
306 # Windows, which doesn't have a recursive delete command. The
307 # (not so) subtlety is that rmdir will fail unless the dir's
308 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000309 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000310 for name in files:
311 os.remove(join(root, name))
312 for name in dirs:
313 os.rmdir(join(root, name))
Walter Dörwald21d3a322003-05-01 17:45:56 +0000314 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000315
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000316class MakedirTests (unittest.TestCase):
317 def setUp(self):
318 os.mkdir(test_support.TESTFN)
319
320 def test_makedir(self):
321 base = test_support.TESTFN
322 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
323 os.makedirs(path) # Should work
324 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
325 os.makedirs(path)
326
327 # Try paths with a '.' in them
328 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
329 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
330 os.makedirs(path)
331 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
332 'dir5', 'dir6')
333 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000334
Tim Peters58eb11c2004-01-18 20:29:55 +0000335
336
337
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000338 def tearDown(self):
339 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
340 'dir4', 'dir5', 'dir6')
341 # If the tests failed, the bottom-most directory ('../dir6')
342 # may not have been created, so we look for the outermost directory
343 # that exists.
344 while not os.path.exists(path) and path != test_support.TESTFN:
345 path = os.path.dirname(path)
346
347 os.removedirs(path)
348
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000349class DevNullTests (unittest.TestCase):
350 def test_devnull(self):
351 f = file(os.devnull, 'w')
352 f.write('hello')
353 f.close()
354 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000355 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000356 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000357
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000358class URandomTests (unittest.TestCase):
359 def test_urandom(self):
360 try:
361 self.assertEqual(len(os.urandom(1)), 1)
362 self.assertEqual(len(os.urandom(10)), 10)
363 self.assertEqual(len(os.urandom(100)), 100)
364 self.assertEqual(len(os.urandom(1000)), 1000)
365 except NotImplementedError:
366 pass
367
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000368class Win32ErrorTests(unittest.TestCase):
369 def test_rename(self):
370 self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
371
372 def test_remove(self):
373 self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
374
375 def test_chdir(self):
376 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
377
Martin v. Löwisd4e3bb32006-05-06 16:32:54 +0000378 def test_mkdir(self):
379 self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
380
381 def test_utime(self):
382 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
383
384 def test_access(self):
385 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
386
387 def test_chmod(self):
388 self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
389
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000390if sys.platform != 'win32':
391 class Win32ErrorTests(unittest.TestCase):
392 pass
393
Fred Drake2e2be372001-09-20 21:33:42 +0000394def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000395 test_support.run_unittest(
396 TemporaryFileTests,
397 StatAttributeTests,
398 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000399 WalkTests,
400 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000401 DevNullTests,
Martin v. Löwis8e0d4942006-05-04 10:08:42 +0000402 URandomTests,
403 Win32ErrorTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000404 )
Fred Drake2e2be372001-09-20 21:33:42 +0000405
406if __name__ == "__main__":
407 test_main()