"""Tests for thor.py: Gandalf asking Thor whether a problem is already covered (gandalf#66).""" import os import sys from unittest.mock import MagicMock, patch import requests sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import thor # noqa: E402 CFG = {'url': 'http://thor.test/', 'api_key': 'k'} def _reply(status=200, body=None, raises=None): resp = MagicMock(status_code=status) if raises: resp.json.side_effect = raises else: resp.json.return_value = body return patch.object(thor.requests, 'get', return_value=resp) class TestCovering: def test_not_configured_asks_nothing(self): with patch.object(thor.requests, 'get') as get: answer = thor.ThorClient({}).covering(host='alpha') assert answer['covered'] is False and answer['error'] == 'not configured' get.assert_not_called() def test_covered_names_the_ticket(self): body = {'covered': True, 'ticket_id': 693930698, 'incidents': [], 'known_conditions': [{'kind': 'reboot', 'ticket_id': '693930698'}]} with _reply(body=body) as get: answer = thor.ThorClient(CFG).covering(host='compute-storage-02') assert answer == {'covered': True, 'ticket_id': '693930698', 'shadow': [], 'error': ''} args, kwargs = get.call_args assert args[0] == 'http://thor.test/api/incidents/covering' assert kwargs['params'] == {'host': 'compute-storage-02'} assert kwargs['headers'] == {'Authorization': 'Bearer k'} assert kwargs['timeout'] <= 5 def test_scope_query(self): with _reply(body={'covered': False, 'incidents': []}) as get: thor.ThorClient(CFG).covering(scope='source:prometheus') assert get.call_args.kwargs['params'] == {'scope': 'source:prometheus'} def test_shadow_incidents_never_cover_but_are_reported(self): body = {'covered': False, 'ticket_id': None, 'incidents': [ {'key': 'host:alpha:reboot', 'mode': 'shadow', 'ticket_id': None}, {'key': 'host:alpha:oom', 'mode': 'live', 'ticket_id': None}]} with _reply(body=body): answer = thor.ThorClient(CFG).covering(host='alpha') assert answer['covered'] is False assert answer['shadow'] == ['host:alpha:reboot'] def test_covered_without_a_ticket_is_not_covered(self): with _reply(body={'covered': True, 'ticket_id': None}): assert thor.ThorClient(CFG).covering(host='alpha')['covered'] is False def test_every_failure_fails_open(self): for status in (400, 401, 503): with _reply(status=status, body={'covered': True, 'ticket_id': '1'}): assert thor.ThorClient(CFG).covering(host='alpha')['covered'] is False with patch.object(thor.requests, 'get', side_effect=requests.Timeout('slow')): answer = thor.ThorClient(CFG).covering(host='alpha') assert answer['covered'] is False and 'slow' in answer['error'] with _reply(raises=ValueError('not json')): assert thor.ThorClient(CFG).covering(host='alpha')['covered'] is False with _reply(body=['a', 'list']): assert thor.ThorClient(CFG).covering(host='alpha')['covered'] is False