1+ from httpx import ASGITransport , AsyncClient
2+ from stac_fastapi .api .app import StacApi
3+
4+ from stac_fastapi .pgstac .config import PostgresSettings , Settings
5+ from stac_fastapi .pgstac .core import CoreCrudClient , health_check
6+ from stac_fastapi .pgstac .db import close_db_connection , connect_to_db
7+
8+
19async def test_ping_no_param (app_client ):
210 """
311 Test ping endpoint with a mocked client.
@@ -7,3 +15,67 @@ async def test_ping_no_param(app_client):
715 res = await app_client .get ("/_mgmt/ping" )
816 assert res .status_code == 200
917 assert res .json () == {"message" : "PONG" }
18+
19+
20+ async def test_health (app_client ):
21+ """
22+ Test health endpoint
23+
24+ Args:
25+ app_client (TestClient): mocked client fixture
26+
27+ """
28+ res = await app_client .get ("/_mgmt/health" )
29+ assert res .status_code == 200
30+ body = res .json ()
31+ assert body ["status" ] == "UP"
32+ assert body ["pgstac" ]["status" ] == "UP"
33+ assert body ["pgstac" ]["pgstac_version" ]
34+
35+
36+ async def test_health_503 (database ):
37+ """Test health endpoint error."""
38+
39+ # No lifespan so no `get_connection` is application state
40+ api = StacApi (
41+ settings = Settings (testing = True ),
42+ extensions = [],
43+ client = CoreCrudClient (),
44+ health_check = health_check ,
45+ )
46+
47+ async with AsyncClient (
48+ transport = ASGITransport (app = api .app ), base_url = "http://test"
49+ ) as client :
50+ res = await client .get ("/_mgmt/health" )
51+ assert res .status_code == 503
52+ body = res .json ()
53+ assert body ["status" ] == "DOWN"
54+ assert body ["lifespan" ]["status" ] == "DOWN"
55+ assert body ["lifespan" ]["message" ] == "application lifespan wasn't run"
56+ assert body ["pgstac" ]["status" ] == "DOWN"
57+ assert body ["pgstac" ]["message" ] == "Could not connect to database"
58+
59+ # No lifespan so no `get_connection` is application state
60+ postgres_settings = PostgresSettings (
61+ postgres_user = database .user ,
62+ postgres_pass = database .password ,
63+ postgres_host_reader = database .host ,
64+ postgres_host_writer = database .host ,
65+ postgres_port = database .port ,
66+ postgres_dbname = database .dbname ,
67+ )
68+ # Create connection pool but close it just after
69+ await connect_to_db (api .app , postgres_settings = postgres_settings )
70+ await close_db_connection (api .app )
71+
72+ async with AsyncClient (
73+ transport = ASGITransport (app = api .app ), base_url = "http://test"
74+ ) as client :
75+ res = await client .get ("/_mgmt/health" )
76+ assert res .status_code == 503
77+ body = res .json ()
78+ assert body ["status" ] == "DOWN"
79+ assert body ["lifespan" ]["status" ] == "UP"
80+ assert body ["pgstac" ]["status" ] == "DOWN"
81+ assert body ["pgstac" ]["message" ] == "pool is closed"
0 commit comments