Add AT&T modem monitoring and device pages; replace Link Debug
Lint / Python (flake8) (pull_request) Successful in 2m6s
Lint / JS (eslint) (pull_request) Successful in 18s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 2m11s
Test / Python Tests (pytest) (pull_request) Successful in 2m20s
Lint / JS (eslint) (push) Successful in 10s
Lint / Python (flake8) (push) Successful in 1m58s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m58s
Lint / Deploy (push) Successful in 4s
Test / Python Tests (pytest) (push) Successful in 58s
Lint / Python (flake8) (pull_request) Successful in 2m6s
Lint / JS (eslint) (pull_request) Successful in 18s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 2m11s
Test / Python Tests (pytest) (pull_request) Successful in 2m20s
Lint / JS (eslint) (push) Successful in 10s
Lint / Python (flake8) (push) Successful in 1m58s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m58s
Lint / Deploy (push) Successful in 4s
Test / Python Tests (pytest) (push) Successful in 58s
Modem and WAN: - Poll the BGW320 status pages read-only for light levels, PON and WAN state, with a WAN / Fiber panel, 7-day Rx trend, and alerts on WAN down, optical limits, and Rx drift - Read WAN outages and Smart Power restarts from the UniFi system log, since outages can be over between 5 minute polls Device pages: - Add device search to the dashboard and a page per host, switch, router, AP, PDU, or modem - Move all Link Debug data into expandable rows there; /links redirects - Collect UDM ports and UniFi device details (firmware, load, WAN, outlets) - Reorder the dashboard Monitoring fixes: - Alert when a configured host stops reporting: its series disappear rather than reporting down, so a dead host never raised an alert - Alert on Prometheus outages instead of blanking the dashboard - Treat a failed Pulse ping as unknown rather than host unreachable - Stop new switch ports reporting lifetime bytes as one interval's rate - Run database sessions in UTC: other server time zones shifted displayed ages and timed suppression expiries Also log every avatar 404 reason, add a favicon, and correct the WAN link labels (1G on Port 9, not 10G SFP+). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #4.
This commit is contained in:
1 parent
e1716d5228
commit
e32499b7f6
25 files changed
+3120
-821
No files matched your search
@@ -0,0 +1,93 @@
|
||||
"""Tests for app.py routes: database and LDAP are mocked."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import app as gandalf # noqa: E402
|
||||
|
||||
AUTH = {'Remote-User': 'jared', 'Remote-Name': 'Jared V', 'Remote-Groups': 'admin'}
|
||||
STATE = {
|
||||
'network_snapshot': json.dumps({
|
||||
'hosts': {'large1': {'ip': '10.0.0.2', 'status': 'up', 'source': 'prometheus', 'interfaces': {'eth0': 'up'}}},
|
||||
'unifi': [{'name': 'USW Flex', 'type': 'usw', 'model': 'USF5P', 'ip': '10.0.0.3', 'mac': '',
|
||||
'connected': True}],
|
||||
}),
|
||||
'link_stats': json.dumps({'hosts': {}, 'unifi_switches': {}}),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
with patch.object(gandalf, 'db') as db:
|
||||
db.get_state.side_effect = lambda key, default=None: STATE.get(key, default)
|
||||
db.get_active_events.return_value = []
|
||||
db.get_recent_resolved.return_value = []
|
||||
db.get_active_suppressions.return_value = []
|
||||
db.get_events_for_target.return_value = []
|
||||
db.count_active_events.return_value = 0
|
||||
db.get_status_summary.return_value = {'critical': 0, 'warning': 0, 'info': 0, 'resolved_24h': 0}
|
||||
db.check_suppressed.return_value = False
|
||||
with patch.object(gandalf, '_cfg', {'auth': {'allowed_groups': ['admin']}, 'ticket_api': {}}):
|
||||
yield gandalf.app.test_client()
|
||||
|
||||
|
||||
class TestPagesAndNav:
|
||||
def test_home_has_search_and_no_link_debug(self, client):
|
||||
html = client.get('/', headers=AUTH).get_data(as_text=True)
|
||||
assert 'id="device-search-input"' in html
|
||||
assert 'Link Debug' not in html
|
||||
|
||||
def test_home_section_order(self, client):
|
||||
html = client.get('/', headers=AUTH).get_data(as_text=True)
|
||||
order = [html.index(m) for m in (
|
||||
'id="device-search"', 'Alert Queue', 'WAN / Fiber', 'g-section-title">Hosts<',
|
||||
'Device Inventory', 'Network Topology',
|
||||
)]
|
||||
assert order == sorted(order)
|
||||
|
||||
def test_old_links_url_redirects_home(self, client):
|
||||
resp = client.get('/links', headers=AUTH)
|
||||
assert resp.status_code == 302 and resp.headers['Location'].endswith('/')
|
||||
|
||||
def test_device_page_escapes_name(self, client):
|
||||
html = client.get('/device/%3Cscript%3Ex', headers=AUTH).get_data(as_text=True)
|
||||
assert '<script>x' not in html
|
||||
|
||||
def test_link_data_api_remains_for_inspector(self, client):
|
||||
assert client.get('/api/links', headers=AUTH).status_code == 200
|
||||
|
||||
|
||||
class TestDeviceApi:
|
||||
def test_requires_auth(self, client):
|
||||
assert client.get('/api/devices').status_code == 401
|
||||
assert client.get('/api/device/large1').status_code == 401
|
||||
|
||||
def test_index_lists_devices(self, client):
|
||||
names = [d['name'] for d in client.get('/api/devices', headers=AUTH).get_json()['devices']]
|
||||
assert names == ['large1', 'USW Flex']
|
||||
|
||||
def test_name_with_a_space(self, client):
|
||||
d = client.get('/api/device/USW%20Flex', headers=AUTH).get_json()
|
||||
assert d['kind'] == 'switch' and d['events'] == []
|
||||
|
||||
def test_unknown_device_is_404(self, client):
|
||||
assert client.get('/api/device/nope', headers=AUTH).status_code == 404
|
||||
|
||||
|
||||
class TestAvatarLogging:
|
||||
def test_missing_ldap_config_says_why(self, client, caplog):
|
||||
assert client.get('/api/avatar', headers=AUTH).status_code == 404
|
||||
assert 'no ldap' in caplog.text
|
||||
|
||||
|
||||
class TestDatabaseTimeZone:
|
||||
def test_sessions_run_in_utc(self):
|
||||
import db as real_db
|
||||
with patch.object(real_db.pymysql, 'connect') as connect:
|
||||
real_db._new_conn({'host': 'h', 'user': 'u', 'password': 'p', 'name': 'n'})
|
||||
assert connect.call_args.kwargs['init_command'] == "SET time_zone='+00:00'"
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Tests for devices.py: the inventory behind search and device pages."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import devices # noqa: E402
|
||||
|
||||
SNAPSHOT = {
|
||||
'hosts': {
|
||||
'large1': {'ip': '10.0.0.2', 'status': 'degraded', 'source': 'prometheus',
|
||||
'interfaces': {'eth0': 'up', 'eth1': 'down'}},
|
||||
},
|
||||
'unifi': [
|
||||
{'name': 'Dream Machine Pro', 'type': 'udm', 'model': 'UDMPRO', 'ip': '203.0.113.5',
|
||||
'mac': 'aa:bb:cc:dd:ee:ff', 'connected': True},
|
||||
{'name': '24RJ45-POE', 'type': 'usw', 'model': 'US24PRO', 'ip': '10.0.0.40',
|
||||
'mac': '11:22:33:44:55:66', 'connected': False},
|
||||
{'name': 'RPDU', 'type': 'usw', 'model': 'USPPDUP', 'ip': '10.0.0.50', 'mac': '', 'connected': True},
|
||||
{'name': 'AP', 'type': 'uap', 'model': 'UAL6', 'ip': '10.0.0.60', 'mac': '', 'connected': True},
|
||||
],
|
||||
}
|
||||
LINKS = {
|
||||
'hosts': {'large1': {'eth0': {'host_ip': '10.0.0.2', 'speed_mbps': 1000}}},
|
||||
'unifi_switches': {
|
||||
'24RJ45-POE': {'ip': '10.0.0.40', 'model': 'US24PRO', 'ports': {
|
||||
'Port 3': {'port_idx': 3, 'up': True, 'speed_mbps': 1000,
|
||||
'lldp': {'system_name': 'large1', 'port_id': 'eth0'}},
|
||||
'Port 4': {'port_idx': 4, 'up': False, 'lldp': None},
|
||||
}},
|
||||
},
|
||||
'unifi_devices': {'Dream Machine Pro': {'firmware': '6.0.17', 'wan': {'wan1': {'up': True}}}},
|
||||
'updated': '2026-11-05 00:00:00 UTC',
|
||||
}
|
||||
MODEM = {'name': 'att-modem', 'reachable': True, 'lan_ip': '192.168.1.254', 'wan_ip': '203.0.113.5',
|
||||
'model': 'BGW320-505', 'wan_problems': []}
|
||||
|
||||
|
||||
def index():
|
||||
return {d['name']: d for d in devices.build_index(SNAPSHOT, LINKS, MODEM)}
|
||||
|
||||
|
||||
class TestKinds:
|
||||
def test_kinds(self):
|
||||
i = index()
|
||||
assert i['large1']['kind'] == 'host'
|
||||
assert i['Dream Machine Pro']['kind'] == 'router'
|
||||
assert i['24RJ45-POE']['kind'] == 'switch'
|
||||
assert i['AP']['kind'] == 'ap'
|
||||
assert i['att-modem']['kind'] == 'modem'
|
||||
|
||||
def test_pdu_model_beats_reported_type(self):
|
||||
assert index()['RPDU']['kind'] == 'pdu'
|
||||
|
||||
|
||||
class TestSearchText:
|
||||
def test_finds_host_by_ip_and_interface(self):
|
||||
s = index()['large1']['search']
|
||||
assert '10.0.0.2' in s and 'eth1' in s
|
||||
|
||||
def test_mac_with_and_without_separators(self):
|
||||
s = index()['Dream Machine Pro']['search']
|
||||
assert 'aa:bb:cc:dd:ee:ff' in s and 'aabbccddeeff' in s
|
||||
|
||||
def test_switch_found_by_port_neighbor(self):
|
||||
assert 'large1' in index()['24RJ45-POE']['search']
|
||||
|
||||
def test_modem_found_by_either_address_or_word(self):
|
||||
s = index()['att-modem']['search']
|
||||
assert '192.168.1.254' in s and '203.0.113.5' in s and 'fiber' in s
|
||||
|
||||
|
||||
class TestStatus:
|
||||
def test_offline_unifi_device_is_down(self):
|
||||
assert index()['24RJ45-POE']['status'] == 'down'
|
||||
|
||||
def test_modem_status(self):
|
||||
def status(**kw):
|
||||
return {d['name']: d for d in devices.build_index({}, {}, dict(MODEM, **kw))}['att-modem']['status']
|
||||
assert status() == 'up'
|
||||
assert status(wan_problems=['optical WAN is Down']) == 'down'
|
||||
assert status(reachable=False) == 'unknown'
|
||||
|
||||
|
||||
class TestPartialData:
|
||||
def test_empty_state(self):
|
||||
assert devices.build_index({}, {}, {}) == []
|
||||
assert devices.build_index(None, None, None) == []
|
||||
|
||||
def test_switch_known_only_from_link_stats(self):
|
||||
d = {x['name']: x for x in devices.build_index({}, LINKS, None)}['24RJ45-POE']
|
||||
assert d['status'] == 'unknown' and d['kind'] == 'switch'
|
||||
|
||||
|
||||
class TestUnconfiguredHosts:
|
||||
LINKS = {'hosts': {'10.0.0.77': {'eth0': {'host_ip': '10.0.0.77', 'speed_mbps': 1000}}}}
|
||||
|
||||
def test_host_only_in_link_stats_is_kept(self):
|
||||
d = {x['name']: x for x in devices.build_index({}, self.LINKS, None)}['10.0.0.77']
|
||||
assert d['kind'] == 'host' and d['status'] == 'unknown' and d['ip'] == '10.0.0.77'
|
||||
|
||||
def test_its_interfaces_are_available(self):
|
||||
d = devices.device_detail('10.0.0.77', {}, self.LINKS, None)
|
||||
assert d['interfaces']['eth0']['speed_mbps'] == 1000
|
||||
|
||||
|
||||
class TestDetail:
|
||||
def test_unknown_device(self):
|
||||
assert devices.device_detail('nope', SNAPSHOT, LINKS, MODEM) is None
|
||||
|
||||
def test_host_merges_state_and_stats(self):
|
||||
d = devices.device_detail('large1', SNAPSHOT, LINKS, MODEM)
|
||||
assert d['interfaces']['eth0'] == {'state': 'up', 'host_ip': '10.0.0.2', 'speed_mbps': 1000}
|
||||
assert d['interfaces']['eth1'] == {'state': 'down'}
|
||||
assert 'search' not in d
|
||||
|
||||
def test_host_shows_switch_port_from_lldp(self):
|
||||
up = devices.device_detail('large1', SNAPSHOT, LINKS, MODEM)['uplinks']
|
||||
assert up == [{'switch': '24RJ45-POE', 'port': 'Port 3', 'port_idx': 3,
|
||||
'host_interface': 'eth0', 'up': True, 'speed_mbps': 1000}]
|
||||
|
||||
def test_switch_has_ports(self):
|
||||
assert set(devices.device_detail('24RJ45-POE', SNAPSHOT, LINKS, MODEM)['ports']) == {'Port 3', 'Port 4'}
|
||||
|
||||
def test_router_has_info_even_without_port_data(self):
|
||||
d = devices.device_detail('Dream Machine Pro', SNAPSHOT, LINKS, MODEM)
|
||||
assert d['info']['firmware'] == '6.0.17' and d['ports'] == {}
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Tests for modem.py parsing. Fixtures copy the BGW320-505 (fw 6.35.8) markup with sanitized values."""
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import modem # noqa: E402
|
||||
|
||||
|
||||
def dom_table(heading, current, flags=(0, 0, 0, 0), limits=(-292, -90, -279, -100)):
|
||||
return f'''
|
||||
<h1>{heading} Currently {current}</h1>
|
||||
<table class="grid table100" summary="{heading} table">
|
||||
<thead><tr><th scope="col" width="30%"> </th><th scope="col">Low</th><th scope="col">High</th></tr></thead>
|
||||
<tbody>
|
||||
<tr class="a"><td class="heading" scope="row">Alarm</td>
|
||||
<td>{flags[0]} (Threshold {limits[0]})</td>
|
||||
<td>{flags[1]} (Threshold {limits[1]})</td>
|
||||
</tr>
|
||||
<tr class="b"><td class="heading" scope="row">Warning</td>
|
||||
<td>{flags[2]} (Threshold {limits[2]})</td>
|
||||
<td>{flags[3]} (Threshold {limits[3]})</td>
|
||||
</tr>
|
||||
</tbody></table>'''
|
||||
|
||||
|
||||
def fiber_page(optical='Up', rx=-169, rx_flags=(0, 0, 0, 0), include_rx=True):
|
||||
rx_table = dom_table('Rx Power', rx, rx_flags) if include_rx else ''
|
||||
return f'''<html><title>Fiber Status</title>
|
||||
<tr><th scope="row" width="47%">Optical WAN Operational Status</th>
|
||||
<td class="col2">{optical} </td></tr>
|
||||
<tr><th scope="row">Wave Length</th><td class="col2">1270 nm </td></tr>
|
||||
<tr><th scope="row">Rx LOS State</th><td class="col2">1</td></tr>
|
||||
<tr><th scope="row">Vendor PN</th><td class="col2">TESTPN</td></tr>
|
||||
{dom_table('Temperature', 34, limits=(-50, 95, -45, 90))}
|
||||
{dom_table('Vcc', 3, limits=(3, 3, 3, 3))}
|
||||
{dom_table('Tx Bias', 6, limits=(0, 500, 0, 400))}
|
||||
{dom_table('Tx Power', 33, limits=(-10, 59, 0, 49))}
|
||||
{rx_table}</html>'''
|
||||
|
||||
|
||||
def broadband_page(connection='Up', pon='OPERATION (O5)'):
|
||||
return f'''<html><title>Broadband Status</title>
|
||||
<tr><th scope="row" width="47%">Broadband Connection Source</th><td class="col2">FIBER</td></tr>
|
||||
<tr><th scope="row" width="47%">Broadband Connection</th>
|
||||
<td class="col2">
|
||||
{connection}
|
||||
</td></tr>
|
||||
<tr><th scope="row">Broadband IPv4 Address</th><td class="col2">203.0.113.10</td></tr>
|
||||
<tr class="a"><th scope="row" class="heading a">Current Speed (Mbps)</th><td>10000</td></tr>
|
||||
<tr><th scope="row">Transmit Bytes</th><td>200</td></tr>
|
||||
<tr><th scope="row">Receive Bytes</th><td>100</td></tr>
|
||||
<tr><th scope="row">Receive Errors</th><td>1</td></tr>
|
||||
<tr><th scope="row">Transmit Errors</th><td>2</td></tr>
|
||||
<tr><th scope="row">Receive Drops</th><td>3</td></tr>
|
||||
<tr><th scope="row">Transmit Drops</th><td>4</td></tr>
|
||||
<tr><th scope="row">Transmit Packets</th><td>7</td></tr>
|
||||
<tr><th scope="row">Transmit Packets</th><td>999</td></tr>
|
||||
<tr><th scope="row">PON Link Status</th><td>{pon}</td></tr>
|
||||
<tr><th scope="row">UNI Status</th><td>up</td></tr></html>'''
|
||||
|
||||
|
||||
SYSINFO = '''<tr><th scope="row">Model Number</th><td class="col2">BGW320-505</td></tr>
|
||||
<tr><th scope="row">Software Version</th><td class="col2">6.35.8</td></tr>
|
||||
<tr><th scope="row">Time Since Last Reboot</th><td class="col2">28951</td></tr>'''
|
||||
|
||||
|
||||
class TestBuildStatus:
|
||||
def test_scales_optical_power_from_tenths_of_dbm(self):
|
||||
d = modem.build_status(fiber_page(), broadband_page(), SYSINFO)
|
||||
assert d['optics']['rx_power']['value'] == -16.9
|
||||
assert d['optics']['tx_power']['value'] == 3.3
|
||||
assert d['optics']['temperature']['value'] == 34.0
|
||||
|
||||
def test_scales_thresholds(self):
|
||||
rx = modem.build_status(fiber_page(), broadband_page())['optics']['rx_power']
|
||||
assert (rx['alarm_low'], rx['alarm_high'], rx['warn_low'], rx['warn_high']) == (-29.2, -9.0, -27.9, -10.0)
|
||||
|
||||
def test_unit_ambiguous_readings_are_dropped_but_flags_kept(self):
|
||||
d = modem.build_status(fiber_page(), broadband_page())
|
||||
assert d['optics']['tx_bias']['value'] is None
|
||||
assert d['optics']['vcc']['alarm_low'] is None
|
||||
assert d['optics']['vcc']['alarm_flag'] is False
|
||||
|
||||
def test_system_and_wan_fields(self):
|
||||
d = modem.build_status(fiber_page(), broadband_page(), SYSINFO)
|
||||
assert d['model'] == 'BGW320-505'
|
||||
assert d['firmware'] == '6.35.8'
|
||||
assert d['uptime_s'] == 28951
|
||||
assert d['broadband_state'] == 'Up'
|
||||
assert d['line_speed_mbps'] == 10000
|
||||
assert d['counters'] == {
|
||||
'rx_bytes': 100, 'tx_bytes': 200, 'rx_errors': 1,
|
||||
'tx_errors': 2, 'rx_drops': 3, 'tx_drops': 4,
|
||||
}
|
||||
|
||||
def test_repeated_label_keeps_first_value(self):
|
||||
assert modem.parse_rows(broadband_page())['Transmit Packets'] == '7'
|
||||
|
||||
def test_sysinfo_is_optional(self):
|
||||
d = modem.build_status(fiber_page(), broadband_page(), '')
|
||||
assert d['model'] == '' and d['uptime_s'] is None
|
||||
|
||||
def test_unknown_page_is_invalid(self):
|
||||
with pytest.raises(modem.ModemDataInvalid):
|
||||
modem.build_status('<html>nope</html>', broadband_page())
|
||||
with pytest.raises(modem.ModemDataInvalid):
|
||||
modem.build_status(fiber_page(), '<html>nope</html>')
|
||||
|
||||
def test_up_link_without_rx_power_is_invalid(self):
|
||||
with pytest.raises(modem.ModemDataInvalid):
|
||||
modem.build_status(fiber_page(include_rx=False), broadband_page())
|
||||
|
||||
def test_cut_fiber_without_rx_power_is_not_invalid(self):
|
||||
d = modem.build_status(fiber_page(optical='Down', include_rx=False), broadband_page(connection='Down'))
|
||||
assert 'rx_power' not in d['optics']
|
||||
assert modem.wan_problems(d)
|
||||
|
||||
|
||||
class TestWanProblems:
|
||||
def test_healthy_link_has_none(self):
|
||||
assert modem.wan_problems(modem.build_status(fiber_page(), broadband_page())) == []
|
||||
|
||||
@pytest.mark.parametrize('field,value,expected', [
|
||||
('broadband_state', 'Down', 'broadband connection is Down'),
|
||||
('optical_state', 'Down', 'optical WAN is Down'),
|
||||
('pon_state', 'INITIAL (O1)', 'PON link state is INITIAL (O1)'),
|
||||
])
|
||||
def test_each_failure_is_reported(self, field, value, expected):
|
||||
d = {'broadband_state': 'Up', 'optical_state': 'Up', 'pon_state': 'OPERATION (O5)', field: value}
|
||||
assert modem.wan_problems(d) == [expected]
|
||||
|
||||
def test_missing_pon_field_is_not_a_problem(self):
|
||||
assert modem.wan_problems({'broadband_state': 'Up', 'optical_state': 'Up', 'pon_state': ''}) == []
|
||||
|
||||
def test_rx_los_pin_is_ignored(self):
|
||||
# Real gateways report Rx LOS State=1 on a healthy link (see fixture).
|
||||
assert modem.wan_problems(modem.build_status(fiber_page(), broadband_page())) == []
|
||||
|
||||
|
||||
class TestMetricStatus:
|
||||
@pytest.mark.parametrize('rx,expected', [
|
||||
(-169, 'ok'),
|
||||
(-279, 'warning'),
|
||||
(-285, 'warning'),
|
||||
(-292, 'alarm'),
|
||||
(-400, 'alarm'),
|
||||
(-100, 'warning'),
|
||||
(-90, 'alarm'),
|
||||
])
|
||||
def test_rx_thresholds(self, rx, expected):
|
||||
rx_metric = modem.parse_dom_metrics(fiber_page(rx=rx))['rx_power']
|
||||
assert modem.metric_status(rx_metric) == expected
|
||||
|
||||
def test_module_flags_win_over_reading(self):
|
||||
alarm = modem.parse_dom_metrics(fiber_page(rx_flags=(1, 0, 0, 0)))['rx_power']
|
||||
warn = modem.parse_dom_metrics(fiber_page(rx_flags=(0, 0, 1, 0)))['rx_power']
|
||||
assert modem.metric_status(alarm) == 'alarm'
|
||||
assert modem.metric_status(warn) == 'warning'
|
||||
|
||||
def test_flag_only_metric(self):
|
||||
assert modem.metric_status(modem.parse_dom_metrics(fiber_page())['vcc']) == 'ok'
|
||||
|
||||
|
||||
class TestCounterRates:
|
||||
def test_rate_from_delta(self):
|
||||
assert modem.counter_rates({'rx_bytes': 300}, {'rx_bytes': 100}, 100)['rx_bytes'] == 2.0
|
||||
|
||||
def test_first_poll_is_none(self):
|
||||
assert modem.counter_rates({'rx_bytes': 300}, None, 100)['rx_bytes'] is None
|
||||
|
||||
def test_reboot_counter_reset_is_none(self):
|
||||
assert modem.counter_rates({'rx_bytes': 5}, {'rx_bytes': 100}, 100)['rx_bytes'] is None
|
||||
|
||||
|
||||
class TestClient:
|
||||
def _client(self, **response):
|
||||
c = modem.ModemClient({'url': 'http://modem.test/'})
|
||||
resp = MagicMock(status_code=response.get('status', 200), text=response.get('text', ''))
|
||||
c.session.get = MagicMock(return_value=resp)
|
||||
return c
|
||||
|
||||
def test_network_failure_is_unreachable(self):
|
||||
c = self._client()
|
||||
c.session.get = MagicMock(side_effect=requests.ConnectionError('boom'))
|
||||
with pytest.raises(modem.ModemUnreachable):
|
||||
c.poll()
|
||||
|
||||
def test_redirect_is_invalid_and_not_followed(self):
|
||||
c = self._client(status=302)
|
||||
with pytest.raises(modem.ModemDataInvalid):
|
||||
c.poll()
|
||||
assert c.session.get.call_args.kwargs['allow_redirects'] is False
|
||||
|
||||
def test_login_page_is_invalid(self):
|
||||
with pytest.raises(modem.ModemDataInvalid, match='login'):
|
||||
self._client(text='<html><title>Login</title></html>').poll()
|
||||
|
||||
|
||||
class TestWanHistory:
|
||||
def ev(self, key, ts, device='RPDU'):
|
||||
return {'key': key, 'ts': ts, 'device': device, 'wan': 'WAN1'}
|
||||
|
||||
def test_outage_opens_and_closes(self):
|
||||
h = {}
|
||||
modem.apply_wan_events(h, [self.ev(modem.LOG_WAN_FAILED, 100), self.ev(modem.LOG_WAN_RESTORED, 200)])
|
||||
assert h['outages'] == [{'failed_at': 100, 'restored_at': 200, 'wan': 'WAN1'}]
|
||||
|
||||
def test_events_are_handled_in_time_order(self):
|
||||
h = {}
|
||||
modem.apply_wan_events(h, [self.ev(modem.LOG_WAN_RESTORED, 200), self.ev(modem.LOG_WAN_FAILED, 100)])
|
||||
assert h['outages'][0]['restored_at'] == 200
|
||||
|
||||
def test_outage_spanning_two_batches(self):
|
||||
h = {}
|
||||
modem.apply_wan_events(h, [self.ev(modem.LOG_WAN_FAILED, 100)])
|
||||
assert h['outages'][0]['restored_at'] is None
|
||||
modem.apply_wan_events(h, [self.ev(modem.LOG_WAN_RESTORED, 200)])
|
||||
assert h['outages'][0]['restored_at'] == 200
|
||||
|
||||
def test_repeat_failure_does_not_open_a_second_outage(self):
|
||||
h = {}
|
||||
modem.apply_wan_events(h, [self.ev(modem.LOG_WAN_FAILED, 100), self.ev(modem.LOG_WAN_FAILED, 150)])
|
||||
assert len(h['outages']) == 1
|
||||
|
||||
def test_restored_without_failure_is_ignored(self):
|
||||
h = {}
|
||||
modem.apply_wan_events(h, [self.ev(modem.LOG_WAN_RESTORED, 200)])
|
||||
assert h['outages'] == []
|
||||
|
||||
def test_blip_is_not_actionable_but_restart_and_instability_are(self):
|
||||
keys = [modem.LOG_WAN_FAILED, modem.LOG_WAN_RESTORED, modem.LOG_MODEM_RESTARTED, modem.LOG_WAN_UNSTABLE]
|
||||
got = modem.apply_wan_events({}, [self.ev(k, i) for i, k in enumerate(keys)])
|
||||
assert [e['key'] for e in got] == [modem.LOG_MODEM_RESTARTED, modem.LOG_WAN_UNSTABLE]
|
||||
|
||||
def test_history_is_bounded(self):
|
||||
h = {}
|
||||
for i in range(60):
|
||||
modem.apply_wan_events(h, [
|
||||
self.ev(modem.LOG_WAN_FAILED, i * 2), self.ev(modem.LOG_WAN_RESTORED, i * 2 + 1),
|
||||
])
|
||||
assert len(h['outages']) == 50
|
||||
|
||||
def test_uptime_reset_confirms_logged_restart(self):
|
||||
h = {}
|
||||
modem.apply_wan_events(h, [self.ev(modem.LOG_MODEM_RESTARTED, 1000)])
|
||||
modem.record_uptime_reset(h, 1023)
|
||||
assert h['restarts'] == [{'at': 1000, 'by': 'RPDU', 'confirmed': True}]
|
||||
|
||||
def test_unexplained_uptime_reset_is_recorded(self):
|
||||
h = {}
|
||||
modem.record_uptime_reset(h, 5000)
|
||||
assert h['restarts'] == [{'at': 5000, 'by': None, 'confirmed': True}]
|
||||
@@ -0,0 +1,375 @@
|
||||
"""Tests for monitor.py alert logic: database and external services are mocked."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import modem as modem_api # noqa: E402
|
||||
import monitor # noqa: E402
|
||||
|
||||
HOST_A, HOST_B = '10.0.0.1:9100', '10.0.0.2:9100'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
with patch.object(monitor, 'db') as mock_db:
|
||||
mock_db.check_suppressed.return_value = False
|
||||
mock_db.get_baseline.return_value = {}
|
||||
# Second consecutive failure and no ticket yet, unless a test overrides it
|
||||
mock_db.upsert_event.return_value = (1, False, 2, None)
|
||||
mock_db.get_modem_rx_values.return_value = []
|
||||
mock_db.get_state.return_value = None
|
||||
yield mock_db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mon(db):
|
||||
m = monitor.NetworkMonitor.__new__(monitor.NetworkMonitor)
|
||||
m.cfg = {}
|
||||
m.fail_thresh = 2
|
||||
m.cluster_thresh = 2
|
||||
m.cluster_name = 'test-cluster'
|
||||
m.tickets = MagicMock()
|
||||
m.tickets.create.return_value = '123'
|
||||
m.prom = MagicMock(url='http://prom.test')
|
||||
m._instance_map = {HOST_A: 'alpha', HOST_B: 'beta'}
|
||||
m._last_iface_states = {}
|
||||
m.modem = MagicMock(base_url='http://modem.test')
|
||||
m.modem_name = 'att-modem'
|
||||
m.modem_lan_ip = '192.168.1.254'
|
||||
m.modem_fail_thresh = 2
|
||||
m.rx_drift_db = 3.0
|
||||
m.rx_drift_min_samples = 288
|
||||
m._prev_modem_counters = None
|
||||
m._prev_modem_time = 0.0
|
||||
return m
|
||||
|
||||
|
||||
def upserted(db):
|
||||
return [(c.args[0], c.args[3], c.args[4]) for c in db.upsert_event.call_args_list]
|
||||
|
||||
|
||||
def healthy_modem(rx=-16.9, rx_status=None):
|
||||
def metric(value, alarm_low, alarm_high, warn_low, warn_high):
|
||||
return {'value': value, 'alarm_low': alarm_low, 'alarm_high': alarm_high,
|
||||
'warn_low': warn_low, 'warn_high': warn_high,
|
||||
'alarm_flag': False, 'warn_flag': False}
|
||||
return {
|
||||
'broadband_state': 'Up', 'optical_state': 'Up', 'pon_state': 'OPERATION (O5)',
|
||||
'counters': {'rx_bytes': 1},
|
||||
'optics': {
|
||||
'rx_power': metric(rx, -29.2, -9.0, -27.9, -10.0),
|
||||
'tx_power': metric(3.3, -1.0, 5.9, 0.0, 4.9),
|
||||
'temperature': metric(34.0, -50.0, 95.0, -45.0, 90.0),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class TestDeadHostDetection:
|
||||
def test_host_missing_from_prometheus_alerts_and_tickets(self, mon, db):
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert ('host_metrics_missing', 'beta', HOST_B) in upserted(db)
|
||||
assert 'No metrics' in mon.tickets.create.call_args.args[0]
|
||||
|
||||
def test_host_reporting_resolves_the_event(self, mon, db):
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}, HOST_B: {'eth0': True}}, [])
|
||||
db.resolve_event.assert_any_call('host_metrics_missing', 'beta', HOST_B)
|
||||
assert not db.upsert_event.called
|
||||
|
||||
def test_no_ticket_before_threshold(self, mon, db):
|
||||
db.upsert_event.return_value = (1, True, 1, None)
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_suppressed_host_gets_no_ticket(self, mon, db):
|
||||
db.check_suppressed.return_value = True
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_missing_hosts_count_toward_cluster_alert(self, mon, db):
|
||||
mon._instance_map['10.0.0.3:9100'] = 'gamma'
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert ('cluster_network_issue', 'test-cluster', '') in upserted(db)
|
||||
|
||||
def test_dead_host_shows_as_down_on_dashboard(self, mon):
|
||||
snap = mon._collect_snapshot({HOST_A: {'eth0': True}})
|
||||
assert snap['hosts']['alpha']['status'] == 'up'
|
||||
assert snap['hosts']['beta']['status'] == 'down'
|
||||
|
||||
|
||||
class TestPrometheusOutage:
|
||||
def test_empty_result_means_unavailable(self):
|
||||
client = monitor.PrometheusClient('http://prom.test')
|
||||
with patch.object(client, '_fetch', return_value=[]):
|
||||
assert client.get_interface_states() is None
|
||||
|
||||
def test_failed_query_is_unavailable_not_empty(self):
|
||||
client = monitor.PrometheusClient('http://prom.test')
|
||||
with patch.object(monitor.requests, 'get', side_effect=OSError('boom')):
|
||||
assert client.get_interface_states() is None
|
||||
assert client.query('up') == []
|
||||
|
||||
def test_outage_alerts_about_prometheus_not_each_host(self, mon, db):
|
||||
mon._process_prometheus_outage([])
|
||||
assert upserted(db) == [('monitor_source_unavailable', 'prometheus', '')]
|
||||
|
||||
def test_dashboard_keeps_hosts_as_unknown(self, mon):
|
||||
mon._last_iface_states = {HOST_A: {'eth0': True}}
|
||||
snap = mon._collect_snapshot(None)
|
||||
assert snap['hosts']['alpha']['status'] == 'unknown'
|
||||
assert snap['hosts']['alpha']['interfaces'] == {'eth0': 'up'}
|
||||
assert snap['hosts']['beta']['status'] == 'unknown'
|
||||
|
||||
|
||||
class TestPingUnknown:
|
||||
def _pulse(self, output):
|
||||
pulse = monitor.PulseClient({})
|
||||
pulse.run_command = MagicMock(return_value=output)
|
||||
return pulse
|
||||
|
||||
def test_pulse_failure_is_unknown(self):
|
||||
assert self._pulse(None).ping('10.0.0.1') is None
|
||||
|
||||
def test_reachability(self):
|
||||
assert self._pulse('REACHABLE\n').ping('10.0.0.1') is True
|
||||
assert self._pulse('UNREACHABLE\n').ping('10.0.0.1') is False
|
||||
|
||||
def test_unknown_neither_alerts_nor_resolves(self, mon, db):
|
||||
mon.cfg = {'monitor': {'ping_hosts': [{'name': 'pbs', 'ip': '10.0.0.3'}]}}
|
||||
mon._process_ping_hosts([], {'pbs': None})
|
||||
assert not db.upsert_event.called
|
||||
assert not db.resolve_event.called
|
||||
|
||||
def test_unreachable_still_alerts(self, mon, db):
|
||||
mon.cfg = {'monitor': {'ping_hosts': [{'name': 'pbs', 'ip': '10.0.0.3'}]}}
|
||||
mon._process_ping_hosts([], {'pbs': False})
|
||||
assert ('host_unreachable', 'pbs', '10.0.0.3') in upserted(db)
|
||||
|
||||
|
||||
class TestUnifiRates:
|
||||
def _collector(self):
|
||||
c = monitor.LinkStatsCollector.__new__(monitor.LinkStatsCollector)
|
||||
c._prev_unifi_time = 100.0
|
||||
c._prev_unifi = {'sw': {'ports': {'Port 1': {
|
||||
'tx_bytes': 100, 'rx_bytes': 100, 'tx_errors': 0, 'rx_errors': 0, 'tx_dropped': 0, 'rx_dropped': 0,
|
||||
}}}}
|
||||
return c
|
||||
|
||||
def test_new_port_has_no_rate_spike(self):
|
||||
port = {'tx_bytes': 10**12, 'rx_bytes': 10**12, 'tx_errors': 5, 'rx_errors': 5,
|
||||
'tx_dropped': 5, 'rx_dropped': 5}
|
||||
raw = {'sw': {'ip': '', 'model': '', 'ports': {'Port 1': dict(port, tx_bytes=300), 'Port 2': port}}}
|
||||
result = self._collector()._compute_unifi_rates(raw, 200.0)['sw']['ports']
|
||||
assert result['Port 2']['tx_bytes_rate'] is None
|
||||
assert result['Port 1']['tx_bytes_rate'] == 2.0
|
||||
|
||||
|
||||
class TestModemAlerts:
|
||||
def test_healthy_link_raises_nothing(self, mon, db):
|
||||
mon._process_modem(healthy_modem(), [])
|
||||
assert not db.upsert_event.called
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_wan_down_is_p1(self, mon, db):
|
||||
data = healthy_modem()
|
||||
data['broadband_state'] = 'Down'
|
||||
mon._process_modem(data, [])
|
||||
assert ('wan_down', 'att-modem', '') in upserted(db)
|
||||
assert mon.tickets.create.call_args.kwargs['priority'] == '1'
|
||||
|
||||
def test_cut_fiber_opens_only_one_ticket(self, mon, db):
|
||||
data = healthy_modem(rx=-40.0)
|
||||
data['optical_state'] = 'Down'
|
||||
mon._process_modem(data, [])
|
||||
assert [e[0] for e in upserted(db)] == ['wan_down']
|
||||
|
||||
def test_low_rx_warning(self, mon, db):
|
||||
mon._process_modem(healthy_modem(rx=-28.0), [])
|
||||
assert ('fiber_signal_warning', 'att-modem', 'rx_power') in upserted(db)
|
||||
assert mon.tickets.create.call_args.kwargs['priority'] == '3'
|
||||
db.resolve_event.assert_any_call('fiber_signal_alarm', 'att-modem', 'rx_power')
|
||||
|
||||
def test_low_rx_alarm_with_link_up(self, mon, db):
|
||||
mon._process_modem(healthy_modem(rx=-30.0), [])
|
||||
assert ('fiber_signal_alarm', 'att-modem', 'rx_power') in upserted(db)
|
||||
db.resolve_event.assert_any_call('fiber_signal_warning', 'att-modem', 'rx_power')
|
||||
|
||||
def test_recovery_resolves_signal_events(self, mon, db):
|
||||
mon._process_modem(healthy_modem(), [])
|
||||
db.resolve_event.assert_any_call('fiber_signal_alarm', 'att-modem', 'rx_power')
|
||||
db.resolve_event.assert_any_call('fiber_signal_warning', 'att-modem', 'rx_power')
|
||||
db.resolve_event.assert_any_call('wan_down', 'att-modem', '')
|
||||
|
||||
def test_suppression_blocks_ticket(self, mon, db):
|
||||
db.check_suppressed.return_value = True
|
||||
mon._process_modem(healthy_modem(rx=-30.0), [])
|
||||
assert upserted(db)
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_drift_needs_enough_history(self, mon, db):
|
||||
db.get_modem_rx_values.return_value = [-17.0] * 10
|
||||
mon._process_modem(healthy_modem(rx=-25.0), [])
|
||||
assert not any(e[0] == 'fiber_rx_drift' for e in upserted(db))
|
||||
|
||||
def test_drift_alerts_inside_the_modem_limits(self, mon, db):
|
||||
db.get_modem_rx_values.return_value = [-17.0] * 300
|
||||
mon._process_modem(healthy_modem(rx=-21.0), [])
|
||||
assert ('fiber_rx_drift', 'att-modem', 'rx_power') in upserted(db)
|
||||
assert 'fiber_signal_warning' not in [e[0] for e in upserted(db)]
|
||||
|
||||
def test_small_change_is_not_drift(self, mon, db):
|
||||
db.get_modem_rx_values.return_value = [-17.0] * 300
|
||||
mon._process_modem(healthy_modem(rx=-18.0), [])
|
||||
assert not db.upsert_event.called
|
||||
db.resolve_event.assert_any_call('fiber_rx_drift', 'att-modem', 'rx_power')
|
||||
|
||||
def test_stronger_signal_is_not_drift(self, mon, db):
|
||||
db.get_modem_rx_values.return_value = [-17.0] * 300
|
||||
mon._process_modem(healthy_modem(rx=-12.0), [])
|
||||
assert not db.upsert_event.called
|
||||
|
||||
|
||||
class TestModemCollection:
|
||||
def test_unreachable_keeps_link_events_open(self, mon, db):
|
||||
mon.modem.poll.side_effect = modem_api.ModemUnreachable('timeout')
|
||||
mon._collect_modem([])
|
||||
assert upserted(db) == [('modem_unreachable', 'att-modem', '')]
|
||||
assert db.set_state.call_args.args[1]['reachable'] is False
|
||||
assert not db.record_modem_sample.called
|
||||
resolved = [c.args[0] for c in db.resolve_event.call_args_list]
|
||||
assert 'wan_down' not in resolved and 'fiber_signal_alarm' not in resolved
|
||||
|
||||
def test_unreadable_page_is_a_warning_not_an_outage(self, mon, db):
|
||||
mon.modem.poll.side_effect = modem_api.ModemDataInvalid('login required')
|
||||
mon._collect_modem([])
|
||||
assert upserted(db) == [('modem_data_invalid', 'att-modem', '')]
|
||||
assert mon.tickets.create.call_args.kwargs['priority'] == '3'
|
||||
|
||||
def test_success_stores_status_and_sample(self, mon, db):
|
||||
mon.modem.poll.return_value = healthy_modem()
|
||||
mon._collect_modem([])
|
||||
assert db.set_state.call_args.args[0] == 'modem_stats'
|
||||
assert db.set_state.call_args.args[1]['reachable'] is True
|
||||
db.record_modem_sample.assert_called_once_with(-16.9, 3.3, 34.0)
|
||||
|
||||
def test_drift_baseline_excludes_the_current_reading(self, mon, db):
|
||||
order = []
|
||||
db.get_modem_rx_values.side_effect = lambda days: order.append('read') or []
|
||||
db.record_modem_sample.side_effect = lambda *a: order.append('write')
|
||||
mon.modem.poll.return_value = healthy_modem()
|
||||
mon._collect_modem([])
|
||||
assert order == ['read', 'write']
|
||||
|
||||
|
||||
class TestWanLog:
|
||||
def _mon(self, mon, events):
|
||||
mon.unifi = MagicMock()
|
||||
mon.unifi.get_system_events.return_value = events
|
||||
return mon
|
||||
|
||||
def _state(self, db, **values):
|
||||
db.get_state.side_effect = lambda key, default=None: values.get(key, default)
|
||||
|
||||
def test_first_run_starts_from_now_without_tickets(self, mon, db):
|
||||
self._state(db)
|
||||
self._mon(mon, [])._process_wan_log([])
|
||||
assert db.set_state.call_args.args[0] == 'unifi_log_cursor'
|
||||
assert not mon.unifi.get_system_events.called
|
||||
|
||||
def test_log_failure_keeps_the_cursor(self, mon, db):
|
||||
self._state(db, unifi_log_cursor='1000')
|
||||
self._mon(mon, None)._process_wan_log([])
|
||||
assert not db.set_state.called
|
||||
|
||||
def test_rpdu_restart_opens_a_ticket_and_resolves(self, mon, db):
|
||||
self._state(db, unifi_log_cursor=str(int(time.time() * 1000)))
|
||||
db.upsert_event.return_value = (9, True, 1, None)
|
||||
self._mon(mon, [{'key': modem_api.LOG_MODEM_RESTARTED, 'ts': time.time(), 'device': 'RPDU', 'wan': ''}])
|
||||
mon._process_wan_log([])
|
||||
assert 'power-cycled' in mon.tickets.create.call_args.args[0]
|
||||
db.resolve_event.assert_called_with('modem_power_cycled', 'att-modem', '')
|
||||
|
||||
def test_short_outage_only_records_history(self, mon, db):
|
||||
now = time.time()
|
||||
self._state(db, unifi_log_cursor=str(int(now * 1000)))
|
||||
self._mon(mon, [
|
||||
{'key': modem_api.LOG_WAN_FAILED, 'ts': now, 'device': 'UDM', 'wan': 'WAN1'},
|
||||
{'key': modem_api.LOG_WAN_RESTORED, 'ts': now + 90, 'device': 'UDM', 'wan': 'WAN1'},
|
||||
])
|
||||
mon._process_wan_log([])
|
||||
assert not mon.tickets.create.called
|
||||
saved = dict((c.args[0], c.args[1]) for c in db.set_state.call_args_list)
|
||||
assert saved['wan_history']['outages'][0]['restored_at'] == now + 90
|
||||
|
||||
def test_unstable_wan_tickets_once_a_day(self, mon, db):
|
||||
now = time.time()
|
||||
history = json.dumps({'outages': [], 'restarts': [], 'unstable_ticketed_at': now - 3600})
|
||||
self._state(db, unifi_log_cursor=str(int(now * 1000)), wan_history=history)
|
||||
self._mon(mon, [{'key': modem_api.LOG_WAN_UNSTABLE, 'ts': now, 'device': 'UDM', 'wan': 'WAN1'}])
|
||||
mon._process_wan_log([])
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_unstable_wan_tickets_after_a_day(self, mon, db):
|
||||
now = time.time()
|
||||
self._state(db, unifi_log_cursor=str(int(now * 1000)))
|
||||
self._mon(mon, [{'key': modem_api.LOG_WAN_UNSTABLE, 'ts': now, 'device': 'UDM', 'wan': 'WAN1'}])
|
||||
mon._process_wan_log([])
|
||||
assert 'unstable' in mon.tickets.create.call_args.args[0]
|
||||
|
||||
def test_suppression_blocks_one_shot_ticket(self, mon, db):
|
||||
now = time.time()
|
||||
db.check_suppressed.return_value = True
|
||||
self._state(db, unifi_log_cursor=str(int(now * 1000)))
|
||||
self._mon(mon, [{'key': modem_api.LOG_MODEM_RESTARTED, 'ts': now, 'device': 'RPDU', 'wan': ''}])
|
||||
mon._process_wan_log([])
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_uptime_going_backwards_records_a_restart(self, mon, db):
|
||||
self._state(db, modem_stats=json.dumps({'uptime_s': 5000}))
|
||||
mon._note_modem_restart({'uptime_s': 60})
|
||||
saved = dict((c.args[0], c.args[1]) for c in db.set_state.call_args_list)
|
||||
assert len(saved['wan_history']['restarts']) == 1
|
||||
|
||||
def test_uptime_going_forward_records_nothing(self, mon, db):
|
||||
self._state(db, modem_stats=json.dumps({'uptime_s': 5000}))
|
||||
mon._note_modem_restart({'uptime_s': 5300})
|
||||
assert not db.set_state.called
|
||||
|
||||
|
||||
class TestUnifiDeviceDetail:
|
||||
def test_parses_string_stats_and_outlets(self):
|
||||
d = monitor.UnifiClient._device_detail({
|
||||
'version': '7.0', 'uptime': 10, 'system-stats': {'cpu': ' 2.4 ', 'mem': 'bad'},
|
||||
'outlet_table': [{'index': 13, 'name': 'AT&T Modem', 'relay_state': True,
|
||||
'cycle_enabled': True, 'outlet_power': '0.000'}],
|
||||
'wan1': {'up': True, 'speed': 1000, 'latency': 15, 'availability': 100},
|
||||
})
|
||||
assert d['cpu_pct'] == 2.4 and d['mem_pct'] is None
|
||||
assert d['outlets'][0]['auto_power_cycle'] is True and d['outlets'][0]['power_w'] == 0.0
|
||||
assert d['wan']['wan1']['speed_mbps'] == 1000
|
||||
assert 'wan2' not in d['wan']
|
||||
|
||||
def test_system_log_filters_and_paginates(self):
|
||||
c = monitor.UnifiClient({'controller': 'https://u.test', 'api_key': 'k'})
|
||||
page = MagicMock()
|
||||
page.json.side_effect = [
|
||||
{'data': [
|
||||
{'key': modem_api.LOG_MODEM_RESTARTED, 'timestamp': 2000, 'parameters': {'DEVICE': {'name': 'RPDU'}}},
|
||||
{'key': 'CLIENT_CONNECTED_WIRED_2', 'timestamp': 2000},
|
||||
{'key': modem_api.LOG_WAN_FAILED, 'timestamp': 500},
|
||||
]},
|
||||
{'data': []},
|
||||
]
|
||||
c.session.post = MagicMock(return_value=page)
|
||||
got = c.get_system_events(1000, modem_api.WAN_LOG_KEYS)
|
||||
assert got == [{'key': modem_api.LOG_MODEM_RESTARTED, 'ts': 2.0, 'device': 'RPDU', 'wan': ''}]
|
||||
|
||||
def test_system_log_failure_is_none_not_empty(self):
|
||||
c = monitor.UnifiClient({'controller': 'https://u.test', 'api_key': 'k'})
|
||||
c.session.post = MagicMock(side_effect=OSError('boom'))
|
||||
assert c.get_system_events(0, modem_api.WAN_LOG_KEYS) is None
|
||||
Reference in new issue
Block a user