Files
xc_agent_platform_demo/tests/test_health.py

76 lines
2.6 KiB
Python
Raw Normal View History

"""Tests for /health and /status handlers."""
from __future__ import annotations
import json
import os
import unittest
from unittest import mock
from src.health import handle_get, health_payload, status_payload
class TestHealth(unittest.TestCase):
def test_health_payload(self) -> None:
self.assertEqual(health_payload(), {"status": "ok"})
def test_handle_get_health(self) -> None:
code, headers, body = handle_get("/health")
self.assertEqual(code, 200)
self.assertIn("application/json", headers["Content-Type"])
data = json.loads(body.decode("utf-8"))
self.assertEqual(data, {"status": "ok"})
def test_handle_get_unknown(self) -> None:
code, _, body = handle_get("/nope")
self.assertEqual(code, 404)
self.assertIn("not_found", body.decode("utf-8"))
def test_status_booleans_only_no_secret_values(self) -> None:
with mock.patch.dict(
os.environ,
{
"STRATEGY_ID": "secret-strategy-id-xyz",
"EXTERNAL_SERVICE_TOKEN": "secret-token-abc",
},
clear=False,
):
payload = status_payload()
self.assertTrue(payload["strategy_id_present"])
self.assertTrue(payload["external_service_token_present"])
blob = json.dumps(payload)
self.assertNotIn("secret-strategy-id-xyz", blob)
self.assertNotIn("secret-token-abc", blob)
def test_status_absent(self) -> None:
env = {k: v for k, v in os.environ.items() if k not in (
"STRATEGY_ID",
"EXTERNAL_SERVICE_TOKEN",
"XC_TOKEN",
"XC_TOKEN_FILE",
"MODELHUB_XC_TOKEN",
)}
with mock.patch.dict(os.environ, env, clear=True):
payload = status_payload()
self.assertFalse(payload["strategy_id_present"])
self.assertFalse(payload["external_service_token_present"])
if __name__ == "__main__":
unittest.main()
class TestStatsStatus(unittest.TestCase):
def test_status_stats_and_metric(self):
from src.live_queue import compute_stats
stats = dict(compute_stats([]), updated_at=123.0)
for snapshot in (None, stats):
with mock.patch('src.health.last_stats', return_value=snapshot):
code, _, body = handle_get('/status')
self.assertEqual(code, 200)
payload = json.loads(body)
self.assertEqual(payload['stats'], snapshot)
self.assertEqual(payload['success_metric'], 'verify_pass')
self.assertIn('strategy_id_present', payload)
self.assertIn('external_service_token_present', payload)