Skip to content

Testing Example

Testing Example

Python
import pytest
from mongo_ops import (
    MongoConnectionManager,
    BaseDocument,
    BaseRepository,
)
from pydantic import Field
from typing import Optional

# Define Model
class User(BaseDocument):
    username: str = Field(..., min_length=3, max_length=50)
    email: str = Field(...)
    is_active: bool = True

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


@pytest.fixture
async def db():
    await MongoConnectionManager.connect(
        uri="mongodb://localhost:27017",
        db_name="test_db"
    )
    yield MongoConnectionManager.get_database()
    await MongoConnectionManager.get_client().drop_database("test_db")
    await MongoConnectionManager.disconnect()

@pytest.mark.asyncio
async def test_create_user(db):
    repo = UserRepository()
    user = await repo.create(User(username="test", email="test@example.com"))
    assert user.id is not None
    assert user.username == "test"

@pytest.mark.asyncio
async def test_get_by_id(db):
    repo = UserRepository()
    created = await repo.create(User(username="test", email="test@example.com"))
    fetched = await repo.get_by_id(str(created.id))
    assert fetched.username == created.username