-1

How to write unit tests for a FastAPI application with the Prisma client?

I already looked in the documentation and code examples but couldn't find it.

I have this code, but I don't know how to create a mock for the db or configure a db for testing with Prisma:

import pytest
import pytest_asyncio
from httpx import AsyncClient
from asgi_lifespan import LifespanManager

from api.main import app as main_app

@pytest_asyncio.fixture
async def app():
    async with LifespanManager(main_app) as manager:
        yield manager.app

@pytest_asyncio.fixture
async def client(app):
    async with AsyncClient(app=app, base_url="http://test") as client:
        print("Client is ready")
        yield client


@pytest.mark.asyncio
async def test_create_user(client) -> None:
    response = await client.post(
        '/user/', headers={'accept': 'application/json', 'Content-Type': 'application/json'},
        json={
            "user": "test"
        }
    ) # This creates a record in the db in use, but I need a mock
    assert response.status_code == 200
    data = response.json()
    assert data['id'] == 1
    assert data['user'] == 'test'
1
  • Do you use dependencies to get DB session inside endpoints? Commented Jul 8 at 14:41

0

Browse other questions tagged or ask your own question.