Backend: Unit tests for service layer and business logic
Issue: Implement Comprehensive Testing Suite for Backend Services & API
Problem Statement
The current EHRS FastAPI backend lacks a standardized testing infrastructure. As the codebase grows (currently 189+ files), the risk of regression bugs increases with every feature addition. Critical business logic—such as patient-user linking, inventory management, and consultation queues—is currently untested automatically.
We need to establish a robust testing framework to ensure data integrity, verify complex business rules, and enable safe refactoring in the future.
Scope
Service functions Business rules Conditional flows Cross-entity logic Edge cases and failure paths
Testing Guidelines
Mock repository/database calls Focus on logic correctness No HTTP or FastAPI routing tests Acceptance Criteria
Goals
-
Establish Testing Infrastructure: Set up
pytestwith database isolation to ensure tests don't pollute local or production environments. - Verify Core Business Logic: Cover the "Happy Paths" and "Edge Cases" for critical services (Patient, Doctor, Medicine, Auth).
- Ensure Data Integrity: Verify database constraints and complex model methods (e.g., PostgreSQL Arrays).
- API Validation: Ensure endpoints correctly validate inputs and return appropriate HTTP status codes.
Scope of Work
1. Infrastructure Setup
-
Configure pytestandpytest-cov. -
Create tests/conftest.pywith global fixtures:-
setup_test_db: Create/Drop schema for a dedicated_testdatabase. -
db_session: Handle transactional rollbacks for every test function. -
client: Override FastAPIget_dbdependency for integration tests.
-
2. Service Layer Unit Tests
Write unit tests for the following critical services:
-
Patient Service: Test patient creation, user linking, and duplicate camp registration prevention. -
Doctor Service: Test doctor profile creation and patient queue assignment. -
Medical Camp Service: Test role-based signup logic (Admin -> Coordinator). -
Medicine Service: Test inventory deduction, stock validation, and batch expiry logic. -
Auth Service: Test password hashing, JWT token generation, and OTP validation. -
Consultation Queue Service: Test wait time calculations and status transitions. -
User Service: Test role assignment idempotency.
3. Model Integrity Tests
-
PatientVisitDetails: Verify add_status()enforces the correct workflow order (entry->doctor_assigning-> ...).
4. API Integration Tests
-
Patient Routes: Verify GET /patients/{book_no}(404/200) andPOST /patients/(201/422).
Technical Requirements
-
Framework:
pytest -
Database: PostgreSQL (Must support
ARRAYandUUIDtypes). -
Client:
httpx/FastAPI TestClient. -
Mocking:
pytest-mock(where external calls like SMS/Email are involved).
Acceptance Criteria
-
tests/conftest.pyis created and correctly handles DB creation/rollback. -
All new tests pass locally using python -m pytest. -
Critical service logic (Patient linking, Inventory updates) has valid test cases. -
Code coverage report is generated successfully. -
No "test pollution" occurs (data created in one test does not persist to another).
Implementation Plan
-
Phase 1: Infrastructure & Config (
conftest.py). - Phase 2: Service Layer Logic (The "Brain").
- Phase 3: API Routes (The "Interface").
- Phase 4: Review & Refine Coverage.
Edited by Praneeth Ashish