Skip to content

Pytest finalizer fails when using both ASGIWebSocketTransport and pytest-asyncio #128

@Toilal

Description

@Toilal

Describe the bug

When using pytest-asyncio instead of anyio pytest plugin, the test teardown fails with following error

RuntimeError: Attempted to exit cancel scope in a different task than it was entered in

I can't reproduce the issue when running anyio pytest plugin.

To Reproduce

I've create a small git repository to help reproduce the issue (Hello World FastAPI Websocket, single test, pytest + pytest-asyncio)

Steps to reproduce the behavior:

  1. Go to https://github.com/Pysae/httpx-ws-pytest
  2. Clone the repository
  3. poetry install
  4. run pytest

Expected behavior

Should be green !

Configuration

  • Python version: 3.14
  • httpx-ws version:
    "httpx (>=0.28.1,<0.29.0)",
    "httpx-ws (>=0.8.2,<0.9.0)",
    "fastapi (>=0.121.3,<0.122.0)"
]```

## Additional context

```@pytest.fixture(scope="session")
    async def client(app: FastAPI) -> AsyncGenerator[AsyncClient, None]:
>       async with AsyncClient(
                transport=ASGIWebSocketTransport(app=app), base_url="http://testserver/"
        ) as c:

httpx_ws_pytest_tests/test_app.py:20: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
.venv/lib/python3.11/site-packages/httpx/_client.py:2016: in __aexit__
    await self._transport.__aexit__(exc_type, exc_value, traceback)
.venv/lib/python3.11/site-packages/httpx_ws/transport.py:218: in __aexit__
    await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
../../../.pyenv/versions/3.11.2/lib/python3.11/contextlib.py:733: in __aexit__
    raise exc_details[1]
../../../.pyenv/versions/3.11.2/lib/python3.11/contextlib.py:716: in __aexit__
    cb_suppress = await cb(*exc_details)
                  ^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py:792: in __aexit__
    return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <anyio._backends._asyncio.CancelScope object at 0x7fe91e5dc850>, exc_type = None, exc_val = None

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> bool:
        del exc_tb
    
        if not self._active:
            raise RuntimeError("This cancel scope is not active")
        if current_task() is not self._host_task:
>           raise RuntimeError(
                "Attempted to exit cancel scope in a different task than it was "
                "entered in"
            )
E           RuntimeError: Attempted to exit cancel scope in a different task than it was entered in

.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py:459: RuntimeError
--------------------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------------------
Client disconnected
========================================================================== short test summary info ==========================================================================
ERROR httpx_ws_pytest_tests/test_app.py::test_ws - RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
======================================================================== 1 passed, 1 error in 0.33s =========================================================================

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions