1+ import sys
12import unittest
23
34from fastapi .testclient import TestClient
45
5- from medcat_service .main import app
6+ from medcat_service .config import ObservabilitySettings , Settings
7+ from medcat_service .main import app , configure_observability
68from medcat_service .test .common import setup_medcat_processor
79
810
911class TestAdminApi (unittest .TestCase ):
1012 ENDPOINT_INFO_ENDPOINT = "/api/info"
13+ METRICS_ENDPOINT = "/metrics"
14+
15+ def _reload_app (self ):
16+ """
17+ Reload the FastAPI app after env changes
18+ Used to fix this error when trying to change the observability
19+ "Cannot add middleware after an application has started"
20+ """
21+ # Clear cached imports so settings are re-evaluated
22+ for mod in list (sys .modules ):
23+ if mod .startswith ("medcat_service" ):
24+ sys .modules .pop (mod )
25+ from medcat_service .main import app
26+
27+ return app
1128
1229 def setUp (self ):
1330 setup_medcat_processor ()
@@ -17,6 +34,26 @@ def testGetInfo(self):
1734 response = self .client .get (self .ENDPOINT_INFO_ENDPOINT )
1835 self .assertEqual (response .status_code , 200 )
1936
37+ def test_get_metrics_enabled (self ):
38+ settings = Settings (observability = ObservabilitySettings (enable_metrics = True ))
39+ app = self ._reload_app ()
40+ configure_observability (settings , app )
41+ client = TestClient (app )
42+
43+ response = client .get (self .METRICS_ENDPOINT )
44+ self .assertEqual (response .status_code , 200 )
45+ self .maxDiff = None
46+ self .assertTrue ("http_requests_total" in response .text )
47+
48+ def test_get_metrics_disabled (self ):
49+ app = self ._reload_app ()
50+ settings = Settings (observability = ObservabilitySettings (enable_metrics = False ))
51+ configure_observability (settings , app )
52+ self .client = TestClient (app )
53+
54+ response = self .client .get (self .METRICS_ENDPOINT )
55+ self .assertEqual (response .status_code , 404 )
56+
2057
2158if __name__ == "__main__" :
2259 unittest .main ()
0 commit comments