question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

pytest event loop is already running

See original GitHub issue

Because the test client calls loop.run_until_complete(connection(receive, send)), I cannot use anything that modifies the event loop in a pytest fixture without getting RuntimeError: This event loop is already running.

I would like to use a package like aresponses to mock aiohttp requests like this:

@pytest.fixture
def mock_endpoint(aresponses):
    aresponses.add('mock.com', '/test/', 'get', 'this is my mock response')

After messing with it for a couple hours, the only way I was able to get successful tests was to wrap the application in middleware:

@pytest.fixture
def app():
    class App:
        def __init__(self, app):
            self.app = app

        def __call__(self, scope):
            return functools.partial(self.asgi, scope=scope)

        async def asgi(self, receive, send, scope):
            async with ResponsesMockServer() as aresponses:
                aresponses.add('mock.com', '/test/', 'get', 'this is my mock response')
                inner = self.app(scope)
                await inner(receive, send)
    return App(application)


@pytest.fixture
def test_client(app):
    with TestClient(app) as test_client:
        yield test_client

I am going to modify this to allow myself to dynamically pass responses through the @pytest.mark decorator, but this workflow is not really convenient at all.

Am I missing something here? Is there a better way to set up my test clients, or should I just keep going down this route?

Thanks

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:6
  • Comments:22 (7 by maintainers)

github_iconTop GitHub Comments

13reactions
teskjecommented, Jun 27, 2019

Just FYI, I’m also stumbling over this currently trying to use the TestClient in an async test function (with pytest-asyncio). Minimal test case:

import pytest
from starlette.responses import HTMLResponse
from starlette.testclient import TestClient

async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = HTMLResponse('<html><body>Hello, world!</body></html>')
    await response(scope, receive, send)

@pytest.mark.asyncio
async def test_app():
    client = TestClient(app)
    response = client.get('/')
    assert response.status_code == 200

Fails with “RuntimeError: This event loop is already running” too. I guess there is currently no workaround, aside from just not using async tests, which I think wouldn’t work in my specific case.

Thank you for working on this!

7reactions
taybincommented, Sep 12, 2019

I have a similar problem where I’m also trying to embed a database connection with a transaction active for the current test in the request.state. I haven’t quite found the magic configuration of pytest, pytest-asyncio, and TestClient to make this work yet.

Basically, I’d love to see an example of how to use TestClient along with databases/asyncpg.

Read more comments on GitHub >

github_iconTop Results From Across the Web

RuntimeError: This event loop is already running in python
I got the issue resolved by using the nest_async pip install nest-asyncio. and adding below lines in my file.
Read more >
How to get around “RuntimeError: This event loop is already ...
The solution was to use nest-asyncio. This package patches “asyncio” and allows nested usage “loop. run_until_complete”. I have simply patched ...
Read more >
RuntimeError: This event loop is already running in python
... This event loop is already running in python [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON : Ru...
Read more >
How I Tested Asyncio Code in PHX Events - OfferZen
It is only possible to invoke the event loop directly to run code. That's why pytest wouldn't be able to test the async...
Read more >
Event Loop — Python 3.11.1 documentation
The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found