60 lines
2.1 KiB
Python
60 lines
2.1 KiB
Python
"""可选真实后端适配器测试(Kafka/ES/MySQL/Redis)。"""
|
||
import _bootstrap # noqa: F401
|
||
import unittest
|
||
from datetime import datetime, timezone
|
||
from unittest.mock import patch
|
||
|
||
from fault_log_analyzer.integrations import (
|
||
ElasticsearchSink,
|
||
KafkaConsumerAdapter,
|
||
KafkaProducerAdapter,
|
||
MySQLFaultRepository,
|
||
RedisDedupCache,
|
||
)
|
||
|
||
|
||
class TestAdaptersRequireDependencies(unittest.TestCase):
|
||
"""未安装对应 SDK 时,实例化应抛出明确 RuntimeError。"""
|
||
|
||
def test_kafka_producer_requires_kafka(self):
|
||
with patch.dict("sys.modules", {"kafka": None}):
|
||
with self.assertRaises(RuntimeError):
|
||
KafkaProducerAdapter("localhost:9092")
|
||
|
||
def test_kafka_consumer_requires_kafka(self):
|
||
with patch.dict("sys.modules", {"kafka": None}):
|
||
with self.assertRaises(RuntimeError):
|
||
KafkaConsumerAdapter("localhost:9092", "g", "logs.raw")
|
||
|
||
def test_elasticsearch_requires_es(self):
|
||
with patch.dict("sys.modules", {"elasticsearch": None}):
|
||
with self.assertRaises(RuntimeError):
|
||
ElasticsearchSink("http://localhost:9200")
|
||
|
||
def test_mysql_requires_pymysql(self):
|
||
with patch.dict("sys.modules", {"pymysql": None}):
|
||
with self.assertRaises(RuntimeError):
|
||
MySQLFaultRepository("localhost", 3306, "u", "p", "db")
|
||
|
||
def test_redis_requires_redis(self):
|
||
with patch.dict("sys.modules", {"redis": None}):
|
||
with self.assertRaises(RuntimeError):
|
||
RedisDedupCache("redis://localhost:6379/0")
|
||
|
||
|
||
class TestElasticsearchIndexName(unittest.TestCase):
|
||
def test_index_name_monthly(self):
|
||
dt = datetime(2025, 1, 15, 10, 0, 0, tzinfo=timezone.utc)
|
||
self.assertEqual(
|
||
ElasticsearchSink._index_name("hms-fault-log", dt), "hms-fault-log-2025.01"
|
||
)
|
||
|
||
def test_index_name_default_now(self):
|
||
name = ElasticsearchSink._index_name("hms-fault-log", None)
|
||
self.assertTrue(name.startswith("hms-fault-log-"))
|
||
self.assertEqual(len(name), len("hms-fault-log-") + 7)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|