Lint / JS (eslint) (push) Successful in 14s
Lint / Python (flake8) (push) Successful in 1m47s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m48s
Lint / JS (eslint) (pull_request) Successful in 12s
Lint / Python (flake8) (pull_request) Successful in 1m0s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m21s
Test / Python Tests (pytest) (pull_request) Successful in 1m43s
Test / Python Tests (pytest) (push) Successful in 1m6s
Titles move to the shared standard [source][auto][gandalf][network] Summary [scope][production][issue], built in one place (ticket_text.title). Checked by running Tinker's TicketHash.php: every Gandalf title shape hashes the same as before, so open tickets keep matching. Thor can read /api/status, /api/events, /api/attention and /api/suppressions with a machine key (Authorization: Bearer, only its SHA-256 in config, read-only, optional source CIDRs; a wrong key is a 401 and never falls back to identity headers). /api/suppressions ?include_ended=1&hours=N returns every suppression in force in the window with start, planned end, actual end and who ended it: new ended_at/ended_by columns, added automatically. Refs #66 (items 1 and 2) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
146 lines
6.3 KiB
Python
146 lines
6.3 KiB
Python
"""Tests for db.py query helpers that do work beyond the SQL: the connection is faked."""
|
|
import os
|
|
import sys
|
|
from contextlib import contextmanager
|
|
from datetime import datetime, timedelta
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
import db # noqa: E402
|
|
|
|
NOW = datetime(2026, 11, 14, 12, 0, 0)
|
|
|
|
|
|
def _fake_conn(rows):
|
|
cur = MagicMock()
|
|
cur.fetchall.return_value = rows
|
|
cur.fetchone.return_value = {'now': NOW}
|
|
conn = MagicMock()
|
|
conn.cursor.return_value.__enter__.return_value = cur
|
|
|
|
@contextmanager
|
|
def get_conn():
|
|
yield conn
|
|
return patch.object(db, 'get_conn', get_conn), cur
|
|
|
|
|
|
def _event(tid, hours_ago_first, hours_ago_resolved, etype='host_unreachable', target='pbs'):
|
|
return {
|
|
'ticket_id': tid, 'event_type': etype, 'target_name': target, 'target_detail': '',
|
|
'severity': 'critical', 'first_seen': NOW - timedelta(hours=hours_ago_first),
|
|
'resolved_at': None if hours_ago_resolved is None else NOW - timedelta(hours=hours_ago_resolved),
|
|
}
|
|
|
|
|
|
class TestGetClearedTickets:
|
|
def test_no_ids_skips_the_query(self):
|
|
patcher, cur = _fake_conn([])
|
|
with patcher:
|
|
assert db.get_cleared_tickets([]) == []
|
|
cur.execute.assert_not_called()
|
|
|
|
def test_only_tickets_whose_every_alert_cleared_long_enough_ago(self):
|
|
rows = [
|
|
_event('1', 300, 250), _event('1', 100, 48), # two outages, both long cleared
|
|
_event('2', 50, 40), _event('2', 5, None), # still active
|
|
_event('3', 10, 2), # cleared too recently
|
|
]
|
|
patcher, cur = _fake_conn(rows)
|
|
with patcher:
|
|
out = db.get_cleared_tickets(['3', '1', '2', '1'], older_than_hours=24)
|
|
assert [r['ticket_id'] for r in out] == ['1']
|
|
assert out[0]['events'] == 2
|
|
assert out[0]['cleared_at'] == (NOW - timedelta(hours=48)).isoformat() + 'Z'
|
|
assert out[0]['first_seen'] == (NOW - timedelta(hours=300)).isoformat() + 'Z'
|
|
assert cur.execute.call_args_list[0].args[1] == ['1', '2', '3']
|
|
|
|
def test_newest_clearance_first(self):
|
|
rows = [_event('1', 400, 300), _event('2', 100, 30, target='micro1')]
|
|
patcher, _ = _fake_conn(rows)
|
|
with patcher:
|
|
out = db.get_cleared_tickets(['1', '2'])
|
|
assert [r['ticket_id'] for r in out] == ['2', '1']
|
|
assert out[0]['target_name'] == 'micro1'
|
|
|
|
|
|
class TestPowerFeeds:
|
|
def test_none_goes_back_to_automatic(self):
|
|
patcher, cur = _fake_conn([])
|
|
with patcher:
|
|
db.set_power_feed('RPDU', 7, None, 'jared')
|
|
sql, args = cur.execute.call_args.args
|
|
assert sql.startswith('DELETE FROM power_feeds') and args == ('RPDU', 7)
|
|
|
|
def test_empty_target_is_saved_as_nothing(self):
|
|
patcher, cur = _fake_conn([])
|
|
with patcher:
|
|
db.set_power_feed('RPDU', 7, '', 'jared')
|
|
sql, args = cur.execute.call_args.args
|
|
assert 'INSERT INTO power_feeds' in sql and args == ('RPDU', 7, '', 'jared')
|
|
|
|
def test_rows_come_back_with_iso_times(self):
|
|
patcher, _ = _fake_conn([{'source': 'RPDU', 'outlet': 7, 'target': 'large1', 'updated_by': 'jared',
|
|
'updated_at': NOW}])
|
|
with patcher:
|
|
assert db.get_power_feeds()[0]['updated_at'] == '2026-11-14T12:00:00Z'
|
|
|
|
|
|
class TestSuppressionWindows:
|
|
"""gandalf#66: Thor reads every suppression with its start and end to tell planned windows
|
|
from outages. 2026-11-25: the only record the rack maintenance was planned was row 2."""
|
|
|
|
@staticmethod
|
|
def _row(i, created_h, expires_h=None, ended_h=None, active=False, ended_by=''):
|
|
now = datetime.utcnow()
|
|
at = lambda h: None if h is None else now - timedelta(hours=h) # noqa: E731
|
|
return {'id': i, 'target_type': 'all', 'target_name': '', 'target_detail': '', 'reason': 'switch update',
|
|
'suppressed_by': 'jared', 'created_at': at(created_h), 'expires_at': at(expires_h),
|
|
'ended_at': at(ended_h), 'ended_by': ended_by, 'active': active}
|
|
|
|
def _windows(self, rows):
|
|
db._suppression_schema_ready = True
|
|
patcher, cur = _fake_conn(rows)
|
|
with patcher:
|
|
return db.get_suppression_windows(datetime.utcnow() - timedelta(hours=24))
|
|
|
|
def test_expired_window_has_its_end(self):
|
|
[w] = self._windows([self._row(2, 12, expires_h=11.5, ended_h=11.5, ended_by='expired')])
|
|
assert w['state'] == 'expired' and w['end_known'] and w['ended_by'] == 'expired'
|
|
assert w['started_at'].endswith('Z') and w['ended_at'] == w['expires_at']
|
|
|
|
def test_removed_by_hand_before_expiry(self):
|
|
[w] = self._windows([self._row(3, 5, expires_h=1, ended_h=4, ended_by='jared')])
|
|
assert w['state'] == 'ended' and w['ended_by'] == 'jared' and w['ended_at'] != w['expires_at']
|
|
|
|
def test_active_has_no_end(self):
|
|
[w] = self._windows([self._row(4, 1, active=True)])
|
|
assert w['state'] == 'active' and w['ended_at'] is None and w['end_known']
|
|
|
|
def test_expired_but_not_yet_cleaned_up(self):
|
|
[w] = self._windows([self._row(5, 3, expires_h=2, active=True)])
|
|
assert w['state'] == 'expired' and w['ended_at'] == w['expires_at'] and w['ended_by'] == 'expired'
|
|
|
|
def test_removed_before_end_times_were_recorded(self):
|
|
[w] = self._windows([self._row(6, 6)])
|
|
assert w['state'] == 'ended' and not w['end_known'] and w['ended_at'] is None
|
|
|
|
def test_deactivate_records_who_and_when(self):
|
|
db._suppression_schema_ready = True
|
|
patcher, cur = _fake_conn([])
|
|
with patcher:
|
|
db.deactivate_suppression(7, ended_by='jared')
|
|
sql, args = cur.execute.call_args.args
|
|
assert 'ended_at=NOW()' in sql and 'ended_by=%s' in sql and args == ('jared', 7)
|
|
|
|
def test_schema_adds_the_columns_once(self):
|
|
db._suppression_schema_ready = False
|
|
patcher, cur = _fake_conn([{'Field': 'id'}, {'Field': 'active'}])
|
|
with patcher:
|
|
db.ensure_suppression_schema()
|
|
db.ensure_suppression_schema()
|
|
sqls = [c.args[0] for c in cur.execute.call_args_list]
|
|
assert sum('ADD COLUMN ended_at' in q for q in sqls) == 1
|
|
assert sum('ADD COLUMN ended_by' in q for q in sqls) == 1
|
|
assert db._suppression_schema_ready
|