Commits

mattip committed 8c87e0e Merge

merge default into branch about to be closed

  • Participants
  • Parent commits a254cb0, 8b94976
  • Branches numpypy.float16

Comments (0)

Files changed (218)

-License for files in the pypy/ directory 
-==================================================
+License
+=======
 
 Except when otherwise stated (look for LICENSE files in directories or
 information at the beginning of each file) all software and
-documentation in the 'pypy' directories is licensed as follows: 
+documentation in the 'pypy', 'ctype_configure', 'dotviewer', 'demo',
+and 'lib_pypy' directories is licensed as follows: 
 
     The MIT License
 

File lib-python/2.7/distutils/command/build_ext.py

         shared extension.  On most platforms, this is just 'ext.libraries';
         on Windows and OS/2, we add the Python library (eg. python20.dll).
         """
+        # For PyPy, we must not add any such Python library, on any platform
+        if "__pypy__" in sys.builtin_module_names:
+            return ext.libraries
         # The python library is always needed on Windows.
         if sys.platform == "win32":
             template = "python%d%d"

File lib-python/conftest.py

 from pypy.interpreter.main import run_string, run_file
 
 # the following adds command line options as a side effect! 
-from pypy.conftest import gettestobjspace, option as pypy_option 
+from pypy.conftest import option as pypy_option 
 
 from pypy.tool.pytest import appsupport 
 from pypy.tool.pytest.confpath import pypydir, testdir, testresultdir

File lib_pypy/_sqlite3.py

                 self.statement.reset()
                 raise self.connection._get_exception(ret)
 
+            if self.statement.kind == DML:
+                self.statement.reset()
+
             if self.statement.kind == DQL and ret == SQLITE_ROW:
                 self.statement._build_row_cast_map()
                 self.statement._readahead(self)
                 self.statement.item = None
                 self.statement.exhausted = True
 
-            if self.statement.kind == DML:
-                self.statement.reset()
-
             self.rowcount = -1
             if self.statement.kind == DML:
                 self.rowcount = sqlite.sqlite3_changes(self.connection.db)

File pypy/conftest.py

-import py, pytest, sys, os, textwrap, types
-from pypy.interpreter.gateway import app2interp_temp
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.function import Method
-from pypy.tool.pytest import appsupport
-from pypy.tool.option import make_config, make_objspace
-from pypy.config.config import ConflictConfigError
-from inspect import isclass, getmro
-from pypy.tool.udir import udir
-from pypy.tool.autopath import pypydir
-from pypy.tool import leakfinder
+import py, pytest, sys, os, textwrap
+from inspect import isclass
 
 # pytest settings
 rsyncdirs = ['.', '../lib-python', '../lib_pypy', '../demo']
 def pytest_report_header():
     return "pytest-%s from %s" %(pytest.__version__, pytest.__file__)
 
+
+def pytest_addhooks(pluginmanager):
+    from pypy.tool.pytest.plugins import LeakFinder
+    pluginmanager.register(LeakFinder())
+
+
 def pytest_configure(config):
     global option
     option = config.option
         pass
 
 def pytest_funcarg__space(request):
+    from pypy.tool.pytest.objspace import gettestobjspace
     spaceconfig = getattr(request.cls, 'spaceconfig', {})
     return gettestobjspace(**spaceconfig)
 
-_SPACECACHE={}
-def gettestobjspace(name=None, **kwds):
-    """ helper for instantiating and caching space's for testing.
-    """
-    try:
-        config = make_config(option, objspace=name, **kwds)
-    except ConflictConfigError, e:
-        # this exception is typically only raised if a module is not available.
-        # in this case the test should be skipped
-        py.test.skip(str(e))
-    key = config.getkey()
-    try:
-        return _SPACECACHE[key]
-    except KeyError:
-        if getattr(option, 'runappdirect', None):
-            if name not in (None, 'std'):
-                myname = getattr(sys, 'pypy_objspaceclass', '')
-                if not myname.lower().startswith(name):
-                    py.test.skip("cannot runappdirect test: "
-                                 "%s objspace required" % (name,))
-            return TinyObjSpace(**kwds)
-        space = maketestobjspace(config)
-        _SPACECACHE[key] = space
-        return space
-
-def maketestobjspace(config=None):
-    if config is None:
-        config = make_config(option)
-    space = make_objspace(config)
-    space.startup() # Initialize all builtin modules
-    space.setitem(space.builtin.w_dict, space.wrap('AssertionError'),
-                  appsupport.build_pytest_assertion(space))
-    space.setitem(space.builtin.w_dict, space.wrap('raises'),
-                  space.wrap(appsupport.app_raises))
-    space.setitem(space.builtin.w_dict, space.wrap('skip'),
-                  space.wrap(appsupport.app_skip))
-    space.raises_w = appsupport.raises_w.__get__(space)
-    space.eq_w = appsupport.eq_w.__get__(space)
-    return space
-
-class TinyObjSpace(object):
-    def __init__(self, **kwds):
-        import sys
-        info = getattr(sys, 'pypy_translation_info', None)
-        for key, value in kwds.iteritems():
-            if key == 'usemodules':
-                if info is not None:
-                    for modname in value:
-                        ok = info.get('objspace.usemodules.%s' % modname,
-                                      False)
-                        if not ok:
-                            py.test.skip("cannot runappdirect test: "
-                                         "module %r required" % (modname,))
-                else:
-                    if '__pypy__' in value:
-                        py.test.skip("no module __pypy__ on top of CPython")
-                continue
-            if info is None:
-                py.test.skip("cannot runappdirect this test on top of CPython")
-            has = info.get(key, None)
-            if has != value:
-                #print sys.pypy_translation_info
-                py.test.skip("cannot runappdirect test: space needs %s = %s, "\
-                    "while pypy-c was built with %s" % (key, value, has))
-
-        for name in ('int', 'long', 'str', 'unicode', 'None'):
-            setattr(self, 'w_' + name, eval(name))
-
-
-    def appexec(self, args, body):
-        body = body.lstrip()
-        assert body.startswith('(')
-        src = py.code.Source("def anonymous" + body)
-        d = {}
-        exec src.compile() in d
-        return d['anonymous'](*args)
-
-    def wrap(self, obj):
-        return obj
-
-    def unpackiterable(self, itr):
-        return list(itr)
-
-    def is_true(self, obj):
-        return bool(obj)
-
-    def str_w(self, w_str):
-        return w_str
-
-    def newdict(self, module=None):
-        return {}
-
-    def newtuple(self, iterable):
-        return tuple(iterable)
-
-    def newlist(self, iterable):
-        return list(iterable)
-
-    def call_function(self, func, *args, **kwds):
-        return func(*args, **kwds)
-
-    def call_method(self, obj, name, *args, **kwds):
-        return getattr(obj, name)(*args, **kwds)
-
-    def getattr(self, obj, name):
-        return getattr(obj, name)
-
-    def setattr(self, obj, name, value):
-        setattr(obj, name, value)
-
-    def getbuiltinmodule(self, name):
-        return __import__(name)
-
-    def delslice(self, obj, *args):
-        obj.__delslice__(*args)
-
-    def is_w(self, obj1, obj2):
-        return obj1 is obj2
-
-def translation_test_so_skip_if_appdirect():
-    if option.runappdirect:
-        py.test.skip("translation test, skipped for appdirect")
-
-
-class OpErrKeyboardInterrupt(KeyboardInterrupt):
-    pass
-
-def check_keyboard_interrupt(e):
-    # we cannot easily convert w_KeyboardInterrupt to KeyboardInterrupt
-    # in general without a space -- here is an approximation
-    try:
-        if e.w_type.name == 'KeyboardInterrupt':
-            tb = sys.exc_info()[2]
-            raise OpErrKeyboardInterrupt, OpErrKeyboardInterrupt(), tb
-    except AttributeError:
-        pass
 
 #
 # Interfacing/Integrating with py.test's collection process
     def makeitem(self, name, obj):
         if isclass(obj) and self.classnamefilter(name):
             if name.startswith('AppTest'):
+                from pypy.tool.pytest.apptest import AppClassCollector
                 return AppClassCollector(name, parent=self)
             elif name.startswith('ExpectTest'):
                 if self.config.option.rundirect:
                     return py.test.collect.Class(name, parent=self)
+                from pypy.tool.pytest.expecttest import ExpectClassCollector
                 return ExpectClassCollector(name, parent=self)
             # XXX todo
             #elif name.startswith('AppExpectTest'):
             #        return AppClassCollector(name, parent=self)
             #    return AppExpectClassCollector(name, parent=self)
             else:
+                from pypy.tool.pytest.inttest import IntClassCollector
                 return IntClassCollector(name, parent=self)
 
         elif hasattr(obj, 'func_code') and self.funcnamefilter(name):
             if name.startswith('app_test_'):
                 assert not obj.func_code.co_flags & 32, \
                     "generator app level functions? you must be joking"
+                from pypy.tool.pytest.apptest import AppTestFunction
                 return AppTestFunction(name, parent=self)
             elif obj.func_code.co_flags & 32: # generator function
                 return pytest.Generator(name, parent=self)
             else:
+                from pypy.tool.pytest.inttest import IntTestFunction
                 return IntTestFunction(name, parent=self)
 
 def skip_on_missing_buildoption(**ropts):
 
 class LazyObjSpaceGetter(object):
     def __get__(self, obj, cls=None):
+        from pypy.tool.pytest.objspace import gettestobjspace
         space = gettestobjspace()
         if cls:
             cls.space = space
         return space
 
 
-class AppError(Exception):
-
-    def __init__(self, excinfo):
-        self.excinfo = excinfo
-
 def pytest_runtest_setup(__multicall__, item):
     if isinstance(item, py.test.collect.Function):
         appclass = item.getparent(PyPyClassCollector)
         if appclass is not None:
+            # Make cls.space and cls.runappdirect available in tests.
             spaceconfig = getattr(appclass.obj, 'spaceconfig', None)
-            if spaceconfig:
+            if spaceconfig is not None:
+                from pypy.tool.pytest.objspace import gettestobjspace
                 appclass.obj.space = gettestobjspace(**spaceconfig)
+            appclass.obj.runappdirect = option.runappdirect
 
     __multicall__.execute()
 
-    if isinstance(item, py.test.collect.Function):
-        if not getattr(item.obj, 'dont_track_allocations', False):
-            leakfinder.start_tracking_allocations()
-
-def pytest_runtest_call(__multicall__, item):
-    __multicall__.execute()
-    item._success = True
-
 def pytest_runtest_teardown(__multicall__, item):
     __multicall__.execute()
 
-    if isinstance(item, py.test.collect.Function):
-        if (not getattr(item.obj, 'dont_track_allocations', False)
-            and leakfinder.TRACK_ALLOCATIONS):
-            item._pypytest_leaks = leakfinder.stop_tracking_allocations(False)
-        else:            # stop_tracking_allocations() already called
-            item._pypytest_leaks = None
-
-        # check for leaks, but only if the test passed so far
-        if getattr(item, '_success', False) and item._pypytest_leaks:
-            raise leakfinder.MallocMismatch(item._pypytest_leaks)
-
     if 'pygame' in sys.modules:
         assert option.view, ("should not invoke Pygame "
                              "if conftest.option.view is False")
 
-_pygame_imported = False
-
-class IntTestFunction(py.test.collect.Function):
-    def __init__(self, *args, **kwargs):
-        super(IntTestFunction, self).__init__(*args, **kwargs)
-        self.keywords['interplevel'] = True
-
-    def runtest(self):
-        try:
-            super(IntTestFunction, self).runtest()
-        except OperationError, e:
-            check_keyboard_interrupt(e)
-            raise
-        except Exception, e:
-            cls = e.__class__
-            while cls is not Exception:
-                if cls.__name__ == 'DistutilsPlatformError':
-                    from distutils.errors import DistutilsPlatformError
-                    if isinstance(e, DistutilsPlatformError):
-                        py.test.skip('%s: %s' % (e.__class__.__name__, e))
-                cls = cls.__bases__[0]
-            raise
-
-class AppTestFunction(py.test.collect.Function):
-    def __init__(self, *args, **kwargs):
-        super(AppTestFunction, self).__init__(*args, **kwargs)
-        self.keywords['applevel'] = True
-
-    def _prunetraceback(self, traceback):
-        return traceback
-
-    def execute_appex(self, space, target, *args):
-        try:
-            target(*args)
-        except OperationError, e:
-            tb = sys.exc_info()[2]
-            if e.match(space, space.w_KeyboardInterrupt):
-                raise OpErrKeyboardInterrupt, OpErrKeyboardInterrupt(), tb
-            appexcinfo = appsupport.AppExceptionInfo(space, e)
-            if appexcinfo.traceback:
-                raise AppError, AppError(appexcinfo), tb
-            raise
-
-    def runtest(self):
-        target = self.obj
-        if self.config.option.runappdirect:
-            return target()
-        space = gettestobjspace()
-        filename = self._getdynfilename(target)
-        func = app2interp_temp(target, filename=filename)
-        print "executing", func
-        self.execute_appex(space, func, space)
-
-    def repr_failure(self, excinfo):
-        if excinfo.errisinstance(AppError):
-            excinfo = excinfo.value.excinfo
-        return super(AppTestFunction, self).repr_failure(excinfo)
-
-    def _getdynfilename(self, func):
-        code = getattr(func, 'im_func', func).func_code
-        return "[%s:%s]" % (code.co_filename, code.co_firstlineno)
-
-class AppTestMethod(AppTestFunction):
-    def setup(self):
-        super(AppTestMethod, self).setup()
-        instance = self.parent.obj
-        w_instance = self.parent.w_instance
-        space = instance.space
-        for name in dir(instance):
-            if name.startswith('w_'):
-                if self.config.option.runappdirect:
-                    setattr(instance, name[2:], getattr(instance, name))
-                else:
-                    obj = getattr(instance, name)
-                    if isinstance(obj, types.MethodType):
-                        source = py.std.inspect.getsource(obj).lstrip()
-                        w_func = space.appexec([], textwrap.dedent("""
-                        ():
-                            %s
-                            return %s
-                        """) % (source, name))
-                        w_obj = Method(space, w_func, w_instance, space.w_None)
-                    else:
-                        w_obj = obj
-                    space.setattr(w_instance, space.wrap(name[2:]), w_obj)
-
-    def runtest(self):
-        target = self.obj
-        if self.config.option.runappdirect:
-            return target()
-        space = target.im_self.space
-        filename = self._getdynfilename(target)
-        func = app2interp_temp(target.im_func, filename=filename)
-        w_instance = self.parent.w_instance
-        self.execute_appex(space, func, space, w_instance)
 
 class PyPyClassCollector(py.test.collect.Class):
+    # All pypy Test classes have a "space" member.
     def setup(self):
         cls = self.obj
         if not hasattr(cls, 'spaceconfig'):
             assert hasattr(cls, 'space') # set by pytest_runtest_setup
         super(PyPyClassCollector, self).setup()
 
-class IntInstanceCollector(py.test.collect.Instance):
-    Function = IntTestFunction
-
-class IntClassCollector(PyPyClassCollector):
-    Instance = IntInstanceCollector
-
-    def _haskeyword(self, keyword):
-        return keyword == 'interplevel' or \
-               super(IntClassCollector, self)._haskeyword(keyword)
-
-    def _keywords(self):
-        return super(IntClassCollector, self)._keywords() + ['interplevel']
-
-class AppClassInstance(py.test.collect.Instance):
-    Function = AppTestMethod
-
-    def setup(self):
-        super(AppClassInstance, self).setup()
-        instance = self.obj
-        space = instance.space
-        w_class = self.parent.w_class
-        if self.config.option.runappdirect:
-            self.w_instance = instance
-        else:
-            self.w_instance = space.call_function(w_class)
-
-class AppClassCollector(PyPyClassCollector):
-    Instance = AppClassInstance
-
-    def _haskeyword(self, keyword):
-        return keyword == 'applevel' or \
-               super(AppClassCollector, self)._haskeyword(keyword)
-
-    def _keywords(self):
-        return super(AppClassCollector, self)._keywords() + ['applevel']
-
-    def setup(self):
-        super(AppClassCollector, self).setup()
-        cls = self.obj
-        #
-        # <hack>
-        for name in dir(cls):
-            if name.startswith('test_'):
-                func = getattr(cls, name, None)
-                code = getattr(func, 'func_code', None)
-                if code and code.co_flags & 32:
-                    raise AssertionError("unsupported: %r is a generator "
-                                         "app-level test method" % (name,))
-        # </hack>
-        #
-        space = cls.space
-        clsname = cls.__name__
-        if self.config.option.runappdirect:
-            w_class = cls
-        else:
-            w_class = space.call_function(space.w_type,
-                                          space.wrap(clsname),
-                                          space.newtuple([]),
-                                          space.newdict())
-        self.w_class = w_class
-
-class ExpectTestMethod(py.test.collect.Function):
-    def safe_name(target):
-        s = "_".join(target)
-        s = s.replace("()", "paren")
-        s = s.replace(".py", "")
-        s = s.replace(".", "_")
-        s = s.replace(os.sep, "_")
-        return s
-
-    safe_name = staticmethod(safe_name)
-
-    def safe_filename(self):
-        name = self.safe_name(self.listnames())
-        num = 0
-        while udir.join(name + '.py').check():
-            num += 1
-            name = self.safe_name(self.listnames()) + "_" + str(num)
-        return name + '.py'
-
-    def _spawn(self, *args, **kwds):
-        import pexpect
-        kwds.setdefault('timeout', 600)
-        child = pexpect.spawn(*args, **kwds)
-        child.logfile = sys.stdout
-        return child
-
-    def spawn(self, argv):
-        return self._spawn(sys.executable, argv)
-
-    def runtest(self):
-        target = self.obj
-        import pexpect
-        source = py.code.Source(target)[1:].deindent()
-        filename = self.safe_filename()
-        source.lines = ['import sys',
-                      'sys.path.insert(0, %s)' % repr(os.path.dirname(pypydir))
-                        ] + source.lines
-        source.lines.append('print "%s ok!"' % filename)
-        f = udir.join(filename)
-        f.write(source)
-        # run target in the guarded environment
-        child = self.spawn([str(f)])
-        import re
-        child.expect(re.escape(filename + " ok!"))
-
-class ExpectClassInstance(py.test.collect.Instance):
-    Function = ExpectTestMethod
-
-class ExpectClassCollector(py.test.collect.Class):
-    Instance = ExpectClassInstance
-
-    def setup(self):
-        super(ExpectClassCollector, self).setup()
-        try:
-            import pexpect
-        except ImportError:
-            py.test.skip("pexpect not found")
-
 
 def pytest_ignore_collect(path):
     return path.check(link=1)

File pypy/doc/sandbox.rst

 this case we also generate systematic run-time checks against buffer
 overflows.
 
+.. warning::
+  
+  The hard work from the PyPy side is done --- you get a fully secure
+  version.  What is only experimental and unpolished is the library to
+  use this sandboxed PyPy from a regular Python interpreter (CPython, or
+  an unsandboxed PyPy).  Contributions welcome.
+
 
 Overview
 --------

File pypy/doc/whatsnew-head.rst

 .. this is the revision of the last merge from default to release-1.9.x
 .. startrev: 8d567513d04d
 
+Fixed the performance of gc.get_referrers()
+
 .. branch: default
 .. branch: app_main-refactor
 .. branch: win-ordinal
 See doc/cppyy.rst for full details and functionality.
 .. branch: nupypy-axis-arg-check
 Check that axis arg is valid in _numpypy
+.. branch:less-gettestobjspace
+.. branch: move-apptest-support
 
 .. branch: iterator-in-rpython
 .. branch: numpypy_count_nonzero

File pypy/interpreter/argument.py

File contents unchanged.

File pypy/interpreter/error.py

             raise operationerrfmt(space.w_TypeError, msg, typename)
         return w_type
 
-    def write_unraisable(self, space, where, w_object=None):
+    def write_unraisable(self, space, where, w_object=None,
+                         with_traceback=False):
         if w_object is None:
             objrepr = ''
         else:
                 objrepr = space.str_w(space.repr(w_object))
             except OperationError:
                 objrepr = '?'
-        msg = 'Exception %s in %s%s ignored\n' % (
-            self.errorstr(space, use_repr=True), where, objrepr)
+        #
         try:
-            space.call_method(space.sys.get('stderr'), 'write', space.wrap(msg))
+            if with_traceback:
+                w_t = self.w_type
+                w_v = self.get_w_value(space)
+                w_tb = space.wrap(self.get_traceback())
+                space.appexec([space.wrap(where),
+                               space.wrap(objrepr),
+                               w_t, w_v, w_tb],
+                """(where, objrepr, t, v, tb):
+                    import sys, traceback
+                    sys.stderr.write('From %s%s:\\n' % (where, objrepr))
+                    traceback.print_exception(t, v, tb)
+                """)
+            else:
+                msg = 'Exception %s in %s%s ignored\n' % (
+                    self.errorstr(space, use_repr=True), where, objrepr)
+                space.call_method(space.sys.get('stderr'), 'write',
+                                  space.wrap(msg))
         except OperationError:
             pass   # ignored
 

File pypy/interpreter/nestedscope.py

     def MAKE_CLOSURE(self, numdefaults, next_instr):
         w_codeobj = self.popvalue()
         codeobj = self.space.interp_w(pycode.PyCode, w_codeobj)
-        if codeobj.magic >= 0xa0df281:    # CPython 2.5 AST branch merge
-            w_freevarstuple = self.popvalue()
-            freevars = [self.space.interp_w(Cell, cell)
-                        for cell in self.space.fixedview(w_freevarstuple)]
-        else:
-            n = len(codeobj.co_freevars)
-            freevars = [None] * n
-            while True:
-                n -= 1
-                if n < 0:
-                    break
-                freevars[n] = self.space.interp_w(Cell, self.popvalue())
+        w_freevarstuple = self.popvalue()
+        freevars = [self.space.interp_w(Cell, cell)
+                    for cell in self.space.fixedview(w_freevarstuple)]
         defaultarguments = self.popvalues(numdefaults)
         fn = function.Function(self.space, codeobj, self.w_globals,
                                defaultarguments, freevars)

File pypy/interpreter/pyframe.py

File contents unchanged.

File pypy/interpreter/test/test_appinterp.py

         per-instance attribute, holding a fresh copy of the dictionary.
         """
         from pypy.interpreter.mixedmodule import MixedModule
-        from pypy.conftest import maketestobjspace
+        from pypy.tool.pytest.objspace import maketestobjspace
 
         class MyModule(MixedModule):
             interpleveldefs = {}
         w_str = space1.getattr(w_mymod1, space1.wrap("hi"))
         assert space1.str_w(w_str) == "hello"
 
+class TestMixedModuleUnfreeze:
+    spaceconfig = dict(usemodules=('_ssl', '_socket'))
+
     def test_random_stuff_can_unfreeze(self):
         # When a module contains an "import" statement in applevel code, the
         # imported module is initialized, possibly after it has been already
         # This is important when the module startup() function does something
         # at runtime, like setting os.environ (posix module) or initializing
         # the winsock library (_socket module)
-        from pypy.conftest import gettestobjspace
-        space = gettestobjspace(usemodules=('_ssl', '_socket'))
-
-        w_socket = space.builtin_modules['_socket']
-        w_ssl = space.builtin_modules['_ssl']
+        w_socket = self.space.builtin_modules['_socket']
+        w_ssl = self.space.builtin_modules['_ssl']
 
         # Uncomment this line for a workaround
         # space.getattr(w_ssl, space.wrap('SSLError'))

File pypy/interpreter/test/test_argument.py

File contents unchanged.

File pypy/interpreter/test/test_code.py

-from pypy.conftest import gettestobjspace
 from pypy.interpreter import gateway
 from pypy.interpreter.astcompiler import consts
 import py
 
 class AppTestCodeIntrospection:
     def setup_class(cls):
-        space = gettestobjspace()
-        cls.space = space
         filename = __file__
         if filename[-3:] != '.py':
             filename = filename[:-1]
 
-        cls.w_file = space.wrap(filename)
-        cls.w_CO_CONTAINSGLOBALS = space.wrap(consts.CO_CONTAINSGLOBALS)
+        cls.w_file = cls.space.wrap(filename)
+        cls.w_CO_CONTAINSGLOBALS = cls.space.wrap(consts.CO_CONTAINSGLOBALS)
 
     def test_attributes(self):
         def f(): pass

File pypy/interpreter/test/test_compiler.py

 from pypy.interpreter.pycode import PyCode
 from pypy.interpreter.error import OperationError
 from pypy.interpreter.argument import Arguments
-from pypy.conftest import gettestobjspace
 
 class BaseTestCompiler:
     def setup_method(self, method):
         assert "LOAD_GLOBAL" not in output
 
 class AppTestCallMethod(object):
-    def setup_class(cls):
-        cls.space = gettestobjspace(**{'objspace.opcodes.CALL_METHOD': True})
+    spaceconfig = {'objspace.opcodes.CALL_METHOD': True}
         
     def test_call_method_kwargs(self):
         source = """def _f(a):

File pypy/interpreter/test/test_executioncontext.py

 import py
 from pypy.interpreter import executioncontext
-from pypy.conftest import gettestobjspace, option
 
 class Finished(Exception):
     pass
 
 
 class TestExecutionContext:
-    keywords = {}
-
-    def setup_class(cls):
-        cls.space = gettestobjspace(**cls.keywords)
-
     def test_action(self):
 
         class DemoAction(executioncontext.AsyncAction):
 
 
 class TestExecutionContextWithCallMethod(TestExecutionContext):
-    keywords = {'objspace.opcodes.CALL_METHOD': True}
+    spaceconfig ={'objspace.opcodes.CALL_METHOD': True}
 
 
 class AppTestDelNotBlocked:
 
     def setup_method(self, meth):
-        if not option.runappdirect:
+        if not self.runappdirect:
             py.test.skip("test is meant for running with py.test -A")
         from pypy.tool.udir import udir
         tmpfile = udir.join('test_execution_context')

File pypy/interpreter/test/test_gateway.py

 
 # -*- coding: utf-8 -*-
 
-from pypy.conftest import gettestobjspace
 from pypy.interpreter import gateway, argument
 from pypy.interpreter.gateway import ObjSpace, W_Root, WrappedDefault
 import py
         assert isinstance(called[0], argument.Arguments)
 
 class TestPassThroughArguments_CALL_METHOD(TestPassThroughArguments):
-
-    def setup_class(cls):
-        space = gettestobjspace(usemodules=('itertools',), **{
+    spaceconfig = dict(usemodules=('itertools',), **{
             "objspace.opcodes.CALL_METHOD": True
             })
-        cls.space = space
 
 class AppTestKeywordsToBuiltinSanity(object):
 

File pypy/interpreter/test/test_syntax.py

 from __future__ import with_statement
 import py
-from pypy.conftest import gettestobjspace
 
 def splitcases(s):
     lines = [line.rstrip() for line in s.split('\n')]

File pypy/interpreter/test/test_zzpickle_and_slow.py

 import py
 from pypy import conftest
-from pypy.conftest import gettestobjspace
 from pypy.interpreter import gateway
 from pypy.rlib.jit import non_virtual_ref, vref_None
 
 class AppTestSlow:    
+    spaceconfig = dict(usemodules=['itertools'])
+
     def setup_class(cls):
-        space = gettestobjspace(usemodules=['itertools'])
-        cls.space = space
         if py.test.config.option.runappdirect:
             filename = __file__
         else:
         if filename[-3:] != '.py':
             filename = filename[:-1]
 
-        cls.w_file = space.wrap(filename)
+        cls.w_file = cls.space.wrap(filename)
 
     def test_inspect(self):
         if not hasattr(len, 'func_code'):
                   space.wrap('read_exc_type'),
                   space.wrap(read_exc_type_gw))
     
-def _detatch_helpers(space):
+def _detach_helpers(space):
     space.delitem(space.builtin.w_dict,
                   space.wrap('hide_top_frame'))
     space.delitem(space.builtin.w_dict,
 
 class AppTestInterpObjectPickling:
     pytestmark = py.test.mark.skipif("config.option.runappdirect")
+    spaceconfig = dict(usemodules=['struct'])
+
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['struct'])
         _attach_helpers(cls.space)
 
     def teardown_class(cls):
-        _detatch_helpers(cls.space)
+        _detach_helpers(cls.space)
 
     def test_pickle_code(self):
         def f():

File pypy/module/__builtin__/test/test_buffer.py

 """Tests some behaviour of the buffer type that is not tested in
 lib-python/2.5.2/test/test_types.py where the stdlib buffer tests live."""
 import autopath
-from pypy.conftest import gettestobjspace
 
 class AppTestBuffer:
     spaceconfig = dict(usemodules=['array'])

File pypy/module/__builtin__/test/test_builtin.py

 import autopath
 import sys
-from pypy import conftest
 
 class AppTestBuiltinApp:
     def setup_class(cls):
         # For example if an object x has a __getattr__, we can get
         # AttributeError if attempting to call x.__getattr__ runs out
         # of stack.  That's annoying, so we just work around it.
-        if conftest.option.runappdirect:
+        if cls.runappdirect:
             cls.w_safe_runtimerror = cls.space.wrap(True)
         else:
             cls.w_safe_runtimerror = cls.space.wrap(sys.version_info < (2, 6))
 
 
 class AppTestGetattr:
-    OPTIONS = {}
-
-    def setup_class(cls):
-        cls.space = conftest.gettestobjspace(**cls.OPTIONS)
+    spaceconfig = {}
 
     def test_getattr(self):
         class a(object):
 
 
 class AppTestGetattrWithGetAttributeShortcut(AppTestGetattr):
-    OPTIONS = {"objspace.std.getattributeshortcut": True}
+    spaceconfig = {"objspace.std.getattributeshortcut": True}
 
 
 class TestInternal:

File pypy/module/__builtin__/test/test_classobj.py

 from __future__ import with_statement
 import py
-from pypy.conftest import gettestobjspace, option
 from pypy.interpreter import gateway
 
 
 
 class AppTestOldStyleClassStrDict(object):
     def setup_class(cls):
-        if option.runappdirect:
+        if cls.runappdirect:
             py.test.skip("can only be run on py.py")
         def is_strdict(space, w_class):
             from pypy.objspace.std.dictmultiobject import StringDictStrategy
         assert self.is_strdict(A)
 
 class AppTestOldStyleMapDict(AppTestOldstyle):
+    spaceconfig = {"objspace.std.withmapdict": True}
+
     def setup_class(cls):
-        cls.space = gettestobjspace(**{"objspace.std.withmapdict": True})
-        if option.runappdirect:
+        if cls.runappdirect:
             py.test.skip("can only be run on py.py")
         def has_mapdict(space, w_inst):
             return space.wrap(w_inst._get_mapdict_map() is not None)

File pypy/module/__pypy__/test/test_builders.py

-from pypy.conftest import gettestobjspace
-
-
 class AppTestBuilders(object):
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['__pypy__'])
+    spaceconfig = dict(usemodules=['__pypy__'])
 
     def test_simple(self):
         from __pypy__.builders import UnicodeBuilder

File pypy/module/__pypy__/test/test_bytebuffer.py

-import py
-from pypy.conftest import gettestobjspace
-
 class AppTest(object):
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['__pypy__'])
+    spaceconfig = dict(usemodules=['__pypy__'])
 
     def test_bytebuffer(self):
         from __pypy__ import bytebuffer

File pypy/module/__pypy__/test/test_debug.py

 import py
-from pypy.conftest import gettestobjspace, option
 from pypy.rlib import debug
 
 class AppTestDebug:
+    spaceconfig = dict(usemodules=['__pypy__'])
+
     def setup_class(cls):
-        if option.runappdirect:
+        if cls.runappdirect:
             py.test.skip("not meant to be run with -A")
-        cls.space = gettestobjspace(usemodules=['__pypy__'])
-        space = cls.space
         cls.w_check_log = cls.space.wrap(cls.check_log)
 
     def setup_method(self, meth):

File pypy/module/__pypy__/test/test_identitydict.py

-import py
-from pypy.conftest import gettestobjspace
-
 class AppTestIdentityDict:
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['__pypy__'])
+    spaceconfig = dict(usemodules=['__pypy__'])
 
     def test_numbers(self):
         from __pypy__ import identity_dict

File pypy/module/__pypy__/test/test_special.py

 import py
-from pypy.conftest import gettestobjspace, option
 
 class AppTest(object):
+    spaceconfig = {"objspace.usemodules.select": False,
+                   "objspace.std.withrangelist": True}
+
     def setup_class(cls):
-        if option.runappdirect:
+        if cls.runappdirect:
             py.test.skip("does not make sense on pypy-c")
-        cls.space = gettestobjspace(**{"objspace.usemodules.select": False, "objspace.std.withrangelist": True})
 
     def test__isfake(self):
         from __pypy__ import isfake

File pypy/module/_ast/test/test_ast.py

 import py
-from pypy.conftest import gettestobjspace
 
 class AppTestAST:
+    spaceconfig = dict(usemodules=['struct'])
 
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['struct'])
-        cls.w_ast = cls.space.appexec([], """():
-    import _ast
-    return _ast""")
+        cls.w_ast = cls.space.getbuiltinmodule('_ast')
 
     def w_get_ast(self, source, mode="exec"):
-        import _ast as ast
+        ast = self.ast
         mod = compile(source, "<test>", mode, ast.PyCF_ONLY_AST)
         assert isinstance(mod, ast.mod)
         return mod

File pypy/module/_bisect/test/test_bisect.py

-from pypy.conftest import gettestobjspace
-
 
 class AppTestBisect:
-
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['_bisect'])
+    spaceconfig = dict(usemodules=['_bisect'])
 
     def test_bisect_left(self):
         from _bisect import bisect_left

File pypy/module/_cffi_backend/ccallback.py

 
     def print_error(self, operr):
         space = self.space
-        operr.write_unraisable(space, "cffi callback", self.w_callable)
+        operr.write_unraisable(space, "callback ", self.w_callable,
+                               with_traceback=True)
 
     def write_error_return_value(self, ll_res):
         fresult = self.getfunctype().ctitem

File pypy/module/_cffi_backend/cerrno.py

+import sys
 from pypy.rlib import rposix
 from pypy.interpreter.executioncontext import ExecutionContext
 from pypy.interpreter.gateway import unwrap_spec
 
+WIN32 = sys.platform == 'win32'
+if WIN32:
+    from pypy.rlib import rwin32
+
 
 ExecutionContext._cffi_saved_errno = 0
+ExecutionContext._cffi_saved_LastError = 0
 
 
 def get_errno_container(space):
 
 
 def restore_errno_from(ec):
+    if WIN32:
+        rwin32.SetLastError(ec._cffi_saved_LastError)
     rposix.set_errno(ec._cffi_saved_errno)
 
 def save_errno_into(ec, errno):
     ec._cffi_saved_errno = errno
+    if WIN32:
+        ec._cffi_saved_LastError = rwin32.GetLastError()
 
 
 def get_errno(space):

File pypy/module/_cffi_backend/ctypefunc.py

 W_CTypeFunc.cif_descr = lltype.nullptr(CIF_DESCRIPTION)     # default value
 
 BIG_ENDIAN = sys.byteorder == 'big'
+USE_C_LIBFFI_MSVC = getattr(clibffi, 'USE_C_LIBFFI_MSVC', False)
 
 
 # ----------
 # We attach to the classes small methods that return a 'ffi_type'
-def _missing_ffi_type(self, cifbuilder):
+def _missing_ffi_type(self, cifbuilder, is_result_type):
     space = self.space
     if self.size < 0:
         raise operationerrfmt(space.w_TypeError,
                               "ctype '%s' has incomplete type",
                               self.name)
+    if is_result_type:
+        place = "return value"
+    else:
+        place = "argument"
     raise operationerrfmt(space.w_NotImplementedError,
-                          "ctype '%s' (size %d) not supported as argument"
-                          " or return value",
-                          self.name, self.size)
+                          "ctype '%s' (size %d) not supported as %s",
+                          self.name, self.size, place)
 
-def _struct_ffi_type(self, cifbuilder):
+def _struct_ffi_type(self, cifbuilder, is_result_type):
     if self.size >= 0:
-        return cifbuilder.fb_struct_ffi_type(self)
-    return _missing_ffi_type(self, cifbuilder)
+        return cifbuilder.fb_struct_ffi_type(self, is_result_type)
+    return _missing_ffi_type(self, cifbuilder, is_result_type)
 
-def _primsigned_ffi_type(self, cifbuilder):
+def _primsigned_ffi_type(self, cifbuilder, is_result_type):
     size = self.size
     if   size == 1: return clibffi.ffi_type_sint8
     elif size == 2: return clibffi.ffi_type_sint16
     elif size == 4: return clibffi.ffi_type_sint32
     elif size == 8: return clibffi.ffi_type_sint64
-    return _missing_ffi_type(self, cifbuilder)
+    return _missing_ffi_type(self, cifbuilder, is_result_type)
 
-def _primunsigned_ffi_type(self, cifbuilder):
+def _primunsigned_ffi_type(self, cifbuilder, is_result_type):
     size = self.size
     if   size == 1: return clibffi.ffi_type_uint8
     elif size == 2: return clibffi.ffi_type_uint16
     elif size == 4: return clibffi.ffi_type_uint32
     elif size == 8: return clibffi.ffi_type_uint64
-    return _missing_ffi_type(self, cifbuilder)
+    return _missing_ffi_type(self, cifbuilder, is_result_type)
 
-def _primfloat_ffi_type(self, cifbuilder):
+def _primfloat_ffi_type(self, cifbuilder, is_result_type):
     size = self.size
     if   size == 4: return clibffi.ffi_type_float
     elif size == 8: return clibffi.ffi_type_double
-    return _missing_ffi_type(self, cifbuilder)
+    return _missing_ffi_type(self, cifbuilder, is_result_type)
 
-def _primlongdouble_ffi_type(self, cifbuilder):
+def _primlongdouble_ffi_type(self, cifbuilder, is_result_type):
     return clibffi.ffi_type_longdouble
 
-def _ptr_ffi_type(self, cifbuilder):
+def _ptr_ffi_type(self, cifbuilder, is_result_type):
     return clibffi.ffi_type_pointer
 
-def _void_ffi_type(self, cifbuilder):
-    return clibffi.ffi_type_void
+def _void_ffi_type(self, cifbuilder, is_result_type):
+    if is_result_type:
+        return clibffi.ffi_type_void
+    return _missing_ffi_type(self, cifbuilder, is_result_type)
 
 W_CType._get_ffi_type                       = _missing_ffi_type
 W_CTypeStruct._get_ffi_type                 = _struct_ffi_type
 W_CTypePrimitiveFloat._get_ffi_type         = _primfloat_ffi_type
 W_CTypePrimitiveLongDouble._get_ffi_type    = _primlongdouble_ffi_type
 W_CTypePtrBase._get_ffi_type                = _ptr_ffi_type
-#W_CTypeVoid._get_ffi_type                  = _void_ffi_type -- special-cased
+W_CTypeVoid._get_ffi_type                   = _void_ffi_type
 # ----------
 
 
 
 
     def fb_fill_type(self, ctype, is_result_type):
-        if is_result_type and isinstance(ctype, W_CTypeVoid):
-            return clibffi.ffi_type_void
-        return ctype._get_ffi_type(self)
+        return ctype._get_ffi_type(self, is_result_type)
 
-    def fb_struct_ffi_type(self, ctype):
+    def fb_struct_ffi_type(self, ctype, is_result_type=False):
         # We can't pass a struct that was completed by verify().
         # Issue: assume verify() is given "struct { long b; ...; }".
         # Then it will complete it in the same way whether it is actually
                "with verify() (see pypy/module/_cffi_backend/ctypefunc.py "
                "for details)"))
 
+        if USE_C_LIBFFI_MSVC and is_result_type:
+            # MSVC returns small structures in registers.  Pretend int32 or
+            # int64 return type.  This is needed as a workaround for what
+            # is really a bug of libffi_msvc seen as an independent library
+            # (ctypes has a similar workaround).
+            if ctype.size <= 4:
+                return clibffi.ffi_type_sint32
+            if ctype.size <= 8:
+                return clibffi.ffi_type_sint64
+
         # allocate an array of (n + 1) ffi_types
         n = len(ctype.fields_list)
         elements = self.fb_alloc(rffi.sizeof(FFI_TYPE_P) * (n + 1))

File pypy/module/_cffi_backend/test/_backend_test_c.py

     e = py.test.raises(TypeError, f)
     assert str(e.value) == "'int(*)(int)' expects 1 arguments, got 0"
 
+def test_callback_exception():
+    import cStringIO, linecache
+    def matches(str, pattern):
+        while '$' in pattern:
+            i = pattern.index('$')
+            assert str[:i] == pattern[:i]
+            j = str.find(pattern[i+1], i)
+            assert i + 1 <= j <= str.find('\n', i)
+            str = str[j:]
+            pattern = pattern[i+1:]
+        assert str == pattern
+        return True
+    def check_value(x):
+        if x == 10000:
+            raise ValueError(42)
+    def cb1(x):
+        check_value(x)
+        return x * 3
+    BShort = new_primitive_type("short")
+    BFunc = new_function_type((BShort,), BShort, False)
+    f = callback(BFunc, cb1, -42)
+    orig_stderr = sys.stderr
+    orig_getline = linecache.getline
+    try:
+        linecache.getline = lambda *args: 'LINE'    # hack: speed up PyPy tests
+        sys.stderr = cStringIO.StringIO()
+        assert f(100) == 300
+        assert sys.stderr.getvalue() == ''
+        assert f(10000) == -42
+        assert matches(sys.stderr.getvalue(), """\
+From callback <function cb1 at 0x$>:
+Traceback (most recent call last):
+  File "$", line $, in cb1
+    $
+  File "$", line $, in check_value
+    $
+ValueError: 42
+""")
+        sys.stderr = cStringIO.StringIO()
+        bigvalue = 20000
+        assert f(bigvalue) == -42
+        assert matches(sys.stderr.getvalue(), """\
+From callback <function cb1 at 0x$>:
+OverflowError: integer 60000 does not fit 'short'
+""")
+    finally:
+        sys.stderr = orig_stderr
+        linecache.getline = orig_getline
+
 def test_callback_return_type():
     for rettype in ["signed char", "short", "int", "long", "long long",
                     "unsigned char", "unsigned short", "unsigned int",
     assert p.a1 == -1
 
 def test_weakref():
-    import weakref
+    import _weakref
     BInt = new_primitive_type("int")
     BPtr = new_pointer_type(BInt)
-    weakref.ref(BInt)
-    weakref.ref(newp(BPtr, 42))
-    weakref.ref(cast(BPtr, 42))
-    weakref.ref(cast(BInt, 42))
+    _weakref.ref(BInt)
+    _weakref.ref(newp(BPtr, 42))
+    _weakref.ref(cast(BPtr, 42))
+    _weakref.ref(cast(BInt, 42))
 
 def test_no_inheritance():
     BInt = new_primitive_type("int")
     a = newp(BArray, [u+'A', u+'B', u+'C'])
     assert type(string(a)) is unicode and string(a) == u+'ABC'
     if 'PY_DOT_PY' not in globals() and sys.version_info < (3,):
-        assert string(a, 8).startswith(u+'ABC') # may contain additional garbage
+        try:
+            # may contain additional garbage
+            assert string(a, 8).startswith(u+'ABC')
+        except ValueError:    # garbage contains values > 0x10FFFF
+            assert sizeof(BWChar) == 4
 
 def test_string_typeerror():
     BShort = new_primitive_type("short")
     data = posix.read(fdr, 256)
     assert data == b"Xhello\n"
     posix.close(fdr)
+
+def test_GetLastError():
+    if sys.platform != "win32":
+        py.test.skip("GetLastError(): only for Windows")
+    #
+    lib = find_and_load_library('KERNEL32')
+    BInt = new_primitive_type("int")
+    BVoid = new_void_type()
+    BFunc1 = new_function_type((BInt,), BVoid, False)
+    BFunc2 = new_function_type((), BInt, False)
+    SetLastError = lib.load_function(BFunc1, "SetLastError")
+    GetLastError = lib.load_function(BFunc2, "GetLastError")
+    #
+    SetLastError(42)
+    # a random function that will reset the real GetLastError() to 0
+    import nt; nt.stat('.')
+    #
+    res = GetLastError()
+    assert res == 42

File pypy/module/_cffi_backend/test/test_c.py

     py.test.skip("requires the b'' literal syntax")
 
 from pypy.tool.udir import udir
-from pypy.conftest import gettestobjspace, option
 from pypy.interpreter import gateway
 from pypy.module._cffi_backend import Module
 from pypy.translator.platform import host
 class AppTestC(object):
     """Populated below, hack hack hack."""
 
+    spaceconfig = dict(usemodules=('_cffi_backend', 'cStringIO'))
+
     def setup_class(cls):
-        space = gettestobjspace(usemodules=('_cffi_backend',))
-        cls.space = space
         testfuncs_w = []
         keepalive_funcs = []
 
             addr = cdll.gettestfunc(w_num)
             return space.wrap(addr)
 
-        if option.runappdirect:
+        space = cls.space
+        if cls.runappdirect:
             def interp2app(func):
                 def run(*args):
                     return func(space, *args)

File pypy/module/_codecs/test/test_codecs.py

 import autopath
-from pypy.conftest import gettestobjspace
 
 
 class AppTestCodecs:
-    def setup_class(cls):
-        space = gettestobjspace(usemodules=('unicodedata', 'struct'))
-        cls.space = space
+    spaceconfig = dict(usemodules=('unicodedata', 'struct'))
 
     def test_register_noncallable(self):
         import _codecs
         assert unicode_escape_decode('\\x61\\x62\\x63') == (u'abc', 12)
 
 class AppTestPartialEvaluation:
-
-    def setup_class(cls):
-        space = gettestobjspace(usemodules=('array',))
-        cls.space = space
+    spaceconfig = dict(usemodules=('array',))
 
     def test_partial_utf8(self):
         import _codecs

File pypy/module/_collections/test/test_defaultdict.py

-import py
-from pypy.conftest import gettestobjspace
 
 class AppTestBasic:
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['_collections'])
+    spaceconfig = dict(usemodules=['_collections'])
 
     def test_basics(self):
         from _collections import defaultdict

File pypy/module/_collections/test/test_deque.py

-import py
-from pypy.conftest import gettestobjspace
 
 class AppTestBasic:
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['_collections'])
+    spaceconfig = dict(usemodules=['_collections'])
 
     def test_basics(self):
         from _collections import deque

File pypy/module/_continuation/test/support.py

 import py
-from pypy.conftest import gettestobjspace
 from pypy.rpython.tool.rffi_platform import CompilationError
 
 
 class BaseAppTest:
+    spaceconfig = dict(usemodules=['_continuation'], continuation=True)
+
     def setup_class(cls):
         try:
             import pypy.rlib.rstacklet
         except CompilationError, e:
             py.test.skip("cannot import rstacklet: %s" % e)
-        cls.space = gettestobjspace(usemodules=['_continuation'], continuation=True)
+

File pypy/module/_continuation/test/test_zpickle.py

-from pypy.conftest import gettestobjspace
-
 
 class AppTestCopy:
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=('_continuation',),
-                                    CALL_METHOD=True)
-        cls.space.config.translation.continuation = True
+    spaceconfig = dict(usemodules=['_continuation'],
+                       continuation=True,
+                       CALL_METHOD=True)
 
     def test_basic_setup(self):
         from _continuation import continulet
 
 class AppTestPickle:
     version = 0
+    spaceconfig = dict(usemodules=['_continuation', 'struct'],
+                       continuation=True,
+                       CALL_METHOD=True)
 
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=('_continuation', 'struct'),
-                                    CALL_METHOD=True)
-        cls.space.config.translation.continuation = True
         cls.space.appexec([], """():
             global continulet, A, __name__
 

File pypy/module/_csv/test/test_dialect.py

-from pypy.conftest import gettestobjspace
-
-
 class AppTestDialect(object):
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['_csv'])
+    spaceconfig = dict(usemodules=['_csv'])
 
     def test_register_dialect(self):
         import _csv

File pypy/module/_csv/test/test_reader.py

-from pypy.conftest import gettestobjspace
+class AppTestReader(object):
+    spaceconfig = dict(usemodules=['_csv'])
 
-
-class AppTestReader(object):
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['_csv'])
-
         w__read_test = cls.space.appexec([], r"""():
             import _csv
             def _read_test(input, expect, **kwargs):

File pypy/module/_csv/test/test_writer.py

-from pypy.conftest import gettestobjspace
+class AppTestWriter(object):
+    spaceconfig = dict(usemodules=['_csv'])
 
-
-class AppTestWriter(object):
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=['_csv'])
-
         w__write_test = cls.space.appexec([], r"""():
             import _csv
 

File pypy/module/_demo/test/test_import.py

-from pypy.conftest import gettestobjspace
 from pypy.module import _demo
+from pypy.tool.option import make_config, make_objspace
 
 class TestImport:
 
         _demo.Module.demo_events = []
 
     def test_startup(self):
-        space = gettestobjspace(usemodules=('_demo',))
+        config = make_config(None, usemodules=('_demo',))
+        space = make_objspace(config)
         w_modules = space.sys.get('modules')
 
         assert _demo.Module.demo_events == ['setup']

File pypy/module/_demo/test/test_sieve.py

-from pypy.conftest import gettestobjspace
-
-
 class AppTestSieve:
-    def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=('_demo',))
+    spaceconfig = dict(usemodules=('_demo',))
 
     def test_sieve(self):
         import _demo

File pypy/module/_ffi/test/test_funcptr.py

-from pypy.conftest import gettestobjspace
 from pypy.rpython.lltypesystem import rffi
 from pypy.rlib.clibffi import get_libc_name
 from pypy.rlib.libffi import types
 import sys, py
 
 class BaseAppTestFFI(object):
+    spaceconfig = dict(usemodules=('_ffi', '_rawffi'))
 
     @classmethod
     def prepare_c_example(cls):
         return str(platform.compile([c_file], eci, 'x', standalone=False))
 
     def setup_class(cls):
-        space = gettestobjspace(usemodules=('_ffi', '_rawffi'))
-        cls.space = space
+        space = cls.space
         cls.w_iswin32 = space.wrap(sys.platform == 'win32')
         cls.w_libfoo_name = space.wrap(cls.prepare_c_example())
         cls.w_libc_name = space.wrap(get_libc_name())

File pypy/module/_ffi/test/test_struct.py

 import sys
-from pypy.conftest import gettestobjspace, option
 from pypy.module._ffi.test.test_funcptr import BaseAppTestFFI
 from pypy.module._ffi.interp_struct import compute_size_and_alignement, W_Field
 from pypy.module._ffi.interp_ffitype import app_types, W_FFIType
         dummy_type.c_alignment = rffi.cast(rffi.USHORT, 0)
         dummy_type.c_type = rffi.cast(rffi.USHORT, 0)
         cls.w_dummy_type = W_FFIType('dummy', dummy_type)
-        cls.w_runappdirect = cls.space.wrap(option.runappdirect)
+        cls.w_runappdirect = cls.space.wrap(cls.runappdirect)
         
     def test__StructDescr(self):
         from _ffi import _StructDescr, Field, types

File pypy/module/_ffi/test/test_type_converter.py

 import sys
-from pypy.conftest import gettestobjspace
 from pypy.rlib.rarithmetic import r_uint, r_singlefloat, r_longlong, r_ulonglong
 from pypy.rlib.libffi import IS_32_BIT
 from pypy.module._ffi.interp_ffitype import app_types, descr_new_pointer
 
 
 class TestFromAppLevel(object):
+    spaceconfig = dict(usemodules=('_ffi',))
 
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=('_ffi',))
         converter = DummyFromAppLevelConverter(cls.space)
         cls.from_app_level = staticmethod(converter.convert)
 
 
 
 class TestFromAppLevel(object):
+    spaceconfig = dict(usemodules=('_ffi',))
 
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=('_ffi',))
         converter = DummyToAppLevelConverter(cls.space)
         cls.from_app_level = staticmethod(converter.convert)
 

File pypy/module/_file/test/test_file.py

 from __future__ import with_statement
 import py, os, errno
 
-from pypy.conftest import gettestobjspace, option
-
 def getfile(space):
     return space.appexec([], """():
         try:
     """)
 
 class AppTestFile(object):
+    spaceconfig = dict(usemodules=("_file",))
+
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=("_file", ))
         cls.w_temppath = cls.space.wrap(
             str(py.test.ensuretemp("fileimpl").join("foo.txt")))
         cls.w_file = getfile(cls.space)
 
         cls.old_read = os.read
 
-        if option.runappdirect:
+        if cls.runappdirect:
             py.test.skip("works with internals of _file impl on py.py")
         state = [0]
         def read(fd, n=None):
     # these tests only really make sense on top of a translated pypy-c,
     # because on top of py.py the inner calls to os.write() don't
     # release our object space's GIL.
+    spaceconfig = dict(usemodules=("_file",))
+
     def setup_class(cls):
-        if not option.runappdirect:
+        if not cls.runappdirect:
             py.test.skip("likely to deadlock when interpreted by py.py")
-        cls.space = gettestobjspace(usemodules=("_file", "thread"))
         cls.w_temppath = cls.space.wrap(
             str(py.test.ensuretemp("fileimpl").join("concurrency.txt")))
         cls.w_file = getfile(cls.space)
 
 
 class AppTestFile25:
+    spaceconfig = dict(usemodules=("_file",))
+
     def setup_class(cls):
-        cls.space = gettestobjspace(usemodules=("_file", ))
         cls.w_temppath = cls.space.wrap(
             str(py.test.ensuretemp("fileimpl").join("foo.txt")))
         cls.w_file = getfile(cls.space)

File pypy/module/_file/test/test_file_extra.py

 import os, random, sys
 import pypy.tool.udir
 import py
-from pypy.conftest import gettestobjspace