testing: "There is no current event loop in thread 'MainThread'."
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
I have several modules with unit-tests: test_sum.py
import pytest
from httpx import AsyncClient
pytestmark = pytest.mark.anyio
async def test_sum(app):
async with AsyncClient(app=app, base_url='http://127.0.0.1:5000') as ac:
response = await ac.post('/v1/sum', json={"x": 4, "y": 6})
assert response.status_code == 200
assert response.json() == {"sum": 10}
test_items.py
from tests.expected_data import created_item
from tests.moks_data import items
pytestmark = pytest.mark.anyio
async def test_create_item(app):
async with AsyncClient(app=app, base_url='http://test') as ac:
response = await ac.post('/v1/items', json={
"name": "TestName",
"description": "Test description",
"price": 100
})
assert response.status_code == 200
assert response.json() == created_item
async def test_get_item(fill_db, app):
async with AsyncClient(app=app, base_url='http://test') as ac:
response = await ac.get('/v1/items/2')
assert response.status_code == 200
assert response.json() == items[1]
conftest.py
import pytest
from alembic.command import downgrade, upgrade
from alembic.config import Config as AlembicConfig
from core.app.web import create_app
from core.data.postgres.engine import session_scope
from core.data.postgres.models import Base, Item
from tests.moks_data import items
@pytest.fixture
def app():
app_instance = create_app()
return app_instance
@pytest.fixture(scope='session')
def db_session():
config = AlembicConfig('alembic.ini')
config.attributes['configure_logger'] = False
upgrade(config, 'head')
yield 'on head'
downgrade(config, 'base')
@pytest.fixture(autouse=True)
async def clear_data(db_session):
yield 'I will clear tables for you'
reference_value_tables = [f'{name}' for name in ('role',)]
async with session_scope() as session:
for name, table in Base.metadata.tables.items():
if name not in reference_value_tables:
await session.execute(table.delete())
@pytest.fixture
async def fill_db(event_loop):
items_list = [Item(**item) for item in items]
async with session_scope() as session:
session.add_all(items_list)
await session.flush()
Description
I’m using: python 3.10.1, fastapi 0.72.0, pytest 6.2.5, pytest-trio 0.7.0, sqlalchemy 1.4.31, alembic 1.7.5, asyncpg 0.25.0, postgresql 14.1.** Now, i have issue when i try to execute my tests.
When i run my tests - tests in test_sum is successfully ended but tests in test_items is failed with error:
There is no current event loop in thread 'MainThread'.
Please tell me what I’m doing wrong and how to solve this problem?
Operating System
Linux
Operating System Details
manjaro linux 21.2.1
FastAPI Version
0.72.0
Python Version
3.10.1
Additional Context
tests work correctly with fastapi <= 0.68
Issue Analytics
- State:
- Created 2 years ago
- Comments:7
Top Results From Across the Web
RuntimeError: There is no current event loop in thread in ...
If the target callable is not a coroutine function, it will be run in a worker thread (due to historical reasons), hence the...
Read more >How to fix Python asyncio RuntimeError: There is no current ...
You are trying to run asyncio.get_event_loop() in some thread other than the main thread – however, asyncio only generates an event loop for...
Read more >there is no current event loop in thread 'mainthread' - You.com
This is my first python project and I am a little out of the loop with what is going wrong. However, it appears...
Read more >Event Loop — Python 3.11.1 documentation
Return the running event loop in the current OS thread. Raise a RuntimeError if there is no running event loop. This function can...
Read more >RuntimeError: There is no current event loop in thread ...
The issue is that asyncio.run creates an event loop, runs your coroutine, and then closes the event loop. Therefore you can't use that...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
this material helped me a lot: https://rogulski.it/blog/sqlalchemy-14-async-orm-with-fastapi/
I encountered this when writing my tests as asynchronous tests (
async def test_xyz
) with asyncpg and pytest-asyncio.I found an alternate solution by opting for non-async
def test_xyz
tests and removing any class wrapper! (Which is what broke regular tests for me). While this doesn’t resolve being able to run async code in tests, I was able to test my endpoints this way.