[pypy-commit] pypy py3.5: hg merge default

rlamy pypy.commits at gmail.com
Fri Jun 30 18:25:46 EDT 2017


Author: Ronan Lamy <ronan.lamy at gmail.com>
Branch: py3.5
Changeset: r91662:96e56ffe7aa7
Date: 2017-06-30 23:25 +0100
http://bitbucket.org/pypy/pypy/changeset/96e56ffe7aa7/

Log:	hg merge default

diff too long, truncating to 2000 out of 2002 lines

diff --git a/lib_pypy/stackless.py b/lib_pypy/stackless.py
--- a/lib_pypy/stackless.py
+++ b/lib_pypy/stackless.py
@@ -268,12 +268,22 @@
         assert abs(d) == 1
         source = getcurrent()
         source.tempval = arg
-        if d > 0:
-            cando = self.balance < 0
-            dir = d
-        else:
-            cando = self.balance > 0
-            dir = 0
+        while True:
+            if d > 0:
+                cando = self.balance < 0
+                dir = d
+            else:
+                cando = self.balance > 0
+                dir = 0
+
+            if cando and self.queue[0]._tasklet_killed:
+                # issue #2595: the tasklet was killed while waiting.
+                # drop that tasklet from consideration and try again.
+                self.balance += d
+                self.queue.popleft()
+            else:
+                # normal path
+                break
 
         if _channel_callback is not None:
             _channel_callback(self, source, dir, not cando)
@@ -348,6 +358,8 @@
     module.
     """
     tempval = None
+    _tasklet_killed = False
+
     def __new__(cls, func=None, label=''):
         res = coroutine.__new__(cls)
         res.label = label
@@ -395,6 +407,7 @@
         If the exception passes the toplevel frame of the tasklet,
         the tasklet will silently die.
         """
+        self._tasklet_killed = True
         if not self.is_zombie:
             # Killing the tasklet by throwing TaskletExit exception.
             coroutine.kill(self)
diff --git a/pypy/module/cppyy/backend/create_cppyy_package.py b/pypy/module/cppyy/backend/create_cppyy_package.py
new file mode 100755
--- /dev/null
+++ b/pypy/module/cppyy/backend/create_cppyy_package.py
@@ -0,0 +1,649 @@
+#!/usr/bin/env python
+from __future__ import print_function
+
+import os, sys
+import argparse, re, shutil, tarfile, urllib2
+
+
+DEBUG_TESTBUILD = False
+
+TARBALL_CACHE_DIR = 'releases'
+
+ROOT_KEEP = ['build', 'cmake', 'config', 'core', 'etc', 'interpreter',
+             'io', 'LICENSE', 'net', 'Makefile', 'CMakeLists.txt', 'math',
+             'main'] # main only needed in more recent root b/c of rootcling
+ROOT_CORE_KEEP = ['CMakeLists.txt', 'base', 'clib', 'clingutils', 'cont',
+                  'dictgen', 'foundation', 'lzma', 'macosx', 'meta',
+                  'metacling', 'metautils', 'rootcling_stage1', 'textinput',
+                  'thread', 'unix', 'utils', 'winnt', 'zip']
+ROOT_IO_KEEP = ['CMakeLists.txt', 'io', 'rootpcm']
+ROOT_NET_KEEP = ['CMakeLists.txt', 'net']
+ROOT_MATH_KEEP = ['CMakeLists.txt', 'mathcore']
+ROOT_ETC_KEEP = ['Makefile.arch', 'class.rules', 'cmake', 'dictpch',
+                 'gdb-backtrace.sh', 'gitinfo.txt', 'helgrind-root.supp',
+                 'hostcert.conf', 'system.plugins-ios',
+                 'valgrind-root-python.supp', 'valgrind-root.supp', 'vmc']
+
+ROOT_EXPLICIT_REMOVE = ['core/base/v7', 'math/mathcore/v7', 'io/io/v7']
+
+
+ERR_RELEASE_NOT_FOUND = 2
+
+
+#
+## CLI arguments
+#
+class ReleaseValidation(argparse.Action):
+    def __call__(self, parser, namespace, value, option_string=None):
+        if not re.match(r'6\.\d\d\.\d\d', value):
+            raise argparse.ArgumentTypeError(
+                "release number should of the form '6.dd.dd'")
+        setattr(namespace, self.dest, value)
+        return value
+
+parser = argparse.ArgumentParser(
+    description='Build PyPi package for cppyy containing the minimum of ROOT')
+parser.add_argument('-r', '--release', type=str, nargs='?',
+                    action=ReleaseValidation, help='ROOT release to use')
+
+args = parser.parse_args()
+
+
+#
+## ROOT source pull and cleansing
+#
+def clean_directory(directory, keeplist, trim_cmake=True):
+    removed_entries = []
+    for entry in os.listdir(directory):
+        if entry[0] == '.' or entry in keeplist:
+            continue
+        removed_entries.append(entry)
+        entry = os.path.join(directory, entry)
+        print('now removing', entry)
+        if os.path.isdir(entry):
+            shutil.rmtree(entry)
+        else:
+            os.remove(entry)
+
+    if not trim_cmake:
+        return
+
+    # now take the removed entries out of the CMakeLists.txt
+    if removed_entries:
+        inp = os.path.join(directory, 'CMakeLists.txt')
+        print('trimming', inp)
+        outp = inp+'.new'
+        new_cml = open(outp, 'w')
+        for line in open(inp).readlines():
+            if ('add_subdirectory' in line) or\
+               ('COMMAND' in line and 'copy' in line) or\
+               ('ROOT_ADD_TEST_SUBDIRECTORY' in line) or\
+               ('install(DIRECTORY' in line):
+                for sub in removed_entries:
+                    if sub in line:
+                        line = '#'+line
+                        break
+            new_cml.write(line)
+        new_cml.close()
+        os.rename(outp, inp)
+    else:
+        print('reusing existing %s/CMakeLists.txt' % (directory,))
+ 
+
+class ReleaseValidation(argparse.Action):
+    def __call__(self, parser, namespace, value, option_string=None):
+        if not re.match(r'6\.\d\d\.\d\d', value):
+            raise argparse.ArgumentTypeError(
+                "release number should of the form '6.dd.dd'")
+        setattr(namespace, self.dest, value)
+        return value
+
+parser = argparse.ArgumentParser(
+    description='Build PyPi package for cppyy containing the minimum of ROOT')
+parser.add_argument('-r', '--release', type=str, nargs='?',
+                    action=ReleaseValidation, help='ROOT release to use')
+
+args = parser.parse_args()
+
+if not os.path.exists(TARBALL_CACHE_DIR):
+    os.mkdir(TARBALL_CACHE_DIR)
+
+if args.release:
+  # use provided release
+    fn = 'root_v%s.source.tar.gz' % args.release
+    addr = 'https://root.cern.ch/download/'+fn
+    if not os.path.exists(os.path.join(TARBALL_CACHE_DIR, fn)):
+        try:
+            print('retrieving', fn)
+            resp = urllib2.urlopen(addr, fn)
+            out = open(os.path.join(TARBALL_CACHE_DIR, fn), 'wb')
+            out.write(resp.read())
+            out.close()
+        except urllib2.HTTPError:
+            print('release %s not found' % args.release)
+            sys.exit(ERR_RELEASE_NOT_FOUND)
+    else:
+        print('reusing', fn, 'from local directory')
+else:
+    print('provide release ... getting latest release is not yet implemented ...')
+    sys.exit(1)
+  # get latest and set fn, args.release, etc.
+
+# construct version for package
+args.version = ''
+testnext = False
+for c in args.release:
+    if testnext:
+        testnext = False
+        if c == '0':
+            continue
+    if c == '.':
+        testnext = True
+    args.version += c
+args.version += '.0'
+
+fn = os.path.join(TARBALL_CACHE_DIR, fn)
+pkgdir = os.path.join('root-'+args.release)
+if not os.path.exists(pkgdir):
+    print('now extracting', args.release)
+    tf = tarfile.TarFile.gzopen(fn)
+    tf.extractall()
+    tf.close()
+else:
+    print('reusing existing directory', pkgdir)
+
+# remove everything except for the listed set of libraries
+os.chdir(pkgdir)
+
+clean_directory(os.path.curdir, ROOT_KEEP)
+clean_directory('core',         ROOT_CORE_KEEP)
+clean_directory('etc',          ROOT_ETC_KEEP, trim_cmake=False)
+clean_directory('io',           ROOT_IO_KEEP)
+clean_directory('math',         ROOT_MATH_KEEP)
+clean_directory('net',          ROOT_NET_KEEP)
+
+
+# trim main (only need rootcling)
+print('trimming main')
+for entry in os.listdir('main/src'):
+    if entry != 'rootcling.cxx':
+        os.remove('main/src/'+entry)
+inp = 'main/CMakeLists.txt'
+outp = inp+'.new'
+new_cml = open(outp, 'w')
+for line in open(inp).readlines():
+    if ('ROOT_EXECUTABLE' in line or\
+        'SET_TARGET_PROPERTIES' in line) and\
+       not 'rootcling' in line:
+        line = '#'+line
+    new_cml.write(line)
+new_cml.close()
+os.rename(outp, inp)
+
+
+# remove afterimage and ftgl explicitly
+print('trimming externals')
+for cmf in ['AfterImage', 'FTGL']:
+    os.remove('cmake/modules/Find%s.cmake' % (cmf,))
+inp = 'cmake/modules/SearchInstalledSoftware.cmake'
+outp = inp+'.new'
+now_stripping = False
+new_cml = open(outp, 'w')
+for line in open(inp).readlines():
+    if '#---Check for ftgl if needed' == line[0:28] or\
+       '#---Check for AfterImage' == line[0:24]:
+        now_stripping = True
+    elif '#---Check' == line[0:9]:
+        now_stripping = False
+    if now_stripping:
+        line = '#'+line
+    new_cml.write(line)
+new_cml.close()
+os.rename(outp, inp)
+
+inp = 'cmake/modules/RootBuildOptions.cmake'
+outp = inp+'.new'
+new_cml = open(outp, 'w')
+for line in open(inp).readlines():
+    if 'ROOT_BUILD_OPTION(builtin_ftgl' in line or\
+       'ROOT_BUILD_OPTION(builtin_afterimage' in line:
+        line = '#'+line
+    new_cml.write(line)
+new_cml.close()
+os.rename(outp, inp)
+
+
+# remove testing and examples
+print('trimming testing')
+inp = 'CMakeLists.txt'
+outp = inp+'.new'
+now_stripping = False
+new_cml = open(outp, 'w')
+for line in open(inp).readlines():
+    if '#---Configure Testing using CTest' == line[0:33] or\
+       '#---hsimple.root' == line[0:16]:
+        now_stripping = True
+    elif '#---Packaging' == line[0:13] or\
+         '#---version' == line[0:11]:
+        now_stripping = False
+    if now_stripping:
+        line = '#'+line
+    new_cml.write(line)
+new_cml.close()
+os.rename(outp, inp)
+
+print('trimming RootCPack')
+inp = 'cmake/modules/RootCPack.cmake'
+outp = inp+'.new'
+new_cml = open(outp, 'w')
+for line in open(inp):
+    if 'README.txt' in line:
+        line = '#'+line
+    new_cml.write(line)
+new_cml.close()
+os.rename(outp, inp)
+
+# some more explicit removes:
+for dir_to_remove in ROOT_EXPLICIT_REMOVE:
+    try:
+        shutil.rmtree(dir_to_remove)
+    except OSError:
+        pass
+
+# special fixes
+inp = 'core/base/src/TVirtualPad.cxx'
+outp = inp+'.new'
+new_cml = open(outp, 'w')
+for line in open(inp):
+    if '#include "X3DBuffer.h"' == line[0:22]:
+        line = """//#include "X3DBuffer.h"
+typedef struct _x3d_sizeof_ {
+   int  numPoints;
+   int  numSegs;
+   int  numPolys;
+} Size3D;
+"""
+    new_cml.write(line)
+new_cml.close()
+os.rename(outp, inp)
+
+inp = 'math/mathcore/src/Fitter.cxx'
+if os.path.exists(inp):
+    outp = inp+'.new'
+    new_cml = open(outp, 'w')
+    for line in open(inp):
+        if '#include "TF1.h"' in line:
+            continue
+        new_cml.write(line)
+    new_cml.close()
+    os.rename(outp, inp)
+
+# done
+os.chdir(os.path.pardir)
+
+# debugging: run a test build
+if DEBUG_TESTBUILD:
+    print('running a debug test build')
+    tb = "test_builddir"
+    if os.path.exists(tb):
+        shutil.rmtree(tb)
+    os.mkdir(tb)
+    os.chdir(tb)
+    os.system('cmake ../%s -DCMAKE_INSTALL_PREFIX=../install -Dminimal=ON -Dasimage=OFF' % pkgdir)
+    os.system('make -j 32')
+
+
+#
+## package creation
+#
+countdown = 0
+pidir = 'Package-'+args.release
+print('creating package', pidir)
+if not os.path.exists(pidir):
+    os.mkdir(pidir)
+os.chdir(pidir); countdown += 1
+
+print('creating LICENSE.txt')
+with open('LICENSE.txt', 'w') as outp:
+    outp.write("""There are three main parts:
+
+ LLVM: distributed under University of Illinois/NCSA Open Source License
+   https://opensource.org/licenses/UoI-NCSA.php
+ ROOT: distributed under LGPL 2.1
+   https://root.cern.ch/license
+ Cppyy: distributed under LBNL BSD
+   https://fedoraproject.org/wiki/Licensing/LBNLBSD
+""")
+
+print('creating MANIFEST.in')
+with open('MANIFEST.in', 'w') as outp:
+    outp.write("""# Include the license file
+include LICENSE.txt
+
+# Include the data files
+recursive-include src *
+""")
+
+print('creating README.rst')
+with open('README.rst', 'w') as outp:
+    outp.write("""PyPy cling-support
+==================
+
+----
+
+Find the documentation here:
+  http://doc.pypy.org/en/latest/cppyy.html
+""")
+
+print('creating setup.cfg')
+with open('setup.cfg', 'w') as outp:
+    outp.write("""[bdist_wheel]
+universal=0
+""")
+
+print('creating setup.py')
+with open('setup.py', 'w') as outp:
+    outp.write("""import os, sys, subprocess
+from setuptools import setup, find_packages
+from distutils import log
+from distutils.command.build import build as _build
+from setuptools.command.install import install as _install
+from distutils.sysconfig import get_python_lib
+from distutils.errors import DistutilsSetupError
+from codecs import open
+
+here = os.path.abspath(os.path.dirname(__file__))
+with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
+    long_description = f.read()
+
+builddir = None
+def get_builddir():
+    global builddir
+    if builddir is None:
+        topdir = os.getcwd()
+        builddir = os.path.join(topdir, 'builddir')
+    return builddir
+
+srcdir = None
+def get_srcdir():
+    global srcdir
+    if srcdir is None:
+        topdir = os.getcwd()
+        srcdir = os.path.join(topdir, 'src', 'backend')
+    return srcdir
+
+class my_cmake_build(_build):
+    def __init__(self, dist, *args, **kwargs):
+        _build.__init__(self, dist, *args, **kwargs)
+        # TODO: can't seem to find a better way of getting hold of
+        # the install_lib parameter during the build phase ...
+        prefix = ''
+        try:
+            prefix = dist.get_command_obj('install').install_lib
+        except AttributeError:
+            pass
+        if not prefix:
+            prefix = get_python_lib(1, 0)
+        self.prefix = os.path.join(prefix, 'cppyy_backend')
+
+    def run(self):
+        # base run
+        _build.run(self)
+
+        # custom run
+        log.info('Now building libcppyy_backend.so and dependencies')
+        builddir = get_builddir()
+        srcdir = get_srcdir()
+        if not os.path.exists(builddir):
+            log.info('Creating build directory %s ...' % builddir)
+            os.makedirs(builddir)
+
+        os.chdir(builddir)
+        log.info('Running cmake for cppyy_backend')
+        if subprocess.call([
+                'cmake', srcdir, '-Dminimal=ON -Dasimage=OFF',
+                '-DCMAKE_INSTALL_PREFIX='+self.prefix]) != 0:
+            raise DistutilsSetupError('Failed to configure cppyy_backend')
+
+        nprocs = os.getenv("MAKE_NPROCS")
+        if nprocs:
+            try:
+                ival = int(nprocs)
+                nprocs = '-j'+nprocs
+            except ValueError:
+                log.warn("Integer expected for MAKE_NPROCS, but got %s (ignored)", nprocs)
+                nprocs = '-j1'
+        else:
+            nprocs = '-j1'
+        log.info('Now building cppyy_backend and dependencies ...')
+        if subprocess.call(['make', nprocs]) != 0:
+            raise DistutilsSetupError('Failed to build cppyy_backend')
+
+        log.info('build finished')
+
+class my_libs_install(_install):
+    def run(self):
+        # base install
+        _install.run(self)
+
+        # custom install
+        log.info('Now installing libcppyy_backend.so and dependencies')
+        builddir = get_builddir()
+        if not os.path.exists(builddir):
+            raise DistutilsSetupError('Failed to find build dir!')
+        os.chdir(builddir)
+
+        prefix = self.install_lib
+        log.info('Now installing in %s ...', prefix)
+        if subprocess.call(['make', 'install']) != 0:
+            raise DistutilsSetupError('Failed to install cppyy_backend')
+
+        log.info('install finished')
+
+    def get_outputs(self):
+        outputs = _install.get_outputs(self)
+        outputs.append(os.path.join(self.install_lib, 'cppyy_backend'))
+        return outputs
+
+setup(
+    name='PyPy-cppyy-backend',
+""")
+    outp.write("    version='%s', # corresponds to ROOT %s, extra number is for packager\n"\
+         % (args.version, args.release))
+    outp.write("""    description='Cling support for PyPy',
+    long_description=long_description,
+
+    url='http://pypy.org',
+
+    # Author details
+    author='PyPy Developers',
+    author_email='pypy-dev at python.org',
+
+    license='LLVM: UoI-NCSA; ROOT: LGPL 2.1; Cppyy: LBNL BSD',
+
+    classifiers=[
+        'Development Status :: 4 - Beta',
+
+        'Intended Audience :: Developers',
+
+        'Topic :: Software Development',
+        'Topic :: Software Development :: Interpreters',
+
+        #'License :: OSI Approved :: MIT License',
+
+        'Programming Language :: Python :: 2',
+        'Programming Language :: Python :: 2.7',
+        'Programming Language :: Python :: Implementation :: PyPy',
+        'Programming Language :: C',
+        'Programming Language :: C++',
+
+        'Natural Language :: English'
+    ],
+
+    keywords='interpreter development',
+
+    packages=find_packages('src', ['backend']),
+    include_package_data=True,
+
+    extras_require={
+    },
+
+    cmdclass = {
+        'build': my_cmake_build,
+        'install': my_libs_install,
+    },
+)
+""")
+
+
+print('creating src ... ROOT part')
+if not os.path.exists('src'):
+    os.mkdir('src')
+os.chdir('src'); countdown += 1
+if not os.path.exists('backend'):
+    src = os.path.join(os.path.pardir, os.path.pardir, pkgdir)
+    print('now copying', src)
+    shutil.copytree(src, 'backend')
+
+print('creating src ... cppyy part')
+os.chdir('backend'); countdown += 1
+if not os.path.exists('cppyy'):
+    os.mkdir('cppyy')
+    os.chdir('cppyy'); countdown += 1
+
+    with open('CMakeLists.txt', 'w') as outp:
+        outp.write("""############################################################################
+# CMakeLists.txt file for building cppyy package
+############################################################################
+
+ROOT_GLOB_SOURCES(sources ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cxx)
+set_source_files_properties(${sources} COMPILE_FLAGS "-fomit-frame-pointer -fvisibility=hidden -DRPY_EXTERN=RPY_EXPORTED -DRPYTHON_LL2CTYPES")
+
+add_definitions(${CLING_CXXFLAGS})
+
+ROOT_LINKER_LIBRARY(cppyy_backend ${sources}
+                               LIBRARIES ${CMAKE_DL_LIBS}
+                               DEPENDENCIES Core Cling RIO Thread)
+
+add_dependencies(cppyy_backend CLING)
+""")
+
+    os.mkdir('src')
+    os.chdir('src'); countdown += 1
+    print('pulling cppyy/clingcwrapper.cxx from pypy')
+    base = 'https://bitbucket.org/pypy/pypy/raw/default/pypy/module/cppyy/'
+    for cppyy_file in ['src/callcontext.h', 'include/capi.h', 'src/clingcwrapper.cxx',
+                       'include/clingcwrapper.h', 'include/cpp_cppyy.h', 'include/cppyy.h']:
+        resp = urllib2.urlopen(base+cppyy_file)
+        with open(os.path.basename(cppyy_file), 'w') as outp:
+            outp.write(resp.read())
+
+    # fix include
+    inp = 'capi.h'
+    outp = inp+'.new'
+    new_cml = open(outp, 'w')
+    for line in open(inp).readlines():
+        if 'src/precommondefs.h' in line:
+            line = '#include "precommondefs.h"\n'
+        new_cml.write(line)
+    new_cml.close()
+    os.rename(outp, inp)
+
+    with open('precommondefs.h', 'w') as outp:
+        outp.write("""/***** Start of precommondefs.h *****/
+
+/* This is extracted from pyconfig.h from CPython.  It sets the macros
+   that affect the features we get from system include files.
+   It must not #include anything. */
+
+#ifndef __PYPY_PRECOMMONDEFS_H
+#define __PYPY_PRECOMMONDEFS_H
+
+
+/* Define on Darwin to activate all library features */
+#define _DARWIN_C_SOURCE 1
+/* This must be set to 64 on some systems to enable large file support. */
+#define _FILE_OFFSET_BITS 64
+/* Define on Linux to activate all library features */
+#define _GNU_SOURCE 1
+/* This must be defined on some systems to enable large file support. */
+#define _LARGEFILE_SOURCE 1
+/* Define on NetBSD to activate all library features */
+#define _NETBSD_SOURCE 1
+/* Define to activate features from IEEE Stds 1003.1-2001 */
+#ifndef _POSIX_C_SOURCE
+#  define _POSIX_C_SOURCE 200112L
+#endif
+/* Define on FreeBSD to activate all library features */
+#define __BSD_VISIBLE 1
+#define __XSI_VISIBLE 700
+/* Windows: winsock/winsock2 mess */
+#define WIN32_LEAN_AND_MEAN
+#ifdef _WIN64
+   typedef          __int64 Signed;
+   typedef unsigned __int64 Unsigned;
+#  define SIGNED_MIN LLONG_MIN
+#else
+   typedef          long Signed;
+   typedef unsigned long Unsigned;
+#  define SIGNED_MIN LONG_MIN
+#endif
+
+#if !defined(RPY_ASSERT) && !defined(RPY_LL_ASSERT) && !defined(NDEBUG)
+#  define NDEBUG
+#endif
+
+
+/* All functions and global variables declared anywhere should use
+   one of the following attributes:
+
+   RPY_EXPORTED:  the symbol is exported out of libpypy-c.so.
+
+   RPY_EXTERN:    the symbol is not exported out of libpypy-c.so, but
+                  otherwise works like 'extern' by being available to
+                  other C sources.
+
+   static:        as usual, this means the symbol is local to this C file.
+
+   Don't use _RPY_HIDDEN directly.  For tests involving building a custom
+   .so, translator/tool/cbuild.py overrides RPY_EXTERN so that it becomes
+   equal to RPY_EXPORTED.
+
+   Any function or global variable declared with no attribute at all is
+   a bug; please report or fix it.
+*/
+#ifdef __GNUC__
+#  define RPY_EXPORTED extern __attribute__((visibility("default")))
+#  define _RPY_HIDDEN  __attribute__((visibility("hidden")))
+#else
+#  define RPY_EXPORTED extern __declspec(dllexport)
+#  define _RPY_HIDDEN  /* nothing */
+#endif
+#ifndef RPY_EXTERN
+#  define RPY_EXTERN   extern _RPY_HIDDEN
+#endif
+
+
+#endif /* __PYPY_PRECOMMONDEFS_H */
+
+/***** End of precommondefs.h *****/
+""")
+
+# back up to pip package top
+for i in range(countdown-1):
+    os.chdir(os.path.pardir)
+
+# add cppyy module to cmake
+os.chdir('src/backend')
+inp = 'CMakeLists.txt'
+print('adding cppyy to cmake')
+outp = inp+'.new'
+new_cml = open(outp, 'w')
+for line in open(inp).readlines():
+    if 'add_subdirectory' in line and 'net' in line:
+        line += 'add_subdirectory (cppyy)\n'
+    new_cml.write(line)
+new_cml.close()
+os.rename(outp, inp)
+
+# done!
diff --git a/pypy/module/cpyext/api.py b/pypy/module/cpyext/api.py
--- a/pypy/module/cpyext/api.py
+++ b/pypy/module/cpyext/api.py
@@ -451,38 +451,10 @@
             error=_compute_error(error, restype), gil=gil,
             result_borrowed=result_borrowed, result_is_ll=result_is_ll)
         FUNCTIONS_BY_HEADER[header][func.__name__] = api_function
-
-        # ZZZ is this whole logic really needed???  It seems to be only
-        # for RPython code calling PyXxx() functions directly.  I would
-        # think that usually directly calling the function is clean
-        # enough now
-        def unwrapper_catch(space, *args):
-            try:
-                res = unwrapper(space, *args)
-            except OperationError as e:
-                if not hasattr(unwrapper.api_func, "error_value"):
-                    raise
-                state = space.fromcache(State)
-                state.set_exception(e)
-                if is_PyObject(restype):
-                    return None
-                else:
-                    return unwrapper.api_func.error_value
-            got_integer = isinstance(res, (int, long, float))
-            if isinstance(restype, lltype.Typedef):
-                real_restype = restype.OF
-            else:
-                real_restype = restype
-            expect_integer = (isinstance(real_restype, lltype.Primitive) and
-                            rffi.cast(restype, 0) == 0)
-            assert got_integer == expect_integer, (
-                'got %r not integer' % (res,))
-            return res
-        INTERPLEVEL_API[func.__name__] = unwrapper_catch  # used in tests
-
         unwrapper = api_function.get_unwrapper()
         unwrapper.func = func
         unwrapper.api_func = api_function
+        INTERPLEVEL_API[func.__name__] = unwrapper  # used in tests
         return unwrapper
     return decorate
 
@@ -769,22 +741,21 @@
             return space.gettypeobject(cls.typedef)
     check_name = "Py" + type_name + "_Check"
 
+    @cts.decl("int %s(void * obj)" % check_name, error=CANNOT_FAIL)
     def check(space, w_obj):
         "Implements the Py_Xxx_Check function"
         w_obj_type = space.type(w_obj)
         w_type = get_w_type(space)
         return (space.is_w(w_obj_type, w_type) or
                 space.issubtype_w(w_obj_type, w_type))
+
+    @cts.decl("int %sExact(void * obj)" % check_name, error=CANNOT_FAIL)
     def check_exact(space, w_obj):
         "Implements the Py_Xxx_CheckExact function"
         w_obj_type = space.type(w_obj)
         w_type = get_w_type(space)
         return space.is_w(w_obj_type, w_type)
 
-    check = cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)(
-        func_with_new_name(check, check_name))
-    check_exact = cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)(
-        func_with_new_name(check_exact, check_name + "Exact"))
     return check, check_exact
 
 pypy_debug_catch_fatal_exception = rffi.llexternal('pypy_debug_catch_fatal_exception', [], lltype.Void)
diff --git a/pypy/module/cpyext/number.py b/pypy/module/cpyext/number.py
--- a/pypy/module/cpyext/number.py
+++ b/pypy/module/cpyext/number.py
@@ -55,54 +55,59 @@
 def func_rename(newname):
     return lambda func: func_with_new_name(func, newname)
 
-def make_numbermethod(name, spacemeth):
+def make_numbermethod(cname, spacemeth):
     @cpython_api([PyObject, PyObject], PyObject)
-    @func_rename('PyNumber_%s' % (name,))
+    @func_rename(cname)
     def PyNumber_Method(space, w_o1, w_o2):
         meth = getattr(space, spacemeth)
         return meth(w_o1, w_o2)
+    return PyNumber_Method
 
 def make_unary_numbermethod(name, spacemeth):
     @cpython_api([PyObject], PyObject)
-    @func_rename('PyNumber_%s' % (name,))
+    @func_rename(cname)
     def PyNumber_Method(space, w_o1):
         meth = getattr(space, spacemeth)
         return meth(w_o1)
+    return PyNumber_Method
 
-def make_inplace_numbermethod(name, spacemeth):
+def make_inplace_numbermethod(cname, spacemeth):
     spacemeth = 'inplace_' + spacemeth.rstrip('_')
     @cpython_api([PyObject, PyObject], PyObject)
-    @func_rename('PyNumber_InPlace%s' % (name,))
+    @func_rename(cname)
     def PyNumber_Method(space, w_o1, w_o2):
         meth = getattr(space, spacemeth)
         return meth(w_o1, w_o2)
+    return PyNumber_Method
 
 for name, spacemeth in [
-    ('Add', 'add'),
-    ('Subtract', 'sub'),
-    ('Multiply', 'mul'),
-    ('Divide', 'div'),
-    ('FloorDivide', 'floordiv'),
-    ('TrueDivide', 'truediv'),
-    ('Remainder', 'mod'),
-    ('Lshift', 'lshift'),
-    ('Rshift', 'rshift'),
-    ('And', 'and_'),
-    ('Xor', 'xor'),
-    ('Or', 'or_'),
-    ('Divmod', 'divmod'),
-    ('MatrixMultiply', 'matmul')
-    ]:
-    make_numbermethod(name, spacemeth)
+        ('Add', 'add'),
+        ('Subtract', 'sub'),
+        ('Multiply', 'mul'),
+        ('Divide', 'div'),
+        ('FloorDivide', 'floordiv'),
+        ('TrueDivide', 'truediv'),
+        ('Remainder', 'mod'),
+        ('Lshift', 'lshift'),
+        ('Rshift', 'rshift'),
+        ('And', 'and_'),
+        ('Xor', 'xor'),
+        ('Or', 'or_'),
+        ('Divmod', 'divmod'),
+        ('MatrixMultiply', 'matmul')]:
+    cname = 'PyNumber_%s' % (name,)
+    globals()[cname] = make_numbermethod(cname, spacemeth)
     if name != 'Divmod':
-        make_inplace_numbermethod(name, spacemeth)
+        cname = 'PyNumber_InPlace%s' % (name,)
+        globals()[cname] = make_inplace_numbermethod(cname, spacemeth)
 
 for name, spacemeth in [
-    ('Negative', 'neg'),
-    ('Positive', 'pos'),
-    ('Absolute', 'abs'),
-    ('Invert', 'invert')]:
-    make_unary_numbermethod(name, spacemeth)
+        ('Negative', 'neg'),
+        ('Positive', 'pos'),
+        ('Absolute', 'abs'),
+        ('Invert', 'invert')]:
+    cname = 'PyNumber_%s' % (name,)
+    globals()[cname] = make_unary_numbermethod(cname, spacemeth)
 
 @cpython_api([PyObject, PyObject, PyObject], PyObject)
 def PyNumber_Power(space, w_o1, w_o2, w_o3):
diff --git a/pypy/module/cpyext/test/test_floatobject.py b/pypy/module/cpyext/test/test_floatobject.py
--- a/pypy/module/cpyext/test/test_floatobject.py
+++ b/pypy/module/cpyext/test/test_floatobject.py
@@ -95,3 +95,15 @@
 
              Py_RETURN_NONE;"""),
             ])
+
+    def test_PyFloat_Check(self):
+        module = self.import_extension('foo', [
+            ("test", "METH_NOARGS",
+             """
+             PyObject* pyobj = PyFloat_FromDouble(1.0);
+             PyFloatObject* pfo = (PyFloatObject*)pyobj;
+             int res = PyFloat_Check(pyobj) && PyFloat_CheckExact(pyobj) &&
+                PyFloat_Check(pfo) && PyFloat_CheckExact(pfo);
+             return PyLong_FromLong(res);"""),
+            ])
+        assert module.test() == 1
diff --git a/pypy/module/cpyext/test/test_iterator.py b/pypy/module/cpyext/test/test_iterator.py
--- a/pypy/module/cpyext/test/test_iterator.py
+++ b/pypy/module/cpyext/test/test_iterator.py
@@ -1,5 +1,8 @@
+import pytest
+from pypy.interpreter.error import OperationError
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
+from pypy.module.cpyext.iterator import PyIter_Next
 
 
 class TestIterator(BaseApiTest):
@@ -14,13 +17,12 @@
         assert space.unwrap(api.PyIter_Next(w_iter)) == 1
         assert space.unwrap(api.PyIter_Next(w_iter)) == 2
         assert space.unwrap(api.PyIter_Next(w_iter)) == 3
-        assert api.PyIter_Next(w_iter) is None
-        assert not api.PyErr_Occurred()
+        assert PyIter_Next(space, w_iter) is None
 
-    def test_iternext_error(self,space, api):
-        assert api.PyIter_Next(space.w_None) is None
-        assert api.PyErr_Occurred() is space.w_TypeError
-        api.PyErr_Clear()
+    def test_iternext_error(self, space):
+        with pytest.raises(OperationError) as excinfo:
+            PyIter_Next(space, space.w_None)
+        assert excinfo.value.w_type is space.w_TypeError
 
 
 class AppTestIterator(AppTestCpythonExtensionBase):
diff --git a/pypy/module/cpyext/test/test_listobject.py b/pypy/module/cpyext/test/test_listobject.py
--- a/pypy/module/cpyext/test/test_listobject.py
+++ b/pypy/module/cpyext/test/test_listobject.py
@@ -1,6 +1,8 @@
-from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
 from pypy.module.cpyext.pyobject import from_ref
+from pypy.module.cpyext.listobject import (
+    PyList_Check, PyList_CheckExact, PyList_Size)
 
 class TestListObject(BaseApiTest):
     def test_list(self, space, api):
@@ -11,15 +13,15 @@
         """)
 
         l = api.PyList_New(0)
-        assert api.PyList_Check(l)
-        assert api.PyList_CheckExact(l)
+        assert PyList_Check(space, l)
+        assert PyList_CheckExact(space, l)
 
         l = space.call_function(L)
-        assert api.PyList_Check(l)
-        assert not api.PyList_CheckExact(l)
+        assert PyList_Check(space, l)
+        assert not PyList_CheckExact(space, l)
 
-        assert not api.PyList_Check(space.newtuple([]))
-        assert not api.PyList_CheckExact(space.newtuple([]))
+        assert not PyList_Check(space, space.newtuple([]))
+        assert not PyList_CheckExact(space, space.newtuple([]))
 
     def test_get_size(self, space, api):
         l = api.PyList_New(0)
@@ -27,12 +29,11 @@
         api.PyList_Append(l, space.wrap(3))
         assert api.PyList_GET_SIZE(l) == 1
 
-    def test_size(self, space, api):
+    def test_size(self, space):
         l = space.newlist([space.w_None, space.w_None])
-        assert api.PyList_Size(l) == 2
-        assert api.PyList_Size(space.w_None) == -1
-        assert api.PyErr_Occurred() is space.w_TypeError
-        api.PyErr_Clear()
+        assert PyList_Size(space, l) == 2
+        with raises_w(space, TypeError):
+            PyList_Size(space, space.w_None)
 
     def test_insert(self, space, api):
         w_l = space.newlist([space.w_None, space.w_None])
diff --git a/pypy/module/cpyext/test/test_longobject.py b/pypy/module/cpyext/test/test_longobject.py
--- a/pypy/module/cpyext/test/test_longobject.py
+++ b/pypy/module/cpyext/test/test_longobject.py
@@ -1,10 +1,14 @@
-import sys, py
+import sys
+import pytest
+from pypy.interpreter.error import OperationError
 from rpython.rtyper.lltypesystem import rffi, lltype
 from rpython.rlib.rarithmetic import maxint
 from pypy.objspace.std.longobject import W_LongObject
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
-
+from pypy.module.cpyext.longobject import (PyLong_Check, PyLong_CheckExact,
+    PyLong_FromLong, PyLong_AsLong, PyLong_AsUnsignedLong, PyLong_AsLongLong,
+    PyLong_AsUnsignedLongLong, PyLong_AsUnsignedLongLongMask)
 
 class TestLongObject(BaseApiTest):
     def test_FromLong(self, space, api):
@@ -16,24 +20,25 @@
         assert isinstance(w_value, W_LongObject)
         assert space.unwrap(w_value) == sys.maxint
 
-    def test_aslong(self, space, api):
-        w_value = api.PyLong_FromLong((sys.maxint - 1) / 2)
+    def test_aslong(self, space):
+        w_value = PyLong_FromLong(space, (sys.maxint - 1) / 2)
         assert isinstance(w_value, W_LongObject)
 
         w_value = space.mul(w_value, space.wrap(2))
         assert isinstance(w_value, W_LongObject)
-        value = api.PyLong_AsLong(w_value)
+        value = PyLong_AsLong(space, w_value)
         assert value == (sys.maxint - 1)
 
         w_value = space.mul(w_value, space.wrap(2))
-
-        value = api.PyLong_AsLong(w_value)
-        assert value == -1 and api.PyErr_Occurred() is space.w_OverflowError
-        api.PyErr_Clear()
-        value = api.PyLong_AsUnsignedLong(w_value)
+        with pytest.raises(OperationError) as excinfo:
+            PyLong_AsLong(space, w_value)
+        assert excinfo.value.w_type is space.w_OverflowError
+        value = PyLong_AsUnsignedLong(space, w_value)
         assert value == (sys.maxint - 1) * 2
 
-        self.raises(space, api, OverflowError, api.PyLong_AsUnsignedLong, space.wrap(-1))
+        with pytest.raises(OperationError) as excinfo:
+            PyLong_AsUnsignedLong(space, space.newint(-1))
+        assert excinfo.value.w_type is space.w_OverflowError
 
     def test_as_ssize_t(self, space, api):
         w_value = space.newlong(2)
@@ -52,12 +57,12 @@
 
     def test_type_check(self, space, api):
         w_l = space.wrap(sys.maxint + 1)
-        assert api.PyLong_Check(w_l)
-        assert api.PyLong_CheckExact(w_l)
+        assert PyLong_Check(space, w_l)
+        assert PyLong_CheckExact(space, w_l)
 
         w_i = space.wrap(sys.maxint)
-        assert api.PyLong_Check(w_i)
-        assert api.PyLong_CheckExact(w_i)
+        assert PyLong_Check(space, w_i)
+        assert PyLong_CheckExact(space, w_i)
 
         L = space.appexec([], """():
             class L(int):
@@ -65,23 +70,25 @@
             return L
         """)
         l = space.call_function(L)
-        assert api.PyLong_Check(l)
-        assert not api.PyLong_CheckExact(l)
+        assert PyLong_Check(space, l)
+        assert not PyLong_CheckExact(space, l)
 
-    def test_as_longlong(self, space, api):
-        assert api.PyLong_AsLongLong(space.wrap(1<<62)) == 1<<62
-        assert api.PyLong_AsLongLong(space.wrap(1<<63)) == -1
-        api.PyErr_Clear()
+    def test_as_longlong(self, space):
+        assert PyLong_AsLongLong(space, space.wrap(1 << 62)) == 1 << 62
+        with pytest.raises(OperationError) as excinfo:
+            PyLong_AsLongLong(space, space.wrap(1 << 63))
+        assert excinfo.value.w_type is space.w_OverflowError
 
-        assert api.PyLong_AsUnsignedLongLong(space.wrap(1<<63)) == 1<<63
-        assert api.PyLong_AsUnsignedLongLong(space.wrap(1<<64)) == (1<<64) - 1
-        assert api.PyErr_Occurred()
-        api.PyErr_Clear()
+        assert PyLong_AsUnsignedLongLong(space, space.wrap(1 << 63)) == 1 << 63
+        with pytest.raises(OperationError) as excinfo:
+            PyLong_AsUnsignedLongLong(space, space.wrap(1 << 64))
+        assert excinfo.value.w_type is space.w_OverflowError
 
-        assert api.PyLong_AsUnsignedLongLongMask(
-            space.wrap(1<<64)) == 0
+        assert PyLong_AsUnsignedLongLongMask(space, space.wrap(1 << 64)) == 0
 
-        self.raises(space, api, OverflowError, api.PyLong_AsUnsignedLongLong, space.wrap(-1))
+        with pytest.raises(OperationError) as excinfo:
+            PyLong_AsUnsignedLongLong(space, space.newint(-1))
+        assert excinfo.value.w_type is space.w_OverflowError
 
     def test_as_long_and_overflow(self, space, api):
         overflow = lltype.malloc(rffi.CArrayPtr(rffi.INT_real).TO, 1, flavor='raw')
@@ -126,10 +133,6 @@
         assert api.PyLong_AsVoidPtr(w_l) == p
 
     def test_sign_and_bits(self, space, api):
-        if space.is_true(space.lt(space.sys.get('version_info'),
-                                  space.wrap((2, 7)))):
-            py.test.skip("unsupported before Python 2.7")
-
         assert api._PyLong_Sign(space.wraplong(0L)) == 0
         assert api._PyLong_Sign(space.wraplong(2L)) == 1
         assert api._PyLong_Sign(space.wraplong(-2L)) == -1
@@ -328,6 +331,6 @@
                     ret = PyLong_FromLong(-1);
                 Py_DECREF(obj);
                 return ret;
-             """),])
+             """)])
         assert module.has_sub() == 0
         assert module.has_pow() == 0
diff --git a/pypy/module/cpyext/test/test_module.py b/pypy/module/cpyext/test/test_module.py
--- a/pypy/module/cpyext/test/test_module.py
+++ b/pypy/module/cpyext/test/test_module.py
@@ -1,4 +1,6 @@
-from pypy.module.cpyext.modsupport import PyModule_New
+import pytest
+from pypy.interpreter.error import OperationError
+from pypy.module.cpyext.modsupport import PyModule_New, PyModule_GetName
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
 from rpython.rtyper.lltypesystem import rffi
@@ -11,13 +13,15 @@
         assert space.eq_w(space.getattr(w_mod, space.newtext('__name__')),
                           space.newtext('testname'))
 
-    def test_module_getname(self, space, api):
+    def test_module_getname(self, space):
         w_sys = space.wrap(space.sys)
-        p = api.PyModule_GetName(w_sys)
+        p = PyModule_GetName(space, w_sys)
         assert rffi.charp2str(p) == 'sys'
-        p2 = api.PyModule_GetName(w_sys)
+        p2 = PyModule_GetName(space, w_sys)
         assert p2 == p
-        self.raises(space, api, SystemError, api.PyModule_GetName, space.w_True)
+        with pytest.raises(OperationError) as excinfo:
+            PyModule_GetName(space, space.w_True)
+        assert excinfo.value.w_type is space.w_SystemError
 
 
 class AppTestModuleObject(AppTestCpythonExtensionBase):
diff --git a/pypy/module/cpyext/test/test_ndarrayobject.py b/pypy/module/cpyext/test/test_ndarrayobject.py
--- a/pypy/module/cpyext/test/test_ndarrayobject.py
+++ b/pypy/module/cpyext/test/test_ndarrayobject.py
@@ -1,13 +1,16 @@
-import py
+import pytest
 import os
+from pypy.interpreter.error import OperationError
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
 from rpython.rtyper.lltypesystem import rffi, lltype
 from pypy.module.micronumpy.ndarray import W_NDimArray
 from pypy.module.micronumpy.descriptor import get_dtype_cache
 import pypy.module.micronumpy.constants as NPY
+from pypy.module.cpyext.ndarrayobject import (
+    _PyArray_FromAny, _PyArray_FromObject)
 
-py.test.skip("Micronumpy not yet supported on py3k.")
+pytest.skip("Micronumpy not yet supported on py3k.")
 
 def scalar(space):
     dtype = get_dtype_cache(space).w_float64dtype
@@ -89,19 +92,19 @@
         ptr = rffi.cast(rffi.DOUBLEP, api._PyArray_DATA(a))
         assert ptr[0] == 10.
 
-    def test_FromAny(self, space, api):
+    def test_FromAny(self, space):
         a = array(space, [10, 5, 3])
-        assert api._PyArray_FromAny(a, None, 0, 0, 0, NULL) is a
-        assert api._PyArray_FromAny(a, None, 1, 4, 0, NULL) is a
-        self.raises(space, api, ValueError, api._PyArray_FromAny,
-                    a, None, 4, 5, 0, NULL)
+        assert _PyArray_FromAny(space, a, None, 0, 0, 0, NULL) is a
+        assert _PyArray_FromAny(space, a, None, 1, 4, 0, NULL) is a
+        with pytest.raises(OperationError) as excinfo:
+            _PyArray_FromAny(space, a, None, 4, 5, 0, NULL)
 
-    def test_FromObject(self, space, api):
+    def test_FromObject(self, space):
         a = array(space, [10, 5, 3])
-        assert api._PyArray_FromObject(a, a.get_dtype().num, 0, 0) is a
-        exc = self.raises(space, api, ValueError, api._PyArray_FromObject,
-                    a, 11, 4, 5)
-        assert exc.errorstr(space).find('desired') >= 0
+        assert _PyArray_FromObject(space, a, a.get_dtype().num, 0, 0) is a
+        with pytest.raises(OperationError) as excinfo:
+            _PyArray_FromObject(space, a, 11, 4, 5)
+        assert excinfo.value.errorstr(space).find('desired') >= 0
 
     def test_list_from_fixedptr(self, space, api):
         A = lltype.GcArray(lltype.Float)
@@ -218,7 +221,7 @@
         assert res.get_scalar_value().imag == 4.
 
     def _test_Ufunc_FromFuncAndDataAndSignature(self, space, api):
-        py.test.skip('preliminary non-translated test')
+        pytest.skip('preliminary non-translated test')
         '''
         PyUFuncGenericFunction funcs[] = {&double_times2, &int_times2};
         char types[] = { NPY_DOUBLE,NPY_DOUBLE, NPY_INT, NPY_INT };
@@ -365,7 +368,7 @@
     def test_ufunc(self):
         if self.runappdirect:
             from numpy import arange
-            py.test.xfail('segfaults on cpython: PyUFunc_API == NULL?')
+            pytest.xfail('segfaults on cpython: PyUFunc_API == NULL?')
         else:
             from _numpypy.multiarray import arange
         mod = self.import_extension('foo', [
diff --git a/pypy/module/cpyext/test/test_number.py b/pypy/module/cpyext/test/test_number.py
--- a/pypy/module/cpyext/test/test_number.py
+++ b/pypy/module/cpyext/test/test_number.py
@@ -1,68 +1,77 @@
+import pytest
 from rpython.rtyper.lltypesystem import lltype
+from pypy.interpreter.error import OperationError
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
+from pypy.module.cpyext.number import (
+    PyIndex_Check, PyNumber_Check, PyNumber_Long,
+    PyNumber_Index, PyNumber_Add,
+    PyNumber_Multiply, PyNumber_InPlaceMultiply, PyNumber_Absolute,
+    PyNumber_Power, PyNumber_InPlacePower)
+from pypy.module.cpyext.floatobject import PyFloat_Check
+from pypy.module.cpyext.longobject import PyLong_CheckExact
+from pypy.module.cpyext.object import PyObject_Size
 
 class TestIterator(BaseApiTest):
-    def test_check(self, space, api):
-        assert api.PyIndex_Check(space.wrap(12))
-        assert api.PyIndex_Check(space.wraplong(-12L))
-        assert not api.PyIndex_Check(space.wrap(12.1))
-        assert not api.PyIndex_Check(space.wrap('12'))
+    def test_check(self, space):
+        assert PyIndex_Check(space, space.wrap(12))
+        assert PyIndex_Check(space, space.wraplong(-12L))
+        assert not PyIndex_Check(space, space.wrap(12.1))
+        assert not PyIndex_Check(space, space.wrap('12'))
 
-        assert api.PyNumber_Check(space.wrap(12))
-        assert api.PyNumber_Check(space.wraplong(-12L))
-        assert api.PyNumber_Check(space.wrap(12.1))
-        assert not api.PyNumber_Check(space.wrap('12'))
-        assert api.PyNumber_Check(space.wrap(1+3j))
+        assert PyNumber_Check(space, space.wrap(12))
+        assert PyNumber_Check(space, space.wraplong(-12L))
+        assert PyNumber_Check(space, space.wrap(12.1))
+        assert not PyNumber_Check(space, space.wrap('12'))
+        assert PyNumber_Check(space, space.wrap(1 + 3j))
 
-    def test_number_long(self, space, api):
-        w_l = api.PyNumber_Long(space.wrap(123))
-        assert api.PyLong_CheckExact(w_l)
-        w_l = api.PyNumber_Long(space.wrap("123"))
-        assert api.PyLong_CheckExact(w_l)
+    def test_number_long(self, space):
+        w_l = PyNumber_Long(space, space.wrap(123))
+        assert PyLong_CheckExact(space, w_l)
+        w_l = PyNumber_Long(space, space.wrap("123"))
+        assert PyLong_CheckExact(space, w_l)
 
-    def test_number_long2(self, space, api):
-        w_l = api.PyNumber_Long(space.wraplong(123L))
-        assert api.PyLong_CheckExact(w_l)
-        w_l = api.PyNumber_Long(space.wrap(2 << 65))
-        assert api.PyLong_CheckExact(w_l)
-        w_l = api.PyNumber_Long(space.wrap(42.3))
-        assert api.PyLong_CheckExact(w_l)
-        w_l = api.PyNumber_Long(space.wrap("42"))
-        assert api.PyLong_CheckExact(w_l)
+    def test_number_long2(self, space):
+        w_l = PyNumber_Long(space, space.wraplong(123L))
+        assert PyLong_CheckExact(space, w_l)
+        w_l = PyNumber_Long(space, space.wrap(2 << 65))
+        assert PyLong_CheckExact(space, w_l)
+        w_l = PyNumber_Long(space, space.wrap(42.3))
+        assert PyLong_CheckExact(space, w_l)
+        w_l = PyNumber_Long(space, space.wrap("42"))
+        assert PyLong_CheckExact(space, w_l)
 
-    def test_number_index(self, space, api):
-        w_l = api.PyNumber_Index(space.wraplong(123L))
-        assert api.PyLong_CheckExact(w_l)
-        w_l = api.PyNumber_Index(space.wrap(42.3))
-        assert w_l is None
-        api.PyErr_Clear()
+    def test_number_index(self, space):
+        w_l = PyNumber_Index(space, space.wraplong(123L))
+        assert PyLong_CheckExact(space, w_l)
+        with pytest.raises(OperationError):
+            PyNumber_Index(space, space.wrap(42.3))
 
     def test_numbermethods(self, space, api):
         assert "ab" == space.unwrap(
-            api.PyNumber_Add(space.wrap("a"), space.wrap("b")))
+            PyNumber_Add(space, space.wrap("a"), space.wrap("b")))
         assert "aaa" == space.unwrap(
-            api.PyNumber_Multiply(space.wrap("a"), space.wrap(3)))
+            PyNumber_Multiply(space, space.wrap("a"), space.wrap(3)))
 
         w_l = space.newlist([1, 2, 3])
-        w_l2 = api.PyNumber_Multiply(w_l, space.wrap(3))
-        assert api.PyObject_Size(w_l2) == 9
-        assert api.PyObject_Size(w_l) == 3
+        w_l2 = PyNumber_Multiply(space, w_l, space.wrap(3))
+        assert PyObject_Size(space, w_l2) == 9
+        assert PyObject_Size(space, w_l) == 3
 
-        w_l3 = api.PyNumber_InPlaceMultiply(w_l, space.wrap(3))
-        assert api.PyObject_Size(w_l) == 9
+        w_l3 = PyNumber_InPlaceMultiply(space, w_l, space.wrap(3))
+        assert PyObject_Size(space, w_l) == 9
         assert w_l3 is w_l
 
         # unary function
-        assert 9 == space.unwrap(api.PyNumber_Absolute(space.wrap(-9)))
+        assert 9 == space.unwrap(PyNumber_Absolute(space, space.wrap(-9)))
 
         # power
         assert 9 == space.unwrap(
-            api.PyNumber_Power(space.wrap(3), space.wrap(2), space.w_None))
+            PyNumber_Power(space, space.wrap(3), space.wrap(2), space.w_None))
         assert 4 == space.unwrap(
-            api.PyNumber_Power(space.wrap(3), space.wrap(2), space.wrap(5)))
+            PyNumber_Power(space, space.wrap(3), space.wrap(2), space.wrap(5)))
         assert 9 == space.unwrap(
-            api.PyNumber_InPlacePower(space.wrap(3), space.wrap(2), space.w_None))
+            PyNumber_InPlacePower(space, space.wrap(3), space.wrap(2), space.w_None))
 
 
 class AppTestCNumber(AppTestCpythonExtensionBase):
diff --git a/pypy/module/cpyext/test/test_object.py b/pypy/module/cpyext/test/test_object.py
--- a/pypy/module/cpyext/test/test_object.py
+++ b/pypy/module/cpyext/test/test_object.py
@@ -1,10 +1,16 @@
-import py, pytest
+import pytest
 
-from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
-from rpython.rtyper.lltypesystem import rffi, lltype
+from rpython.rtyper.lltypesystem import rffi
 from pypy.module.cpyext.api import (
     Py_LT, Py_LE, Py_NE, Py_EQ, Py_GE, Py_GT)
+from pypy.module.cpyext.object import (
+    PyObject_IsTrue, PyObject_Not, PyObject_GetAttrString,
+    PyObject_DelAttrString, PyObject_GetAttr, PyObject_DelAttr,
+    PyObject_GetItem, PyObject_RichCompareBool,
+    PyObject_IsInstance, PyObject_IsSubclass, PyObject_AsFileDescriptor,
+    PyObject_Hash)
 
 class TestObject(BaseApiTest):
     def test_IsTrue(self, space, api):
@@ -25,9 +31,10 @@
                     raise ValueError
             return C()""")
 
-        assert api.PyObject_IsTrue(w_obj) == -1
-        assert api.PyObject_Not(w_obj) == -1
-        api.PyErr_Clear()
+        with raises_w(space, ValueError):
+            PyObject_IsTrue(space, w_obj)
+        with raises_w(space, ValueError):
+            PyObject_Not(space, w_obj)
 
     def test_HasAttr(self, space, api):
         hasattr_ = lambda w_obj, name: api.PyObject_HasAttr(w_obj,
@@ -59,22 +66,21 @@
         rffi.free_charp(buf)
         assert space.unwrap(space.getattr(w_obj, space.wrap('test'))) == 20
 
-    def test_getattr(self, space, api):
+    def test_getattr(self, space):
         charp1 = rffi.str2charp("__len__")
         charp2 = rffi.str2charp("not_real")
-        assert api.PyObject_GetAttrString(space.wrap(""), charp1)
-        assert not api.PyObject_GetAttrString(space.wrap(""), charp2)
-        assert api.PyErr_Occurred() is space.w_AttributeError
-        api.PyErr_Clear()
-        assert api.PyObject_DelAttrString(space.wrap(""), charp1) == -1
-        assert api.PyErr_Occurred() is space.w_AttributeError
-        api.PyErr_Clear()
+        assert PyObject_GetAttrString(space, space.wrap(""), charp1)
+
+        with raises_w(space, AttributeError):
+            PyObject_GetAttrString(space, space.wrap(""), charp2)
+        with raises_w(space, AttributeError):
+            PyObject_DelAttrString(space, space.wrap(""), charp1)
         rffi.free_charp(charp1)
         rffi.free_charp(charp2)
 
-        assert api.PyObject_GetAttr(space.wrap(""), space.wrap("__len__"))
-        assert api.PyObject_DelAttr(space.wrap(""), space.wrap("__len__")) == -1
-        api.PyErr_Clear()
+        assert PyObject_GetAttr(space, space.wrap(""), space.wrap("__len__"))
+        with raises_w(space, AttributeError):
+            PyObject_DelAttr(space, space.wrap(""), space.wrap("__len__"))
 
     def test_getitem(self, space, api):
         w_t = space.wrap((1, 2, 3, 4, 5))
@@ -88,9 +94,8 @@
         assert space.getitem(w_d, space.wrap("key")) is space.w_None
 
         assert api.PyObject_DelItem(w_d, space.wrap("key")) == 0
-        assert api.PyObject_GetItem(w_d, space.wrap("key")) is None
-        assert api.PyErr_Occurred() is space.w_KeyError
-        api.PyErr_Clear()
+        with raises_w(space, KeyError):
+            PyObject_GetItem(space, w_d, space.wrap("key"))
 
     def test_size(self, space, api):
         assert api.PyObject_Size(space.newlist([space.w_None])) == 1
@@ -119,9 +124,9 @@
             w_o2 = space.wrap(o2)
 
             for opid, expected in [
-                    (Py_LT, o1 <  o2), (Py_LE, o1 <= o2),
+                    (Py_LT, o1 < o2), (Py_LE, o1 <= o2),
                     (Py_NE, o1 != o2), (Py_EQ, o1 == o2),
-                    (Py_GT, o1 >  o2), (Py_GE, o1 >= o2)]:
+                    (Py_GT, o1 > o2), (Py_GE, o1 >= o2)]:
                 assert compare(w_o1, w_o2, opid) == expected
 
         test_compare(1, 2)
@@ -129,9 +134,8 @@
         test_compare('2', '1')
 
         w_i = space.wrap(1)
-        assert api.PyObject_RichCompareBool(w_i, w_i, 123456) == -1
-        assert api.PyErr_Occurred() is space.w_SystemError
-        api.PyErr_Clear()
+        with raises_w(space, SystemError):
+            PyObject_RichCompareBool(space, w_i, w_i, 123456)
 
     def test_IsInstance(self, space, api):
         assert api.PyObject_IsInstance(space.wrap(1), space.w_int) == 1
@@ -140,8 +144,8 @@
         assert api.PyObject_IsInstance(
             space.wrap(1), space.newtuple([space.w_int, space.w_float])) == 1
         assert api.PyObject_IsInstance(space.w_type, space.w_type) == 1
-        assert api.PyObject_IsInstance(space.wrap(1), space.w_None) == -1
-        api.PyErr_Clear()
+        with raises_w(space, TypeError):
+            PyObject_IsInstance(space, space.wrap(1), space.w_None)
 
     def test_IsSubclass(self, space, api):
         assert api.PyObject_IsSubclass(space.w_type, space.w_type) == 1
@@ -149,14 +153,13 @@
         assert api.PyObject_IsSubclass(space.w_object, space.w_type) == 0
         assert api.PyObject_IsSubclass(
             space.w_type, space.newtuple([space.w_int, space.w_type])) == 1
-        assert api.PyObject_IsSubclass(space.wrap(1), space.w_type) == -1
-        api.PyErr_Clear()
+        with raises_w(space, TypeError):
+            PyObject_IsSubclass(space, space.wrap(1), space.w_type)
 
     def test_fileno(self, space, api):
         assert api.PyObject_AsFileDescriptor(space.wrap(1)) == 1
-        assert api.PyObject_AsFileDescriptor(space.wrap(-20)) == -1
-        assert api.PyErr_Occurred() is space.w_ValueError
-        api.PyErr_Clear()
+        with raises_w(space, ValueError):
+            PyObject_AsFileDescriptor(space, space.wrap(-20))
 
         w_File = space.appexec([], """():
             class File:
@@ -169,9 +172,8 @@
     def test_hash(self, space, api):
         assert api.PyObject_Hash(space.wrap(72)) == 72
         assert api.PyObject_Hash(space.wrap(-1)) == -2
-        assert (api.PyObject_Hash(space.wrap([])) == -1 and
-            api.PyErr_Occurred() is space.w_TypeError)
-        api.PyErr_Clear()
+        with raises_w(space, TypeError):
+            PyObject_Hash(space, space.wrap([]))
 
     def test_hash_double(self, space, api):
         assert api._Py_HashDouble(72.0) == 72
@@ -195,7 +197,7 @@
         from pypy.interpreter import gateway
 
         AppTestCpythonExtensionBase.setup_class.im_func(cls)
-        tmpname = str(py.test.ensuretemp('out', dir=0))
+        tmpname = str(pytest.ensuretemp('out', dir=0))
         cls.w_tmpname = cls.space.wrap(tmpname)
 
         if not cls.runappdirect:
diff --git a/pypy/module/cpyext/test/test_pyerrors.py b/pypy/module/cpyext/test/test_pyerrors.py
--- a/pypy/module/cpyext/test/test_pyerrors.py
+++ b/pypy/module/cpyext/test/test_pyerrors.py
@@ -5,9 +5,7 @@
 from pypy.module.cpyext.state import State
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
-from rpython.rtyper.lltypesystem import rffi, ll2ctypes
-
-from pypy.interpreter.gateway import interp2app
+from rpython.rtyper.lltypesystem import rffi
 
 class TestExceptions(BaseApiTest):
     def test_GivenExceptionMatches(self, space, api):
@@ -61,13 +59,6 @@
         assert space.eq_w(state.operror.w_type, space.w_MemoryError)
         api.PyErr_Clear()
 
-    def test_BadArgument(self, space, api):
-        ret = api.PyErr_BadArgument()
-        state = space.fromcache(State)
-        assert space.eq_w(state.operror.w_type, space.w_TypeError)
-        assert ret == 0
-        api.PyErr_Clear()
-
     def test_Warning(self, space, api, capfd):
         message = rffi.str2charp("this is a warning")
         api.PyErr_WarnEx(None, message, 1)
diff --git a/pypy/module/cpyext/test/test_pyfile.py b/pypy/module/cpyext/test/test_pyfile.py
--- a/pypy/module/cpyext/test/test_pyfile.py
+++ b/pypy/module/cpyext/test/test_pyfile.py
@@ -1,8 +1,8 @@
+import pytest
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.object import Py_PRINT_RAW
 from rpython.rtyper.lltypesystem import rffi
 from rpython.tool.udir import udir
-import pytest
 
 class TestFile(BaseApiTest):
 
diff --git a/pypy/module/cpyext/test/test_pystrtod.py b/pypy/module/cpyext/test/test_pystrtod.py
--- a/pypy/module/cpyext/test/test_pystrtod.py
+++ b/pypy/module/cpyext/test/test_pystrtod.py
@@ -1,67 +1,62 @@
 import math
 
 from pypy.module.cpyext import pystrtod
-from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
 from rpython.rtyper.lltypesystem import rffi
 from rpython.rtyper.lltypesystem import lltype
+from pypy.module.cpyext.pystrtod import PyOS_string_to_double
 
 
 class TestPyOS_string_to_double(BaseApiTest):
 
-    def test_simple_float(self, api):
+    def test_simple_float(self, space):
         s = rffi.str2charp('0.4')
         null = lltype.nullptr(rffi.CCHARPP.TO)
-        r = api.PyOS_string_to_double(s, null, None)
+        r = PyOS_string_to_double(space, s, null, None)
         assert r == 0.4
         rffi.free_charp(s)
 
-    def test_empty_string(self, api):
+    def test_empty_string(self, space):
         s = rffi.str2charp('')
         null = lltype.nullptr(rffi.CCHARPP.TO)
-        r = api.PyOS_string_to_double(s, null, None)
-        assert r == -1.0
-        raises(ValueError)
-        api.PyErr_Clear()
+        with raises_w(space, ValueError):
+            PyOS_string_to_double(space, s, null, None)
         rffi.free_charp(s)
 
-    def test_bad_string(self, api):
+    def test_bad_string(self, space):
         s = rffi.str2charp(' 0.4')
         null = lltype.nullptr(rffi.CCHARPP.TO)
-        r = api.PyOS_string_to_double(s, null, None)
-        assert r == -1.0
-        raises(ValueError)
-        api.PyErr_Clear()
+        with raises_w(space, ValueError):
+            PyOS_string_to_double(space, s, null, None)
         rffi.free_charp(s)
 
-    def test_overflow_pos(self, api):
+    def test_overflow_pos(self, space):
         s = rffi.str2charp('1e500')
         null = lltype.nullptr(rffi.CCHARPP.TO)
-        r = api.PyOS_string_to_double(s, null, None)
+        r = PyOS_string_to_double(space, s, null, None)
         assert math.isinf(r)
         assert r > 0
         rffi.free_charp(s)
 
-    def test_overflow_neg(self, api):
+    def test_overflow_neg(self, space):
         s = rffi.str2charp('-1e500')
         null = lltype.nullptr(rffi.CCHARPP.TO)
-        r = api.PyOS_string_to_double(s, null, None)
+        r = PyOS_string_to_double(space, s, null, None)
         assert math.isinf(r)
         assert r < 0
         rffi.free_charp(s)
 
-    def test_overflow_exc(self, space, api):
+    def test_overflow_exc(self, space):
         s = rffi.str2charp('1e500')
         null = lltype.nullptr(rffi.CCHARPP.TO)
-        r = api.PyOS_string_to_double(s, null, space.w_ValueError)
-        assert r == -1.0
-        raises(ValueError)
-        api.PyErr_Clear()
+        with raises_w(space, ValueError):
+            PyOS_string_to_double(space, s, null, space.w_ValueError)
         rffi.free_charp(s)
 
-    def test_endptr_number(self, api):
+    def test_endptr_number(self, space):
         s = rffi.str2charp('0.4')
         endp = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
-        r = api.PyOS_string_to_double(s, endp, None)
+        r = PyOS_string_to_double(space, s, endp, None)
         assert r == 0.4
         endp_addr = rffi.cast(rffi.LONG, endp[0])
         s_addr = rffi.cast(rffi.LONG, s)
@@ -69,10 +64,10 @@
         rffi.free_charp(s)
         lltype.free(endp, flavor='raw')
 
-    def test_endptr_tail(self, api):
+    def test_endptr_tail(self, space):
         s = rffi.str2charp('0.4 foo')
         endp = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
-        r = api.PyOS_string_to_double(s, endp, None)
+        r = PyOS_string_to_double(space, s, endp, None)
         assert r == 0.4
         endp_addr = rffi.cast(rffi.LONG, endp[0])
         s_addr = rffi.cast(rffi.LONG, s)
@@ -80,16 +75,14 @@
         rffi.free_charp(s)
         lltype.free(endp, flavor='raw')
 
-    def test_endptr_no_conversion(self, api):
+    def test_endptr_no_conversion(self, space):
         s = rffi.str2charp('foo')
         endp = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
-        r = api.PyOS_string_to_double(s, endp, None)
-        assert r == -1.0
-        raises(ValueError)
+        with raises_w(space, ValueError):
+            PyOS_string_to_double(space, s, endp, None)
         endp_addr = rffi.cast(rffi.LONG, endp[0])
         s_addr = rffi.cast(rffi.LONG, s)
         assert endp_addr == s_addr
-        api.PyErr_Clear()
         rffi.free_charp(s)
         lltype.free(endp, flavor='raw')
 
@@ -164,4 +157,4 @@
         r = api.PyOS_double_to_string(3.14, 'g', 3, 0, ptype)
         assert '3.14' == rffi.charp2str(r)
         assert ptype == lltype.nullptr(rffi.INTP.TO)
-        rffi.free_charp(r)
\ No newline at end of file
+        rffi.free_charp(r)
diff --git a/pypy/module/cpyext/test/test_sequence.py b/pypy/module/cpyext/test/test_sequence.py
--- a/pypy/module/cpyext/test/test_sequence.py
+++ b/pypy/module/cpyext/test/test_sequence.py
@@ -1,9 +1,12 @@
-from rpython.rtyper.lltypesystem import rffi, lltype
+from rpython.rtyper.lltypesystem import rffi
 from pypy.interpreter.error import OperationError
-from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
-from pypy.module.cpyext import sequence
-import py.test
+from pypy.module.cpyext.sequence import (
+    PySequence_Fast, PySequence_Contains, PySequence_Index,
+    PySequence_GetItem, PySequence_SetItem, PySequence_DelItem)
+
+import pytest
 
 class TestSequence(BaseApiTest):
     def test_check(self, space, api):
@@ -56,16 +59,12 @@
         w_t2 = api.PySequence_InPlaceRepeat(w_t1, 3)
         assert space.unwrap(w_t2) == [0, 1, 0, 1, 0, 1]
 
-    def test_exception(self, space, api):
+    def test_exception(self, space):
         message = rffi.str2charp("message")
-        assert not api.PySequence_Fast(space.wrap(3), message)
-        assert api.PyErr_Occurred() is space.w_TypeError
-        api.PyErr_Clear()
-
-        exc = raises(OperationError, sequence.PySequence_Fast,
-                     space, space.wrap(3), message)
-        assert exc.value.match(space, space.w_TypeError)
-        assert space.str_w(exc.value.get_w_value(space)) == "message"
+        with pytest.raises(OperationError) as excinfo:
+            PySequence_Fast(space, space.wrap(3), message)
+        assert excinfo.value.match(space, space.w_TypeError)
+        assert space.str_w(excinfo.value.get_w_value(space)) == "message"
         rffi.free_charp(message)
 
     def test_get_slice(self, space, api):
@@ -80,7 +79,7 @@
 
     def test_get_slice_fast(self, space, api):
         w_t = space.wrap([1, 2, 3, 4, 5])
-        api.PySequence_Fast(w_t, "foo") # converts
+        api.PySequence_Fast(w_t, "foo")  # converts
         assert space.unwrap(api.PySequence_GetSlice(w_t, 2, 4)) == [3, 4]
         assert space.unwrap(api.PySequence_GetSlice(w_t, 1, -1)) == [2, 3, 4]
 
@@ -97,13 +96,12 @@
         exc = raises(OperationError, space.next, w_iter)
         assert exc.value.match(space, space.w_StopIteration)
 
-    def test_contains(self, space, api):
+    def test_contains(self, space):
         w_t = space.wrap((1, 'ha'))
-        assert api.PySequence_Contains(w_t, space.wrap(u'ha'))
-        assert not api.PySequence_Contains(w_t, space.wrap(2))
-        assert api.PySequence_Contains(space.w_None, space.wrap(2)) == -1
-        assert api.PyErr_Occurred()
-        api.PyErr_Clear()
+        assert PySequence_Contains(space, w_t, space.wrap(u'ha'))
+        assert not PySequence_Contains(space, w_t, space.wrap(2))
+        with raises_w(space, TypeError):
+            PySequence_Contains(space, space.w_None, space.wrap(2))
 
     def test_setitem(self, space, api):
         w_value = space.wrap(42)
@@ -112,39 +110,33 @@
         result = api.PySequence_SetItem(l, 0, w_value)
         assert result != -1
         assert space.eq_w(space.getitem(l, space.wrap(0)), w_value)
-
-        self.raises(space, api, IndexError, api.PySequence_SetItem,
-                    l, 3, w_value)
+        with raises_w(space, IndexError):
+            PySequence_SetItem(space, l, 3, w_value)
 
         t = api.PyTuple_New(1)
         api.PyTuple_SetItem(t, 0, l)
-        self.raises(space, api, TypeError, api.PySequence_SetItem,
-                    t, 0, w_value)
-
-        self.raises(space, api, TypeError, api.PySequence_SetItem,
-                    space.newdict(), 0, w_value)
+        with raises_w(space, TypeError):
+            PySequence_SetItem(space, t, 0, w_value)
+        with raises_w(space, TypeError):
+            PySequence_SetItem(space, space.newdict(), 0, w_value)
 
     def test_delitem(self, space, api):
         w_l = space.wrap([1, 2, 3, 4])
-
         result = api.PySequence_DelItem(w_l, 2)
         assert result == 0
         assert space.eq_w(w_l, space.wrap([1, 2, 4]))
-
-        self.raises(space, api, IndexError, api.PySequence_DelItem,
-                    w_l, 3)
+        with raises_w(space, IndexError):
+            PySequence_DelItem(space, w_l, 3)
 
     def test_getitem(self, space, api):
         thelist = [8, 7, 6, 5, 4, 3, 2, 1]
         w_l = space.wrap(thelist)
-
         result = api.PySequence_GetItem(w_l, 4)
         assert space.is_true(space.eq(result, space.wrap(4)))
-
         result = api.PySequence_ITEM(w_l, 4)
         assert space.is_true(space.eq(result, space.wrap(4)))
-
-        self.raises(space, api, IndexError, api.PySequence_GetItem, w_l, 9000)
+        with raises_w(space, IndexError):
+            PySequence_GetItem(space, w_l, 9000)
 
     def test_index(self, space, api):
         thelist = [9, 8, 7, 6, 5, 4, 3, 2, 1]
@@ -155,10 +147,8 @@
         assert result == thelist.index(5)
 
         w_tofind = space.wrap(9001)
-        result = api.PySequence_Index(w_l, w_tofind)
-        assert result == -1
-        assert api.PyErr_Occurred() is space.w_ValueError
-        api.PyErr_Clear()
+        with raises_w(space, ValueError):
+            PySequence_Index(space, w_l, w_tofind)
 
         w_gen = space.appexec([], """():
            return (x ** 2 for x in range(40))""")
@@ -196,7 +186,7 @@
         assert space.int_w(space.len(w_l)) == 4
         assert space.int_w(space.getitem(w_l, space.wrap(1))) == 2
         assert space.int_w(space.getitem(w_l, space.wrap(0))) == 1
-        e = py.test.raises(OperationError, space.getitem, w_l, space.wrap(15))
+        e = pytest.raises(OperationError, space.getitem, w_l, space.wrap(15))
         assert "list index out of range" in e.value.errorstr(space)
         assert space.int_w(space.getitem(w_l, space.wrap(-1))) == 4
         space.setitem(w_l, space.wrap(1), space.wrap(13))
diff --git a/pypy/module/cpyext/test/test_setobject.py b/pypy/module/cpyext/test/test_setobject.py
--- a/pypy/module/cpyext/test/test_setobject.py
+++ b/pypy/module/cpyext/test/test_setobject.py
@@ -1,31 +1,30 @@
-import py
-
-from pypy.module.cpyext.pyobject import PyObject, PyObjectP, make_ref, from_ref
-from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
-from rpython.rtyper.lltypesystem import rffi, lltype
+from pypy.module.cpyext.setobject import (
+    PySet_Check, PyFrozenSet_Check, PyFrozenSet_CheckExact,
+    PySet_Add, PySet_Size, PySet_GET_SIZE)
 
 
 class TestTupleObject(BaseApiTest):
-    def test_setobj(self, space, api):
-        assert not api.PySet_Check(space.w_None)
-        assert not api.PyFrozenSet_Check(space.w_None)
-        assert api.PySet_Add(space.w_None, space.w_None) == -1
-        api.PyErr_Clear()
+    def test_setobj(self, space):
+        assert not PySet_Check(space, space.w_None)
+        assert not PyFrozenSet_Check(space, space.w_None)
+        with raises_w(space, SystemError):
+            PySet_Add(space, space.w_None, space.w_None)
         w_set = space.call_function(space.w_set)
-        assert not api.PyFrozenSet_CheckExact(w_set)
-        space.call_method(w_set, 'update', space.wrap([1,2,3,4]))
-        assert api.PySet_Size(w_set) == 4
-        assert api.PySet_GET_SIZE(w_set) == 4
-        raises(TypeError, api.PySet_Size(space.newlist([])))
-        api.PyErr_Clear()
+        assert not PyFrozenSet_CheckExact(space, w_set)
+        space.call_method(w_set, 'update', space.wrap([1, 2, 3, 4]))
+        assert PySet_Size(space, w_set) == 4
+        assert PySet_GET_SIZE(space, w_set) == 4
+        with raises_w(space, TypeError):
+            PySet_Size(space, space.newlist([]))
 
     def test_set_add_discard(self, space, api):
         w_set = api.PySet_New(None)
         assert api.PySet_Size(w_set) == 0
-        w_set = api.PyFrozenSet_New(space.wrap([1,2,3,4]))
+        w_set = api.PyFrozenSet_New(space.wrap([1, 2, 3, 4]))
         assert api.PySet_Size(w_set) == 4
-        w_set = api.PySet_New(space.wrap([1,2,3,4]))
+        w_set = api.PySet_New(space.wrap([1, 2, 3, 4]))
         assert api.PySet_Size(w_set) == 4
         api.PySet_Add(w_set, space.wrap(6))
         assert api.PySet_Size(w_set) == 5
@@ -33,14 +32,14 @@
         assert api.PySet_Size(w_set) == 4
 
     def test_set_contains(self, space, api):
-        w_set = api.PySet_New(space.wrap([1,2,3,4]))
+        w_set = api.PySet_New(space.wrap([1, 2, 3, 4]))
         assert api.PySet_Contains(w_set, space.wrap(1))
         assert not api.PySet_Contains(w_set, space.wrap(0))
 
     def test_set_pop_clear(self, space, api):
-        w_set = api.PySet_New(space.wrap([1,2,3,4]))
+        w_set = api.PySet_New(space.wrap([1, 2, 3, 4]))
         w_obj = api.PySet_Pop(w_set)
-        assert space.int_w(w_obj) in (1,2,3,4)
+        assert space.int_w(w_obj) in (1, 2, 3, 4)
         assert space.len_w(w_set) == 3
         api.PySet_Clear(w_set)
         assert space.len_w(w_set) == 0
@@ -72,6 +71,5 @@
              PySet_GET_SIZE(dumb_pointer);
 
              return o;
-             """
-            )
+             """)
         ])
diff --git a/pypy/module/cpyext/test/test_sliceobject.py b/pypy/module/cpyext/test/test_sliceobject.py
--- a/pypy/module/cpyext/test/test_sliceobject.py
+++ b/pypy/module/cpyext/test/test_sliceobject.py
@@ -2,13 +2,14 @@
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
 from pypy.module.cpyext.api import Py_ssize_t, Py_ssize_tP
+from pypy.module.cpyext.sliceobject import PySlice_Check
 
 class TestSliceObject(BaseApiTest):
-    def test_slice(self, space, api):
+    def test_slice(self, space):
         w_i = space.wrap(10)
         w_slice = space.newslice(w_i, w_i, w_i)
-        assert api.PySlice_Check(w_slice)
-        assert not api.PySlice_Check(w_i)
+        assert PySlice_Check(space, w_slice)
+        assert not PySlice_Check(space, w_i)
 
     def test_GetIndicesEx(self, space, api):
         w = space.wrap
diff --git a/pypy/module/cpyext/test/test_tupleobject.py b/pypy/module/cpyext/test/test_tupleobject.py
--- a/pypy/module/cpyext/test/test_tupleobject.py
+++ b/pypy/module/cpyext/test/test_tupleobject.py
@@ -1,24 +1,25 @@
 import py
 
 from pypy.module.cpyext.pyobject import PyObject, PyObjectP, make_ref, from_ref
-from pypy.module.cpyext.tupleobject import PyTupleObject
-from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
 from rpython.rtyper.lltypesystem import rffi, lltype
 from rpython.rlib.debug import FatalError
+from pypy.module.cpyext.tupleobject import (
+    PyTupleObject, PyTuple_Check, PyTuple_SetItem, PyTuple_Size)
 
 
 class TestTupleObject(BaseApiTest):
 
-    def test_tupleobject(self, space, api):
-        assert not api.PyTuple_Check(space.w_None)
-        assert api.PyTuple_SetItem(space.w_None, 0, space.w_None) == -1
+    def test_tupleobject(self, space):
+        assert not PyTuple_Check(space, space.w_None)
+        with raises_w(space, SystemError):
+            PyTuple_SetItem(space, space.w_None, 0, space.w_None)
         atuple = space.newtuple([space.wrap(0), space.wrap(1),
                                  space.wrap('yay')])
-        assert api.PyTuple_Size(atuple) == 3
-        #assert api.PyTuple_GET_SIZE(atuple) == 3  --- now a C macro
-        raises(TypeError, api.PyTuple_Size(space.newlist([])))
-        api.PyErr_Clear()
+        assert PyTuple_Size(space, atuple) == 3
+        with raises_w(space, SystemError):
+            PyTuple_Size(space, space.newlist([]))
 
     def test_tuple_realize_refuses_nulls(self, space, api):
         py_tuple = api.PyTuple_New(1)
diff --git a/pypy/module/cpyext/test/test_weakref.py b/pypy/module/cpyext/test/test_weakref.py
--- a/pypy/module/cpyext/test/test_weakref.py
+++ b/pypy/module/cpyext/test/test_weakref.py
@@ -1,5 +1,6 @@
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
-from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
+from pypy.module.cpyext.weakrefobject import PyWeakref_NewRef
 
 class TestWeakReference(BaseApiTest):
     def test_weakref(self, space, api):
@@ -10,12 +11,11 @@
         assert space.is_w(api.PyWeakref_LockObject(w_ref), w_obj)
 
         w_obj = space.newtuple([])
-        assert api.PyWeakref_NewRef(w_obj, space.w_None) is None
-        assert api.PyErr_Occurred() is space.w_TypeError
-        api.PyErr_Clear()
+        with raises_w(space, TypeError):
+            PyWeakref_NewRef(space, w_obj, space.w_None)
 
     def test_proxy(self, space, api):
-        w_obj = space.w_Warning # some weakrefable object
+        w_obj = space.w_Warning  # some weakrefable object
         w_proxy = api.PyWeakref_NewProxy(w_obj, None)
         assert space.unwrap(space.str(w_proxy)) == "<class 'Warning'>"
         assert space.unwrap(space.repr(w_proxy)).startswith('<weak')
diff --git a/pypy/module/test_lib_pypy/test_stackless.py b/pypy/module/test_lib_pypy/test_stackless.py
--- a/pypy/module/test_lib_pypy/test_stackless.py
+++ b/pypy/module/test_lib_pypy/test_stackless.py
@@ -599,4 +599,23 @@
 
         stackless.run()
 
-
+    def test_kill_tasklet_waiting_for_channel(self):
+        # issue #2595
+        c = stackless.channel()
+        def sender():
+            c.send(1)
+        def receiver():
+            v = c.receive()
+        def killer(tl):
+            tl.kill()
+        def main():
+            trk = stackless.tasklet(receiver)()
+            stackless.schedule()
+            killer(trk)
+            stackless.schedule()
+            stackless.tasklet(sender)()
+            stackless.schedule()
+            stackless.tasklet(receiver)()
+            stackless.schedule()
+        stackless.tasklet(main)()
+        stackless.run()
diff --git a/rpython/rlib/test/test_rposix.py b/rpython/rlib/test/test_rposix.py
--- a/rpython/rlib/test/test_rposix.py
+++ b/rpython/rlib/test/test_rposix.py
@@ -753,6 +753,9 @@
 
 @rposix_requires('posix_fadvise')
 def test_posix_fadvise():
+    if sys.maxint <= 2**32:
+        py.test.skip("ll2ctypes run of posix_fadvise() on 32-bit "
+                     "gets confused by the size of OFF_T")
     fname = str(udir.join('test_os_posix_fadvise'))
     fd = os.open(fname, os.O_CREAT | os.O_RDWR)
     try:
@@ -769,6 +772,9 @@
 
 @rposix_requires('posix_fallocate')
 def test_posix_fallocate():
+    if sys.maxint <= 2**32:
+        py.test.skip("ll2ctypes run of posix_fallocate() on 32-bit "
+                     "gets confused by the size of OFF_T")
     fname = str(udir.join('os_test.txt'))


More information about the pypy-commit mailing list