fix: unit test refactoring with conftest and more mocks

ref: N25B-205
This commit is contained in:
Björn Otgaar
2025-10-28 13:26:33 +01:00
parent c75f5de97c
commit 423309e063
7 changed files with 142 additions and 27 deletions

View File

@@ -81,47 +81,45 @@ def fake_json_invalid_id_negototiate():
}
)
def mock_command_agent():
"""Fixture to create a mock BDIAgent."""
agent = MagicMock()
agent.bdi = MagicMock()
agent.jid = "ri_command_agent@test"
return agent
@pytest.mark.asyncio
async def test_setup_creates_socket_and_negotiate_1(monkeypatch):
"""
Test the setup of the communication agent
"""
# --- Arrange ---
fake_socket = MagicMock()
fake_socket.send_json = AsyncMock()
fake_socket.recv_json = fake_json_correct_negototiate_1()
fake_socket.recv_json = AsyncMock(return_value={
"endpoint": "negotiate/ports",
"data": [
{"id": "main", "port": 5555, "bind": False},
{"id": "actuation", "port": 5556, "bind": True},
],
})
# Mock context.socket to return our fake socket
monkeypatch.setattr(
"control_backend.agents.ri_communication_agent.context.socket", lambda _: fake_socket
)
# Mock RICommandAgent agent startup
with patch(
"control_backend.agents.ri_communication_agent.RICommandAgent", autospec=True
) as MockCommandAgent:
with patch("control_backend.agents.ri_communication_agent.RICommandAgent") as MockCommandAgent:
fake_agent_instance = MockCommandAgent.return_value
fake_agent_instance.start = AsyncMock()
# --- Act ---
agent = RICommunicationAgent(
"test@server", "password", address="tcp://localhost:5555", bind=False
)
agent = RICommunicationAgent("test@server", "password", address="tcp://localhost:5555", bind=False)
await agent.setup()
# --- Assert ---
fake_socket.connect.assert_any_call("tcp://localhost:5555")
fake_socket.send_json.assert_any_call({"endpoint": "negotiate/ports", "data": None})
fake_socket.recv_json.assert_awaited()
fake_agent_instance.start.assert_awaited()
MockCommandAgent.assert_called_once_with(
ANY, # Server Name
ANY, # Server Password
address="tcp://*:5556", # derived from the 'port' value in negotiation
bind=True,
ANY, ANY, address="tcp://*:5556", bind=True
)
# Ensure the agent attached a ListenBehaviour
assert any(isinstance(b, agent.ListenBehaviour) for b in agent.behaviours)
@@ -141,6 +139,9 @@ async def test_setup_creates_socket_and_negotiate_2(monkeypatch):
)
# Mock RICommandAgent agent startup
patch("control_backend.agents.ri_communication_agent.RICommandAgent", mock_command_agent)
with patch(
"control_backend.agents.ri_communication_agent.RICommandAgent", autospec=True
) as MockCommandAgent:
@@ -588,4 +589,4 @@ async def test_setup_unpacking_exception(monkeypatch, caplog):
fake_agent_instance.start.assert_not_awaited()
# Ensure no behaviour was attached
assert not any(isinstance(b, agent.ListenBehaviour) for b in agent.behaviours)
assert not any(isinstance(b, agent.ListenBehaviour) for b in agent.behaviours)