1
# 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
# portable than they had been thought to be.
9
from test import test_support
11
warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, __name__)
12
warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, __name__)
14
# Tests creating TESTFN
15
class FileTests(unittest.TestCase):
17
if os.path.exists(test_support.TESTFN):
18
os.unlink(test_support.TESTFN)
21
def test_access(self):
22
f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
24
self.assert_(os.access(test_support.TESTFN, os.W_OK))
26
def test_closerange(self):
27
first = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
28
# We must allocate two consecutive file descriptors, otherwise
29
# it will mess up other file descriptors (perhaps even the three
31
second = os.dup(first)
34
while second != first + 1:
39
print >> sys.stderr, (
40
"couldn't allocate two consecutive fds, "
41
"skipping test_closerange")
43
first, second = second, os.dup(second)
46
# close a fd that is open, and one that isn't
47
os.closerange(first, first + 2)
48
self.assertRaises(OSError, os.write, first, "a")
50
def test_rename(self):
51
path = unicode(test_support.TESTFN)
52
old = sys.getrefcount(path)
53
self.assertRaises(TypeError, os.rename, path, 0)
54
new = sys.getrefcount(path)
55
self.assertEqual(old, new)
58
class TemporaryFileTests(unittest.TestCase):
61
os.mkdir(test_support.TESTFN)
64
for name in self.files:
66
os.rmdir(test_support.TESTFN)
68
def check_tempfile(self, name):
69
# make sure it doesn't already exist:
70
self.failIf(os.path.exists(name),
71
"file already exists for temporary file")
72
# make sure we can create the file
74
self.files.append(name)
76
def test_tempnam(self):
77
if not hasattr(os, "tempnam"):
79
warnings.filterwarnings("ignore", "tempnam", RuntimeWarning,
81
self.check_tempfile(os.tempnam())
83
name = os.tempnam(test_support.TESTFN)
84
self.check_tempfile(name)
86
name = os.tempnam(test_support.TESTFN, "pfx")
87
self.assert_(os.path.basename(name)[:3] == "pfx")
88
self.check_tempfile(name)
90
def test_tmpfile(self):
91
if not hasattr(os, "tmpfile"):
93
# As with test_tmpnam() below, the Windows implementation of tmpfile()
94
# attempts to create a file in the root directory of the current drive.
95
# On Vista and Server 2008, this test will always fail for normal users
96
# as writing to the root directory requires elevated privileges. With
97
# XP and below, the semantics of tmpfile() are the same, but the user
98
# running the test is more likely to have administrative privileges on
99
# their account already. If that's the case, then os.tmpfile() should
100
# work. In order to make this test as useful as possible, rather than
101
# trying to detect Windows versions or whether or not the user has the
102
# right permissions, just try and create a file in the root directory
103
# and see if it raises a 'Permission denied' OSError. If it does, then
104
# test that a subsequent call to os.tmpfile() raises the same error. If
105
# it doesn't, assume we're on XP or below and the user running the test
106
# has administrative privileges, and proceed with the test as normal.
107
if sys.platform == 'win32':
108
name = '\\python_test_os_test_tmpfile.txt'
109
if os.path.exists(name):
113
except IOError, first:
114
# open() failed, assert tmpfile() fails in the same way.
115
# Although open() raises an IOError and os.tmpfile() raises an
116
# OSError(), 'args' will be (13, 'Permission denied') in both
120
except OSError, second:
121
self.assertEqual(first.args, second.args)
123
self.fail("expected os.tmpfile() to raise OSError")
126
# open() worked, therefore, tmpfile() should work. Close our
127
# dummy file and proceed with the test as normal.
136
self.assert_(s == "foobar")
138
def test_tmpnam(self):
140
if not hasattr(os, "tmpnam"):
142
warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning,
145
if sys.platform in ("win32",):
146
# The Windows tmpnam() seems useless. From the MS docs:
148
# The character string that tmpnam creates consists of
149
# the path prefix, defined by the entry P_tmpdir in the
150
# file STDIO.H, followed by a sequence consisting of the
151
# digit characters '0' through '9'; the numerical value
152
# of this string is in the range 1 - 65,535. Changing the
153
# definitions of L_tmpnam or P_tmpdir in STDIO.H does not
154
# change the operation of tmpnam.
156
# The really bizarre part is that, at least under MSVC6,
157
# P_tmpdir is "\\". That is, the path returned refers to
158
# the root of the current drive. That's a terrible place to
159
# put temp files, and, depending on privileges, the user
160
# may not even be able to open a file in the root directory.
161
self.failIf(os.path.exists(name),
162
"file already exists for temporary file")
164
self.check_tempfile(name)
166
# Test attributes on return values from os.*stat* family.
167
class StatAttributeTests(unittest.TestCase):
169
os.mkdir(test_support.TESTFN)
170
self.fname = os.path.join(test_support.TESTFN, "f1")
171
f = open(self.fname, 'wb')
176
os.unlink(self.fname)
177
os.rmdir(test_support.TESTFN)
179
def test_stat_attributes(self):
180
if not hasattr(os, "stat"):
184
result = os.stat(self.fname)
186
# Make sure direct access works
187
self.assertEquals(result[stat.ST_SIZE], 3)
188
self.assertEquals(result.st_size, 3)
192
# Make sure all the attributes are there
193
members = dir(result)
194
for name in dir(stat):
195
if name[:3] == 'ST_':
197
if name.endswith("TIME"):
198
def trunc(x): return int(x)
200
def trunc(x): return x
201
self.assertEquals(trunc(getattr(result, attr)),
202
result[getattr(stat, name)])
203
self.assert_(attr in members)
207
self.fail("No exception thrown")
211
# Make sure that assignment fails
214
self.fail("No exception thrown")
220
self.fail("No exception thrown")
221
except (AttributeError, TypeError):
226
self.fail("No exception thrown")
227
except AttributeError:
230
# Use the stat_result constructor with a too-short tuple.
232
result2 = os.stat_result((10,))
233
self.fail("No exception thrown")
237
# Use the constructr with a too-long tuple.
239
result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
244
def test_statvfs_attributes(self):
245
if not hasattr(os, "statvfs"):
249
result = os.statvfs(self.fname)
251
# On AtheOS, glibc always returns ENOSYS
253
if e.errno == errno.ENOSYS:
256
# Make sure direct access works
257
self.assertEquals(result.f_bfree, result[3])
259
# Make sure all the attributes are there.
260
members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
261
'ffree', 'favail', 'flag', 'namemax')
262
for value, member in enumerate(members):
263
self.assertEquals(getattr(result, 'f_' + member), result[value])
265
# Make sure that assignment really fails
268
self.fail("No exception thrown")
274
self.fail("No exception thrown")
275
except AttributeError:
278
# Use the constructor with a too-short tuple.
280
result2 = os.statvfs_result((10,))
281
self.fail("No exception thrown")
285
# Use the constructr with a too-long tuple.
287
result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
291
def test_utime_dir(self):
293
st = os.stat(test_support.TESTFN)
294
# round to int, because some systems may support sub-second
295
# time stamps in stat, but not in utime.
296
os.utime(test_support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
297
st2 = os.stat(test_support.TESTFN)
298
self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
300
# Restrict test to Win32, since there is no guarantee other
301
# systems support centiseconds
302
if sys.platform == 'win32':
303
def get_file_system(path):
304
root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
306
kernel32 = ctypes.windll.kernel32
307
buf = ctypes.create_string_buffer("", 100)
308
if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)):
311
if get_file_system(test_support.TESTFN) == "NTFS":
312
def test_1565150(self):
314
os.utime(self.fname, (t1, t1))
315
self.assertEquals(os.stat(self.fname).st_mtime, t1)
317
def test_1686475(self):
318
# Verify that an open file can be stat'ed
320
os.stat(r"c:\pagefile.sys")
321
except WindowsError, e:
322
if e.errno == 2: # file does not exist; cannot run test
324
self.fail("Could not stat pagefile.sys")
326
from test import mapping_tests
328
class EnvironTests(mapping_tests.BasicTestMappingProtocol):
329
"""check that os.environ object conform to mapping protocol"""
331
def _reference(self):
332
return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
333
def _empty_mapping(self):
337
self.__save = dict(os.environ)
341
os.environ.update(self.__save)
344
def test_update2(self):
345
if os.path.exists("/bin/sh"):
346
os.environ.update(HELLO="World")
347
value = os.popen("/bin/sh -c 'echo $HELLO'").read().strip()
348
self.assertEquals(value, "World")
350
class WalkTests(unittest.TestCase):
351
"""Tests for os.walk()."""
353
def test_traversal(self):
355
from os.path import join
359
# TEST1/ a file kid and two directory kids
361
# SUB1/ a file kid and a directory kid
364
# SUB2/ a file kid and a dirsymlink kid
366
# link/ a symlink to TESTFN.2
369
walk_path = join(test_support.TESTFN, "TEST1")
370
sub1_path = join(walk_path, "SUB1")
371
sub11_path = join(sub1_path, "SUB11")
372
sub2_path = join(walk_path, "SUB2")
373
tmp1_path = join(walk_path, "tmp1")
374
tmp2_path = join(sub1_path, "tmp2")
375
tmp3_path = join(sub2_path, "tmp3")
376
link_path = join(sub2_path, "link")
377
t2_path = join(test_support.TESTFN, "TEST2")
378
tmp4_path = join(test_support.TESTFN, "TEST2", "tmp4")
381
os.makedirs(sub11_path)
382
os.makedirs(sub2_path)
384
for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
386
f.write("I'm " + path + " and proud of it. Blame test_os.\n")
388
if hasattr(os, "symlink"):
389
os.symlink(os.path.abspath(t2_path), link_path)
390
sub2_tree = (sub2_path, ["link"], ["tmp3"])
392
sub2_tree = (sub2_path, [], ["tmp3"])
395
all = list(os.walk(walk_path))
396
self.assertEqual(len(all), 4)
397
# We can't know which order SUB1 and SUB2 will appear in.
398
# Not flipped: TESTFN, SUB1, SUB11, SUB2
399
# flipped: TESTFN, SUB2, SUB1, SUB11
400
flipped = all[0][1][0] != "SUB1"
402
self.assertEqual(all[0], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
403
self.assertEqual(all[1 + flipped], (sub1_path, ["SUB11"], ["tmp2"]))
404
self.assertEqual(all[2 + flipped], (sub11_path, [], []))
405
self.assertEqual(all[3 - 2 * flipped], sub2_tree)
409
for root, dirs, files in os.walk(walk_path):
410
all.append((root, dirs, files))
411
# Don't descend into SUB1.
413
# Note that this also mutates the dirs we appended to all!
415
self.assertEqual(len(all), 2)
416
self.assertEqual(all[0], (walk_path, ["SUB2"], ["tmp1"]))
417
self.assertEqual(all[1], sub2_tree)
420
all = list(os.walk(walk_path, topdown=False))
421
self.assertEqual(len(all), 4)
422
# We can't know which order SUB1 and SUB2 will appear in.
423
# Not flipped: SUB11, SUB1, SUB2, TESTFN
424
# flipped: SUB2, SUB11, SUB1, TESTFN
425
flipped = all[3][1][0] != "SUB1"
427
self.assertEqual(all[3], (walk_path, ["SUB1", "SUB2"], ["tmp1"]))
428
self.assertEqual(all[flipped], (sub11_path, [], []))
429
self.assertEqual(all[flipped + 1], (sub1_path, ["SUB11"], ["tmp2"]))
430
self.assertEqual(all[2 - 2 * flipped], sub2_tree)
432
if hasattr(os, "symlink"):
433
# Walk, following symlinks.
434
for root, dirs, files in os.walk(walk_path, followlinks=True):
435
if root == link_path:
436
self.assertEqual(dirs, [])
437
self.assertEqual(files, ["tmp4"])
440
self.fail("Didn't follow symlink with followlinks=True")
443
# Tear everything down. This is a decent use for bottom-up on
444
# Windows, which doesn't have a recursive delete command. The
445
# (not so) subtlety is that rmdir will fail unless the dir's
446
# kids are removed first, so bottom up is essential.
447
for root, dirs, files in os.walk(test_support.TESTFN, topdown=False):
449
os.remove(os.path.join(root, name))
451
dirname = os.path.join(root, name)
452
if not os.path.islink(dirname):
456
os.rmdir(test_support.TESTFN)
458
class MakedirTests (unittest.TestCase):
460
os.mkdir(test_support.TESTFN)
462
def test_makedir(self):
463
base = test_support.TESTFN
464
path = os.path.join(base, 'dir1', 'dir2', 'dir3')
465
os.makedirs(path) # Should work
466
path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
469
# Try paths with a '.' in them
470
self.failUnlessRaises(OSError, os.makedirs, os.curdir)
471
path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
473
path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
481
path = os.path.join(test_support.TESTFN, 'dir1', 'dir2', 'dir3',
482
'dir4', 'dir5', 'dir6')
483
# If the tests failed, the bottom-most directory ('../dir6')
484
# may not have been created, so we look for the outermost directory
486
while not os.path.exists(path) and path != test_support.TESTFN:
487
path = os.path.dirname(path)
491
class DevNullTests (unittest.TestCase):
492
def test_devnull(self):
493
f = file(os.devnull, 'w')
496
f = file(os.devnull, 'r')
497
self.assertEqual(f.read(), '')
500
class URandomTests (unittest.TestCase):
501
def test_urandom(self):
503
self.assertEqual(len(os.urandom(1)), 1)
504
self.assertEqual(len(os.urandom(10)), 10)
505
self.assertEqual(len(os.urandom(100)), 100)
506
self.assertEqual(len(os.urandom(1000)), 1000)
507
# see http://bugs.python.org/issue3708
508
self.assertEqual(len(os.urandom(0.9)), 0)
509
self.assertEqual(len(os.urandom(1.1)), 1)
510
self.assertEqual(len(os.urandom(2.0)), 2)
511
except NotImplementedError:
514
class Win32ErrorTests(unittest.TestCase):
515
def test_rename(self):
516
self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak")
518
def test_remove(self):
519
self.assertRaises(WindowsError, os.remove, test_support.TESTFN)
521
def test_chdir(self):
522
self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
524
def test_mkdir(self):
525
self.assertRaises(WindowsError, os.chdir, test_support.TESTFN)
527
def test_utime(self):
528
self.assertRaises(WindowsError, os.utime, test_support.TESTFN, None)
530
def test_access(self):
531
self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
533
def test_chmod(self):
534
self.assertRaises(WindowsError, os.utime, test_support.TESTFN, 0)
536
if sys.platform != 'win32':
537
class Win32ErrorTests(unittest.TestCase):
541
test_support.run_unittest(
553
if __name__ == "__main__":