Pytest: runtimeerror there is no current event loop in thread 'mainthread'

Viewed 3943

I am new using asyncio, I have a test function that I am trying to test using pytest: This is my test structure:

MyClass()
    
    async def myFunction(payload, headers):
        session = aiohttp.ClientSession()
        with session.post(url, json=payload, headers=headers) as resp:
        
            response = await resp.json()
    
        return response

then I have my test like:

def my_test():
    loop = asyncio.get_event_loop()
    reponse = loop.run_until_complete(MyClass().myFunction(url, headers))
    loop.close()

when I run my tests I got:

pytest runtimeerror there is no current event loop in thread 'mainthread'

How can I fix it, I feel I need to handle the thread in a different way.

I have seen some related questions but no one using pytests Finally I am using Python 3.8.6.

1 Answers

this should work:

def my_test():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    response = loop.run_until_complete(MyClass().my_function())
    loop.close()
    # assert your response

Explanation:

Since you are calling asyncio.get_event_loop() from a test context it returns a loop that is not be able to use loop.call_later() tha't internally is used by aiohttp.ClientSession(), this is why you need to use loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) see more here: https://github.com/python/cpython/blob/6fcb6cfb139ade1aac6dbee0b18ca72b18cbe0d2/Lib/asyncio/events.py#L735

Related