Resolve "Backend: Unit tests for service layer and business logic"
Closes #19 (closed)
MR: Add Comprehensive Testing Suite for Backend Services & API
Summary
This Merge Request introduces a complete testing infrastructure for the EHRS FastAPI backend. It establishes a tests/ directory structure mirroring the application layout, configures global fixtures for database isolation, and includes unit/integration tests for critical business logic across Services, Models, and API layers.
Key Changes
1. Testing Infrastructure (tests/conftest.py)
-
Dedicated Test Database: Configured to use a separate PostgreSQL database (
ehrs_test) to prevent data pollution in development/production DBs. -
Transactional Rollback: Implemented a
db_sessionfixture that wraps every test in a transaction and rolls it back upon completion, ensuring a clean state for every test. -
FastAPI Dependency Override: Overrides
get_dbto inject the test session into API routes during integration testing.
2. Service Layer Tests (tests/test_services/)
Added unit tests for core business logic, covering:
- Doctor Service: Creation logic (linking User+Doctor) and patient queue assignment.
- Medical Camp Service: Role-based signup logic (ensuring Admins sign up as Coordinators, not Volunteers).
- Medicine Service: Inventory management, stock deduction, and error handling for insufficient stock.
- Consultation Queue: Wait time calculation algorithms and valid status transition enforcement.
- User Service: Idempotency of role assignment (preventing duplicate roles).
- Patient Service: User reconciliation (linking new patients to existing users) and camp registration rules.
3. Model Integrity Tests (tests/test_models/)
-
Visit Details: Validated
add_statuslogic to enforce strict workflow dependencies (e.g.,vitalscannot be added beforeentry).
4. API Integration Tests (tests/test_api/)
- Patient Routes: Verified endpoints for creating and retrieving patients, ensuring Pydantic validation and correct HTTP status codes (201 vs 404).
Files Added
tests/conftest.pytests/test_services/test_doctor.pytests/test_services/test_medical_camp.pytests/test_services/test_medicine.pytests/test_services/test_consultation_queue.pytests/test_services/test_user.pytests/test_services/test_patient.pytests/test_services/test_patient_consultation.pytests/test_models/test_visit.pytests/test_api/test_patient_routes.py
How to Test
Prerequisites
Ensure you have a PostgreSQL instance running and the test dependencies installed:
[pip install pytest pytest-mock httpx pytest-cov]
Database Setup
Create the dedicated test database in your PostgreSQL instance
Running the Tests
Execute the full suite from the project root:
Run all tests with verbose output
python3 -m pytest -v
Run with coverage report
python3 -m pytest -v --cov=app tests/
Checklist
[] Global fixtures for DB isolation created.
[] Critical path service logic covered.
[] Database model constraints verified.
[] API integration tests added.
[] Local tests passing.