42 lines
1.0 KiB
Python
42 lines
1.0 KiB
Python
"""
|
|
Shared pytest fixtures for all backend tests.
|
|
|
|
Strategy:
|
|
- Use mongomock to create an in-memory MongoDB per test.
|
|
- Directly set MongoDB.db to the mock database so get_database() returns it.
|
|
- Patch MongoDB.connect_db / close_db so FastAPI's lifespan doesn't try
|
|
to connect to a real MongoDB server.
|
|
"""
|
|
import pytest
|
|
import mongomock
|
|
from unittest.mock import patch
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_db():
|
|
"""Fresh in-memory MongoDB database for each test."""
|
|
client = mongomock.MongoClient()
|
|
return client["test_grateful_journal"]
|
|
|
|
|
|
@pytest.fixture
|
|
def client(mock_db):
|
|
"""
|
|
FastAPI TestClient with MongoDB replaced by an in-memory mock.
|
|
|
|
Yields (TestClient, mock_db) so tests can inspect the database directly.
|
|
"""
|
|
from db import MongoDB
|
|
from main import app
|
|
|
|
with (
|
|
patch.object(MongoDB, "connect_db"),
|
|
patch.object(MongoDB, "close_db"),
|
|
):
|
|
MongoDB.db = mock_db
|
|
with TestClient(app) as c:
|
|
yield c, mock_db
|
|
|
|
MongoDB.db = None
|