Skip to content

Task finalizers run outside of event loop #878

Open
@CGamesPlay

Description

Something about how pytest-asyncio is handling finalizers isn't working right. When a task is abandoned by a test, the task's finalizers get run outside of the event loop, meaning any async cleanup will not be run. The following test fails with pytest-asyncio, but works fine if you switch to using asyncio.run.

import asyncio
import pytest

async def func():
    try:
        await asyncio.sleep(0.1)
    finally:
        assert asyncio.current_task() is not None

@pytest.mark.asyncio
async def test_it():
    asyncio.create_task(func())

I encountered this issue because my cleanup code was calling ContextVar.reset, and it would emit a warning (shown below), and I believe this is the root cause.

ValueError: <Token var=<ContextVar name='var' at 0x106a40a40> at 0x106a74240> was created in a different Context

Python 3.11.9
Pytest 8.2.2
pytest-asyncio 0.23.7

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions