blob: cf67ef83ac0b194018b7c14e10a3efa86803945e [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
3# more portable than they had been thought to be.
4
5import os
6import unittest
Jeremy Hyltona7fc21b2001-08-20 20:10:01 +00007import warnings
Fred Drake38c2ef02001-07-17 20:52:51 +00008
Barry Warsaw60f01882001-08-22 19:24:42 +00009warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
10warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
11
Guido van Rossum2e8bba52002-08-22 19:40:33 +000012from test.test_support import TESTFN, run_suite
Fred Drake38c2ef02001-07-17 20:52:51 +000013
Fred Drake38c2ef02001-07-17 20:52:51 +000014class TemporaryFileTests(unittest.TestCase):
15 def setUp(self):
16 self.files = []
17 os.mkdir(TESTFN)
18
19 def tearDown(self):
20 for name in self.files:
21 os.unlink(name)
22 os.rmdir(TESTFN)
23
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
39 name = os.tempnam(TESTFN)
Fred Drake38c2ef02001-07-17 20:52:51 +000040 self.check_tempfile(name)
41
42 name = os.tempnam(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):
57 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$")
Fred Drake38c2ef02001-07-17 20:52:51 +000061 self.check_tempfile(os.tmpnam())
Tim Peters87cc0c32001-07-21 01:41:30 +000062
Guido van Rossum98bf58f2001-10-18 20:34:25 +000063# Test attributes on return values from os.*stat* family.
64class StatAttributeTests(unittest.TestCase):
65 def setUp(self):
66 os.mkdir(TESTFN)
67 self.fname = os.path.join(TESTFN, "f1")
68 f = open(self.fname, 'wb')
69 f.write("ABC")
70 f.close()
Tim Peterse0c446b2001-10-18 21:57:37 +000071
Guido van Rossum98bf58f2001-10-18 20:34:25 +000072 def tearDown(self):
73 os.unlink(self.fname)
74 os.rmdir(TESTFN)
75
76 def test_stat_attributes(self):
77 if not hasattr(os, "stat"):
78 return
79
80 import stat
81 result = os.stat(self.fname)
82
83 # Make sure direct access works
84 self.assertEquals(result[stat.ST_SIZE], 3)
85 self.assertEquals(result.st_size, 3)
86
87 import sys
88
89 # Make sure all the attributes are there
90 members = dir(result)
91 for name in dir(stat):
92 if name[:3] == 'ST_':
93 attr = name.lower()
94 self.assertEquals(getattr(result, attr),
95 result[getattr(stat, name)])
96 self.assert_(attr in members)
97
98 try:
99 result[200]
100 self.fail("No exception thrown")
101 except IndexError:
102 pass
103
104 # Make sure that assignment fails
105 try:
106 result.st_mode = 1
107 self.fail("No exception thrown")
108 except TypeError:
109 pass
110
111 try:
112 result.st_rdev = 1
113 self.fail("No exception thrown")
Guido van Rossum1fff8782001-10-18 21:19:31 +0000114 except (AttributeError, TypeError):
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000115 pass
116
117 try:
118 result.parrot = 1
119 self.fail("No exception thrown")
120 except AttributeError:
121 pass
122
123 # Use the stat_result constructor with a too-short tuple.
124 try:
125 result2 = os.stat_result((10,))
126 self.fail("No exception thrown")
127 except TypeError:
128 pass
129
130 # Use the constructr with a too-long tuple.
131 try:
132 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
133 except TypeError:
134 pass
135
Tim Peterse0c446b2001-10-18 21:57:37 +0000136
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000137 def test_statvfs_attributes(self):
138 if not hasattr(os, "statvfs"):
139 return
140
141 import statvfs
Martin v. Löwisf90ae202002-06-11 06:22:31 +0000142 try:
143 result = os.statvfs(self.fname)
144 except OSError, e:
145 # On AtheOS, glibc always returns ENOSYS
146 import errno
147 if e.errno == errno.ENOSYS:
148 return
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000149
150 # Make sure direct access works
151 self.assertEquals(result.f_bfree, result[statvfs.F_BFREE])
152
153 # Make sure all the attributes are there
154 members = dir(result)
155 for name in dir(statvfs):
156 if name[:2] == 'F_':
157 attr = name.lower()
158 self.assertEquals(getattr(result, attr),
159 result[getattr(statvfs, name)])
160 self.assert_(attr in members)
161
162 # Make sure that assignment really fails
163 try:
164 result.f_bfree = 1
165 self.fail("No exception thrown")
166 except TypeError:
167 pass
168
169 try:
170 result.parrot = 1
171 self.fail("No exception thrown")
172 except AttributeError:
173 pass
174
175 # Use the constructor with a too-short tuple.
176 try:
177 result2 = os.statvfs_result((10,))
178 self.fail("No exception thrown")
179 except TypeError:
180 pass
181
182 # Use the constructr with a too-long tuple.
183 try:
184 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
185 except TypeError:
186 pass
Fred Drake38c2ef02001-07-17 20:52:51 +0000187
Raymond Hettinger2c2d3222003-03-09 07:05:43 +0000188from test_userdict import TestMappingProtocol
189
190class EnvironTests(TestMappingProtocol):
191 """check that os.environ object conform to mapping protocol"""
192 _tested_class = None
193 def _reference(self):
194 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
195 def _empty_mapping(self):
196 os.environ.clear()
197 return os.environ
198 def setUp(self):
199 self.__save = dict(os.environ)
200 os.environ.clear()
201 def tearDown(self):
202 os.environ.clear()
203 os.environ.update(self.__save)
204
Tim Petersc4e09402003-04-25 07:11:48 +0000205class WalkTests(unittest.TestCase):
206 """Tests for os.walk()."""
207
208 def test_traversal(self):
209 import os
210 from os.path import join
211
212 # Build:
213 # TESTFN/ a file kid and two directory kids
214 # tmp1
215 # SUB1/ a file kid and a directory kid
216 # tmp2
217 # SUB11/ no kids
218 # SUB2/ just a file kid
219 # tmp3
220 sub1_path = join(TESTFN, "SUB1")
221 sub11_path = join(sub1_path, "SUB11")
222 sub2_path = join(TESTFN, "SUB2")
223 tmp1_path = join(TESTFN, "tmp1")
224 tmp2_path = join(sub1_path, "tmp2")
225 tmp3_path = join(sub2_path, "tmp3")
226
227 # Create stuff.
228 os.makedirs(sub11_path)
229 os.makedirs(sub2_path)
230 for path in tmp1_path, tmp2_path, tmp3_path:
231 f = file(path, "w")
232 f.write("I'm " + path + " and proud of it. Blame test_os.\n")
233 f.close()
234
235 # Walk top-down.
236 all = list(os.walk(TESTFN))
237 self.assertEqual(len(all), 4)
238 # We can't know which order SUB1 and SUB2 will appear in.
239 # Not flipped: TESTFN, SUB1, SUB11, SUB2
240 # flipped: TESTFN, SUB2, SUB1, SUB11
241 flipped = all[0][1][0] != "SUB1"
242 all[0][1].sort()
243 self.assertEqual(all[0], (TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
244 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
245 self.assertEqual(all[2 + flipped], (sub11_path, [], []))
246 self.assertEqual(all[3 - 2 * flipped], (sub2_path, [], ["tmp3"]))
247
248 # Prune the search.
249 all = []
250 for root, dirs, files in os.walk(TESTFN):
251 all.append((root, dirs, files))
252 # Don't descend into SUB1.
253 if 'SUB1' in dirs:
254 # Note that this also mutates the dirs we appended to all!
255 dirs.remove('SUB1')
256 self.assertEqual(len(all), 2)
257 self.assertEqual(all[0], (TESTFN, ["SUB2"], ["tmp1"]))
258 self.assertEqual(all[1], (sub2_path, [], ["tmp3"]))
259
260 # Walk bottom-up.
261 all = list(os.walk(TESTFN, topdown=False))
262 self.assertEqual(len(all), 4)
263 # We can't know which order SUB1 and SUB2 will appear in.
264 # Not flipped: SUB11, SUB1, SUB2, TESTFN
265 # flipped: SUB2, SUB11, SUB1, TESTFN
266 flipped = all[3][1][0] != "SUB1"
267 all[3][1].sort()
268 self.assertEqual(all[3], (TESTFN, ["SUB1", "SUB2"], ["tmp1"]))
269 self.assertEqual(all[flipped], (sub11_path, [], []))
270 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
271 self.assertEqual(all[2 - 2 * flipped], (sub2_path, [], ["tmp3"]))
272
273 # Tear everything down. This is a decent use for bottom-up on
274 # Windows, which doesn't have a recursive delete command. The
275 # (not so) subtlety is that rmdir will fail unless the dir's
276 # kids are removed first, so bottom up is essential.
277 for root, dirs, files in os.walk(TESTFN, topdown=False):
278 for name in files:
279 os.remove(join(root, name))
280 for name in dirs:
281 os.rmdir(join(root, name))
282 os.rmdir(TESTFN)
283
Fred Drake2e2be372001-09-20 21:33:42 +0000284def test_main():
Guido van Rossum2e8bba52002-08-22 19:40:33 +0000285 suite = unittest.TestSuite()
Tim Petersc4e09402003-04-25 07:11:48 +0000286 for cls in (TemporaryFileTests,
287 StatAttributeTests,
288 EnvironTests,
289 WalkTests,
290 ):
291 suite.addTest(unittest.makeSuite(cls))
Guido van Rossum2e8bba52002-08-22 19:40:33 +0000292 run_suite(suite)
Fred Drake2e2be372001-09-20 21:33:42 +0000293
294if __name__ == "__main__":
295 test_main()