[pypy-svn] r8688 - in pypy/dist/pypy: appspace/test appspace/test/patched lib/test2
sanxiyn at codespeak.net
sanxiyn at codespeak.net
Sat Jan 29 07:37:09 CET 2005
Author: sanxiyn
Date: Sat Jan 29 07:37:09 2005
New Revision: 8688
Added:
pypy/dist/pypy/lib/test2/autopath.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/autopath.py
pypy/dist/pypy/lib/test2/builtin_functions_test.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/builtin_functions_test.py
pypy/dist/pypy/lib/test2/cpy_test_types.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/cpy_test_types.py
pypy/dist/pypy/lib/test2/no_test_stringmodule.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/no_test_stringmodule.py
pypy/dist/pypy/lib/test2/support_tests.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/support_tests.py
pypy/dist/pypy/lib/test2/test_cmathmodule.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_cmathmodule.py
pypy/dist/pypy/lib/test2/test_complexobject.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_complexobject.py
pypy/dist/pypy/lib/test2/test_exceptions.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_exceptions.py
pypy/dist/pypy/lib/test2/test_file.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_file.py
pypy/dist/pypy/lib/test2/test_md5.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_md5.py
pypy/dist/pypy/lib/test2/test_sha.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_sha.py
pypy/dist/pypy/lib/test2/test_struct.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/test_struct.py
pypy/dist/pypy/lib/test2/test_sys.py
- copied unchanged from r8687, pypy/dist/pypy/appspace/test/patched/test_sys.py
Removed:
pypy/dist/pypy/appspace/test/autopath.py
pypy/dist/pypy/appspace/test/builtin_functions_test.py
pypy/dist/pypy/appspace/test/cpy_test_types.py
pypy/dist/pypy/appspace/test/no_test_stringmodule.py
pypy/dist/pypy/appspace/test/patched/test_sys.py
pypy/dist/pypy/appspace/test/support_tests.py
pypy/dist/pypy/appspace/test/test_cmathmodule.py
pypy/dist/pypy/appspace/test/test_complexobject.py
pypy/dist/pypy/appspace/test/test_exceptions.py
pypy/dist/pypy/appspace/test/test_file.py
pypy/dist/pypy/appspace/test/test_md5.py
pypy/dist/pypy/appspace/test/test_sha.py
pypy/dist/pypy/appspace/test/test_struct.py
Log:
more file moves
Deleted: /pypy/dist/pypy/appspace/test/autopath.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/autopath.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,114 +0,0 @@
-"""
-self cloning, automatic path configuration
-
-copy this into any subdirectory of pypy from which scripts need
-to be run, typically all of the test subdirs.
-The idea is that any such script simply issues
-
- import autopath
-
-and this will make sure that the parent directory containing "pypy"
-is in sys.path.
-
-If you modify the master "autopath.py" version (in pypy/tool/autopath.py)
-you can directly run it which will copy itself on all autopath.py files
-it finds under the pypy root directory.
-
-This module always provides these attributes:
-
- pypydir pypy root directory path
- this_dir directory where this autopath.py resides
-
-"""
-
-
-def __dirinfo(part):
- """ return (partdir, this_dir) and insert parent of partdir
- into sys.path. If the parent directories don't have the part
- an EnvironmentError is raised."""
-
- import sys, os
- try:
- head = this_dir = os.path.realpath(os.path.dirname(__file__))
- except NameError:
- head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0]))
-
- while head:
- partdir = head
- head, tail = os.path.split(head)
- if tail == part:
- break
- else:
- raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir)
-
- checkpaths = sys.path[:]
- pypy_root = os.path.join(head, '')
-
- while checkpaths:
- orig = checkpaths.pop()
- if os.path.join(os.path.realpath(orig), '').startswith(pypy_root):
- sys.path.remove(orig)
- sys.path.insert(0, head)
-
- munged = {}
- for name, mod in sys.modules.items():
- fn = getattr(mod, '__file__', None)
- if '.' in name or not isinstance(fn, str):
- continue
- newname = os.path.splitext(os.path.basename(fn))[0]
- if not newname.startswith(part + '.'):
- continue
- path = os.path.join(os.path.dirname(os.path.realpath(fn)), '')
- if path.startswith(pypy_root) and newname != part:
- modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep)
- if newname != '__init__':
- modpaths.append(newname)
- modpath = '.'.join(modpaths)
- if modpath not in sys.modules:
- munged[modpath] = mod
-
- for name, mod in munged.iteritems():
- if name not in sys.modules:
- sys.modules[name] = mod
- if '.' in name:
- prename = name[:name.rfind('.')]
- postname = name[len(prename)+1:]
- if prename not in sys.modules:
- __import__(prename)
- if not hasattr(sys.modules[prename], postname):
- setattr(sys.modules[prename], postname, mod)
-
- return partdir, this_dir
-
-def __clone():
- """ clone master version of autopath.py into all subdirs """
- from os.path import join, walk
- if not this_dir.endswith(join('pypy','tool')):
- raise EnvironmentError("can only clone master version "
- "'%s'" % join(pypydir, 'tool',_myname))
-
-
- def sync_walker(arg, dirname, fnames):
- if _myname in fnames:
- fn = join(dirname, _myname)
- f = open(fn, 'rwb+')
- try:
- if f.read() == arg:
- print "checkok", fn
- else:
- print "syncing", fn
- f = open(fn, 'w')
- f.write(arg)
- finally:
- f.close()
- s = open(join(pypydir, 'tool', _myname), 'rb').read()
- walk(pypydir, sync_walker, s)
-
-_myname = 'autopath.py'
-
-# set guaranteed attributes
-
-pypydir, this_dir = __dirinfo('pypy')
-
-if __name__ == '__main__':
- __clone()
Deleted: /pypy/dist/pypy/appspace/test/builtin_functions_test.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/builtin_functions_test.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,1234 +0,0 @@
-# Python test set -- built-in functions
-import autopath
-from pypy.interpreter.gateway import app2interp_temp
-
-def app_init_globals():
- ''' support functionality for these tests '''
- import __builtin__ as b
-
- from sets import Set
- from support_tests import fcmp, have_unicode, TESTFN, unlink
-
- if not have_unicode:
- b.basestring = str
-
- import sys, cStringIO
-
- class Squares:
-
- def __init__(self, max):
- self.max = max
- self.sofar = []
-
- def __len__(self): return len(self.sofar)
-
- def __getitem__(self, i):
- if not 0 <= i < self.max: raise IndexError
- n = len(self.sofar)
- while n <= i:
- self.sofar.append(n*n)
- n += 1
- return self.sofar[i]
-
- class StrSquares:
-
- def __init__(self, max):
- self.max = max
- self.sofar = []
-
- def __len__(self):
- return len(self.sofar)
-
- def __getitem__(self, i):
- if not 0 <= i < self.max:
- raise IndexError
- n = len(self.sofar)
- while n <= i:
- self.sofar.append(str(n*n))
- n += 1
- return self.sofar[i]
-
- class BitBucket:
- def write(self, line):
- pass
-
- L = [
- ('0', 0),
- ('1', 1),
- ('9', 9),
- ('10', 10),
- ('99', 99),
- ('100', 100),
- ('314', 314),
- (' 314', 314),
- ('314 ', 314),
- (' \t\t 314 \t\t ', 314),
- (`sys.maxint`, sys.maxint),
- (' 1x', ValueError),
- (' 1 ', 1),
- (' 1\02 ', ValueError),
- ('', ValueError),
- (' ', ValueError),
- (' \t\t ', ValueError)
- ]
- if have_unicode:
- L += [
- (unicode('0'), 0),
- (unicode('1'), 1),
- (unicode('9'), 9),
- (unicode('10'), 10),
- (unicode('99'), 99),
- (unicode('100'), 100),
- (unicode('314'), 314),
- (unicode(' 314'), 314),
- (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
- (unicode(' \t\t 314 \t\t '), 314),
- (unicode(' 1x'), ValueError),
- (unicode(' 1 '), 1),
- (unicode(' 1\02 '), ValueError),
- (unicode(''), ValueError),
- (unicode(' '), ValueError),
- (unicode(' \t\t '), ValueError),
- (unichr(0x200), ValueError),
- ]
- b.Set = Set
- b.fcmp = fcmp
- b.have_unicode = have_unicode
- b.TESTFN = TESTFN
- b.unlink = unlink
- b.sys = sys
- b.cStringIO = cStringIO
- b.Squares = Squares
- b.StrSquares = StrSquares
- b.BitBucket = BitBucket
- b.L = L
-
-
-class AppTestBuiltin:
- objspacename = 'std'
-
- full_test = 1
-
- def setup_class(cls):
- app2interp_temp(app_init_globals)(cls.space)
-
- # we use "if 1:" to keep all method definitions indented, making
- # it maximally easy to edit this file to pick and choose which
- # ones to run (running everything takes 4 minutes or so...)
- if 1:
- def test_import(self):
- __import__('sys')
- __import__('time')
- __import__('string')
- raises(ImportError, __import__, 'spamspam')
- raises(TypeError, __import__, 1, 2, 3, 4)
-
- def test_abs(self):
- # int
- assert abs(0) == 0
- assert abs(1234) == 1234
- assert abs(-1234) == 1234
- # float
- assert abs(0.0) == 0.0
- assert abs(3.14) == 3.14
- assert abs(-3.14) == 3.14
- # long
- assert abs(0L) == 0L
- assert abs(1234L) == 1234L
- assert abs(-1234L) == 1234L
- # str
- raises(TypeError, abs, 'a')
-
- def test_apply(self):
- def f0(*args):
- assert args == ()
- def f1(a1):
- assert a1 == 1
- def f2(a1, a2):
- assert a1 == 1
- assert a2 == 2
- def f3(a1, a2, a3):
- assert a1 == 1
- assert a2 == 2
- assert a3 == 3
- apply(f0, ())
- apply(f1, (1,))
- apply(f2, (1, 2))
- apply(f3, (1, 2, 3))
-
- # A PyCFunction that takes only positional parameters should allow
- # an empty keyword dictionary to pass without a complaint, but
- # raise a TypeError if the dictionary is non-empty.
- apply(id, (1,), {})
- raises(TypeError, apply, id, (1,), {"foo": 1})
- raises(TypeError, apply)
- raises(TypeError, apply, id, 42)
- raises(TypeError, apply, id, (42,), 42)
-
- def test_callable(self):
- assert callable(len)
- def f(): pass
- assert callable(f)
- class C:
- def meth(self): pass
- assert callable(C)
- x = C()
- assert callable(x.meth)
- assert not callable(x)
- class D(C):
- def __call__(self): pass
- y = D()
- assert callable(y)
- y()
-
- def test_chr(self):
- assert chr(32) == ' '
- assert chr(65) == 'A'
- assert chr(97) == 'a'
- assert chr(0xff) == '\xff'
- raises(ValueError, chr, 256)
- raises(TypeError, chr)
-
- def test_cmp(self):
- assert cmp(-1, 1) == -1
- assert cmp(1, -1) == 1
- assert cmp(1, 1) == 0
- ''' TODO XXX Circular objects not handled yet
- # verify that circular objects are handled
- a = []; a.append(a)
- b = []; b.append(b)
- from UserList import UserList
- c = UserList(); c.append(c)
- assert cmp(a, b) == 0
- assert cmp(b, c) == 0
- assert cmp(c, a) == 0
- assert cmp(a, c) == 0
- # okay, now break the cycles
- a.pop(); b.pop(); c.pop()
- '''
- raises(TypeError, cmp)
-
- ''' TODO: XXX Coerce is not implemented
- def test_coerce(self):
- assert not fcmp(coerce(1, 1.1), (1.0, 1.1))
- assert coerce(1, 1L) == (1L, 1L)
- assert not fcmp(coerce(1L, 1.1), (1.0, 1.1))
- raises(TypeError, coerce)
- class BadNumber:
- def __coerce__(self, other):
- raise ValueError
- raises(ValueError, coerce, 42, BadNumber())
- raises(OverflowError, coerce, 0.5, int("12345" * 1000))
- '''
-
- def test_compile(self):
- compile('print 1\n', '', 'exec')
- bom = '\xef\xbb\xbf'
- compile(bom + 'print 1\n', '', 'exec')
- raises(TypeError, compile)
- raises(ValueError, compile,
- 'print 42\n', '<string>', 'badmode')
- raises(ValueError, compile,
- 'print 42\n', '<string>', 'single', 0xff)
- if have_unicode:
- compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
-
- def test_delattr(self):
- import sys
- sys.spam = 1
- delattr(sys, 'spam')
- raises(TypeError, delattr)
-
- def test_dir(self):
- x = 1
- assert 'x' in dir()
- import sys
- assert 'modules' in dir(sys)
- raises(TypeError, dir, 42, 42)
-
- def test_divmod(self):
- assert divmod(12, 7) == (1, 5)
- assert divmod(-12, 7) == (-2, 2)
- assert divmod(12, -7) == (-2, -2)
- assert divmod(-12, -7) == (1, -5)
-
- assert divmod(12L, 7L) == (1L, 5L)
- assert divmod(-12L, 7L) == (-2L, 2L)
- assert divmod(12L, -7L) == (-2L, -2L)
- assert divmod(-12L, -7L) == (1L, -5L)
-
- assert divmod(12, 7L) == (1, 5L)
- assert divmod(-12, 7L) == (-2, 2L)
- assert divmod(12L, -7) == (-2L, -2)
- assert divmod(-12L, -7) == (1L, -5)
-
- assert not fcmp(divmod(3.25, 1.0), (3.0, 0.25))
- assert not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))
- assert not fcmp(divmod(3.25, -1.0), (-4.0, -0.75))
- assert not fcmp(divmod(-3.25, -1.0), (3.0, -0.25))
-
- raises(TypeError, divmod)
-
- ''' XXX TODO No eval() support yet
- def test_eval(self):
- assert eval('1+1') == 2
- assert eval(' 1+1\n') == 2
- globals = {'a': 1, 'b': 2}
- locals = {'b': 200, 'c': 300}
- assert eval('a', globals) == 1
- assert eval('a', globals, locals) == 1
- assert eval('b', globals, locals) == 200
- assert eval('c', globals, locals) == 300
- if have_unicode:
- assert eval(unicode('1+1')) == 2
- assert eval(unicode(' 1+1\n')) == 2
- globals = {'a': 1, 'b': 2}
- locals = {'b': 200, 'c': 300}
- if have_unicode:
- assert eval(unicode('a'), globals) == 1
- assert eval(unicode('a'), globals, locals) == 1
- assert eval(unicode('b'), globals, locals) == 200
- assert eval(unicode('c'), globals, locals) == 300
- bom = '\xef\xbb\xbf'
- assert eval(bom + 'a', globals, locals) == 1
- assert eval(unicode('u"\xc3\xa5"', 'utf8'), globals) == (
- unicode('\xc3\xa5', 'utf8'))
- raises(TypeError, eval)
- raises(TypeError, eval, ())
-
- '\'' XXX TODO: Figure out later
- # Done outside of the method test_z to get the correct scope
- z = 0
- f = open(TESTFN, 'w')
- f.write('z = z+1\n')
- f.write('z = z*2\n')
- f.close()
- execfile(TESTFN)
-
- def test_execfile(self):
- globals = {'a': 1, 'b': 2}
- locals = {'b': 200, 'c': 300}
-
- assert self.__class__.z == 2
- globals['z'] = 0
- execfile(TESTFN, globals)
- assert globals['z'] == 2
- locals['z'] = 0
- execfile(TESTFN, globals, locals)
- assert locals['z'] == 2
- unlink(TESTFN)
- raises(TypeError, execfile)
- import os
- raises(IOError, execfile, os.curdir)
- raises(IOError, execfile, "I_dont_exist")
- '\''
- '''
-
- ''' XXX TODO: filter does NOT rely on __getitem__, but rather on
- __iter__; it appears to me that the following two tests,
- therefore, pass in CPython only because of the accident that
- in that implementation str does not define __iter__ (while
- list and tuple do, in 2.3). Probably best to substitute
- most of these tests with more appropriate ones!
- '''
- def test_filter(self):
- assert filter(lambda c: 'a' <= c <= 'z', 'Hello World') == (
- 'elloorld')
- assert (filter(None, [1, 'hello', [], [3], '', None, 9, 0])
- ) == [1, 'hello', [3], 9]
- assert filter(lambda x: x > 0, [1, -3, 9, 0, 2]) == (
- [1, 9, 2])
- assert filter(None, Squares(10)) == (
- [1, 4, 9, 16, 25, 36, 49, 64, 81])
- assert filter(lambda x: x%2, Squares(10)) == (
- [1, 9, 25, 49, 81])
- def identity(item):
- return 1
- filter(identity, Squares(5))
- raises(TypeError, filter)
- ''' XXX rest of test disabled as above explained
- class BadSeq(object):
- def __getitem__(self, index):
- if index<4:
- return 42
- raise ValueError
- raises(ValueError, filter, lambda x: x, BadSeq())
- def badfunc():
- pass
- raises(TypeError, filter, badfunc, range(5))
-
- # test bltinmodule.c::filtertuple()
- assert filter(None, (1, 2)) == (1, 2)
- assert filter(lambda x: x>=3, (1, 2, 3, 4)) == (3, 4)
- raises(TypeError, filter, 42, (1, 2))
-
- # test bltinmodule.c::filterstring()
- assert filter(None, "12") == "12"
- assert filter(lambda x: x>="3", "1234") == "34"
- raises(TypeError, filter, 42, "12")
- class badstr(str):
- def __getitem__(self, index):
- raise ValueError
- raises(ValueError, filter,
- lambda x: x >="3", badstr("1234"))
-
- class badstr2(str):
- def __getitem__(self, index):
- return 42
- raises(TypeError, filter,
- lambda x: x >=42, badstr2("1234"))
-
- class weirdstr(str):
- def __getitem__(self, index):
- return weirdstr(2*str.__getitem__(self, index))
- assert filter(lambda x: x>="33", weirdstr("1234")) == (
- "3344")
-
- class shiftstr(str):
- def __getitem__(self, index):
- return chr(ord(str.__getitem__(self, index))+1)
- assert filter(lambda x: x>="3", shiftstr("1234")) == "345"
-
- if have_unicode:
- # test bltinmodule.c::filterunicode()
- assert filter(None, unicode("12")) == unicode("12")
- assert filter(lambda x: x>="3", unicode("1234")) == (
- unicode("34"))
- raises(TypeError, filter, 42, unicode("12"))
- raises(ValueError, filter, lambda x: x >="3",
- badstr(unicode("1234")))
-
- class badunicode(unicode):
- def __getitem__(self, index):
- return 42
- raises(TypeError, filter, lambda x: x >=42,
- badunicode("1234"))
-
- class weirdunicode(unicode):
- def __getitem__(self, index):
- return weirdunicode(2*unicode.__getitem__(self, index))
- assert (
- filter(lambda x: x>=unicode("33"), weirdunicode("1234"))) == (
- unicode("3344"))
-
- class shiftunicode(unicode):
- def __getitem__(self, index):
- return unichr(ord(unicode.__getitem__(self, index))+1)
- assert (
- filter(lambda x: x>=unicode("3"), shiftunicode("1234"))) == (
- unicode("345")
- )
-
- def test_filter_subclasses(self):
- # test that filter() never returns tuple, str or unicode subclasses
- # and that the result always goes through __getitem__
- funcs = (None, bool, lambda x: True)
- class tuple2(tuple):
- def __getitem__(self, index):
- return 2*tuple.__getitem__(self, index)
- class str2(str):
- def __getitem__(self, index):
- return 2*str.__getitem__(self, index)
- inputs = {
- tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
- str2: {"": "", "123": "112233"}
- }
- if have_unicode:
- class unicode2(unicode):
- def __getitem__(self, index):
- return 2*unicode.__getitem__(self, index)
- inputs[unicode2] = {
- unicode(): unicode(),
- unicode("123"): unicode("112233")
- }
-
- for (cls, inps) in inputs.iteritems():
- for (inp, exp) in inps.iteritems():
- # make sure the output goes through __getitem__
- # even if func is None
- assert (
- filter(funcs[0], cls(inp))) == (
- filter(funcs[1], cls(inp))
- )
- for func in funcs:
- outp = filter(func, cls(inp))
- assert outp == exp
- assert not isinstance(outp, cls)
- '''
-
- def test_float(self):
- assert float(3.14) == 3.14
- assert float(314) == 314.0
- assert float(314L) == 314.0
- assert float(" 3.14 ") == 3.14
- if have_unicode:
- assert float(unicode(" 3.14 ")) == 3.14
- assert float(unicode(
- " \u0663.\u0661\u0664 ",'raw-unicode-escape')) == 3.14
-
- def test_getattr(self):
- import sys
- assert getattr(sys, 'stdout') is sys.stdout
- raises(TypeError, getattr, sys, 1)
- raises(TypeError, getattr, sys, 1, "foo")
- raises(TypeError, getattr)
- if have_unicode:
- raises(UnicodeError, getattr, sys,
- unichr(sys.maxunicode))
-
- def test_hasattr(self):
- import sys
- assert hasattr(sys, 'stdout')
- raises(TypeError, hasattr, sys, 1)
- raises(TypeError, hasattr)
- if have_unicode:
- raises(UnicodeError, hasattr, sys,
- unichr(sys.maxunicode))
-
- def test_hash(self):
- hash(None)
- assert hash(1) == hash(1L)
- assert hash(1) == hash(1.0)
- hash('spam')
- if have_unicode:
- assert hash('spam') == hash(unicode('spam'))
- hash((0,1,2,3))
- def f(): pass
- raises(TypeError, hash, [])
- raises(TypeError, hash, {})
-
- def test_hex(self):
- assert hex(16) == '0x10'
- assert hex(16L) == '0x10L'
- assert len(hex(-1)) == len(hex(sys.maxint))
- assert hex(-16) in ('0xfffffff0', '0xfffffffffffffff0')
- assert hex(-16L) == '-0x10L'
- raises(TypeError, hex, {})
-
- def test_id(self):
- id(None)
- id(1)
- id(1L)
- id(1.0)
- id('spam')
- id((0,1,2,3))
- id([0,1,2,3])
- id({'spam': 1, 'eggs': 2, 'ham': 3})
-
- # Test input() later, together with raw_input
-
- def test_int(self):
- assert int(314) == 314
- assert int(3.14) == 3
- assert int(314L) == 314
- # Check that conversion from float truncates towards zero
- assert int(-3.14) == -3
- assert int(3.9) == 3
- assert int(-3.9) == -3
- assert int(3.5) == 3
- assert int(-3.5) == -3
- # Different base:
- assert int("10",16) == 16L
- if have_unicode:
- assert int(unicode("10"),16) == 16L
- # Test conversion from strings and various anomalies
- for s, v in L:
- for sign in "", "+", "-":
- for prefix in "", " ", "\t", " \t\t ":
- ss = prefix + sign + s
- vv = v
- if sign == "-" and v is not ValueError:
- vv = -v
- try:
- assert int(ss) == vv
- except v:
- pass
-
- s = `-1-sys.maxint`
- assert int(s)+1 == -sys.maxint
- # should return long
- ''' XXX TODO: Longs not well supported yet
- int(s[1:])
-
- # should return long
- x = int(1e100)
- assert isinstance(x, long)
- x = int(-1e100)
- assert isinstance(x, long)
- '''
-
- # SF bug 434186: 0x80000000/2 != 0x80000000>>1.
- # Worked by accident in Windows release build, but failed in
- # debug build. Failed in all Linux builds.
- x = -1-sys.maxint
- assert x >> 1 == x//2
-
- raises(ValueError, int, '123\0')
- raises(ValueError, int, '53', 40)
-
- ''' XXX TODO: Longs not supported yet
- x = int('1' * 600)
- assert isinstance(x, long)
-
- if have_unicode:
- x = int(unichr(0x661) * 600)
- assert isinstance(x, long)
-
- raises(TypeError, int, 1, 12)
- '''
-
- assert int('0123', 0) == 83
-
- def test_intern(self):
- raises(TypeError, intern)
- s = "never interned before"
- assert intern(s) is s
- s2 = s.swapcase().swapcase()
- assert intern(s2) is s
-
- def test_iter(self):
- raises(TypeError, iter)
- raises(TypeError, iter, 42, 42)
- lists = [("1", "2"), ["1", "2"], "12"]
- if have_unicode:
- lists.append(unicode("12"))
- for l in lists:
- i = iter(l)
- assert i.next() == '1'
- assert i.next() == '2'
- raises(StopIteration, i.next)
-
- def test_isinstance(self):
- class C:
- pass
- class D(C):
- pass
- class E:
- pass
- c = C()
- d = D()
- e = E()
- assert isinstance(c, C)
- assert isinstance(d, C)
- assert not isinstance(e, C)
- assert not isinstance(c, D)
- assert not isinstance('foo', E)
- raises(TypeError, isinstance, E, 'foo')
- raises(TypeError, isinstance)
-
- def test_issubclass(self):
- class C:
- pass
- class D(C):
- pass
- class E:
- pass
- c = C()
- d = D()
- e = E()
- assert issubclass(D, C)
- assert issubclass(C, C)
- assert not issubclass(C, D)
- raises(TypeError, issubclass, 'foo', E)
- raises(TypeError, issubclass, E, 'foo')
- raises(TypeError, issubclass)
-
- def test_len(self):
- assert len('123') == 3
- assert len(()) == 0
- assert len((1, 2, 3, 4)) == 4
- assert len([1, 2, 3, 4]) == 4
- assert len({}) == 0
- assert len({'a':1, 'b': 2}) == 2
- class BadSeq:
- def __len__(self):
- raise ValueError
- raises(ValueError, len, BadSeq())
-
- if 1:
-
- def test_list(self):
- assert list([]) == []
- l0_3 = [0, 1, 2, 3]
- l0_3_bis = list(l0_3)
- assert l0_3 == l0_3_bis
- assert l0_3 is not l0_3_bis
- assert list(()) == []
- assert list((0, 1, 2, 3)) == [0, 1, 2, 3]
- assert list('') == []
- assert list('spam') == ['s', 'p', 'a', 'm']
-
- ''' XXX TODO: disabled for now -- far too slow!
- if sys.maxint == 0x7fffffff:
- # This test can currently only work on 32-bit machines.
- # XXX If/when PySequence_Length() returns a ssize_t, it should be
- # XXX re-enabled.
- # Verify clearing of bug #556025.
- # This assumes that the max data size (sys.maxint) == max
- # address size this also assumes that the address size is at
- # least 4 bytes with 8 byte addresses, the bug is not well
- # tested
- #
- # Note: This test is expected to SEGV under Cygwin 1.3.12 or
- # earlier due to a newlib bug. See the following mailing list
- # thread for the details:
-
- # http://sources.redhat.com/ml/newlib/2002/msg00369.html
- raises(MemoryError, list, xrange(sys.maxint // 2))
- '''
-
- ''' XXX TODO: disabled for now -- long not yet well supported
- def test_long(self):
- assert long(314) == 314L
- assert long(3.14) == 3L
- assert long(314L) == 314L
- # Check that conversion from float truncates towards zero
- assert long(-3.14) == -3L
- assert long(3.9) == 3L
- assert long(-3.9) == -3L
- assert long(3.5) == 3L
- assert long(-3.5) == -3L
- assert long("-3") == -3L
- if have_unicode:
- assert long(unicode("-3")) == -3L
- # Different base:
- assert long("10",16) == 16L
- if have_unicode:
- assert long(unicode("10"),16) == 16L
- # Check conversions from string (same test set as for int(), and then some)
- LL = [
- ('1' + '0'*20, 10L**20),
- ('1' + '0'*100, 10L**100)
- ]
- L2 = L[:]
- if have_unicode:
- L2 += [
- (unicode('1') + unicode('0')*20, 10L**20),
- (unicode('1') + unicode('0')*100, 10L**100),
- ]
- for s, v in L2 + LL:
- for sign in "", "+", "-":
- for prefix in "", " ", "\t", " \t\t ":
- ss = prefix + sign + s
- vv = v
- if sign == "-" and v is not ValueError:
- vv = -v
- try:
- assert long(ss) == long(vv)
- except v:
- pass
-
- raises(ValueError, long, '123\0')
- raises(ValueError, long, '53', 40)
- raises(TypeError, long, 1, 12)
- '''
-
- def test_map(self):
- assert (
- map(None, 'hello world')) == (
- ['h','e','l','l','o',' ','w','o','r','l','d']
- )
- assert (
- map(None, 'abcd', 'efg')) == (
- [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
- )
- assert (
- map(None, range(10))) == (
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- )
- assert (
- map(lambda x: x*x, range(1,4))) == (
- [1, 4, 9]
- )
- try:
- from math import sqrt
- except ImportError:
- def sqrt(x):
- return pow(x, 0.5)
- assert (
- map(lambda x: map(sqrt,x), [[16, 4], [81, 9]])) == (
- [[4.0, 2.0], [9.0, 3.0]]
- )
- assert (
- map(lambda x, y: x+y, [1,3,2], [9,1,4])) == (
- [10, 4, 6]
- )
-
- def plus(*v):
- accu = 0
- for i in v: accu = accu + i
- return accu
- assert (
- map(plus, [1, 3, 7])) == (
- [1, 3, 7]
- )
- assert (
- map(plus, [1, 3, 7], [4, 9, 2])) == (
- [1+4, 3+9, 7+2]
- )
- assert (
- map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])) == (
- [1+4+1, 3+9+1, 7+2+0]
- )
- assert (
- map(None, Squares(10))) == (
- [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- )
- assert (
- map(int, Squares(10))) == (
- [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- )
- assert (
- map(None, Squares(3), Squares(2))) == (
- [(0,0), (1,1), (4,None)]
- )
- assert (
- map(max, Squares(3), Squares(2))) == (
- [0, 1, 4]
- )
- raises(TypeError, map)
- raises(TypeError, map, lambda x: x, 42)
- assert map(None, [42]) == [42]
- class BadSeq:
- def __getitem__(self, index):
- raise ValueError
- raises(ValueError, map, lambda x: x, BadSeq())
-
- def test_max(self):
- assert max('123123') == '3'
- assert max(1, 2, 3) == 3
- assert max((1, 2, 3, 1, 2, 3)) == 3
- assert max([1, 2, 3, 1, 2, 3]) == 3
-
- assert max(1, 2L, 3.0) == 3.0
- assert max(1L, 2.0, 3) == 3
- assert max(1.0, 2, 3L) == 3L
-
- def test_min(self):
- assert min('123123') == '1'
- assert min(1, 2, 3) == 1
- assert min((1, 2, 3, 1, 2, 3)) == 1
- assert min([1, 2, 3, 1, 2, 3]) == 1
-
- assert min(1, 2L, 3.0) == 1
- assert min(1L, 2.0, 3) == 1L
- assert min(1.0, 2, 3L) == 1.0
-
- raises(TypeError, min)
- raises(TypeError, min, 42)
- raises(ValueError, min, ())
- class BadSeq:
- def __getitem__(self, index):
- raise ValueError
- raises(ValueError, min, BadSeq())
- ''' XXX TODO: some weird bug in pypy here -- fix later
- class BadNumber:
- def __cmp__(self, other):
- raise ValueError
- raises(ValueError, min, (42, BadNumber()))
- '''
-
- def test_oct(self):
- assert oct(100) == '0144'
- assert oct(100L) == '0144L'
- assert oct(-100) in ('037777777634', '01777777777777777777634')
- assert oct(-100L) == '-0144L'
- raises(TypeError, oct, ())
-
-
- def test_open(self):
- def write_testfile():
- # NB the first 4 lines are also used to test input and raw_input, below
- fp = open(TESTFN, 'w')
- try:
- fp.write('1+1\n')
- fp.write('1+1\n')
- fp.write('The quick brown fox jumps over the lazy dog')
- fp.write('.\n')
- fp.write('Dear John\n')
- fp.write('XXX'*100)
- fp.write('YYY'*100)
- finally:
- fp.close()
- write_testfile()
- fp = open(TESTFN, 'r')
- try:
- assert fp.readline(4) == '1+1\n'
- assert fp.readline(4) == '1+1\n'
- assert fp.readline() == 'The quick brown fox jumps over the lazy dog.\n'
- assert fp.readline(4) == 'Dear'
- assert fp.readline(100) == ' John\n'
- assert fp.read(300) == 'XXX'*100
- assert fp.read(1000) == 'YYY'*100
- finally:
- fp.close()
- unlink(TESTFN)
-
- def test_ord(self):
- assert ord(' ') == 32
- assert ord('A') == 65
- assert ord('a') == 97
- raises(TypeError, ord, 42)
- if have_unicode:
- assert ord(unichr(sys.maxunicode)) == sys.maxunicode
- raises(TypeError, ord, unicode("12"))
-
- def test_pow(self):
- assert pow(0,0) == 1
- assert pow(0,1) == 0
- assert pow(1,0) == 1
- assert pow(1,1) == 1
-
- assert pow(2,0) == 1
- assert pow(2,10) == 1024
- assert pow(2,20) == 1024*1024
- assert pow(2,30) == 1024*1024*1024
-
- assert pow(-2,0) == 1
- assert pow(-2,1) == -2
- assert pow(-2,2) == 4
- assert pow(-2,3) == -8
-
- assert pow(0L,0) == 1
- assert pow(0L,1) == 0
- assert pow(1L,0) == 1
- assert pow(1L,1) == 1
-
- assert pow(2L,0) == 1
- assert pow(2L,10) == 1024
- assert pow(2L,20) == 1024*1024
- assert pow(2L,30) == 1024*1024*1024
-
- assert pow(-2L,0) == 1
- assert pow(-2L,1) == -2
- assert pow(-2L,2) == 4
- assert pow(-2L,3) == -8
-
- assert round(pow(0.,0) - 1., 7) == 0
- assert round(pow(0.,1) - 0., 7) == 0
- assert round(pow(1.,0) - 1., 7) == 0
- assert round(pow(1.,1) - 1., 7) == 0
-
- assert round(pow(2.,0) - 1., 7) == 0
- assert round(pow(2.,10) - 1024., 7) == 0
- assert round(pow(2.,20) - 1024.*1024., 7) == 0
- assert round(pow(2.,30) - 1024.*1024.*1024., 7) == 0
-
- assert round(pow(-2.,0) - 1., 7) == 0
- assert round(pow(-2.,1) - -2., 7) == 0
- assert round(pow(-2.,2) - 4., 7) == 0
- assert round(pow(-2.,3) - -8., 7) == 0
-
- for x in 2, 2L, 2.0:
- for y in 10, 10L, 10.0:
- for z in 1000, 1000L, 1000.0:
- if isinstance(x, float) or \
- isinstance(y, float) or \
- isinstance(z, float):
- raises(TypeError, pow, x, y, z)
- else:
- assert round(pow(x, y, z) - 24.0, 7) == 0
-
- raises(TypeError, pow, -1, -2, 3)
- raises(ValueError, pow, 1, 2, 0)
- raises(TypeError, pow, -1L, -2L, 3L)
- raises(ValueError, pow, 1L, 2L, 0L)
- raises(ValueError, pow, -342.43, 0.234)
-
- raises(TypeError, pow)
-
- def test_range(self):
- assert range(3) == [0, 1, 2]
- assert range(1, 5) == [1, 2, 3, 4]
- assert range(0) == []
- assert range(-3) == []
- assert range(1, 10, 3) == [1, 4, 7]
- assert range(5, -5, -3) == [5, 2, -1, -4]
-
- # Now test range() with longs
- assert range(-2**100) == []
- assert range(0, -2**100) == []
- assert range(0, 2**100, -1) == []
- assert range(0, 2**100, -1) == []
-
- a = long(10 * sys.maxint)
- b = long(100 * sys.maxint)
- c = long(50 * sys.maxint)
-
- assert range(a, a+2) == [a, a+1]
- assert range(a+2, a, -1L) == [a+2, a+1]
- assert range(a+4, a, -2) == [a+4, a+2]
-
- seq = range(a, b, c)
- assert a in seq
- assert b not in seq
- assert len(seq) == 2
-
- seq = range(b, a, -c)
- assert b in seq
- assert a not in seq
- assert len(seq) == 2
-
- seq = range(-a, -b, -c)
- assert -a in seq
- assert -b not in seq
- assert len(seq) == 2
-
- raises(TypeError, range)
- raises(TypeError, range, 1, 2, 3, 4)
- raises(ValueError, range, 1, 2, 0)
-
- # Reject floats when it would require PyLongs to represent.
- # (smaller floats still accepted, but deprecated)
- raises(TypeError, range, 1e100, 1e101, 1e101)
-
- raises(TypeError, range, 0, "spam")
- raises(TypeError, range, 0, 42, "spam")
-
- raises(OverflowError, range, -sys.maxint, sys.maxint)
- raises(OverflowError, range, 0, 2*sys.maxint)
-
- ''' XXX TODO: input and raw_input not supported yet
- def test_input_and_raw_input(self):
- self.write_testfile()
- fp = open(TESTFN, 'r')
- savestdin = sys.stdin
- savestdout = sys.stdout # Eats the echo
- try:
- sys.stdin = fp
- sys.stdout = BitBucket()
- assert input() == 2
- assert input('testing\n') == 2
- assert raw_input() == 'The quick brown fox jumps over the lazy dog.'
- assert raw_input('testing\n') == 'Dear John'
- sys.stdin = cStringIO.StringIO("NULL\0")
- raises(TypeError, input, 42, 42)
- sys.stdin = cStringIO.StringIO(" 'whitespace'")
- assert input() == 'whitespace'
- sys.stdin = cStringIO.StringIO()
- raises(EOFError, input)
- del sys.stdout
- raises(RuntimeError, input, 'prompt')
- del sys.stdin
- raises(RuntimeError, input, 'prompt')
- finally:
- sys.stdin = savestdin
- sys.stdout = savestdout
- fp.close()
- unlink(TESTFN)
- '''
-
- def test_reduce(self):
- assert reduce(lambda x, y: x+y, ['a', 'b', 'c'], '') == 'abc'
- assert (
- reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], [])) == (
- ['a','c','d','w']
- )
- assert reduce(lambda x, y: x*y, range(2,8), 1) == 5040
- assert (
- reduce(lambda x, y: x*y, range(2,21), 1L)) == (
- 2432902008176640000L
- )
- assert reduce(lambda x, y: x+y, Squares(10)) == 285
- assert reduce(lambda x, y: x+y, Squares(10), 0) == 285
- assert reduce(lambda x, y: x+y, Squares(0), 0) == 0
- raises(TypeError, reduce)
- raises(TypeError, reduce, 42, 42)
- raises(TypeError, reduce, 42, 42, 42)
- assert reduce(42, "1") == "1" # func is never called with one item
- assert reduce(42, "", "1") == "1" # func is never called with one item
- raises(TypeError, reduce, 42, (42, 42))
-
- class BadSeq:
- def __getitem__(self, index):
- raise ValueError
- raises(ValueError, reduce, 42, BadSeq())
-
- ''' XXX TODO: we don't have reload yet
- def test_reload(self):
- import sys
- reload(sys)
- import string
- reload(string)
- ## import sys
- ## raises(ImportError, reload, sys)
- '''
-
- def test_repr(self):
- assert repr('') == '\'\''
- assert repr(0) == '0'
- assert repr(0L) == '0L'
- assert repr(()) == '()'
- assert repr([]) == '[]'
- assert repr({}) == '{}'
- ''' XXX TODO: we don't yet support "circular" objects!
- a = []
- a.append(a)
- assert repr(a) == '[[...]]'
- a = {}
- a[0] = a
- assert repr(a) == '{0: {...}}'
- '''
-
- def test_round(self):
- assert round(0.0) == 0.0
- assert round(1.0) == 1.0
- assert round(10.0) == 10.0
- assert round(1000000000.0) == 1000000000.0
- assert round(1e20) == 1e20
-
- assert round(-1.0) == -1.0
- assert round(-10.0) == -10.0
- assert round(-1000000000.0) == -1000000000.0
- assert round(-1e20) == -1e20
-
- assert round(0.1) == 0.0
- assert round(1.1) == 1.0
- assert round(10.1) == 10.0
- assert round(1000000000.1) == 1000000000.0
-
- assert round(-1.1) == -1.0
- assert round(-10.1) == -10.0
- assert round(-1000000000.1) == -1000000000.0
-
- assert round(0.9) == 1.0
- assert round(9.9) == 10.0
- assert round(999999999.9) == 1000000000.0
-
- assert round(-0.9) == -1.0
- assert round(-9.9) == -10.0
- assert round(-999999999.9) == -1000000000.0
-
- assert round(-8.0, -1) == -10.0
-
- raises(TypeError, round)
-
- def test_setattr(self):
- setattr(sys, 'spam', 1)
- assert sys.spam == 1
- raises(TypeError, setattr, sys, 1, 'spam')
- raises(TypeError, setattr)
-
- def test_str(self):
- assert str('') == ''
- assert str(0) == '0'
- assert str(0L) == '0'
- assert str(()) == '()'
- assert str([]) == '[]'
- assert str({}) == '{}'
- ''' XXX TODO: we don't yet support "circular" objects!
- a = []
- a.append(a)
- assert str(a) == '[[...]]'
- a = {}
- a[0] = a
- assert str(a) == '{0: {...}}'
- '''
-
- def test_sum(self):
- assert sum([]) == 0
- assert sum(range(2,8)) == 27
- assert sum(iter(range(2,8))) == 27
- assert sum(Squares(10)) == 285
- assert sum(iter(Squares(10))) == 285
- assert sum([[1], [2], [3]], []) == [1, 2, 3]
-
- raises(TypeError, sum)
- raises(TypeError, sum, 42)
- raises(TypeError, sum, ['a', 'b', 'c'])
- raises(TypeError, sum, ['a', 'b', 'c'], '')
- raises(TypeError, sum, [[1], [2], [3]])
- raises(TypeError, sum, [{2:3}])
- raises(TypeError, sum, [{2:3}]*2, {2:3})
-
- class BadSeq:
- def __getitem__(self, index):
- raise ValueError
- raises(ValueError, sum, BadSeq())
-
- def test_tuple(self):
- assert tuple(()) == ()
- t0_3 = (0, 1, 2, 3)
- t0_3_bis = tuple(t0_3)
- ''' XXX TODO: tuples are immutable -- returns same object in CPython '''
- #self.assert_(t0_3 is t0_3_bis)
- assert t0_3 == t0_3_bis
- assert tuple([]) == ()
- assert tuple([0, 1, 2, 3]) == (0, 1, 2, 3)
- assert tuple('') == ()
- assert tuple('spam') == ('s', 'p', 'a', 'm')
-
- def test_type(self):
- assert type('') == type('123')
- assert type('') != type(())
-
- def test_unichr(self):
- if have_unicode:
- assert unichr(32) == unicode(' ')
- assert unichr(65) == unicode('A')
- assert unichr(97) == unicode('a')
- assert (
- unichr(sys.maxunicode)) == (
- unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape')
- )
- raises(ValueError, unichr, sys.maxunicode+1)
- raises(TypeError, unichr)
-
- def test_vars(self):
- def get_vars_f0():
- return vars()
- def get_vars_f2():
- get_vars_f0()
- a = 1
- b = 2
- return vars()
- assert Set(vars()) == Set(dir())
- import sys
- assert Set(vars(sys)) == Set(dir(sys))
- assert get_vars_f0() == {}
- assert get_vars_f2() == {'a': 1, 'b': 2}
- raises(TypeError, vars, 42, 42)
- raises(TypeError, vars, 42)
-
- def test_zip(self):
- a = (1, 2, 3)
- b = (4, 5, 6)
- t = [(1, 4), (2, 5), (3, 6)]
- assert zip(a, b) == t
- b = [4, 5, 6]
- assert zip(a, b) == t
- b = (4, 5, 6, 7)
- assert zip(a, b) == t
- class I:
- def __getitem__(self, i):
- if i < 0 or i > 2: raise IndexError
- return i + 4
- assert zip(a, I()) == t
- raises(TypeError, zip)
- raises(TypeError, zip, None)
- class G:
- pass
- raises(TypeError, zip, a, G())
-
- # Make sure zip doesn't try to allocate a billion elements for the
- # result list when one of its arguments doesn't say how long it is.
- # A MemoryError is the most likely failure mode.
- class SequenceWithoutALength:
- def __getitem__(self, i):
- if i == 5:
- raise IndexError
- else:
- return i
- s = SequenceWithoutALength()
- assert (
- zip(s, xrange(2**30))) == (
- [(x,x) for x in s]
- )
-
- class BadSeq:
- def __getitem__(self, i):
- if i == 5:
- raise ValueError
- else:
- return i
- raises(ValueError, zip, BadSeq(), BadSeq())
Deleted: /pypy/dist/pypy/appspace/test/cpy_test_types.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/cpy_test_types.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,787 +0,0 @@
-# Python test set -- part 6, built-in types
-# Slightly edited version for PyPy.
-
-from support_tests import *
-
-print '6. Built-in types'
-
-print '6.1 Truth value testing'
-if None: raise TestFailed, 'None is true instead of false'
-if 0: raise TestFailed, '0 is true instead of false'
-if 0L: raise TestFailed, '0L is true instead of false'
-if 0.0: raise TestFailed, '0.0 is true instead of false'
-if '': raise TestFailed, '\'\' is true instead of false'
-if (): raise TestFailed, '() is true instead of false'
-if []: raise TestFailed, '[] is true instead of false'
-if {}: raise TestFailed, '{} is true instead of false'
-if not 1: raise TestFailed, '1 is false instead of true'
-if not 1L: raise TestFailed, '1L is false instead of true'
-if not 1.0: raise TestFailed, '1.0 is false instead of true'
-if not 'x': raise TestFailed, '\'x\' is false instead of true'
-if not (1, 1): raise TestFailed, '(1, 1) is false instead of true'
-if not [1]: raise TestFailed, '[1] is false instead of true'
-if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true'
-def f(): pass
-class C: pass
-import sys
-x = C()
-if not f: raise TestFailed, 'f is false instead of true'
-if not C: raise TestFailed, 'C is false instead of true'
-if not sys: raise TestFailed, 'sys is false instead of true'
-if not x: raise TestFailed, 'x is false instead of true'
-
-print '6.2 Boolean operations'
-if 0 or 0: raise TestFailed, '0 or 0 is true instead of false'
-if 1 and 1: pass
-else: raise TestFailed, '1 and 1 is false instead of false'
-if not 1: raise TestFailed, 'not 1 is true instead of false'
-
-print '6.3 Comparisons'
-if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
-else: raise TestFailed, 'int comparisons failed'
-if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass
-else: raise TestFailed, 'long int comparisons failed'
-if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass
-else: raise TestFailed, 'float comparisons failed'
-if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass
-else: raise TestFailed, 'string comparisons failed'
-if 0 in [0] and 0 not in [1]: pass
-else: raise TestFailed, 'membership test failed'
-if None is None and [] is not []: pass
-else: raise TestFailed, 'identity test failed'
-
-
-print '6.3.1 Conversion errors'
-try: float('')
-except ValueError: pass
-else: raise TestFailed, "float('') didn't raise ValueError"
-
-try: float('5\0')
-except ValueError: pass
-else: raise TestFailed, "float('5\0') didn't raise ValueError"
-
-print '6.3.2 Division errors'
-try: 5.0 / 0.0
-except ZeroDivisionError: pass
-else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError"
-
-try: 5.0 // 0.0
-except ZeroDivisionError: pass
-else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError"
-
-try: 5.0 % 0.0
-except ZeroDivisionError: pass
-else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError"
-
-try: 5L / 0
-except ZeroDivisionError: pass
-else: raise TestFailed, "5L / 0 didn't raise ZeroDivisionError"
-
-try: 5 / 0L
-except ZeroDivisionError: pass
-else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError"
-
-try: 5 // 0L
-except ZeroDivisionError: pass
-else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError"
-
-try: 5 % 0L
-except ZeroDivisionError: pass
-else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError"
-
-print '6.4 Numeric types (mostly conversions)'
-if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons'
-if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons'
-if -1 != -1L or -1 != -1.0 or -1L != -1.0:
- raise TestFailed, 'int/long/float value not equal'
-# calling built-in types without argument must return 0
-if int() != 0: raise TestFailed, 'int() does not return 0'
-if long() != 0L: raise TestFailed, 'long() does not return 0L'
-if float() != 0.0: raise TestFailed, 'float() does not return 0.0'
-if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
-else: raise TestFailed, 'int() does not round properly'
-if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass
-else: raise TestFailed, 'long() does not round properly'
-if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
-else: raise TestFailed, 'float() does not work properly'
-print '6.4.1 32-bit integers'
-if 12 + 24 != 36: raise TestFailed, 'int op'
-if 12 + (-24) != -12: raise TestFailed, 'int op'
-if (-12) + 24 != 12: raise TestFailed, 'int op'
-if (-12) + (-24) != -36: raise TestFailed, 'int op'
-if not 12 < 24: raise TestFailed, 'int op'
-if not -24 < -12: raise TestFailed, 'int op'
-# Test for a particular bug in integer multiply
-xsize, ysize, zsize = 238, 356, 4
-if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912):
- raise TestFailed, 'int mul commutativity'
-# And another.
-m = -sys.maxint - 1
-for divisor in 1, 2, 4, 8, 16, 32:
- j = m // divisor
- prod = divisor * j
- if prod != m:
- raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m)
- if type(prod) is not int:
- raise TestFailed, ("expected type(prod) to be int, not %r" %
- type(prod))
-# Check for expected * overflow to long.
-for divisor in 1, 2, 4, 8, 16, 32:
- j = m // divisor - 1
- prod = divisor * j
- if type(prod) is not long:
- raise TestFailed, ("expected type(%r) to be long, not %r" %
- (prod, type(prod)))
-# Check for expected * overflow to long.
-m = sys.maxint
-for divisor in 1, 2, 4, 8, 16, 32:
- j = m // divisor + 1
- prod = divisor * j
- if type(prod) is not long:
- raise TestFailed, ("expected type(%r) to be long, not %r" %
- (prod, type(prod)))
-
-print '6.4.2 Long integers'
-if 12L + 24L != 36L: raise TestFailed, 'long op'
-if 12L + (-24L) != -12L: raise TestFailed, 'long op'
-if (-12L) + 24L != 12L: raise TestFailed, 'long op'
-if (-12L) + (-24L) != -36L: raise TestFailed, 'long op'
-if not 12L < 24L: raise TestFailed, 'long op'
-if not -24L < -12L: raise TestFailed, 'long op'
-x = sys.maxint
-if int(long(x)) != x: raise TestFailed, 'long op'
-try: y = int(long(x)+1L)
-except OverflowError: raise TestFailed, 'long op'
-if not isinstance(y, long): raise TestFailed, 'long op'
-x = -x
-if int(long(x)) != x: raise TestFailed, 'long op'
-x = x-1
-if int(long(x)) != x: raise TestFailed, 'long op'
-try: y = int(long(x)-1L)
-except OverflowError: raise TestFailed, 'long op'
-if not isinstance(y, long): raise TestFailed, 'long op'
-
-try: 5 << -5
-except ValueError: pass
-else: raise TestFailed, 'int negative shift <<'
-
-try: 5L << -5L
-except ValueError: pass
-else: raise TestFailed, 'long negative shift <<'
-
-try: 5 >> -5
-except ValueError: pass
-else: raise TestFailed, 'int negative shift >>'
-
-try: 5L >> -5L
-except ValueError: pass
-else: raise TestFailed, 'long negative shift >>'
-
-print '6.4.3 Floating point numbers'
-if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op'
-if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op'
-if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op'
-if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op'
-if not 12.0 < 24.0: raise TestFailed, 'float op'
-if not -24.0 < -12.0: raise TestFailed, 'float op'
-
-print '6.5 Sequence types'
-
-print '6.5.1 Strings'
-if len('') != 0: raise TestFailed, 'len(\'\')'
-if len('a') != 1: raise TestFailed, 'len(\'a\')'
-if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')'
-if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation'
-if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3'
-if 0*'abcde' != '': raise TestFailed, 'string repetition 0*'
-if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string'
-if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass
-else: raise TestFailed, 'in/not in string'
-x = 'x'*103
-if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug'
-
-#extended slices for strings
-a = '0123456789'
-vereq(a[::], a)
-vereq(a[::2], '02468')
-vereq(a[1::2], '13579')
-vereq(a[::-1],'9876543210')
-vereq(a[::-2], '97531')
-vereq(a[3::-2], '31')
-vereq(a[-100:100:], a)
-vereq(a[100:-100:-1], a[::-1])
-vereq(a[-100L:100L:2L], '02468')
-
-if have_unicode:
- a = unicode('0123456789', 'ascii')
- vereq(a[::], a)
- vereq(a[::2], unicode('02468', 'ascii'))
- vereq(a[1::2], unicode('13579', 'ascii'))
- vereq(a[::-1], unicode('9876543210', 'ascii'))
- vereq(a[::-2], unicode('97531', 'ascii'))
- vereq(a[3::-2], unicode('31', 'ascii'))
- vereq(a[-100:100:], a)
- vereq(a[100:-100:-1], a[::-1])
- vereq(a[-100L:100L:2L], unicode('02468', 'ascii'))
-
-
-print '6.5.2 Tuples'
-# calling built-in types without argument must return empty
-if tuple() != (): raise TestFailed,'tuple() does not return ()'
-if len(()) != 0: raise TestFailed, 'len(())'
-if len((1,)) != 1: raise TestFailed, 'len((1,))'
-if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))'
-if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation'
-if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3'
-if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*'
-if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple'
-if 0 in (0,1,2) and 1 in (0,1,2) and 2 in (0,1,2) and 3 not in (0,1,2): pass
-else: raise TestFailed, 'in/not in tuple'
-try: ()[0]
-except IndexError: pass
-else: raise TestFailed, "tuple index error didn't raise IndexError"
-x = ()
-x += ()
-if x != (): raise TestFailed, 'tuple inplace add from () to () failed'
-x += (1,)
-if x != (1,): raise TestFailed, 'tuple resize from () failed'
-
-# extended slicing - subscript only for tuples
-a = (0,1,2,3,4)
-vereq(a[::], a)
-vereq(a[::2], (0,2,4))
-vereq(a[1::2], (1,3))
-vereq(a[::-1], (4,3,2,1,0))
-vereq(a[::-2], (4,2,0))
-vereq(a[3::-2], (3,1))
-vereq(a[-100:100:], a)
-vereq(a[100:-100:-1], a[::-1])
-vereq(a[-100L:100L:2L], (0,2,4))
-
-# Check that a specific bug in _PyTuple_Resize() is squashed.
-def f():
- for i in range(1000):
- yield i
-vereq(list(tuple(f())), range(1000))
-
-# Verify that __getitem__ overrides are not recognized by __iter__
-# XXX TODO: this fails with PyPy because overriding __getitem__ will
-# really override what the sequence iterator returns
-#class T(tuple):
-# def __getitem__(self, key):
-# return str(key) + '!!!'
-#vereq(iter(T((1,2))).next(), 1)
-
-print '6.5.3 Lists'
-# calling built-in types without argument must return empty
-if list() != []: raise TestFailed,'list() does not return []'
-if len([]) != 0: raise TestFailed, 'len([])'
-if len([1,]) != 1: raise TestFailed, 'len([1,])'
-if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])'
-if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation'
-if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3'
-if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L'
-if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*'
-if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*'
-if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list'
-if 0 in [0,1,2] and 1 in [0,1,2] and 2 in [0,1,2] and 3 not in [0,1,2]: pass
-else: raise TestFailed, 'in/not in list'
-a = [1, 2, 3, 4, 5]
-a[:-1] = a
-if a != [1, 2, 3, 4, 5, 5]:
- raise TestFailed, "list self-slice-assign (head)"
-a = [1, 2, 3, 4, 5]
-a[1:] = a
-if a != [1, 1, 2, 3, 4, 5]:
- raise TestFailed, "list self-slice-assign (tail)"
-a = [1, 2, 3, 4, 5]
-a[1:-1] = a
-if a != [1, 1, 2, 3, 4, 5, 5]:
- raise TestFailed, "list self-slice-assign (center)"
-try: [][0]
-except IndexError: pass
-else: raise TestFailed, "list index error didn't raise IndexError"
-try: [][0] = 5
-except IndexError: pass
-else: raise TestFailed, "list assignment index error didn't raise IndexError"
-try: [].pop()
-except IndexError: pass
-else: raise TestFailed, "empty list.pop() didn't raise IndexError"
-try: [1].pop(5)
-except IndexError: pass
-else: raise TestFailed, "[1].pop(5) didn't raise IndexError"
-try: [][0:1] = 5
-except TypeError: pass
-else: raise TestFailed, "bad list slice assignment didn't raise TypeError"
-try: [].extend(None)
-except TypeError: pass
-else: raise TestFailed, "list.extend(None) didn't raise TypeError"
-a = [1, 2, 3, 4]
-a *= 0
-if a != []:
- raise TestFailed, "list inplace repeat"
-
-a = []
-a[:] = tuple(range(10))
-if a != range(10):
- raise TestFailed, "assigning tuple to slice"
-
-print '6.5.3a Additional list operations'
-a = [0,1,2,3,4]
-a[0L] = 1
-a[1L] = 2
-a[2L] = 3
-if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]'
-a[0] = 5
-a[1] = 6
-a[2] = 7
-if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]'
-a[-2L] = 88
-a[-1L] = 99
-if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]'
-a[-2] = 8
-a[-1] = 9
-if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]'
-a[:2] = [0,4]
-a[-3:] = []
-a[1:1] = [1,2,3]
-if a != [0,1,2,3,4]: raise TestFailed, 'list slice assignment'
-a[ 1L : 4L] = [7,8,9]
-if a != [0,7,8,9,4]: raise TestFailed, 'list slice assignment using long ints'
-del a[1:4]
-if a != [0,4]: raise TestFailed, 'list slice deletion'
-del a[0]
-if a != [4]: raise TestFailed, 'list item deletion [0]'
-del a[-1]
-if a != []: raise TestFailed, 'list item deletion [-1]'
-a=range(0,5)
-del a[1L:4L]
-if a != [0,4]: raise TestFailed, 'list slice deletion'
-del a[0L]
-if a != [4]: raise TestFailed, 'list item deletion [0]'
-del a[-1L]
-if a != []: raise TestFailed, 'list item deletion [-1]'
-a=[]
-a.append(0)
-a.append(1)
-a.append(2)
-if a != [0,1,2]: raise TestFailed, 'list append'
-a.insert(0, -2)
-a.insert(1, -1)
-a.insert(2,0)
-if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert'
-b = a[:]
-b.insert(-2, "foo")
-b.insert(-200, "left")
-b.insert(200, "right")
-if b != ["left",-2,-1,0,0,"foo",1,2,"right"]: raise TestFailed, 'list insert2'
-# a = [-2,-1,0,0,1,2]
-if a.count(0) != 2: raise TestFailed, ' list count'
-if a.index(0) != 2: raise TestFailed, 'list index'
-if a.index(0,2) != 2: raise TestFailed, 'list index, start argument'
-if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument'
-if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument'
-if a.index(0,3) != 3: raise TestFailed, 'list index, start argument'
-if a.index(0,-3) != 3: raise TestFailed, 'list index, -start argument'
-if a.index(0,3,4) != 3: raise TestFailed, 'list index, stop argument'
-if a.index(0,-3,-2) != 3: raise TestFailed, 'list index, -stop argument'
-if a.index(0,-4*sys.maxint,4*sys.maxint) != 2:
- raise TestFailed, 'list index, -maxint, maxint argument'
-try:
- a.index(0, 4*sys.maxint,-4*sys.maxint)
-except ValueError:
- pass
-else:
- raise TestFailed, 'list index, maxint,-maxint argument'
-
-try:
- a.index(2,0,-10)
-except ValueError:
- pass
-else:
- raise TestFailed, 'list index, very -stop argument'
-a.remove(0)
-try:
- a.index(2,0,4)
-except ValueError:
- pass
-else:
- raise TestFailed, 'list index, stop argument.'
-if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove'
-a.reverse()
-if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse'
-a.sort()
-if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort'
-def revcmp(a, b): return cmp(b, a)
-a.sort(revcmp)
-if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func'
-# The following dumps core in unpatched Python 1.5:
-def myComparison(x,y):
- return cmp(x%3, y%7)
-z = range(12)
-z.sort(myComparison)
-
-try: z.sort(2)
-except TypeError: pass
-else: raise TestFailed, 'list sort compare function is not callable'
-
-''' XXX TODO: add detection of list modification during sort
-def selfmodifyingComparison(x,y):
- z.append(1)
- return cmp(x, y)
-try: z.sort(selfmodifyingComparison)
-except ValueError: pass
-else: raise TestFailed, 'modifying list during sort'
-'''
-
-try: z.sort(lambda x, y: 's')
-except TypeError: pass
-else: raise TestFailed, 'list sort compare function does not return int'
-
-# Test extreme cases with long ints
-a = [0,1,2,3,4]
-if a[ -pow(2,128L): 3 ] != [0,1,2]:
- raise TestFailed, "list slicing with too-small long integer"
-if a[ 3: pow(2,145L) ] != [3,4]:
- raise TestFailed, "list slicing with too-large long integer"
-
-# extended slicing
-
-# subscript
-a = [0,1,2,3,4]
-vereq(a[::], a)
-vereq(a[::2], [0,2,4])
-vereq(a[1::2], [1,3])
-vereq(a[::-1], [4,3,2,1,0])
-vereq(a[::-2], [4,2,0])
-vereq(a[3::-2], [3,1])
-vereq(a[-100:100:], a)
-vereq(a[100:-100:-1], a[::-1])
-vereq(a[-100L:100L:2L], [0,2,4])
-vereq(a[1000:2000:2], [])
-vereq(a[-1000:-2000:-2], [])
-# deletion
-del a[::2]
-vereq(a, [1,3])
-a = range(5)
-del a[1::2]
-vereq(a, [0,2,4])
-a = range(5)
-del a[1::-2]
-vereq(a, [0,2,3,4])
-a = range(10)
-del a[::1000]
-vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
-# assignment
-a = range(10)
-a[::2] = [-1]*5
-vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])
-a = range(10)
-a[::-4] = [10]*3
-vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])
-a = range(4)
-a[::-1] = a
-vereq(a, [3, 2, 1, 0])
-a = range(10)
-b = a[:]
-c = a[:]
-a[2:3] = ["two", "elements"]
-b[slice(2,3)] = ["two", "elements"]
-c[2:3:] = ["two", "elements"]
-vereq(a, b)
-vereq(a, c)
-a = range(10)
-a[::2] = tuple(range(5))
-vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9])
-
-# Verify that __getitem__ overrides are not recognized by __iter__
-# XXX TODO same as class T(tuple) above
-#class L(list):
-# def __getitem__(self, key):
-# return str(key) + '!!!'
-#vereq(iter(L([1,2])).next(), 1)
-
-
-print '6.6 Mappings == Dictionaries'
-# calling built-in types without argument must return empty
-if dict() != {}: raise TestFailed,'dict() does not return {}'
-d = {}
-if d.keys() != []: raise TestFailed, '{}.keys()'
-if d.values() != []: raise TestFailed, '{}.values()'
-if d.items() != []: raise TestFailed, '{}.items()'
-if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')'
-if ('a' in d) != 0: raise TestFailed, "'a' in {}"
-if ('a' not in d) != 1: raise TestFailed, "'a' not in {}"
-if len(d) != 0: raise TestFailed, 'len({})'
-d = {'a': 1, 'b': 2}
-if len(d) != 2: raise TestFailed, 'len(dict)'
-k = d.keys()
-k.sort()
-if k != ['a', 'b']: raise TestFailed, 'dict keys()'
-if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass
-else: raise TestFailed, 'dict keys()'
-if 'a' in d and 'b' in d and 'c' not in d: pass
-else: raise TestFailed, 'dict keys() # in/not in version'
-if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item'
-d['c'] = 3
-d['a'] = 4
-if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment'
-del d['b']
-if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion'
-print '6.6.1 dict methods'
-# dict.clear()
-d = {1:1, 2:2, 3:3}
-d.clear()
-if d != {}: raise TestFailed, 'dict clear'
-# dict.update()
-d.update({1:100})
-d.update({2:20})
-d.update({1:1, 2:2, 3:3})
-if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
-d.clear()
-try: d.update(None)
-except AttributeError: pass
-else: raise TestFailed, 'dict.update(None), AttributeError expected'
-print '6.6.2 user-dict methods'
-class SimpleUserDict:
- def __init__(self):
- self.d = {1:1, 2:2, 3:3}
- def keys(self):
- return self.d.keys()
- def __getitem__(self, i):
- return self.d[i]
-d.update(SimpleUserDict())
-if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
-d.clear()
-class FailingUserDict:
- def keys(self):
- raise ValueError
-try: d.update(FailingUserDict())
-except ValueError: pass
-else: raise TestFailed, 'dict.keys() expected ValueError'
-class FailingUserDict:
- def keys(self):
- class BogonIter:
- def __iter__(self):
- raise ValueError
- return BogonIter()
-try: d.update(FailingUserDict())
-except ValueError: pass
-else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
-class FailingUserDict:
- def keys(self):
- class BogonIter:
- def __init__(self):
- self.i = 1
- def __iter__(self):
- return self
- def next(self):
- if self.i:
- self.i = 0
- return 'a'
- raise ValueError
- return BogonIter()
- def __getitem__(self, key):
- return key
-try: d.update(FailingUserDict())
-except ValueError: pass
-else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
-class FailingUserDict:
- def keys(self):
- class BogonIter:
- def __init__(self):
- self.i = ord('a')
- def __iter__(self):
- return self
- def next(self):
- if self.i <= ord('z'):
- rtn = chr(self.i)
- self.i += 1
- return rtn
- raise StopIteration
- return BogonIter()
- def __getitem__(self, key):
- raise ValueError
-try: d.update(FailingUserDict())
-except ValueError: pass
-else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
-print '6.6.3 dict.fromkeys'
-# dict.fromkeys()
-if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
- raise TestFailed, 'dict.fromkeys did not work as a class method'
-d = {}
-if d.fromkeys('abc') is d:
- raise TestFailed, 'dict.fromkeys did not return a new dict'
-if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
- raise TestFailed, 'dict.fromkeys failed with default value'
-if d.fromkeys((4,5),0) != {4:0, 5:0}:
- raise TestFailed, 'dict.fromkeys failed with specified value'
-if d.fromkeys([]) != {}:
- raise TestFailed, 'dict.fromkeys failed with null sequence'
-def g():
- yield 1
-if d.fromkeys(g()) != {1:None}:
- raise TestFailed, 'dict.fromkeys failed with a generator'
-try: {}.fromkeys(3)
-except TypeError: pass
-else: raise TestFailed, 'dict.fromkeys failed to raise TypeError'
-class dictlike(dict): pass
-if dictlike.fromkeys('a') != {'a':None}:
- raise TestFailed, 'dictsubclass.fromkeys did not inherit'
-if dictlike().fromkeys('a') != {'a':None}:
- raise TestFailed, 'dictsubclass.fromkeys did not inherit'
-if type(dictlike.fromkeys('a')) is not dictlike:
- raise TestFailed, 'dictsubclass.fromkeys created wrong type'
-if type(dictlike().fromkeys('a')) is not dictlike:
- raise TestFailed, 'dictsubclass.fromkeys created wrong type'
-
-from UserDict import UserDict
-class mydict(dict):
- def __new__(cls):
- return UserDict()
-ud = mydict.fromkeys('ab')
-if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict):
- raise TestFailed, 'fromkeys did not instantiate using __new__'
-
-print '6.6.4 dict copy, get, setdefault'
-
-# dict.copy()
-d = {1:1, 2:2, 3:3}
-if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
-if {}.copy() != {}: raise TestFailed, 'empty dict copy'
-# dict.get()
-d = {}
-if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg'
-if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg'
-d = {'a' : 1, 'b' : 2}
-if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg'
-if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg'
-if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg'
-if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg'
-# dict.setdefault()
-d = {}
-if d.setdefault('key0') is not None:
- raise TestFailed, 'missing {} setdefault, no 2nd arg'
-if d.setdefault('key0') is not None:
- raise TestFailed, 'present {} setdefault, no 2nd arg'
-d.setdefault('key', []).append(3)
-if d['key'][0] != 3:
- raise TestFailed, 'missing {} setdefault, w/ 2nd arg'
-d.setdefault('key', []).append(4)
-if len(d['key']) != 2:
- raise TestFailed, 'present {} setdefault, w/ 2nd arg'
-
-print '6.6.5 dict popitem'
-
-# dict.popitem()
-for copymode in -1, +1:
- # -1: b has same structure as a
- # +1: b is a.copy()
- for log2size in range(4):#(12):
- size = 2**log2size
- a = {}
- b = {}
- for i in range(size):
- a[`i`] = i
- if copymode < 0:
- b[`i`] = i
- if copymode > 0:
- b = a.copy()
- for i in range(size):
- ka, va = ta = a.popitem()
- if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta)
- kb, vb = tb = b.popitem()
- if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb)
- if copymode < 0 and ta != tb:
- raise TestFailed, "a.popitem != b.popitem: %s, %s" % (
- str(ta), str(tb))
- if a: raise TestFailed, 'a not empty after popitems: %s' % str(a)
- if b: raise TestFailed, 'b not empty after popitems: %s' % str(b)
-
-d.clear()
-try: d.popitem()
-except KeyError: pass
-else: raise TestFailed, "{}.popitem doesn't raise KeyError"
-
-print '6.6.6 dict pop'
-
-# Tests for pop with specified key
-d.clear()
-k, v = 'abc', 'def'
-d[k] = v
-try: d.pop('ghi')
-except KeyError: pass
-else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary"
-
-if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair"
-if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair"
-
-try: d.pop(k)
-except KeyError: pass
-else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty"
-
-# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
-# see SF bug #689659
-x = 4503599627370496L
-y = 4503599627370496
-h = {x: 'anything', y: 'something else'}
-if h[x] != h[y]:
- raise TestFailed, "long/int key should match"
-
-if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
-d[k] = v
-if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"
-
-''' TODO: doesn't raise correctly
-d[1] = 1
-try:
- for i in d:
- d[i+1] = 1
-except RuntimeError:
- pass
-else:
- raise TestFailed, "changing dict size during iteration doesn't raise Error"
-'''
-
-print '6.7 type'
-
-try: type(1, 2)
-except TypeError: pass
-else: raise TestFailed, 'type(), w/2 args expected TypeError'
-
-try: type(1, 2, 3, 4)
-except TypeError: pass
-else: raise TestFailed, 'type(), w/4 args expected TypeError'
-
-''' TODO: No buffer support yet XXX
-print '6.8 buffer'
-
-try: buffer('asdf', -1)
-except ValueError: pass
-else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
-
-try: buffer(None)
-except TypeError: pass
-else: raise TestFailed, "buffer(None) should raise TypeError"
-
-a = buffer('asdf')
-hash(a)
-b = a * 5
-if a == b:
- raise TestFailed, 'buffers should not be equal'
-if str(b) != ('asdf' * 5):
- raise TestFailed, 'repeated buffer has wrong content'
-if str(a * 0) != '':
- raise TestFailed, 'repeated buffer zero times has wrong content'
-if str(a + buffer('def')) != 'asdfdef':
- raise TestFailed, 'concatenation of buffers yields wrong content'
-
-try: a[1] = 'g'
-except TypeError: pass
-else: raise TestFailed, "buffer assignment should raise TypeError"
-
-try: a[0:1] = 'g'
-except TypeError: pass
-else: raise TestFailed, "buffer slice assignment should raise TypeError"
-'''
-print '6.99999999... All tests ran to completion'
Deleted: /pypy/dist/pypy/appspace/test/no_test_stringmodule.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/no_test_stringmodule.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,39 +0,0 @@
-#!/usr/bin/env python
-
-
-"""
-Test module for functions in stringmodule.py
-
-"""
-
-import string as c_py_string
-import unittest
-
-import autopath
-from pypy.tool import testit
-from pypy.appspace import string as pypy_string
-
-class TestStringmodule(unittest.TestCase):
- def regression(self, sFuncname, *args, **kwargs):
- try:
- c_py_res = getattr(c_py_string, sFuncname)(*args, **kwargs)
- except Exception, ce:
- c_py_res = ce.__class__
-
- try:
- pypy_res = getattr(pypy_string, sFuncname)(*args, **kwargs)
- except Exception, pe:
- pypy_res = pe.__class__
-
- self.assertEqual(c_py_res, pypy_res, 'not equal \n1:<%s>\n2:<%s>' % (c_py_res, pypy_res))
-
-
- def test_maketrans(self):
- self.regression('maketrans','','')
- self.regression('maketrans','a','b')
- self.regression('maketrans','aa','bb')
- self.regression('maketrans','aa','')
-
-
-if __name__ == "__main__":
- testit.main()
\ No newline at end of file
Deleted: /pypy/dist/pypy/appspace/test/patched/test_sys.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/patched/test_sys.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,256 +0,0 @@
-# -*- coding: iso-8859-1 -*-
-import unittest, test.test_support
-import sys, cStringIO
-
-class SysModuleTest(unittest.TestCase):
-
- def test_original_displayhook(self):
- import __builtin__
- savestdout = sys.stdout
- out = cStringIO.StringIO()
- sys.stdout = out
-
- dh = sys.__displayhook__
-
- self.assertRaises(TypeError, dh)
- if hasattr(__builtin__, "_"):
- del __builtin__._
-
- dh(None)
- self.assertEqual(out.getvalue(), "")
- self.assert_(not hasattr(__builtin__, "_"))
- dh(42)
- self.assertEqual(out.getvalue(), "42\n")
- self.assertEqual(__builtin__._, 42)
-
- del sys.stdout
- self.assertRaises(RuntimeError, dh, 42)
-
- sys.stdout = savestdout
-
- def test_lost_displayhook(self):
- olddisplayhook = sys.displayhook
- del sys.displayhook
- code = compile("42", "<string>", "single")
- self.assertRaises(RuntimeError, eval, code)
- sys.displayhook = olddisplayhook
-
- def test_custom_displayhook(self):
- olddisplayhook = sys.displayhook
- def baddisplayhook(obj):
- raise ValueError
- sys.displayhook = baddisplayhook
- code = compile("42", "<string>", "single")
- self.assertRaises(ValueError, eval, code)
- sys.displayhook = olddisplayhook
-
- def test_original_excepthook(self):
- savestderr = sys.stderr
- err = cStringIO.StringIO()
- sys.stderr = err
-
- eh = sys.__excepthook__
-
- self.assertRaises(TypeError, eh)
- try:
- raise ValueError(42)
- except ValueError, exc:
- eh(*sys.exc_info())
-
- sys.stderr = savestderr
- self.assert_(err.getvalue().endswith("ValueError: 42\n"))
-
- # FIXME: testing the code for a lost or replaced excepthook in
- # Python/pythonrun.c::PyErr_PrintEx() is tricky.
-
- def test_exc_clear(self):
- self.assertRaises(TypeError, sys.exc_clear, 42)
-
- # Verify that exc_info is present and matches exc, then clear it, and
- # check that it worked.
- def clear_check(exc):
- typ, value, traceback = sys.exc_info()
- self.assert_(typ is not None)
- self.assert_(value is exc)
- self.assert_(traceback is not None)
-
- sys.exc_clear()
-
- typ, value, traceback = sys.exc_info()
- self.assert_(typ is None)
- self.assert_(value is None)
- self.assert_(traceback is None)
-
- def clear():
- try:
- raise ValueError, 42
- except ValueError, exc:
- clear_check(exc)
-
- # Raise an exception and check that it can be cleared
- clear()
-
- # Verify that a frame currently handling an exception is
- # unaffected by calling exc_clear in a nested frame.
- try:
- raise ValueError, 13
- except ValueError, exc:
- typ1, value1, traceback1 = sys.exc_info()
- clear()
- typ2, value2, traceback2 = sys.exc_info()
-
- self.assert_(typ1 is typ2)
- self.assert_(value1 is exc)
- self.assert_(value1 is value2)
- self.assert_(traceback1 is traceback2)
-
- # Check that an exception can be cleared outside of an except block
- clear_check(exc)
-
- def test_exit(self):
- self.assertRaises(TypeError, sys.exit, 42, 42)
-
- # call without argument
- try:
- sys.exit(0)
- except SystemExit, exc:
- self.assertEquals(exc.code, 0)
- except:
- self.fail("wrong exception")
- else:
- self.fail("no exception")
-
- # call with tuple argument with one entry
- # entry will be unpacked
- try:
- sys.exit(42)
- except SystemExit, exc:
- self.assertEquals(exc.code, 42)
- except:
- self.fail("wrong exception")
- else:
- self.fail("no exception")
-
- # call with integer argument
- try:
- sys.exit((42,))
- except SystemExit, exc:
- self.assertEquals(exc.code, 42)
- except:
- self.fail("wrong exception")
- else:
- self.fail("no exception")
-
- # call with string argument
- try:
- sys.exit("exit")
- except SystemExit, exc:
- self.assertEquals(exc.code, "exit")
- except:
- self.fail("wrong exception")
- else:
- self.fail("no exception")
-
- # call with tuple argument with two entries
- try:
- sys.exit((17, 23))
- except SystemExit, exc:
- self.assertEquals(exc.code, (17, 23))
- except:
- self.fail("wrong exception")
- else:
- self.fail("no exception")
-
- def test_getdefaultencoding(self):
- if test.test_support.have_unicode:
- self.assertRaises(TypeError, sys.getdefaultencoding, 42)
- # can't check more than the type, as the user might have changed it
- self.assert_(isinstance(sys.getdefaultencoding(), str))
-
- # testing sys.settrace() is done in test_trace.py
- # testing sys.setprofile() is done in test_profile.py
-
- def test_setcheckinterval(self):
- self.assertRaises(TypeError, sys.setcheckinterval)
- orig = sys.getcheckinterval()
- for n in 0, 100, 120, orig: # orig last to restore starting state
- sys.setcheckinterval(n)
- self.assertEquals(sys.getcheckinterval(), n)
-
- def test_recursionlimit(self):
- self.assertRaises(TypeError, sys.getrecursionlimit, 42)
- oldlimit = sys.getrecursionlimit()
- self.assertRaises(TypeError, sys.setrecursionlimit)
- self.assertRaises(ValueError, sys.setrecursionlimit, -42)
- sys.setrecursionlimit(10000)
- self.assertEqual(sys.getrecursionlimit(), 10000)
- sys.setrecursionlimit(oldlimit)
-
- def test_getwindowsversion(self):
- if hasattr(sys, "getwindowsversion"):
- v = sys.getwindowsversion()
- self.assert_(isinstance(v, tuple))
- self.assertEqual(len(v), 5)
- self.assert_(isinstance(v[0], int))
- self.assert_(isinstance(v[1], int))
- self.assert_(isinstance(v[2], int))
- self.assert_(isinstance(v[3], int))
- self.assert_(isinstance(v[4], str))
-
- def test_dlopenflags(self):
- if hasattr(sys, "setdlopenflags"):
- self.assert_(hasattr(sys, "getdlopenflags"))
- self.assertRaises(TypeError, sys.getdlopenflags, 42)
- oldflags = sys.getdlopenflags()
- self.assertRaises(TypeError, sys.setdlopenflags)
- sys.setdlopenflags(oldflags+1)
- self.assertEqual(sys.getdlopenflags(), oldflags+1)
- sys.setdlopenflags(oldflags)
-
- def test_refcount(self):
- if hasattr(sys, 'getrefcount'):
- self.assertRaises(TypeError, sys.getrefcount)
- c = sys.getrefcount(None)
- n = None
- self.assertEqual(sys.getrefcount(None), c+1)
- del n
- self.assertEqual(sys.getrefcount(None), c)
- if hasattr(sys, "gettotalrefcount"):
- self.assert_(isinstance(sys.gettotalrefcount(), int))
-
- def test_getframe(self):
- self.assertRaises(TypeError, sys._getframe, 42, 42)
- self.assertRaises(ValueError, sys._getframe, 2000000000)
- self.assert_(
- SysModuleTest.test_getframe.im_func.func_code \
- is sys._getframe().f_code
- )
-
- def test_attributes(self):
- self.assert_(isinstance(sys.api_version, int))
- self.assert_(isinstance(sys.argv, list))
- self.assert_(sys.byteorder in ("little", "big"))
- self.assert_(isinstance(sys.builtin_module_names, tuple))
- self.assert_(isinstance(sys.copyright, basestring))
- self.assert_(isinstance(sys.exec_prefix, basestring))
- self.assert_(isinstance(sys.executable, basestring))
- self.assert_(isinstance(sys.hexversion, int))
- self.assert_(isinstance(sys.maxint, int))
- self.assert_(isinstance(sys.maxunicode, int))
- self.assert_(isinstance(sys.platform, basestring))
- self.assert_(isinstance(sys.prefix, basestring))
- self.assert_(isinstance(sys.version, basestring))
- vi = sys.version_info
- self.assert_(isinstance(vi, tuple))
- self.assertEqual(len(vi), 5)
- self.assert_(isinstance(vi[0], int))
- self.assert_(isinstance(vi[1], int))
- self.assert_(isinstance(vi[2], int))
- self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
- self.assert_(isinstance(vi[4], int))
-
-def test_main():
- test.test_support.run_unittest(SysModuleTest)
-
-if __name__ == "__main__":
- test_main()
Deleted: /pypy/dist/pypy/appspace/test/support_tests.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/support_tests.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,184 +0,0 @@
-"""Supporting definitions for the Python regression tests."""
-
-'''
-if __name__ != 'test.test_support':
- raise ImportError, 'test_support must be imported from the test package'
-'''
-
-import sys, os
-from os import unlink
-
-try:
- tmpdir = sys.pypy_getudir()
-except AttributeError:
- import py
- tmpdir = str(py.test.config.tmpdir)
-TESTFN = os.path.join(tmpdir, '@test')
-
-class Error(Exception):
- """Base class for regression test exceptions."""
-
-class TestFailed(Error):
- """Test failed."""
-
-class TestSkipped(Error):
- """Test skipped.
-
- This can be raised to indicate that a test was deliberatly
- skipped, but not because a feature wasn't available. For
- example, if some resource can't be used, such as the network
- appears to be unavailable, this should be raised instead of
- TestFailed.
- """
-
-class ResourceDenied(TestSkipped):
- """Test skipped because it requested a disallowed resource.
-
- This is raised when a test calls requires() for a resource that
- has not be enabled. It is used to distinguish between expected
- and unexpected skips.
- """
-
-verbose = 0 # Flag set to 0 by regrtest.py
-use_resources = None # Flag set to [] by regrtest.py
-
-# _original_stdout is meant to hold stdout at the time regrtest began.
-# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
-# The point is to have some flavor of stdout the user can actually see.
-_original_stdout = None
-def record_original_stdout(stdout):
- global _original_stdout
- _original_stdout = stdout
-
-def get_original_stdout():
- return _original_stdout or sys.stdout
-
-def unload(name):
- try:
- del sys.modules[name]
- except KeyError:
- pass
-
-def forget(modname):
- '''"Forget" a module was ever imported by removing it from sys.modules and
- deleting any .pyc and .pyo files.'''
- unload(modname)
- import os
- for dirname in sys.path:
- try:
- os.unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
- except os.error:
- pass
- # Deleting the .pyo file cannot be within the 'try' for the .pyc since
- # the chance exists that there is no .pyc (and thus the 'try' statement
- # is exited) but there is a .pyo file.
- try:
- os.unlink(os.path.join(dirname, modname + os.extsep + 'pyo'))
- except os.error:
- pass
-
-def is_resource_enabled(resource):
- """Test whether a resource is enabled. Known resources are set by
- regrtest.py."""
- return use_resources is not None and resource in use_resources
-
-def requires(resource, msg=None):
- """Raise ResourceDenied if the specified resource is not available.
-
- If the caller's module is __main__ then automatically return True. The
- possibility of False being returned occurs when regrtest.py is executing."""
- # see if the caller's module is __main__ - if so, treat as if
- # the resource was set
- if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
- return
- if not is_resource_enabled(resource):
- if msg is None:
- msg = "Use of the `%s' resource not enabled" % resource
- raise ResourceDenied(msg)
-
-FUZZ = 1e-6
-
-def fcmp(x, y): # fuzzy comparison function
- if type(x) == type(0.0) or type(y) == type(0.0):
- try:
- x, y = float(x), float(y)
- fuzz = (abs(x) + abs(y)) * FUZZ
- if abs(x-y) <= fuzz:
- return 0
- except:
- pass
- elif type(x) == type(y) and type(x) in (type(()), type([])):
- for i in range(min(len(x), len(y))):
- outcome = fcmp(x[i], y[i])
- if outcome != 0:
- return outcome
- return cmp(len(x), len(y))
- return cmp(x, y)
-
-try:
- unicode
- have_unicode = 0 # XXX UNICODE 1
-except NameError:
- have_unicode = 0
-
-is_jython = sys.platform.startswith('java')
-
-
-
-##if fp is not None:
-## fp.close()
-##del fp
-
-def findfile(file, here=__file__):
- """Try to find a file on sys.path and the working directory. If it is not
- found the argument passed to the function is returned (this does not
- necessarily signal failure; could still be the legitimate path)."""
- import os
- if os.path.isabs(file):
- return file
- path = sys.path
- path = [os.path.dirname(here)] + path
- for dn in path:
- fn = os.path.join(dn, file)
- if os.path.exists(fn): return fn
- return file
-
-def verify(condition, reason='test failed'):
- """Verify that condition is true. If not, raise TestFailed.
-
- The optional argument reason can be given to provide
- a better error text.
- """
-
- if not condition:
- raise TestFailed(reason)
-
-def vereq(a, b):
- """Raise TestFailed if a == b is false.
-
- This is better than verify(a == b) because, in case of failure, the
- error message incorporates repr(a) and repr(b) so you can see the
- inputs.
-
- Note that "not (a == b)" isn't necessarily the same as "a != b"; the
- former is tested.
- """
-
- if not (a == b):
- raise TestFailed, "%r == %r" % (a, b)
-
-def sortdict(dict):
- "Like repr(dict), but in sorted order."
- items = dict.items()
- items.sort()
- reprpairs = ["%r: %r" % pair for pair in items]
- withcommas = ", ".join(reprpairs)
- return "{%s}" % withcommas
-
-def check_syntax(statement):
- try:
- compile(statement, '<string>', 'exec')
- except SyntaxError:
- pass
- else:
- print 'Missing SyntaxError: "%s"' % statement
Deleted: /pypy/dist/pypy/appspace/test/test_cmathmodule.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/test_cmathmodule.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,62 +0,0 @@
-#!/usr/bin/env python
-
-# taken from CPython 2.3
-
-"""
-Test module for functions in cmathmodule.py
-
-It seems the log and log10 functions are generating errors
-due to numerical problems with floor() in complex.__div__.
-"""
-
-import math
-import cmath
-import sys
-import unittest
-import autopath
-
-from pypy.appspace import cmathmodule
-from pypy.appspace.test.test_complexobject import equal
-
-def enumerate():
- valueRange = [-12.34, -3, -1, -0.5, 0, 0.5, 1, 3, 12.34]
- res = []
- for x0 in valueRange:
- for y0 in valueRange:
- z = complex(x0,y0)
- res.append(z)
- return res
-
-
-
-class TestCMathModule:
-
- def assertAEqual(self, a, b):
- if not equal(a, b):
- raise self.failureException, '%s ~== %s'%(a, b)
-
- def test_funcs(self):
- "Compare many functions with CPython."
-
- for z in enumerate():
-
- for op in "sqrt acos acosh asin asinh atan atanh cos cosh exp".split():
- if op == "atan" and equal(z, complex(0,-1)) or equal(z, complex(0,1)):
- continue
- if op == "atanh" and equal(z, complex(-1,0)) or equal(z, complex(1,0)):
- continue
- op0 = cmath.__dict__[op](z)
- op1 = cmathmodule.__dict__[op](z)
- self.assertAEqual(op0, op1)
-
-
- def test_log_log10(self):
- "Compare log/log10 functions with CPython."
-
- for z in enumerate():
- for op in "log log10".split():
- if z != 0:
- op0 = cmath.__dict__[op](z)
- op1 = cmathmodule.__dict__[op](z)
- self.assertAEqual(op0, op1)
-
Deleted: /pypy/dist/pypy/appspace/test/test_complexobject.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/test_complexobject.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,255 +0,0 @@
-#!/usr/bin/env python
-
-"""
-
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-
-Note that this test currently runs at cpython-level and not
-at any application level ....
-
-"""
-#taken from CPython 2.3 (?)
-
-"""
-Test module for class complex in complexobject.py
-
-As it seems there are some numerical differences in
-the __div__ and __divmod__ methods which have to be
-sorted out.
-"""
-
-import autopath
-
-import math
-import cmath
-import sys
-import types
-import unittest
-
-from pypy.tool import testit
-#from pypy.appspace.complexobject import complex as pycomplex
-from pypy.module.test.applevel_in_cpython import applevel_in_cpython
-our_own_builtin = applevel_in_cpython('__builtin__')
-pycomplex = our_own_builtin.complex
-
-
-try:
- unicode
- have_unicode = 0 # pypy doesn't have unicode, we know it ...
-except NameError:
- have_unicode = 0
-
-
-def equal(a, b):
- "Compare two complex or normal numbers. 0 if different, 1 if roughly equal."
-
- numTypes = [types.IntType, types.LongType, types.FloatType]
- da, db = dir(a), dir(b)
-
- if 'real' in da and 'real' in db and 'imag' in da and 'imag' in db:
- if math.fabs(a.real-b.real) > 1e-10:
- return 0
- if math.fabs(a.imag-b.imag) > 1e-10:
- return 0
- else:
- return 1
- elif type(a) in numTypes and type(b) in numTypes:
- if math.fabs(a-b) > 1e-10:
- return 0
- else:
- return 1
-
-
-
-
-def enumerate():
- valueRange = [-3, -0.5, 0, 1]
- res = []
- for x0 in valueRange:
- for y0 in valueRange:
- for x1 in valueRange:
- for y1 in valueRange:
- z0c = complex(x0,y0)
- z1c = complex(x1,y1)
- z0p = pycomplex(x0,y0)
- z1p = pycomplex(x1,y1)
- res.append((z0c, z1c, z0p, z1p))
-
- return res
-
-
-
-class TestComplex(unittest.TestCase):
-
- def assertAEqual(self, a, b):
- if not equal(a, b):
- raise self.failureException, '%s ~== %s'%(a, b)
-
- def test_wrongInit1(self):
- "Compare wrong init. with CPython."
-
- try:
- complex("1", "1")
- except TypeError:
- pass
- else:
- self.fail('complex("1", "1")')
-
- try:
- pycomplex("1", "1")
- except TypeError:
- pass
- else:
- self.fail('complex("1", "1")')
-
-
- def test_wrongInit2(self):
- "Compare wrong init. with CPython."
-
- try:
- complex(1, "1")
- except TypeError:
- pass
- else:
- self.fail('complex(1, "1")')
-
- try:
- pycomplex(1, "1")
- except TypeError:
- pass
- else:
- self.fail('complex(1, "1")')
-
-
- def test_wrongInitFromString(self):
- "Compare string init. with CPython."
-
- if complex(" 3.14+J ") != 3.14+1j:
- self.fail('complex(" 3.14+J )"')
- if not equal(pycomplex(" 3.14+J "), pycomplex(3.14,1)):
- self.fail('complex(" 3.14+J )"')
-
-
- def test_wrongInitFromUnicodeString(self):
- "Compare unicode string init. with CPython."
-
- if have_unicode:
- if complex(unicode(" 3.14+J ")) != 3.14+1j:
- self.fail('complex(u" 3.14+J )"')
- if not equal(pycomplex(unicode(" 3.14+J ")), pycomplex(3.14, 1)):
- self.fail('complex(u" 3.14+J )"')
-
-
- def test_class(self):
- "Compare class with CPython."
-
- class Z:
- def __complex__(self):
- return 3.14j
- z = Z()
- if complex(z) != 3.14j:
- self.fail('complex(classinstance)')
-
- if not equal(complex(z), pycomplex(0, 3.14)):
- self.fail('complex(classinstance)')
-
-
- def test_add_sub_mul_div(self):
- "Compare add/sub/mul/div with CPython."
-
- for (z0c, z1c, z0p, z1p) in enumerate():
- mc = z0c*z1c
- mp = z0p*z1p
- self.assertAEqual(mc, mp)
-
- sc = z0c+z1c
- sp = z0p+z1p
- self.assertAEqual(sc, sp)
-
- dc = z0c-z1c
- dp = z0p-z1p
- self.assertAEqual(dc, dp)
-
- if not equal(z1c, complex(0,0)):
- qc = z0c/z1c
- qp = z0p/z1p
- self.assertAEqual(qc, qp)
-
-
- def test_special(self):
- "Compare special methods with CPython."
-
- for (x, y) in [(0,0), (0,1), (1,3.)]:
- zc = complex(x, y)
- zp = pycomplex(x, y)
-
- self.assertAEqual(zc, zp)
- self.assertAEqual(-zc, -zp)
- self.assertAEqual(+zc, +zp)
- self.assertAEqual(abs(zc), abs(zp))
- self.assertAEqual(zc, zp)
- #self.assertEqual(zc.conjugate(), zp.conjugate()) XXX
- self.assertEqual(str(zc), str(zp))
- self.assertEqual(hash(zc), hash(zp))
-
-
- # this fails on python2.3 and is depreacted anyway
- def _test_divmod(self):
- "Compare divmod with CPython."
-
- for (z0c, z1c, z0p, z1p) in enumerate():
- mc = z0c*z1c
- mp = z0p*z1p
- self.assertAEqual(mc, mp)
-
- if not equal(z1c, complex(0,0)):
- ddc, mmc = divmod(z0c, z1c)
- self.assertAEqual(ddc*z1c + mmc, z0c)
- ddp, mmp = divmod(z0p, z1p)
- self.assertAEqual(ddp*z1p + mmp, z0p)
- self.assertAEqual(ddc, ddp)
- self.assertAEqual(mmc, mmp)
-
-
- # these fail on python2.3
- def _test_mod(self):
- "Compare mod with CPython."
-
- for (z0c, z1c, z0p, z1p) in enumerate():
- mc = z0c*z1c
- mp = z0p*z1p
- self.assertAEqual(mc, mp)
-
- if not equal(z1c, complex(0,0)):
- rc = z0c%z1c
- rp = z0p%z1p
- self.assertAEqual(rc, rp)
-
- def test_div(self):
- "Compare mod with CPython."
-
- for (z0c, z1c, z0p, z1p) in enumerate():
- mc = z0c*z1c
- mp = z0p*z1p
- self.assertAEqual(mc, mp)
-
- if not equal(z1c, complex(0,0)):
- rc = z0c/z1c
- rp = z0p/z1p
- self.assertAEqual(rc, rp)
-
-
- def test_pow(self):
- "Compare pow with CPython."
-
- for (z0c, z1c, z0p, z1p) in enumerate():
- if not equal(z0c, 0j) and (z1c.imag != 0.0):
- pc = z0c**z1c
- pp = z0p**z1p
- self.assertAEqual(pc, pp)
- pc = z0c**z0c.real
- pp = z0p**z0p.real
- self.assertAEqual(pc, pp)
-
-if __name__ == "__main__":
- testit.main()
Deleted: /pypy/dist/pypy/appspace/test/test_exceptions.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/test_exceptions.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,5 +0,0 @@
-import autopath
-
-def failing_app_test_import():
- import exceptions
- assert exceptions.SyntaxError is SyntaxError
Deleted: /pypy/dist/pypy/appspace/test/test_file.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/test_file.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,193 +0,0 @@
-import os
-import autopath
-from pypy.appspace import _file
-from pypy.tool.udir import udir
-import py
-import unittest
-
-class TestFile:
- def setup_method(self, method):
- filename = os.path.join(autopath.this_dir, 'test_file.py')
- self.fd = _file.file_(filename, 'r')
-
- def teardown_method(self, method):
- self.fd.close()
-
- def test_case_1(self):
- assert self.fd.tell() == 0
-
- def test_case_readonly(self):
- fn = str(udir.join('temptestfile'))
- f=_file.file_(fn, 'w')
- assert f.name == fn
- assert f.mode == 'w'
- assert f.closed == False
- assert f.encoding == None # Fix when we find out what this is
- py.test.raises(TypeError, setattr, f, 'name', 42)
-
-
- def test_from_cpython(self):
-
- from test.test_support import verify, TESTFN, TestFailed
- from UserList import UserList
-
- # verify expected attributes exist
- f = file(TESTFN, 'w')
- softspace = f.softspace
- f.name # merely shouldn't blow up
- f.mode # ditto
- f.closed # ditto
-
- # verify softspace is writable
- f.softspace = softspace # merely shouldn't blow up
-
- # verify the others aren't
- for attr in 'name', 'mode', 'closed':
- try:
- setattr(f, attr, 'oops')
- except TypeError:
- pass
- else:
- raise TestFailed('expected TypeError setting file attr %r' % attr)
- f.close()
-
- # 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()
- verify(buf == '12')
-
- # 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()
-
- # verify that we get a sensible error message for bad mode argument
- bad_mode = "qwerty"
- try:
- open(TESTFN, bad_mode)
- except IOError, msg:
- pass # We have problems with Exceptions
- 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.
- else:
- print "no error for invalid mode: %s" % bad_mode
-
- f = open(TESTFN)
- if f.name != TESTFN:
- raise TestFailed, 'file.name should be "%s"' % TESTFN
-
- if f.isatty():
- raise TestFailed, 'file.isatty() should be false'
-
- if f.closed:
- raise TestFailed, 'file.closed should be false'
-
-
- f.close()
- if not f.closed:
- raise TestFailed, 'file.closed should be true'
-
- # make sure that explicitly setting the buffer size doesn't cause
- # misbehaviour especially with repeated close() calls
- for s in (-1, 0, 1, 512):
- try:
- f = open(TESTFN, 'w', s)
- f.write(str(s))
- f.close()
- f.close()
- f = open(TESTFN, 'r', s)
- d = int(f.read())
- f.close()
- f.close()
- except IOError, msg:
- raise TestFailed, 'error setting buffer size %d: %s' % (s, str(msg))
- if d != s:
- raise TestFailed, 'readback failure using buffer size %d'
-
- methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readline',
- 'readlines', 'seek', 'tell', 'truncate', 'write',
- 'xreadlines', '__iter__']
-
- for methodname in methods:
- method = getattr(f, methodname)
- try:
- method()
- except ValueError:
- pass
- else:
- raise TestFailed, 'file.%s() on a closed file should raise a ValueError' % methodname
-
- try:
- f.writelines([])
- except ValueError:
- pass
- else:
- raise TestFailed, 'file.writelines([]) on a closed file should raise a ValueError'
-
- os.unlink(TESTFN)
-
- def bug801631():
- # SF bug <http://www.python.org/sf/801631>
- # "file.truncate fault on windows"
- f = file(TESTFN, 'wb')
- f.write('12345678901') # 11 bytes
- f.close()
-
- f = file(TESTFN,'rb+')
- data = f.read(5)
- if data != '12345':
- raise TestFailed("Read on file opened for update failed %r" % data)
- if f.tell() != 5:
- raise TestFailed("File pos after read wrong %d" % f.tell())
-
- f.truncate()
- if f.tell() != 5:
- raise TestFailed("File pos after ftruncate wrong %d" % f.tell())
-
- f.close()
- size = os.path.getsize(TESTFN)
- if size != 5:
- raise TestFailed("File size after ftruncate wrong %d" % size)
-
- try:
- bug801631()
- finally:
- os.unlink(TESTFN)
-
Deleted: /pypy/dist/pypy/appspace/test/test_md5.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/test_md5.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,241 +0,0 @@
-"""A test script to compare MD5 implementations.
-
-A note about performance: the pure Python MD5 takes roughly
-160 sec. per MB of data on a 233 MHz Intel Pentium CPU.
-"""
-
-import autopath
-import string, unittest
-import md5 # CPython's implementation in C.
-from pypy.appspace import md5 as pymd5 # The pure Python implementation.
-
-
-# Helpers...
-
-def formatHex(str):
- "Print a string's HEX code in groups of two digits."
-
- d = map(None, str)
- d = map(ord, d)
- d = map(lambda x:"%02x" % x, d)
- return string.join(d, " ")
-
-
-def format(str):
- "Print a string as-is in groups of two characters."
-
- s = ''
- for i in range(0, len(str)-1, 2):
- s = s + "%03s" % str[i:i+2]
- return s[1:]
-
-
-def printDiff(message, d1, d2, expectedResult=None):
- "Print different outputs for same message."
-
- print "Message: '%s'" % message
- print "Message length: %d" % len(message)
- if expectedResult:
- print "%-48s (expected)" % format(expectedResult)
- print "%-48s (Std. lib. MD5)" % formatHex(d1)
- print "%-48s (Pure Python MD5)" % formatHex(d2)
- print
-
-
-# The real comparison function.
-
-def compareImp(message):
- """Compare two MD5 implementations, C vs. pure Python module.
-
- For equal digests this returns None, otherwise it returns
- a tuple of both digests.
- """
-
- # Use Python's standard library MD5 compiled C module.
- m1 = md5.md5()
- m1.update(message)
- d1 = m1.digest()
- d1h = m1.hexdigest()
-
- # Use MD5 module in pure Python.
- m2 = pymd5.md5()
- m2.update(message)
- d2 = m2.digest()
- d2h = m2.hexdigest()
-
- # Return None if equal or the different digests if not equal.
- if d1 == d2 and d1h == d2h:
- return
- else:
- return d1, d2
-
-
-class MD5CompareTestCase(unittest.TestCase):
- "Compare pure Python MD5 against Python's std. lib. version."
-
- def test1(self):
- "Test cases with known digest result."
-
- cases = (
- ("",
- "d41d8cd98f00b204e9800998ecf8427e"),
- ("a",
- "0cc175b9c0f1b6a831c399e269772661"),
- ("abc",
- "900150983cd24fb0d6963f7d28e17f72"),
- ("message digest",
- "f96b697d7cb7938d525a2f31aaf161d0"),
- ("abcdefghijklmnopqrstuvwxyz",
- "c3fcd3d76192e4007dfb496cca67e13b"),
- ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
- "d174ab98d277d9f5a5611c2c9f419d9f"),
- ("1234567890"*8,
- "57edf4a22be3c955ac49da2e2107b67a"),
- )
-
- for i in xrange(len(cases)):
- res = compareImp(cases[i][0])
- try:
- assert res == None
- except AssertionError, details:
- d1, d2 = res
- message, expectedResult = cases[i][0], None
- if len(cases[i]) == 2:
- expectedResult = cases[i][1]
- printDiff(message, d1, d2, expectedResult)
-
-
- def test2(self):
- "Test cases without known digest result."
-
- cases = (
- "123",
- "1234",
- "12345",
- "123456",
- "1234567",
- "12345678",
- "123456789 123456789 123456789 ",
- "123456789 123456789 ",
- "123456789 123456789 1",
- "123456789 123456789 12",
- "123456789 123456789 123",
- "123456789 123456789 1234",
- "123456789 123456789 123456789 1",
- "123456789 123456789 123456789 12",
- "123456789 123456789 123456789 123",
- "123456789 123456789 123456789 1234",
- "123456789 123456789 123456789 12345",
- "123456789 123456789 123456789 123456",
- "123456789 123456789 123456789 1234567",
- "123456789 123456789 123456789 12345678",
- )
-
- for i in xrange(len(cases)):
- res = compareImp(cases[i][0])
- try:
- assert res == None
- except AssertionError, details:
- d1, d2 = res
- message = cases[i][0]
- printDiff(message, d1, d2)
-
-
- def test3(self):
- "Test cases with long messages (can take a while)."
-
- cases = (
- (2**10*'a',),
- (2**10*'abcd',),
-## (2**20*'a',), ## 1 MB, takes about 160 sec. on a 233 Mhz Pentium.
- )
-
- for i in xrange(len(cases)):
- res = compareImp(cases[i][0])
- try:
- assert res == None
- except AssertionError, details:
- d1, d2 = res
- message = cases[i][0]
- printDiff(message, d1, d2)
-
-
- def test4(self):
- "Test cases with increasingly growing message lengths."
-
- i = 0
- while i < 2**5:
- message = i * 'a'
- res = compareImp(message)
- try:
- assert res == None
- except AssertionError, details:
- d1, d2 = res
- printDiff(message, d1, d2)
- i = i + 1
-
-
- def test5(self):
- "Test updating cloned objects."
-
- cases = (
- "123",
- "1234",
- "12345",
- "123456",
- "1234567",
- "12345678",
- "123456789 123456789 123456789 ",
- "123456789 123456789 ",
- "123456789 123456789 1",
- "123456789 123456789 12",
- "123456789 123456789 123",
- "123456789 123456789 1234",
- "123456789 123456789 123456789 1",
- "123456789 123456789 123456789 12",
- "123456789 123456789 123456789 123",
- "123456789 123456789 123456789 1234",
- "123456789 123456789 123456789 12345",
- "123456789 123456789 123456789 123456",
- "123456789 123456789 123456789 1234567",
- "123456789 123456789 123456789 12345678",
- )
-
- # Load both with same prefix.
- prefix1 = 2**10 * 'a'
-
- m1 = md5.md5()
- m1.update(prefix1)
- m1c = m1.copy()
-
- m2 = pymd5.md5()
- m2.update(prefix1)
- m2c = m2.copy()
-
- # Update and compare...
- for i in xrange(len(cases)):
- message = cases[i][0]
-
- m1c.update(message)
- d1 = m1c.hexdigest()
-
- m2c.update(message)
- d2 = m2c.hexdigest()
-
- assert d1 == d2
-
-
-def makeSuite():
- suite = unittest.TestSuite()
-
- suite.addTest(MD5CompareTestCase('test1'))
- suite.addTest(MD5CompareTestCase('test2'))
- suite.addTest(MD5CompareTestCase('test3'))
- suite.addTest(MD5CompareTestCase('test4'))
- suite.addTest(MD5CompareTestCase('test5'))
-
- return suite
-
-
-if __name__ == "__main__":
- unittest.TextTestRunner().run(makeSuite())
Deleted: /pypy/dist/pypy/appspace/test/test_sha.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/test_sha.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,25 +0,0 @@
-# Testing sha module (NIST's Secure Hash Algorithm)
-
-# use the three examples from Federal Information Processing Standards
-# Publication 180-1, Secure Hash Standard, 1995 April 17
-# http://www.itl.nist.gov/div897/pubs/fip180-1.htm
-
-import autopath
-from pypy.appspace import sha
-
-class TestSHA:
- def check(self, data, digest):
- computed = sha.new(data).hexdigest()
- assert computed == digest
-
- def test_case_1(self):
- self.check("abc",
- "a9993e364706816aba3e25717850c26c9cd0d89d")
-
- def test_case_2(self):
- self.check("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
- "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
-
- def disabled_too_slow_test_case_3(self):
- self.check("a" * 1000000,
- "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
Deleted: /pypy/dist/pypy/appspace/test/test_struct.py
==============================================================================
--- /pypy/dist/pypy/appspace/test/test_struct.py Sat Jan 29 07:37:09 2005
+++ (empty file)
@@ -1,439 +0,0 @@
-import autopath
-from pypy.appspace.test.support_tests import TestFailed, verbose, verify
-from pypy.appspace import struct
-import sys
-
-ISBIGENDIAN = sys.byteorder == "big"
-del sys
-verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN,
- "bigendian determination appears wrong")
-
-def string_reverse(s):
- chars = list(s)
- chars.reverse()
- return "".join(chars)
-
-def bigendian_to_native(value):
- if ISBIGENDIAN:
- return value
- else:
- return string_reverse(value)
-
-def simple_err(func, *args):
- try:
- func(*args)
- except struct.error:
- pass
- else:
- raise TestFailed, "%s%s did not raise struct.error" % (
- func.__name__, args)
-
-def any_err(func, *args):
- try:
- func(*args)
- except (struct.error, OverflowError, TypeError):
- pass
- else:
- raise TestFailed, "%s%s did not raise error" % (
- func.__name__, args)
-
-
-simple_err(struct.calcsize, 'Z')
-
-sz = struct.calcsize('i')
-if sz * 3 != struct.calcsize('iii'):
- raise TestFailed, 'inconsistent sizes'
-
-fmt = 'cbxxxxxxhhhhiillffd'
-fmt3 = '3c3b18x12h6i6l6f3d'
-sz = struct.calcsize(fmt)
-sz3 = struct.calcsize(fmt3)
-if sz * 3 != sz3:
- raise TestFailed, 'inconsistent sizes (3*%r -> 3*%d = %d, %r -> %d)' % (
- fmt, sz, 3*sz, fmt3, sz3)
-
-simple_err(struct.pack, 'iii', 3)
-simple_err(struct.pack, 'i', 3, 3, 3)
-simple_err(struct.pack, 'i', 'foo')
-simple_err(struct.pack, 'P', 'foo')
-simple_err(struct.unpack, 'd', 'flap')
-s = struct.pack('ii', 1, 2)
-simple_err(struct.unpack, 'iii', s)
-simple_err(struct.unpack, 'i', s)
-
-c = 'a'
-b = 0
-h = 255
-i = 65535
-l = 65536
-f = 3.1415
-d = 3.1415
-
-for prefix in ('', '@', '<', '>', '=', '!'):
- for format in ('xcbhilfd', 'xcBHILfd'):
- format = prefix + format
- if verbose:
- print "trying:", format
- s = struct.pack(format, c, b, h, i, l, f, d)
- 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
- int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)):
- # ^^^ calculate only to two decimal places
- raise TestFailed, "unpack/pack not transitive (%s, %s)" % (
- str(format), str((cp, bp, hp, ip, lp, fp, dp)))
-
-# Test some of the new features in detail
-
-# (format, argument, big-endian result, little-endian result, asymmetric)
-tests = [
- ('c', 'a', 'a', 'a', 0),
- ('xc', 'a', '\0a', '\0a', 0),
- ('cx', 'a', 'a\0', 'a\0', 0),
- ('s', 'a', 'a', 'a', 0),
- ('0s', 'helloworld', '', '', 1),
- ('1s', 'helloworld', 'h', 'h', 1),
- ('9s', 'helloworld', 'helloworl', 'helloworl', 1),
- ('10s', 'helloworld', 'helloworld', 'helloworld', 0),
- ('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1),
- ('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1),
- ('b', 7, '\7', '\7', 0),
- ('b', -7, '\371', '\371', 0),
- ('B', 7, '\7', '\7', 0),
- ('B', 249, '\371', '\371', 0),
- ('h', 700, '\002\274', '\274\002', 0),
- ('h', -700, '\375D', 'D\375', 0),
- ('H', 700, '\002\274', '\274\002', 0),
- ('H', 0x10000-700, '\375D', 'D\375', 0),
- ('i', 70000000, '\004,\035\200', '\200\035,\004', 0),
- ('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
- ('I', 70000000L, '\004,\035\200', '\200\035,\004', 0),
- ('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
- ('l', 70000000, '\004,\035\200', '\200\035,\004', 0),
- ('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
- ('L', 70000000L, '\004,\035\200', '\200\035,\004', 0),
- ('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
- ('f', 2.0, '@\000\000\000', '\000\000\000@', 0),
- ('d', 2.0, '@\000\000\000\000\000\000\000','\000\000\000\000\000\000\000@', 0),
- ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0),
- ('d', -2.0, '\300\000\000\000\000\000\000\000','\000\000\000\000\000\000\000\300', 0),
-]
-
-for fmt, arg, big, lil, asy in tests:
- if verbose:
- print "%r %r %r %r" % (fmt, arg, big, lil)
- for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
- ('='+fmt, ISBIGENDIAN and big or lil)]:
- res = struct.pack(xfmt, arg)
- if res != exp:
- raise TestFailed, "pack(%r, %r) -> %r # expected %r" % (
- fmt, arg, res, exp)
- n = struct.calcsize(xfmt)
- if n != len(res):
- raise TestFailed, "calcsize(%r) -> %d # expected %d" % (
- xfmt, n, len(res))
- rev = struct.unpack(xfmt, res)[0]
- if rev != arg and not asy:
- raise TestFailed, "unpack(%r, %r) -> (%r,) # expected (%r,)" % (
- fmt, res, rev, arg)
-
-###########################################################################
-# Simple native q/Q tests.
-
-has_native_qQ = 1
-try:
- struct.pack("q", 5)
-except struct.error:
- has_native_qQ = 0
-
-if verbose:
- print "Platform has native q/Q?", has_native_qQ and "Yes." or "No."
-
-any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless
-simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless
-simple_err(struct.pack, "Q", "a") # ditto, but 'Q'
-
-def test_native_qQ():
- bytes = struct.calcsize('q')
- # The expected values here are in big-endian format, primarily because
- # I'm on a little-endian machine and so this is the clearest way (for
- # me) to force the code to get exercised.
- for format, input, expected in (
- ('q', -1, '\xff' * bytes),
- ('q', 0, '\x00' * bytes),
- ('Q', 0, '\x00' * bytes),
- ('q', 1L, '\x00' * (bytes-1) + '\x01'),
- ('Q', (1L << (8*bytes))-1, '\xff' * bytes),
- ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))):
- got = struct.pack(format, input)
- native_expected = bigendian_to_native(expected)
- verify(got == native_expected,
- "%r-pack of %r gave %r, not %r" %
- (format, input, got, native_expected))
- retrieved = struct.unpack(format, got)[0]
- verify(retrieved == input,
- "%r-unpack of %r gave %r, not %r" %
- (format, got, retrieved, input))
-
-if has_native_qQ:
- test_native_qQ()
-
-###########################################################################
-# Standard integer tests (bBhHiIlLqQ).
-
-import binascii
-
-class IntTester:
-
- # XXX Most std integer modes fail to test for out-of-range.
- # The "i" and "l" codes appear to range-check OK on 32-bit boxes, but
- # fail to check correctly on some 64-bit ones (Tru64 Unix + Compaq C
- # reported by Mark Favas).
- BUGGY_RANGE_CHECK = "bBhHiIlL"
-
- def __init__(self, formatpair, bytesize):
- assert len(formatpair) == 2
- self.formatpair = formatpair
- for direction in "<>!=":
- for code in formatpair:
- format = direction + code
- verify(struct.calcsize(format) == bytesize)
- self.bytesize = bytesize
- self.bitsize = bytesize * 8
- self.signed_code, self.unsigned_code = formatpair
- self.unsigned_min = 0
- self.unsigned_max = 2L**self.bitsize - 1
- self.signed_min = -(2L**(self.bitsize-1))
- self.signed_max = 2L**(self.bitsize-1) - 1
-
- def test_one(self, x, pack=struct.pack,
- unpack=struct.unpack,
- unhexlify=binascii.unhexlify):
- if verbose:
- print "trying std", self.formatpair, "on", x, "==", hex(x)
-
- # Try signed.
- code = self.signed_code
- if self.signed_min <= x <= self.signed_max:
- # Try big -endian.
- expected = long(x)
- if x < 0:
- expected += 1L << self.bitsize
- assert expected > 0
- expected = hex(expected)[2:-1] # chop "0x" and trailing 'L'
- if len(expected) & 1:
- expected = "0" + expected
- expected = unhexlify(expected)
- expected = "\x00" * (self.bytesize - len(expected)) + expected
-
- # Pack work?
- format = ">" + code
- got = pack(format, x)
- verify(got == expected,
- "'%s'-pack of %r gave %r, not %r" %
- (format, x, got, expected))
-
- # Unpack work?
- retrieved = unpack(format, got)[0]
- verify(x == retrieved,
- "'%s'-unpack of %r gave %r, not %r" %
- (format, got, retrieved, x))
-
- # Adding any byte should cause a "too big" error.
- any_err(unpack, format, '\x01' + got)
-
- # Try little-endian.
- format = "<" + code
- expected = string_reverse(expected)
-
- # Pack work?
- got = pack(format, x)
- verify(got == expected,
- "'%s'-pack of %r gave %r, not %r" %
- (format, x, got, expected))
-
- # Unpack work?
- retrieved = unpack(format, got)[0]
- verify(x == retrieved,
- "'%s'-unpack of %r gave %r, not %r" %
- (format, got, retrieved, x))
-
- # Adding any byte should cause a "too big" error.
- any_err(unpack, format, '\x01' + got)
-
- else:
- # x is out of range -- verify pack realizes that.
- if code in self.BUGGY_RANGE_CHECK:
- if verbose:
- print "Skipping buggy range check for code", code
- else:
- any_err(pack, ">" + code, x)
- any_err(pack, "<" + code, x)
-
- # Much the same for unsigned.
- code = self.unsigned_code
- if self.unsigned_min <= x <= self.unsigned_max:
- # Try big-endian.
- format = ">" + code
- expected = long(x)
- expected = hex(expected)[2:-1] # chop "0x" and trailing 'L'
- if len(expected) & 1:
- expected = "0" + expected
- expected = unhexlify(expected)
- expected = "\x00" * (self.bytesize - len(expected)) + expected
-
- # Pack work?
- got = pack(format, x)
- verify(got == expected,
- "'%s'-pack of %r gave %r, not %r" %
- (format, x, got, expected))
-
- # Unpack work?
- retrieved = unpack(format, got)[0]
- verify(x == retrieved,
- "'%s'-unpack of %r gave %r, not %r" %
- (format, got, retrieved, x))
-
- # Adding any byte should cause a "too big" error.
- any_err(unpack, format, '\x01' + got)
-
- # Try little-endian.
- format = "<" + code
- expected = string_reverse(expected)
-
- # Pack work?
- got = pack(format, x)
- verify(got == expected,
- "'%s'-pack of %r gave %r, not %r" %
- (format, x, got, expected))
-
- # Unpack work?
- retrieved = unpack(format, got)[0]
- verify(x == retrieved,
- "'%s'-unpack of %r gave %r, not %r" %
- (format, got, retrieved, x))
-
- # Adding any byte should cause a "too big" error.
- any_err(unpack, format, '\x01' + got)
-
- else:
- # x is out of range -- verify pack realizes that.
- if code in self.BUGGY_RANGE_CHECK:
- if verbose:
- print "Skipping buggy range check for code", code
- else:
- any_err(pack, ">" + code, x)
- any_err(pack, "<" + code, x)
-
- def run(self):
- from random import randrange
-
- # Create all interesting powers of 2.
- values = []
- for exp in range(self.bitsize + 3):
- values.append(1L << exp)
-
- # Add some random values.
- for i in range(self.bitsize):
- val = 0L
- for j in range(self.bytesize):
- val = (val << 8) | randrange(256)
- values.append(val)
-
- # Try all those, and their negations, and +-1 from them. Note
- # that this tests all power-of-2 boundaries in range, and a few out
- # of range, plus +-(2**n +- 1).
- for base in values:
- for val in -base, base:
- for incr in -1, 0, 1:
- x = val + incr
- try:
- x = int(x)
- except OverflowError:
- pass
- self.test_one(x)
-
- # Some error cases.
- for direction in "<>":
- for code in self.formatpair:
- for badobject in "a string", 3+42j, randrange:
- any_err(struct.pack, direction + code, badobject)
-
-for args in [("bB", 1),
- ("hH", 2),
- ("iI", 4),
- ("lL", 4),
- ("qQ", 8)]:
- t = IntTester(*args)
- t.run()
-
-
-###########################################################################
-# The p ("Pascal string") code.
-
-def test_p_code():
- for code, input, expected, expectedback in [
- ('p','abc', '\x00', ''),
- ('1p', 'abc', '\x00', ''),
- ('2p', 'abc', '\x01a', 'a'),
- ('3p', 'abc', '\x02ab', 'ab'),
- ('4p', 'abc', '\x03abc', 'abc'),
- ('5p', 'abc', '\x03abc\x00', 'abc'),
- ('6p', 'abc', '\x03abc\x00\x00', 'abc'),
- ('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]:
- got = struct.pack(code, input)
- if got != expected:
- raise TestFailed("pack(%r, %r) == %r but expected %r" %
- (code, input, got, expected))
- (got,) = struct.unpack(code, got)
- if got != expectedback:
- raise TestFailed("unpack(%r, %r) == %r but expected %r" %
- (code, input, got, expectedback))
-
-test_p_code()
-
-
-###########################################################################
-# SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry
-# from the low-order discarded bits could propagate into the exponent
-# field, causing the result to be wrong by a factor of 2.
-
-def test_705836():
- import math
-
- for base in range(1, 33):
- # smaller <- largest representable float less than base.
- delta = 0.5
- while base - delta / 2.0 != base:
- delta /= 2.0
- smaller = base - delta
- # Packing this rounds away a solid string of trailing 1 bits.
- packed = struct.pack("<f", smaller)
- unpacked = struct.unpack("<f", packed)[0]
- # This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
- # 16, respectively.
- # print base,delta,"pypy :%s"%packed,unpacked,"CPython :",Cunpacked
- verify(base == unpacked," %s == %s"%(base,unpacked))
- bigpacked = struct.pack(">f", smaller)
- verify(bigpacked == string_reverse(packed),
- ">f pack should be byte-reversal of <f pack")
- unpacked = struct.unpack(">f", bigpacked)[0]
- verify(base == unpacked)
-
- # Largest finite IEEE single.
- big = (1 << 24) - 1
- big = math.ldexp(big, 127 - 23)
- packed = struct.pack(">f", big)
- unpacked = struct.unpack(">f", packed)[0]
- verify(big == unpacked)
-
- # The same, but tack on a 1 bit so it rounds up to infinity.
- big = (1 << 25) - 1
- big = math.ldexp(big, 127 - 24)
- try:
- packed = struct.pack(">f", big)
- except OverflowError:
- pass
- else:
- TestFailed("expected OverflowError")
-
-test_705836()
More information about the Pypy-commit
mailing list