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(
"[🔥 CRITICAL] "
"alert1 (job1)
"
"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(
"[⚠️ WARNING] "
"alert1 (job1)
"
"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(
"[🥦 RESOLVED] "
"alert1 (job1)
"
"some description",
html,
)
plaintext = alert.plaintext()
self.assertEqual("[🥦 RESOLVED] alert1: some description", plaintext)
if __name__ == "__main__":
unittest.main()