How to mock async python function using fast client?

Viewed 17

I am trying to write a unit test case against this api :

@router.get(
    "",
    summary = "Get All Items",
    response_model = 
        List[Item]
    ],
    status_code = 200
)
async def get_items():
    items = await cosmos_query("items") // method inside common.helper file

Here is my unit test case where I want to return items from "mock_cosmos_query_to_get_items" when I call "await cosmos_query("items")" in my unit test case.

from ast import List
import pytest
from httpx import AsyncClient
from fastapi.testclient import TestClient
from app.main import app
from app.models import Item
from unittest.mock import Mock, patch

async def mock_cosmos_query_to_get_items():
    itemList = List[Item]
    itemList.append(Item('item 1', 'Fake description')) 
    itemList.append(Item('item 2', 'Fake description')) 
    return itemList 



@pytest.mark.asyncio
@patch('common.helper.requests.get')
async def test_get_spaces_when_expand_and_admin_then_get_spaces(mock_get):
    mock_get.return_value.ok = True
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/api/spaces", params={"expand": "true"})
    assert response.status_code == 200

Is this the correct way to mock the function call in async method ? How can I assert number of items and object details in my unit test case ?

0 Answers
Related