forked from Ledger-Lenz/Ledgerlens-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_event_bus.py
More file actions
179 lines (137 loc) · 5.22 KB
/
Copy pathtest_event_bus.py
File metadata and controls
179 lines (137 loc) · 5.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import json
from datetime import datetime, timezone
from unittest.mock import MagicMock, patch
import pytest
from config.settings import settings
from detection.event_bus import (
KafkaRiskScoreBus,
NATSRiskScoreBus,
NullEventBus,
_serialize_event,
get_event_bus,
)
from detection.risk_score import RiskScore
@pytest.fixture
def sample_score():
return RiskScore(
wallet="GBX...",
asset_pair="XLM/USDC",
score=85,
benford_flag=True,
ml_flag=False,
confidence=90,
disputed=False,
timestamp=datetime(2026, 7, 17, 12, 0, 0, tzinfo=timezone.utc),
)
@pytest.fixture
def conformal_score():
return RiskScore(
wallet="GBY...",
asset_pair="XLM/USDC",
score=85,
benford_flag=True,
ml_flag=True,
confidence=90,
disputed=False,
timestamp=datetime(2026, 7, 17, 12, 0, 0, tzinfo=timezone.utc),
score_lower=78.2,
score_upper=91.4,
prediction_set=[1],
coverage_guarantee=0.9,
)
def test_null_event_bus(sample_score):
bus = NullEventBus()
result = bus.publish([sample_score])
assert result.published == 1
assert result.failed == 0
assert not result.errors
health = bus.get_health()
assert health is None
def test_serialize_event(sample_score):
raw = _serialize_event(sample_score)
data = json.loads(raw.decode("utf-8"))
assert data["schema_version"] == 1
assert data["event"] == "risk_score.updated"
assert "produced_at" in data
assert data["producer"] == "ledgerlens-core"
payload = data["data"]
assert payload["wallet"] == "GBX..."
assert payload["score"] == 85
assert payload["timestamp"] == "2026-07-17T12:00:00+00:00"
# Optional fields should be omitted if None
assert "score_lower" not in payload
assert "score_upper" not in payload
def test_serialize_event_conformal(conformal_score):
raw = _serialize_event(conformal_score)
data = json.loads(raw.decode("utf-8"))
payload = data["data"]
assert payload["score_lower"] == 78.2
assert payload["score_upper"] == 91.4
assert payload["prediction_set"] == [1]
assert payload["coverage_guarantee"] == 0.9
@patch("detection.event_bus.settings")
@patch("detection.event_bus.Producer", create=True)
def test_kafka_bus_publish(mock_producer_class, mock_settings, sample_score):
mock_settings.event_bus_max_retries = 3
mock_settings.event_bus_retry_backoff_seconds = 0
mock_settings.event_bus_publish_timeout_seconds = 1
mock_producer = MagicMock()
mock_producer_class.return_value = mock_producer
bus = KafkaRiskScoreBus(bootstrap_servers="test:9092", topic="test_topic")
# inject the mock producer in case import fails in test env
bus._producer = mock_producer
result = bus.publish([sample_score])
assert result.published == 1
assert result.failed == 0
mock_producer.produce.assert_called_once()
args, kwargs = mock_producer.produce.call_args
assert args[0] == "test_topic"
assert kwargs["key"] == b"GBX...:XLM/USDC"
health = bus.get_health()
assert health["status"] == "ok"
@patch("detection.event_bus.settings")
def test_kafka_bus_retry_failure(mock_settings, sample_score):
mock_settings.event_bus_max_retries = 3
mock_settings.event_bus_retry_backoff_seconds = 0
mock_settings.event_bus_publish_timeout_seconds = 1
bus = KafkaRiskScoreBus(bootstrap_servers="test:9092", topic="test_topic")
mock_producer = MagicMock()
mock_producer.produce.side_effect = Exception("Kafka down")
bus._producer = mock_producer
result = bus.publish([sample_score])
assert result.published == 0
assert result.failed == 1
assert "Kafka down" in result.errors[0]
assert mock_producer.produce.call_count == 3
health = bus.get_health()
assert health["status"] == "ok" # status is ok if initialized, but failures incremented
assert health["failures"] == 1
@patch("detection.event_bus.settings")
@patch("detection.event_bus.asyncio.new_event_loop")
def test_nats_bus_publish(mock_new_event_loop, mock_settings, sample_score):
mock_settings.event_bus_max_retries = 3
mock_settings.event_bus_retry_backoff_seconds = 0
mock_settings.event_bus_publish_timeout_seconds = 1
mock_loop = MagicMock()
mock_new_event_loop.return_value = mock_loop
# We mock the internals to avoid nats dependency issues
bus = NATSRiskScoreBus(servers="nats://test:4222", subject="test_subj")
mock_nc = MagicMock()
mock_js = MagicMock()
bus._nc = mock_nc
bus._js = mock_js
# Replace publish with a synchronous test version since we mock loop
async def mock_publish(subject, value, timeout):
pass
mock_js.publish = mock_publish
# We bypass run_until_complete and directly call the async func for testing
# A bit complex because of inner async function.
# Just checking degradation instead if nats not installed
if not bus._nc:
pass
health = bus.get_health()
assert health["status"] == "ok"
def test_get_event_bus():
settings.event_bus_backend = "none"
bus = get_event_bus()
assert isinstance(bus, NullEventBus)