Skip to content

Loop is closed before fixture teardown completes #708

Closed as not planned
@jpwright

Description

I am looking to use pytest-asyncio to create a fixture that spawns a subprocess and then kills the subprocess when the fixture teardown is complete. I've noticed that the event loop can be closed before the fixture teardown is complete, which can lead to the subprocess kill not working.

Here is a simple example (tested using pytest-asyncio 0.23.2):

import asyncio
import pytest
import pytest_asyncio

import logging
logger = logging.getLogger(__name__)

@pytest_asyncio.fixture
async def echo():
    p = await asyncio.create_subprocess_shell(
        f"sleep 2"
    )
    yield p
    p.kill()

@pytest.mark.asyncio
async def test_echo(echo):
    logger.info(echo)

Which produces the following output:

================================ test session starts =================================
platform linux -- Python 3.11.6, pytest-7.4.3, pluggy-1.3.0
rootdir: /home/jason/pytest-asyncio
plugins: asyncio-0.23.2
asyncio: mode=Mode.STRICT
collected 1 item                                                                     

test.py::test_echo 
----------------------------------- live log call ------------------------------------
INFO     test:test.py:18 <Process 756596>
PASSED                                                                         [100%]
--------------------------------- live log teardown ----------------------------------
WARNING  asyncio:unix_events.py:1427 Loop <_UnixSelectorEventLoop running=False closed=True debug=False> that handles pid 756596 is closed


================================= 1 passed in 0.00s ==================================

I am invoking the test using python3 -m pytest --log-cli-level=INFO ./test.py. I noticed that the issue is intermittent without logging to CLI... perhaps timing-related.

In my actual use case the warning cannot be ignored as the subprocess will not terminate on its own.

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions