Skip to content

Commit a0a9f03

Browse files
committed
sonarqube
1 parent 144bfb0 commit a0a9f03

File tree

8 files changed

+68
-29
lines changed

8 files changed

+68
-29
lines changed

agents/matlab/matlab_agent/resources/use_matlab_agent_interactive.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
class AsyncInteractiveMatlabClient:
2727
"""Asynchronous client for sending interactive simulation requests to MATLAB."""
2828

29-
def __init__(self, agent_id: str, destination_id: str, config: Dict[str, Any]):
29+
def __init__(self, agent_id: str, destination_id: str,
30+
config: Dict[str, Any]):
3031
self.agent_id = agent_id
3132
self.destination_id = destination_id
3233
self.config = config
@@ -56,15 +57,18 @@ async def setup(self):
5657

5758
self.queue = await self.channel.declare_queue(self.result_queue, durable=True)
5859
await self.queue.bind(
59-
self.ex_result, routing_key=f"{self.destination_id}.result.{self.agent_id}"
60+
self.ex_result, routing_key=f"{
61+
self.destination_id}.result.{
62+
self.agent_id}"
6063
)
6164

6265
async def send_initial_interactive_request(
6366
self, payload: Dict[str, Any], request_id: str
6467
):
6568
"""Send the initial interactive simulation request to MATLAB."""
6669
payload["simulation"]["request_id"] = request_id
67-
payload["simulation"].setdefault("bridge_meta", {})["protocol"] = "rabbitmq"
70+
payload["simulation"].setdefault("bridge_meta", {})[
71+
"protocol"] = "rabbitmq"
6872

6973
yaml_body = yaml.dump(payload, default_flow_style=False)
7074
routing_key = f"{self.agent_id}.{self.destination_id}"
@@ -124,7 +128,6 @@ async def main():
124128
)
125129
args = parser.parse_args()
126130

127-
128131
async with await anyio.open_file(args.api_payload, "r", encoding="utf-8") as f:
129132
payload = yaml.safe_load(await f.read())
130133

agents/matlab/matlab_agent/src/comm/connect.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
BROKER_NOT_INITIALIZED_ERROR = "Broker not initialized"
1616

17+
1718
class Connect:
1819
"""
1920
A communication wrapper that provides a unified interface for messaging,

agents/matlab/matlab_agent/src/comm/rabbitmq/rabbitmq_manager.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,9 @@ def connect(self) -> bool:
6666

6767
if use_tls:
6868
context = ssl.create_default_context()
69-
ssl_options = pika.SSLOptions(context, rabbitmq_config.get('host', 'localhost'))
69+
ssl_options = pika.SSLOptions(
70+
context, rabbitmq_config.get(
71+
'host', 'localhost'))
7072
parameters = pika.ConnectionParameters(
7173
host=rabbitmq_config.get('host', 'localhost'),
7274
port=rabbitmq_config.get('port', 5671),

agents/matlab/matlab_agent/src/core/interactive.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,9 @@ def handle_interactive_simulation(
268268
pm = PerformanceMonitor()
269269
sim = msg_dict["simulation"]
270270
pm.start_operation(sim["request_id"])
271-
logger.debug("[INTERACTIVE] Starting interactive simulation: %s", sim["file"])
271+
logger.debug(
272+
"[INTERACTIVE] Starting interactive simulation: %s",
273+
sim["file"])
272274
controller = MatlabInteractiveController(
273275
path_simulation or sim.get("path"),
274276
sim["file"],

agents/matlab/matlab_agent/src/main.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
SIMULATION_STREAMING = 'SimulationStreaming.m'
1818
MATLAB_AGENT_RESOURCES = 'matlab_agent.resources'
1919

20+
2021
@click.command()
2122
@click.option('--config-file', '-c', type=click.Path(exists=True),
2223
default=None, help='Path to custom configuration file')
@@ -94,13 +95,13 @@ def generate_default_project():
9495
files_to_generate = {
9596
'config.yaml': ('matlab_agent.config', 'config.yaml.template'),
9697
SIMULATION_WRAPPER_STREAMING: (MATLAB_AGENT_RESOURCES,
97-
SIMULATION_WRAPPER_STREAMING),
98+
SIMULATION_WRAPPER_STREAMING),
9899
SIMULATION_WRAPPER_INTERACTIVE: (MATLAB_AGENT_RESOURCES,
99-
SIMULATION_WRAPPER_INTERACTIVE),
100+
SIMULATION_WRAPPER_INTERACTIVE),
100101
SIMULATION_BATCH: ('matlab_agent.docs.examples',
101-
'simulation_batch.m.template'),
102+
'simulation_batch.m.template'),
102103
SIMULATION_STREAMING: ('matlab_agent.docs.examples',
103-
'simulation_streaming.m.template'),
104+
'simulation_streaming.m.template'),
104105
'client/use_matlab_agent_interactive.py': (MATLAB_AGENT_RESOURCES,
105106
'use_matlab_agent_interactive.py'),
106107
'client/use_matlab_agent.py': (MATLAB_AGENT_RESOURCES,

agents/matlab/matlab_agent/test/integration/test_integration_rabbitmq_client.py

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ def send_result(self, source: str, response: Dict[str, Any]) -> None: # noqa: D
6060
self.sent_results.append({"source": source, "response": response})
6161

6262
def send_message(self, routing_key: str, message: Dict[str, Any]) -> None: # noqa: D401
63-
self.sent_messages.append({"routing_key": routing_key, "message": message})
63+
self.sent_messages.append(
64+
{"routing_key": routing_key, "message": message})
6465

6566

6667
class MockSimulationInputs:
@@ -114,7 +115,8 @@ def __init__(self, **kwargs: Any) -> None: # noqa: D401
114115
class MockMessageHandler:
115116
"""Lightweight replacement for the real *MessageHandler*."""
116117

117-
def __init__(self, agent_id: str, rabbitmq_manager: Any, config: Dict[str, Any]):
118+
def __init__(self, agent_id: str, rabbitmq_manager: Any,
119+
config: Dict[str, Any]):
118120
self.agent_id = agent_id
119121
self.rabbitmq_manager = rabbitmq_manager
120122
self.path_simulation = config.get("simulation", {}).get("path")
@@ -130,7 +132,13 @@ def handle_message(self, ch, method, properties, body: bytes) -> None: # noqa:
130132
self.processed_messages.append(msg_dict)
131133

132134
sim = msg_dict.get("simulation", {})
133-
required = {"request_id", "client_id", "simulator", "type", "file", "inputs"}
135+
required = {
136+
"request_id",
137+
"client_id",
138+
"simulator",
139+
"type",
140+
"file",
141+
"inputs"}
134142
missing = required - sim.keys()
135143
if missing:
136144
response = {
@@ -172,7 +180,8 @@ def handle_message(self, ch, method, properties, body: bytes) -> None: # noqa:
172180
"error": f"Unknown simulation type: {payload.simulation.type}",
173181
}
174182

175-
self.rabbitmq_manager.send_result(method.routing_key.split(".")[0], response)
183+
self.rabbitmq_manager.send_result(
184+
method.routing_key.split(".")[0], response)
176185
ch.basic_ack(method.delivery_tag)
177186

178187
except yaml.YAMLError as exc:
@@ -181,9 +190,15 @@ def handle_message(self, ch, method, properties, body: bytes) -> None: # noqa:
181190
self._send_error(ch, method, "execution_error", str(exc))
182191

183192
def _send_error(self, ch, method, err_type: str, details: str) -> None: # noqa: ANN001
184-
err = {"status": "error", "error": {"message": "Error processing message", "details": details, "type": err_type}}
193+
err = {
194+
"status": "error",
195+
"error": {
196+
"message": "Error processing message",
197+
"details": details,
198+
"type": err_type}}
185199
try:
186-
self.rabbitmq_manager.send_result(method.routing_key.split(".")[0], err)
200+
self.rabbitmq_manager.send_result(
201+
method.routing_key.split(".")[0], err)
187202
finally:
188203
ch.basic_nack(method.delivery_tag, requeue=False)
189204

@@ -198,7 +213,8 @@ def setUp(self): # noqa: D401
198213
self.sim_file = self.temp_dir / "sim.yaml"
199214

200215
# Credentials obtained via autouse fixture
201-
creds: Dict[str, Any] = cast(Dict[str, Any], getattr(self, "dummy_credentials", {})).get("rabbitmq", {})
216+
creds: Dict[str, Any] = cast(Dict[str, Any], getattr(
217+
self, "dummy_credentials", {})).get("rabbitmq", {})
202218

203219
cfg = {
204220
"rabbitmq": {
@@ -233,23 +249,30 @@ def tearDown(self): # noqa: D401
233249

234250
@patch("resources.use_matlab_agent.pika.BlockingConnection")
235251
def test_init(self, _): # noqa: ANN001
236-
handler = MockMessageHandler("id", self.manager, {"simulation": {"path": "/a"}})
252+
handler = MockMessageHandler(
253+
"id", self.manager, {
254+
"simulation": {
255+
"path": "/a"}})
237256
self.assertEqual(handler.path_simulation, "/a")
238257

239258
@patch("resources.use_matlab_agent.pika.BlockingConnection")
240259
def test_invalid_yaml(self, _): # noqa: ANN001
241260
handler = MockMessageHandler("id", self.manager, {})
242261
method = Mock(routing_key="dt.m", delivery_tag="t")
243262
handler.handle_message(self.channel, method, Mock(), b":::bad:::yaml")
244-
self.assertEqual(self.manager.sent_results[0]["response"]["error"]["type"], "execution_error")
263+
self.assertEqual(
264+
self.manager.sent_results[0]["response"]["error"]["type"],
265+
"execution_error")
245266

246267
@patch("resources.use_matlab_agent.pika.BlockingConnection")
247268
def test_missing_fields(self, _): # noqa: ANN001
248269
handler = MockMessageHandler("id", self.manager, {})
249270
body = yaml.dump({"simulation": {"request_id": "x"}}).encode()
250271
method = Mock(routing_key="dt.m", delivery_tag="t")
251272
handler.handle_message(self.channel, method, Mock(), body)
252-
self.assertEqual(self.manager.sent_results[0]["response"]["error"]["type"], "validation_error")
273+
self.assertEqual(
274+
self.manager.sent_results[0]["response"]["error"]["type"],
275+
"validation_error")
253276

254277
def test_dummy_result_callback(self): # noqa: D401
255278
result = {"status": "completed"}

agents/matlab/matlab_agent/test/unit/test_matlab_simulator.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
"""Unit tests for the MATLAB simulator module."""
22

33
import pytest
4-
from unittest.mock import Mock, patch, MagicMock, PropertyMock
4+
from pytest import approx
5+
from unittest.mock import Mock, patch, MagicMock
56
from pathlib import Path
67

7-
import matlab.engine
8-
98
from src.core.matlab_simulator import MatlabSimulator, MatlabSimulationError
109

1110

@@ -98,7 +97,11 @@ def test_run_success(self, running_simulator):
9897
{'x_i': 10, 'y_i': 10, 'z_i': 10, 'v_x': 1, 'v_y': 1, 'v_z': 1, 't': 10},
9998
['x_f', 'y_f', 'z_f']
10099
)
101-
assert result == {'x_f': 20.0, 'y_f': 30.0, 'z_f': 40.0}
100+
assert result == {
101+
'x_f': approx(20.0, rel=1e-9, abs=1e-9),
102+
'y_f': approx(30.0, rel=1e-9, abs=1e-9),
103+
'z_f': approx(40.0, rel=1e-9, abs=1e-9)
104+
}
102105
running_simulator.eng.feval.assert_called_with(
103106
'simulation_batch', 10.0, 10.0, 10.0, 1.0, 1.0, 1.0, 10.0, nargout=3)
104107

@@ -109,7 +112,10 @@ def test_run_with_named_args(self, running_simulator):
109112
{'initial_pos': 10, 'velocity': 5},
110113
['final_pos', 'final_vel']
111114
)
112-
assert result == {'final_pos': 20.0, 'final_vel': 30.0}
115+
assert result == {
116+
'final_pos': approx(20.0, rel=1e-9, abs=1e-9),
117+
'final_vel': approx(30.0, rel=1e-9, abs=1e-9)
118+
}
113119
running_simulator.eng.feval.assert_called_with(
114120
'simulation_batch', 10.0, 5.0, nargout=2)
115121

@@ -195,7 +201,7 @@ def test_get_metadata_with_start_time(self, running_simulator):
195201
metadata = running_simulator.get_metadata()
196202

197203
assert 'execution_time' in metadata
198-
assert metadata['execution_time'] == 5.0
204+
assert metadata['execution_time'] == approx(5.0, rel=1e-9, abs=1e-9)
199205

200206
def test_get_metadata_without_start_time(self, simulator):
201207
"""Test getting metadata without start time."""
@@ -227,7 +233,7 @@ def test_get_metadata_with_additional_info(self, running_simulator):
227233
metadata = running_simulator.get_metadata()
228234

229235
assert 'execution_time' in metadata
230-
assert metadata['execution_time'] == 10.0
236+
assert metadata['execution_time'] == approx(10.0, rel=1e-9, abs=1e-9)
231237
assert 'memory_usage' in metadata
232238
assert 'matlab_version' in metadata
233239
assert metadata['matlab_version'] == "R2021b"

agents/matlab/matlab_agent/test/unit/test_streaming.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import subprocess
1212

1313
import pytest
14+
from pytest import approx
1415

1516
from src.core.streaming import (
1617
MatlabStreamingController,
@@ -329,8 +330,8 @@ def kill(self):
329330

330331
# Verify values make sense
331332
assert metadata['execution_time'] >= 2.0 # At least 2 seconds
332-
assert metadata['matlab_memory'] == 1.0 # 1 MB
333-
assert metadata['matlab_cpu'] == 5.0 # 5%
333+
assert metadata['matlab_memory'] == approx(1.0, rel=1e-9, abs=1e-9) # 1 MB
334+
assert metadata['matlab_cpu'] == approx(5.0, rel=1e-9, abs=1e-9) # 5%
334335

335336

336337
def test_handle_streaming_error_bad_request(

0 commit comments

Comments
 (0)