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

Cleaning up pending tasks #435

Closed
matthew-at-qamcom opened this issue Oct 27, 2022 · 3 comments
Closed

Cleaning up pending tasks #435

matthew-at-qamcom opened this issue Oct 27, 2022 · 3 comments

Comments

@matthew-at-qamcom
Copy link

I'm extremely new to asyncio, so my apologies if this is obvious. If I've made an error, I'd love an explanation.

I was receiving the error Task was destroyed but it is pending!, even though all my tests were passing. My tests were basically (1) create web service (2) test API functionality using aiohttp, for example:

@pytest.mark.asyncio
async def test_server_running(event_loop, unused_tcp_port):
    port = unused_tcp_port
    make_service(port) # Creates a Tornado Application

    async with aiohttp.ClientSession() as session:
        async with session.get(f"http://localhost:{port}") as response:
            result = await response.text()
            assert result is not None

    # await tear_down(event_loop) # <-- see below

I was able to resolve this with a tear down function (inspired by the method AsyncTestCase.tearDown().

async def tear_down(event_loop):
    # Collect all tasks and cancel those that are not 'done'.                                       
    tasks = asyncio.all_tasks(event_loop)
    tasks = [t for t in tasks if not t.done()]
    for task in tasks:
        task.cancel()

    # Wait for all tasks to complete, ignoring any CancelledErrors                                  
    try:
        await asyncio.wait(tasks)
    except asyncio.exceptions.CancelledError:
        pass

Is this an appropriate solution to the Task was destroyed but it is pending! error? Did I miss something obvious? Is there a better way?

Thanks.

@matthew-at-qamcom
Copy link
Author

This issue feels similar to #200 and #309.

@seifertm
Copy link
Contributor

seifertm commented Nov 1, 2022

This is certainly not obvious and your question is very valid.

At the moment, there's no "official" way to clean up tasks after a test finishes. Your approach seems to be a reasonable workaround for now.

I'll mark this as a duplicate of #200.

@seifertm seifertm closed this as not planned Won't fix, can't repro, duplicate, stale Nov 1, 2022
@matthew-at-qamcom
Copy link
Author

Thanks for your response. It's greatly appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants