|
| 1 | +"""Tests for core health helpers and readiness API views.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from datetime import UTC, datetime |
| 6 | + |
| 7 | +from django.db.utils import OperationalError |
| 8 | +from rest_framework import status |
| 9 | +from rest_framework.test import APIRequestFactory |
| 10 | + |
| 11 | +from core.api.views import HealthCheckView |
| 12 | +from core.health import check_database, get_readiness_payload |
| 13 | + |
| 14 | + |
| 15 | +class _HealthyCursor: |
| 16 | + """Minimal cursor stub for the successful database probe path.""" |
| 17 | + |
| 18 | + def __init__(self) -> None: |
| 19 | + self.executed_sql: list[str] = [] |
| 20 | + self.fetchone_calls = 0 |
| 21 | + |
| 22 | + def __enter__(self) -> _HealthyCursor: |
| 23 | + return self |
| 24 | + |
| 25 | + def __exit__(self, exc_type, exc, tb) -> None: |
| 26 | + return None |
| 27 | + |
| 28 | + def execute(self, sql: str) -> None: |
| 29 | + self.executed_sql.append(sql) |
| 30 | + |
| 31 | + def fetchone(self) -> tuple[int]: |
| 32 | + self.fetchone_calls += 1 |
| 33 | + return (1,) |
| 34 | + |
| 35 | + |
| 36 | +class _HealthyConnection: |
| 37 | + """Connection stub that returns the supplied cursor.""" |
| 38 | + |
| 39 | + def __init__(self, cursor: _HealthyCursor) -> None: |
| 40 | + self._cursor = cursor |
| 41 | + |
| 42 | + def cursor(self) -> _HealthyCursor: |
| 43 | + return self._cursor |
| 44 | + |
| 45 | + |
| 46 | +class _UnavailableConnection: |
| 47 | + """Connection stub that raises the expected operational error.""" |
| 48 | + |
| 49 | + def cursor(self): |
| 50 | + raise OperationalError("database unavailable") |
| 51 | + |
| 52 | + |
| 53 | +def test_check_database_returns_ok_when_default_database_is_reachable(monkeypatch) -> None: |
| 54 | + """The probe should execute a lightweight query and report success.""" |
| 55 | + |
| 56 | + cursor = _HealthyCursor() |
| 57 | + monkeypatch.setattr( |
| 58 | + "core.health.connections", |
| 59 | + {"default": _HealthyConnection(cursor)}, |
| 60 | + ) |
| 61 | + |
| 62 | + assert check_database() == (True, "ok") |
| 63 | + assert cursor.executed_sql == ["SELECT 1"] |
| 64 | + assert cursor.fetchone_calls == 1 |
| 65 | + |
| 66 | + |
| 67 | +def test_check_database_returns_unavailable_on_operational_error(monkeypatch) -> None: |
| 68 | + """Operational errors should degrade the readiness dependency check.""" |
| 69 | + |
| 70 | + monkeypatch.setattr( |
| 71 | + "core.health.connections", |
| 72 | + {"default": _UnavailableConnection()}, |
| 73 | + ) |
| 74 | + |
| 75 | + assert check_database() == (False, "unavailable") |
| 76 | + |
| 77 | + |
| 78 | +def test_get_readiness_payload_includes_release_timestamp_and_checks(monkeypatch, settings) -> None: |
| 79 | + """The readiness payload should expose the stable response contract.""" |
| 80 | + |
| 81 | + fixed_now = datetime(2026, 4, 21, 9, 3, 36, tzinfo=UTC) |
| 82 | + monkeypatch.setattr("core.health.check_database", lambda: (True, "ok")) |
| 83 | + monkeypatch.setattr("core.health.timezone.now", lambda: fixed_now) |
| 84 | + settings.RELEASE_VERSION = "2026.04.21" |
| 85 | + |
| 86 | + assert get_readiness_payload() == { |
| 87 | + "status": "ok", |
| 88 | + "service": "returnhub", |
| 89 | + "release": "2026.04.21", |
| 90 | + "timestamp": fixed_now.isoformat(), |
| 91 | + "checks": {"database": "ok"}, |
| 92 | + } |
| 93 | + |
| 94 | + |
| 95 | +def test_get_readiness_payload_falls_back_to_degraded_and_dev_release( |
| 96 | + monkeypatch, settings |
| 97 | +) -> None: |
| 98 | + """The helper should preserve safe defaults for degraded environments.""" |
| 99 | + |
| 100 | + fixed_now = datetime(2026, 4, 21, 9, 3, 36, tzinfo=UTC) |
| 101 | + monkeypatch.setattr("core.health.check_database", lambda: (False, "unavailable")) |
| 102 | + monkeypatch.setattr("core.health.timezone.now", lambda: fixed_now) |
| 103 | + del settings.RELEASE_VERSION |
| 104 | + |
| 105 | + assert get_readiness_payload() == { |
| 106 | + "status": "degraded", |
| 107 | + "service": "returnhub", |
| 108 | + "release": "dev", |
| 109 | + "timestamp": fixed_now.isoformat(), |
| 110 | + "checks": {"database": "unavailable"}, |
| 111 | + } |
| 112 | + |
| 113 | + |
| 114 | +def test_health_check_view_returns_200_for_healthy_payload(monkeypatch) -> None: |
| 115 | + """The API view should return 200 when the app is ready.""" |
| 116 | + |
| 117 | + monkeypatch.setattr( |
| 118 | + "core.api.views.get_readiness_payload", |
| 119 | + lambda: {"status": "ok", "checks": {"database": "ok"}}, |
| 120 | + ) |
| 121 | + |
| 122 | + response = HealthCheckView.as_view()(APIRequestFactory().get("/api/health/")) |
| 123 | + |
| 124 | + assert response.status_code == status.HTTP_200_OK |
| 125 | + assert response.data == {"status": "ok", "checks": {"database": "ok"}} |
| 126 | + |
| 127 | + |
| 128 | +def test_health_check_view_returns_503_for_degraded_payload(monkeypatch) -> None: |
| 129 | + """The API view should signal unready status to probes and load balancers.""" |
| 130 | + |
| 131 | + monkeypatch.setattr( |
| 132 | + "core.api.views.get_readiness_payload", |
| 133 | + lambda: {"status": "degraded", "checks": {"database": "unavailable"}}, |
| 134 | + ) |
| 135 | + |
| 136 | + response = HealthCheckView.as_view()(APIRequestFactory().get("/api/health/")) |
| 137 | + |
| 138 | + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE |
| 139 | + assert response.data == {"status": "degraded", "checks": {"database": "unavailable"}} |
0 commit comments