matrix-alertbot/tests/test_alert.py

103 lines
3.5 KiB
Python

import unittest
from typing import Dict
from matrix_alertbot.alert import Alert
class AlertTestCase(unittest.TestCase):
def setUp(self) -> None:
self.alert_dict: Dict = {
"fingerprint": "fingerprint1",
"generatorURL": "http://example.com",
"status": "unknown",
"labels": {"alertname": "alert1", "severity": "critical", "job": "job1"},
"annotations": {"description": "some description"},
}
def test_create_firing_alert_from_dict(self) -> None:
self.alert_dict["status"] = "firing"
alert = Alert.from_dict(self.alert_dict)
self.assertEqual("fingerprint1", alert.id)
self.assertEqual("http://example.com", alert.url)
self.assertTrue(alert.firing)
self.assertEqual("critical", alert.status)
self.assertDictEqual(
{"alertname": "alert1", "severity": "critical", "job": "job1"}, alert.labels
)
self.assertDictEqual({"description": "some description"}, alert.annotations)
def test_create_resolved_alert_from_dict(self) -> None:
self.alert_dict["status"] = "resolved"
alert = Alert.from_dict(self.alert_dict)
self.assertEqual("resolved", alert.status)
self.assertFalse(alert.firing)
def test_create_unknown_alert_from_dict(self) -> None:
alert = Alert.from_dict(self.alert_dict)
self.assertEqual("resolved", alert.status)
self.assertFalse(alert.firing)
def test_display_firing_critical_alert(self) -> None:
self.alert_dict["status"] = "firing"
alert = Alert.from_dict(self.alert_dict)
alert.labels["severity"] = "critical"
html = alert.html()
self.assertEqual(
"<font color='#dc3545'><b>[🔥 CRITICAL]</b></font> "
"<a href='http://example.com'>alert1</a> (job1)<br/>"
"some description",
html,
)
plaintext = alert.plaintext()
self.assertEqual("[🔥 CRITICAL] alert1: some description", plaintext)
def test_display_firing_warning_alert(self) -> None:
self.alert_dict["status"] = "firing"
self.alert_dict["labels"]["severity"] = "warning"
alert = Alert.from_dict(self.alert_dict)
html = alert.html()
self.assertEqual(
"<font color='#ffc107'><b>[⚠️ WARNING]</b></font> "
"<a href='http://example.com'>alert1</a> (job1)<br/>"
"some description",
html,
)
plaintext = alert.plaintext()
self.assertEqual("[⚠️ WARNING] alert1: some description", plaintext)
def test_display_firing_unknown_alert(self) -> None:
self.alert_dict["status"] = "firing"
self.alert_dict["labels"]["severity"] = "unknown"
alert = Alert.from_dict(self.alert_dict)
with self.assertRaisesRegex(KeyError, "unknown"):
alert.html()
with self.assertRaisesRegex(KeyError, "unknown"):
alert.plaintext()
def test_display_resolved_alert(self) -> None:
self.alert_dict["status"] = "resolved"
alert = Alert.from_dict(self.alert_dict)
html = alert.html()
self.assertEqual(
"<font color='#33cc33'><b>[🥦 RESOLVED]</b></font> "
"<a href='http://example.com'>alert1</a> (job1)<br/>"
"some description",
html,
)
plaintext = alert.plaintext()
self.assertEqual("[🥦 RESOLVED] alert1: some description", plaintext)
if __name__ == "__main__":
unittest.main()