Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test passes but ERROR is thrown when closing a generator, only shows up in pytest-asyncio pytest run #203

Closed
jreiberkyle opened this issue Jan 30, 2021 · 1 comment

Comments

@jreiberkyle
Copy link

jreiberkyle commented Jan 30, 2021

I am running python 3.7.9 and pytest-asyncio 0.14.0 / pytest 6.2.1. When I run the following code in pytest, I get an error thrown even though the test passes.

$>pytest -vv test.py --log-cli-level=DEBUG

test.py

import pytest
@pytest.mark.asyncio
async def test_generator_limit():
    async def gen():
        yield 1
        yield 2
        yield 3
        yield 4

    async for res in gen():
        if res == 2:
            break

ERROR asyncio:base_events.py:1619 Task was destroyed but it is pending! task: <Task pending coro=<<async_generator_athrow without __name__>()>>

If I run this code as a script, I get no such error

import asyncio

async def test_generator_limit():
    async def gen():
        yield 1
        yield 2
        yield 3
        yield 4

    async for res in gen():
        if res == 2:
            break

asyncio.run(test_generator_limit(), debug=True)

(NOTE: the value of debug does not change the results)

This error only shows up when I introduce the break. According to PEP 525 this appears to be valid async code.

@jreiberkyle jreiberkyle changed the title ERROR when closing a generator, only shows up in pytest-asyncio test run test passes but ERROR is thrown when closing a generator, only shows up in pytest-asyncio pytest run Jan 30, 2021
@seifertm
Copy link
Contributor

seifertm commented Jan 7, 2022

Thanks for the report and for the great examples! The issue is still present in pytest-async v0.16.

asyncio.run cleans up any async generator functions before exiting (see #222). This is why you don't see the "Task pending error" when running your second example. pytest-asyncio does no such thing when the event_loop fixture is torn down, resulting in the error you describe.

Issue #222 proposed that pytest-asyncio should behave similar to asyncio.run and clean up existing tasks. We closed that in favour of #235. I hope you don't mind if I do the same here. Let's continue the discussion in #235.

@seifertm seifertm closed this as completed Jan 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants