Devr.AI icon indicating copy to clipboard operation
Devr.AI copied to clipboard

Test/backend core coverage

Open muhammadtihame opened this issue 10 months ago • 3 comments

📝 Description

This PR significantly improves backend reliability by adding comprehensive unit test coverage for core handler, event, and agent state modules. While writing tests, a production bug was discovered and fixed in HandlerRegistry.get_handler() related to incorrect assumptions about event value types.

The changes are intentionally scoped to core backend logic and do not introduce new features or alter public APIs.


🔧 Changes Made

  • Added 74 unit tests covering core backend modules:
    • HandlerRegistry
    • BaseHandler
    • MessageHandler
    • FAQHandler
    • ClassificationRouter
    • AgentState
    • BaseEvent
  • Fixed a production bug in HandlerRegistry.get_handler():
    • Previously assumed event.platform and event.event_type were enums with .value
    • Updated logic to safely support both enum and string values
  • Improved test isolation to avoid circular import issues
  • Updated configuration where required to support testing

🐞 Bug Fix Details

Issue HandlerRegistry.get_handler() assumed event.platform and event.event_type were enum objects, but BaseEvent stores these fields as strings in some cases. This caused handler resolution failures at runtime.

Fix The handler key resolution now gracefully handles both enum and string inputs.


🧪 Verification

All scoped backend tests pass locally:

python -m pytest \
tests/test_handler_registry.py \
tests/test_base_handler.py \
tests/test_message_handler.py \
tests/test_faq_handler.py \
tests/test_classification_router.py \
tests/test_agent_state.py \
tests/test_events.py -v


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

* **New Features**
  * Configurable async database connection with pooling and a new code-chunk data model.
  * More flexible event routing accepting varied platform/event-type representations.

* **Documentation**
  * New guide on database connection, pooling, and usage examples.

* **Tests**
  * Large suite of new and expanded tests for handlers, routing, DB pooling, message/FAQ flows, and state.

* **Bug Fixes / Reliability**
  * Improved error handling and safer background task execution; minor test fixes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Final cleanup pushed.

- Fixed syntax errors in test_weaviate.py
- Removed invalid import in test_supabase.py
- No behavior changes
- All 74 unit tests pass

Thanks for the reviews — please let me know if anything else is needed.

muhammadtihame avatar Jan 30 '26 15:01 muhammadtihame

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Added an optional database_url setting and a new async DB core (SQLAlchemy + asyncpg) with a FastAPI get_db dependency; normalized handler registry key resolution; minor message handler cleanup; added DB docs, dependencies, many tests, and small logging/error-handling improvements across orchestration and routing.

Changes

Cohort / File(s) Summary
Configuration
backend/app/core/config/settings.py
Added optional database_url: Optional[str] = None to Settings.
Database core & docs
backend/app/database/core.py, docs/DATABASE_CONNECTION.md
New async SQLAlchemy engine and async_session_maker (asyncpg), guarded init from settings, pooled connection config, get_db() async dependency, and documentation describing usage and tests.
Dependencies & project config
pyproject.toml, backend/requirements.txt
Added sqlalchemy, asyncpg, and pytest-asyncio; pytest asyncio config added to pyproject.toml.
Handler layer
backend/app/core/handler/handler_registry.py, backend/app/core/handler/message_handler.py
Registry now normalizes enum/string keys for lookups; removed placeholder comments from message handler.
Event dispatch safety
backend/app/core/events/event_bus.py
Wrapped fire-and-forget handler tasks with a _safe_call that logs handler exceptions instead of letting them propagate.
Models
backend/app/models/database/supabase.py
Added new CodeChunk Pydantic model representing repository file/code chunk metadata.
Logging / Error handling
backend/app/agents/base_agent.py, backend/app/core/handler/faq_handler.py, backend/app/core/orchestration/..., backend/app/api/v1/integrations.py, backend/app/core/orchestration/queue_manager.py, backend/routes.py
Enhanced logging: added module loggers, used exc_info=True and structured/contextual logs, wrapped certain send/publish calls with try/except and improved messages.
Tests — setup & fixtures
tests/conftest.py
Added pytest fixtures for sample events, mock Discord bot, and mock LLM clients.
Tests — DB & pooling
tests/test_db_pool.py, tests/tests_db.py
New async tests validating engine pool config, concurrent session acquisition, rollback behavior; removed duplicate import in tests_db.
Tests — handlers & routing
tests/test_base_handler.py, tests/test_handler_registry.py, tests/test_message_handler.py, tests/test_faq_handler.py
New/expanded tests for handler pipeline, registry lookup (platform-specific fallback), message/FAQ handling and Discord integration.
Tests — classification & events
tests/test_classification_router.py, tests/test_events.py
Triage/classification tests (LLM parsing and fallbacks) and comprehensive BaseEvent serialization/deserialization tests.
Tests — state, supabase, weaviate
tests/test_agent_state.py, tests/test_supabase.py, tests/test_weaviate.py
AgentState reducer tests; small import/order change in supabase tests; fixed string literal typos in weaviate tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FastAPI_Route as FastAPI Route
    participant DI_get_db as get_db()
    participant DB_Engine as AsyncEngine

    Client->>FastAPI_Route: HTTP request needing DB
    FastAPI_Route->>DI_get_db: request AsyncSession dependency
    DI_get_db->>DB_Engine: checkout AsyncSession from pool
    DB_Engine-->>DI_get_db: AsyncSession (checked-out)
    DI_get_db-->>FastAPI_Route: yield AsyncSession
    FastAPI_Route->>DB_Engine: execute queries via AsyncSession
    FastAPI_Route->>DI_get_db: on completion or error -> cleanup
    DI_get_db->>DB_Engine: commit/rollback and release session
    DB_Engine-->>DI_get_db: session returned to pool

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • AOSSIE-Org/Devr.AI#76 — touches agent_coordinator.py; overlaps with updated exception logging/context in orchestration.
  • AOSSIE-Org/Devr.AI#85 — related to settings exposure and how new database_url may be consumed by core modules.
  • AOSSIE-Org/Devr.AI#87 — also modifies config surface; related to adding database_url to Settings.

Suggested labels

enhancement

Suggested reviewers

  • chandansgowda
  • smokeyScraper

Poem

🐰 I sniffed the config, found a URL bright,
I hopped to the pool and kept sessions tight,
Async hops, tests leaped in a row,
Logs grow wiser where errors may show,
Code and carrots—I'm ready to write!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 79.61% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Test/backend core coverage' directly describes the main objective of the PR, which adds comprehensive unit-test coverage for core backend logic.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Post copyable unit tests in a comment

[!TIP] Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs). Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jan 30 '26 15:01 coderabbitai[bot]

Update: I’ve pushed fixes addressing all CodeRabbit feedback.

  • Updated documentation paths to match repo layout
  • Aligned SQLAlchemy versions across pyproject.toml and requirements.txt
  • Fixed Ruff lint issues (B007, ARG002, unused imports)
  • Improved exception handling (no silent swallowing)
  • Migrated async tests to pytest.mark.asyncio
  • Added ClassVar annotations where required

All tests pass locally: 74 passed, 3 warnings

Looking forward to your feedback, Thanks.

muhammadtihame avatar Feb 04 '26 15:02 muhammadtihame

Thanks for catching that, CodeChunk is referenced later in the test. I’ve restored the import and verified the tests pass.

muhammadtihame avatar Feb 04 '26 17:02 muhammadtihame