Files
thor/tests/test_clients.py
T

236 lines
11 KiB
Python
Raw Normal View History

import pytest
import requests
from thor.clients import SourceError
from thor.clients.gandalf import GandalfClient
from thor.clients.loki import LokiClient, find_shutdown, quote, shutdown_query
from thor.clients.prometheus import PrometheusClient
from thor.clients.proxmox import ProxmoxClient
from thor.clients.tinker import TinkerClient, backoff_s
from .fakes import FakeResponse, FakeSession
PROM = 'http://prom:9090'
LOKI = 'http://loki:3100'
# -- Prometheus ----------------------------------------------------------
def test_prometheus_instant_query_parses_and_skips_bad_values():
sess = FakeSession().add('GET', f'{PROM}/api/v1/query', FakeResponse(200, {
'status': 'success', 'data': {'result': [
{'metric': {'instance': '10.10.10.4:9100'}, 'value': [1795410700.1, '11']},
{'metric': {}, 'value': [1795410700.1, 'NaN-not']},
]}}))
out = PrometheusClient(PROM, session=sess).query('node_vmstat_oom_kill', at=1795410700)
assert out == [{'metric': {'instance': '10.10.10.4:9100'}, 'ts': 1795410700.1, 'value': 11.0}]
assert sess.requests[0]['params']['time'] == '1795410700.000'
def test_prometheus_range_query():
sess = FakeSession().add('GET', f'{PROM}/api/v1/query_range', FakeResponse(200, {
'status': 'success', 'data': {'result': [{'metric': {'a': 'b'}, 'values': [[1, '2'], [3, 'x']]}]}}))
out = PrometheusClient(PROM, session=sess).query_range('up', 0, 10, 5)
assert out == [{'metric': {'a': 'b'}, 'values': [(1.0, 2.0)]}]
assert sess.requests[0]['params']['step'] == '5'
@pytest.mark.parametrize('reply', [
FakeResponse(500, {'status': 'error'}),
FakeResponse(200, {'status': 'error', 'error': 'bad query'}),
FakeResponse(200, None, text='<html>'),
requests.ConnectionError('refused'),
requests.Timeout('slow'),
])
def test_prometheus_failures_are_source_errors(reply):
sess = FakeSession().add('GET', PROM, reply)
with pytest.raises(SourceError) as e:
PrometheusClient(PROM, session=sess).ping()
assert e.value.source == 'prometheus'
# -- Loki ----------------------------------------------------------------
def _loki_reply(*streams):
return FakeResponse(200, {'status': 'success', 'data': {'result': [
{'stream': labels, 'values': values} for labels, values in streams]}})
def test_loki_lines_keep_labels_and_sort():
sess = FakeSession().add('GET', f'{LOKI}/loki/api/v1/query_range', _loki_reply(
({'host': 'a'}, [['2000000000', 'old']]),
({'host': 'b'}, [['3000000000', 'new']]),
))
out = LokiClient(LOKI, session=sess).lines('{job="journal"}', 0, 10)
assert out == [(3.0, 'new', {'host': 'b'}), (2.0, 'old', {'host': 'a'})]
fwd = LokiClient(LOKI, session=sess).lines('{job="journal"}', 0, 10, direction='forward')
assert [x[1] for x in fwd] == ['old', 'new']
def test_loki_refuses_windows_over_30_days_and_errors():
with pytest.raises(SourceError):
LokiClient(LOKI, session=FakeSession()).lines('{a="b"}', 0, 31 * 86400)
sess = FakeSession().add('GET', LOKI, FakeResponse(500, {'status': 'error'}))
with pytest.raises(SourceError):
LokiClient(LOKI, session=sess).ping()
def test_find_shutdown_matches_logind_line_and_quotes_host():
line = 'The system will power off now!'
sess = FakeSession().add('GET', LOKI, _loki_reply(
({'host': 'compute-storage-01'}, [['1795576895000000000', line]])))
found = find_shutdown(LokiClient(LOKI, session=sess), 'compute-storage-01', before=1795577000)
assert found == {'at': 1795576895.0, 'kind': 'power off', 'line': line}
q = sess.requests[0]['params']['query']
assert q.startswith('{host="compute-storage-01", job="journal", unit="systemd-logind.service"}')
assert shutdown_query('a"b').startswith('{host="a\\"b"')
assert quote('x\\y') == 'x\\\\y'
def test_find_shutdown_none_vs_unknown():
sess = FakeSession().add('GET', LOKI, _loki_reply())
assert find_shutdown(LokiClient(LOKI, session=sess), 'storage-01', before=100.0) is None
down = FakeSession().add('GET', LOKI, requests.ConnectionError('x'))
with pytest.raises(SourceError):
find_shutdown(LokiClient(LOKI, session=down), 'storage-01', before=100.0)
# -- Proxmox -------------------------------------------------------------
def test_proxmox_fails_over_between_nodes_and_remembers():
sess = (FakeSession()
.add('GET', 'https://10.0.0.1:8006', requests.ConnectionError('down'))
.add('GET', 'https://10.0.0.2:8006', FakeResponse(200, {'data': [
{'name': 'noout', 'value': 1}, {'name': 'pause', 'value': 0}]})))
px = ProxmoxClient(['10.0.0.1', '10.0.0.2'], 'thor@pve!monitor', 'secret', session=sess)
assert px.ceph_flags() == {'noout': True, 'pause': False}
assert sess.requests[1]['headers']['Authorization'] == 'PVEAPIToken=thor@pve!monitor=secret'
assert sess.requests[1]['verify'] is False
px.ceph_flags()
assert sess.requests[2]['url'].startswith('https://10.0.0.2:8006') # preferred node first now
def test_proxmox_token_refusal_does_not_try_other_nodes():
sess = (FakeSession().add('GET', 'https://10.0.0.1:8006', FakeResponse(401, {}))
.add('GET', 'https://10.0.0.2:8006', FakeResponse(200, {'data': {}})))
with pytest.raises(SourceError, match='token refused'):
ProxmoxClient(['10.0.0.1', '10.0.0.2'], 'id', 's', session=sess).ping()
assert len(sess.requests) == 1
def test_proxmox_unconfigured_and_all_nodes_down():
with pytest.raises(SourceError, match='no API token'):
ProxmoxClient(['10.0.0.1'], '', '', session=FakeSession()).ping()
sess = FakeSession().add('GET', 'https://', requests.ConnectionError('x'))
with pytest.raises(SourceError, match='10.0.0.1'):
ProxmoxClient(['10.0.0.1'], 'id', 's', session=sess).cluster_status()
def test_proxmox_helpers_pass_params():
sess = FakeSession().add('GET', 'https://n:8006', FakeResponse(200, {'data': [{'vmid': 154}]}))
px = ProxmoxClient(['n'], 'id', 's', session=sess)
assert px.resources('vm') == [{'vmid': 154}]
assert sess.requests[0]['params'] == {'type': 'vm'}
assert px.ha_status() == [{'vmid': 154}]
# -- Gandalf -------------------------------------------------------------
T2_SUPPRESSION = {'id': 2, 'reason': 'switch update', 'started_at': '2026-11-25T03:11:39Z',
'ended_at': '2026-11-25T03:41:39Z', 'state': 'expired', 'target_type': 'all'}
def test_gandalf_suppressions_with_history():
sess = FakeSession().add('GET', 'http://g/api/suppressions',
FakeResponse(200, {'since': 'x', 'suppressions': [T2_SUPPRESSION]}))
g = GandalfClient('http://g/', 'key', session=sess)
assert g.suppressions(hours=48) == [T2_SUPPRESSION]
req = sess.requests[0]
assert req['params'] == {'include_ended': '1', 'hours': '48'}
assert req['headers']['Authorization'] == 'Bearer key'
g.suppressions(hours=10_000)
assert sess.requests[1]['params']['hours'] == str(31 * 24)
def test_gandalf_errors():
with pytest.raises(SourceError, match='no API key'):
GandalfClient('http://g', '', session=FakeSession()).ping()
sess = FakeSession().add('GET', 'http://g', FakeResponse(401, {}))
with pytest.raises(SourceError, match='key refused'):
GandalfClient('http://g', 'k', session=sess).status()
bad = FakeSession().add('GET', 'http://g', FakeResponse(200, ['not', 'a', 'dict']))
with pytest.raises(SourceError):
GandalfClient('http://g', 'k', session=bad).status()
with pytest.raises(SourceError):
GandalfClient('http://g', 'k', session=bad).suppressions()
# -- Tinker --------------------------------------------------------------
TINKER = 'https://t/create_ticket_api.php'
def test_tinker_create_sends_dedup_key_and_reads_action():
sess = FakeSession().add('POST', TINKER, FakeResponse(200, {'success': True, 'ticket_id': '123', 'action': 'new'}))
t = TinkerClient(TINKER, 'k', session=sess)
r = t.create(title='[h][auto][thor][software] x', description='d', priority=3, category='Software',
ticket_type='Issue', dedup_key='host:h:oom')
assert (r.ticket_id, r.action, r.ok) == ('123', 'new', True)
body = sess.requests[0]['json']
assert body['dedup_key'] == 'host:h:oom' and body['priority'] == '3' and body['status'] == 'Open'
def test_tinker_create_failures():
assert not TinkerClient('', '').create(title='t', description='', priority=3, category='c',
ticket_type='Issue', dedup_key='k').ok
sess = FakeSession().add('POST', TINKER, FakeResponse(403, {}))
t = TinkerClient(TINKER, 'k', session=sess)
r = t.create(title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k')
assert r.error == 'HTTP 403'
assert t.writes_denied
assert t.comment('1', 'x') is False
dup = FakeSession().add('POST', TINKER, FakeResponse(200, {'existing_ticket_id': 77}))
r = TinkerClient(TINKER, 'k', session=dup).create(
title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k')
assert (r.ticket_id, r.action) == ('77', 'deduplicated')
odd = FakeSession().add('POST', TINKER, FakeResponse(200, {'success': False}))
assert 'unexpected' in TinkerClient(TINKER, 'k', session=odd).create(
title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k').error
def test_tinker_comment_and_reads():
sess = (FakeSession()
.add('POST', 'https://t/api/ticket_comment_api.php', FakeResponse(200, {'success': True}),
FakeResponse(404, {}), requests.ConnectionError('x'))
.add('GET', 'https://t/api/tickets_api.php',
FakeResponse(200, {'success': True, 'pages': 2,
'tickets': [{'ticket_id': 1, 'title': 'a', 'status': 'Open'}]}),
FakeResponse(200, {'success': True, 'pages': 2,
'tickets': [{'ticket_id': 2, 'title': 'b', 'status': 'Pending'}]}),
FakeResponse(200, {'success': True, 'ticket': {'ticket_id': '693930698'}})))
t = TinkerClient(TINKER, 'k', session=sess)
assert t.comment('1', 'hi') is True
assert t.comment('1', 'hi') is True # deleted ticket: done
assert t.comment('1', 'hi') is False # network error: retry later
assert set(t.open_tickets()) == {'1', '2'}
assert t.ticket('693930698') == {'ticket_id': '693930698'}
assert TinkerClient('', '').open_tickets() is None
def test_backoff():
assert backoff_s(1) == 120
assert backoff_s(3) == 480
assert backoff_s(50) == 3600
def test_tinker_network_errors_and_unknown_reads():
down = FakeSession().add('POST', TINKER, requests.ConnectionError('x')).add(
'GET', 'https://t/api/tickets_api.php', requests.ConnectionError('x'))
t = TinkerClient(TINKER, 'k', session=down)
r = t.create(title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k')
assert not r.ok and r.ticket_id is None and 'x' in r.error
assert t.open_tickets() is None
assert t.ticket('1') is None
assert 'TicketResult' in repr(r)
refused = FakeSession().add('POST', 'https://t/api/ticket_comment_api.php', FakeResponse(401, {}))
assert TinkerClient(TINKER, 'k', session=refused).comment('1', 'x') is False
missing = FakeSession().add('GET', 'https://t/api/tickets_api.php', FakeResponse(404, {}),
FakeResponse(200, {'success': False}))
tm = TinkerClient(TINKER, 'k', session=missing)
assert tm.ticket('1') is None
assert tm.open_tickets() is None