"""Runs against a real MariaDB when THOR_TEST_DB_HOST is set (the CI integration job).""" import os import pytest from thor.config import DatabaseSettings from thor.db import MIGRATIONS, Database, DatabaseError, Store, from_dt, to_dt pytestmark = pytest.mark.skipif(not os.environ.get('THOR_TEST_DB_HOST'), reason='needs THOR_TEST_DB_HOST') @pytest.fixture def db(): d = Database(DatabaseSettings( host=os.environ['THOR_TEST_DB_HOST'], port=int(os.environ.get('THOR_TEST_DB_PORT', '3306')), name=os.environ.get('THOR_TEST_DB_NAME', 'thor'), user=os.environ.get('THOR_TEST_DB_USER', 'thor'), password=os.environ.get('THOR_TEST_DB_PASSWORD', ''))) for t in ('state', 'cycles', 'source_status', 'blind_periods', 'incidents', 'actions', 'observations', 'known_conditions', 'schema_version'): d.execute(f'DROP TABLE IF EXISTS {t}') # nosec B608 - fixed table names return d def test_migrate_is_idempotent(db): assert db.migrate() == len(MIGRATIONS) assert db.migrate() == len(MIGRATIONS) assert len(db.query('SELECT * FROM schema_version')) == len(MIGRATIONS) def test_store_round_trips(db): db.migrate() s = Store(db) t = 1795575600.123 s.set_state('last_cycle', {'blind': ['loki'], 'ok': True}, t) s.set_state('last_cycle', {'blind': [], 'ok': True}, t + 1) assert s.get_state('last_cycle') == {'blind': [], 'ok': True} assert s.get_state('missing', 'dflt') == 'dflt' s.record_cycle(started=t, finished=t + 2, window_start=t - 120, window_end=t, ok=True, blind=['loki']) s.record_cycle(started=t - 100000, finished=t, window_start=t, window_end=t, ok=False, blind=[], error='x') assert s.prune_cycles(t - 1) == 1 s.save_source_status('loki', False, t, None, 'HTTP 500', t) s.save_source_status('loki', True, t + 5, t + 5, '', t + 5) loki = s.source_statuses()['loki'] assert loki == {'up': True, 'since': pytest.approx(t + 5, abs=0.001), 'last_ok': pytest.approx(t + 5, abs=0.001), 'last_error': ''} s.open_blind_period('loki', t, 'HTTP 500') assert s.blind_periods(t - 10)[0]['ended'] is None s.close_blind_period('loki', t + 60) periods = s.blind_periods(t - 10) assert periods[0]['ended'] == pytest.approx(t + 60, abs=0.001) assert s.blind_periods(t + 61) == [] def test_time_conversion_is_utc(): t = 1795575600.5 assert from_dt(to_dt(t)) == t assert to_dt(t).isoformat() == '2026-11-25T03:00:00.500000' assert to_dt(None) is None and from_dt(None) is None def test_unreachable_database_raises_database_error(): d = Database(DatabaseSettings(host='127.0.0.1', port=1, user='x', password='y')) with pytest.raises(DatabaseError): d.query('SELECT 1') def test_incidents_actions_observations(db): db.migrate() s = Store(db) t = 1795410668.0 inc = {'key': 'host:compute-storage-01:oom', 'state': 'open', 'priority': 1, 'kind': 'oom', 'subject': 'compute-storage-01', 'mode': 'shadow', 'first_seen': t, 'last_seen': t + 60, 'opened_at': t + 120, 'cleared_at': None, 'events': [{'at': t}]} s.save_incident(inc, t + 120) inc['state'] = 'cleared' inc['cleared_at'] = t + 1000 s.save_incident(inc, t + 1000) assert s.load_incidents(t) == [inc] assert s.load_incidents(t + 5000) == [] # cleared and old: not reloaded shadow = s.add_action({'incident_key': inc['key'], 'kind': 'open', 'created': t, 'mode': 'shadow', 'payload': {'title': 'x'}}) live = s.add_action({'incident_key': inc['key'], 'kind': 'open', 'created': t, 'mode': 'live', 'payload': {'title': 'y'}}) due = s.due_actions(t + 1) assert [a['id'] for a in due] == [live] and due[0]['payload'] == {'title': 'y'} s.mark_action_failed(live, 'down', 1, t + 100) assert s.due_actions(t + 50) == [] s.mark_action_sent(live, '615797777', t + 200) assert s.incident_ticket(inc['key']) == '615797777' assert s.incident_ticket('other') is None s.mark_action_failed(shadow, 'x', 30, None) recent = s.recent_actions(t - 1) assert {a['id'] for a in recent} == {shadow, live} f = {'key': 'host:storage-01:scrape', 'kind': 'scrape', 'subject': 'storage-01', 'role': 'symptom', 'start': t + 10, 'end': t + 20, 'summary': 'slow'} s.save_observation(f, t + 20) s.save_observation(dict(f, start=t + 5, end=t + 15, summary='timed out'), t + 30) obs = s.recent_observations(t) assert len(obs) == 1 and obs[0]['summary'] == 'timed out' assert obs[0]['first_seen'] == pytest.approx(t + 5, abs=0.001) assert obs[0]['last_seen'] == pytest.approx(t + 20, abs=0.001) def test_known_conditions_seeded_and_managed(db): db.migrate() s = Store(db) seeded = s.known_conditions() assert [(k['kind'], k['subject'], k['ticket_id']) for k in seeded] == [ ('reboot', 'compute-storage-02', '693930698'), ('ceph_flag', 'noout', '693930698'), ('ups_battery', 'ups', None)] new = s.add_known_condition('reboot', 'pbs', '1', 'testing', 'jared', 1795410668.0) assert len(s.known_conditions()) == 4 assert s.end_known_condition(new, 'jared', 1795410700.0) == 1 assert s.end_known_condition(new, 'jared', 1795410700.0) == 0 assert len(s.known_conditions()) == 3 s.save_incident({'key': 'k', 'state': 'pending', 'priority': 3, 'kind': 'x', 'subject': 's', 'mode': 'shadow', 'first_seen': 1.0, 'last_seen': 1.0}, 2.0) s.delete_incident('k') assert s.load_incidents(0) == []