| 1 |
from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase |
| 2 |
from pypy.module.cpyext.test.test_api import BaseApiTest |
| 3 |
from pypy.module.cpyext.genobject import PyGen_Check, PyGen_CheckExact |
| 4 |
from pypy.module.cpyext.genobject import PyCoro_CheckExact |
| 5 |
|
| 6 |
|
| 7 |
class TestGenObject(BaseApiTest): |
| 8 |
def test_genobject(self, space): |
| 9 |
w_geniter = space.appexec([], """(): |
| 10 |
def f(): |
| 11 |
yield 42 |
| 12 |
return f() |
| 13 |
""") |
| 14 |
assert PyGen_Check(space, w_geniter) |
| 15 |
assert PyGen_CheckExact(space, w_geniter) |
| 16 |
assert not PyCoro_CheckExact(space, w_geniter) |
| 17 |
assert not PyGen_Check(space, space.wrap(2)) |
| 18 |
assert not PyGen_CheckExact(space, space.wrap("b")) |
| 19 |
assert not PyCoro_CheckExact(space, space.wrap([])) |
| 20 |
|
| 21 |
w_coroutine = space.appexec([], """(): |
| 22 |
async def f(): |
| 23 |
pass |
| 24 |
return f() |
| 25 |
""") |
| 26 |
assert not PyGen_Check(space, w_coroutine) |
| 27 |
assert not PyGen_CheckExact(space, w_coroutine) |
| 28 |
assert PyCoro_CheckExact(space, w_coroutine) |
| 29 |
|
| 30 |
class AppTestCoroutine(AppTestCpythonExtensionBase): |
| 31 |
def test_generator_coroutine(self): |
| 32 |
module = self.import_extension('test_gen', [ |
| 33 |
('is_coroutine', 'METH_O', |
| 34 |
''' |
| 35 |
if (!PyGen_CheckExact(args)) |
| 36 |
Py_RETURN_NONE; |
| 37 |
PyObject* co = ((PyGenObject*)args)->gi_code; |
| 38 |
if (((PyCodeObject*)co)->co_flags & CO_ITERABLE_COROUTINE) |
| 39 |
Py_RETURN_TRUE; |
| 40 |
else |
| 41 |
Py_RETURN_FALSE; |
| 42 |
''')]) |
| 43 |
|
| 44 |
def it(): |
| 45 |
yield 42 |
| 46 |
|
| 47 |
assert module.is_coroutine(it()) is False |
| 48 |
self.debug_collect() |
| 49 |
from types import coroutine |
| 50 |
assert module.is_coroutine(coroutine(it)()) is True |
| 51 |
|
| 52 |
def test_await(self): |
| 53 |
""" |
| 54 |
module = self.import_extension('test_coroutine', [ |
| 55 |
('await_', 'METH_O', |
| 56 |
''' |
| 57 |
PyAsyncMethods* am = args->ob_type->tp_as_async; |
| 58 |
if (am && am->am_await) { |
| 59 |
return am->am_await(args); |
| 60 |
} |
| 61 |
PyErr_SetString(PyExc_TypeError, "Not an awaitable"); |
| 62 |
return NULL; |
| 63 |
'''),]) |
| 64 |
async def f(): |
| 65 |
pass |
| 66 |
raises(StopIteration, next, module.await_(f())) |
| 67 |
""" |