Commits

David Schneider committed 7aeb31f Merge

merge arm-backend-2

Comments (0)

Files changed (183)

lib-python/conftest.py

     group.addoption('--pypy', action="store", type="string",
        dest="pypy",  help="use given pypy executable to run lib-python tests. "
                           "This will run the tests directly (i.e. not through py.py)")
-   
+    group.addoption('--filter', action="store", type="string", default=None,
+                    dest="unittest_filter",  help="Similar to -k, XXX")
+
 option = py.test.config.option 
 
 def gettimeout(): 
             else:
                 status = 'abnormal termination 0x%x' % status
         else:
-            status = os.system("%s >>%s 2>>%s" %(cmd, stdout, stderr))
+            if self.config.option.unittest_filter is not None:
+                cmd += ' --filter %s' % self.config.option.unittest_filter
+            if self.config.option.usepdb:
+                cmd += ' --pdb'
+            if self.config.option.capture == 'no':
+                status = os.system(cmd)
+            else:
+                status = os.system("%s >>%s 2>>%s" %(cmd, stdout, stderr))
             if os.WIFEXITED(status):
                 status = os.WEXITSTATUS(status)
             else:

lib-python/modified-2.7.0/UserDict.py

+"""A more or less complete user-defined wrapper around dictionary objects."""
+
+# XXX This is a bit of a hack (as usual :-))
+# the actual content of the file is not changed, but we put it here to make
+# virtualenv happy (because its internal logic expects at least one of the
+# REQUIRED_MODULES to be in modified-*)
+
+class UserDict:
+    def __init__(self, dict=None, **kwargs):
+        self.data = {}
+        if dict is not None:
+            self.update(dict)
+        if len(kwargs):
+            self.update(kwargs)
+    def __repr__(self): return repr(self.data)
+    def __cmp__(self, dict):
+        if isinstance(dict, UserDict):
+            return cmp(self.data, dict.data)
+        else:
+            return cmp(self.data, dict)
+    __hash__ = None # Avoid Py3k warning
+    def __len__(self): return len(self.data)
+    def __getitem__(self, key):
+        if key in self.data:
+            return self.data[key]
+        if hasattr(self.__class__, "__missing__"):
+            return self.__class__.__missing__(self, key)
+        raise KeyError(key)
+    def __setitem__(self, key, item): self.data[key] = item
+    def __delitem__(self, key): del self.data[key]
+    def clear(self): self.data.clear()
+    def copy(self):
+        if self.__class__ is UserDict:
+            return UserDict(self.data.copy())
+        import copy
+        data = self.data
+        try:
+            self.data = {}
+            c = copy.copy(self)
+        finally:
+            self.data = data
+        c.update(self)
+        return c
+    def keys(self): return self.data.keys()
+    def items(self): return self.data.items()
+    def iteritems(self): return self.data.iteritems()
+    def iterkeys(self): return self.data.iterkeys()
+    def itervalues(self): return self.data.itervalues()
+    def values(self): return self.data.values()
+    def has_key(self, key): return key in self.data
+    def update(self, dict=None, **kwargs):
+        if dict is None:
+            pass
+        elif isinstance(dict, UserDict):
+            self.data.update(dict.data)
+        elif isinstance(dict, type({})) or not hasattr(dict, 'items'):
+            self.data.update(dict)
+        else:
+            for k, v in dict.items():
+                self[k] = v
+        if len(kwargs):
+            self.data.update(kwargs)
+    def get(self, key, failobj=None):
+        if key not in self:
+            return failobj
+        return self[key]
+    def setdefault(self, key, failobj=None):
+        if key not in self:
+            self[key] = failobj
+        return self[key]
+    def pop(self, key, *args):
+        return self.data.pop(key, *args)
+    def popitem(self):
+        return self.data.popitem()
+    def __contains__(self, key):
+        return key in self.data
+    @classmethod
+    def fromkeys(cls, iterable, value=None):
+        d = cls()
+        for key in iterable:
+            d[key] = value
+        return d
+
+class IterableUserDict(UserDict):
+    def __iter__(self):
+        return iter(self.data)
+
+import _abcoll
+_abcoll.MutableMapping.register(IterableUserDict)
+
+
+class DictMixin:
+    # Mixin defining all dictionary methods for classes that already have
+    # a minimum dictionary interface including getitem, setitem, delitem,
+    # and keys. Without knowledge of the subclass constructor, the mixin
+    # does not define __init__() or copy().  In addition to the four base
+    # methods, progressively more efficiency comes with defining
+    # __contains__(), __iter__(), and iteritems().
+
+    # second level definitions support higher levels
+    def __iter__(self):
+        for k in self.keys():
+            yield k
+    def has_key(self, key):
+        try:
+            self[key]
+        except KeyError:
+            return False
+        return True
+    def __contains__(self, key):
+        return self.has_key(key)
+
+    # third level takes advantage of second level definitions
+    def iteritems(self):
+        for k in self:
+            yield (k, self[k])
+    def iterkeys(self):
+        return self.__iter__()
+
+    # fourth level uses definitions from lower levels
+    def itervalues(self):
+        for _, v in self.iteritems():
+            yield v
+    def values(self):
+        return [v for _, v in self.iteritems()]
+    def items(self):
+        return list(self.iteritems())
+    def clear(self):
+        for key in self.keys():
+            del self[key]
+    def setdefault(self, key, default=None):
+        try:
+            return self[key]
+        except KeyError:
+            self[key] = default
+        return default
+    def pop(self, key, *args):
+        if len(args) > 1:
+            raise TypeError, "pop expected at most 2 arguments, got "\
+                              + repr(1 + len(args))
+        try:
+            value = self[key]
+        except KeyError:
+            if args:
+                return args[0]
+            raise
+        del self[key]
+        return value
+    def popitem(self):
+        try:
+            k, v = self.iteritems().next()
+        except StopIteration:
+            raise KeyError, 'container is empty'
+        del self[k]
+        return (k, v)
+    def update(self, other=None, **kwargs):
+        # Make progressively weaker assumptions about "other"
+        if other is None:
+            pass
+        elif hasattr(other, 'iteritems'):  # iteritems saves memory and lookups
+            for k, v in other.iteritems():
+                self[k] = v
+        elif hasattr(other, 'keys'):
+            for k in other.keys():
+                self[k] = other[k]
+        else:
+            for k, v in other:
+                self[k] = v
+        if kwargs:
+            self.update(kwargs)
+    def get(self, key, default=None):
+        try:
+            return self[key]
+        except KeyError:
+            return default
+    def __repr__(self):
+        return repr(dict(self.iteritems()))
+    def __cmp__(self, other):
+        if other is None:
+            return 1
+        if isinstance(other, DictMixin):
+            other = dict(other.iteritems())
+        return cmp(dict(self.iteritems()), other)
+    def __len__(self):
+        return len(self.keys())

lib-python/modified-2.7.0/ctypes/test/__init__.py

         result = unittest.TestResult()
         test(result)
         return result
+
+def xfail(method):
+    """
+    Poor's man xfail: remove it when all the failures have been fixed
+    """
+    def new_method(self):
+        try:
+            method(self)
+        except:
+            pass
+        else:
+            self.assertTrue(False, "DID NOT RAISE")
+    return new_method

lib-python/modified-2.7.0/ctypes/test/test_bitfields.py

 
 import ctypes
 import _ctypes_test
+from ctypes.test import xfail
 
 class BITS(Structure):
     _fields_ = [("A", c_int, 1),
         return self.get_except(type(Structure), "X", (),
                                {"_fields_": fields})
 
+    @xfail
     def test_nonint_types(self):
         # bit fields are not allowed on non-integer types.
         result = self.fail_fields(("a", c_char_p, 1))
         result = self.fail_fields(("a", Dummy, 1))
         self.assertEqual(result, (TypeError, 'bit fields not allowed for type Dummy'))
 
+    @xfail
     def test_single_bitfield_size(self):
         for c_typ in int_types:
             result = self.fail_fields(("a", c_typ, -1))

lib-python/modified-2.7.0/ctypes/test/test_byteswap.py

 from binascii import hexlify
 
 from ctypes import *
+from ctypes.test import xfail
 
 def bin(s):
     return hexlify(memoryview(s)).upper()
             setattr(bits, "i%s" % i, 1)
             dump(bits)
 
+    @xfail
     def test_endian_short(self):
         if sys.byteorder == "little":
             self.assertTrue(c_short.__ctype_le__ is c_short)
         self.assertEqual(bin(s), "3412")
         self.assertEqual(s.value, 0x1234)
 
+    @xfail
     def test_endian_int(self):
         if sys.byteorder == "little":
             self.assertTrue(c_int.__ctype_le__ is c_int)
         self.assertEqual(bin(s), "78563412")
         self.assertEqual(s.value, 0x12345678)
 
+    @xfail
     def test_endian_longlong(self):
         if sys.byteorder == "little":
             self.assertTrue(c_longlong.__ctype_le__ is c_longlong)
         self.assertEqual(bin(s), "EFCDAB9078563412")
         self.assertEqual(s.value, 0x1234567890ABCDEF)
 
+    @xfail
     def test_endian_float(self):
         if sys.byteorder == "little":
             self.assertTrue(c_float.__ctype_le__ is c_float)
         self.assertAlmostEqual(s.value, math.pi, 6)
         self.assertEqual(bin(struct.pack(">f", math.pi)), bin(s))
 
+    @xfail
     def test_endian_double(self):
         if sys.byteorder == "little":
             self.assertTrue(c_double.__ctype_le__ is c_double)
         self.assertTrue(c_char.__ctype_le__ is c_char)
         self.assertTrue(c_char.__ctype_be__ is c_char)
 
+    @xfail
     def test_struct_fields_1(self):
         if sys.byteorder == "little":
             base = BigEndianStructure
             pass
         self.assertRaises(TypeError, setattr, S, "_fields_", [("s", T)])
 
+    @xfail
     def test_struct_fields_2(self):
         # standard packing in struct uses no alignment.
         # So, we have to align using pad bytes.
         s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)
         self.assertEqual(bin(s1), bin(s2))
 
+    @xfail
     def test_unaligned_nonnative_struct_fields(self):
         if sys.byteorder == "little":
             base = BigEndianStructure

lib-python/modified-2.7.0/ctypes/test/test_callbacks.py

 import unittest
 from ctypes import *
 import _ctypes_test
+from ctypes.test import xfail
 
 class Callbacks(unittest.TestCase):
     functype = CFUNCTYPE
         prototype = self.functype.im_func(object)
         self.assertRaises(TypeError, prototype, lambda: None)
 
+    @xfail
     def test_issue_7959(self):
         proto = self.functype.im_func(None)
 

lib-python/modified-2.7.0/ctypes/test/test_cast.py

 import unittest
 import sys
 
+from ctypes.test import xfail
+
 class Test(unittest.TestCase):
 
     def test_array2pointer(self):

lib-python/modified-2.7.0/ctypes/test/test_frombuffer.py

 import array
 import gc
 import unittest
+from ctypes.test import xfail
 
 class X(Structure):
     _fields_ = [("c_int", c_int)]
         self._init_called = True
 
 class Test(unittest.TestCase):
+    @xfail
     def test_fom_buffer(self):
         a = array.array("i", range(16))
         x = (c_int * 16).from_buffer(a)
         self.assertRaises(TypeError,
                           (c_char * 16).from_buffer, "a" * 16)
 
+    @xfail
     def test_fom_buffer_with_offset(self):
         a = array.array("i", range(16))
         x = (c_int * 15).from_buffer(a, sizeof(c_int))
         self.assertRaises(ValueError, lambda: (c_int * 16).from_buffer(a, sizeof(c_int)))
         self.assertRaises(ValueError, lambda: (c_int * 1).from_buffer(a, 16 * sizeof(c_int)))
 
+    @xfail
     def test_from_buffer_copy(self):
         a = array.array("i", range(16))
         x = (c_int * 16).from_buffer_copy(a)
         x = (c_char * 16).from_buffer_copy("a" * 16)
         self.assertEqual(x[:], "a" * 16)
 
+    @xfail
     def test_fom_buffer_copy_with_offset(self):
         a = array.array("i", range(16))
         x = (c_int * 15).from_buffer_copy(a, sizeof(c_int))

lib-python/modified-2.7.0/ctypes/test/test_functions.py

 
 from ctypes import *
 import sys, unittest
+from ctypes.test import xfail
 
 try:
     WINFUNCTYPE
             self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h),
                                  (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9))
 
+    @xfail
     def test_sf1651235(self):
         # see http://www.python.org/sf/1651235
 

lib-python/modified-2.7.0/ctypes/test/test_init.py

 from ctypes import *
 import unittest
+from ctypes.test import xfail
 
 class X(Structure):
     _fields_ = [("a", c_int),
 
 
 class InitTest(unittest.TestCase):
+    @xfail
     def test_get(self):
         # make sure the only accessing a nested structure
         # doesn't call the structure's __new__ and __init__

lib-python/modified-2.7.0/ctypes/test/test_internals.py

 import unittest
 from ctypes import *
 from sys import getrefcount as grc
+from ctypes.test import xfail
 
 # XXX This test must be reviewed for correctness!!!
 
         self.assertEqual(refcnt, grc(i))
         self.assertEqual(ci._objects, None)
 
+    @xfail
     def test_c_char_p(self):
         s = "Hello, World"
         refcnt = grc(s)

lib-python/modified-2.7.0/ctypes/test/test_libc.py

         lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort))
         self.assertEqual(chars.raw, "   ,,aaaadmmmnpppsss\x00")
 
+    def test_no_more_xfail(self):
+        import ctypes.test
+        self.assertTrue(not hasattr(ctypes.test, 'xfail'),
+                        "You should incrementally grep for '@xfail' and remove them, they are real failures")
+
 if __name__ == "__main__":
     unittest.main()

lib-python/modified-2.7.0/ctypes/test/test_numbers.py

 from ctypes import *
 import unittest
 import struct
+from ctypes.test import xfail
 
 def valid_ranges(*types):
     # given a sequence of numeric types, collect their _type_
 ##            self.assertRaises(ValueError, t, l-1)
 ##            self.assertRaises(ValueError, t, h+1)
 
+    @xfail
     def test_from_param(self):
         # the from_param class method attribute always
         # returns PyCArgObject instances
         for t in signed_types + unsigned_types + float_types:
             self.assertEqual(ArgType, type(t.from_param(0)))
 
+    @xfail
     def test_byref(self):
         # calling byref returns also a PyCArgObject instance
         for t in signed_types + unsigned_types + float_types + bool_types:
             self.assertEqual(ArgType, type(parm))
 
 
+    @xfail
     def test_floats(self):
         # c_float and c_double can be created from
         # Python int, long and float
             self.assertEqual(t(2L).value, 2.0)
             self.assertEqual(t(f).value, 2.0)
 
+    @xfail
     def test_integers(self):
         class FloatLike(object):
             def __float__(self):

lib-python/modified-2.7.0/ctypes/test/test_parameters.py

 import unittest, sys
 
+from ctypes.test import xfail
+
 class SimpleTypesTestCase(unittest.TestCase):
 
     def setUp(self):
         self.assertEqual(CWCHARP.from_param("abc"), "abcabcabc")
 
     # XXX Replace by c_char_p tests
+    @xfail
     def test_cstrings(self):
         from ctypes import c_char_p, byref
 
         pa = c_wchar_p.from_param(c_wchar_p(u"123"))
         self.assertEqual(type(pa), c_wchar_p)
 
+    @xfail
     def test_int_pointers(self):
         from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
         LPINT = POINTER(c_int)

lib-python/modified-2.7.0/ctypes/test/test_pep3118.py

 import unittest
 from ctypes import *
 import re, sys
+from ctypes.test import xfail
 
 if sys.byteorder == "little":
     THIS_ENDIAN = "<"
 
 class Test(unittest.TestCase):
 
+    @xfail
     def test_native_types(self):
         for tp, fmt, shape, itemtp in native_types:
             ob = tp()
                 print(tp)
                 raise
 
+    @xfail
     def test_endian_types(self):
         for tp, fmt, shape, itemtp in endian_types:
             ob = tp()

lib-python/modified-2.7.0/ctypes/test/test_pickling.py

 from ctypes import *
 import _ctypes_test
 dll = CDLL(_ctypes_test.__file__)
+from ctypes.test import xfail
 
 class X(Structure):
     _fields_ = [("a", c_int), ("b", c_double)]
     def loads(self, item):
         return pickle.loads(item)
 
+    @xfail
     def test_simple(self):
         for src in [
             c_int(42),
             self.assertEqual(memoryview(src).tobytes(),
                                  memoryview(dst).tobytes())
 
+    @xfail
     def test_struct(self):
         X.init_called = 0
 
         self.assertEqual(memoryview(y).tobytes(),
                              memoryview(x).tobytes())
 
+    @xfail
     def test_unpickable(self):
         # ctypes objects that are pointers or contain pointers are
         # unpickable.
             ]:
             self.assertRaises(ValueError, lambda: self.dumps(item))
 
+    @xfail
     def test_wchar(self):
         pickle.dumps(c_char("x"))
         # Issue 5049

lib-python/modified-2.7.0/ctypes/test/test_prototypes.py

 from ctypes import *
 import unittest
+from ctypes.test import xfail
 
 # IMPORTANT INFO:
 #
         func.restype = c_long
         func.argtypes = None
 
+    @xfail
     def test_paramflags(self):
         # function returns c_void_p result,
         # and has a required parameter named 'input'

lib-python/modified-2.7.0/ctypes/test/test_python_api.py

 from ctypes import *
 import unittest, sys
-from ctypes.test import is_resource_enabled
+from ctypes.test import is_resource_enabled, xfail
 
 ################################################################
 # This section should be moved into ctypes\__init__.py, when it's ready.
 
 class PythonAPITestCase(unittest.TestCase):
 
+    @xfail
     def test_PyString_FromStringAndSize(self):
         PyString_FromStringAndSize = pythonapi.PyString_FromStringAndSize
 
 
         self.assertEqual(PyString_FromStringAndSize("abcdefghi", 3), "abc")
 
+    @xfail
     def test_PyString_FromString(self):
         pythonapi.PyString_FromString.restype = py_object
         pythonapi.PyString_FromString.argtypes = (c_char_p,)
             del res
             self.assertEqual(grc(42), ref42)
 
+    @xfail
     def test_PyObj_FromPtr(self):
         s = "abc def ghi jkl"
         ref = grc(s)
         # not enough arguments
         self.assertRaises(TypeError, PyOS_snprintf, buf)
 
+    @xfail
     def test_pyobject_repr(self):
         self.assertEqual(repr(py_object()), "py_object(<NULL>)")
         self.assertEqual(repr(py_object(42)), "py_object(42)")

lib-python/modified-2.7.0/ctypes/test/test_refcounts.py

 import unittest
 import ctypes
 import gc
+from ctypes.test import xfail
 
 MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
 OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
         self.assertEqual(grc(func), 2)
 
 class AnotherLeak(unittest.TestCase):
+    @xfail
     def test_callback(self):
         import sys
 

lib-python/modified-2.7.0/ctypes/test/test_simplesubclasses.py

 import unittest
 from ctypes import *
+from ctypes.test import xfail
 
 class MyInt(c_int):
     def __cmp__(self, other):
         self.assertEqual(None, cb())
 
 
+    @xfail
     def test_int_callback(self):
         args = []
         def func(arg):

lib-python/modified-2.7.0/ctypes/test/test_stringptr.py

 from ctypes import *
 
 import _ctypes_test
+from ctypes.test import xfail
 
 lib = CDLL(_ctypes_test.__file__)
 
 class StringPtrTestCase(unittest.TestCase):
 
+    @xfail
     def test__POINTER_c_char(self):
         class X(Structure):
             _fields_ = [("str", POINTER(c_char))]
 
         self.assertRaises(TypeError, setattr, x, "str", "Hello, World")
 
+    @xfail
     def test__c_char_p(self):
         class X(Structure):
             _fields_ = [("str", c_char_p)]

lib-python/modified-2.7.0/ctypes/test/test_strings.py

 import unittest
 from ctypes import *
 from test import test_support
+from ctypes.test import xfail
 
 class StringArrayTestCase(unittest.TestCase):
     def test(self):
         self.assertRaises(ValueError, setattr, buf, "value", "aaaaaaaa")
         self.assertRaises(TypeError, setattr, buf, "value", 42)
 
+    @xfail
     def test_c_buffer_value(self, memoryview=memoryview):
         buf = c_buffer(32)
 
         self.assertRaises(TypeError, setattr, buf, "value", memoryview("abc"))
         self.assertRaises(ValueError, setattr, buf, "raw", memoryview("x" * 100))
 
+    @xfail
     def test_c_buffer_raw(self, memoryview=memoryview):
         buf = c_buffer(32)
 
         self.assertRaises(TypeError, setattr, buf, "value", memoryview("abc"))
         self.assertRaises(ValueError, setattr, buf, "raw", memoryview("x" * 100))
 
+    @xfail
     def test_c_buffer_deprecated(self):
         # Compatibility with 2.x
         with test_support.check_py3k_warnings():

lib-python/modified-2.7.0/ctypes/test/test_varsize_struct.py

 from ctypes import *
 import unittest
+from ctypes.test import xfail
 
 class VarSizeTest(unittest.TestCase):
+    @xfail
     def test_resize(self):
         class X(Structure):
             _fields_ = [("item", c_int),

lib-python/modified-2.7.0/site.py

+"""Append module search paths for third-party packages to sys.path.
+
+****************************************************************
+* This module is automatically imported during initialization. *
+****************************************************************
+
+In earlier versions of Python (up to 1.5a3), scripts or modules that
+needed to use site-specific modules would place ``import site''
+somewhere near the top of their code.  Because of the automatic
+import, this is no longer necessary (but code that does it still
+works).
+
+This will append site-specific paths to the module search path.  On
+Unix (including Mac OSX), it starts with sys.prefix and
+sys.exec_prefix (if different) and appends
+lib/python<version>/site-packages as well as lib/site-python.
+On other platforms (such as Windows), it tries each of the
+prefixes directly, as well as with lib/site-packages appended.  The
+resulting directories, if they exist, are appended to sys.path, and
+also inspected for path configuration files.
+
+A path configuration file is a file whose name has the form
+<package>.pth; its contents are additional directories (one per line)
+to be added to sys.path.  Non-existing directories (or
+non-directories) are never added to sys.path; no directory is added to
+sys.path more than once.  Blank lines and lines beginning with
+'#' are skipped. Lines starting with 'import' are executed.
+
+For example, suppose sys.prefix and sys.exec_prefix are set to
+/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
+with three subdirectories, foo, bar and spam, and two path
+configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
+following:
+
+  # foo package configuration
+  foo
+  bar
+  bletch
+
+and bar.pth contains:
+
+  # bar package configuration
+  bar
+
+Then the following directories are added to sys.path, in this order:
+
+  /usr/local/lib/python2.5/site-packages/bar
+  /usr/local/lib/python2.5/site-packages/foo
+
+Note that bletch is omitted because it doesn't exist; bar precedes foo
+because bar.pth comes alphabetically before foo.pth; and spam is
+omitted because it is not mentioned in either path configuration file.
+
+After these path manipulations, an attempt is made to import a module
+named sitecustomize, which can perform arbitrary additional
+site-specific customizations.  If this import fails with an
+ImportError exception, it is silently ignored.
+
+"""
+
+import sys
+import os
+import __builtin__
+
+# Prefixes for site-packages; add additional prefixes like /usr/local here
+PREFIXES = [sys.prefix, sys.exec_prefix]
+# Enable per user site-packages directory
+# set it to False to disable the feature or True to force the feature
+ENABLE_USER_SITE = None
+
+# for distutils.commands.install
+# These values are initialized by the getuserbase() and getusersitepackages()
+# functions, through the main() function when Python starts.
+USER_SITE = None
+USER_BASE = None
+
+def makepath(*paths):
+    dir = os.path.join(*paths)
+    try:
+        dir = os.path.abspath(dir)
+    except OSError:
+        pass
+    return dir, os.path.normcase(dir)
+
+
+def abs__file__():
+    """Set all module' __file__ attribute to an absolute path"""
+    for m in sys.modules.values():
+        if hasattr(m, '__loader__'):
+            continue   # don't mess with a PEP 302-supplied __file__
+        try:
+            prev = m.__file__
+            new = os.path.abspath(m.__file__)
+            if prev != new:
+                m.__file__ = new
+        except (AttributeError, OSError):
+            pass
+
+
+def removeduppaths():
+    """ Remove duplicate entries from sys.path along with making them
+    absolute"""
+    # This ensures that the initial path provided by the interpreter contains
+    # only absolute pathnames, even if we're running from the build directory.
+    L = []
+    known_paths = set()
+    for dir in sys.path:
+        # Filter out duplicate paths (on case-insensitive file systems also
+        # if they only differ in case); turn relative paths into absolute
+        # paths.
+        dir, dircase = makepath(dir)
+        if not dircase in known_paths:
+            L.append(dir)
+            known_paths.add(dircase)
+    sys.path[:] = L
+    return known_paths
+
+# XXX This should not be part of site.py, since it is needed even when
+# using the -S option for Python.  See http://www.python.org/sf/586680
+def addbuilddir():
+    """Append ./build/lib.<platform> in case we're running in the build dir
+    (especially for Guido :-)"""
+    from sysconfig import get_platform
+    s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
+    if hasattr(sys, 'gettotalrefcount'):
+        s += '-pydebug'
+    s = os.path.join(os.path.dirname(sys.path.pop()), s)
+    sys.path.append(s)
+
+
+def _init_pathinfo():
+    """Return a set containing all existing directory entries from sys.path"""
+    d = set()
+    for dir in sys.path:
+        try:
+            if os.path.isdir(dir):
+                dir, dircase = makepath(dir)
+                d.add(dircase)
+        except TypeError:
+            continue
+    return d
+
+
+def addpackage(sitedir, name, known_paths):
+    """Process a .pth file within the site-packages directory:
+       For each line in the file, either combine it with sitedir to a path
+       and add that to known_paths, or execute it if it starts with 'import '.
+    """
+    if known_paths is None:
+        _init_pathinfo()
+        reset = 1
+    else:
+        reset = 0
+    fullname = os.path.join(sitedir, name)
+    try:
+        f = open(fullname, "rU")
+    except IOError:
+        return
+    with f:
+        for line in f:
+            if line.startswith("#"):
+                continue
+            if line.startswith(("import ", "import\t")):
+                exec line
+                continue
+            line = line.rstrip()
+            dir, dircase = makepath(sitedir, line)
+            if not dircase in known_paths and os.path.exists(dir):
+                sys.path.append(dir)
+                known_paths.add(dircase)
+    if reset:
+        known_paths = None
+    return known_paths
+
+
+def addsitedir(sitedir, known_paths=None):
+    """Add 'sitedir' argument to sys.path if missing and handle .pth files in
+    'sitedir'"""
+    if known_paths is None:
+        known_paths = _init_pathinfo()
+        reset = 1
+    else:
+        reset = 0
+    sitedir, sitedircase = makepath(sitedir)
+    if not sitedircase in known_paths:
+        sys.path.append(sitedir)        # Add path component
+    try:
+        names = os.listdir(sitedir)
+    except os.error:
+        return
+    dotpth = os.extsep + "pth"
+    names = [name for name in names if name.endswith(dotpth)]
+    for name in sorted(names):
+        addpackage(sitedir, name, known_paths)
+    if reset:
+        known_paths = None
+    return known_paths
+
+
+def check_enableusersite():
+    """Check if user site directory is safe for inclusion
+
+    The function tests for the command line flag (including environment var),
+    process uid/gid equal to effective uid/gid.
+
+    None: Disabled for security reasons
+    False: Disabled by user (command line option)
+    True: Safe and enabled
+    """
+    if sys.flags.no_user_site:
+        return False
+
+    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
+        # check process uid == effective uid
+        if os.geteuid() != os.getuid():
+            return None
+    if hasattr(os, "getgid") and hasattr(os, "getegid"):
+        # check process gid == effective gid
+        if os.getegid() != os.getgid():
+            return None
+
+    return True
+
+def getuserbase():
+    """Returns the `user base` directory path.
+
+    The `user base` directory can be used to store data. If the global
+    variable ``USER_BASE`` is not initialized yet, this function will also set
+    it.
+    """
+    global USER_BASE
+    if USER_BASE is not None:
+        return USER_BASE
+    from sysconfig import get_config_var
+    USER_BASE = get_config_var('userbase')
+    return USER_BASE
+
+def getusersitepackages():
+    """Returns the user-specific site-packages directory path.
+
+    If the global variable ``USER_SITE`` is not initialized yet, this
+    function will also set it.
+    """
+    global USER_SITE
+    user_base = getuserbase() # this will also set USER_BASE
+
+    if USER_SITE is not None:
+        return USER_SITE
+
+    from sysconfig import get_path
+    import os
+
+    if sys.platform == 'darwin':
+        from sysconfig import get_config_var
+        if get_config_var('PYTHONFRAMEWORK'):
+            USER_SITE = get_path('purelib', 'osx_framework_user')
+            return USER_SITE
+
+    USER_SITE = get_path('purelib', '%s_user' % os.name)
+    return USER_SITE
+
+def addusersitepackages(known_paths):
+    """Add a per user site-package to sys.path
+
+    Each user has its own python directory with site-packages in the
+    home directory.
+    """
+    # get the per user site-package path
+    # this call will also make sure USER_BASE and USER_SITE are set
+    user_site = getusersitepackages()
+
+    if ENABLE_USER_SITE and os.path.isdir(user_site):
+        addsitedir(user_site, known_paths)
+    return known_paths
+
+def getsitepackages():
+    """Returns a list containing all global site-packages directories
+    (and possibly site-python).
+
+    For each directory present in the global ``PREFIXES``, this function
+    will find its `site-packages` subdirectory depending on the system
+    environment, and will return a list of full paths.
+    """
+    # pypy specific logic
+    if hasattr(sys, 'pypy_version_info') and hasattr(sys, 'prefix'):
+        from distutils.sysconfig import get_python_lib
+        sitedir = get_python_lib(standard_lib=False)
+        return [sitedir]
+
+    # cpython logic
+    sitepackages = []
+    seen = set()
+
+    for prefix in PREFIXES:
+        if not prefix or prefix in seen:
+            continue
+        seen.add(prefix)
+
+        if sys.platform in ('os2emx', 'riscos'):
+            sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
+        elif os.sep == '/':
+            sitepackages.append(os.path.join(prefix, "lib",
+                                        "python" + sys.version[:3],
+                                        "site-packages"))
+            sitepackages.append(os.path.join(prefix, "lib", "site-python"))
+        else:
+            sitepackages.append(prefix)
+            sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
+        if sys.platform == "darwin":
+            # for framework builds *only* we add the standard Apple
+            # locations.
+            from sysconfig import get_config_var
+            framework = get_config_var("PYTHONFRAMEWORK")
+            if framework and "/%s.framework/"%(framework,) in prefix:
+                sitepackages.append(
+                        os.path.join("/Library", framework,
+                            sys.version[:3], "site-packages"))
+    return sitepackages
+
+def addsitepackages(known_paths):
+    """Add site-packages (and possibly site-python) to sys.path"""
+    for sitedir in getsitepackages():
+        if os.path.isdir(sitedir):
+            addsitedir(sitedir, known_paths)
+
+    return known_paths
+
+def setBEGINLIBPATH():
+    """The OS/2 EMX port has optional extension modules that do double duty
+    as DLLs (and must use the .DLL file extension) for other extensions.
+    The library search path needs to be amended so these will be found
+    during module import.  Use BEGINLIBPATH so that these are at the start
+    of the library search path.
+
+    """
+    dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
+    libpath = os.environ['BEGINLIBPATH'].split(';')
+    if libpath[-1]:
+        libpath.append(dllpath)
+    else:
+        libpath[-1] = dllpath
+    os.environ['BEGINLIBPATH'] = ';'.join(libpath)
+
+
+def setquit():
+    """Define new builtins 'quit' and 'exit'.
+
+    These are objects which make the interpreter exit when called.
+    The repr of each object contains a hint at how it works.
+
+    """
+    if os.sep == ':':
+        eof = 'Cmd-Q'
+    elif os.sep == '\\':
+        eof = 'Ctrl-Z plus Return'
+    else:
+        eof = 'Ctrl-D (i.e. EOF)'
+
+    class Quitter(object):
+        def __init__(self, name):
+            self.name = name
+        def __repr__(self):
+            return 'Use %s() or %s to exit' % (self.name, eof)
+        def __call__(self, code=None):
+            # Shells like IDLE catch the SystemExit, but listen when their
+            # stdin wrapper is closed.
+            try:
+                sys.stdin.close()
+            except:
+                pass
+            raise SystemExit(code)
+    __builtin__.quit = Quitter('quit')
+    __builtin__.exit = Quitter('exit')
+
+
+class _Printer(object):
+    """interactive prompt objects for printing the license text, a list of
+    contributors and the copyright notice."""
+
+    MAXLINES = 23
+
+    def __init__(self, name, data, files=(), dirs=()):
+        self.__name = name
+        self.__data = data
+        self.__files = files
+        self.__dirs = dirs
+        self.__lines = None
+
+    def __setup(self):
+        if self.__lines:
+            return
+        data = None
+        for dir in self.__dirs:
+            for filename in self.__files:
+                filename = os.path.join(dir, filename)
+                try:
+                    fp = file(filename, "rU")
+                    data = fp.read()
+                    fp.close()
+                    break
+                except IOError:
+                    pass
+            if data:
+                break
+        if not data:
+            data = self.__data
+        self.__lines = data.split('\n')
+        self.__linecnt = len(self.__lines)
+
+    def __repr__(self):
+        self.__setup()
+        if len(self.__lines) <= self.MAXLINES:
+            return "\n".join(self.__lines)
+        else:
+            return "Type %s() to see the full %s text" % ((self.__name,)*2)
+
+    def __call__(self):
+        self.__setup()
+        prompt = 'Hit Return for more, or q (and Return) to quit: '
+        lineno = 0
+        while 1:
+            try:
+                for i in range(lineno, lineno + self.MAXLINES):
+                    print self.__lines[i]
+            except IndexError:
+                break
+            else:
+                lineno += self.MAXLINES
+                key = None
+                while key is None:
+                    key = raw_input(prompt)
+                    if key not in ('', 'q'):
+                        key = None
+                if key == 'q':
+                    break
+
+##def setcopyright():
+##    """Set 'copyright' and 'credits' in __builtin__"""
+##    __builtin__.copyright = _Printer("copyright", sys.copyright)
+##    if sys.platform[:4] == 'java':
+##        __builtin__.credits = _Printer(
+##            "credits",
+##            "Jython is maintained by the Jython developers (www.jython.org).")
+##    else:
+##        __builtin__.credits = _Printer("credits", """\
+##    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
+##    for supporting Python development.  See www.python.org for more information.""")
+##    here = os.path.dirname(os.__file__)
+##    __builtin__.license = _Printer(
+##        "license", "See http://www.python.org/%.3s/license.html" % sys.version,
+##        ["LICENSE.txt", "LICENSE"],
+##        [os.path.join(here, os.pardir), here, os.curdir])
+
+def setcopyright():
+    # XXX this is the PyPy-specific version.  Should be unified with the above.
+    __builtin__.copyright = _Printer("copyright", sys.copyright)
+    __builtin__.credits = _Printer(
+        "credits",
+        "PyPy is maintained by the PyPy developers: http://codespeak.net/pypy")
+    __builtin__.license = _Printer(
+        "license",
+        "See http://codespeak.net/svn/pypy/dist/LICENSE")
+
+
+
+class _Helper(object):
+    """Define the builtin 'help'.
+    This is a wrapper around pydoc.help (with a twist).
+
+    """
+
+    def __repr__(self):
+        return "Type help() for interactive help, " \
+               "or help(object) for help about object."
+    def __call__(self, *args, **kwds):
+        import pydoc
+        return pydoc.help(*args, **kwds)
+
+def sethelper():
+    __builtin__.help = _Helper()
+
+def aliasmbcs():
+    """On Windows, some default encodings are not provided by Python,
+    while they are always available as "mbcs" in each locale. Make
+    them usable by aliasing to "mbcs" in such a case."""
+    if sys.platform == 'win32':
+        import locale, codecs
+        enc = locale.getdefaultlocale()[1]
+        if enc is not None and enc.startswith('cp'):            # "cp***" ?
+            try:
+                codecs.lookup(enc)
+            except LookupError:
+                import encodings
+                encodings._cache[enc] = encodings._unknown
+                encodings.aliases.aliases[enc] = 'mbcs'
+
+def setencoding():
+    """Set the string encoding used by the Unicode implementation.  The
+    default is 'ascii', but if you're willing to experiment, you can
+    change this."""
+    encoding = "ascii" # Default value set by _PyUnicode_Init()
+    if 0:
+        # Enable to support locale aware default string encodings.
+        import locale
+        loc = locale.getdefaultlocale()
+        if loc[1]:
+            encoding = loc[1]
+    if 0:
+        # Enable to switch off string to Unicode coercion and implicit
+        # Unicode to string conversion.
+        encoding = "undefined"
+    if encoding != "ascii":
+        # On Non-Unicode builds this will raise an AttributeError...
+        sys.setdefaultencoding(encoding) # Needs Python Unicode build !
+
+
+def execsitecustomize():
+    """Run custom site specific code, if available."""
+    try:
+        import sitecustomize
+    except ImportError:
+        pass
+    except Exception:
+        if sys.flags.verbose:
+            sys.excepthook(*sys.exc_info())
+        else:
+            print >>sys.stderr, \
+                "'import sitecustomize' failed; use -v for traceback"
+
+
+def execusercustomize():
+    """Run custom user specific code, if available."""
+    try:
+        import usercustomize
+    except ImportError:
+        pass
+    except Exception:
+        if sys.flags.verbose:
+            sys.excepthook(*sys.exc_info())
+        else:
+            print>>sys.stderr, \
+                "'import usercustomize' failed; use -v for traceback"
+
+
+def main():
+    global ENABLE_USER_SITE
+
+    abs__file__()
+    known_paths = removeduppaths()
+    if (os.name == "posix" and sys.path and
+        os.path.basename(sys.path[-1]) == "Modules"):
+        addbuilddir()
+    if ENABLE_USER_SITE is None:
+        ENABLE_USER_SITE = check_enableusersite()
+    known_paths = addusersitepackages(known_paths)
+    known_paths = addsitepackages(known_paths)
+    if sys.platform == 'os2emx':
+        setBEGINLIBPATH()
+    setquit()
+    setcopyright()
+    sethelper()
+    aliasmbcs()
+    setencoding()
+    execsitecustomize()
+    if ENABLE_USER_SITE:
+        execusercustomize()
+    # Remove sys.setdefaultencoding() so that users cannot change the
+    # encoding after initialization.  The test for presence is needed when
+    # this module is run as a script, because this code is executed twice.
+    if hasattr(sys, "setdefaultencoding"):
+        del sys.setdefaultencoding
+
+main()
+
+def _script():
+    help = """\
+    %s [--user-base] [--user-site]
+
+    Without arguments print some useful information
+    With arguments print the value of USER_BASE and/or USER_SITE separated
+    by '%s'.
+
+    Exit codes with --user-base or --user-site:
+      0 - user site directory is enabled
+      1 - user site directory is disabled by user
+      2 - uses site directory is disabled by super user
+          or for security reasons
+     >2 - unknown error
+    """
+    args = sys.argv[1:]
+    if not args:
+        print "sys.path = ["
+        for dir in sys.path:
+            print "    %r," % (dir,)
+        print "]"
+        print "USER_BASE: %r (%s)" % (USER_BASE,
+            "exists" if os.path.isdir(USER_BASE) else "doesn't exist")
+        print "USER_SITE: %r (%s)" % (USER_SITE,
+            "exists" if os.path.isdir(USER_SITE) else "doesn't exist")
+        print "ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE
+        sys.exit(0)
+
+    buffer = []
+    if '--user-base' in args:
+        buffer.append(USER_BASE)
+    if '--user-site' in args:
+        buffer.append(USER_SITE)
+
+    if buffer:
+        print os.pathsep.join(buffer)
+        if ENABLE_USER_SITE:
+            sys.exit(0)
+        elif ENABLE_USER_SITE is False:
+            sys.exit(1)
+        elif ENABLE_USER_SITE is None:
+            sys.exit(2)
+        else:
+            sys.exit(3)
+    else:
+        import textwrap
+        print textwrap.dedent(help % (sys.argv[0], os.pathsep))
+        sys.exit(10)
+
+if __name__ == '__main__':
+    _script()

lib-python/modified-2.7.0/test/test_builtin.py

+# Python test set -- built-in functions
+
+import platform
+import unittest
+from test.test_support import fcmp, have_unicode, TESTFN, unlink, \
+                              run_unittest, check_py3k_warnings, \
+                              check_impl_detail
+import warnings
+from operator import neg
+
+import sys, cStringIO, random, UserDict
+
+# count the number of test runs.
+# used to skip running test_execfile() multiple times
+# and to create unique strings to intern in test_intern()
+numruns = 0
+
+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
+
+
+class TestFailingBool:
+    def __nonzero__(self):
+        raise RuntimeError
+
+class TestFailingIter:
+    def __iter__(self):
+        raise RuntimeError
+
+class BuiltinTest(unittest.TestCase):
+
+    def test_import(self):
+        __import__('sys')
+        __import__('time')
+        __import__('string')
+        __import__(name='sys')
+        __import__(name='time', level=0)
+        self.assertRaises(ImportError, __import__, 'spamspam')
+        self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
+        self.assertRaises(ValueError, __import__, '')
+        self.assertRaises(TypeError, __import__, 'sys', name='sys')
+
+    def test_abs(self):
+        # int
+        self.assertEqual(abs(0), 0)
+        self.assertEqual(abs(1234), 1234)
+        self.assertEqual(abs(-1234), 1234)
+        self.assertTrue(abs(-sys.maxint-1) > 0)
+        # float
+        self.assertEqual(abs(0.0), 0.0)
+        self.assertEqual(abs(3.14), 3.14)
+        self.assertEqual(abs(-3.14), 3.14)
+        # long
+        self.assertEqual(abs(0L), 0L)
+        self.assertEqual(abs(1234L), 1234L)
+        self.assertEqual(abs(-1234L), 1234L)
+        # str
+        self.assertRaises(TypeError, abs, 'a')
+        # bool
+        self.assertEqual(abs(True), 1)
+        self.assertEqual(abs(False), 0)
+        # other
+        self.assertRaises(TypeError, abs)
+        self.assertRaises(TypeError, abs, None)
+        class AbsClass(object):
+            def __abs__(self):
+                return -5
+        self.assertEqual(abs(AbsClass()), -5)
+
+    def test_all(self):
+        self.assertEqual(all([2, 4, 6]), True)
+        self.assertEqual(all([2, None, 6]), False)
+        self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
+        self.assertRaises(RuntimeError, all, TestFailingIter())
+        self.assertRaises(TypeError, all, 10)               # Non-iterable
+        self.assertRaises(TypeError, all)                   # No args
+        self.assertRaises(TypeError, all, [2, 4, 6], [])    # Too many args
+        self.assertEqual(all([]), True)                     # Empty iterator
+        S = [50, 60]
+        self.assertEqual(all(x > 42 for x in S), True)
+        S = [50, 40, 60]
+        self.assertEqual(all(x > 42 for x in S), False)
+
+    def test_any(self):
+        self.assertEqual(any([None, None, None]), False)
+        self.assertEqual(any([None, 4, None]), True)
+        self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
+        self.assertRaises(RuntimeError, all, TestFailingIter())
+        self.assertRaises(TypeError, any, 10)               # Non-iterable
+        self.assertRaises(TypeError, any)                   # No args
+        self.assertRaises(TypeError, any, [2, 4, 6], [])    # Too many args
+        self.assertEqual(any([]), False)                    # Empty iterator
+        S = [40, 60, 30]
+        self.assertEqual(any(x > 42 for x in S), True)
+        S = [10, 20, 30]
+        self.assertEqual(any(x > 42 for x in S), False)
+
+    def test_neg(self):
+        x = -sys.maxint-1
+        self.assertTrue(isinstance(x, int))
+        self.assertEqual(-x, sys.maxint+1)
+
+    def test_apply(self):
+        def f0(*args):
+            self.assertEqual(args, ())
+        def f1(a1):
+            self.assertEqual(a1, 1)
+        def f2(a1, a2):
+            self.assertEqual(a1, 1)
+            self.assertEqual(a2, 2)
+        def f3(a1, a2, a3):
+            self.assertEqual(a1, 1)
+            self.assertEqual(a2, 2)
+            self.assertEqual(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,), {})
+        self.assertRaises(TypeError, apply, id, (1,), {"foo": 1})
+        self.assertRaises(TypeError, apply)
+        self.assertRaises(TypeError, apply, id, 42)
+        self.assertRaises(TypeError, apply, id, (42,), 42)
+
+    def test_callable(self):
+        self.assertTrue(callable(len))
+        self.assertFalse(callable("a"))
+        self.assertTrue(callable(callable))
+        self.assertTrue(callable(lambda x, y: x + y))
+        self.assertFalse(callable(__builtins__))
+        def f(): pass
+        self.assertTrue(callable(f))
+
+        class Classic:
+            def meth(self): pass
+        self.assertTrue(callable(Classic))
+        c = Classic()
+        self.assertTrue(callable(c.meth))
+        self.assertFalse(callable(c))
+
+        class NewStyle(object):
+            def meth(self): pass
+        self.assertTrue(callable(NewStyle))
+        n = NewStyle()
+        self.assertTrue(callable(n.meth))
+        self.assertFalse(callable(n))
+
+        # Classic and new-style classes evaluate __call__() differently
+        c.__call__ = None
+        self.assertTrue(callable(c))
+        del c.__call__
+        self.assertFalse(callable(c))
+        n.__call__ = None
+        self.assertFalse(callable(n))
+        del n.__call__
+        self.assertFalse(callable(n))
+
+        class N2(object):
+            def __call__(self): pass
+        n2 = N2()
+        self.assertTrue(callable(n2))
+        class N3(N2): pass
+        n3 = N3()
+        self.assertTrue(callable(n3))
+
+    def test_chr(self):
+        self.assertEqual(chr(32), ' ')
+        self.assertEqual(chr(65), 'A')
+        self.assertEqual(chr(97), 'a')
+        self.assertEqual(chr(0xff), '\xff')
+        self.assertRaises(ValueError, chr, 256)
+        self.assertRaises(TypeError, chr)
+
+    def test_cmp(self):
+        self.assertEqual(cmp(-1, 1), -1)
+        self.assertEqual(cmp(1, -1), 1)
+        self.assertEqual(cmp(1, 1), 0)
+        # verify that circular objects are not handled
+        a = []; a.append(a)
+        b = []; b.append(b)
+        from UserList import UserList
+        c = UserList(); c.append(c)
+        self.assertRaises(RuntimeError, cmp, a, b)
+        self.assertRaises(RuntimeError, cmp, b, c)
+        self.assertRaises(RuntimeError, cmp, c, a)
+        self.assertRaises(RuntimeError, cmp, a, c)
+       # okay, now break the cycles
+        a.pop(); b.pop(); c.pop()
+        self.assertRaises(TypeError, cmp)
+
+    def test_coerce(self):
+        self.assertTrue(not fcmp(coerce(1, 1.1), (1.0, 1.1)))
+        self.assertEqual(coerce(1, 1L), (1L, 1L))
+        self.assertTrue(not fcmp(coerce(1L, 1.1), (1.0, 1.1)))
+        self.assertRaises(TypeError, coerce)
+        class BadNumber:
+            def __coerce__(self, other):
+                raise ValueError
+        self.assertRaises(ValueError, coerce, 42, BadNumber())
+        self.assertRaises(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')
+        compile(source='pass', filename='?', mode='exec')
+        compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
+        compile('pass', '?', dont_inherit=1, mode='exec')
+        self.assertRaises(TypeError, compile)
+        self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
+        self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
+        if check_impl_detail(cpython=True):
+            self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
+        self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
+                          mode='eval', source='0', filename='tmp')
+        if have_unicode:
+            compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
+            if check_impl_detail(cpython=True):
+                self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
+            self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
+
+
+    def test_delattr(self):
+        import sys
+        sys.spam = 1
+        delattr(sys, 'spam')
+        self.assertRaises(TypeError, delattr)
+
+    def test_dir(self):
+        # dir(wrong number of arguments)
+        self.assertRaises(TypeError, dir, 42, 42)
+
+        # dir() - local scope
+        local_var = 1
+        self.assertIn('local_var', dir())
+
+        # dir(module)
+        import sys
+        self.assertIn('exit', dir(sys))
+
+        # dir(module_with_invalid__dict__)
+        import types
+        class Foo(types.ModuleType):
+            __dict__ = 8
+        f = Foo("foo")
+        self.assertRaises(TypeError, dir, f)
+
+        # dir(type)
+        self.assertIn("strip", dir(str))
+        self.assertNotIn("__mro__", dir(str))
+
+        # dir(obj)
+        class Foo(object):
+            def __init__(self):
+                self.x = 7
+                self.y = 8
+                self.z = 9
+        f = Foo()
+        self.assertIn("y", dir(f))
+
+        # dir(obj_no__dict__)
+        class Foo(object):
+            __slots__ = []
+        f = Foo()
+        self.assertIn("__repr__", dir(f))
+
+        # dir(obj_no__class__with__dict__)
+        # (an ugly trick to cause getattr(f, "__class__") to fail)
+        class Foo(object):
+            __slots__ = ["__class__", "__dict__"]
+            def __init__(self):
+                self.bar = "wow"
+        f = Foo()
+        self.assertNotIn("__repr__", dir(f))
+        self.assertIn("bar", dir(f))
+
+        # dir(obj_using __dir__)
+        class Foo(object):
+            def __dir__(self):
+                return ["kan", "ga", "roo"]
+        f = Foo()
+        self.assertTrue(dir(f) == ["ga", "kan", "roo"])
+
+        # dir(obj__dir__not_list)
+        class Foo(object):
+            def __dir__(self):
+                return 7
+        f = Foo()
+        self.assertRaises(TypeError, dir, f)
+
+    def test_divmod(self):
+        self.assertEqual(divmod(12, 7), (1, 5))
+        self.assertEqual(divmod(-12, 7), (-2, 2))
+        self.assertEqual(divmod(12, -7), (-2, -2))
+        self.assertEqual(divmod(-12, -7), (1, -5))
+
+        self.assertEqual(divmod(12L, 7L), (1L, 5L))
+        self.assertEqual(divmod(-12L, 7L), (-2L, 2L))
+        self.assertEqual(divmod(12L, -7L), (-2L, -2L))
+        self.assertEqual(divmod(-12L, -7L), (1L, -5L))
+
+        self.assertEqual(divmod(12, 7L), (1, 5L))
+        self.assertEqual(divmod(-12, 7L), (-2, 2L))
+        self.assertEqual(divmod(12L, -7), (-2L, -2))
+        self.assertEqual(divmod(-12L, -7), (1L, -5))
+
+        self.assertEqual(divmod(-sys.maxint-1, -1),
+                         (sys.maxint+1, 0))
+
+        self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
+        self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
+        self.assertTrue(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
+        self.assertTrue(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
+
+        self.assertRaises(TypeError, divmod)
+
+    def test_eval(self):
+        self.assertEqual(eval('1+1'), 2)
+        self.assertEqual(eval(' 1+1\n'), 2)
+        globals = {'a': 1, '