Skip to content

test: expand test coverage for main app, auth middleware, and patient visit details

Mukthanand Reddy M requested to merge tests/mukthanand into develop

Merge Request

Overview

This MR expands test coverage for the main application, auth middleware, and patient visit details model by adding comprehensive unit tests. The original test files contained minimal smoke tests that didn't provide sufficient confidence in the correctness of the implementation.

What does this MR do and why?

The motivation behind this change is to improve code quality and reliability by adding comprehensive test coverage. The original test files contained minimal smoke tests:

  1. tests/test_main.py - Had only 2 basic smoke tests
  2. tests/test_middleware/test_auth_middleware.py - Had only 3 basic tests
  3. tests/test_models/test_patient_visit_details_model.py - Had basic status tests

This MR expands all three files to include comprehensive unit tests covering:

  • Initialization and configuration
  • Happy path scenarios
  • Edge cases and error handling
  • Parametrized tests for multiple input combinations

Changes Made

Files Modified:

  1. tests/test_main.py

    • Expanded from 2 basic tests to 20+ comprehensive tests
    • Added test classes: TestMainEndpoints, TestMainAppInitialization, TestStartupEvent, TestRootAsync, TestHealthCheckAsync, TestWebSocketEndpoint
    • Tests cover: root endpoint response format, health check validation, FastAPI app configuration, CORS middleware, API router inclusion, startup event output
  2. tests/test_middleware/test_auth_middleware.py

    • Expanded from 3 tests to 15+ comprehensive tests
    • Added test classes: TestAuthMiddlewareInitialization, TestAuthMiddlewareNonHTTPScope, TestAuthMiddlewarePublicPaths, TestAuthMiddlewareValidToken, TestAuthMiddlewareInvalidToken
    • Tests cover: middleware initialization, WebSocket/lifespan scope handling, public path bypass, JWT token validation, database user lookup, invalid/missing token handling
  3. tests/test_models/test_patient_visit_details_model.py

    • Expanded from basic status tests to 25+ comprehensive tests
    • Added test classes: TestVisitStatusEnum, TestPatientVisitDetailsVitalsColumns
    • Tests cover: all enum values, vitals column existence and assignment, relationships, table constraints, model instantiation

Technical Details

  • All tests follow pytest best practices with async support via pytest.mark.asyncio
  • Uses mocking with unittest.mock for database and external dependencies
  • Parametrized tests used where appropriate for testing multiple input combinations
  • All tests maintain backward compatibility with existing test infrastructure
  • No changes to application code - purely test additions

Type of Change

  • 🐛 Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to change)
  • 📝 Documentation update
  • ️ Refactor (no functional changes)
  • Performance improvement
  • 🧪 Test update
  • 🔧 Configuration change
  • 🚨 Security fix
  • 🗑️ Deprecation (removing deprecated code)

Related Issues / References

N/A - Test coverage improvement

Screenshots or Screen Recordings

N/A - This MR contains only backend test updates

How to Validate Locally

Previous Behaviour:

  • tests/test_main.py: 2 basic smoke tests
  • tests/test_middleware/test_auth_middleware.py: 3 basic tests
  • tests/test_models/test_patient_visit_details_model.py: basic tests

Changes Made:

  • Expanded each test file with comprehensive unit tests
  • Added test classes for better organization
  • Added parametrized tests for multiple scenarios

New Behaviour:

  • All three test files now have comprehensive coverage

Validation Steps:

  1. Navigate to ehrs-fastapi directory
  2. Ensure dependencies are installed: uv sync
  3. Run the modified test files:
    uv run pytest tests/test_main.py tests/test_middleware/test_auth_middleware.py tests/test_models/test_patient_visit_details_model.py -v
  4. Run pre-commit checks:
    uv run pre-commit run --files tests/test_main.py tests/test_middleware/test_auth_middleware.py tests/test_models/test_patient_visit_details_model.py
  5. Expected: All tests and checks should pass

Testing Done

  • Unit tests added/updated
  • API endpoint tests passing

Test Cases Covered:

Scenario Expected Result Status
Root endpoint returns welcome payload Returns message, version, docs, socketio, health keys
Health endpoint returns healthy status Returns {"status": "healthy"}
FastAPI app initialization App created with correct title and version
CORS middleware configured Middleware present in app
API router included Routes registered correctly
Startup event executes Prints success messages
Auth middleware initialization Middleware callable with app
Public paths bypass auth Login, OTP endpoints skip auth
Valid JWT token attaches user User object attached to request
Invalid token continues request Request continues with user=None
VisitStatusEnum values All status values present
Vitals columns exist All vitals columns present on model
Model relationships Visit and consultations relations exist
Table constraints Check constraints defined

Test Commands Run:

# Run all tests in modified files
uv run pytest tests/test_main.py tests/test_middleware/test_auth_middleware.py tests/test_models/test_patient_visit_details_model.py -v

# Run pre-commit on modified files
uv run pre-commit run --files tests/test_main.py tests/test_middleware/test_auth_middleware.py tests/test_models/test_patient_visit_details_model.py

# Run full test suite with coverage
uv run pytest -n auto --cov=app --cov-report=term-missing --cov-fail-under=60

Code Quality Checklist

Code Standards

  • Code follows project conventions (naming, structure, formatting)
  • No debug statements or commented-out code left (unless necessary and intended)
  • No unused imports, variables, or functions
  • No duplicate code (DRY principle followed)
  • Type hints are properly defined (no Any unless justified and no mypy type check errors)
  • Ruff checks pass:
    ruff check .
    ruff format . --check

Python & FastAPI Best Practices

  • Functions follow single-responsibility principle
  • Async/await used correctly (no blocking calls in async functions)
  • Dependency injection used appropriately
  • Pydantic models used for request/response validation (N/A - test file)
  • SQLAlchemy queries are optimized (N/A - test file)
  • Error handling is comprehensive (tests cover error scenarios)

API Design

  • RESTful conventions followed (N/A - test file)
  • Proper HTTP status codes returned (N/A - test file)
  • Input validation implemented (N/A - test file)
  • Authentication/authorization enforced (tested in auth middleware tests)
  • Role Base access control used for user restriction (N/A - test file)
  • API documentation (docstrings) updated

Database & Migrations

  • Database migrations created (if schema changed) - N/A
  • Database migrations version is pointing to the latest version (and version name follows project conventions) - N/A
  • Migrations are reversible (migrations contain downgrade scripts) - N/A
  • Indexes added for frequently queried fields - N/A
  • No raw SQL queries (using SQLAlchemy ORM) - N/A
  • Data integrity constraints maintained

Security

  • No sensitive data logged (passwords, tokens, PII)
  • SQL injection prevention verified (ORM used)
  • Input sanitization implemented (N/A - test file)
  • Authentication tokens handled securely (tested in auth middleware)
  • CORS settings appropriate (tested in app initialization)
  • Security scan passes:
    bandit -r app/

Error Handling

  • Errors are caught and handled gracefully
  • User-friendly error messages returned (N/A - test file)
  • Errors are logged appropriately (N/A - test file)
  • HTTP error responses follow API standards (N/A - test file)

Documentation

  • README.md updated (if setup steps changed) - N/A
  • .env.example updated (if new env vars added) - N/A
  • API documentation updated (docstrings, OpenAPI specs) - N/A
  • CHANGELOG.md will be updated (if applicable) - N/A
  • Code comments explain complex logic (not what, but why)

Known Limitations / Technical Debt

None - Tests are comprehensive and follow best practices. No technical debt introduced.

Additional Notes

  • Tests are designed to be maintainable and readable
  • Test names clearly describe what is being tested
  • All tests include docstrings explaining the purpose
  • All 124 tests in modified files pass
  • Full test suite (372 tests) passes
  • Test coverage: 62.97% (exceeds 60% threshold)

MR Acceptance Checklist

Quality & Correctness

  • Code works as intended and solves the stated problem
  • No bugs introduced (existing functionality not broken)
  • Edge cases handled appropriately

Maintainability

  • Code is readable and well-organized
  • Code is testable and well-tested
  • Follows project patterns and conventions

Acceptance Review

  • Reviewed by at least 1 teammate
  • Reviewed by product owner
Edited by Mukthanand Reddy M

Merge request reports

Loading