Files
gandalf/tests/test_kuma.py
T

69 lines
2.4 KiB
Python
Raw Normal View History

"""kuma.py: switching the Uptime Kuma maintenance window, against a fake Socket.IO client."""
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import kuma # noqa: E402
CFG = {'url': 'http://kuma.test:3001', 'username': 'gandalf', 'password': 'pw', 'maintenance_id': 7}
class FakeSocket:
def __init__(self, answers=None, connect_error=None):
self.answers = answers or {}
self.connect_error = connect_error
self.calls, self.disconnected = [], False
def connect(self, url, **kw):
if self.connect_error:
raise self.connect_error
self.url = url
def call(self, event, data=None, timeout=None):
self.calls.append((event, data))
return self.answers.get(event, {'ok': True})
def disconnect(self):
self.disconnected = True
def run(active=True, **kw):
sock = FakeSocket(**kw)
kuma.set_maintenance(CFG, active, client_factory=lambda: sock)
return sock
class TestKuma:
def test_configured_needs_every_field(self):
assert kuma.configured(CFG)
assert not kuma.configured(dict(CFG, password=''))
assert not kuma.configured(None)
def test_resume_logs_in_then_switches_the_window_on(self):
sock = run(True)
assert sock.calls == [('login', {'username': 'gandalf', 'password': 'pw', 'token': ''}),
('resumeMaintenance', 7)]
assert sock.disconnected and sock.url == CFG['url']
def test_pause(self):
assert run(False).calls[-1] == ('pauseMaintenance', 7)
def test_refused_login(self):
with pytest.raises(kuma.KumaError, match='login refused: Incorrect username or password'):
run(answers={'login': {'ok': False, 'msg': 'Incorrect username or password.'}})
def test_two_factor_account(self):
with pytest.raises(kuma.KumaError, match='two-factor'):
run(answers={'login': {'ok': False, 'tokenRequired': True}})
def test_refused_change(self):
with pytest.raises(kuma.KumaError, match='resumeMaintenance refused'):
run(answers={'resumeMaintenance': {'ok': False, 'msg': 'not found'}})
def test_unreachable(self):
sock = FakeSocket(connect_error=ConnectionError('refused'))
with pytest.raises(kuma.KumaError, match='ConnectionError'):
kuma.set_maintenance(CFG, True, client_factory=lambda: sock)
assert sock.disconnected