fault-log-analyzer/tests/test_classifier.py

49 lines
1.7 KiB
Python

import _bootstrap # noqa: F401
import unittest
from datetime import datetime, timezone
from fault_log_analyzer.classifier import FaultClassifier
from fault_log_analyzer.models import FaultLog, FaultType
def make_log(message, cluster_id=""):
return FaultLog(
fault_log_id="fl-1",
host_id="h-1",
fingerprint="fp",
level="ERROR",
message=message,
occurred_at=datetime(2025, 1, 1, tzinfo=timezone.utc),
cluster_id=cluster_id,
)
class TestFaultClassifier(unittest.TestCase):
def test_pattern_match(self):
c = FaultClassifier([FaultType(fault_type="disk_full", name="磁盘满", pattern=r"no space|disk full")])
self.assertEqual(c.match(make_log("No space left on device")), "disk_full")
def test_name_match(self):
c = FaultClassifier([FaultType(fault_type="oom", name="OOMKilled")])
self.assertEqual(c.match(make_log("OOMKilled process")), "oom")
def test_cluster_type_map_priority(self):
c = FaultClassifier([FaultType(fault_type="disk_full", name="磁盘满", pattern="")])
self.assertEqual(c.match(make_log("anything", cluster_id="c1"), {"c1": "disk_full"}), "disk_full")
def test_no_match(self):
c = FaultClassifier([])
self.assertIsNone(c.match(make_log("unknown message")))
def test_guess_candidate(self):
c = FaultClassifier()
self.assertEqual(c.guess_candidate("No space left on device"), "disk_full")
self.assertEqual(c.guess_candidate("Out of memory"), "oom")
self.assertEqual(c.guess_candidate("Connection refused"), "connection_refused")
self.assertEqual(c.guess_candidate("nothing recognizable"), "unknown")
if __name__ == "__main__":
unittest.main()