-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_communication.py
More file actions
332 lines (249 loc) · 10.4 KB
/
test_communication.py
File metadata and controls
332 lines (249 loc) · 10.4 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import os
import pytest
import asyncio
from unittest.mock import MagicMock, AsyncMock
from fastapi import FastAPI, APIRouter
from httpx import AsyncClient
from httpx._transports.asgi import ASGITransport
from openscada_lite.modules.security.service import SecurityService
from openscada_lite.common.models.dtos import (
DriverConnectCommand,
DriverConnectStatus,
RawTagUpdateMsg,
)
from openscada_lite.modules.communication.controller import CommunicationController
from openscada_lite.modules.communication.service import CommunicationService
from openscada_lite.modules.communication.model import CommunicationModel
from openscada_lite.common.bus.event_types import EventType
from openscada_lite.common.bus.event_bus import EventBus
from openscada_lite.common.config.config import Config
from openscada_lite.modules.communication.manager.connector_manager import (
ConnectorManager,
)
# --------------------------
# Fixtures
# --------------------------
@pytest.fixture(autouse=True)
def reset_event_bus(monkeypatch):
"""Reset the EventBus singleton before each test."""
monkeypatch.setattr(EventBus, "_instance", None)
@pytest.fixture(autouse=True)
def reset_connector_manager(monkeypatch):
"""Reset the ConnectorManager singleton before each test."""
monkeypatch.setattr(ConnectorManager, "_instance", None)
@pytest.fixture(scope="session", autouse=True)
def set_scada_config_path():
"""Ensure SCADA_CONFIG_PATH points to the test configuration."""
os.environ["SCADA_CONFIG_PATH"] = "tests/system_config.json"
@pytest.fixture
def dummy_event_bus():
"""Provide a dummy async EventBus for tests."""
class DummyEventBus:
def __init__(self):
self.published = []
def publish(self, event_type, data):
self.published.append((event_type, data))
def subscribe(self, event_type, handler):
pass # To implement if needed by the test
return DummyEventBus()
@pytest.fixture(autouse=True)
def allow_all_security(monkeypatch):
mock_security_service = MagicMock()
mock_security_service.is_allowed.return_value = True
monkeypatch.setattr(SecurityService, "_instance", mock_security_service)
@pytest.fixture
def model():
return CommunicationModel()
@pytest.fixture
def service(model, dummy_event_bus):
svc = CommunicationService(dummy_event_bus, model, None)
return svc, dummy_event_bus, model
@pytest.fixture
def fastapi_app(model):
"""FastAPI app with CommunicationController mounted."""
app = FastAPI()
router = APIRouter()
controller = CommunicationController(model, MagicMock(), "communication", router)
controller.service = MagicMock()
app.include_router(controller.router)
return app, controller
# --------------------------
# Tests: Controller Endpoints
# --------------------------
@pytest.mark.asyncio
async def test_connect_driver_valid_status(fastapi_app):
app, controller = fastapi_app
controller.service.handle_controller_message = AsyncMock(return_value=True)
# Use ASGITransport to wrap the FastAPI app
transport = ASGITransport(app=app)
async with AsyncClient(
transport=transport, base_url="http://testserver"
) as ac: # NOSONAR
data = DriverConnectCommand(driver_name="WaterTank", status="connect")
response = await ac.post(
"/communication/driverconnectcommand", json=data.to_dict()
)
assert response.status_code == 200
assert response.json()["status"] == "ok"
assert response.json()["reason"] == "Request accepted."
assert "data" in response.json() # Optionally check for data key
controller.service.handle_controller_message.assert_called_once_with(data)
@pytest.mark.asyncio
async def test_connect_driver_invalid_status(fastapi_app):
app, controller = fastapi_app
controller.service.handle_controller_message = AsyncMock(return_value=True)
mock_security_service = MagicMock()
mock_security_service.is_allowed.return_value = True
SecurityService._instance = mock_security_service
# Use ASGITransport to wrap the FastAPI app
transport = ASGITransport(app=app)
async with AsyncClient(
transport=transport, base_url="http://testserver"
) as ac: # NOSONAR
data = DriverConnectCommand(driver_name="WaterTank", status="bad_status")
response = await ac.post(
"/communication/driverconnectcommand", json=data.to_dict()
)
assert response.status_code == 400
assert response.json()["status"] == "error"
assert (
response.json()["reason"]
== "Invalid status. Must be 'connect', 'disconnect', or 'toggle'."
)
assert "data" in response.json() # Optionally check for data key
controller.service.handle_controller_message.assert_not_called()
@pytest.mark.asyncio
async def test_publish_status_emits(fastapi_app):
Config.reset_instance()
Config.get_instance("tests/config/test_config.json")
_, controller = fastapi_app
# Mock socketio.emit as async function
async_mock = MagicMock()
def fake_emit(*args, **kwargs):
async_mock(*args, **kwargs)
controller.socketio.emit = fake_emit
# Create a command message
cmd = DriverConnectCommand(
track_id="1234", driver_name="WaterTank", status="connect"
)
# Call publish (synchronous method, no await needed)
controller.publish(cmd)
# Wait for the batch worker to process the buffer
await asyncio.sleep(1.1) # Slightly longer than the batch interval (1 second)
# Verify emit was called
async_mock.assert_called_once()
args, kwargs = async_mock.call_args
# Check the event name
assert args[0] == "communication_driverconnectstatus"
# Check that the emitted batch contains the expected message
emitted_batch = args[1]
assert isinstance(emitted_batch, list), "Expected a batch (list) of messages"
assert any(
message["track_id"] == "1234" and message["driver_name"] == "WaterTank"
for message in emitted_batch
), "Expected message not found in emitted batch"
# Check the room argument
assert kwargs["room"] == "communication_room"
# --------------------------
# Tests: Service / EventBus
# --------------------------
@pytest.mark.asyncio
async def test_service_publishes_connect_status(service):
Config.reset_instance()
Config.get_instance("tests/config/test_config.json")
bus = EventBus.get_instance()
comm_service = CommunicationService(bus, CommunicationModel(), None)
events = []
wait_event = asyncio.Event()
async def handler(evt):
events.append(evt)
await asyncio.sleep(0) # Make function actually async
wait_event.set()
bus.subscribe(EventType.DRIVER_CONNECT_STATUS, handler)
await comm_service.async_init()
await comm_service.handle_controller_message(
DriverConnectCommand("WaterTank", "connect")
)
assert any(getattr(e, "driver_name", None) == "WaterTank" for e in events)
@pytest.mark.asyncio
async def test_service_invalid_bus_message_raises(service):
svc, _, _ = service
svc.controller = MagicMock()
with pytest.raises(TypeError):
await svc.handle_bus_message(
DriverConnectStatus(track_id="1", driver_name="X", status="connect")
)
# --------------------------
# Tests: CommunicationModel
# --------------------------
def test_set_and_get_status():
model = CommunicationModel()
model.update(DriverConnectStatus("WaterTank", "connect"))
model.update(DriverConnectStatus("AuxServer", "disconnect"))
assert {k: v.status for k, v in model.get_all().items()} == {
"WaterTank": "connect",
"AuxServer": "disconnect",
}
# Ensure model internal dict is not overwritten
all_status = model.get_all()
all_status["WaterTank"].status = "disconnect"
assert model.get_all()["WaterTank"].status == "connect"
def test_driver_initial_status_is_disconnected():
model = CommunicationModel()
driver_name = "WaterTank"
model.update(DriverConnectStatus(driver_name, "disconnect"))
assert model.get_all()[driver_name].status == "disconnect"
@pytest.mark.asyncio
async def test_driver_publishes_disconnected_status_on_start():
Config.reset_instance()
Config.get_instance("tests/config/test_config.json")
bus = EventBus.get_instance()
comm_service = CommunicationService(bus, CommunicationModel(), None)
manager = comm_service.connection_manager
events = []
wait_event = asyncio.Event()
async def handler(evt):
events.append(evt)
await asyncio.sleep(0) # Make function actually async
wait_event.set()
bus.subscribe(EventType.DRIVER_CONNECT_STATUS, handler)
await manager.start_all()
await asyncio.wait_for(wait_event.wait(), timeout=2.0)
assert any(getattr(e, "status", None) == "offline" for e in events)
await manager.stop_all()
@pytest.mark.asyncio
async def test_emit_communication_status(monkeypatch):
class DummyConfig:
def get_datapoint_types_for_driver(self, driver_name, types):
if driver_name == "TestDriver":
return {"TANK": {"default": 0.0}, "PUMP": {"default": "CLOSED"}}
return {}
def get_drivers(self):
return []
def get_types(self):
return {}
monkeypatch.setattr(
"openscada_lite.common.config.config.Config.get_instance", lambda: DummyConfig()
)
bus = EventBus.get_instance()
published = []
# Fixed fake_publish function
async def fake_publish(self, event_type, data):
published.append((event_type, data))
await asyncio.sleep(0) # Add a minimal async operation
monkeypatch.setattr(EventBus, "publish", fake_publish)
service = CommunicationService(bus, CommunicationModel(), None)
manager = service.connection_manager
manager.driver_status["TestDriver"] = "online"
status = DriverConnectStatus(driver_name="TestDriver", status="offline")
await manager.emit_communication_status(status)
raw_updates = [d for e, d in published if e == EventType.RAW_TAG_UPDATE]
assert len(raw_updates) == 2
for msg in raw_updates:
assert isinstance(msg, RawTagUpdateMsg)
assert msg.quality == "unknown"
assert msg.datapoint_identifier in ["TestDriver@TANK", "TestDriver@PUMP"]
if msg.datapoint_identifier.endswith("TANK"):
assert msg.value == pytest.approx(0.0)
elif msg.datapoint_identifier.endswith("PUMP"):
assert msg.value == "CLOSED"