Skip to content

Commit 096e9ee

Browse files
committed
Fix healt endpoint, tests
1 parent a7e9ee9 commit 096e9ee

2 files changed

Lines changed: 23 additions & 6 deletions

File tree

app/main.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
from contextlib import asynccontextmanager
22

3-
from fastapi import FastAPI, Request
3+
from fastapi import Depends, FastAPI, Request
44
from fastapi.exceptions import HTTPException
55
from fastapi.responses import HTMLResponse
66
from fastapi.responses import JSONResponse as _JSONResponse
77
from sqlalchemy import text
8+
from sqlalchemy.orm import Session
89

910

1011
class JSONResponse(_JSONResponse):
@@ -15,7 +16,7 @@ class JSONResponse(_JSONResponse):
1516

1617
from app.api.v1.router import api_router
1718
from app.config import settings
18-
from app.database import engine
19+
from app.database import get_db
1920
from app.web.router import router as web_router
2021
import pathlib
2122

@@ -47,6 +48,7 @@ async def lifespan(app: FastAPI):
4748
<meta charset="UTF-8">
4849
<meta name="viewport" content="width=device-width, initial-scale=1.0">
4950
<title>Login Required – MakerSpaceAPI</title>
51+
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg">
5052
<link rel="stylesheet" href="/static/css/tailwind.css">
5153
</head>
5254
<body class="bg-gray-50 text-gray-900 min-h-screen flex items-center justify-center">
@@ -78,12 +80,11 @@ async def http_exception_handler(request: Request, exc: HTTPException) -> JSONRe
7880
same_site="lax",
7981
)
8082

81-
@app.get("/api/health", tags=["health"], include_in_schema=True)
82-
def health():
83+
@app.get("/api/health", tags=["health"])
84+
def health(db: Session = Depends(get_db)):
8385
"""Public health check. Returns 200 when the database is reachable."""
8486
try:
85-
with engine.connect() as conn:
86-
conn.execute(text("SELECT 1"))
87+
db.execute(text("SELECT 1"))
8788
return {"status": "ok", "database": "ok"}
8889
except Exception:
8990
return JSONResponse({"status": "error", "database": "unreachable"}, status_code=503)

tests/test_health.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from unittest.mock import MagicMock, patch
2+
3+
from sqlalchemy.exc import OperationalError
4+
5+
6+
def test_health_ok(client):
7+
resp = client.get("/api/health")
8+
assert resp.status_code == 200
9+
assert resp.json() == {"status": "ok", "database": "ok"}
10+
11+
12+
def test_health_db_unreachable(client):
13+
with patch("app.main.Session.execute", side_effect=OperationalError("x", {}, None)):
14+
resp = client.get("/api/health")
15+
assert resp.status_code == 503
16+
assert resp.json() == {"status": "error", "database": "unreachable"}

0 commit comments

Comments
 (0)