Mass check-in after untabifying all files that need it.

This commit is contained in:
Guido van Rossum 1998-03-26 19:42:58 +00:00
parent cd0f59ea08
commit 41360a4696
36 changed files with 919 additions and 919 deletions

View file

@ -30,58 +30,58 @@ import test_support
def main(): def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], 'vgqx') opts, args = getopt.getopt(sys.argv[1:], 'vgqx')
except getopt.error, msg: except getopt.error, msg:
print msg print msg
print __doc__ print __doc__
return 2 return 2
verbose = 0 verbose = 0
quiet = 0 quiet = 0
generate = 0 generate = 0
exclude = 0 exclude = 0
for o, a in opts: for o, a in opts:
if o == '-v': verbose = verbose+1 if o == '-v': verbose = verbose+1
if o == '-q': quiet = 1; verbose = 0 if o == '-q': quiet = 1; verbose = 0
if o == '-g': generate = 1 if o == '-g': generate = 1
if o == '-x': exclude = 1 if o == '-x': exclude = 1
if generate and verbose: if generate and verbose:
print "-g and -v don't go together!" print "-g and -v don't go together!"
return 2 return 2
good = [] good = []
bad = [] bad = []
skipped = [] skipped = []
for i in range(len(args)): for i in range(len(args)):
# Strip trailing ".py" from arguments # Strip trailing ".py" from arguments
if args[i][-3:] == '.py': if args[i][-3:] == '.py':
args[i] = args[i][:-3] args[i] = args[i][:-3]
if exclude: if exclude:
nottests[:0] = args nottests[:0] = args
args = [] args = []
tests = args or findtests() tests = args or findtests()
test_support.verbose = verbose # Tell tests to be moderately quiet test_support.verbose = verbose # Tell tests to be moderately quiet
for test in tests: for test in tests:
if not quiet: if not quiet:
print test print test
ok = runtest(test, generate, verbose) ok = runtest(test, generate, verbose)
if ok > 0: if ok > 0:
good.append(test) good.append(test)
elif ok == 0: elif ok == 0:
bad.append(test) bad.append(test)
else: else:
if not quiet: if not quiet:
print "test", test, print "test", test,
print "skipped -- an optional feature could not be imported" print "skipped -- an optional feature could not be imported"
skipped.append(test) skipped.append(test)
if good and not quiet: if good and not quiet:
if not bad and not skipped and len(good) > 1: if not bad and not skipped and len(good) > 1:
print "All", print "All",
print count(len(good), "test"), "OK." print count(len(good), "test"), "OK."
if bad: if bad:
print count(len(bad), "test"), "failed:", print count(len(bad), "test"), "failed:",
print string.join(bad) print string.join(bad)
if skipped and not quiet: if skipped and not quiet:
print count(len(skipped), "test"), "skipped:", print count(len(skipped), "test"), "skipped:",
print string.join(skipped) print string.join(skipped)
return len(bad) > 0 return len(bad) > 0
stdtests = [ stdtests = [
@ -105,10 +105,10 @@ def findtests():
names = os.listdir(testdir) names = os.listdir(testdir)
tests = [] tests = []
for name in names: for name in names:
if name[:5] == "test_" and name[-3:] == ".py": if name[:5] == "test_" and name[-3:] == ".py":
modname = name[:-3] modname = name[:-3]
if modname not in stdtests and modname not in nottests: if modname not in stdtests and modname not in nottests:
tests.append(modname) tests.append(modname)
tests.sort() tests.sort()
return stdtests + tests return stdtests + tests
@ -118,76 +118,76 @@ def runtest(test, generate, verbose):
outputdir = os.path.join(testdir, "output") outputdir = os.path.join(testdir, "output")
outputfile = os.path.join(outputdir, test) outputfile = os.path.join(outputdir, test)
try: try:
if generate: if generate:
cfp = open(outputfile, "w") cfp = open(outputfile, "w")
elif verbose: elif verbose:
cfp = sys.stdout cfp = sys.stdout
else: else:
cfp = Compare(outputfile) cfp = Compare(outputfile)
except IOError: except IOError:
cfp = None cfp = None
print "Warning: can't open", outputfile print "Warning: can't open", outputfile
try: try:
save_stdout = sys.stdout save_stdout = sys.stdout
try: try:
if cfp: if cfp:
sys.stdout = cfp sys.stdout = cfp
print test # Output file starts with test name print test # Output file starts with test name
__import__(test, globals(), locals(), []) __import__(test, globals(), locals(), [])
finally: finally:
sys.stdout = save_stdout sys.stdout = save_stdout
except ImportError, msg: except ImportError, msg:
return -1 return -1
except KeyboardInterrupt, v: except KeyboardInterrupt, v:
raise KeyboardInterrupt, v, sys.exc_info()[2] raise KeyboardInterrupt, v, sys.exc_info()[2]
except test_support.TestFailed, msg: except test_support.TestFailed, msg:
print "test", test, "failed --", msg print "test", test, "failed --", msg
return 0 return 0
except: except:
type, value = sys.exc_info()[:2] type, value = sys.exc_info()[:2]
print "test", test, "crashed --", type, ":", value print "test", test, "crashed --", type, ":", value
if verbose: if verbose:
traceback.print_exc(file=sys.stdout) traceback.print_exc(file=sys.stdout)
return 0 return 0
else: else:
return 1 return 1
def findtestdir(): def findtestdir():
if __name__ == '__main__': if __name__ == '__main__':
file = sys.argv[0] file = sys.argv[0]
else: else:
file = __file__ file = __file__
testdir = os.path.dirname(file) or os.curdir testdir = os.path.dirname(file) or os.curdir
return testdir return testdir
def count(n, word): def count(n, word):
if n == 1: if n == 1:
return "%d %s" % (n, word) return "%d %s" % (n, word)
else: else:
return "%d %ss" % (n, word) return "%d %ss" % (n, word)
class Compare: class Compare:
def __init__(self, filename): def __init__(self, filename):
self.fp = open(filename, 'r') self.fp = open(filename, 'r')
def write(self, data): def write(self, data):
expected = self.fp.read(len(data)) expected = self.fp.read(len(data))
if data <> expected: if data <> expected:
raise test_support.TestFailed, \ raise test_support.TestFailed, \
'Writing: '+`data`+', expected: '+`expected` 'Writing: '+`data`+', expected: '+`expected`
def flush(self): def flush(self):
pass pass
def close(self): def close(self):
leftover = self.fp.read() leftover = self.fp.read()
if leftover: if leftover:
raise test_support.TestFailed, 'Unread: '+`leftover` raise test_support.TestFailed, 'Unread: '+`leftover`
self.fp.close() self.fp.close()
def isatty(self): def isatty(self):
return 0 return 0
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())

View file

@ -6,7 +6,7 @@ import al
from test_support import verbose from test_support import verbose
alattrs = ['__doc__', '__name__', 'getdefault', 'getminmax', 'getname', 'getparams', alattrs = ['__doc__', '__name__', 'getdefault', 'getminmax', 'getname', 'getparams',
'newconfig', 'openport', 'queryparams', 'setparams'] 'newconfig', 'openport', 'queryparams', 'setparams']
# This is a very inobstrusive test for the existance of the al module and all it's # This is a very inobstrusive test for the existance of the al module and all it's
# attributes. More comprehensive examples can be found in Demo/al # attributes. More comprehensive examples can be found in Demo/al
@ -14,11 +14,11 @@ alattrs = ['__doc__', '__name__', 'getdefault', 'getminmax', 'getname', 'getpara
def main(): def main():
# touch all the attributes of al without doing anything # touch all the attributes of al without doing anything
if verbose: if verbose:
print 'Touching al module attributes...' print 'Touching al module attributes...'
for attr in alattrs: for attr in alattrs:
if verbose: if verbose:
print 'touching: ', attr print 'touching: ', attr
getattr(al, attr) getattr(al, attr)
main() main()

View file

@ -10,50 +10,50 @@ def main():
testtype('c', 'c') testtype('c', 'c')
for type in (['b', 'h', 'i', 'l', 'f', 'd']): for type in (['b', 'h', 'i', 'l', 'f', 'd']):
testtype(type, 1) testtype(type, 1)
unlink(TESTFN) unlink(TESTFN)
def testtype(type, example): def testtype(type, example):
a = array.array(type) a = array.array(type)
a.append(example) a.append(example)
if verbose: if verbose:
print 40*'*' print 40*'*'
print 'array after append: ', a print 'array after append: ', a
a.typecode a.typecode
a.itemsize a.itemsize
if a.typecode in ('i', 'b', 'h', 'l'): if a.typecode in ('i', 'b', 'h', 'l'):
a.byteswap() a.byteswap()
if a.typecode == 'c': if a.typecode == 'c':
f = open(TESTFN, "w") f = open(TESTFN, "w")
f.write("The quick brown fox jumps over the lazy dog.\n") f.write("The quick brown fox jumps over the lazy dog.\n")
f.close() f.close()
f = open(TESTFN, 'r') f = open(TESTFN, 'r')
a.fromfile(f, 10) a.fromfile(f, 10)
f.close() f.close()
if verbose: if verbose:
print 'char array with 10 bytes of TESTFN appended: ', a print 'char array with 10 bytes of TESTFN appended: ', a
a.fromlist(['a', 'b', 'c']) a.fromlist(['a', 'b', 'c'])
if verbose: if verbose:
print 'char array with list appended: ', a print 'char array with list appended: ', a
a.insert(0, example) a.insert(0, example)
if verbose: if verbose:
print 'array of %s after inserting another:' % a.typecode, a print 'array of %s after inserting another:' % a.typecode, a
f = open(TESTFN, 'w') f = open(TESTFN, 'w')
a.tofile(f) a.tofile(f)
f.close() f.close()
a.tolist() a.tolist()
a.tostring() a.tostring()
if verbose: if verbose:
print 'array of %s converted to a list: ' % a.typecode, a.tolist() print 'array of %s converted to a list: ' % a.typecode, a.tolist()
if verbose: if verbose:
print 'array of %s converted to a string: ' \ print 'array of %s converted to a string: ' \
% a.typecode, `a.tostring()` % a.typecode, `a.tostring()`
main() main()

View file

@ -7,166 +7,166 @@ def gendata1():
def gendata2(): def gendata2():
if verbose: if verbose:
print 'getsample' print 'getsample'
if audioop.getsample('\0\1', 2, 0) == 1: if audioop.getsample('\0\1', 2, 0) == 1:
return '\0\0\0\1\0\2' return '\0\0\0\1\0\2'
else: else:
return '\0\0\1\0\2\0' return '\0\0\1\0\2\0'
def gendata4(): def gendata4():
if verbose: if verbose:
print 'getsample' print 'getsample'
if audioop.getsample('\0\0\0\1', 4, 0) == 1: if audioop.getsample('\0\0\0\1', 4, 0) == 1:
return '\0\0\0\0\0\0\0\1\0\0\0\2' return '\0\0\0\0\0\0\0\1\0\0\0\2'
else: else:
return '\0\0\0\0\1\0\0\0\2\0\0\0' return '\0\0\0\0\1\0\0\0\2\0\0\0'
def testmax(data): def testmax(data):
if verbose: if verbose:
print 'max' print 'max'
if audioop.max(data[0], 1) <> 2 or \ if audioop.max(data[0], 1) <> 2 or \
audioop.max(data[1], 2) <> 2 or \ audioop.max(data[1], 2) <> 2 or \
audioop.max(data[2], 4) <> 2: audioop.max(data[2], 4) <> 2:
return 0 return 0
return 1 return 1
def testminmax(data): def testminmax(data):
if verbose: if verbose:
print 'minmax' print 'minmax'
if audioop.minmax(data[0], 1) <> (0, 2) or \ if audioop.minmax(data[0], 1) <> (0, 2) or \
audioop.minmax(data[1], 2) <> (0, 2) or \ audioop.minmax(data[1], 2) <> (0, 2) or \
audioop.minmax(data[2], 4) <> (0, 2): audioop.minmax(data[2], 4) <> (0, 2):
return 0 return 0
return 1 return 1
def testmaxpp(data): def testmaxpp(data):
if verbose: if verbose:
print 'maxpp' print 'maxpp'
if audioop.maxpp(data[0], 1) <> 0 or \ if audioop.maxpp(data[0], 1) <> 0 or \
audioop.maxpp(data[1], 2) <> 0 or \ audioop.maxpp(data[1], 2) <> 0 or \
audioop.maxpp(data[2], 4) <> 0: audioop.maxpp(data[2], 4) <> 0:
return 0 return 0
return 1 return 1
def testavg(data): def testavg(data):
if verbose: if verbose:
print 'avg' print 'avg'
if audioop.avg(data[0], 1) <> 1 or \ if audioop.avg(data[0], 1) <> 1 or \
audioop.avg(data[1], 2) <> 1 or \ audioop.avg(data[1], 2) <> 1 or \
audioop.avg(data[2], 4) <> 1: audioop.avg(data[2], 4) <> 1:
return 0 return 0
return 1 return 1
def testavgpp(data): def testavgpp(data):
if verbose: if verbose:
print 'avgpp' print 'avgpp'
if audioop.avgpp(data[0], 1) <> 0 or \ if audioop.avgpp(data[0], 1) <> 0 or \
audioop.avgpp(data[1], 2) <> 0 or \ audioop.avgpp(data[1], 2) <> 0 or \
audioop.avgpp(data[2], 4) <> 0: audioop.avgpp(data[2], 4) <> 0:
return 0 return 0
return 1 return 1
def testrms(data): def testrms(data):
if audioop.rms(data[0], 1) <> 1 or \ if audioop.rms(data[0], 1) <> 1 or \
audioop.rms(data[1], 2) <> 1 or \ audioop.rms(data[1], 2) <> 1 or \
audioop.rms(data[2], 4) <> 1: audioop.rms(data[2], 4) <> 1:
return 0 return 0
return 1 return 1
def testcross(data): def testcross(data):
if verbose: if verbose:
print 'cross' print 'cross'
if audioop.cross(data[0], 1) <> 0 or \ if audioop.cross(data[0], 1) <> 0 or \
audioop.cross(data[1], 2) <> 0 or \ audioop.cross(data[1], 2) <> 0 or \
audioop.cross(data[2], 4) <> 0: audioop.cross(data[2], 4) <> 0:
return 0 return 0
return 1 return 1
def testadd(data): def testadd(data):
if verbose: if verbose:
print 'add' print 'add'
data2 = [] data2 = []
for d in data: for d in data:
str = '' str = ''
for s in d: for s in d:
str = str + chr(ord(s)*2) str = str + chr(ord(s)*2)
data2.append(str) data2.append(str)
if audioop.add(data[0], data[0], 1) <> data2[0] or \ if audioop.add(data[0], data[0], 1) <> data2[0] or \
audioop.add(data[1], data[1], 2) <> data2[1] or \ audioop.add(data[1], data[1], 2) <> data2[1] or \
audioop.add(data[2], data[2], 4) <> data2[2]: audioop.add(data[2], data[2], 4) <> data2[2]:
return 0 return 0
return 1 return 1
def testbias(data): def testbias(data):
if verbose: if verbose:
print 'bias' print 'bias'
# Note: this test assumes that avg() works # Note: this test assumes that avg() works
d1 = audioop.bias(data[0], 1, 100) d1 = audioop.bias(data[0], 1, 100)
d2 = audioop.bias(data[1], 2, 100) d2 = audioop.bias(data[1], 2, 100)
d4 = audioop.bias(data[2], 4, 100) d4 = audioop.bias(data[2], 4, 100)
if audioop.avg(d1, 1) <> 101 or \ if audioop.avg(d1, 1) <> 101 or \
audioop.avg(d2, 2) <> 101 or \ audioop.avg(d2, 2) <> 101 or \
audioop.avg(d4, 4) <> 101: audioop.avg(d4, 4) <> 101:
return 0 return 0
return 1 return 1
def testlin2lin(data): def testlin2lin(data):
if verbose: if verbose:
print 'lin2lin' print 'lin2lin'
# too simple: we test only the size # too simple: we test only the size
for d1 in data: for d1 in data:
for d2 in data: for d2 in data:
got = len(d1)/3 got = len(d1)/3
wtd = len(d2)/3 wtd = len(d2)/3
if len(audioop.lin2lin(d1, got, wtd)) <> len(d2): if len(audioop.lin2lin(d1, got, wtd)) <> len(d2):
return 0 return 0
return 1 return 1
def testadpcm2lin(data): def testadpcm2lin(data):
# Very cursory test # Very cursory test
if audioop.adpcm2lin('\0\0', 1, None) <> ('\0\0\0\0', (0,0)): if audioop.adpcm2lin('\0\0', 1, None) <> ('\0\0\0\0', (0,0)):
return 0 return 0
return 1 return 1
def testlin2adpcm(data): def testlin2adpcm(data):
if verbose: if verbose:
print 'lin2adpcm' print 'lin2adpcm'
# Very cursory test # Very cursory test
if audioop.lin2adpcm('\0\0\0\0', 1, None) <> ('\0\0', (0,0)): if audioop.lin2adpcm('\0\0\0\0', 1, None) <> ('\0\0', (0,0)):
return 0 return 0
return 1 return 1
def testlin2ulaw(data): def testlin2ulaw(data):
if verbose: if verbose:
print 'lin2ulaw' print 'lin2ulaw'
if audioop.lin2ulaw(data[0], 1) <> '\377\347\333' or \ if audioop.lin2ulaw(data[0], 1) <> '\377\347\333' or \
audioop.lin2ulaw(data[1], 2) <> '\377\377\377' or \ audioop.lin2ulaw(data[1], 2) <> '\377\377\377' or \
audioop.lin2ulaw(data[2], 4) <> '\377\377\377': audioop.lin2ulaw(data[2], 4) <> '\377\377\377':
return 0 return 0
return 1 return 1
def testulaw2lin(data): def testulaw2lin(data):
if verbose: if verbose:
print 'ulaw2lin' print 'ulaw2lin'
# Cursory # Cursory
d = audioop.lin2ulaw(data[0], 1) d = audioop.lin2ulaw(data[0], 1)
if audioop.ulaw2lin(d, 1) <> data[0]: if audioop.ulaw2lin(d, 1) <> data[0]:
return 0 return 0
return 1 return 1
def testmul(data): def testmul(data):
if verbose: if verbose:
print 'mul' print 'mul'
data2 = [] data2 = []
for d in data: for d in data:
str = '' str = ''
for s in d: for s in d:
str = str + chr(ord(s)*2) str = str + chr(ord(s)*2)
data2.append(str) data2.append(str)
if audioop.mul(data[0], 1, 2) <> data2[0] or \ if audioop.mul(data[0], 1, 2) <> data2[0] or \
audioop.mul(data[1],2, 2) <> data2[1] or \ audioop.mul(data[1],2, 2) <> data2[1] or \
audioop.mul(data[2], 4, 2) <> data2[2]: audioop.mul(data[2], 4, 2) <> data2[2]:
return 0 return 0
return 1 return 1
def testratecv(data): def testratecv(data):
@ -181,75 +181,75 @@ def testratecv(data):
def testreverse(data): def testreverse(data):
if verbose: if verbose:
print 'reverse' print 'reverse'
if audioop.reverse(data[0], 1) <> '\2\1\0': if audioop.reverse(data[0], 1) <> '\2\1\0':
return 0 return 0
return 1 return 1
def testtomono(data): def testtomono(data):
if verbose: if verbose:
print 'tomono' print 'tomono'
data2 = '' data2 = ''
for d in data[0]: for d in data[0]:
data2 = data2 + d + d data2 = data2 + d + d
if audioop.tomono(data2, 1, 0.5, 0.5) <> data[0]: if audioop.tomono(data2, 1, 0.5, 0.5) <> data[0]:
return 0 return 0
return 1 return 1
def testtostereo(data): def testtostereo(data):
if verbose: if verbose:
print 'tostereo' print 'tostereo'
data2 = '' data2 = ''
for d in data[0]: for d in data[0]:
data2 = data2 + d + d data2 = data2 + d + d
if audioop.tostereo(data[0], 1, 1, 1) <> data2: if audioop.tostereo(data[0], 1, 1, 1) <> data2:
return 0 return 0
return 1 return 1
def testfindfactor(data): def testfindfactor(data):
if verbose: if verbose:
print 'findfactor' print 'findfactor'
if audioop.findfactor(data[1], data[1]) <> 1.0: if audioop.findfactor(data[1], data[1]) <> 1.0:
return 0 return 0
return 1 return 1
def testfindfit(data): def testfindfit(data):
if verbose: if verbose:
print 'findfit' print 'findfit'
if audioop.findfit(data[1], data[1]) <> (0, 1.0): if audioop.findfit(data[1], data[1]) <> (0, 1.0):
return 0 return 0
return 1 return 1
def testfindmax(data): def testfindmax(data):
if verbose: if verbose:
print 'findmax' print 'findmax'
if audioop.findmax(data[1], 1) <> 2: if audioop.findmax(data[1], 1) <> 2:
return 0 return 0
return 1 return 1
def testgetsample(data): def testgetsample(data):
if verbose: if verbose:
print 'getsample' print 'getsample'
for i in range(3): for i in range(3):
if audioop.getsample(data[0], 1, i) <> i or \ if audioop.getsample(data[0], 1, i) <> i or \
audioop.getsample(data[1], 2, i) <> i or \ audioop.getsample(data[1], 2, i) <> i or \
audioop.getsample(data[2], 4, i) <> i: audioop.getsample(data[2], 4, i) <> i:
return 0 return 0
return 1 return 1
def testone(name, data): def testone(name, data):
try: try:
func = eval('test'+name) func = eval('test'+name)
except NameError: except NameError:
print 'No test found for audioop.'+name+'()' print 'No test found for audioop.'+name+'()'
return return
try: try:
rv = func(data) rv = func(data)
except 'xx': except 'xx':
print 'Test FAILED for audioop.'+name+'() (with an exception)' print 'Test FAILED for audioop.'+name+'() (with an exception)'
return return
if not rv: if not rv:
print 'Test FAILED for audioop.'+name+'()' print 'Test FAILED for audioop.'+name+'()'
def testall(): def testall():
data = [gendata1(), gendata2(), gendata4()] data = [gendata1(), gendata2(), gendata4()]
@ -257,8 +257,8 @@ def testall():
# We know there is a routine 'add' # We know there is a routine 'add'
routines = [] routines = []
for n in names: for n in names:
if type(eval('audioop.'+n)) == type(audioop.add): if type(eval('audioop.'+n)) == type(audioop.add):
routines.append(n) routines.append(n)
for n in routines: for n in routines:
testone(n, data) testone(n, data)
testall() testall()

View file

@ -11,11 +11,11 @@ from test_support import verbose
def test(): def test():
try: try:
fname1 = tempfile.mktemp() fname1 = tempfile.mktemp()
fname2 = tempfile.mktemp() fname2 = tempfile.mktemp()
f = open(fname1, 'w') f = open(fname1, 'w')
except: except:
raise ImportError, "Cannot test binascii without a temp file" raise ImportError, "Cannot test binascii without a temp file"
start = 'Jack is my hero' start = 'Jack is my hero'
f.write(start) f.write(start)
@ -23,24 +23,24 @@ def test():
binhex.binhex(fname1, fname2) binhex.binhex(fname1, fname2)
if verbose: if verbose:
print 'binhex' print 'binhex'
binhex.hexbin(fname2, fname1) binhex.hexbin(fname2, fname1)
if verbose: if verbose:
print 'hexbin' print 'hexbin'
f = open(fname1, 'r') f = open(fname1, 'r')
finish = f.readline() finish = f.readline()
if start <> finish: if start <> finish:
print 'Error: binhex <> hexbin' print 'Error: binhex <> hexbin'
elif verbose: elif verbose:
print 'binhex == hexbin' print 'binhex == hexbin'
try: try:
import os import os
os.unlink(fname1) os.unlink(fname1)
os.unlink(fname2) os.unlink(fname2)
except: except:
pass pass
test() test()

View file

@ -11,11 +11,11 @@ from test_support import verbose
def test(): def test():
try: try:
fname1 = tempfile.mktemp() fname1 = tempfile.mktemp()
fname2 = tempfile.mktemp() fname2 = tempfile.mktemp()
f = open(fname1, 'w') f = open(fname1, 'w')
except: except:
raise ImportError, "Cannot test binascii without a temp file" raise ImportError, "Cannot test binascii without a temp file"
start = 'Jack is my hero' start = 'Jack is my hero'
f.write(start) f.write(start)
@ -23,24 +23,24 @@ def test():
binhex.binhex(fname1, fname2) binhex.binhex(fname1, fname2)
if verbose: if verbose:
print 'binhex' print 'binhex'
binhex.hexbin(fname2, fname1) binhex.hexbin(fname2, fname1)
if verbose: if verbose:
print 'hexbin' print 'hexbin'
f = open(fname1, 'r') f = open(fname1, 'r')
finish = f.readline() finish = f.readline()
if start <> finish: if start <> finish:
print 'Error: binhex <> hexbin' print 'Error: binhex <> hexbin'
elif verbose: elif verbose:
print 'binhex == hexbin' print 'binhex == hexbin'
try: try:
import os import os
os.unlink(fname1) os.unlink(fname1)
os.unlink(fname2) os.unlink(fname2)
except: except:
pass pass
test() test()

View file

@ -9,12 +9,12 @@ from test_support import verbose
def test(openmethod, what): def test(openmethod, what):
if verbose: if verbose:
print '\nTesting: ', what print '\nTesting: ', what
fname = tempfile.mktemp() fname = tempfile.mktemp()
f = openmethod(fname, 'c') f = openmethod(fname, 'c')
if verbose: if verbose:
print 'creation...' print 'creation...'
f['0'] = '' f['0'] = ''
f['a'] = 'Guido' f['a'] = 'Guido'
f['b'] = 'van' f['b'] = 'van'
@ -22,47 +22,47 @@ def test(openmethod, what):
f['d'] = 'invented' f['d'] = 'invented'
f['f'] = 'Python' f['f'] = 'Python'
if verbose: if verbose:
print '%s %s %s' % (f['a'], f['b'], f['c']) print '%s %s %s' % (f['a'], f['b'], f['c'])
if what == 'BTree' : if what == 'BTree' :
if verbose: if verbose:
print 'key ordering...' print 'key ordering...'
f.set_location(f.first()[0]) f.set_location(f.first()[0])
while 1: while 1:
try: try:
rec = f.next() rec = f.next()
except KeyError: except KeyError:
if rec <> f.last(): if rec <> f.last():
print 'Error, last <> last!' print 'Error, last <> last!'
f.previous() f.previous()
break break
if verbose: if verbose:
print rec print rec
if not f.has_key('a'): if not f.has_key('a'):
print 'Error, missing key!' print 'Error, missing key!'
f.sync() f.sync()
f.close() f.close()
if verbose: if verbose:
print 'modification...' print 'modification...'
f = openmethod(fname, 'w') f = openmethod(fname, 'w')
f['d'] = 'discovered' f['d'] = 'discovered'
if verbose: if verbose:
print 'access...' print 'access...'
for key in f.keys(): for key in f.keys():
word = f[key] word = f[key]
if verbose: if verbose:
print word print word
f.close() f.close()
types = [(bsddb.btopen, 'BTree'), types = [(bsddb.btopen, 'BTree'),
(bsddb.hashopen, 'Hash Table'), (bsddb.hashopen, 'Hash Table'),
# (bsddb.rnopen,'Record Numbers'), 'put' for RECNO for bsddb 1.85 # (bsddb.rnopen,'Record Numbers'), 'put' for RECNO for bsddb 1.85
# appears broken... at least on # appears broken... at least on
# Solaris Intel - rmasse 1/97 # Solaris Intel - rmasse 1/97
] ]
for type in types: for type in types:
test(type[0], type[1]) test(type[0], type[1])

View file

@ -6,8 +6,8 @@ import cd
from test_support import verbose from test_support import verbose
cdattrs = ['BLOCKSIZE', 'CDROM', 'DATASIZE', 'ERROR', 'NODISC', 'PAUSED', 'PLAYING', 'READY', cdattrs = ['BLOCKSIZE', 'CDROM', 'DATASIZE', 'ERROR', 'NODISC', 'PAUSED', 'PLAYING', 'READY',
'STILL', '__doc__', '__name__', 'atime', 'audio', 'catalog', 'control', 'createparser', 'error', 'STILL', '__doc__', '__name__', 'atime', 'audio', 'catalog', 'control', 'createparser', 'error',
'ident', 'index', 'msftoframe', 'open', 'pnum', 'ptime'] 'ident', 'index', 'msftoframe', 'open', 'pnum', 'ptime']
# This is a very inobstrusive test for the existance of the cd module and all it's # This is a very inobstrusive test for the existance of the cd module and all it's
@ -17,10 +17,10 @@ cdattrs = ['BLOCKSIZE', 'CDROM', 'DATASIZE', 'ERROR', 'NODISC', 'PAUSED', 'PLAYI
def main(): def main():
# touch all the attributes of cd without doing anything # touch all the attributes of cd without doing anything
if verbose: if verbose:
print 'Touching cd module attributes...' print 'Touching cd module attributes...'
for attr in cdattrs: for attr in cdattrs:
if verbose: if verbose:
print 'touching: ', attr print 'touching: ', attr
getattr(cd, attr) getattr(cd, attr)
main() main()

View file

@ -69,10 +69,10 @@ clattrs = ['ADDED_ALGORITHM_ERROR', 'ALAW', 'ALGORITHM_ID',
def main(): def main():
# touch all the attributes of al without doing anything # touch all the attributes of al without doing anything
if verbose: if verbose:
print 'Touching cl module attributes...' print 'Touching cl module attributes...'
for attr in clattrs: for attr in clattrs:
if verbose: if verbose:
print 'touching: ', attr print 'touching: ', attr
getattr(cl, attr) getattr(cl, attr)
main() main()

View file

@ -6,27 +6,27 @@ import cmath
from test_support import verbose from test_support import verbose
testdict = {'acos' : 1.0, testdict = {'acos' : 1.0,
'acosh' : 1.0, 'acosh' : 1.0,
'asin' : 1.0, 'asin' : 1.0,
'asinh' : 1.0, 'asinh' : 1.0,
'atan' : 0.2, 'atan' : 0.2,
'atanh' : 0.2, 'atanh' : 0.2,
'cos' : 1.0, 'cos' : 1.0,
'cosh' : 1.0, 'cosh' : 1.0,
'exp' : 1.0, 'exp' : 1.0,
'log' : 1.0, 'log' : 1.0,
'log10' : 1.0, 'log10' : 1.0,
'sin' : 1.0, 'sin' : 1.0,
'sinh' : 1.0, 'sinh' : 1.0,
'sqrt' : 1.0, 'sqrt' : 1.0,
'tan' : 1.0, 'tan' : 1.0,
'tanh' : 1.0} 'tanh' : 1.0}
for func in testdict.keys(): for func in testdict.keys():
f = getattr(cmath, func) f = getattr(cmath, func)
r = f(testdict[func]) r = f(testdict[func])
if verbose: if verbose:
print 'Calling %s(%f) = %f' % (func, testdict[func], abs(r)) print 'Calling %s(%f) = %f' % (func, testdict[func], abs(r))
p = cmath.pi p = cmath.pi
e = cmath.e e = cmath.e

View file

@ -14,8 +14,8 @@ d['12345678910'] = '019237410982340912840198242'
d.keys() d.keys()
if d.has_key('a'): if d.has_key('a'):
if verbose: if verbose:
print 'Test dbm keys: ', d.keys() print 'Test dbm keys: ', d.keys()
d.close() d.close()
d = dbm.open(filename, 'r') d = dbm.open(filename, 'r')
d.close() d.close()

View file

@ -12,20 +12,20 @@ sharedlibs = [
for s, func in sharedlibs: for s, func in sharedlibs:
try: try:
if verbose: if verbose:
print 'trying to open:', s, print 'trying to open:', s,
l = dl.open(s) l = dl.open(s)
except dl.error: except dl.error:
if verbose: if verbose:
print 'failed' print 'failed'
pass pass
else: else:
if verbose: if verbose:
print 'succeeded...', print 'succeeded...',
l.call(func) l.call(func)
l.close() l.close()
if verbose: if verbose:
print 'worked!' print 'worked!'
break break
else: else:
print 'Could not open any shared libraries' print 'Could not open any shared libraries'

View file

@ -7,31 +7,31 @@ import errno
from test_support import verbose from test_support import verbose
errors = ['E2BIG', 'EACCES', 'EADDRINUSE', 'EADDRNOTAVAIL', 'EADV', errors = ['E2BIG', 'EACCES', 'EADDRINUSE', 'EADDRNOTAVAIL', 'EADV',
'EAFNOSUPPORT', 'EAGAIN', 'EALREADY', 'EBADE', 'EBADF', 'EAFNOSUPPORT', 'EAGAIN', 'EALREADY', 'EBADE', 'EBADF',
'EBADFD', 'EBADMSG', 'EBADR', 'EBADRQC', 'EBADSLT', 'EBADFD', 'EBADMSG', 'EBADR', 'EBADRQC', 'EBADSLT',
'EBFONT', 'EBUSY', 'ECHILD', 'ECHRNG', 'ECOMM', 'EBFONT', 'EBUSY', 'ECHILD', 'ECHRNG', 'ECOMM',
'ECONNABORTED', 'ECONNREFUSED', 'ECONNRESET', 'ECONNABORTED', 'ECONNREFUSED', 'ECONNRESET',
'EDEADLK', 'EDEADLOCK', 'EDESTADDRREQ', 'EDOM', 'EDEADLK', 'EDEADLOCK', 'EDESTADDRREQ', 'EDOM',
'EDQUOT', 'EEXIST', 'EFAULT', 'EFBIG', 'EHOSTDOWN', 'EDQUOT', 'EEXIST', 'EFAULT', 'EFBIG', 'EHOSTDOWN',
'EHOSTUNREACH', 'EIDRM', 'EILSEQ', 'EINPROGRESS', 'EHOSTUNREACH', 'EIDRM', 'EILSEQ', 'EINPROGRESS',
'EINTR', 'EINVAL', 'EIO', 'EISCONN', 'EISDIR', 'EINTR', 'EINVAL', 'EIO', 'EISCONN', 'EISDIR',
'EL2HLT', 'EL2NSYNC', 'EL3HLT', 'EL3RST', 'ELIBACC', 'EL2HLT', 'EL2NSYNC', 'EL3HLT', 'EL3RST', 'ELIBACC',
'ELIBBAD', 'ELIBEXEC', 'ELIBMAX', 'ELIBSCN', 'ELNRNG', 'ELIBBAD', 'ELIBEXEC', 'ELIBMAX', 'ELIBSCN', 'ELNRNG',
'ELOOP', 'EMFILE', 'EMLINK', 'EMSGSIZE', 'EMULTIHOP', 'ELOOP', 'EMFILE', 'EMLINK', 'EMSGSIZE', 'EMULTIHOP',
'ENAMETOOLONG', 'ENETDOWN', 'ENETRESET', 'ENETUNREACH', 'ENAMETOOLONG', 'ENETDOWN', 'ENETRESET', 'ENETUNREACH',
'ENFILE', 'ENOANO', 'ENOBUFS', 'ENOCSI', 'ENODATA', 'ENFILE', 'ENOANO', 'ENOBUFS', 'ENOCSI', 'ENODATA',
'ENODEV', 'ENOENT', 'ENOEXEC', 'ENOLCK', 'ENOLINK', 'ENODEV', 'ENOENT', 'ENOEXEC', 'ENOLCK', 'ENOLINK',
'ENOMEM', 'ENOMSG', 'ENONET', 'ENOPKG', 'ENOPROTOOPT', 'ENOMEM', 'ENOMSG', 'ENONET', 'ENOPKG', 'ENOPROTOOPT',
'ENOSPC', 'ENOSR', 'ENOSTR', 'ENOSYS', 'ENOTBLK', 'ENOSPC', 'ENOSR', 'ENOSTR', 'ENOSYS', 'ENOTBLK',
'ENOTCONN', 'ENOTDIR', 'ENOTEMPTY', 'ENOTOBACCO', 'ENOTSOCK', 'ENOTCONN', 'ENOTDIR', 'ENOTEMPTY', 'ENOTOBACCO', 'ENOTSOCK',
'ENOTTY', 'ENOTUNIQ', 'ENXIO', 'EOPNOTSUPP', 'ENOTTY', 'ENOTUNIQ', 'ENXIO', 'EOPNOTSUPP',
'EOVERFLOW', 'EPERM', 'EPFNOSUPPORT', 'EPIPE', 'EOVERFLOW', 'EPERM', 'EPFNOSUPPORT', 'EPIPE',
'EPROTO', 'EPROTONOSUPPORT', 'EPROTOTYPE', 'EPROTO', 'EPROTONOSUPPORT', 'EPROTOTYPE',
'ERANGE', 'EREMCHG', 'EREMOTE', 'ERESTART', 'ERANGE', 'EREMCHG', 'EREMOTE', 'ERESTART',
'EROFS', 'ESHUTDOWN', 'ESOCKTNOSUPPORT', 'ESPIPE', 'EROFS', 'ESHUTDOWN', 'ESOCKTNOSUPPORT', 'ESPIPE',
'ESRCH', 'ESRMNT', 'ESTALE', 'ESTRPIPE', 'ETIME', 'ESRCH', 'ESRMNT', 'ESTALE', 'ESTRPIPE', 'ETIME',
'ETIMEDOUT', 'ETOOMANYREFS', 'ETXTBSY', 'EUNATCH', 'ETIMEDOUT', 'ETOOMANYREFS', 'ETXTBSY', 'EUNATCH',
'EUSERS', 'EWOULDBLOCK', 'EXDEV', 'EXFULL'] 'EUSERS', 'EWOULDBLOCK', 'EXDEV', 'EXFULL']
# #
# This is is a wee bit bogus since the module only conditionally adds # This is is a wee bit bogus since the module only conditionally adds
@ -40,10 +40,10 @@ errors = ['E2BIG', 'EACCES', 'EADDRINUSE', 'EADDRNOTAVAIL', 'EADV',
# #
for error in errors: for error in errors:
try: try:
a = getattr(errno, error) a = getattr(errno, error)
except AttributeError: except AttributeError:
if verbose: if verbose:
print '%s: not found' % error print '%s: not found' % error
else: else:
if verbose: if verbose:
print '%s: %d' % (error, a) print '%s: %d' % (error, a)

View file

@ -8,9 +8,9 @@ print '5. Built-in exceptions'
def r(thing): def r(thing):
if type(thing) == ClassType: if type(thing) == ClassType:
print thing.__name__ print thing.__name__
else: else:
print thing print thing
r(AttributeError) r(AttributeError)
import sys import sys
@ -24,14 +24,14 @@ fp.close()
fp = open(TESTFN, 'r') fp = open(TESTFN, 'r')
savestdin = sys.stdin savestdin = sys.stdin
try: try:
try: try:
sys.stdin = fp sys.stdin = fp
x = raw_input() x = raw_input()
except EOFError: except EOFError:
pass pass
finally: finally:
sys.stdin = savestdin sys.stdin = savestdin
fp.close() fp.close()
r(IOError) r(IOError)
try: open('this file does not exist', 'r') try: open('this file does not exist', 'r')
@ -64,7 +64,7 @@ except NameError: pass
r(OverflowError) r(OverflowError)
x = 1 x = 1
try: try:
while 1: x = x+x while 1: x = x+x
except OverflowError: pass except OverflowError: pass
r(RuntimeError) r(RuntimeError)

View file

@ -85,67 +85,67 @@ def main():
# insure that we at least have an X display before continuing. # insure that we at least have an X display before continuing.
import os import os
try: try:
display = os.environ['DISPLAY'] display = os.environ['DISPLAY']
except: except:
# Raise ImportError because regrtest.py handles it specially. # Raise ImportError because regrtest.py handles it specially.
raise ImportError, "No $DISPLAY -- skipping gl test" raise ImportError, "No $DISPLAY -- skipping gl test"
# touch all the attributes of gl without doing anything # touch all the attributes of gl without doing anything
if verbose: if verbose:
print 'Touching gl module attributes...' print 'Touching gl module attributes...'
for attr in glattrs: for attr in glattrs:
if verbose: if verbose:
print 'touching: ', attr print 'touching: ', attr
getattr(gl, attr) getattr(gl, attr)
# create a small 'Crisscross' window # create a small 'Crisscross' window
if verbose: if verbose:
print 'Creating a small "CrissCross" window...' print 'Creating a small "CrissCross" window...'
print 'foreground' print 'foreground'
gl.foreground() gl.foreground()
if verbose: if verbose:
print 'prefposition' print 'prefposition'
gl.prefposition(500, 900, 500, 900) gl.prefposition(500, 900, 500, 900)
if verbose: if verbose:
print 'winopen "CrissCross"' print 'winopen "CrissCross"'
w = gl.winopen('CrissCross') w = gl.winopen('CrissCross')
if verbose: if verbose:
print 'clear' print 'clear'
gl.clear() gl.clear()
if verbose: if verbose:
print 'ortho2' print 'ortho2'
gl.ortho2(0.0, 400.0, 0.0, 400.0) gl.ortho2(0.0, 400.0, 0.0, 400.0)
if verbose: if verbose:
print 'color WHITE' print 'color WHITE'
gl.color(GL.WHITE) gl.color(GL.WHITE)
if verbose: if verbose:
print 'color RED' print 'color RED'
gl.color(GL.RED) gl.color(GL.RED)
if verbose: if verbose:
print 'bgnline' print 'bgnline'
gl.bgnline() gl.bgnline()
if verbose: if verbose:
print 'v2f' print 'v2f'
gl.v2f(0.0, 0.0) gl.v2f(0.0, 0.0)
gl.v2f(400.0, 400.0) gl.v2f(400.0, 400.0)
if verbose: if verbose:
print 'endline' print 'endline'
gl.endline() gl.endline()
if verbose: if verbose:
print 'bgnline' print 'bgnline'
gl.bgnline() gl.bgnline()
if verbose: if verbose:
print 'v2i' print 'v2i'
gl.v2i(400, 0) gl.v2i(400, 0)
gl.v2i(0, 400) gl.v2i(0, 400)
if verbose: if verbose:
print 'endline' print 'endline'
gl.endline() gl.endline()
if verbose: if verbose:
print 'Displaying window for 2 seconds...' print 'Displaying window for 2 seconds...'
time.sleep(2) time.sleep(2)
if verbose: if verbose:
print 'winclose' print 'winclose'
gl.winclose(w) gl.winclose(w)
main() main()

View file

@ -10,16 +10,16 @@ groups = grp.getgrall()
if verbose: if verbose:
print 'Groups:' print 'Groups:'
for group in groups: for group in groups:
print group print group
if not groups: if not groups:
if verbose: if verbose:
print "Empty Group Database -- no further tests of grp module possible" print "Empty Group Database -- no further tests of grp module possible"
else: else:
group = grp.getgrgid(groups[0][2]) group = grp.getgrgid(groups[0][2])
if verbose: if verbose:
print 'Group Entry for GID %d: %s' % (groups[0][2], group) print 'Group Entry for GID %d: %s' % (groups[0][2], group)
group = grp.getgrnam(groups[0][0]) group = grp.getgrnam(groups[0][0])
if verbose: if verbose:
print 'Group Entry for group %s: %s' % (groups[0][0], group) print 'Group Entry for group %s: %s' % (groups[0][0], group)

View file

@ -15,14 +15,14 @@ def main(use_rgbimg=1):
uu.decode(get_qualified_path('testrgb.uue'), 'test.rgb') uu.decode(get_qualified_path('testrgb.uue'), 'test.rgb')
if use_rgbimg: if use_rgbimg:
image, width, height = getrgbimage('test.rgb') image, width, height = getrgbimage('test.rgb')
else: else:
image, width, height = getimage('test.rgb') image, width, height = getimage('test.rgb')
# Return the selected part of image, which should by width by height # Return the selected part of image, which should by width by height
# in size and consist of pixels of psize bytes. # in size and consist of pixels of psize bytes.
if verbose: if verbose:
print 'crop' print 'crop'
newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1) newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1)
# Return image scaled to size newwidth by newheight. No interpolation # Return image scaled to size newwidth by newheight. No interpolation
@ -30,7 +30,7 @@ def main(use_rgbimg=1):
# Therefore, computer-generated images or dithered images will # Therefore, computer-generated images or dithered images will
# not look nice after scaling. # not look nice after scaling.
if verbose: if verbose:
print 'scale' print 'scale'
scaleimage = imageop.scale(image, 4, width, height, 1, 1) scaleimage = imageop.scale(image, 4, width, height, 1, 1)
# Run a vertical low-pass filter over an image. It does so by computing # Run a vertical low-pass filter over an image. It does so by computing
@ -38,34 +38,34 @@ def main(use_rgbimg=1):
# pixels. The main use of this routine is to forestall excessive flicker # pixels. The main use of this routine is to forestall excessive flicker
# if the image two vertically-aligned source pixels, hence the name. # if the image two vertically-aligned source pixels, hence the name.
if verbose: if verbose:
print 'tovideo' print 'tovideo'
videoimage = imageop.tovideo (image, 4, width, height) videoimage = imageop.tovideo (image, 4, width, height)
# Convert an rgb image to an 8 bit rgb # Convert an rgb image to an 8 bit rgb
if verbose: if verbose:
print 'rgb2rgb8' print 'rgb2rgb8'
greyimage = imageop.rgb2rgb8(image, width, height) greyimage = imageop.rgb2rgb8(image, width, height)
# Convert an 8 bit rgb image to a 24 bit rgb image # Convert an 8 bit rgb image to a 24 bit rgb image
if verbose: if verbose:
print 'rgb82rgb' print 'rgb82rgb'
image = imageop.rgb82rgb(greyimage, width, height) image = imageop.rgb82rgb(greyimage, width, height)
# Convert an rgb image to an 8 bit greyscale image # Convert an rgb image to an 8 bit greyscale image
if verbose: if verbose:
print 'rgb2grey' print 'rgb2grey'
greyimage = imageop.rgb2grey(image, width, height) greyimage = imageop.rgb2grey(image, width, height)
# Convert an 8 bit greyscale image to a 24 bit rgb image # Convert an 8 bit greyscale image to a 24 bit rgb image
if verbose: if verbose:
print 'grey2rgb' print 'grey2rgb'
image = imageop.grey2rgb(greyimage, width, height) image = imageop.grey2rgb(greyimage, width, height)
# Convert a 8-bit deep greyscale image to a 1-bit deep image by # Convert a 8-bit deep greyscale image to a 1-bit deep image by
# tresholding all the pixels. The resulting image is tightly packed # tresholding all the pixels. The resulting image is tightly packed
# and is probably only useful as an argument to mono2grey. # and is probably only useful as an argument to mono2grey.
if verbose: if verbose:
print 'grey2mono' print 'grey2mono'
monoimage = imageop.grey2mono (greyimage, width, height, 0) monoimage = imageop.grey2mono (greyimage, width, height, 0)
# monoimage, width, height = getimage('monotest.rgb') # monoimage, width, height = getimage('monotest.rgb')
@ -75,42 +75,42 @@ def main(use_rgbimg=1):
# monochrome black-and-white image to greyscale pass the values 0 and # monochrome black-and-white image to greyscale pass the values 0 and
# 255 respectively. # 255 respectively.
if verbose: if verbose:
print 'mono2grey' print 'mono2grey'
greyimage = imageop.mono2grey (monoimage, width, height, 0, 255) greyimage = imageop.mono2grey (monoimage, width, height, 0, 255)
# Convert an 8-bit greyscale image to a 1-bit monochrome image using a # Convert an 8-bit greyscale image to a 1-bit monochrome image using a
# (simple-minded) dithering algorithm. # (simple-minded) dithering algorithm.
if verbose: if verbose:
print 'dither2mono' print 'dither2mono'
monoimage = imageop.dither2mono (greyimage, width, height) monoimage = imageop.dither2mono (greyimage, width, height)
# Convert an 8-bit greyscale image to a 4-bit greyscale image without # Convert an 8-bit greyscale image to a 4-bit greyscale image without
# dithering. # dithering.
if verbose: if verbose:
print 'grey2grey4' print 'grey2grey4'
grey4image = imageop.grey2grey4 (greyimage, width, height) grey4image = imageop.grey2grey4 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image without # Convert an 8-bit greyscale image to a 2-bit greyscale image without
# dithering. # dithering.
if verbose: if verbose:
print 'grey2grey2' print 'grey2grey2'
grey2image = imageop.grey2grey2 (greyimage, width, height) grey2image = imageop.grey2grey2 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image with # Convert an 8-bit greyscale image to a 2-bit greyscale image with
# dithering. As for dither2mono, the dithering algorithm is currently # dithering. As for dither2mono, the dithering algorithm is currently
# very simple. # very simple.
if verbose: if verbose:
print 'dither2grey2' print 'dither2grey2'
grey2image = imageop.dither2grey2 (greyimage, width, height) grey2image = imageop.dither2grey2 (greyimage, width, height)
# Convert a 4-bit greyscale image to an 8-bit greyscale image. # Convert a 4-bit greyscale image to an 8-bit greyscale image.
if verbose: if verbose:
print 'grey42grey' print 'grey42grey'
greyimage = imageop.grey42grey (grey4image, width, height) greyimage = imageop.grey42grey (grey4image, width, height)
# Convert a 2-bit greyscale image to an 8-bit greyscale image. # Convert a 2-bit greyscale image to an 8-bit greyscale image.
if verbose: if verbose:
print 'grey22grey' print 'grey22grey'
image = imageop.grey22grey (grey2image, width, height) image = imageop.grey22grey (grey2image, width, height)
# Cleanup # Cleanup
@ -123,12 +123,12 @@ def getrgbimage(name):
import rgbimg import rgbimg
try: try:
sizes = rgbimg.sizeofimage(name) sizes = rgbimg.sizeofimage(name)
except rgbimg.error: except rgbimg.error:
name = get_qualified_path(name) name = get_qualified_path(name)
sizes = rgbimg.sizeofimage(name) sizes = rgbimg.sizeofimage(name)
if verbose: if verbose:
print 'rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)) print 'rgbimg opening test image: %s, sizes: %s' % (name, str(sizes))
image = rgbimg.longimagedata(name) image = rgbimg.longimagedata(name)
return (image, sizes[0], sizes[1]) return (image, sizes[0], sizes[1])
@ -141,12 +141,12 @@ def getimage(name):
import imgfile import imgfile
try: try:
sizes = imgfile.getsizes(name) sizes = imgfile.getsizes(name)
except imgfile.error: except imgfile.error:
name = get_qualified_path(name) name = get_qualified_path(name)
sizes = imgfile.getsizes(name) sizes = imgfile.getsizes(name)
if verbose: if verbose:
print 'imgfile opening test image: %s, sizes: %s' % (name, str(sizes)) print 'imgfile opening test image: %s, sizes: %s' % (name, str(sizes))
image = imgfile.read(name) image = imgfile.read(name)
return (image, sizes[0], sizes[1]) return (image, sizes[0], sizes[1])
@ -157,13 +157,13 @@ def get_qualified_path(name):
import os import os
path = sys.path path = sys.path
try: try:
path = [os.path.dirname(__file__)] + path path = [os.path.dirname(__file__)] + path
except NameError: except NameError:
pass pass
for dir in path: for dir in path:
fullname = os.path.join(dir, name) fullname = os.path.join(dir, name)
if os.path.exists(fullname): if os.path.exists(fullname):
return fullname return fullname
return name return name
# rgbimg (unlike imgfile) is portable to platforms other than SGI. # rgbimg (unlike imgfile) is portable to platforms other than SGI.

View file

@ -24,12 +24,12 @@ def main():
unlink('greytest.rgb') unlink('greytest.rgb')
def findfile(file): def findfile(file):
if os.path.isabs(file): return file if os.path.isabs(file): return file
import sys import sys
for dn in sys.path: for dn in sys.path:
fn = os.path.join(dn, file) fn = os.path.join(dn, file)
if os.path.exists(fn): return fn if os.path.exists(fn): return fn
return file return file
def testimage(name): def testimage(name):
"""Run through the imgfile's battery of possible methods """Run through the imgfile's battery of possible methods
@ -44,23 +44,23 @@ def testimage(name):
# try opening the name directly # try opening the name directly
try: try:
# This function returns a tuple (x, y, z) where x and y are the size # This function returns a tuple (x, y, z) where x and y are the size
# of the image in pixels and z is the number of bytes per pixel. Only # of the image in pixels and z is the number of bytes per pixel. Only
# 3 byte RGB pixels and 1 byte greyscale pixels are supported. # 3 byte RGB pixels and 1 byte greyscale pixels are supported.
sizes = imgfile.getsizes(name) sizes = imgfile.getsizes(name)
except imgfile.error: except imgfile.error:
# get a more qualified path component of the script... # get a more qualified path component of the script...
if __name__ == '__main__': if __name__ == '__main__':
ourname = sys.argv[0] ourname = sys.argv[0]
else: # ...or the full path of the module else: # ...or the full path of the module
ourname = sys.modules[__name__].__file__ ourname = sys.modules[__name__].__file__
parts = string.splitfields(ourname, os.sep) parts = string.splitfields(ourname, os.sep)
parts[-1] = name parts[-1] = name
name = string.joinfields(parts, os.sep) name = string.joinfields(parts, os.sep)
sizes = imgfile.getsizes(name) sizes = imgfile.getsizes(name)
if verbose: if verbose:
print 'Opening test image: %s, sizes: %s' % (name, str(sizes)) print 'Opening test image: %s, sizes: %s' % (name, str(sizes))
# This function reads and decodes the image on the specified file, # This function reads and decodes the image on the specified file,
# and returns it as a python string. The string has either 1 byte # and returns it as a python string. The string has either 1 byte
# greyscale pixels or 4 byte RGBA pixels. The bottom left pixel # greyscale pixels or 4 byte RGBA pixels. The bottom left pixel
@ -74,12 +74,12 @@ def testimage(name):
# are stored as 4 byte values of which only the lower three # are stored as 4 byte values of which only the lower three
# bytes are used). These are the formats returned by gl.lrectread. # bytes are used). These are the formats returned by gl.lrectread.
if verbose: if verbose:
print 'Writing output file' print 'Writing output file'
imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2]) imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2])
if verbose: if verbose:
print 'Opening scaled test image: %s, sizes: %s' % (name, str(sizes)) print 'Opening scaled test image: %s, sizes: %s' % (name, str(sizes))
# This function is identical to read but it returns an image that # This function is identical to read but it returns an image that
# is scaled to the given x and y sizes. If the filter and blur # is scaled to the given x and y sizes. If the filter and blur
# parameters are omitted scaling is done by simply dropping # parameters are omitted scaling is done by simply dropping
@ -93,7 +93,7 @@ def testimage(name):
# makes no attempt to keep the aspect ratio correct, so that # makes no attempt to keep the aspect ratio correct, so that
# is the users' responsibility. # is the users' responsibility.
if verbose: if verbose:
print 'Filtering with "impulse"' print 'Filtering with "impulse"'
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0) simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0)
# This function sets a global flag which defines whether the # This function sets a global flag which defines whether the
@ -101,14 +101,14 @@ def testimage(name):
# top (flag is zero, compatible with SGI GL) or from top to # top (flag is zero, compatible with SGI GL) or from top to
# bottom(flag is one, compatible with X). The default is zero. # bottom(flag is one, compatible with X). The default is zero.
if verbose: if verbose:
print 'Switching to X compatibility' print 'Switching to X compatibility'
imgfile.ttob (1) imgfile.ttob (1)
if verbose: if verbose:
print 'Filtering with "triangle"' print 'Filtering with "triangle"'
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0) simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0)
if verbose: if verbose:
print 'Switching back to SGI compatibility' print 'Switching back to SGI compatibility'
imgfile.ttob (0) imgfile.ttob (0)
if verbose: print 'Filtering with "quadratic"' if verbose: print 'Filtering with "quadratic"'
@ -117,7 +117,7 @@ def testimage(name):
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0) simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0)
if verbose: if verbose:
print 'Writing output file' print 'Writing output file'
imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2]) imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2])
os.unlink(outputfile) os.unlink(outputfile)

View file

@ -4,7 +4,7 @@ import new
class Eggs: class Eggs:
def get_yolks(self): def get_yolks(self):
return self.yolks return self.yolks
print 'new.module()' print 'new.module()'
m = new.module('Spam') m = new.module('Spam')

View file

@ -11,19 +11,19 @@ except nis.error, msg:
done = 0 done = 0
for nismap in maps: for nismap in maps:
if verbose: if verbose:
print nismap print nismap
mapping = nis.cat(nismap) mapping = nis.cat(nismap)
for k, v in mapping.items(): for k, v in mapping.items():
if verbose: if verbose:
print ' ', k, v print ' ', k, v
if not k: if not k:
continue continue
if nis.match(k, nismap) <> v: if nis.match(k, nismap) <> v:
print "NIS match failed for key `%s' in map `%s'" % (k, nismap) print "NIS match failed for key `%s' in map `%s'" % (k, nismap)
else: else:
# just test the one key, otherwise this test could take a # just test the one key, otherwise this test could take a
# very long time # very long time
done = 1 done = 1
break break
if done: if done:
break break

View file

@ -9,18 +9,18 @@ print 'XXX Not yet fully implemented'
print '2.1 try inside for loop' print '2.1 try inside for loop'
n = 0 n = 0
for i in range(10): for i in range(10):
n = n+i n = n+i
try: 1/0 try: 1/0
except NameError: pass except NameError: pass
except ZeroDivisionError: pass except ZeroDivisionError: pass
except TypeError: pass except TypeError: pass
try: pass try: pass
except: pass except: pass
try: pass try: pass
finally: pass finally: pass
n = n+i n = n+i
if n <> 90: if n <> 90:
raise TestFailed, 'try inside for' raise TestFailed, 'try inside for'
print '2.2 raise class exceptions' print '2.2 raise class exceptions'
@ -30,7 +30,7 @@ class BClass(AClass): pass
class CClass: pass class CClass: pass
class DClass(AClass): class DClass(AClass):
def __init__(self, ignore): def __init__(self, ignore):
pass pass
try: raise AClass() try: raise AClass()
except: pass except: pass
@ -50,12 +50,12 @@ b = BClass()
try: raise AClass, b try: raise AClass, b
except BClass, v: except BClass, v:
if v != b: raise TestFailed if v != b: raise TestFailed
else: raise TestFailed else: raise TestFailed
try: raise b try: raise b
except AClass, v: except AClass, v:
if v != b: raise TestFailed if v != b: raise TestFailed
# not enough arguments # not enough arguments
try: raise BClass, a try: raise BClass, a
@ -64,7 +64,7 @@ except TypeError: pass
try: raise DClass, a try: raise DClass, a
except DClass, v: except DClass, v:
if not isinstance(v, DClass): if not isinstance(v, DClass):
raise TestFailed raise TestFailed
print '2.3 comparing function objects' print '2.3 comparing function objects'

View file

@ -6,11 +6,11 @@ def test(name, input, output, *args):
f = getattr(operator, name) f = getattr(operator, name)
params = (input,) + args params = (input,) + args
try: try:
val = apply(f, params) val = apply(f, params)
except: except:
val = sys.exc_type val = sys.exc_type
if val <> output: if val <> output:
print '%s%s = %s: %s expected' % (f.__name__, params, `val`, `output`) print '%s%s = %s: %s expected' % (f.__name__, params, `val`, `output`)
test('abs', -1, 1) test('abs', -1, 1)
test('add', 3, 7, 4) test('add', 3, 7, 4)

View file

@ -1,7 +1,7 @@
# Test packages (dotted-name import) # Test packages (dotted-name import)
import sys, os, string, tempfile, traceback import sys, os, string, tempfile, traceback
from os import mkdir, rmdir # Can't test if these fail from os import mkdir, rmdir # Can't test if these fail
del mkdir, rmdir del mkdir, rmdir
from test_support import verbose from test_support import verbose
@ -10,19 +10,19 @@ from test_support import verbose
def mkhier(root, descr): def mkhier(root, descr):
mkdir(root) mkdir(root)
for name, contents in descr: for name, contents in descr:
comps = string.split(name) comps = string.split(name)
fullname = root fullname = root
for c in comps: for c in comps:
fullname = os.path.join(fullname, c) fullname = os.path.join(fullname, c)
if contents is None: if contents is None:
mkdir(fullname) mkdir(fullname)
else: else:
if verbose: print "write", fullname if verbose: print "write", fullname
f = open(fullname, "w") f = open(fullname, "w")
f.write(contents) f.write(contents)
if contents and contents[-1] != '\n': if contents and contents[-1] != '\n':
f.write('\n') f.write('\n')
f.close() f.close()
def mkdir(x): def mkdir(x):
if verbose: print "mkdir", x if verbose: print "mkdir", x
@ -31,11 +31,11 @@ def mkdir(x):
def cleanout(root): def cleanout(root):
names = os.listdir(root) names = os.listdir(root)
for name in names: for name in names:
fullname = os.path.join(root, name) fullname = os.path.join(root, name)
if os.path.isdir(fullname) and not os.path.islink(fullname): if os.path.isdir(fullname) and not os.path.islink(fullname):
cleanout(fullname) cleanout(fullname)
else: else:
os.remove(fullname) os.remove(fullname)
rmdir(root) rmdir(root)
def rmdir(x): def rmdir(x):
@ -53,19 +53,19 @@ def runtest(hier, code):
f.write(code) f.write(code)
f.close() f.close()
try: try:
sys.path.insert(0, root) sys.path.insert(0, root)
if verbose: print "sys.path =", sys.path if verbose: print "sys.path =", sys.path
try: try:
execfile(codefile, globals(), {}) execfile(codefile, globals(), {})
except: except:
traceback.print_exc(file=sys.stdout) traceback.print_exc(file=sys.stdout)
finally: finally:
sys.path[:] = savepath sys.path[:] = savepath
try: try:
cleanout(root) cleanout(root)
except (os.error, IOError): except (os.error, IOError):
pass pass
os.remove(codefile) os.remove(codefile)
# Test descriptions # Test descriptions
@ -203,12 +203,12 @@ args = []
if __name__ == '__main__': if __name__ == '__main__':
args = sys.argv[1:] args = sys.argv[1:]
if args and args[0] == '-q': if args and args[0] == '-q':
verbose = 0 verbose = 0
del args[0] del args[0]
for name, hier, code in tests: for name, hier, code in tests:
if args and name not in args: if args and name not in args:
print "skipping test", name print "skipping test", name
continue continue
print "running test", name print "running test", name
runtest(hier, code) runtest(hier, code)

View file

@ -13,16 +13,16 @@ def powtest(type):
raise ValueError, 'pow(0,'+str(i)+') != 0' raise ValueError, 'pow(0,'+str(i)+') != 0'
if (pow(type(1),1)!=type(1)): if (pow(type(1),1)!=type(1)):
raise ValueError, 'pow(1,'+str(i)+') != 1' raise ValueError, 'pow(1,'+str(i)+') != 1'
for i in range(-100, 100): for i in range(-100, 100):
if (pow(type(i),3)!=i*i*i): if (pow(type(i),3)!=i*i*i):
raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i)
pow2=1 pow2=1
for i in range(0,31): for i in range(0,31):
if (pow(2,i)!=pow2): if (pow(2,i)!=pow2):
raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2)
if (i!=30): pow2=pow2*2 if (i!=30): pow2=pow2*2
print " Testing 3-argument pow() function..." print " Testing 3-argument pow() function..."
il, ih = -20, 20 il, ih = -20, 20
@ -31,7 +31,7 @@ def powtest(type):
compare = cmp compare = cmp
if (type==float): if (type==float):
il=1 il=1
compare = test_support.fcmp compare = test_support.fcmp
elif (type==int): elif (type==int):
jl=0 jl=0
elif (type==long): elif (type==long):
@ -39,11 +39,11 @@ def powtest(type):
for i in range(il, ih+1): for i in range(il, ih+1):
for j in range(jl,jh+1): for j in range(jl,jh+1):
for k in range(kl, kh+1): for k in range(kl, kh+1):
if (k!=0): if (k!=0):
if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): if compare(pow(type(i),j,k), pow(type(i),j)% type(k)):
raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ raise ValueError, "pow(" +str(i)+ "," +str(j)+ \
"," +str(k)+ ") != pow(" +str(i)+ "," + \ "," +str(k)+ ") != pow(" +str(i)+ "," + \
str(j)+ ") % " +str(k) str(j)+ ") % " +str(k)
print 'Testing integer mode...' print 'Testing integer mode...'

View file

@ -9,17 +9,17 @@ for e in entries:
name = e[0] name = e[0]
uid = e[2] uid = e[2]
if verbose: if verbose:
print name, uid print name, uid
print 'pwd.getpwuid()' print 'pwd.getpwuid()'
dbuid = pwd.getpwuid(uid) dbuid = pwd.getpwuid(uid)
if dbuid[0] <> name: if dbuid[0] <> name:
print 'Mismatch in pwd.getpwuid()' print 'Mismatch in pwd.getpwuid()'
print 'pwd.getpwnam()' print 'pwd.getpwnam()'
dbname = pwd.getpwnam(name) dbname = pwd.getpwnam(name)
if dbname[2] <> uid: if dbname[2] <> uid:
print 'Mismatch in pwd.getpwnam()' print 'Mismatch in pwd.getpwnam()'
else: else:
print 'name matches uid' print 'name matches uid'
break break
# try to get some errors # try to get some errors
@ -35,21 +35,21 @@ fakename = allnames[namei]
while bynames.has_key(fakename): while bynames.has_key(fakename):
chars = map(None, fakename) chars = map(None, fakename)
for i in range(len(chars)): for i in range(len(chars)):
if chars[i] == 'z': if chars[i] == 'z':
chars[i] = 'A' chars[i] = 'A'
break break
elif chars[i] == 'Z': elif chars[i] == 'Z':
continue continue
else: else:
chars[i] = chr(ord(chars[i]) + 1) chars[i] = chr(ord(chars[i]) + 1)
break break
else: else:
namei = namei + 1 namei = namei + 1
try: try:
fakename = allnames[namei] fakename = allnames[namei]
except IndexError: except IndexError:
# should never happen... if so, just forget it # should never happen... if so, just forget it
break break
fakename = string.join(map(None, chars), '') fakename = string.join(map(None, chars), '')
try: try:

View file

@ -15,8 +15,8 @@ try:
assert re.sub("(?i)b+", "x", "bbbb BBBB") == 'x x' assert re.sub("(?i)b+", "x", "bbbb BBBB") == 'x x'
def bump_num(matchobj): def bump_num(matchobj):
int_value = int(matchobj.group(0)) int_value = int(matchobj.group(0))
return str(int_value + 1) return str(int_value + 1)
assert re.sub(r'\d+', bump_num, '08.2 -2 23x99y') == '9.3 -3 24x100y' assert re.sub(r'\d+', bump_num, '08.2 -2 23x99y') == '9.3 -3 24x100y'
@ -151,9 +151,9 @@ except AssertionError:
for flags in [re.I, re.M, re.X, re.S, re.L]: for flags in [re.I, re.M, re.X, re.S, re.L]:
try: try:
r = re.compile('^pattern$', flags) r = re.compile('^pattern$', flags)
except: except:
print 'Exception raised on flag', flags print 'Exception raised on flag', flags
from re_tests import * from re_tests import *
if verbose: if verbose:
@ -166,86 +166,86 @@ for t in tests:
sys.stdout.flush() sys.stdout.flush()
pattern=s=outcome=repl=expected=None pattern=s=outcome=repl=expected=None
if len(t)==5: if len(t)==5:
pattern, s, outcome, repl, expected = t pattern, s, outcome, repl, expected = t
elif len(t)==3: elif len(t)==3:
pattern, s, outcome = t pattern, s, outcome = t
else: else:
raise ValueError, ('Test tuples should have 3 or 5 fields',t) raise ValueError, ('Test tuples should have 3 or 5 fields',t)
try: try:
obj=re.compile(pattern) obj=re.compile(pattern)
except re.error: except re.error:
if outcome==SYNTAX_ERROR: pass # Expected a syntax error if outcome==SYNTAX_ERROR: pass # Expected a syntax error
else: else:
print '=== Syntax error:', t print '=== Syntax error:', t
except KeyboardInterrupt: raise KeyboardInterrupt except KeyboardInterrupt: raise KeyboardInterrupt
except: except:
print '*** Unexpected error ***' print '*** Unexpected error ***'
if verbose: if verbose:
traceback.print_exc(file=sys.stdout) traceback.print_exc(file=sys.stdout)
else: else:
try: try:
result=obj.search(s) result=obj.search(s)
except (re.error), msg: except (re.error), msg:
print '=== Unexpected exception', t, repr(msg) print '=== Unexpected exception', t, repr(msg)
if outcome==SYNTAX_ERROR: if outcome==SYNTAX_ERROR:
# This should have been a syntax error; forget it. # This should have been a syntax error; forget it.
pass pass
elif outcome==FAIL: elif outcome==FAIL:
if result is None: pass # No match, as expected if result is None: pass # No match, as expected
else: print '=== Succeeded incorrectly', t else: print '=== Succeeded incorrectly', t
elif outcome==SUCCEED: elif outcome==SUCCEED:
if result is not None: if result is not None:
# Matched, as expected, so now we compute the # Matched, as expected, so now we compute the
# result string and compare it to our expected result. # result string and compare it to our expected result.
start, end = result.span(0) start, end = result.span(0)
vardict={'found': result.group(0), vardict={'found': result.group(0),
'groups': result.group(), 'groups': result.group(),
'flags': result.re.flags} 'flags': result.re.flags}
for i in range(1, 100): for i in range(1, 100):
try: try:
gi = result.group(i) gi = result.group(i)
# Special hack because else the string concat fails: # Special hack because else the string concat fails:
if gi is None: if gi is None:
gi = "None" gi = "None"
except IndexError: except IndexError:
gi = "Error" gi = "Error"
vardict['g%d' % i] = gi vardict['g%d' % i] = gi
for i in result.re.groupindex.keys(): for i in result.re.groupindex.keys():
try: try:
gi = result.group(i) gi = result.group(i)
if gi is None: if gi is None:
gi = "None" gi = "None"
except IndexError: except IndexError:
gi = "Error" gi = "Error"
vardict[i] = gi vardict[i] = gi
repl=eval(repl, vardict) repl=eval(repl, vardict)
if repl!=expected: if repl!=expected:
print '=== grouping error', t, print '=== grouping error', t,
print repr(repl)+' should be '+repr(expected) print repr(repl)+' should be '+repr(expected)
else: else:
print '=== Failed incorrectly', t print '=== Failed incorrectly', t
# Try the match with the search area limited to the extent # Try the match with the search area limited to the extent
# of the match and see if it still succeeds. \B will # of the match and see if it still succeeds. \B will
# break (because it won't match at the end or start of a # break (because it won't match at the end or start of a
# string), so we'll ignore patterns that feature it. # string), so we'll ignore patterns that feature it.
if pattern[:2]!='\\B' and pattern[-2:]!='\\B': if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
obj=re.compile(pattern) obj=re.compile(pattern)
result=obj.search(s, pos=result.start(0), endpos=result.end(0)+1) result=obj.search(s, pos=result.start(0), endpos=result.end(0)+1)
if result==None: if result==None:
print '=== Failed on range-limited match', t print '=== Failed on range-limited match', t
# Try the match with IGNORECASE enabled, and check that it # Try the match with IGNORECASE enabled, and check that it
# still succeeds. # still succeeds.
obj=re.compile(pattern, re.IGNORECASE) obj=re.compile(pattern, re.IGNORECASE)
result=obj.search(s) result=obj.search(s)
if result==None: if result==None:
print '=== Fails on case-insensitive match', t print '=== Fails on case-insensitive match', t
# Try the match with LOCALE enabled, and check that it # Try the match with LOCALE enabled, and check that it
# still succeeds. # still succeeds.
obj=re.compile(pattern, re.LOCALE) obj=re.compile(pattern, re.LOCALE)
result=obj.search(s) result=obj.search(s)
if result==None: if result==None:

View file

@ -67,44 +67,44 @@ if verbose: print 'Running regex_tests test suite'
for t in tests: for t in tests:
pattern=s=outcome=repl=expected=None pattern=s=outcome=repl=expected=None
if len(t)==5: if len(t)==5:
pattern, s, outcome, repl, expected = t pattern, s, outcome, repl, expected = t
elif len(t)==3: elif len(t)==3:
pattern, s, outcome = t pattern, s, outcome = t
else: else:
raise ValueError, ('Test tuples should have 3 or 5 fields',t) raise ValueError, ('Test tuples should have 3 or 5 fields',t)
try: try:
obj=regex.compile(pattern) obj=regex.compile(pattern)
except regex.error: except regex.error:
if outcome==SYNTAX_ERROR: pass # Expected a syntax error if outcome==SYNTAX_ERROR: pass # Expected a syntax error
else: else:
# Regex syntax errors aren't yet reported, so for # Regex syntax errors aren't yet reported, so for
# the official test suite they'll be quietly ignored. # the official test suite they'll be quietly ignored.
pass pass
#print '=== Syntax error:', t #print '=== Syntax error:', t
else: else:
try: try:
result=obj.search(s) result=obj.search(s)
except regex.error, msg: except regex.error, msg:
print '=== Unexpected exception', t, repr(msg) print '=== Unexpected exception', t, repr(msg)
if outcome==SYNTAX_ERROR: if outcome==SYNTAX_ERROR:
# This should have been a syntax error; forget it. # This should have been a syntax error; forget it.
pass pass
elif outcome==FAIL: elif outcome==FAIL:
if result==-1: pass # No match, as expected if result==-1: pass # No match, as expected
else: print '=== Succeeded incorrectly', t else: print '=== Succeeded incorrectly', t
elif outcome==SUCCEED: elif outcome==SUCCEED:
if result!=-1: if result!=-1:
# Matched, as expected, so now we compute the # Matched, as expected, so now we compute the
# result string and compare it to our expected result. # result string and compare it to our expected result.
start, end = obj.regs[0] start, end = obj.regs[0]
found=s[start:end] found=s[start:end]
groups=obj.group(1,2,3,4,5,6,7,8,9,10) groups=obj.group(1,2,3,4,5,6,7,8,9,10)
vardict=vars() vardict=vars()
for i in range(len(groups)): for i in range(len(groups)):
vardict['g'+str(i+1)]=str(groups[i]) vardict['g'+str(i+1)]=str(groups[i])
repl=eval(repl) repl=eval(repl)
if repl!=expected: if repl!=expected:
print '=== grouping error', t, repr(repl)+' should be '+repr(expected) print '=== grouping error', t, repr(repl)+' should be '+repr(expected)
else: else:
print '=== Failed incorrectly', t print '=== Failed incorrectly', t

View file

@ -9,32 +9,32 @@ error = 'test_rgbimg.error'
print 'RGBimg test suite:' print 'RGBimg test suite:'
def findfile(file): def findfile(file):
if os.path.isabs(file): return file if os.path.isabs(file): return file
import sys import sys
path = sys.path path = sys.path
try: try:
path = [os.path.dirname(__file__)] + path path = [os.path.dirname(__file__)] + path
except NameError: except NameError:
pass pass
for dn in path: for dn in path:
fn = os.path.join(dn, file) fn = os.path.join(dn, file)
if os.path.exists(fn): return fn if os.path.exists(fn): return fn
return file return file
def testimg(rgb_file, raw_file): def testimg(rgb_file, raw_file):
rgb_file = findfile(rgb_file) rgb_file = findfile(rgb_file)
raw_file = findfile(raw_file) raw_file = findfile(raw_file)
width, height = rgbimg.sizeofimage(rgb_file) width, height = rgbimg.sizeofimage(rgb_file)
rgb = rgbimg.longimagedata(rgb_file) rgb = rgbimg.longimagedata(rgb_file)
if len(rgb) != width * height * 4: if len(rgb) != width * height * 4:
raise error, 'bad image length' raise error, 'bad image length'
raw = open(raw_file, 'rb').read() raw = open(raw_file, 'rb').read()
if rgb != raw: if rgb != raw:
raise error, \ raise error, \
'images don\'t match for '+rgb_file+' and '+raw_file 'images don\'t match for '+rgb_file+' and '+raw_file
for depth in [1, 3, 4]: for depth in [1, 3, 4]:
rgbimg.longstoimage(rgb, width, height, depth, '@.rgb') rgbimg.longstoimage(rgb, width, height, depth, '@.rgb')
os.unlink('@.rgb') os.unlink('@.rgb')
table = [ table = [
('testrgb.uue', 'test.rgb'), ('testrgb.uue', 'test.rgb'),
@ -45,7 +45,7 @@ for source, target in table:
source = findfile(source) source = findfile(source)
target = findfile(target) target = findfile(target)
if verbose: if verbose:
print "uudecoding", source, "->", target, "..." print "uudecoding", source, "->", target, "..."
uu.decode(source, target) uu.decode(source, target)
if verbose: if verbose:
@ -53,23 +53,23 @@ if verbose:
ttob = rgbimg.ttob(0) ttob = rgbimg.ttob(0)
if ttob != 0: if ttob != 0:
raise error, 'ttob should start out as zero' raise error, 'ttob should start out as zero'
testimg('test.rgb', 'test.rawimg') testimg('test.rgb', 'test.rawimg')
ttob = rgbimg.ttob(1) ttob = rgbimg.ttob(1)
if ttob != 0: if ttob != 0:
raise error, 'ttob should be zero' raise error, 'ttob should be zero'
testimg('test.rgb', 'test.rawimg.rev') testimg('test.rgb', 'test.rawimg.rev')
ttob = rgbimg.ttob(0) ttob = rgbimg.ttob(0)
if ttob != 1: if ttob != 1:
raise error, 'ttob should be one' raise error, 'ttob should be one'
ttob = rgbimg.ttob(0) ttob = rgbimg.ttob(0)
if ttob != 0: if ttob != 0:
raise error, 'ttob should be zero' raise error, 'ttob should be zero'
for source, target in table: for source, target in table:
unlink(findfile(target)) unlink(findfile(target))

View file

@ -16,7 +16,7 @@ class Nope:
class Almost: class Almost:
def fileno(self): def fileno(self):
return 'fileno' return 'fileno'
try: try:
rfd, wfd, xfd = select.select([Nope()], [], []) rfd, wfd, xfd = select.select([Nope()], [], [])
@ -34,31 +34,31 @@ else:
def test(): def test():
import sys import sys
if sys.platform[:3] in ('win', 'mac', 'os2'): if sys.platform[:3] in ('win', 'mac', 'os2'):
if verbose: if verbose:
print "Can't test select easily on", sys.platform print "Can't test select easily on", sys.platform
return return
cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
p = os.popen(cmd, 'r') p = os.popen(cmd, 'r')
for tout in (0, 1, 2, 4, 8, 16) + (None,)*10: for tout in (0, 1, 2, 4, 8, 16) + (None,)*10:
if verbose: if verbose:
print 'timeout =', tout print 'timeout =', tout
rfd, wfd, xfd = select.select([p], [], [], tout) rfd, wfd, xfd = select.select([p], [], [], tout)
## print rfd, wfd, xfd ## print rfd, wfd, xfd
if (rfd, wfd, xfd) == ([], [], []): if (rfd, wfd, xfd) == ([], [], []):
continue continue
if (rfd, wfd, xfd) == ([p], [], []): if (rfd, wfd, xfd) == ([p], [], []):
line = p.readline() line = p.readline()
if verbose: if verbose:
print `line` print `line`
if not line: if not line:
if verbose: if verbose:
print 'EOF' print 'EOF'
break break
continue continue
print 'Heh?' print 'Heh?'
p.close() p.close()
test() test()

View file

@ -1,11 +1,11 @@
# Not tested: # Not tested:
# socket.fromfd() # socket.fromfd()
# sktobj.getsockopt() # sktobj.getsockopt()
# sktobj.recvfrom() # sktobj.recvfrom()
# sktobj.sendto() # sktobj.sendto()
# sktobj.setblocking() # sktobj.setblocking()
# sktobj.setsockopt() # sktobj.setsockopt()
# sktobj.shutdown() # sktobj.shutdown()
from test_support import verbose, TestFailed from test_support import verbose, TestFailed
@ -16,9 +16,9 @@ import string
def missing_ok(str): def missing_ok(str):
try: try:
getattr(socket, str) getattr(socket, str)
except AttributeError: except AttributeError:
pass pass
try: raise socket.error try: raise socket.error
except socket.error: print "socket.error" except socket.error: print "socket.error"
@ -33,37 +33,37 @@ socket.SOCK_SEQPACKET
for optional in ("AF_UNIX", for optional in ("AF_UNIX",
"SO_DEBUG", "SO_ACCEPTCONN", "SO_REUSEADDR", "SO_KEEPALIVE", "SO_DEBUG", "SO_ACCEPTCONN", "SO_REUSEADDR", "SO_KEEPALIVE",
"SO_DONTROUTE", "SO_BROADCAST", "SO_USELOOPBACK", "SO_LINGER", "SO_DONTROUTE", "SO_BROADCAST", "SO_USELOOPBACK", "SO_LINGER",
"SO_OOBINLINE", "SO_REUSEPORT", "SO_SNDBUF", "SO_RCVBUF", "SO_OOBINLINE", "SO_REUSEPORT", "SO_SNDBUF", "SO_RCVBUF",
"SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO", "SO_RCVTIMEO", "SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO", "SO_RCVTIMEO",
"SO_ERROR", "SO_TYPE", "SOMAXCONN", "SO_ERROR", "SO_TYPE", "SOMAXCONN",
"MSG_OOB", "MSG_PEEK", "MSG_DONTROUTE", "MSG_EOR", "MSG_OOB", "MSG_PEEK", "MSG_DONTROUTE", "MSG_EOR",
"MSG_TRUNC", "MSG_CTRUNC", "MSG_WAITALL", "MSG_BTAG", "MSG_TRUNC", "MSG_CTRUNC", "MSG_WAITALL", "MSG_BTAG",
"MSG_ETAG", "MSG_ETAG",
"SOL_SOCKET", "SOL_SOCKET",
"IPPROTO_IP", "IPPROTO_ICMP", "IPPROTO_IGMP", "IPPROTO_IP", "IPPROTO_ICMP", "IPPROTO_IGMP",
"IPPROTO_GGP", "IPPROTO_TCP", "IPPROTO_EGP", "IPPROTO_GGP", "IPPROTO_TCP", "IPPROTO_EGP",
"IPPROTO_PUP", "IPPROTO_UDP", "IPPROTO_IDP", "IPPROTO_PUP", "IPPROTO_UDP", "IPPROTO_IDP",
"IPPROTO_HELLO", "IPPROTO_ND", "IPPROTO_TP", "IPPROTO_HELLO", "IPPROTO_ND", "IPPROTO_TP",
"IPPROTO_XTP", "IPPROTO_EON", "IPPROTO_BIP", "IPPROTO_XTP", "IPPROTO_EON", "IPPROTO_BIP",
"IPPROTO_RAW", "IPPROTO_MAX", "IPPROTO_RAW", "IPPROTO_MAX",
"IPPORT_RESERVED", "IPPORT_USERRESERVED", "IPPORT_RESERVED", "IPPORT_USERRESERVED",
"INADDR_ANY", "INADDR_BROADCAST", "INADDR_LOOPBACK", "INADDR_ANY", "INADDR_BROADCAST", "INADDR_LOOPBACK",
"INADDR_UNSPEC_GROUP", "INADDR_ALLHOSTS_GROUP", "INADDR_UNSPEC_GROUP", "INADDR_ALLHOSTS_GROUP",
"INADDR_MAX_LOCAL_GROUP", "INADDR_NONE", "INADDR_MAX_LOCAL_GROUP", "INADDR_NONE",
"IP_OPTIONS", "IP_HDRINCL", "IP_TOS", "IP_TTL", "IP_OPTIONS", "IP_HDRINCL", "IP_TOS", "IP_TTL",
"IP_RECVOPTS", "IP_RECVRETOPTS", "IP_RECVDSTADDR", "IP_RECVOPTS", "IP_RECVRETOPTS", "IP_RECVDSTADDR",
"IP_RETOPTS", "IP_MULTICAST_IF", "IP_MULTICAST_TTL", "IP_RETOPTS", "IP_MULTICAST_IF", "IP_MULTICAST_TTL",
"IP_MULTICAST_LOOP", "IP_ADD_MEMBERSHIP", "IP_MULTICAST_LOOP", "IP_ADD_MEMBERSHIP",
"IP_DROP_MEMBERSHIP", "IP_DROP_MEMBERSHIP",
): ):
missing_ok(optional) missing_ok(optional)
socktype = socket.SocketType socktype = socket.SocketType
@ -80,7 +80,7 @@ if verbose:
for name in all_host_names: for name in all_host_names:
if string.find(name, '.'): if string.find(name, '.'):
break break
else: else:
print 'FQDN not found' print 'FQDN not found'
@ -95,52 +95,52 @@ canfork = hasattr(os, 'fork')
try: try:
PORT = 50007 PORT = 50007
if not canfork or os.fork(): if not canfork or os.fork():
# parent is server # parent is server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(hostname, PORT) s.bind(hostname, PORT)
s.listen(1) s.listen(1)
if verbose: if verbose:
print 'parent accepting' print 'parent accepting'
if canfork: if canfork:
conn, addr = s.accept() conn, addr = s.accept()
if verbose: if verbose:
print 'connected by', addr print 'connected by', addr
# couple of interesting tests while we've got a live socket # couple of interesting tests while we've got a live socket
f = conn.fileno() f = conn.fileno()
if verbose: if verbose:
print 'fileno:', f print 'fileno:', f
p = conn.getpeername() p = conn.getpeername()
if verbose: if verbose:
print 'peer:', p print 'peer:', p
n = conn.getsockname() n = conn.getsockname()
if verbose: if verbose:
print 'sockname:', n print 'sockname:', n
f = conn.makefile() f = conn.makefile()
if verbose: if verbose:
print 'file obj:', f print 'file obj:', f
while 1: while 1:
data = conn.recv(1024) data = conn.recv(1024)
if not data: if not data:
break break
if verbose: if verbose:
print 'received:', data print 'received:', data
conn.send(data) conn.send(data)
conn.close() conn.close()
else: else:
try: try:
# child is client # child is client
time.sleep(5) time.sleep(5)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if verbose: if verbose:
print 'child connecting' print 'child connecting'
s.connect(hostname, PORT) s.connect(hostname, PORT)
msg = 'socket test' msg = 'socket test'
s.send(msg) s.send(msg)
data = s.recv(1024) data = s.recv(1024)
if msg <> data: if msg <> data:
print 'parent/client mismatch' print 'parent/client mismatch'
s.close() s.close()
finally: finally:
os._exit(1) os._exit(1)
except socket.error, msg: except socket.error, msg:
raise TestFailed, msg raise TestFailed, msg

View file

@ -13,12 +13,12 @@ def main():
# Try a bunch of dates and times, chosen to vary through time of # Try a bunch of dates and times, chosen to vary through time of
# day and daylight saving time # day and daylight saving time
for j in range(-5, 5): for j in range(-5, 5):
for i in range(25): for i in range(25):
strftest(now + (i + j*100)*23*3603) strftest(now + (i + j*100)*23*3603)
def strftest(now): def strftest(now):
if verbose: if verbose:
print "strftime test for", time.ctime(now) print "strftime test for", time.ctime(now)
nowsecs = str(long(now))[:-1] nowsecs = str(long(now))[:-1]
gmt = time.gmtime(now) gmt = time.gmtime(now)
now = time.localtime(now) now = time.localtime(now)
@ -29,106 +29,106 @@ def strftest(now):
jan1 = time.localtime(time.mktime((now[0], 1, 1) + (0,)*6)) jan1 = time.localtime(time.mktime((now[0], 1, 1) + (0,)*6))
try: try:
if now[8]: tz = time.tzname[1] if now[8]: tz = time.tzname[1]
else: tz = time.tzname[0] else: tz = time.tzname[0]
except AttributeError: except AttributeError:
tz = '' tz = ''
if now[3] > 12: clock12 = now[3] - 12 if now[3] > 12: clock12 = now[3] - 12
elif now[3] > 0: clock12 = now[3] elif now[3] > 0: clock12 = now[3]
else: clock12 = 12 else: clock12 = 12
expectations = ( expectations = (
('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'),
('%A', calendar.day_name[now[6]], 'full weekday name'), ('%A', calendar.day_name[now[6]], 'full weekday name'),
('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'),
('%B', calendar.month_name[now[1]], 'full month name'), ('%B', calendar.month_name[now[1]], 'full month name'),
# %c see below # %c see below
('%d', '%02d' % now[2], 'day of month as number (00-31)'), ('%d', '%02d' % now[2], 'day of month as number (00-31)'),
('%H', '%02d' % now[3], 'hour (00-23)'), ('%H', '%02d' % now[3], 'hour (00-23)'),
('%I', '%02d' % clock12, 'hour (01-12)'), ('%I', '%02d' % clock12, 'hour (01-12)'),
('%j', '%03d' % now[7], 'julian day (001-366)'), ('%j', '%03d' % now[7], 'julian day (001-366)'),
('%m', '%02d' % now[1], 'month as number (01-12)'), ('%m', '%02d' % now[1], 'month as number (01-12)'),
('%M', '%02d' % now[4], 'minute, (00-59)'), ('%M', '%02d' % now[4], 'minute, (00-59)'),
('%p', ampm, 'AM or PM as appropriate'), ('%p', ampm, 'AM or PM as appropriate'),
('%S', '%02d' % now[5], 'seconds of current time (00-60)'), ('%S', '%02d' % now[5], 'seconds of current time (00-60)'),
('%U', '%02d' % ((now[7] + jan1[6])/7), ('%U', '%02d' % ((now[7] + jan1[6])/7),
'week number of the year (Sun 1st)'), 'week number of the year (Sun 1st)'),
('%w', '%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), ('%w', '%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'),
('%W', '%02d' % ((now[7] + (jan1[6] - 1)%7)/7), ('%W', '%02d' % ((now[7] + (jan1[6] - 1)%7)/7),
'week number of the year (Mon 1st)'), 'week number of the year (Mon 1st)'),
# %x see below # %x see below
('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'),
('%y', '%02d' % (now[0]%100), 'year without century'), ('%y', '%02d' % (now[0]%100), 'year without century'),
('%Y', '%d' % now[0], 'year with century'), ('%Y', '%d' % now[0], 'year with century'),
# %Z see below # %Z see below
('%%', '%', 'single percent sign'), ('%%', '%', 'single percent sign'),
) )
nonstandard_expectations = ( nonstandard_expectations = (
# These are standard but don't have predictable output # These are standard but don't have predictable output
('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'),
('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)),
'%m/%d/%y %H:%M:%S'), '%m/%d/%y %H:%M:%S'),
('(%Z)', '(%s)' % tz, 'time zone name'), ('(%Z)', '(%s)' % tz, 'time zone name'),
# These are some platform specific extensions # These are some platform specific extensions
('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'),
('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'),
('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'),
('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'),
('%n', '\n', 'newline character'), ('%n', '\n', 'newline character'),
('%r', '%02d:%02d:%02d %s' % (clock12, now[4], now[5], ampm), ('%r', '%02d:%02d:%02d %s' % (clock12, now[4], now[5], ampm),
'%I:%M:%S %p'), '%I:%M:%S %p'),
('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'),
('%s', nowsecs, 'seconds since the Epoch in UCT'), ('%s', nowsecs, 'seconds since the Epoch in UCT'),
('%t', '\t', 'tab character'), ('%t', '\t', 'tab character'),
('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'),
('%3y', '%03d' % (now[0]%100), ('%3y', '%03d' % (now[0]%100),
'year without century rendered using fieldwidth'), 'year without century rendered using fieldwidth'),
) )
if verbose: if verbose:
print "Strftime test, platform: %s, Python version: %s" % \ print "Strftime test, platform: %s, Python version: %s" % \
(sys.platform, string.split(sys.version)[0]) (sys.platform, string.split(sys.version)[0])
for e in expectations: for e in expectations:
try: try:
result = time.strftime(e[0], now) result = time.strftime(e[0], now)
except ValueError, error: except ValueError, error:
print "Standard '%s' format gave error:" % e[0], error print "Standard '%s' format gave error:" % e[0], error
continue continue
if result == e[1]: continue if result == e[1]: continue
if result[0] == '%': if result[0] == '%':
print "Does not support standard '%s' format (%s)" % (e[0], e[2]) print "Does not support standard '%s' format (%s)" % (e[0], e[2])
else: else:
print "Conflict for %s (%s):" % (e[0], e[2]) print "Conflict for %s (%s):" % (e[0], e[2])
print " Expected %s, but got %s" % (e[1], result) print " Expected %s, but got %s" % (e[1], result)
for e in nonstandard_expectations: for e in nonstandard_expectations:
try: try:
result = time.strftime(e[0], now) result = time.strftime(e[0], now)
except ValueError, result: except ValueError, result:
if verbose: if verbose:
print "Error for nonstandard '%s' format (%s): %s" % \ print "Error for nonstandard '%s' format (%s): %s" % \
(e[0], e[2], str(result)) (e[0], e[2], str(result))
continue continue
if result == e[1]: if result == e[1]:
if verbose: if verbose:
print "Supports nonstandard '%s' format (%s)" % (e[0], e[2]) print "Supports nonstandard '%s' format (%s)" % (e[0], e[2])
elif result[0] == '%': elif result[0] == '%':
if verbose: if verbose:
print "Does not appear to support '%s' format (%s)" % (e[0], print "Does not appear to support '%s' format (%s)" % (e[0],
e[2]) e[2])
else: else:
if verbose: if verbose:
print "Conflict for nonstandard '%s' format (%s):" % (e[0], print "Conflict for nonstandard '%s' format (%s):" % (e[0],
e[2]) e[2])
print " Expected %s, but got %s" % (e[1], result) print " Expected %s, but got %s" % (e[1], result)
def fixasctime(s): def fixasctime(s):
if s[8] == ' ': if s[8] == ' ':
s = s[:8] + '0' + s[9:] s = s[:8] + '0' + s[9:]
return s return s
main() main()

View file

@ -3,19 +3,19 @@ import strop, sys
def test(name, input, output, *args): def test(name, input, output, *args):
if verbose: if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output), print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name) f = getattr(strop, name)
try: try:
value = apply(f, (input,) + args) value = apply(f, (input,) + args)
except: except:
value = sys.exc_type value = sys.exc_type
if value != output: if value != output:
if verbose: if verbose:
print 'no' print 'no'
print f, `input`, `output`, `value` print f, `input`, `output`, `value`
else: else:
if verbose: if verbose:
print 'yes' print 'yes'
test('atoi', " 1 ", 1) test('atoi', " 1 ", 1)
test('atoi', " 1x", ValueError) test('atoi', " 1x", ValueError)

View file

@ -4,13 +4,13 @@ import struct
def simple_err(func, *args): def simple_err(func, *args):
try: try:
apply(func, args) apply(func, args)
except struct.error: except struct.error:
pass pass
else: else:
raise TestFailed, "%s%s did not raise struct.error" % ( raise TestFailed, "%s%s did not raise struct.error" % (
func.__name__, args) func.__name__, args)
## pdb.set_trace() ## pdb.set_trace()
simple_err(struct.calcsize, 'Q') simple_err(struct.calcsize, 'Q')
@ -24,7 +24,7 @@ sz = struct.calcsize(fmt)
sz3 = struct.calcsize(fmt3) sz3 = struct.calcsize(fmt3)
if sz * 3 <> sz3: if sz * 3 <> sz3:
raise TestFailed, 'inconsistent sizes (3*%s -> 3*%d = %d, %s -> %d)' % ( raise TestFailed, 'inconsistent sizes (3*%s -> 3*%d = %d, %s -> %d)' % (
`fmt`, sz, 3*sz, `fmt3`, sz3) `fmt`, sz, 3*sz, `fmt3`, sz3)
simple_err(struct.pack, 'iii', 3) simple_err(struct.pack, 'iii', 3)
simple_err(struct.pack, 'i', 3, 3, 3) simple_err(struct.pack, 'i', 3, 3, 3)
@ -44,16 +44,16 @@ d = 3.1415
for prefix in ('', '@', '<', '>', '=', '!'): for prefix in ('', '@', '<', '>', '=', '!'):
for format in ('xcbhilfd', 'xcBHILfd'): for format in ('xcbhilfd', 'xcBHILfd'):
format = prefix + format format = prefix + format
if verbose: if verbose:
print "trying:", format print "trying:", format
s = struct.pack(format, c, b, h, i, l, f, d) s = struct.pack(format, c, b, h, i, l, f, d)
cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s) cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s)
if (cp <> c or bp <> b or hp <> h or ip <> i or lp <> l or if (cp <> c or bp <> b or hp <> h or ip <> i or lp <> l or
int(100 * fp) <> int(100 * f) or int(100 * dp) <> int(100 * d)): int(100 * fp) <> int(100 * f) or int(100 * dp) <> int(100 * d)):
# ^^^ calculate only to two decimal places # ^^^ calculate only to two decimal places
raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( raise TestFailed, "unpack/pack not transitive (%s, %s)" % (
str(format), str((cp, bp, hp, ip, lp, fp, dp))) str(format), str((cp, bp, hp, ip, lp, fp, dp)))
# Test some of the new features in detail # Test some of the new features in detail
@ -98,24 +98,24 @@ def badpack(fmt, arg, got, exp):
def badunpack(fmt, arg, got, exp): def badunpack(fmt, arg, got, exp):
return "unpack(%s, %s) -> (%s,) # expected (%s,)" % ( return "unpack(%s, %s) -> (%s,) # expected (%s,)" % (
`fmt`, `arg`, `got`, `exp`) `fmt`, `arg`, `got`, `exp`)
isbigendian = struct.pack('=h', 1) == '\0\1' isbigendian = struct.pack('=h', 1) == '\0\1'
for fmt, arg, big, lil, asy in tests: for fmt, arg, big, lil, asy in tests:
if verbose: if verbose:
print `fmt`, `arg`, `big`, `lil` print `fmt`, `arg`, `big`, `lil`
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil), for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
('='+fmt, isbigendian and big or lil)]: ('='+fmt, isbigendian and big or lil)]:
res = struct.pack(xfmt, arg) res = struct.pack(xfmt, arg)
if res != exp: if res != exp:
raise TestFailed, "pack(%s, %s) -> %s # expected %s" % ( raise TestFailed, "pack(%s, %s) -> %s # expected %s" % (
`fmt`, `arg`, `res`, `exp`) `fmt`, `arg`, `res`, `exp`)
n = struct.calcsize(xfmt) n = struct.calcsize(xfmt)
if n != len(res): if n != len(res):
raise TestFailed, "calcsize(%s) -> %d # expected %d" % ( raise TestFailed, "calcsize(%s) -> %d # expected %d" % (
`xfmt`, n, len(res)) `xfmt`, n, len(res))
rev = struct.unpack(xfmt, res)[0] rev = struct.unpack(xfmt, res)[0]
if rev != arg and not asy: if rev != arg and not asy:
raise TestFailed, "unpack(%s, %s) -> (%s,) # expected (%s,)" % ( raise TestFailed, "unpack(%s, %s) -> (%s,) # expected (%s,)" % (
`fmt`, `res`, `rev`, `arg`) `fmt`, `res`, `rev`, `arg`)

View file

@ -3,29 +3,29 @@ import sunaudiodev
import os import os
def findfile(file): def findfile(file):
if os.path.isabs(file): return file if os.path.isabs(file): return file
import sys import sys
path = sys.path path = sys.path
try: try:
path = [os.path.dirname(__file__)] + path path = [os.path.dirname(__file__)] + path
except NameError: except NameError:
pass pass
for dn in path: for dn in path:
fn = os.path.join(dn, file) fn = os.path.join(dn, file)
if os.path.exists(fn): return fn if os.path.exists(fn): return fn
return file return file
def play_sound_file(path): def play_sound_file(path):
fp = open(path, 'r') fp = open(path, 'r')
data = fp.read() data = fp.read()
fp.close() fp.close()
try: try:
a = sunaudiodev.open('w') a = sunaudiodev.open('w')
except sunaudiodev.error, msg: except sunaudiodev.error, msg:
raise TestFailed, msg raise TestFailed, msg
else: else:
a.write(data) a.write(data)
a.close() a.close()
def test(): def test():
play_sound_file(findfile('audiotest.au')) play_sound_file(findfile('audiotest.au'))

View file

@ -14,13 +14,13 @@ if long(time.mktime(time.localtime(t))) <> long(t):
time.sleep(1.2) time.sleep(1.2)
tt = time.gmtime(t) tt = time.gmtime(t)
for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
'j', 'm', 'M', 'p', 'S', 'j', 'm', 'M', 'p', 'S',
'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
format = ' %' + directive format = ' %' + directive
try: try:
time.strftime(format, tt) time.strftime(format, tt)
except ValueError: except ValueError:
print 'conversion specifier:', format, ' failed.' print 'conversion specifier:', format, ' failed.'
time.timezone time.timezone
time.tzname time.tzname
@ -33,7 +33,7 @@ except TypeError:
try: try:
time.mktime((999999, 999999, 999999, 999999, time.mktime((999999, 999999, 999999, 999999,
999999, 999999, 999999, 999999, 999999, 999999, 999999, 999999,
999999)) 999999))
except OverflowError: except OverflowError:
pass pass

View file

@ -5,8 +5,8 @@ l = [4, 5, 6]
class Seq: class Seq:
def __getitem__(self, i): def __getitem__(self, i):
if i >= 0 and i < 3: return i if i >= 0 and i < 3: return i
raise IndexError raise IndexError
a = -1 a = -1
b = -1 b = -1
@ -104,12 +104,12 @@ BozoError = 'BozoError'
class BadSeq: class BadSeq:
def __getitem__(self, i): def __getitem__(self, i):
if i >= 0 and i < 3: if i >= 0 and i < 3:
return i return i
elif i == 3: elif i == 3:
raise BozoError raise BozoError
else: else:
raise IndexError raise IndexError
# trigger code while not expecting an IndexError # trigger code while not expecting an IndexError