Files
thor/tests/test_web.py
T

59 lines
2.2 KiB
Python
Raw Normal View History

from thor.config import Settings
from thor.web.app import create_app, detect_version
from .fakes import Clock, FakeStore
def client(store, clock=None):
app = create_app(Settings(), store, 'abc123', clock=clock or Clock())
return app.test_client()
def test_health_ok_when_monitor_fresh():
clock = Clock()
store = FakeStore()
store.state['last_good_cycle'] = clock.t - 30
store.state['last_cycle'] = {'blind': ['loki']}
r = client(store, clock).get('/health')
assert r.status_code == 200
body = r.get_json()
assert body == {'status': 'ok', 'sha': 'abc123', 'db': True, 'monitor': 'ok', 'monitor_age_s': 30,
'blind': ['loki']}
assert r.headers['X-Frame-Options'] == 'DENY'
def test_health_503_when_stale_never_ran_or_no_db():
clock = Clock()
store = FakeStore()
r = client(store, clock).get('/health')
assert r.status_code == 503 and r.get_json()['monitor'] == 'no good cycle yet'
store.state['last_good_cycle'] = clock.t - 361
r = client(store, clock).get('/health')
assert r.status_code == 503 and r.get_json()['monitor'] == 'stale'
store.down = True
r = client(store, clock).get('/health')
assert r.status_code == 503 and r.get_json()['db'] is False
def test_metrics():
clock = Clock()
store = FakeStore()
store.state['last_good_cycle'] = 1795575600.0
store.state['last_cycle'] = {'started': 10.0, 'finished': 12.5}
store.sources = {'loki': {'up': False}, 'prometheus': {'up': True}}
text = client(store, clock).get('/metrics').get_data(as_text=True)
assert 'thor_build_info{sha="abc123"} 1' in text
assert 'thor_database_up 1' in text
assert 'thor_last_good_cycle_timestamp_seconds 1795575600.000' in text
assert 'thor_cycle_duration_seconds 2.500' in text
assert 'thor_source_up{source="loki"} 0' in text
store.down = True
text = client(store, clock).get('/metrics').get_data(as_text=True)
assert 'thor_database_up 0' in text and 'thor_source_up' not in text
def test_detect_version(monkeypatch, tmp_path):
monkeypatch.setenv('THOR_SHA', 'deadbeef')
assert detect_version() == 'deadbeef'
monkeypatch.delenv('THOR_SHA')
assert detect_version(str(tmp_path)) == 'unknown' # not a git checkout