"""The SNMP pages (milestone 491): devices not answering first and saying why,
readings in their units, the editor, and Test's answer."""
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace as NS
from plugins.snmp.routes import devices_for_host
from tests._templates import render_plugin_template
from tests.test_style_tokens import hex_colours
def _view(name, reach, says="Answering.", readings=(), ok_minutes=None, missing=()):
now = datetime.now(timezone.utc)
return {"id": f"id-{name}", "name": name, "address": "10.0.0.9", "port": 161, "version": "2c",
"reach": reach, "says": says, "polled_at": now - timedelta(seconds=20),
"ok_at": now - timedelta(minutes=ok_minutes) if ok_minutes is not None else None,
"readings": list(readings), "missing": list(missing)}
async def test_a_device_not_answering_says_why_and_since_when(app):
from quart import session
devices = [
_view("ups", "down", "No reply from 10.0.0.9:161 within 5 s. Check the address.", ok_minutes=180,
readings=[{"key": "battery_charge", "name": "Charge", "counter": False, "text": "97%"}]),
_view("printer", "down", "No reply from 10.0.0.10:161 within 5 s."),
_view("switch", "up", readings=[{"key": "if1_in", "name": "Interface 1 in", "counter": True, "text": "—"},
{"key": "uptime", "name": "Uptime", "counter": False, "text": "12d 4h"}],
missing=["Load"]),
_view("new", "pending"),
]
async with app.test_request_context("/plugins/snmp/"):
session["user_role"] = "admin"
page = await render_plugin_template(app, "snmp", "snmp/index.html", devices=devices)
page = " ".join(page.split())
assert page.count('Not answering') == 2
assert "No reply from 10.0.0.9:161 within 5 s. Check the address." in page
assert "Last answered" in page and ">3h ago" in page and "It has never answered." in page
assert "the readings below are from then" in page
assert '97%' in page and '12d 4h' in page
assert "from the second poll" in page # a counter's rate needs two polls
assert "Not answered by this device: Load" in page
assert "Not polled yet: the first poll runs within a minute of saving." in page
assert 'href="/plugins/snmp/devices/new"' in page and 'href="/plugins/snmp/devices/id-ups/edit"' in page
main = page[page.index("49 xe-0/1/0' in ok
assert 'role="alert"' in bad and "No reply from 10.0.0.2:161" in bad
def test_a_device_shows_on_its_bound_host_or_at_its_address():
devices = [NS(name="sw", address="192.168.1.2", host_id=None),
NS(name="ups", address="10.0.0.9", host_id="h-nas"),
NS(name="pdu", address="nas.lan", host_id=None)]
assert [d.name for d in devices_for_host(devices, "h-nas", "192.168.1.50", "NAS.lan")] == ["ups", "pdu"]
assert [d.name for d in devices_for_host(devices, "h-other", "10.0.0.9", "x")] == [] # bound elsewhere
assert [d.name for d in devices_for_host(devices, "h1", "192.168.1.2", None)] == ["sw"]
assert devices_for_host(devices, "h1", "", None) == []