blob: 2bc5fc0ab7bfee4b96e9a236d65c8fbeff7b72e7 [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
Walter Dörwald21d3a322003-05-01 17:45:56 +00008from test import test_support
Fred Drake38c2ef02001-07-17 20:52:51 +00009
Barry Warsaw60f01882001-08-22 19:24:42 +000010warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
11warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
12
Fred Drake38c2ef02001-07-17 20:52:51 +000013class TemporaryFileTests(unittest.TestCase):
14 def setUp(self):
15 self.files = []
Walter Dörwald21d3a322003-05-01 17:45:56 +000016 os.mkdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000017
18 def tearDown(self):
19 for name in self.files:
20 os.unlink(name)
Walter Dörwald21d3a322003-05-01 17:45:56 +000021 os.rmdir(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000022
23 def check_tempfile(self, name):
24 # make sure it doesn't already exist:
25 self.failIf(os.path.exists(name),
26 "file already exists for temporary file")
27 # make sure we can create the file
28 open(name, "w")
29 self.files.append(name)
30
31 def test_tempnam(self):
32 if not hasattr(os, "tempnam"):
33 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000034 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000035 r"test_os$")
Fred Drake38c2ef02001-07-17 20:52:51 +000036 self.check_tempfile(os.tempnam())
37
Walter Dörwald21d3a322003-05-01 17:45:56 +000038 name = os.tempnam(test_support.TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000039 self.check_tempfile(name)
40
Walter Dörwald21d3a322003-05-01 17:45:56 +000041 name = os.tempnam(test_support.TESTFN, "pfx")
Fred Drake38c2ef02001-07-17 20:52:51 +000042 self.assert_(os.path.basename(name)[:3] == "pfx")
43 self.check_tempfile(name)
44
45 def test_tmpfile(self):
46 if not hasattr(os, "tmpfile"):
47 return
48 fp = os.tmpfile()
49 fp.write("foobar")
50 fp.seek(0,0)
51 s = fp.read()
52 fp.close()
53 self.assert_(s == "foobar")
54
55 def test_tmpnam(self):
Tim Peters5501b5e2003-04-28 03:13:03 +000056 import sys
Fred Drake38c2ef02001-07-17 20:52:51 +000057 if not hasattr(os, "tmpnam"):
58 return
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +000059 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
Tim Petersd3925062002-04-16 01:27:44 +000060 r"test_os$")
Tim Peters5501b5e2003-04-28 03:13:03 +000061 name = os.tmpnam()
62 if sys.platform in ("win32",):
63 # The Windows tmpnam() seems useless. From the MS docs:
64 #
65 # The character string that tmpnam creates consists of
66 # the path prefix, defined by the entry P_tmpdir in the
67 # file STDIO.H, followed by a sequence consisting of the
68 # digit characters '0' through '9'; the numerical value
69 # of this string is in the range 1 - 65,535. Changing the
70 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not
71 # change the operation of tmpnam.
72 #
73 # The really bizarre part is that, at least under MSVC6,
74 # P_tmpdir is "\\". That is, the path returned refers to
75 # the root of the current drive. That's a terrible place to
76 # put temp files, and, depending on privileges, the user
77 # may not even be able to open a file in the root directory.
78 self.failIf(os.path.exists(name),
79 "file already exists for temporary file")
80 else:
81 self.check_tempfile(name)
Tim Peters87cc0c32001-07-21 01:41:30 +000082
Guido van Rossum98bf58f2001-10-18 20:34:25 +000083# Test attributes on return values from os.*stat* family.
84class StatAttributeTests(unittest.TestCase):
85 def setUp(self):
Walter Dörwald21d3a322003-05-01 17:45:56 +000086 os.mkdir(test_support.TESTFN)
87 self.fname = os.path.join(test_support.TESTFN, "f1")
Guido van Rossum98bf58f2001-10-18 20:34:25 +000088 f = open(self.fname, 'wb')
89 f.write("ABC")
90 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +000091
Guido van Rossum98bf58f2001-10-18 20:34:25 +000092 def tearDown(self):
93 os.unlink(self.fname)
Walter Dörwald21d3a322003-05-01 17:45:56 +000094 os.rmdir(test_support.TESTFN)
Guido van Rossum98bf58f2001-10-18 20:34:25 +000095
96 def test_stat_attributes(self):
97 if not hasattr(os, "stat"):
98 return
99
100 import stat
101 result = os.stat(self.fname)
102
103 # Make sure direct access works
104 self.assertEquals(result[stat.ST_SIZE], 3)
105 self.assertEquals(result.st_size, 3)
106
107 import sys
108
109 # Make sure all the attributes are there
110 members = dir(result)
111 for name in dir(stat):
112 if name[:3] == 'ST_':
113 attr = name.lower()
Martin v. Löwis4d394df2005-01-23 09:19:22 +0000114 if name.endswith("TIME"):
115 def trunc(x): return int(x)
116 else:
117 def trunc(x): return x
118 self.assertEquals(trunc(getattr(result, attr)),
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000119 result[getattr(stat, name)])
120 self.assert_(attr in members)
121
122 try:
123 result[200]
124 self.fail("No exception thrown")
125 except IndexError:
126 pass
127
128 # Make sure that assignment fails
129 try:
130 result.st_mode = 1
131 self.fail("No exception thrown")
132 except TypeError:
133 pass
134
135 try:
136 result.st_rdev = 1
137 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000138 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000139 pass
140
141 try:
142 result.parrot = 1
143 self.fail("No exception thrown")
144 except AttributeError:
145 pass
146
147 # Use the stat_result constructor with a too-short tuple.
148 try:
149 result2 = os.stat_result((10,))
150 self.fail("No exception thrown")
151 except TypeError:
152 pass
153
154 # Use the constructr with a too-long tuple.
155 try:
156 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
157 except TypeError:
158 pass
159
Tim Peterse0c446b2001-10-18 21:57:37 +0000160
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000161 def test_statvfs_attributes(self):
162 if not hasattr(os, "statvfs"):
163 return
164
165 import statvfs
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000166 try:
167 result = os.statvfs(self.fname)
168 except OSError, e:
169 # On AtheOS, glibc always returns ENOSYS
170 import errno
171 if e.errno == errno.ENOSYS:
172 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000173
174 # Make sure direct access works
175 self.assertEquals(result.f_bfree, result[statvfs.F_BFREE])
176
177 # Make sure all the attributes are there
178 members = dir(result)
179 for name in dir(statvfs):
180 if name[:2] == 'F_':
181 attr = name.lower()
182 self.assertEquals(getattr(result, attr),
183 result[getattr(statvfs, name)])
184 self.assert_(attr in members)
185
186 # Make sure that assignment really fails
187 try:
188 result.f_bfree = 1
189 self.fail("No exception thrown")
190 except TypeError:
191 pass
192
193 try:
194 result.parrot = 1
195 self.fail("No exception thrown")
196 except AttributeError:
197 pass
198
199 # Use the constructor with a too-short tuple.
200 try:
201 result2 = os.statvfs_result((10,))
202 self.fail("No exception thrown")
203 except TypeError:
204 pass
205
206 # Use the constructr with a too-long tuple.
207 try:
208 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
209 except TypeError:
210 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000211
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000212from test import mapping_tests
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000213
Walter Dörwald0a6d0ff2004-05-31 16:29:04 +0000214class EnvironTests(mapping_tests.BasicTestMappingProtocol):
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000215 """check that os.environ object conform to mapping protocol"""
Walter Dörwald118f9312004-06-02 18:42:25 +0000216 type2test = None
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000217 def _reference(self):
218 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
219 def _empty_mapping(self):
220 os.environ.clear()
221 return os.environ
222 def setUp(self):
223 self.__save = dict(os.environ)
224 os.environ.clear()
225 def tearDown(self):
226 os.environ.clear()
227 os.environ.update(self.__save)
228
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000229 # Bug 1110478
Martin v. Löwis5510f652005-02-17 21:23:20 +0000230 def test_update2(self):
Martin v. Löwis1d11de62005-01-29 13:29:23 +0000231 if os.path.exists("/bin/sh"):
232 os.environ.update(HELLO="World")
233 value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
234 self.assertEquals(value, "World")
235
Tim Petersc4e09402003-04-25 07:11:48 +0000236class WalkTests(unittest.TestCase):
237 """Tests for os.walk()."""
238
239 def test_traversal(self):
240 import os
241 from os.path import join
242
243 # Build:
244 # TESTFN/ a file kid and two directory kids
245 # tmp1
246 # SUB1/ a file kid and a directory kid
247 # tmp2
248 # SUB11/ no kids
249 # SUB2/ just a file kid
250 # tmp3
Walter Dörwald21d3a322003-05-01 17:45:56 +0000251 sub1_path = join(test_support.TESTFN, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000252 sub11_path = join(sub1_path, "SUB11")
Walter Dörwald21d3a322003-05-01 17:45:56 +0000253 sub2_path = join(test_support.TESTFN, "SUB2")
254 tmp1_path = join(test_support.TESTFN, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000255 tmp2_path = join(sub1_path, "tmp2")
256 tmp3_path = join(sub2_path, "tmp3")
257
258 # Create stuff.
259 os.makedirs(sub11_path)
260 os.makedirs(sub2_path)
261 for path in tmp1_path, tmp2_path, tmp3_path:
262 f = file(path, "w")
263 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
264 f.close()
265
266 # Walk top-down.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000267 all = list(os.walk(test_support.TESTFN))
Tim Petersc4e09402003-04-25 07:11:48 +0000268 self.assertEqual(len(all), 4)
269 # We can't know which order SUB1 and SUB2 will appear in.
270 # Not flipped: TESTFN, SUB1, SUB11, SUB2
271 # flipped: TESTFN, SUB2, SUB1, SUB11
272 flipped = all[0][1][0] != "SUB1"
273 all[0][1].sort()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000274 self.assertEqual(all[0], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000275 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
276 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
277 self.assertEqual(all[3 - 2 * flipped], (sub2_path, [], ["tmp3"]))
278
279 # Prune the search.
280 all = []
Walter Dörwald21d3a322003-05-01 17:45:56 +0000281 for root, dirs, files in os.walk(test_support.TESTFN):
Tim Petersc4e09402003-04-25 07:11:48 +0000282 all.append((root, dirs, files))
283 # Don't descend into SUB1.
284 if 'SUB1' in dirs:
285 # Note that this also mutates the dirs we appended to all!
286 dirs.remove('SUB1')
287 self.assertEqual(len(all), 2)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000288 self.assertEqual(all[0], (test_support.TESTFN, ["SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000289 self.assertEqual(all[1], (sub2_path, [], ["tmp3"]))
290
291 # Walk bottom-up.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000292 all = list(os.walk(test_support.TESTFN, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000293 self.assertEqual(len(all), 4)
294 # We can't know which order SUB1 and SUB2 will appear in.
295 # Not flipped: SUB11, SUB1, SUB2, TESTFN
296 # flipped: SUB2, SUB11, SUB1, TESTFN
297 flipped = all[3][1][0] != "SUB1"
298 all[3][1].sort()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000299 self.assertEqual(all[3], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000300 self.assertEqual(all[flipped], (sub11_path, [], []))
301 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
302 self.assertEqual(all[2 - 2 * flipped], (sub2_path, [], ["tmp3"]))
303
304 # Tear everything down. This is a decent use for bottom-up on
305 # Windows, which doesn't have a recursive delete command. The
306 # (not so) subtlety is that rmdir will fail unless the dir's
307 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000308 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000309 for name in files:
310 os.remove(join(root, name))
311 for name in dirs:
312 os.rmdir(join(root, name))
Walter Dörwald21d3a322003-05-01 17:45:56 +0000313 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000314
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000315class MakedirTests (unittest.TestCase):
316 def setUp(self):
317 os.mkdir(test_support.TESTFN)
318
319 def test_makedir(self):
320 base = test_support.TESTFN
321 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
322 os.makedirs(path) # Should work
323 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
324 os.makedirs(path)
325
326 # Try paths with a '.' in them
327 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
328 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
329 os.makedirs(path)
330 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
331 'dir5', 'dir6')
332 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000333
Tim Peters58eb11c2004-01-18 20:29:55 +0000334
335
336
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000337 def tearDown(self):
338 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
339 'dir4', 'dir5', 'dir6')
340 # If the tests failed, the bottom-most directory ('../dir6')
341 # may not have been created, so we look for the outermost directory
342 # that exists.
343 while not os.path.exists(path) and path != test_support.TESTFN:
344 path = os.path.dirname(path)
345
346 os.removedirs(path)
347
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000348class DevNullTests (unittest.TestCase):
349 def test_devnull(self):
350 f = file(os.devnull, 'w')
351 f.write('hello')
352 f.close()
353 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000354 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000355 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000356
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000357class URandomTests (unittest.TestCase):
358 def test_urandom(self):
359 try:
360 self.assertEqual(len(os.urandom(1)), 1)
361 self.assertEqual(len(os.urandom(10)), 10)
362 self.assertEqual(len(os.urandom(100)), 100)
363 self.assertEqual(len(os.urandom(1000)), 1000)
364 except NotImplementedError:
365 pass
366
Fred Drake2e2be372001-09-20 21:33:42 +0000367def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000368 test_support.run_unittest(
369 TemporaryFileTests,
370 StatAttributeTests,
371 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000372 WalkTests,
373 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000374 DevNullTests,
Tim Peters45e77c52004-08-29 18:47:31 +0000375 URandomTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000376 )
Fred Drake2e2be372001-09-20 21:33:42 +0000377
378if __name__ == "__main__":
379 test_main()