Skip to content

Strange behaviour with asyncio.create_task and fixture scope #904

Closed as not planned
@Hernell12

Description

In the following script I create a asyncio task in a fixture which should read the contents of a given queue in the background the moment something gets put into the queue. When the @fixture(scope="function", autouse=True) all the values get read from the queue as they are written to it (as expected). When I change the fixture to @fixture(scope="module", autouse=True) the values only get read from the queue at teardown - the task gets continued only while teardown. In fact this behavior appears for every scope!="function". This seems to be the case for every task created in a fixture and leads to not working tests for fixtures with scopes other than "function".
Am I missing something here and this is intended behavior? Or is this a bug?

from pytest_asyncio import fixture
from pytest import mark
from asyncio import sleep, create_task
from asyncio.queues import Queue
from logging import error


queue = Queue()


async def recv(queue: Queue):
    error(f'recv task started')
    await queue.put("test")
    while True:
        error(f'recv {await queue.get()}')


@fixture(scope="module", autouse=True)
async def fix():
    global queue
    task = create_task(recv(queue))
    yield
    task.cancel()


@mark.asyncio
async def test_test():
    global queue
    for i in range(5):
        error(f'send {i}')
        await queue.put(i)
        await sleep(0.1)
    assert False

image
(scope="function") Expected behavior. The messages get read while the test is running - The task gets continued while the test is running

image
(scope="module") Unexpected behavior. The messages get read at teardown - The task gets continued after the test is run

Metadata

Assignees

No one assigned

    Labels

    needsinfoRequires additional information from the issue author

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions