RuntimeWarning: coroutine was never awaited in tests

1k Views Asked by At

i'm trying to mock an async function that is being called inside of a fastapi endpoint but i'm getting the runtime warning that the coroutine _ was never awaited.

src.api.endpoint.py


from ..create_utils import helper_function

Router = APIRouter()

@api_route(
   Router.post,
   '/endpoint',
)
async def endpoint(
   inputs: InputModel,
   db,
   caller,
):
   return await helper_function(inputs, db, caller)


tests.api.endpoint.py


import asyncio
import pytest
import json
import unittest

from unittest.mock import AsyncMock, Mock


@pytest.fixture(scope="function")
async def mock_helper_function(mocker):
    async_mock = AsyncMock()
    sup = mocker.patch('src.api.endpoint.helper_function', 
                 side_effect=async_mock) #where func is being imported not defined
    return async_mock


@pytest.fixture(scope="module")
def event_loop():
    return asyncio.get_event_loop()

@pytest.mark.parametrize(
    'attributes',
    [('CHECKING_ASSET_ATTRIBUTES')]
)
@pytest.mark.asyncio
async def test_endpoint_helper_func(api, attributes, borrower_ids, mock_helper_function):
    caller = 'unauthenticated-user'
    owners = [borrower_ids[caller]]
    response =  await api.response(owners, [attributes], caller) #call to endpoint

    assert response.status_code == 200
    await mock_assets_create.assert_called()

running this test causes the following error

RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited

specs python: 3.9

it appears this answer should solve my issue but doesn't https://stackoverflow.com/a/60094385

i have ran asyncio.iscoroutinefunction() on the patch mock and have confirmed it returns true. both in the fixture and in the test.

i also followed this post for guidance https://stackoverflow.com/a/74012507

1

There are 1 best solutions below

1
On
@pytest.fixture(scope="function")
async def mock_helper_function(mocker):
    async_mock = AsyncMock()
    async_mock.return_value = None
    sup = mocker.patch('src.api.endpoint.helper_function', 
                 side_effect=async_mock) #where func is being imported not defined
    return async_mock