Author: Ronan Lamy <[email protected]>
Branch: 
Changeset: r89504:094c5770114b
Date: 2017-01-11 20:39 +0000
http://bitbucket.org/pypy/pypy/changeset/094c5770114b/

Log:    Remove more uses of api.XXX magic

diff --git a/pypy/module/cpyext/test/test_eval.py 
b/pypy/module/cpyext/test/test_eval.py
--- a/pypy/module/cpyext/test/test_eval.py
+++ b/pypy/module/cpyext/test/test_eval.py
@@ -1,17 +1,26 @@
+import sys
+import os
+import pytest
 from rpython.rtyper.lltypesystem import rffi, lltype
 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.object import PyObject_Size, PyObject_GetItem
+from pypy.module.cpyext.pythonrun import Py_AtExit
 from pypy.module.cpyext.eval import (
-    Py_single_input, Py_file_input, Py_eval_input, PyCompilerFlags)
-from pypy.module.cpyext.api import (c_fopen, c_fclose, c_fileno, 
-                Py_ssize_tP, is_valid_fd)
+    Py_single_input, Py_file_input, Py_eval_input, PyCompilerFlags,
+    PyEval_CallObjectWithKeywords, PyObject_CallObject, PyEval_EvalCode,
+    PyRun_SimpleString, PyRun_String, PyRun_StringFlags, PyRun_File,
+    PyEval_GetBuiltins, PyEval_GetLocals, PyEval_GetGlobals,
+    _PyEval_SliceIndex)
+from pypy.module.cpyext.api import (
+    c_fopen, c_fclose, c_fileno, Py_ssize_tP, is_valid_fd)
 from pypy.interpreter.gateway import interp2app
+from pypy.interpreter.error import OperationError
 from pypy.interpreter.astcompiler import consts
 from rpython.tool.udir import udir
-import sys, os
 
 class TestEval(BaseApiTest):
-    def test_eval(self, space, api):
+    def test_eval(self, space):
         w_l, w_f = space.fixedview(space.appexec([], """():
         l = []
         def f(arg1, arg2):
@@ -22,7 +31,7 @@
         """))
 
         w_t = space.newtuple([space.wrap(1), space.wrap(2)])
-        w_res = api.PyEval_CallObjectWithKeywords(w_f, w_t, None)
+        w_res = PyEval_CallObjectWithKeywords(space, w_f, w_t, None)
         assert space.int_w(w_res) == 2
         assert space.len_w(w_l) == 2
         w_f = space.appexec([], """():
@@ -35,10 +44,10 @@
         w_t = space.newtuple([space.w_None, space.w_None])
         w_d = space.newdict()
         space.setitem(w_d, space.wrap("xyz"), space.wrap(3))
-        w_res = api.PyEval_CallObjectWithKeywords(w_f, w_t, w_d)
+        w_res = PyEval_CallObjectWithKeywords(space, w_f, w_t, w_d)
         assert space.int_w(w_res) == 21
 
-    def test_call_object(self, space, api):
+    def test_call_object(self, space):
         w_l, w_f = space.fixedview(space.appexec([], """():
         l = []
         def f(arg1, arg2):
@@ -49,7 +58,7 @@
         """))
 
         w_t = space.newtuple([space.wrap(1), space.wrap(2)])
-        w_res = api.PyObject_CallObject(w_f, w_t)
+        w_res = PyObject_CallObject(space, w_f, w_t)
         assert space.int_w(w_res) == 2
         assert space.len_w(w_l) == 2
 
@@ -61,11 +70,11 @@
             """)
 
         w_t = space.newtuple([space.wrap(1), space.wrap(2)])
-        w_res = api.PyObject_CallObject(w_f, w_t)
+        w_res = PyObject_CallObject(space, w_f, w_t)
 
         assert space.int_w(w_res) == 10
 
-    def test_evalcode(self, space, api):
+    def test_evalcode(self, space):
         w_f = space.appexec([], """():
             def f(*args):
                 assert isinstance(args, tuple)
@@ -77,84 +86,78 @@
         w_globals = space.newdict()
         w_locals = space.newdict()
         space.setitem(w_locals, space.wrap("args"), w_t)
-        w_res = api.PyEval_EvalCode(w_f.code, w_globals, w_locals)
+        w_res = PyEval_EvalCode(space, w_f.code, w_globals, w_locals)
 
         assert space.int_w(w_res) == 10
 
-    def test_run_simple_string(self, space, api):
+    def test_run_simple_string(self, space):
         def run(code):
             buf = rffi.str2charp(code)
             try:
-                return api.PyRun_SimpleString(buf)
+                return PyRun_SimpleString(space, buf)
             finally:
                 rffi.free_charp(buf)
 
-        assert 0 == run("42 * 43")
+        assert run("42 * 43") == 0  # no error
+        with pytest.raises(OperationError):
+            run("4..3 * 43")
 
-        assert -1 == run("4..3 * 43")
-
-        assert api.PyErr_Occurred()
-        api.PyErr_Clear()
-
-    def test_run_string(self, space, api):
+    def test_run_string(self, space):
         def run(code, start, w_globals, w_locals):
             buf = rffi.str2charp(code)
             try:
-                return api.PyRun_String(buf, start, w_globals, w_locals)
+                return PyRun_String(space, buf, start, w_globals, w_locals)
             finally:
                 rffi.free_charp(buf)
 
         w_globals = space.newdict()
         assert 42 * 43 == space.unwrap(
             run("42 * 43", Py_eval_input, w_globals, w_globals))
-        assert api.PyObject_Size(w_globals) == 0
+        assert PyObject_Size(space, w_globals) == 0
 
         assert run("a = 42 * 43", Py_single_input,
                    w_globals, w_globals) == space.w_None
         assert 42 * 43 == space.unwrap(
-            api.PyObject_GetItem(w_globals, space.wrap("a")))
+            PyObject_GetItem(space, w_globals, space.wrap("a")))
 
-    def test_run_string_flags(self, space, api):
+    def test_run_string_flags(self, space):
         flags = lltype.malloc(PyCompilerFlags, flavor='raw')
         flags.c_cf_flags = rffi.cast(rffi.INT, consts.PyCF_SOURCE_IS_UTF8)
         w_globals = space.newdict()
         buf = rffi.str2charp("a = u'caf\xc3\xa9'")
         try:
-            api.PyRun_StringFlags(buf, Py_single_input,
-                                  w_globals, w_globals, flags)
+            PyRun_StringFlags(space, buf, Py_single_input, w_globals,
+                              w_globals, flags)
         finally:
             rffi.free_charp(buf)
         w_a = space.getitem(w_globals, space.wrap("a"))
         assert space.unwrap(w_a) == u'caf\xe9'
         lltype.free(flags, flavor='raw')
 
-    def test_run_file(self, space, api):
+    def test_run_file(self, space):
         filepath = udir / "cpyext_test_runfile.py"
         filepath.write("raise ZeroDivisionError")
         fp = c_fopen(str(filepath), "rb")
         filename = rffi.str2charp(str(filepath))
         w_globals = w_locals = space.newdict()
-        api.PyRun_File(fp, filename, Py_file_input, w_globals, w_locals)
+        with raises_w(space, ZeroDivisionError):
+            PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals)
         c_fclose(fp)
-        assert api.PyErr_Occurred() is space.w_ZeroDivisionError
-        api.PyErr_Clear()
 
         # try again, but with a closed file
         fp = c_fopen(str(filepath), "rb")
         os.close(c_fileno(fp))
-        api.PyRun_File(fp, filename, Py_file_input, w_globals, w_locals)
+        with raises_w(space, IOError):
+            PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals)
         if is_valid_fd(c_fileno(fp)):
             c_fclose(fp)
-        assert api.PyErr_Occurred() is space.w_IOError
-        api.PyErr_Clear()
-
         rffi.free_charp(filename)
 
-    def test_getbuiltins(self, space, api):
-        assert api.PyEval_GetBuiltins() is space.builtin.w_dict
+    def test_getbuiltins(self, space):
+        assert PyEval_GetBuiltins(space) is space.builtin.w_dict
 
         def cpybuiltins(space):
-            return api.PyEval_GetBuiltins()
+            return PyEval_GetBuiltins(space)
         w_cpybuiltins = space.wrap(interp2app(cpybuiltins))
 
         w_result = space.appexec([w_cpybuiltins], """(cpybuiltins):
@@ -168,13 +171,13 @@
         """)
         assert space.len_w(w_result) == 1
 
-    def test_getglobals(self, space, api):
-        assert api.PyEval_GetLocals() is None
-        assert api.PyEval_GetGlobals() is None
+    def test_getglobals(self, space):
+        assert PyEval_GetLocals(space) is None
+        assert PyEval_GetGlobals(space) is None
 
         def cpyvars(space):
-            return space.newtuple([api.PyEval_GetGlobals(),
-                                   api.PyEval_GetLocals()])
+            return space.newtuple([PyEval_GetGlobals(space),
+                                   PyEval_GetLocals(space)])
         w_cpyvars = space.wrap(interp2app(cpyvars))
 
         w_result = space.appexec([w_cpyvars], """(cpyvars):
@@ -186,26 +189,26 @@
         assert sorted(locals) == ['cpyvars', 'x']
         assert sorted(globals) == ['__builtins__', 'anonymous', 'y']
 
-    def test_sliceindex(self, space, api):
+    def test_sliceindex(self, space):
         pi = lltype.malloc(Py_ssize_tP.TO, 1, flavor='raw')
-        assert api._PyEval_SliceIndex(space.w_None, pi) == 0
-        api.PyErr_Clear()
+        with pytest.raises(OperationError):
+            _PyEval_SliceIndex(space, space.w_None, pi)
 
-        assert api._PyEval_SliceIndex(space.wrap(123), pi) == 1
+        assert _PyEval_SliceIndex(space, space.wrap(123), pi) == 1
         assert pi[0] == 123
 
-        assert api._PyEval_SliceIndex(space.wrap(1 << 66), pi) == 1
+        assert _PyEval_SliceIndex(space, space.wrap(1 << 66), pi) == 1
         assert pi[0] == sys.maxint
 
         lltype.free(pi, flavor='raw')
 
-    def test_atexit(self, space, api):
+    def test_atexit(self, space):
         lst = []
         def func():
             lst.append(42)
-        api.Py_AtExit(func)
+        Py_AtExit(space, func)
         cpyext = space.getbuiltinmodule('cpyext')
-        cpyext.shutdown(space) # simulate shutdown
+        cpyext.shutdown(space)  # simulate shutdown
         assert lst == [42]
 
 class AppTestCall(AppTestCpythonExtensionBase):
@@ -269,6 +272,7 @@
                 return res;
              """),
             ])
+
         def f(*args):
             return args
         assert module.call_func(f) == (None,)
@@ -322,7 +326,7 @@
             ])
         assert module.get_flags() == (0, 0)
 
-        ns = {'module':module}
+        ns = {'module': module}
         exec """from __future__ import division    \nif 1:
                 def nested_flags():
                     return module.get_flags()""" in ns
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
@@ -1,36 +1,40 @@
+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 rpython.rtyper.lltypesystem import rffi
+from pypy.module.cpyext.floatobject import (
+    PyFloat_FromDouble, PyFloat_AsDouble, PyFloat_AS_DOUBLE, PyNumber_Float,
+    _PyFloat_Unpack4, _PyFloat_Unpack8)
 
 class TestFloatObject(BaseApiTest):
-    def test_floatobject(self, space, api):
-        assert space.unwrap(api.PyFloat_FromDouble(3.14)) == 3.14
-        assert api.PyFloat_AsDouble(space.wrap(23.45)) == 23.45
-        assert api.PyFloat_AS_DOUBLE(space.wrap(23.45)) == 23.45
+    def test_floatobject(self, space):
+        assert space.unwrap(PyFloat_FromDouble(space, 3.14)) == 3.14
+        assert PyFloat_AsDouble(space, space.wrap(23.45)) == 23.45
+        assert PyFloat_AS_DOUBLE(space, space.wrap(23.45)) == 23.45
+        with pytest.raises(OperationError):
+            PyFloat_AsDouble(space, space.w_None)
 
-        assert api.PyFloat_AsDouble(space.w_None) == -1
-        api.PyErr_Clear()
-
-    def test_coerce(self, space, api):
-        assert space.type(api.PyNumber_Float(space.wrap(3))) is space.w_float
-        assert space.type(api.PyNumber_Float(space.wrap("3"))) is space.w_float
+    def test_coerce(self, space):
+        assert space.type(PyNumber_Float(space, space.wrap(3))) is 
space.w_float
+        assert space.type(PyNumber_Float(space, space.wrap("3"))) is 
space.w_float
 
         w_obj = space.appexec([], """():
             class Coerce(object):
                 def __float__(self):
                     return 42.5
             return Coerce()""")
-        assert space.eq_w(api.PyNumber_Float(w_obj), space.wrap(42.5))
+        assert space.eq_w(PyNumber_Float(space, w_obj), space.wrap(42.5))
 
-    def test_unpack(self, space, api):
+    def test_unpack(self, space):
         with rffi.scoped_str2charp("\x9a\x99\x99?") as ptr:
-            assert abs(api._PyFloat_Unpack4(ptr, 1) - 1.2) < 1e-7
+            assert abs(_PyFloat_Unpack4(space, ptr, 1) - 1.2) < 1e-7
         with rffi.scoped_str2charp("?\x99\x99\x9a") as ptr:
-            assert abs(api._PyFloat_Unpack4(ptr, 0) - 1.2) < 1e-7
+            assert abs(_PyFloat_Unpack4(space, ptr, 0) - 1.2) < 1e-7
         with rffi.scoped_str2charp("\x1f\x85\xebQ\xb8\x1e\t@") as ptr:
-            assert abs(api._PyFloat_Unpack8(ptr, 1) - 3.14) < 1e-15
+            assert abs(_PyFloat_Unpack8(space, ptr, 1) - 3.14) < 1e-15
         with rffi.scoped_str2charp("@\t\x1e\xb8Q\xeb\x85\x1f") as ptr:
-            assert abs(api._PyFloat_Unpack8(ptr, 0) - 3.14) < 1e-15
+            assert abs(_PyFloat_Unpack8(space, ptr, 0) - 3.14) < 1e-15
 
 class AppTestFloatObject(AppTestCpythonExtensionBase):
     def test_fromstring(self):
@@ -79,8 +83,6 @@
         assert math.isinf(neginf)
 
     def test_macro_accepts_wrong_pointer_type(self):
-        import math
-
         module = self.import_extension('foo', [
             ("test_macros", "METH_NOARGS",
              """
diff --git a/pypy/module/cpyext/test/test_funcobject.py 
b/pypy/module/cpyext/test/test_funcobject.py
--- a/pypy/module/cpyext/test/test_funcobject.py
+++ b/pypy/module/cpyext/test/test_funcobject.py
@@ -1,16 +1,18 @@
-from rpython.rtyper.lltypesystem import rffi, lltype
-from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
+from rpython.rtyper.lltypesystem import rffi
 from pypy.module.cpyext.test.test_api import BaseApiTest
-from pypy.module.cpyext.pyobject import PyObject, make_ref, from_ref
+from pypy.module.cpyext.pyobject import PyObject, make_ref, from_ref, decref
+from pypy.module.cpyext.methodobject import PyClassMethod_New
 from pypy.module.cpyext.funcobject import (
-    PyFunctionObject, PyCodeObject, CODE_FLAGS)
-from pypy.interpreter.function import Function, Method
+    PyFunctionObject, PyCodeObject, CODE_FLAGS, PyMethod_Function,
+    PyMethod_Self, PyMethod_Class, PyMethod_New, PyFunction_GetCode,
+    PyCode_NewEmpty, PyCode_GetNumFree)
+from pypy.interpreter.function import Function
 from pypy.interpreter.pycode import PyCode
 
 globals().update(CODE_FLAGS)
 
 class TestFunctionObject(BaseApiTest):
-    def test_function(self, space, api):
+    def test_function(self, space):
         w_function = space.appexec([], """():
             def f(): pass
             return f
@@ -19,10 +21,10 @@
         assert (from_ref(space, rffi.cast(PyObject, ref.c_ob_type)) is
                 space.gettypeobject(Function.typedef))
         assert "f" == space.unwrap(
-           from_ref(space, rffi.cast(PyFunctionObject, ref).c_func_name))
-        api.Py_DecRef(ref)
+            from_ref(space, rffi.cast(PyFunctionObject, ref).c_func_name))
+        decref(space, ref)
 
-    def test_method(self, space, api):
+    def test_method(self, space):
         w_method = space.appexec([], """():
             class C(list):
                 def method(self): pass
@@ -33,30 +35,30 @@
         w_self = space.getattr(w_method, space.wrap("im_self"))
         w_class = space.getattr(w_method, space.wrap("im_class"))
 
-        assert space.is_w(api.PyMethod_Function(w_method), w_function)
-        assert space.is_w(api.PyMethod_Self(w_method), w_self)
-        assert space.is_w(api.PyMethod_Class(w_method), w_class)
+        assert space.is_w(PyMethod_Function(space, w_method), w_function)
+        assert space.is_w(PyMethod_Self(space, w_method), w_self)
+        assert space.is_w(PyMethod_Class(space, w_method), w_class)
 
-        w_method2 = api.PyMethod_New(w_function, w_self, w_class)
+        w_method2 = PyMethod_New(space, w_function, w_self, w_class)
         assert space.eq_w(w_method, w_method2)
 
-    def test_getcode(self, space, api):
+    def test_getcode(self, space):
         w_function = space.appexec([], """():
             def func(x, y, z): return x
             return func
         """)
-        w_code = api.PyFunction_GetCode(w_function)
+        w_code = PyFunction_GetCode(space, w_function)
         assert w_code.co_name == "func"
 
         ref = make_ref(space, w_code)
         assert (from_ref(space, rffi.cast(PyObject, ref.c_ob_type)) is
                 space.gettypeobject(PyCode.typedef))
         assert "func" == space.unwrap(
-           from_ref(space, rffi.cast(PyCodeObject, ref).c_co_name))
+            from_ref(space, rffi.cast(PyCodeObject, ref).c_co_name))
         assert 3 == rffi.cast(PyCodeObject, ref).c_co_argcount
-        api.Py_DecRef(ref)
+        decref(space, ref)
 
-    def test_co_flags(self, space, api):
+    def test_co_flags(self, space):
         def get_flags(signature, body="pass"):
             w_code = space.appexec([], """():
                 def func(%s): %s
@@ -64,7 +66,7 @@
             """ % (signature, body))
             ref = make_ref(space, w_code)
             co_flags = rffi.cast(PyCodeObject, ref).c_co_flags
-            api.Py_DecRef(ref)
+            decref(space, ref)
             return co_flags
         assert get_flags("x") == CO_NESTED | CO_OPTIMIZED | CO_NEWLOCALS
         assert get_flags("x", "exec x") == CO_NESTED | CO_NEWLOCALS
@@ -72,29 +74,29 @@
         assert get_flags("x, **kw") & CO_VARKEYWORDS
         assert get_flags("x", "yield x") & CO_GENERATOR
 
-    def test_newcode(self, space, api):
+    def test_newcode(self, space):
         filename = rffi.str2charp('filename')
         funcname = rffi.str2charp('funcname')
-        w_code = api.PyCode_NewEmpty(filename, funcname, 3)
+        w_code = PyCode_NewEmpty(space, filename, funcname, 3)
         assert w_code.co_filename == 'filename'
         assert w_code.co_firstlineno == 3
 
         ref = make_ref(space, w_code)
         assert "filename" == space.unwrap(
             from_ref(space, rffi.cast(PyCodeObject, ref).c_co_filename))
-        api.Py_DecRef(ref)
+        decref(space, ref)
         rffi.free_charp(filename)
         rffi.free_charp(funcname)
 
-    def test_getnumfree(self, space, api):
+    def test_getnumfree(self, space):
         w_function = space.appexec([], """():
             a = 5
             def method(x): return a, x
             return method
         """)
-        assert api.PyCode_GetNumFree(w_function.code) == 1
+        assert PyCode_GetNumFree(space, w_function.code) == 1
 
-    def test_classmethod(self, space, api):
+    def test_classmethod(self, space):
         w_function = space.appexec([], """():
             def method(x): return x
             return method
@@ -106,6 +108,7 @@
         space.setattr(w_class, space.wrap("method"), w_function)
         assert space.is_w(space.call_method(w_instance, "method"), w_instance)
         # now a classmethod
-        w_classmethod = api.PyClassMethod_New(w_function)
+        w_classmethod = PyClassMethod_New(space, w_function)
         space.setattr(w_class, space.wrap("classmethod"), w_classmethod)
-        assert space.is_w(space.call_method(w_instance, "classmethod"), 
w_class)
+        assert space.is_w(
+            space.call_method(w_instance, "classmethod"), w_class)
diff --git a/pypy/module/cpyext/test/test_import.py 
b/pypy/module/cpyext/test/test_import.py
--- a/pypy/module/cpyext/test/test_import.py
+++ b/pypy/module/cpyext/test/test_import.py
@@ -1,48 +1,51 @@
 from pypy.module.cpyext.test.test_api import BaseApiTest
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
+from pypy.module.cpyext.import_ import *
+from pypy.module.cpyext.import_ import (
+    _PyImport_AcquireLock, _PyImport_ReleaseLock)
 from rpython.rtyper.lltypesystem import rffi
 
 class TestImport(BaseApiTest):
-    def test_import(self, space, api):
-        stat = api.PyImport_Import(space.wrap("stat"))
+    def test_import(self, space):
+        stat = PyImport_Import(space, space.wrap("stat"))
         assert stat
         assert space.getattr(stat, space.wrap("S_IMODE"))
 
-    def test_addmodule(self, space, api):
+    def test_addmodule(self, space):
         with rffi.scoped_str2charp("sys") as modname:
-            w_sys = api.PyImport_AddModule(modname)
+            w_sys = PyImport_AddModule(space, modname)
         assert w_sys is space.sys
 
         with rffi.scoped_str2charp("foobar") as modname:
-            w_foobar = api.PyImport_AddModule(modname)
+            w_foobar = PyImport_AddModule(space, modname)
         assert space.str_w(space.getattr(w_foobar,
                                          space.wrap('__name__'))) == 'foobar'
 
-    def test_getmoduledict(self, space, api):
+    def test_getmoduledict(self, space):
         testmod = "_functools"
-        w_pre_dict = api.PyImport_GetModuleDict()
+        w_pre_dict = PyImport_GetModuleDict(space, )
         assert not space.contains_w(w_pre_dict, space.wrap(testmod))
 
         with rffi.scoped_str2charp(testmod) as modname:
-            w_module = api.PyImport_ImportModule(modname)
+            w_module = PyImport_ImportModule(space, modname)
             print w_module
             assert w_module
 
-        w_dict = api.PyImport_GetModuleDict()
+        w_dict = PyImport_GetModuleDict(space, )
         assert space.contains_w(w_dict, space.wrap(testmod))
 
-    def test_reload(self, space, api):
-        stat = api.PyImport_Import(space.wrap("stat"))
+    def test_reload(self, space):
+        stat = PyImport_Import(space, space.wrap("stat"))
         space.delattr(stat, space.wrap("S_IMODE"))
-        stat = api.PyImport_ReloadModule(stat)
+        stat = PyImport_ReloadModule(space, stat)
         assert space.getattr(stat, space.wrap("S_IMODE"))
 
-    def test_lock(self, space, api):
+    def test_lock(self, space):
         # "does not crash"
-        api._PyImport_AcquireLock()
-        api._PyImport_AcquireLock()
-        api._PyImport_ReleaseLock()
-        api._PyImport_ReleaseLock()
+        _PyImport_AcquireLock(space, )
+        _PyImport_AcquireLock(space, )
+        _PyImport_ReleaseLock(space, )
+        _PyImport_ReleaseLock(space, )
 
 
 class AppTestImportLogic(AppTestCpythonExtensionBase):
diff --git a/pypy/module/cpyext/test/test_intobject.py 
b/pypy/module/cpyext/test/test_intobject.py
--- a/pypy/module/cpyext/test/test_intobject.py
+++ b/pypy/module/cpyext/test/test_intobject.py
@@ -1,51 +1,52 @@
-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.intobject import (
+    PyInt_Check, PyInt_AsLong, PyInt_AS_LONG, PyInt_FromLong,
+    PyInt_AsUnsignedLong, PyInt_AsUnsignedLongMask,
+    PyInt_AsUnsignedLongLongMask)
 import sys
 
 class TestIntObject(BaseApiTest):
-    def test_intobject(self, space, api):
-        assert api.PyInt_Check(space.wrap(3))
-        assert api.PyInt_Check(space.w_True)
-        assert not api.PyInt_Check(space.wrap((1, 2, 3)))
+    def test_intobject(self, space):
+        assert PyInt_Check(space, space.wrap(3))
+        assert PyInt_Check(space, space.w_True)
+        assert not PyInt_Check(space, space.wrap((1, 2, 3)))
         for i in [3, -5, -1, -sys.maxint, sys.maxint - 1]:
-            x = api.PyInt_AsLong(space.wrap(i))
-            y = api.PyInt_AS_LONG(space.wrap(i))
+            x = PyInt_AsLong(space, space.wrap(i))
+            y = PyInt_AS_LONG(space, space.wrap(i))
             assert x == i
             assert y == i
-            w_x = api.PyInt_FromLong(x + 1)
+            w_x = PyInt_FromLong(space, x + 1)
             assert space.type(w_x) is space.w_int
             assert space.eq_w(w_x, space.wrap(i + 1))
 
-        assert api.PyInt_AsLong(space.w_None) == -1
-        assert api.PyErr_Occurred() is space.w_TypeError
-        api.PyErr_Clear()
+        with raises_w(space, TypeError):
+            PyInt_AsLong(space, space.w_None)
 
-        assert api.PyInt_AsLong(None) == -1
-        assert api.PyErr_Occurred() is space.w_TypeError
-        api.PyErr_Clear()
+        with raises_w(space, TypeError):
+            PyInt_AsLong(space, None)
 
-        assert api.PyInt_AsUnsignedLong(space.wrap(sys.maxint)) == sys.maxint
-        assert api.PyInt_AsUnsignedLong(space.wrap(-5)) == sys.maxint * 2 + 1
-        assert api.PyErr_Occurred() is space.w_ValueError
-        api.PyErr_Clear()
+        assert PyInt_AsUnsignedLong(space, space.wrap(sys.maxint)) == 
sys.maxint
+        with raises_w(space, ValueError):
+            PyInt_AsUnsignedLong(space, space.wrap(-5))
 
-        assert (api.PyInt_AsUnsignedLongMask(space.wrap(sys.maxint))
+        assert (PyInt_AsUnsignedLongMask(space, space.wrap(sys.maxint))
                 == sys.maxint)
-        assert (api.PyInt_AsUnsignedLongMask(space.wrap(10**30))
-                == 10**30 % ((sys.maxint + 1) * 2))
+        assert (PyInt_AsUnsignedLongMask(space, space.wrap(10 ** 30))
+                == 10 ** 30 % ((sys.maxint + 1) * 2))
 
-        assert (api.PyInt_AsUnsignedLongLongMask(space.wrap(sys.maxint))
+        assert (PyInt_AsUnsignedLongLongMask(space, space.wrap(sys.maxint))
                 == sys.maxint)
-        assert (api.PyInt_AsUnsignedLongLongMask(space.wrap(10**30))
-                == 10**30 % (2**64))
+        assert (PyInt_AsUnsignedLongLongMask(space, space.wrap(10 ** 30))
+                == 10 ** 30 % (2 ** 64))
 
-    def test_coerce(self, space, api):
+    def test_coerce(self, space):
         w_obj = space.appexec([], """():
             class Coerce(object):
                 def __int__(self):
                     return 42
             return Coerce()""")
-        assert api.PyInt_AsLong(w_obj) == 42
+        assert PyInt_AsLong(space, w_obj) == 42
 
 class AppTestIntObject(AppTestCpythonExtensionBase):
     def test_fromstring(self):
@@ -203,4 +204,3 @@
                 """
                 ),
                 ])
-
diff --git a/pypy/module/cpyext/test/test_unicodeobject.py 
b/pypy/module/cpyext/test/test_unicodeobject.py
--- a/pypy/module/cpyext/test/test_unicodeobject.py
+++ b/pypy/module/cpyext/test/test_unicodeobject.py
@@ -1,5 +1,6 @@
 # encoding: utf-8
-from pypy.module.cpyext.test.test_api import BaseApiTest
+import pytest
+from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
 from pypy.module.cpyext.unicodeobject import (
     Py_UNICODE, PyUnicodeObject, new_empty_unicode)
@@ -7,6 +8,7 @@
 from pypy.module.cpyext.pyobject import Py_DecRef, from_ref
 from rpython.rtyper.lltypesystem import rffi, lltype
 import sys, py
+from pypy.module.cpyext.unicodeobject import *
 
 class AppTestUnicodeObject(AppTestCpythonExtensionBase):
     def test_unicodeobject(self):
@@ -131,13 +133,13 @@
         assert module.test_macro_invocations() == u''
 
 class TestUnicode(BaseApiTest):
-    def test_unicodeobject(self, space, api):
-        assert api.PyUnicode_GET_SIZE(space.wrap(u'sp&#65533;m')) == 4
-        assert api.PyUnicode_GetSize(space.wrap(u'sp&#65533;m')) == 4
+    def test_unicodeobject(self, space):
+        assert PyUnicode_GET_SIZE(space, space.wrap(u'sp&#65533;m')) == 4
+        assert PyUnicode_GetSize(space, space.wrap(u'sp&#65533;m')) == 4
         unichar = rffi.sizeof(Py_UNICODE)
-        assert api.PyUnicode_GET_DATA_SIZE(space.wrap(u'sp&#65533;m')) == 4 * 
unichar
+        assert PyUnicode_GET_DATA_SIZE(space, space.wrap(u'sp&#65533;m')) == 4 
* unichar
 
-        encoding = rffi.charp2str(api.PyUnicode_GetDefaultEncoding())
+        encoding = rffi.charp2str(PyUnicode_GetDefaultEncoding(space, ))
         w_default_encoding = space.call_function(
             space.sys.get('getdefaultencoding')
         )
@@ -145,43 +147,45 @@
         invalid = rffi.str2charp('invalid')
         utf_8 = rffi.str2charp('utf-8')
         prev_encoding = rffi.str2charp(space.unwrap(w_default_encoding))
-        self.raises(space, api, TypeError, api.PyUnicode_SetDefaultEncoding, 
lltype.nullptr(rffi.CCHARP.TO))
-        assert api.PyUnicode_SetDefaultEncoding(invalid) == -1
-        assert api.PyErr_Occurred() is space.w_LookupError
-        api.PyErr_Clear()
-        assert api.PyUnicode_SetDefaultEncoding(utf_8) == 0
-        assert rffi.charp2str(api.PyUnicode_GetDefaultEncoding()) == 'utf-8'
-        assert api.PyUnicode_SetDefaultEncoding(prev_encoding) == 0
+        with raises_w(space, TypeError):
+            PyUnicode_SetDefaultEncoding(space, lltype.nullptr(rffi.CCHARP.TO))
+        with raises_w(space, LookupError):
+            PyUnicode_SetDefaultEncoding(space, invalid)
+
+        assert PyUnicode_SetDefaultEncoding(space, utf_8) == 0
+        assert rffi.charp2str(PyUnicode_GetDefaultEncoding(space, )) == 'utf-8'
+        assert PyUnicode_SetDefaultEncoding(space, prev_encoding) == 0
         rffi.free_charp(invalid)
         rffi.free_charp(utf_8)
         rffi.free_charp(prev_encoding)
 
-    def test_AS(self, space, api):
+    def test_AS(self, space):
         word = space.wrap(u'spam')
-        array = rffi.cast(rffi.CWCHARP, api.PyUnicode_AS_DATA(word))
-        array2 = api.PyUnicode_AS_UNICODE(word)
-        array3 = api.PyUnicode_AsUnicode(word)
+        array = rffi.cast(rffi.CWCHARP, PyUnicode_AS_DATA(space, word))
+        array2 = PyUnicode_AS_UNICODE(space, word)
+        array3 = PyUnicode_AsUnicode(space, word)
         for (i, char) in enumerate(space.unwrap(word)):
             assert array[i] == char
             assert array2[i] == char
             assert array3[i] == char
-        self.raises(space, api, TypeError, api.PyUnicode_AsUnicode,
-                    space.wrap('spam'))
+        with raises_w(space, TypeError):
+            PyUnicode_AsUnicode(space, space.wrap('spam'))
 
         utf_8 = rffi.str2charp('utf-8')
-        encoded = api.PyUnicode_AsEncodedString(space.wrap(u'sp&#65533;m'),
+        encoded = PyUnicode_AsEncodedString(space, space.wrap(u'sp&#65533;m'),
                                                 utf_8, None)
         assert space.unwrap(encoded) == 'sp\xef\xbf\xbdm'
-        encoded_obj = api.PyUnicode_AsEncodedObject(space.wrap(u'sp&#65533;m'),
+        encoded_obj = PyUnicode_AsEncodedObject(space, 
space.wrap(u'sp&#65533;m'),
                                                 utf_8, None)
         assert space.eq_w(encoded, encoded_obj)
-        self.raises(space, api, TypeError, api.PyUnicode_AsEncodedString,
-               space.newtuple([1, 2, 3]), None, None)
-        self.raises(space, api, TypeError, api.PyUnicode_AsEncodedString,
-               space.wrap(''), None, None)
+        with raises_w(space, TypeError):
+            PyUnicode_AsEncodedString(
+                space, space.newtuple([1, 2, 3]), None, None)
+        with raises_w(space, TypeError):
+            PyUnicode_AsEncodedString(space, space.wrap(''), None, None)
         ascii = rffi.str2charp('ascii')
         replace = rffi.str2charp('replace')
-        encoded = api.PyUnicode_AsEncodedString(space.wrap(u'sp&#65533;m'),
+        encoded = PyUnicode_AsEncodedString(space, space.wrap(u'sp&#65533;m'),
                                                 ascii, replace)
         assert space.unwrap(encoded) == 'sp?m'
         rffi.free_charp(utf_8)
@@ -189,38 +193,38 @@
         rffi.free_charp(ascii)
 
         buf = rffi.unicode2wcharp(u"12345")
-        api.PyUnicode_AsWideChar(space.wrap(u'longword'), buf, 5)
+        PyUnicode_AsWideChar(space, space.wrap(u'longword'), buf, 5)
         assert rffi.wcharp2unicode(buf) == 'longw'
-        api.PyUnicode_AsWideChar(space.wrap(u'a'), buf, 5)
+        PyUnicode_AsWideChar(space, space.wrap(u'a'), buf, 5)
         assert rffi.wcharp2unicode(buf) == 'a'
         rffi.free_wcharp(buf)
 
-    def test_fromstring(self, space, api):
+    def test_fromstring(self, space):
         s = rffi.str2charp(u'sp\x09m'.encode("utf-8"))
-        w_res = api.PyUnicode_FromString(s)
+        w_res = PyUnicode_FromString(space, s)
         assert space.unwrap(w_res) == u'sp\x09m'
 
-        res = api.PyUnicode_FromStringAndSize(s, 4)
+        res = PyUnicode_FromStringAndSize(space, s, 4)
         w_res = from_ref(space, res)
-        api.Py_DecRef(res)
+        Py_DecRef(space, res)
         assert space.unwrap(w_res) == u'sp\x09m'
         rffi.free_charp(s)
 
-    def test_unicode_resize(self, space, api):
+    def test_unicode_resize(self, space):
         py_uni = new_empty_unicode(space, 10)
         ar = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
         py_uni.c_str[0] = u'a'
         py_uni.c_str[1] = u'b'
         py_uni.c_str[2] = u'c'
         ar[0] = rffi.cast(PyObject, py_uni)
-        api.PyUnicode_Resize(ar, 3)
+        PyUnicode_Resize(space, ar, 3)
         py_uni = rffi.cast(PyUnicodeObject, ar[0])
         assert py_uni.c_length == 3
         assert py_uni.c_str[1] == u'b'
         assert py_uni.c_str[3] == u'\x00'
         # the same for growing
         ar[0] = rffi.cast(PyObject, py_uni)
-        api.PyUnicode_Resize(ar, 10)
+        PyUnicode_Resize(space, ar, 10)
         py_uni = rffi.cast(PyUnicodeObject, ar[0])
         assert py_uni.c_length == 10
         assert py_uni.c_str[1] == 'b'
@@ -228,47 +232,46 @@
         Py_DecRef(space, ar[0])
         lltype.free(ar, flavor='raw')
 
-    def test_AsUTF8String(self, space, api):
+    def test_AsUTF8String(self, space):
         w_u = space.wrap(u'sp\x09m')
-        w_res = api.PyUnicode_AsUTF8String(w_u)
+        w_res = PyUnicode_AsUTF8String(space, w_u)
         assert space.type(w_res) is space.w_str
         assert space.unwrap(w_res) == 'sp\tm'
 
-    def test_decode_utf8(self, space, api):
+    def test_decode_utf8(self, space):
         u = rffi.str2charp(u'sp\x134m'.encode("utf-8"))
-        w_u = api.PyUnicode_DecodeUTF8(u, 5, None)
+        w_u = PyUnicode_DecodeUTF8(space, u, 5, None)
         assert space.type(w_u) is space.w_unicode
         assert space.unwrap(w_u) == u'sp\x134m'
 
-        w_u = api.PyUnicode_DecodeUTF8(u, 2, None)
+        w_u = PyUnicode_DecodeUTF8(space, u, 2, None)
         assert space.type(w_u) is space.w_unicode
         assert space.unwrap(w_u) == 'sp'
         rffi.free_charp(u)
 
-    def test_encode_utf8(self, space, api):
+    def test_encode_utf8(self, space):
         u = rffi.unicode2wcharp(u'sp\x09m')
-        w_s = api.PyUnicode_EncodeUTF8(u, 4, None)
+        w_s = PyUnicode_EncodeUTF8(space, u, 4, None)
         assert space.unwrap(w_s) == u'sp\x09m'.encode('utf-8')
         rffi.free_wcharp(u)
 
-    def test_encode_decimal(self, space, api):
+    def test_encode_decimal(self, space):
         with rffi.scoped_unicode2wcharp(u' (12, 35 ABC)') as u:
             with rffi.scoped_alloc_buffer(20) as buf:
-                res = api.PyUnicode_EncodeDecimal(u, 13, buf.raw, None)
+                res = PyUnicode_EncodeDecimal(space, u, 13, buf.raw, None)
                 s = rffi.charp2str(buf.raw)
         assert res == 0
         assert s == ' (12, 35 ABC)'
 
         with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
             with rffi.scoped_alloc_buffer(20) as buf:
-                res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw, None)
-        assert res == -1
-        api.PyErr_Clear()
+                with pytest.raises(OperationError):
+                    PyUnicode_EncodeDecimal(space, u, 9, buf.raw, None)
 
         with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
             with rffi.scoped_alloc_buffer(20) as buf:
                 with rffi.scoped_str2charp("replace") as errors:
-                    res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw,
+                    res = PyUnicode_EncodeDecimal(space, u, 9, buf.raw,
                                                       errors)
                 s = rffi.charp2str(buf.raw)
         assert res == 0
@@ -277,140 +280,140 @@
         with rffi.scoped_unicode2wcharp(u'12\u1234') as u:
             with rffi.scoped_alloc_buffer(20) as buf:
                 with rffi.scoped_str2charp("xmlcharrefreplace") as errors:
-                    res = api.PyUnicode_EncodeDecimal(u, 3, buf.raw,
+                    res = PyUnicode_EncodeDecimal(space, u, 3, buf.raw,
                                                       errors)
                 s = rffi.charp2str(buf.raw)
         assert res == 0
         assert s == "12&#4660;"
 
 
-    def test_IS(self, space, api):
+    def test_IS(self, space):
         for char in [0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1c, 0x1d, 0x1e, 0x1f,
                      0x20, 0x85, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002,
                      0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008,
                      0x2009, 0x200a,
                      #0x200b is in Other_Default_Ignorable_Code_Point in 4.1.0
                      0x2028, 0x2029, 0x202f, 0x205f, 0x3000]:
-            assert api.Py_UNICODE_ISSPACE(unichr(char))
-        assert not api.Py_UNICODE_ISSPACE(u'a')
+            assert Py_UNICODE_ISSPACE(space, unichr(char))
+        assert not Py_UNICODE_ISSPACE(space, u'a')
 
-        assert api.Py_UNICODE_ISALPHA(u'a')
-        assert not api.Py_UNICODE_ISALPHA(u'0')
-        assert api.Py_UNICODE_ISALNUM(u'a')
-        assert api.Py_UNICODE_ISALNUM(u'0')
-        assert not api.Py_UNICODE_ISALNUM(u'+')
+        assert Py_UNICODE_ISALPHA(space, u'a')
+        assert not Py_UNICODE_ISALPHA(space, u'0')
+        assert Py_UNICODE_ISALNUM(space, u'a')
+        assert Py_UNICODE_ISALNUM(space, u'0')
+        assert not Py_UNICODE_ISALNUM(space, u'+')
 
-        assert api.Py_UNICODE_ISDECIMAL(u'\u0660')
-        assert not api.Py_UNICODE_ISDECIMAL(u'a')
-        assert api.Py_UNICODE_ISDIGIT(u'9')
-        assert not api.Py_UNICODE_ISDIGIT(u'@')
-        assert api.Py_UNICODE_ISNUMERIC(u'9')
-        assert not api.Py_UNICODE_ISNUMERIC(u'@')
+        assert Py_UNICODE_ISDECIMAL(space, u'\u0660')
+        assert not Py_UNICODE_ISDECIMAL(space, u'a')
+        assert Py_UNICODE_ISDIGIT(space, u'9')
+        assert not Py_UNICODE_ISDIGIT(space, u'@')
+        assert Py_UNICODE_ISNUMERIC(space, u'9')
+        assert not Py_UNICODE_ISNUMERIC(space, u'@')
 
         for char in [0x0a, 0x0d, 0x1c, 0x1d, 0x1e, 0x85, 0x2028, 0x2029]:
-            assert api.Py_UNICODE_ISLINEBREAK(unichr(char))
+            assert Py_UNICODE_ISLINEBREAK(space, unichr(char))
 
-        assert api.Py_UNICODE_ISLOWER(u'\xdf') # sharp s
-        assert api.Py_UNICODE_ISUPPER(u'\xde') # capital thorn
-        assert api.Py_UNICODE_ISLOWER(u'a')
-        assert not api.Py_UNICODE_ISUPPER(u'a')
-        assert not api.Py_UNICODE_ISTITLE(u'\xce')
-        assert api.Py_UNICODE_ISTITLE(
+        assert Py_UNICODE_ISLOWER(space, u'\xdf') # sharp s
+        assert Py_UNICODE_ISUPPER(space, u'\xde') # capital thorn
+        assert Py_UNICODE_ISLOWER(space, u'a')
+        assert not Py_UNICODE_ISUPPER(space, u'a')
+        assert not Py_UNICODE_ISTITLE(space, u'\xce')
+        assert Py_UNICODE_ISTITLE(space,
             u'\N{LATIN CAPITAL LETTER L WITH SMALL LETTER J}')
 
-    def test_TOLOWER(self, space, api):
-        assert api.Py_UNICODE_TOLOWER(u'&#65533;') == u'&#65533;'
-        assert api.Py_UNICODE_TOLOWER(u'&#65533;') == u'&#65533;'
+    def test_TOLOWER(self, space):
+        assert Py_UNICODE_TOLOWER(space, u'&#65533;') == u'&#65533;'
+        assert Py_UNICODE_TOLOWER(space, u'&#65533;') == u'&#65533;'
 
-    def test_TOUPPER(self, space, api):
-        assert api.Py_UNICODE_TOUPPER(u'&#65533;') == u'&#65533;'
-        assert api.Py_UNICODE_TOUPPER(u'&#65533;') == u'&#65533;'
+    def test_TOUPPER(self, space):
+        assert Py_UNICODE_TOUPPER(space, u'&#65533;') == u'&#65533;'
+        assert Py_UNICODE_TOUPPER(space, u'&#65533;') == u'&#65533;'
 
-    def test_TOTITLE(self, space, api):
-        assert api.Py_UNICODE_TOTITLE(u'/') == u'/'
-        assert api.Py_UNICODE_TOTITLE(u'&#65533;') == u'&#65533;'
-        assert api.Py_UNICODE_TOTITLE(u'&#65533;') == u'&#65533;'
+    def test_TOTITLE(self, space):
+        assert Py_UNICODE_TOTITLE(space, u'/') == u'/'
+        assert Py_UNICODE_TOTITLE(space, u'&#65533;') == u'&#65533;'
+        assert Py_UNICODE_TOTITLE(space, u'&#65533;') == u'&#65533;'
 
-    def test_TODECIMAL(self, space, api):
-        assert api.Py_UNICODE_TODECIMAL(u'6') == 6
-        assert api.Py_UNICODE_TODECIMAL(u'A') == -1
+    def test_TODECIMAL(self, space):
+        assert Py_UNICODE_TODECIMAL(space, u'6') == 6
+        assert Py_UNICODE_TODECIMAL(space, u'A') == -1
 
-    def test_TODIGIT(self, space, api):
-        assert api.Py_UNICODE_TODIGIT(u'6') == 6
-        assert api.Py_UNICODE_TODIGIT(u'A') == -1
+    def test_TODIGIT(self, space):
+        assert Py_UNICODE_TODIGIT(space, u'6') == 6
+        assert Py_UNICODE_TODIGIT(space, u'A') == -1
 
-    def test_TONUMERIC(self, space, api):
-        assert api.Py_UNICODE_TONUMERIC(u'6') == 6.0
-        assert api.Py_UNICODE_TONUMERIC(u'A') == -1.0
-        assert api.Py_UNICODE_TONUMERIC(u'\N{VULGAR FRACTION ONE HALF}') == .5
+    def test_TONUMERIC(self, space):
+        assert Py_UNICODE_TONUMERIC(space, u'6') == 6.0
+        assert Py_UNICODE_TONUMERIC(space, u'A') == -1.0
+        assert Py_UNICODE_TONUMERIC(space, u'\N{VULGAR FRACTION ONE HALF}') == 
.5
 
-    def test_fromobject(self, space, api):
+    def test_fromobject(self, space):
         w_u = space.wrap(u'a')
-        assert api.PyUnicode_FromObject(w_u) is w_u
+        assert PyUnicode_FromObject(space, w_u) is w_u
         assert space.unwrap(
-            api.PyUnicode_FromObject(space.wrap('test'))) == 'test'
+            PyUnicode_FromObject(space, space.wrap('test'))) == 'test'
 
-    def test_decode(self, space, api):
+    def test_decode(self, space):
         b_text = rffi.str2charp('caf\x82xx')
         b_encoding = rffi.str2charp('cp437')
         assert space.unwrap(
-            api.PyUnicode_Decode(b_text, 4, b_encoding, None)) == u'caf\xe9'
+            PyUnicode_Decode(space, b_text, 4, b_encoding, None)) == u'caf\xe9'
 
-        w_text = api.PyUnicode_FromEncodedObject(space.wrap("test"), 
b_encoding, None)
+        w_text = PyUnicode_FromEncodedObject(space, space.wrap("test"), 
b_encoding, None)
         assert space.isinstance_w(w_text, space.w_unicode)
         assert space.unwrap(w_text) == "test"
 
-        assert api.PyUnicode_FromEncodedObject(space.wrap(u"test"), 
b_encoding, None) is None
-        assert api.PyErr_Occurred() is space.w_TypeError
-        assert api.PyUnicode_FromEncodedObject(space.wrap(1), b_encoding, 
None) is None
-        assert api.PyErr_Occurred() is space.w_TypeError
-        api.PyErr_Clear()
+        with raises_w(space, TypeError):
+            PyUnicode_FromEncodedObject(space, space.wrap(u"test"),
+                                        b_encoding, None)
+        with raises_w(space, TypeError):
+            PyUnicode_FromEncodedObject(space, space.wrap(1), b_encoding, None)
 
         rffi.free_charp(b_text)
         rffi.free_charp(b_encoding)
 
-    def test_decode_null_encoding(self, space, api):
+    def test_decode_null_encoding(self, space):
         null_charp = lltype.nullptr(rffi.CCHARP.TO)
         u_text = u'abcdefg'
-        s_text = space.str_w(api.PyUnicode_AsEncodedString(space.wrap(u_text), 
null_charp, null_charp))
+        s_text = space.str_w(PyUnicode_AsEncodedString(space, 
space.wrap(u_text), null_charp, null_charp))
         b_text = rffi.str2charp(s_text)
-        assert space.unwrap(api.PyUnicode_Decode(b_text, len(s_text), 
null_charp, null_charp)) == u_text
-        self.raises(space, api, TypeError, api.PyUnicode_FromEncodedObject, 
space.wrap(u_text), null_charp, None)
+        assert space.unwrap(PyUnicode_Decode(space, b_text, len(s_text), 
null_charp, null_charp)) == u_text
+        with raises_w(space, TypeError):
+            PyUnicode_FromEncodedObject(
+                space, space.wrap(u_text), null_charp, None)
         rffi.free_charp(b_text)
 
-    def test_mbcs(self, space, api):
+    def test_mbcs(self, space):
         if sys.platform != 'win32':
             py.test.skip("mcbs encoding only exists on Windows")
         # unfortunately, mbcs is locale-dependent.
         # This tests works at least on a Western Windows.
         unichars = u"abc" + unichr(12345)
         wbuf = rffi.unicode2wcharp(unichars)
-        w_str = api.PyUnicode_EncodeMBCS(wbuf, 4, None)
+        w_str = PyUnicode_EncodeMBCS(space, wbuf, 4, None)
         rffi.free_wcharp(wbuf)
         assert space.type(w_str) is space.w_str
         assert space.str_w(w_str) == "abc?"
 
-    def test_escape(self, space, api):
+    def test_escape(self, space):
         def test(ustr):
             w_ustr = space.wrap(ustr.decode('Unicode-Escape'))
-            result = api.PyUnicode_AsUnicodeEscapeString(w_ustr)
+            result = PyUnicode_AsUnicodeEscapeString(space, w_ustr)
             assert space.eq_w(space.wrap(ustr), result)
 
         test('\\u674f\\u7f8e')
         test('\\u0105\\u0107\\u017c\\u017a')
         test('El Ni\\xf1o')
 
-    def test_ascii(self, space, api):
+    def test_ascii(self, space):
         ustr = "abcdef"
         w_ustr = space.wrap(ustr.decode("ascii"))
-        result = api.PyUnicode_AsASCIIString(w_ustr)
+        result = PyUnicode_AsASCIIString(space, w_ustr)
+        assert space.eq_w(space.wrap(ustr), result)
+        with raises_w(space, UnicodeEncodeError):
+            PyUnicode_AsASCIIString(space, space.wrap(u"abcd\xe9f"))
 
-        assert space.eq_w(space.wrap(ustr), result)
-
-        w_ustr = space.wrap(u"abcd\xe9f")
-        self.raises(space, api, UnicodeEncodeError, 
api.PyUnicode_AsASCIIString, w_ustr)
-
-    def test_decode_utf16(self, space, api):
+    def test_decode_utf16(self, space):
         def test(encoded, endian, realendian=None):
             encoded_charp = rffi.str2charp(encoded)
             strict_charp = rffi.str2charp("strict")
@@ -426,7 +429,7 @@
             else:
                 pendian = None
 
-            w_ustr = api.PyUnicode_DecodeUTF16(encoded_charp, len(encoded), 
strict_charp, pendian)
+            w_ustr = PyUnicode_DecodeUTF16(space, encoded_charp, len(encoded), 
strict_charp, pendian)
             assert space.eq_w(space.call_method(w_ustr, 'encode', 
space.wrap('ascii')),
                               space.wrap("abcd"))
 
@@ -446,7 +449,7 @@
         test("\xFE\xFF\x00\x61\x00\x62\x00\x63\x00\x64", 0, 1)
         test("\xFF\xFE\x61\x00\x62\x00\x63\x00\x64\x00", 0, -1)
 
-    def test_decode_utf32(self, space, api):
+    def test_decode_utf32(self, space):
         def test(encoded, endian, realendian=None):
             encoded_charp = rffi.str2charp(encoded)
             strict_charp = rffi.str2charp("strict")
@@ -462,7 +465,8 @@
             else:
                 pendian = None
 
-            w_ustr = api.PyUnicode_DecodeUTF32(encoded_charp, len(encoded), 
strict_charp, pendian)
+            w_ustr = PyUnicode_DecodeUTF32(space, encoded_charp, len(encoded),
+                                           strict_charp, pendian)
             assert space.eq_w(space.call_method(w_ustr, 'encode', 
space.wrap('ascii')),
                               space.wrap("ab"))
 
@@ -485,148 +489,150 @@
         test("\x00\x00\xFE\xFF\x00\x00\x00\x61\x00\x00\x00\x62", 0, 1)
         test("\xFF\xFE\x00\x00\x61\x00\x00\x00\x62\x00\x00\x00", 0, -1)
 
-    def test_compare(self, space, api):
-        assert api.PyUnicode_Compare(space.wrap('a'), space.wrap('b')) == -1
+    def test_compare(self, space):
+        assert PyUnicode_Compare(space, space.wrap('a'), space.wrap('b')) == -1
 
-    def test_concat(self, space, api):
-        w_res = api.PyUnicode_Concat(space.wrap(u'a'), space.wrap(u'b'))
+    def test_concat(self, space):
+        w_res = PyUnicode_Concat(space, space.wrap(u'a'), space.wrap(u'b'))
         assert space.unwrap(w_res) == u'ab'
 
-    def test_copy(self, space, api):
+    def test_copy(self, space):
         w_x = space.wrap(u"abcd\u0660")
         count1 = space.int_w(space.len(w_x))
         target_chunk = lltype.malloc(rffi.CWCHARP.TO, count1, flavor='raw')
 
-        x_chunk = api.PyUnicode_AS_UNICODE(w_x)
-        api.Py_UNICODE_COPY(target_chunk, x_chunk, 4)
+        x_chunk = PyUnicode_AS_UNICODE(space, w_x)
+        Py_UNICODE_COPY(space, target_chunk, x_chunk, 4)
         w_y = space.wrap(rffi.wcharpsize2unicode(target_chunk, 4))
 
         assert space.eq_w(w_y, space.wrap(u"abcd"))
 
-        size = api.PyUnicode_GET_SIZE(w_x)
-        api.Py_UNICODE_COPY(target_chunk, x_chunk, size)
+        size = PyUnicode_GET_SIZE(space, w_x)
+        Py_UNICODE_COPY(space, target_chunk, x_chunk, size)
         w_y = space.wrap(rffi.wcharpsize2unicode(target_chunk, size))
 
         assert space.eq_w(w_y, w_x)
 
         lltype.free(target_chunk, flavor='raw')
 
-    def test_ascii_codec(self, space, api):
+    def test_ascii_codec(self, space):
         s = 'abcdefg'
         data = rffi.str2charp(s)
-        w_u = api.PyUnicode_DecodeASCII(data, len(s), 
lltype.nullptr(rffi.CCHARP.TO))
+        NULL = lltype.nullptr(rffi.CCHARP.TO)
+        w_u = PyUnicode_DecodeASCII(space, data, len(s), NULL)
         assert space.eq_w(w_u, space.wrap(u"abcdefg"))
         rffi.free_charp(data)
 
         s = 'abcd\xFF'
         data = rffi.str2charp(s)
-        self.raises(space, api, UnicodeDecodeError, api.PyUnicode_DecodeASCII,
-                    data, len(s), lltype.nullptr(rffi.CCHARP.TO))
+        with raises_w(space, UnicodeDecodeError):
+            PyUnicode_DecodeASCII(space, data, len(s), NULL)
         rffi.free_charp(data)
 
         uni = u'abcdefg'
         data = rffi.unicode2wcharp(uni)
-        w_s = api.PyUnicode_EncodeASCII(data, len(uni), 
lltype.nullptr(rffi.CCHARP.TO))
+        w_s = PyUnicode_EncodeASCII(space, data, len(uni), NULL)
         assert space.eq_w(space.wrap("abcdefg"), w_s)
         rffi.free_wcharp(data)
 
         u = u'&#65533;bcd&#65533;fg'
         data = rffi.unicode2wcharp(u)
-        w_s = api.PyUnicode_EncodeASCII(data, len(u), 
lltype.nullptr(rffi.CCHARP.TO))
-        self.raises(space, api, UnicodeEncodeError, api.PyUnicode_EncodeASCII,
-                    data, len(u), lltype.nullptr(rffi.CCHARP.TO))
+        with raises_w(space, UnicodeEncodeError):
+            PyUnicode_EncodeASCII(space, data, len(u), NULL)
         rffi.free_wcharp(data)
 
-    def test_latin1(self, space, api):
+    def test_latin1(self, space):
         s = 'abcdefg'
         data = rffi.str2charp(s)
-        w_u = api.PyUnicode_DecodeLatin1(data, len(s), 
lltype.nullptr(rffi.CCHARP.TO))
+        w_u = PyUnicode_DecodeLatin1(space, data, len(s),
+                                     lltype.nullptr(rffi.CCHARP.TO))
         assert space.eq_w(w_u, space.wrap(u"abcdefg"))
         rffi.free_charp(data)
 
         uni = u'abcdefg'
         data = rffi.unicode2wcharp(uni)
-        w_s = api.PyUnicode_EncodeLatin1(data, len(uni), 
lltype.nullptr(rffi.CCHARP.TO))
+        w_s = PyUnicode_EncodeLatin1(space, data, len(uni),
+                                     lltype.nullptr(rffi.CCHARP.TO))
         assert space.eq_w(space.wrap("abcdefg"), w_s)
         rffi.free_wcharp(data)
 
         ustr = "abcdef"
         w_ustr = space.wrap(ustr.decode("ascii"))
-        result = api.PyUnicode_AsLatin1String(w_ustr)
+        result = PyUnicode_AsLatin1String(space, w_ustr)
         assert space.eq_w(space.wrap(ustr), result)
 
-    def test_format(self, space, api):
+    def test_format(self, space):
         w_format = space.wrap(u'hi %s')
         w_args = space.wrap((u'test',))
-        w_formated = api.PyUnicode_Format(w_format, w_args)
+        w_formated = PyUnicode_Format(space, w_format, w_args)
         assert space.unwrap(w_formated) == space.unwrap(space.mod(w_format, 
w_args))
 
-    def test_join(self, space, api):
+    def test_join(self, space):
         w_sep = space.wrap(u'<sep>')
         w_seq = space.wrap([u'a', u'b'])
-        w_joined = api.PyUnicode_Join(w_sep, w_seq)
+        w_joined = PyUnicode_Join(space, w_sep, w_seq)
         assert space.unwrap(w_joined) == u'a<sep>b'
 
-    def test_fromordinal(self, space, api):
-        w_char = api.PyUnicode_FromOrdinal(65)
+    def test_fromordinal(self, space):
+        w_char = PyUnicode_FromOrdinal(space, 65)
         assert space.unwrap(w_char) == u'A'
-        w_char = api.PyUnicode_FromOrdinal(0)
+        w_char = PyUnicode_FromOrdinal(space, 0)
         assert space.unwrap(w_char) == u'\0'
-        w_char = api.PyUnicode_FromOrdinal(0xFFFF)
+        w_char = PyUnicode_FromOrdinal(space, 0xFFFF)
         assert space.unwrap(w_char) == u'\uFFFF'
 
-    def test_replace(self, space, api):
+    def test_replace(self, space):
         w_str = space.wrap(u"abababab")
         w_substr = space.wrap(u"a")
         w_replstr = space.wrap(u"z")
         assert u"zbzbabab" == space.unwrap(
-            api.PyUnicode_Replace(w_str, w_substr, w_replstr, 2))
+            PyUnicode_Replace(space, w_str, w_substr, w_replstr, 2))
         assert u"zbzbzbzb" == space.unwrap(
-            api.PyUnicode_Replace(w_str, w_substr, w_replstr, -1))
+            PyUnicode_Replace(space, w_str, w_substr, w_replstr, -1))
 
-    def test_tailmatch(self, space, api):
+    def test_tailmatch(self, space):
         w_str = space.wrap(u"abcdef")
         # prefix match
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("cde"), 2, 9, -1) == 1
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("cde"), 2, 4, -1) == 
0 # ends at 'd'
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("cde"), 1, 6, -1) == 
0 # starts at 'b'
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("cdf"), 2, 6, -1) == 0
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("cde"), 2, 9, -1) 
== 1
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("cde"), 2, 4, -1) 
== 0 # ends at 'd'
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("cde"), 1, 6, -1) 
== 0 # starts at 'b'
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("cdf"), 2, 6, -1) 
== 0
         # suffix match
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("cde"), 1, 5,  1) == 1
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("cde"), 3, 5,  1) == 
0 # starts at 'd'
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("cde"), 1, 6,  1) == 
0 # ends at 'f'
-        assert api.PyUnicode_Tailmatch(w_str, space.wrap("bde"), 1, 5,  1) == 0
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("cde"), 1, 5,  1) 
== 1
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("cde"), 3, 5,  1) 
== 0 # starts at 'd'
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("cde"), 1, 6,  1) 
== 0 # ends at 'f'
+        assert PyUnicode_Tailmatch(space, w_str, space.wrap("bde"), 1, 5,  1) 
== 0
         # type checks
-        self.raises(space, api, TypeError,
-                    api.PyUnicode_Tailmatch, w_str, space.wrap(3), 2, 10, 1)
-        self.raises(space, api, TypeError,
-                    api.PyUnicode_Tailmatch, space.wrap(3), space.wrap("abc"),
-                    2, 10, 1)
+        with raises_w(space, TypeError):
+            PyUnicode_Tailmatch(space, w_str, space.wrap(3), 2, 10, 1)
+        with raises_w(space, TypeError):
+            PyUnicode_Tailmatch(
+                space, space.wrap(3), space.wrap("abc"), 2, 10, 1)
 
-    def test_count(self, space, api):
+    def test_count(self, space):
         w_str = space.wrap(u"abcabdab")
-        assert api.PyUnicode_Count(w_str, space.wrap(u"ab"), 0, -1) == 2
-        assert api.PyUnicode_Count(w_str, space.wrap(u"ab"), 0, 2) == 1
-        assert api.PyUnicode_Count(w_str, space.wrap(u"ab"), -5, 30) == 2
+        assert PyUnicode_Count(space, w_str, space.wrap(u"ab"), 0, -1) == 2
+        assert PyUnicode_Count(space, w_str, space.wrap(u"ab"), 0, 2) == 1
+        assert PyUnicode_Count(space, w_str, space.wrap(u"ab"), -5, 30) == 2
 
-    def test_find(self, space, api):
+    def test_find(self, space):
         w_str = space.wrap(u"abcabcd")
-        assert api.PyUnicode_Find(w_str, space.wrap(u"c"), 0, 7, 1) == 2
-        assert api.PyUnicode_Find(w_str, space.wrap(u"c"), 3, 7, 1) == 5
-        assert api.PyUnicode_Find(w_str, space.wrap(u"c"), 0, 7, -1) == 5
-        assert api.PyUnicode_Find(w_str, space.wrap(u"c"), 3, 7, -1) == 5
-        assert api.PyUnicode_Find(w_str, space.wrap(u"c"), 0, 4, -1) == 2
-        assert api.PyUnicode_Find(w_str, space.wrap(u"z"), 0, 4, -1) == -1
+        assert PyUnicode_Find(space, w_str, space.wrap(u"c"), 0, 7, 1) == 2
+        assert PyUnicode_Find(space, w_str, space.wrap(u"c"), 3, 7, 1) == 5
+        assert PyUnicode_Find(space, w_str, space.wrap(u"c"), 0, 7, -1) == 5
+        assert PyUnicode_Find(space, w_str, space.wrap(u"c"), 3, 7, -1) == 5
+        assert PyUnicode_Find(space, w_str, space.wrap(u"c"), 0, 4, -1) == 2
+        assert PyUnicode_Find(space, w_str, space.wrap(u"z"), 0, 4, -1) == -1
 
-    def test_split(self, space, api):
+    def test_split(self, space):
         w_str = space.wrap(u"a\nb\nc\nd")
         assert "[u'a', u'b', u'c', u'd']" == space.unwrap(space.repr(
-                api.PyUnicode_Split(w_str, space.wrap('\n'), -1)))
+                PyUnicode_Split(space, w_str, space.wrap('\n'), -1)))
         assert r"[u'a', u'b', u'c\nd']" == space.unwrap(space.repr(
-                api.PyUnicode_Split(w_str, space.wrap('\n'), 2)))
+                PyUnicode_Split(space, w_str, space.wrap('\n'), 2)))
         assert r"[u'a', u'b', u'c d']" == space.unwrap(space.repr(
-                api.PyUnicode_Split(space.wrap(u'a\nb  c d'), None, 2)))
+                PyUnicode_Split(space, space.wrap(u'a\nb  c d'), None, 2)))
         assert "[u'a', u'b', u'c', u'd']" == space.unwrap(space.repr(
-                api.PyUnicode_Splitlines(w_str, 0)))
+                PyUnicode_Splitlines(space, w_str, 0)))
         assert r"[u'a\n', u'b\n', u'c\n', u'd']" == space.unwrap(space.repr(
-                api.PyUnicode_Splitlines(w_str, 1)))
+                PyUnicode_Splitlines(space, w_str, 1)))
diff --git a/pypy/module/cpyext/unicodeobject.py 
b/pypy/module/cpyext/unicodeobject.py
--- a/pypy/module/cpyext/unicodeobject.py
+++ b/pypy/module/cpyext/unicodeobject.py
@@ -487,6 +487,7 @@
         if not PyUnicode_Check(space, w_unicode):
             PyErr_BadArgument(space)
         return unicodeobject.encode_object(space, w_unicode, encoding, 
"strict")
+    globals()['PyUnicode_As%sString' % suffix] = PyUnicode_AsXXXString
 
     @cpython_api([CONST_STRING, Py_ssize_t, CONST_STRING], PyObject)
     @func_renamer('PyUnicode_Decode%s' % suffix)
_______________________________________________
pypy-commit mailing list
[email protected]
https://mail.python.org/mailman/listinfo/pypy-commit

Reply via email to