blob: 472d13fd092a1ce285d2bdd0fb72a7fbcbb28ee3 [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
Tim Petersc4e09402003-04-25 07:11:48 +0000229class WalkTests(unittest.TestCase):
230 """Tests for os.walk()."""
231
232 def test_traversal(self):
233 import os
234 from os.path import join
235
236 # Build:
237 # TESTFN/ a file kid and two directory kids
238 # tmp1
239 # SUB1/ a file kid and a directory kid
240 # tmp2
241 # SUB11/ no kids
242 # SUB2/ just a file kid
243 # tmp3
Walter Dörwald21d3a322003-05-01 17:45:56 +0000244 sub1_path = join(test_support.TESTFN, "SUB1")
Tim Petersc4e09402003-04-25 07:11:48 +0000245 sub11_path = join(sub1_path, "SUB11")
Walter Dörwald21d3a322003-05-01 17:45:56 +0000246 sub2_path = join(test_support.TESTFN, "SUB2")
247 tmp1_path = join(test_support.TESTFN, "tmp1")
Tim Petersc4e09402003-04-25 07:11:48 +0000248 tmp2_path = join(sub1_path, "tmp2")
249 tmp3_path = join(sub2_path, "tmp3")
250
251 # Create stuff.
252 os.makedirs(sub11_path)
253 os.makedirs(sub2_path)
254 for path in tmp1_path, tmp2_path, tmp3_path:
255 f = file(path, "w")
256 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
257 f.close()
258
259 # Walk top-down.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000260 all = list(os.walk(test_support.TESTFN))
Tim Petersc4e09402003-04-25 07:11:48 +0000261 self.assertEqual(len(all), 4)
262 # We can't know which order SUB1 and SUB2 will appear in.
263 # Not flipped: TESTFN, SUB1, SUB11, SUB2
264 # flipped: TESTFN, SUB2, SUB1, SUB11
265 flipped = all[0][1][0] != "SUB1"
266 all[0][1].sort()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000267 self.assertEqual(all[0], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000268 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
269 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
270 self.assertEqual(all[3 - 2 * flipped], (sub2_path, [], ["tmp3"]))
271
272 # Prune the search.
273 all = []
Walter Dörwald21d3a322003-05-01 17:45:56 +0000274 for root, dirs, files in os.walk(test_support.TESTFN):
Tim Petersc4e09402003-04-25 07:11:48 +0000275 all.append((root, dirs, files))
276 # Don't descend into SUB1.
277 if 'SUB1' in dirs:
278 # Note that this also mutates the dirs we appended to all!
279 dirs.remove('SUB1')
280 self.assertEqual(len(all), 2)
Walter Dörwald21d3a322003-05-01 17:45:56 +0000281 self.assertEqual(all[0], (test_support.TESTFN, ["SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000282 self.assertEqual(all[1], (sub2_path, [], ["tmp3"]))
283
284 # Walk bottom-up.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000285 all = list(os.walk(test_support.TESTFN, topdown=False))
Tim Petersc4e09402003-04-25 07:11:48 +0000286 self.assertEqual(len(all), 4)
287 # We can't know which order SUB1 and SUB2 will appear in.
288 # Not flipped: SUB11, SUB1, SUB2, TESTFN
289 # flipped: SUB2, SUB11, SUB1, TESTFN
290 flipped = all[3][1][0] != "SUB1"
291 all[3][1].sort()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000292 self.assertEqual(all[3], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
Tim Petersc4e09402003-04-25 07:11:48 +0000293 self.assertEqual(all[flipped], (sub11_path, [], []))
294 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
295 self.assertEqual(all[2 - 2 * flipped], (sub2_path, [], ["tmp3"]))
296
297 # Tear everything down. This is a decent use for bottom-up on
298 # Windows, which doesn't have a recursive delete command. The
299 # (not so) subtlety is that rmdir will fail unless the dir's
300 # kids are removed first, so bottom up is essential.
Walter Dörwald21d3a322003-05-01 17:45:56 +0000301 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
Tim Petersc4e09402003-04-25 07:11:48 +0000302 for name in files:
303 os.remove(join(root, name))
304 for name in dirs:
305 os.rmdir(join(root, name))
Walter Dörwald21d3a322003-05-01 17:45:56 +0000306 os.rmdir(test_support.TESTFN)
Tim Petersc4e09402003-04-25 07:11:48 +0000307
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000308class MakedirTests (unittest.TestCase):
309 def setUp(self):
310 os.mkdir(test_support.TESTFN)
311
312 def test_makedir(self):
313 base = test_support.TESTFN
314 path = os.path.join(base, 'dir1', 'dir2', 'dir3')
315 os.makedirs(path) # Should work
316 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
317 os.makedirs(path)
318
319 # Try paths with a '.' in them
320 self.failUnlessRaises(OSError, os.makedirs, os.curdir)
321 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
322 os.makedirs(path)
323 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
324 'dir5', 'dir6')
325 os.makedirs(path)
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000326
Tim Peters58eb11c2004-01-18 20:29:55 +0000327
328
329
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000330 def tearDown(self):
331 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
332 'dir4', 'dir5', 'dir6')
333 # If the tests failed, the bottom-most directory ('../dir6')
334 # may not have been created, so we look for the outermost directory
335 # that exists.
336 while not os.path.exists(path) and path != test_support.TESTFN:
337 path = os.path.dirname(path)
338
339 os.removedirs(path)
340
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000341class DevNullTests (unittest.TestCase):
342 def test_devnull(self):
343 f = file(os.devnull, 'w')
344 f.write('hello')
345 f.close()
346 f = file(os.devnull, 'r')
Tim Peters4182cfd2004-06-08 20:34:34 +0000347 self.assertEqual(f.read(), '')
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000348 f.close()
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000349
Martin v. Löwisdc3883f2004-08-29 15:46:35 +0000350class URandomTests (unittest.TestCase):
351 def test_urandom(self):
352 try:
353 self.assertEqual(len(os.urandom(1)), 1)
354 self.assertEqual(len(os.urandom(10)), 10)
355 self.assertEqual(len(os.urandom(100)), 100)
356 self.assertEqual(len(os.urandom(1000)), 1000)
357 except NotImplementedError:
358 pass
359
Fred Drake2e2be372001-09-20 21:33:42 +0000360def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000361 test_support.run_unittest(
362 TemporaryFileTests,
363 StatAttributeTests,
364 EnvironTests,
Andrew M. Kuchlingb386f6a2003-12-23 16:36:11 +0000365 WalkTests,
366 MakedirTests,
Martin v. Löwisbdec50f2004-06-08 08:29:33 +0000367 DevNullTests,
Tim Peters45e77c52004-08-29 18:47:31 +0000368 URandomTests
Walter Dörwald21d3a322003-05-01 17:45:56 +0000369 )
Fred Drake2e2be372001-09-20 21:33:42 +0000370
371if __name__ == "__main__":
372 test_main()