Skip to content

Commit f44c2c0

Browse files
authored
Merge pull request #18 from miracle2k/asyncgen
Asyncgenerators: Tests + Error handling
2 parents 3a06dcf + ff8f34f commit f44c2c0

2 files changed

Lines changed: 33 additions & 3 deletions

File tree

tests/interop/test_calls.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@ class Seen:
99
flag = 0
1010

1111

12+
async def async_gen_to_list(generator):
13+
result = []
14+
async for item in generator:
15+
result.append(item)
16+
return result
17+
18+
1219
class TestCalls(aiotest.TestCase):
1320
async def call_t_a(self, proc, *args, loop=None):
1421
"""called from Trio"""
@@ -231,3 +238,24 @@ def err_asyncio():
231238
with pytest.raises(RuntimeError) as err:
232239
await self.call_t_a(err_asyncio, loop=loop)
233240
assert err.value.args[0] == "I has an owie"
241+
242+
@pytest.mark.trio
243+
async def test_trio_asyncio_generator(self, loop):
244+
async def dly_asyncio():
245+
yield 1
246+
await asyncio.sleep(0.01, loop=loop)
247+
yield 2
248+
249+
res = await async_gen_to_list(loop.wrap_generator(dly_asyncio))
250+
assert res == [1, 2]
251+
252+
@pytest.mark.trio
253+
async def test_trio_asyncio_generator_with_error(self, loop):
254+
async def dly_asyncio():
255+
yield 1
256+
raise RuntimeError("I has an owie")
257+
yield 2
258+
259+
with pytest.raises(RuntimeError) as err:
260+
await async_gen_to_list(loop.wrap_generator(dly_asyncio))
261+
assert err.value.args[0] == "I has an owie"

trio_asyncio/util.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,13 @@ async def run_generator(loop, async_generator):
5959
async def consume_next():
6060
try:
6161
item = await async_generator.__anext__()
62+
result = trio.hazmat.Value(value=item)
6263
except StopAsyncIteration:
63-
item = STOP
64+
result = trio.hazmat.Value(value=STOP)
65+
except Exception as e:
66+
result = trio.hazmat.Error(error=e)
6467

65-
trio.hazmat.reschedule(task, trio.hazmat.Value(value=item))
66-
# trio.hazmat.reschedule(task, STOP)
68+
trio.hazmat.reschedule(task, result)
6769

6870
def abort_cb(raise_cancel_arg):
6971
# Save the cancel-raising function

0 commit comments

Comments
 (0)