Skip to content

Bug: the app for test client is running in a different event loop #1920

Open
@orsinium

Description

@orsinium

Description

I've been trying to make rollbacks for database changes for the SQLAlchemy plugin. See the discussion:

https://github.com/orgs/litestar-org/discussions/1919

And I've encountered the issue described in the discussion above and in this issue:

encode/starlette#1315

RuntimeError: Task <Task pending name='anyio.from_thread.BlockingPortal._call_func' coro=<BlockingPortal._call_func() running at /.../anyio/from_thread.py:219> cb=[TaskGroup._spawn.<locals>.task_done() at /.../anyio/_backends/_asyncio.py:726]> got Future <Future pending cb=[Protocol._on_waiter_completed()]> attached to a different loop

After diving into the issue deeper, I've discovered that BaseTestClient.portal always creates the portal in a separate thread and runs in this thread a new event loop. This behavior is described in the anyio.from_thread.start_blocking_portal function docstring:

Start a new event loop in a new thread and run a blocking portal in its main task.

That means if I create in tests the database connection before calling AsyncTestClient.__aenter__ (or TestClient.__enter__), it will be running in the main thread pytest-asyncio event loop and so it cannot be used as SQLAlchemyAsyncConfig.session_maker. And if you try, with the power of monkey patching, to create the database connection after entering the client context, you cannot use this database connection in the main thread in tests.

URL to code causing the issue

No response

MCVE

No response

Steps to reproduce

No response

Screenshots

No response

Logs

No response

Litestar Version

2.0.0b2

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.xThis is related to Litestar version 3Bug 🐛This is something that is not working as expected

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions