0001 # As a test suite for the os module, this is woefully inadequate, but this 0002 # does add tests for a few functions which have been determined to be more 0003 # portable than they had been thought to be. 0004 0005 import os 0006 import unittest 0007 import warnings 0008 from test import test_support 0009 0010 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__) 0011 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__) 0012 0013 class TemporaryFileTests(unittest.TestCase): 0014 def setUp(self): 0015 self.files = [] 0016 os.mkdir(test_support.TESTFN) 0017 0018 def tearDown(self): 0019 for name in self.files: 0020 os.unlink(name) 0021 os.rmdir(test_support.TESTFN) 0022 0023 def check_tempfile(self, name): 0024 # make sure it doesn't already exist: 0025 self.failIf(os.path.exists(name), 0026 "file already exists for temporary file") 0027 # make sure we can create the file 0028 open(name, "w") 0029 self.files.append(name) 0030 0031 def test_tempnam(self): 0032 if not hasattr(os, "tempnam"): 0033 return 0034 warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, 0035 r"test_os$") 0036 self.check_tempfile(os.tempnam()) 0037 0038 name = os.tempnam(test_support.TESTFN) 0039 self.check_tempfile(name) 0040 0041 name = os.tempnam(test_support.TESTFN, "pfx") 0042 self.assert_(os.path.basename(name)[:3] == "pfx") 0043 self.check_tempfile(name) 0044 0045 def test_tmpfile(self): 0046 if not hasattr(os, "tmpfile"): 0047 return 0048 fp = os.tmpfile() 0049 fp.write("foobar") 0050 fp.seek(0,0) 0051 s = fp.read() 0052 fp.close() 0053 self.assert_(s == "foobar") 0054 0055 def test_tmpnam(self): 0056 import sys 0057 if not hasattr(os, "tmpnam"): 0058 return 0059 warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, 0060 r"test_os$") 0061 name = os.tmpnam() 0062 if sys.platform in ("win32",): 0063 # The Windows tmpnam() seems useless. From the MS docs: 0064 # 0065 # The character string that tmpnam creates consists of 0066 # the path prefix, defined by the entry P_tmpdir in the 0067 # file STDIO.H, followed by a sequence consisting of the 0068 # digit characters '0' through '9'; the numerical value 0069 # of this string is in the range 1 - 65,535. Changing the 0070 # definitions of L_tmpnam or P_tmpdir in STDIO.H does not 0071 # change the operation of tmpnam. 0072 # 0073 # The really bizarre part is that, at least under MSVC6, 0074 # P_tmpdir is "\\". That is, the path returned refers to 0075 # the root of the current drive. That's a terrible place to 0076 # put temp files, and, depending on privileges, the user 0077 # may not even be able to open a file in the root directory. 0078 self.failIf(os.path.exists(name), 0079 "file already exists for temporary file") 0080 else: 0081 self.check_tempfile(name) 0082 0083 # Test attributes on return values from os.*stat* family. 0084 class StatAttributeTests(unittest.TestCase): 0085 def setUp(self): 0086 os.mkdir(test_support.TESTFN) 0087 self.fname = os.path.join(test_support.TESTFN, "f1") 0088 f = open(self.fname, 'wb') 0089 f.write("ABC") 0090 f.close() 0091 0092 def tearDown(self): 0093 os.unlink(self.fname) 0094 os.rmdir(test_support.TESTFN) 0095 0096 def test_stat_attributes(self): 0097 if not hasattr(os, "stat"): 0098 return 0099 0100 import stat 0101 result = os.stat(self.fname) 0102 0103 # Make sure direct access works 0104 self.assertEquals(result[stat.ST_SIZE], 3) 0105 self.assertEquals(result.st_size, 3) 0106 0107 import sys 0108 0109 # Make sure all the attributes are there 0110 members = dir(result) 0111 for name in dir(stat): 0112 if name[:3] == 'ST_': 0113 attr = name.lower() 0114 self.assertEquals(getattr(result, attr), 0115 result[getattr(stat, name)]) 0116 self.assert_(attr in members) 0117 0118 try: 0119 result[200] 0120 self.fail("No exception thrown") 0121 except IndexError: 0122 pass 0123 0124 # Make sure that assignment fails 0125 try: 0126 result.st_mode = 1 0127 self.fail("No exception thrown") 0128 except TypeError: 0129 pass 0130 0131 try: 0132 result.st_rdev = 1 0133 self.fail("No exception thrown") 0134 except (AttributeError, TypeError): 0135 pass 0136 0137 try: 0138 result.parrot = 1 0139 self.fail("No exception thrown") 0140 except AttributeError: 0141 pass 0142 0143 # Use the stat_result constructor with a too-short tuple. 0144 try: 0145 result2 = os.stat_result((10,)) 0146 self.fail("No exception thrown") 0147 except TypeError: 0148 pass 0149 0150 # Use the constructr with a too-long tuple. 0151 try: 0152 result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14)) 0153 except TypeError: 0154 pass 0155 0156 0157 def test_statvfs_attributes(self): 0158 if not hasattr(os, "statvfs"): 0159 return 0160 0161 import statvfs 0162 try: 0163 result = os.statvfs(self.fname) 0164 except OSError, e: 0165 # On AtheOS, glibc always returns ENOSYS 0166 import errno 0167 if e.errno == errno.ENOSYS: 0168 return 0169 0170 # Make sure direct access works 0171 self.assertEquals(result.f_bfree, result[statvfs.F_BFREE]) 0172 0173 # Make sure all the attributes are there 0174 members = dir(result) 0175 for name in dir(statvfs): 0176 if name[:2] == 'F_': 0177 attr = name.lower() 0178 self.assertEquals(getattr(result, attr), 0179 result[getattr(statvfs, name)]) 0180 self.assert_(attr in members) 0181 0182 # Make sure that assignment really fails 0183 try: 0184 result.f_bfree = 1 0185 self.fail("No exception thrown") 0186 except TypeError: 0187 pass 0188 0189 try: 0190 result.parrot = 1 0191 self.fail("No exception thrown") 0192 except AttributeError: 0193 pass 0194 0195 # Use the constructor with a too-short tuple. 0196 try: 0197 result2 = os.statvfs_result((10,)) 0198 self.fail("No exception thrown") 0199 except TypeError: 0200 pass 0201 0202 # Use the constructr with a too-long tuple. 0203 try: 0204 result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14)) 0205 except TypeError: 0206 pass 0207 0208 from test import mapping_tests 0209 0210 class EnvironTests(mapping_tests.BasicTestMappingProtocol): 0211 """check that os.environ object conform to mapping protocol""" 0212 type2test = None 0213 def _reference(self): 0214 return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"} 0215 def _empty_mapping(self): 0216 os.environ.clear() 0217 return os.environ 0218 def setUp(self): 0219 self.__save = dict(os.environ) 0220 os.environ.clear() 0221 def tearDown(self): 0222 os.environ.clear() 0223 os.environ.update(self.__save) 0224 0225 class WalkTests(unittest.TestCase): 0226 """Tests for os.walk().""" 0227 0228 def test_traversal(self): 0229 import os 0230 from os.path import join 0231 0232 # Build: 0233 # TESTFN/ a file kid and two directory kids 0234 # tmp1 0235 # SUB1/ a file kid and a directory kid 0236 # tmp2 0237 # SUB11/ no kids 0238 # SUB2/ just a file kid 0239 # tmp3 0240 sub1_path = join(test_support.TESTFN, "SUB1") 0241 sub11_path = join(sub1_path, "SUB11") 0242 sub2_path = join(test_support.TESTFN, "SUB2") 0243 tmp1_path = join(test_support.TESTFN, "tmp1") 0244 tmp2_path = join(sub1_path, "tmp2") 0245 tmp3_path = join(sub2_path, "tmp3") 0246 0247 # Create stuff. 0248 os.makedirs(sub11_path) 0249 os.makedirs(sub2_path) 0250 for path in tmp1_path, tmp2_path, tmp3_path: 0251 f = file(path, "w") 0252 f.write("I'm " + path + " and proud of it. Blame test_os.\n") 0253 f.close() 0254 0255 # Walk top-down. 0256 all = list(os.walk(test_support.TESTFN)) 0257 self.assertEqual(len(all), 4) 0258 # We can't know which order SUB1 and SUB2 will appear in. 0259 # Not flipped: TESTFN, SUB1, SUB11, SUB2 0260 # flipped: TESTFN, SUB2, SUB1, SUB11 0261 flipped = all[0][1][0] != "SUB1" 0262 all[0][1].sort() 0263 self.assertEqual(all[0], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"])) 0264 self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"])) 0265 self.assertEqual(all[2 + flipped], (sub11_path, [], [])) 0266 self.assertEqual(all[3 - 2 * flipped], (sub2_path, [], ["tmp3"])) 0267 0268 # Prune the search. 0269 all = [] 0270 for root, dirs, files in os.walk(test_support.TESTFN): 0271 all.append((root, dirs, files)) 0272 # Don't descend into SUB1. 0273 if 'SUB1' in dirs: 0274 # Note that this also mutates the dirs we appended to all! 0275 dirs.remove('SUB1') 0276 self.assertEqual(len(all), 2) 0277 self.assertEqual(all[0], (test_support.TESTFN, ["SUB2"], ["tmp1"])) 0278 self.assertEqual(all[1], (sub2_path, [], ["tmp3"])) 0279 0280 # Walk bottom-up. 0281 all = list(os.walk(test_support.TESTFN, topdown=False)) 0282 self.assertEqual(len(all), 4) 0283 # We can't know which order SUB1 and SUB2 will appear in. 0284 # Not flipped: SUB11, SUB1, SUB2, TESTFN 0285 # flipped: SUB2, SUB11, SUB1, TESTFN 0286 flipped = all[3][1][0] != "SUB1" 0287 all[3][1].sort() 0288 self.assertEqual(all[3], (test_support.TESTFN, ["SUB1", "SUB2"], ["tmp1"])) 0289 self.assertEqual(all[flipped], (sub11_path, [], [])) 0290 self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"])) 0291 self.assertEqual(all[2 - 2 * flipped], (sub2_path, [], ["tmp3"])) 0292 0293 # Tear everything down. This is a decent use for bottom-up on 0294 # Windows, which doesn't have a recursive delete command. The 0295 # (not so) subtlety is that rmdir will fail unless the dir's 0296 # kids are removed first, so bottom up is essential. 0297 for root, dirs, files in os.walk(test_support.TESTFN, topdown=False): 0298 for name in files: 0299 os.remove(join(root, name)) 0300 for name in dirs: 0301 os.rmdir(join(root, name)) 0302 os.rmdir(test_support.TESTFN) 0303 0304 class MakedirTests (unittest.TestCase): 0305 def setUp(self): 0306 os.mkdir(test_support.TESTFN) 0307 0308 def test_makedir(self): 0309 base = test_support.TESTFN 0310 path = os.path.join(base, 'dir1', 'dir2', 'dir3') 0311 os.makedirs(path) # Should work 0312 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4') 0313 os.makedirs(path) 0314 0315 # Try paths with a '.' in them 0316 self.failUnlessRaises(OSError, os.makedirs, os.curdir) 0317 path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir) 0318 os.makedirs(path) 0319 path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4', 0320 'dir5', 'dir6') 0321 os.makedirs(path) 0322 0323 0324 0325 0326 def tearDown(self): 0327 path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3', 0328 'dir4', 'dir5', 'dir6') 0329 # If the tests failed, the bottom-most directory ('../dir6') 0330 # may not have been created, so we look for the outermost directory 0331 # that exists. 0332 while not os.path.exists(path) and path != test_support.TESTFN: 0333 path = os.path.dirname(path) 0334 0335 os.removedirs(path) 0336 0337 class DevNullTests (unittest.TestCase): 0338 def test_devnull(self): 0339 f = file(os.devnull, 'w') 0340 f.write('hello') 0341 f.close() 0342 f = file(os.devnull, 'r') 0343 self.assertEqual(f.read(), '') 0344 f.close() 0345 0346 class URandomTests (unittest.TestCase): 0347 def test_urandom(self): 0348 try: 0349 self.assertEqual(len(os.urandom(1)), 1) 0350 self.assertEqual(len(os.urandom(10)), 10) 0351 self.assertEqual(len(os.urandom(100)), 100) 0352 self.assertEqual(len(os.urandom(1000)), 1000) 0353 except NotImplementedError: 0354 pass 0355 0356 def test_main(): 0357 test_support.run_unittest( 0358 TemporaryFileTests, 0359 StatAttributeTests, 0360 EnvironTests, 0361 WalkTests, 0362 MakedirTests, 0363 DevNullTests, 0364 URandomTests 0365 ) 0366 0367 if __name__ == "__main__": 0368 test_main() 0369
Generated by PyXR 0.9.4