test_file.py 2.55 KB
Newer Older
1
import sys
2
import os
3
from array import array
4

5
from test_support import verify, TESTFN, TestFailed
6 7 8 9 10 11 12 13 14 15
from UserList import UserList

# verify writelines with instance sequence
l = UserList(['1', '2'])
f = open(TESTFN, 'wb')
f.writelines(l)
f.close()
f = open(TESTFN, 'rb')
buf = f.read()
f.close()
16
verify(buf == '12')
17

18 19 20 21 22 23 24
# verify readinto
a = array('c', 'x'*10)
f = open(TESTFN, 'rb')
n = f.readinto(a)
f.close()
verify(buf == a.tostring()[:n])

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
# verify writelines with integers
f = open(TESTFN, 'wb')
try:
    f.writelines([1, 2, 3])
except TypeError:
    pass
else:
    print "writelines accepted sequence of integers"
f.close()

# verify writelines with integers in UserList
f = open(TESTFN, 'wb')
l = UserList([1,2,3])
try:
    f.writelines(l)
except TypeError:
    pass
else:
    print "writelines accepted sequence of integers"
f.close()

# verify writelines with non-string object
class NonString: pass

f = open(TESTFN, 'wb')
try:
    f.writelines([NonString(), NonString()])
except TypeError:
    pass
else:
    print "writelines accepted sequence of non-string objects"
f.close()
57

58
# verify that we get a sensible error message for bad mode argument
59 60 61 62
bad_mode = "qwerty"
try:
    open(TESTFN, bad_mode)
except IOError, msg:
63 64 65 66 67 68
    if msg[0] != 0:
        s = str(msg)
        if s.find(TESTFN) != -1 or s.find(bad_mode) == -1:
            print "bad error message for invalid mode: %s" % s
    # if msg[0] == 0, we're probably on Windows where there may be
    # no obvious way to discover why open() failed.
69 70 71
else:
    print "no error for invalid mode: %s" % bad_mode

72 73
f = open(TESTFN)
if f.name != TESTFN:
74
    raise TestFailed, 'file.name should be "%s"' % TESTFN
75
if f.isatty():
76
    raise TestFailed, 'file.isatty() should be false'
77 78

if f.closed:
79
    raise TestFailed, 'file.closed should be false'
80

81 82 83 84 85
try:
    f.readinto("")
except TypeError:
    pass
else:
86
    raise TestFailed, 'file.readinto("") should raise a TypeError'
87

88 89
f.close()
if not f.closed:
90
    raise TestFailed, 'file.closed should be true'
91

92 93 94 95 96
methods = ['fileno', 'flush', 'isatty', 'read', 'readinto', 'readline', 'readlines', 'seek', 'tell', 'truncate', 'write', 'xreadlines' ]
if sys.platform.startswith('atheos'):
    methods.remove('truncate')

for methodname in methods:
97 98 99 100 101 102
    method = getattr(f, methodname)
    try:
        method()
    except ValueError:
        pass
    else:
103
        raise TestFailed, 'file.%s() on a closed file should raise a ValueError' % methodname
104 105 106 107 108 109

try:
    f.writelines([])
except ValueError:
    pass
else:
110
    raise TestFailed, 'file.writelines([]) on a closed file should raise a ValueError'
111

112
os.unlink(TESTFN)