fault-log-analyzer/tests/test_classifier.py

67 lines
2.5 KiB
Python

"""簇 -> fault_type 归类测试。"""
import _bootstrap # noqa: F401
import unittest
from fault_log_analyzer.classifier import DEFAULT_FAULT_TYPES, Classifier
from fault_log_analyzer.models import FaultType
class TestDefaultClassifier(unittest.TestCase):
def test_pattern_disk(self):
self.assertEqual(Classifier().classify("No space left on device"), "disk_full")
def test_pattern_memory(self):
self.assertEqual(
Classifier().classify("out of memory: process killed"), "memory_exhausted"
)
def test_pattern_network(self):
self.assertEqual(Classifier().classify("connection refused"), "network_unreachable")
def test_hint_timeout(self):
self.assertEqual(Classifier().classify("request timed out"), "timeout")
def test_hint_permission(self):
self.assertEqual(Classifier().classify("permission denied"), "permission_denied")
def test_hint_unknown(self):
self.assertIsNone(Classifier().classify("some ordinary message"))
class TestClusterMapping(unittest.TestCase):
def test_registered_cluster_takes_priority(self):
c = Classifier()
c.register_cluster(1, "disk_full")
self.assertEqual(c.classify("nothing relevant", cluster_id=1), "disk_full")
def test_classify_cluster_sets_map(self):
c = Classifier()
self.assertEqual(c.classify_cluster(3, ["no space left on device"]), "disk_full")
self.assertEqual(c.classify("whatever", cluster_id=3), "disk_full")
class TestCustomFaultTypes(unittest.TestCase):
def test_disabled_type_skipped(self):
c = Classifier([FaultType(fault_type="custom", name="C", pattern="custom", enabled=False)])
self.assertIsNone(c.classify("a custom message that is not a known hint"))
def test_custom_pattern_matches(self):
c = Classifier([FaultType(fault_type="custom", name="C", pattern="custom error")])
self.assertEqual(c.classify("a custom error happened"), "custom")
def test_invalid_pattern_regex_ignored(self):
c = Classifier([FaultType(fault_type="bad", name="B", pattern="(")])
self.assertIsNone(c.classify("anything"))
class TestDefaultFaultTypes(unittest.TestCase):
def test_has_expected_types(self):
names = {ft.fault_type for ft in DEFAULT_FAULT_TYPES}
self.assertIn("disk_full", names)
self.assertIn("memory_exhausted", names)
self.assertIn("network_unreachable", names)
if __name__ == "__main__":
unittest.main()