Skip to content

Commit d8ef257

Browse files
authored
feat: added db health check (#9)
* feat: added db health check * feat: added error message to health check * test: fixed health check test
1 parent 07f6b3b commit d8ef257

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

app/routers/health.py

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,37 @@
1-
from fastapi import APIRouter
1+
from fastapi import APIRouter, Depends
2+
from loguru import logger
3+
from sqlalchemy.orm import Session
4+
5+
from app.database.db import get_db
6+
from app.database.models.processing_job import ProcessingJobRecord
27

38
router = APIRouter()
49

510

11+
def check_db_status(db: Session) -> dict:
12+
try:
13+
if db.is_active:
14+
db.query(ProcessingJobRecord).limit(1).all()
15+
db_status = "ok"
16+
db_message = None
17+
else:
18+
raise Exception("Database session is not active")
19+
except Exception as e:
20+
logger.exception("Database connection check failed")
21+
db_status = "error"
22+
db_message = str(e)
23+
24+
status = {
25+
"status": db_status,
26+
}
27+
if db_message:
28+
status["message"] = db_message
29+
return status
30+
31+
632
@router.get("/health")
7-
async def health():
8-
return {"status": "ok"}
33+
async def health(db: Session = Depends(get_db)):
34+
return {
35+
"status": "ok",
36+
"database": check_db_status(db),
37+
}

tests/routers/test_health.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
def test_health(client):
1+
from unittest.mock import patch
2+
3+
4+
@patch("app.routers.health.check_db_status")
5+
def test_health(mock_db_status, client):
6+
db_status = {"status": "error", "message": "Database connection failed"}
7+
mock_db_status.return_value = db_status
28
r = client.get("/health")
39
assert r.status_code == 200
4-
assert r.json() == {"status": "ok"}
10+
assert r.json() == {"status": "ok", "database": db_status}

0 commit comments

Comments
 (0)