Skip to content

Testing Example

A zero-MongoDB unit-test quickstart. The full guide is use case 14.


๐Ÿš€ Mock-Based Quickstart

Patch the connection manager and stub the collection โ€” no network, no docker.

Python
import pytest
from unittest.mock import AsyncMock, patch

from bson import ObjectId
from mongo_ops import BaseDocument, BaseRepository
from mongo_ops.repository import MongoConnectionManager


class User(BaseDocument):
    username: str = ""
    email: str = ""


class UserRepository(BaseRepository[User]):
    def __init__(self):
        super().__init__("users", User)


@pytest.fixture
def repo():
    mock_collection = AsyncMock()
    with patch.object(MongoConnectionManager, "get_database") as mock_db:
        mock_db.return_value.__getitem__.return_value = mock_collection
        r = UserRepository()
        r.collection = mock_collection
        return r


@pytest.mark.asyncio
async def test_create_user(repo):
    mock_collection = repo.collection
    oid = ObjectId()
    mock_collection.insert_one.return_value.inserted_id = oid

    user = await repo.create(User(username="test", email="test@example.com"))

    assert user.id == oid
    assert user.username == "test"


@pytest.mark.asyncio
async def test_get_by_id(repo):
    oid = ObjectId()
    repo.collection.find_one.return_value = {
        "_id": oid,
        "username": "test",
        "email": "test@example.com",
        "created_at": "2024-01-01T00:00:00",
        "updated_at": "2024-01-01T00:00:00",
    }

    fetched = await repo.get_by_id(str(oid))

    assert fetched is not None
    assert fetched.username == "test"

๐Ÿ’ก Notes

  • from mongo_ops.repository import MongoConnectionManager โ€” patch where it is used (mongo_ops.repository.MongoConnectionManager), matching the library's own tests.
  • pytest-asyncio runs as auto mode per pyproject.toml, so @pytest.mark.asyncio works without extra config.
  • For population, cache, registry, and transaction mockups โ€” see the full testing guide.