-
Notifications
You must be signed in to change notification settings - Fork 132
Test/backend core coverage #260
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
muhammadtihame
wants to merge
3
commits into
AOSSIE-Org:main
Choose a base branch
from
muhammadtihame:test/backend-core-coverage
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession | ||
| from typing import AsyncGenerator | ||
| from app.core.config import settings | ||
| import logging | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Database configuration | ||
| DATABASE_URL = settings.database_url | ||
|
|
||
| if not DATABASE_URL: | ||
| logger.warning("DATABASE_URL is not set. Database connection pooling will not be available.") | ||
| # Fallback or strict error depending on requirements. | ||
| # For now ensuring tests/code doesn't crash on import if env missing during build. | ||
| # But initialization should be guarded. | ||
|
|
||
| # Initialize SQLAlchemy Async Engine with pooling | ||
| # If DATABASE_URL is missing, engine will be None and get_db will fail/error out appropriately when called | ||
| engine = create_async_engine( | ||
| DATABASE_URL, | ||
| echo=False, | ||
| pool_size=20, # Maintain 20 open connections | ||
| max_overflow=10, # Allow 10 extra during spikes | ||
| pool_timeout=30, # Wait 30s for a connection before raising timeout | ||
| pool_pre_ping=True, # Check connection health before handing it out | ||
| ) if DATABASE_URL else None | ||
|
|
||
| # Session Factory | ||
| async_session_maker = async_sessionmaker( | ||
| engine, | ||
| class_=AsyncSession, | ||
| expire_on_commit=False, | ||
| autocommit=False, | ||
| autoflush=False, | ||
| ) if engine else None | ||
|
|
||
|
|
||
| async def get_db() -> AsyncGenerator[AsyncSession, None]: | ||
| """ | ||
| Dependency to provide a thread-safe database session. | ||
| Ensures that the session is closed after the request is processed. | ||
| """ | ||
| if not async_session_maker: | ||
| raise RuntimeError("Database engine is not initialized. check DATABASE_URL.") | ||
|
|
||
| async with async_session_maker() as session: | ||
| try: | ||
| yield session | ||
| # automatic commit/rollback is often handled by caller or service layer logic | ||
| except Exception: | ||
| logger.exception("Database session error") | ||
| await session.rollback() | ||
| raise | ||
| # session.close() is handled automatically by the async context manager |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # Database Connection Management | ||
|
|
||
| This document describes the thread-safe database connection management implemented for the Devr.AI backend. | ||
|
|
||
| ## Overview | ||
|
|
||
| We use **SQLAlchemy** (AsyncIO) with **asyncpg** to manage a pool of connections to the Supabase PostgreSQL database. This allows for high-concurrency operations without the limitations of HTTP-based PostgREST calls (which `supabase-py` wraps). | ||
|
|
||
| ## Configuration | ||
|
|
||
| The connection manager reads the `DATABASE_URL` from the application settings (loaded from `.env`). | ||
|
|
||
| ```env | ||
| DATABASE_URL=postgresql+asyncpg://user:password@host:5432/dbname | ||
| ``` | ||
|
|
||
| ## Key Components | ||
|
|
||
| ### 1. Engine & Pooling | ||
| Located in `app/database/core.py`. | ||
| - **Pool Size**: 20 connections maintained open. | ||
| - **Max Overflow**: 10 temporary connections allowed during high load. | ||
| - **Pool Timeout**: 30 seconds wait time before raising an error. | ||
| - **Pre-Ping**: Checked before checkout to ensure connection health. | ||
|
|
||
| ### 2. Dependency Injection | ||
| Use `get_db` in FastAPI routes or other async functions to get a session. | ||
|
|
||
| ```python | ||
| from app.database.core import get_db | ||
| from sqlalchemy import text | ||
|
|
||
| @router.get("/items") | ||
| async def read_items(db: AsyncSession = Depends(get_db)): | ||
| result = await db.execute(text("SELECT * FROM items")) | ||
| return result.mappings().all() | ||
| ``` | ||
|
|
||
| The `get_db` generator ensures: | ||
| - A session is created from the pool. | ||
| - The session is passed to the function. | ||
| - The session is **automatically closed** after the function completes (even on error). | ||
| - If an error occurs, the transaction is rolled back. | ||
|
|
||
| ## Testing | ||
| Unit tests in `tests/test_db_pool.py` verify: | ||
| - Pool configuration. | ||
| - Concurrent session acquisition (simulating 50+ parallel requests). | ||
| - Proper cleanup (rollback and close) on errors. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| """ | ||
| Shared pytest fixtures for Devr.AI backend tests. | ||
| """ | ||
| import sys | ||
| import os | ||
| from datetime import datetime | ||
| from typing import Dict, Any | ||
| from unittest.mock import MagicMock, AsyncMock | ||
|
|
||
| import pytest | ||
|
|
||
| # Add backend to path for imports | ||
| sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) | ||
| sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'backend'))) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # Event fixtures | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| @pytest.fixture | ||
| def sample_event_data() -> Dict[str, Any]: | ||
| """Returns minimal valid data for creating a BaseEvent.""" | ||
| return { | ||
| "id": "evt-12345", | ||
| "platform": "discord", | ||
| "event_type": "message.created", | ||
| "actor_id": "user-001", | ||
| "actor_name": "TestUser", | ||
| "channel_id": "chan-001", | ||
| "content": "Hello, how do I contribute?", | ||
| "raw_data": {"original": "payload"}, | ||
| "metadata": {"source": "test"}, | ||
| } | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def sample_faq_event_data(sample_event_data) -> Dict[str, Any]: | ||
| """Event data for a FAQ request.""" | ||
| data = sample_event_data.copy() | ||
| data["event_type"] = "faq.requested" | ||
| data["content"] = "what is devr.ai?" | ||
| return data | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # Handler fixtures | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| @pytest.fixture | ||
| def mock_discord_bot(): | ||
| """Mock Discord bot with channel sending capability.""" | ||
| bot = MagicMock() | ||
| channel = MagicMock() | ||
| channel.send = AsyncMock() | ||
| bot.get_channel = MagicMock(return_value=channel) | ||
| return bot | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # LLM fixtures | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| @pytest.fixture | ||
| def mock_llm_client(): | ||
| """Mock LLM client that returns a valid JSON triage response.""" | ||
| mock_llm = MagicMock() | ||
| mock_response = MagicMock() | ||
| mock_response.content = '{"needs_devrel": true, "priority": "high", "reasoning": "Test reasoning"}' | ||
| mock_llm.ainvoke = AsyncMock(return_value=mock_response) | ||
| return mock_llm | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_llm_client_error(): | ||
| """Mock LLM client that raises an exception.""" | ||
| mock_llm = MagicMock() | ||
| mock_llm.ainvoke = AsyncMock(side_effect=Exception("LLM API Error")) | ||
| return mock_llm |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clarify the module path to match the repo layout.
The file lives under
backend/app/...in this repo; adjusting the path avoids confusion for contributors.✏️ Suggested doc tweak
📝 Committable suggestion
🤖 Prompt for AI Agents