Merge branch 'dev' of https://git.science.uu.nl/ics/sp/2025/n25b/pepperplus-cb into feat/recieve-programs-ui
This commit is contained in:
@@ -25,13 +25,9 @@ async def test_setup_bind(zmq_context, mocker):
|
||||
|
||||
await agent.setup()
|
||||
|
||||
# Ensure PUB socket bound
|
||||
fake_socket.bind.assert_any_call("tcp://localhost:5555")
|
||||
# Ensure SUB socket connected to internal address and subscribed
|
||||
fake_socket.connect.assert_any_call("tcp://internal:1234")
|
||||
fake_socket.setsockopt.assert_any_call(zmq.SUBSCRIBE, b"command")
|
||||
|
||||
# Ensure behaviour attached
|
||||
assert any(isinstance(b, agent.SendCommandsBehaviour) for b in agent.behaviours)
|
||||
|
||||
|
||||
@@ -46,7 +42,6 @@ async def test_setup_connect(zmq_context, mocker):
|
||||
|
||||
await agent.setup()
|
||||
|
||||
# Ensure PUB socket connected
|
||||
fake_socket.connect.assert_any_call("tcp://localhost:5555")
|
||||
|
||||
|
||||
@@ -78,7 +73,7 @@ async def test_send_commands_behaviour_valid_message():
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_commands_behaviour_invalid_message(caplog):
|
||||
async def test_send_commands_behaviour_invalid_message():
|
||||
"""Test behaviour with invalid JSON message triggers error logging"""
|
||||
fake_socket = AsyncMock()
|
||||
fake_socket.recv_multipart = AsyncMock(return_value=(b"command", b"{invalid_json}"))
|
||||
@@ -91,9 +86,7 @@ async def test_send_commands_behaviour_invalid_message(caplog):
|
||||
behaviour = agent.SendCommandsBehaviour()
|
||||
behaviour.agent = agent
|
||||
|
||||
with caplog.at_level("ERROR"):
|
||||
await behaviour.run()
|
||||
await behaviour.run()
|
||||
|
||||
fake_socket.recv_multipart.assert_awaited()
|
||||
fake_socket.send_json.assert_not_awaited()
|
||||
assert "Error processing message" in caplog.text
|
||||
|
||||
@@ -100,6 +100,7 @@ async def test_setup_creates_socket_and_negotiate_1(zmq_context):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = fake_json_correct_negototiate_1()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Mock RICommandAgent agent startup
|
||||
with patch(
|
||||
@@ -110,13 +111,16 @@ async def test_setup_creates_socket_and_negotiate_1(zmq_context):
|
||||
|
||||
# --- Act ---
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=False
|
||||
"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.send_json.assert_any_call({"endpoint": "negotiate/ports", "data": {}})
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
fake_agent_instance.start.assert_awaited()
|
||||
MockCommandAgent.assert_called_once_with(
|
||||
@@ -138,6 +142,7 @@ async def test_setup_creates_socket_and_negotiate_2(zmq_context):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = fake_json_correct_negototiate_2()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Mock RICommandAgent agent startup
|
||||
with patch(
|
||||
@@ -148,13 +153,16 @@ async def test_setup_creates_socket_and_negotiate_2(zmq_context):
|
||||
|
||||
# --- Act ---
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=False
|
||||
"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.send_json.assert_any_call({"endpoint": "negotiate/ports", "data": {}})
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
fake_agent_instance.start.assert_awaited()
|
||||
MockCommandAgent.assert_called_once_with(
|
||||
@@ -168,7 +176,7 @@ async def test_setup_creates_socket_and_negotiate_2(zmq_context):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_setup_creates_socket_and_negotiate_3(zmq_context, caplog):
|
||||
async def test_setup_creates_socket_and_negotiate_3(zmq_context):
|
||||
"""
|
||||
Test the functionality of setup with incorrect negotiation message
|
||||
"""
|
||||
@@ -176,6 +184,7 @@ async def test_setup_creates_socket_and_negotiate_3(zmq_context, caplog):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = fake_json_wrong_negototiate_1()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Mock RICommandAgent agent startup
|
||||
|
||||
@@ -186,13 +195,15 @@ async def test_setup_creates_socket_and_negotiate_3(zmq_context, caplog):
|
||||
) as MockCommandAgent:
|
||||
fake_agent_instance = MockCommandAgent.return_value
|
||||
fake_agent_instance.start = AsyncMock()
|
||||
|
||||
# --- Act ---
|
||||
with caplog.at_level("ERROR"):
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=False
|
||||
)
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
agent = RICommunicationAgent(
|
||||
"test@server",
|
||||
"password",
|
||||
address="tcp://localhost:5555",
|
||||
bind=False,
|
||||
)
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
# --- Assert ---
|
||||
fake_socket.connect.assert_any_call("tcp://localhost:5555")
|
||||
@@ -200,7 +211,6 @@ async def test_setup_creates_socket_and_negotiate_3(zmq_context, caplog):
|
||||
|
||||
# Since it failed, there should not be any command agent.
|
||||
fake_agent_instance.start.assert_not_awaited()
|
||||
assert "Failed to set up RICommunicationAgent" in caplog.text
|
||||
|
||||
# Ensure the agent did not attach a ListenBehaviour
|
||||
assert not any(isinstance(b, agent.ListenBehaviour) for b in agent.behaviours)
|
||||
@@ -215,6 +225,7 @@ async def test_setup_creates_socket_and_negotiate_4(zmq_context):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = fake_json_correct_negototiate_3()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Mock RICommandAgent agent startup
|
||||
with patch(
|
||||
@@ -222,16 +233,18 @@ async def test_setup_creates_socket_and_negotiate_4(zmq_context):
|
||||
) as MockCommandAgent:
|
||||
fake_agent_instance = MockCommandAgent.return_value
|
||||
fake_agent_instance.start = AsyncMock()
|
||||
|
||||
# --- Act ---
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=True
|
||||
"test@server",
|
||||
"password",
|
||||
address="tcp://localhost:5555",
|
||||
bind=True,
|
||||
)
|
||||
await agent.setup()
|
||||
|
||||
# --- Assert ---
|
||||
fake_socket.bind.assert_any_call("tcp://localhost:5555")
|
||||
fake_socket.send_json.assert_any_call({"endpoint": "negotiate/ports", "data": None})
|
||||
fake_socket.send_json.assert_any_call({"endpoint": "negotiate/ports", "data": {}})
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
fake_agent_instance.start.assert_awaited()
|
||||
MockCommandAgent.assert_called_once_with(
|
||||
@@ -253,6 +266,7 @@ async def test_setup_creates_socket_and_negotiate_5(zmq_context):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = fake_json_correct_negototiate_4()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Mock RICommandAgent agent startup
|
||||
with patch(
|
||||
@@ -260,16 +274,18 @@ async def test_setup_creates_socket_and_negotiate_5(zmq_context):
|
||||
) 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
|
||||
"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.send_json.assert_any_call({"endpoint": "negotiate/ports", "data": {}})
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
fake_agent_instance.start.assert_awaited()
|
||||
MockCommandAgent.assert_called_once_with(
|
||||
@@ -291,6 +307,7 @@ async def test_setup_creates_socket_and_negotiate_6(zmq_context):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = fake_json_correct_negototiate_5()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Mock RICommandAgent agent startup
|
||||
with patch(
|
||||
@@ -298,16 +315,18 @@ async def test_setup_creates_socket_and_negotiate_6(zmq_context):
|
||||
) 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
|
||||
"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.send_json.assert_any_call({"endpoint": "negotiate/ports", "data": {}})
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
fake_agent_instance.start.assert_awaited()
|
||||
MockCommandAgent.assert_called_once_with(
|
||||
@@ -321,7 +340,7 @@ async def test_setup_creates_socket_and_negotiate_6(zmq_context):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_setup_creates_socket_and_negotiate_7(zmq_context, caplog):
|
||||
async def test_setup_creates_socket_and_negotiate_7(zmq_context):
|
||||
"""
|
||||
Test the functionality of setup with incorrect id
|
||||
"""
|
||||
@@ -329,6 +348,7 @@ async def test_setup_creates_socket_and_negotiate_7(zmq_context, caplog):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = fake_json_invalid_id_negototiate()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Mock RICommandAgent agent startup
|
||||
|
||||
@@ -341,11 +361,14 @@ async def test_setup_creates_socket_and_negotiate_7(zmq_context, caplog):
|
||||
fake_agent_instance.start = AsyncMock()
|
||||
|
||||
# --- Act ---
|
||||
with caplog.at_level("WARNING"):
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=False
|
||||
)
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
agent = RICommunicationAgent(
|
||||
"test@server",
|
||||
"password",
|
||||
address="tcp://localhost:5555",
|
||||
bind=False,
|
||||
)
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
# --- Assert ---
|
||||
fake_socket.connect.assert_any_call("tcp://localhost:5555")
|
||||
@@ -353,11 +376,10 @@ async def test_setup_creates_socket_and_negotiate_7(zmq_context, caplog):
|
||||
|
||||
# Since it failed, there should not be any command agent.
|
||||
fake_agent_instance.start.assert_not_awaited()
|
||||
assert "Unhandled negotiation id:" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_setup_creates_socket_and_negotiate_timeout(zmq_context, caplog):
|
||||
async def test_setup_creates_socket_and_negotiate_timeout(zmq_context):
|
||||
"""
|
||||
Test the functionality of setup with incorrect negotiation message
|
||||
"""
|
||||
@@ -365,6 +387,7 @@ async def test_setup_creates_socket_and_negotiate_timeout(zmq_context, caplog):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = AsyncMock(side_effect=asyncio.TimeoutError)
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
with patch(
|
||||
"control_backend.agents.ri_communication_agent.RICommandAgent", autospec=True
|
||||
@@ -373,47 +396,47 @@ async def test_setup_creates_socket_and_negotiate_timeout(zmq_context, caplog):
|
||||
fake_agent_instance.start = AsyncMock()
|
||||
|
||||
# --- Act ---
|
||||
with caplog.at_level("WARNING"):
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=False
|
||||
)
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
agent = RICommunicationAgent(
|
||||
"test@server",
|
||||
"password",
|
||||
address="tcp://localhost:5555",
|
||||
bind=False,
|
||||
)
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
# --- Assert ---
|
||||
fake_socket.connect.assert_any_call("tcp://localhost:5555")
|
||||
|
||||
# Since it failed, there should not be any command agent.
|
||||
fake_agent_instance.start.assert_not_awaited()
|
||||
assert "No connection established in 20 seconds" in caplog.text
|
||||
|
||||
# Ensure the agent did not attach a ListenBehaviour
|
||||
assert not any(isinstance(b, agent.ListenBehaviour) for b in agent.behaviours)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listen_behaviour_ping_correct(caplog):
|
||||
async def test_listen_behaviour_ping_correct():
|
||||
fake_socket = AsyncMock()
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.recv_json = AsyncMock(return_value={"endpoint": "ping", "data": {}})
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# TODO: Integration test between actual server and password needed for spade agents
|
||||
agent = RICommunicationAgent("test@server", "password")
|
||||
agent.req_socket = fake_socket
|
||||
agent._req_socket = fake_socket
|
||||
agent.connected = True
|
||||
|
||||
behaviour = agent.ListenBehaviour()
|
||||
agent.add_behaviour(behaviour)
|
||||
|
||||
# Run once (CyclicBehaviour normally loops)
|
||||
with caplog.at_level("DEBUG"):
|
||||
await behaviour.run()
|
||||
await behaviour.run()
|
||||
|
||||
fake_socket.send_json.assert_awaited()
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
assert "Received message" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listen_behaviour_ping_wrong_endpoint(caplog):
|
||||
async def test_listen_behaviour_ping_wrong_endpoint():
|
||||
"""
|
||||
Test if our listen behaviour can work with wrong messages (wrong endpoint)
|
||||
"""
|
||||
@@ -430,48 +453,51 @@ async def test_listen_behaviour_ping_wrong_endpoint(caplog):
|
||||
],
|
||||
}
|
||||
)
|
||||
fake_pub_socket = AsyncMock()
|
||||
|
||||
agent = RICommunicationAgent("test@server", "password")
|
||||
agent.req_socket = fake_socket
|
||||
agent = RICommunicationAgent("test@server", "password", fake_pub_socket)
|
||||
agent._req_socket = fake_socket
|
||||
agent.connected = True
|
||||
|
||||
behaviour = agent.ListenBehaviour()
|
||||
agent.add_behaviour(behaviour)
|
||||
|
||||
# Run once (CyclicBehaviour normally loops)
|
||||
with caplog.at_level("INFO"):
|
||||
await behaviour.run()
|
||||
|
||||
assert "Received message with topic different than ping, while ping expected." in caplog.text
|
||||
await behaviour.run()
|
||||
|
||||
fake_socket.send_json.assert_awaited()
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listen_behaviour_timeout(zmq_context, caplog):
|
||||
async def test_listen_behaviour_timeout(zmq_context):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
# recv_json will never resolve, simulate timeout
|
||||
fake_socket.recv_json = AsyncMock(side_effect=asyncio.TimeoutError)
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
agent = RICommunicationAgent("test@server", "password")
|
||||
agent.req_socket = fake_socket
|
||||
agent._req_socket = fake_socket
|
||||
agent.connected = True
|
||||
|
||||
behaviour = agent.ListenBehaviour()
|
||||
agent.add_behaviour(behaviour)
|
||||
|
||||
with caplog.at_level("INFO"):
|
||||
await behaviour.run()
|
||||
|
||||
assert "No ping retrieved in 3 seconds" in caplog.text
|
||||
await behaviour.run()
|
||||
assert not any(isinstance(b, agent.ListenBehaviour) for b in agent.behaviours)
|
||||
assert not agent.connected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listen_behaviour_ping_no_endpoint(caplog):
|
||||
async def test_listen_behaviour_ping_no_endpoint():
|
||||
"""
|
||||
Test if our listen behaviour can work with wrong messages (wrong endpoint)
|
||||
"""
|
||||
fake_socket = AsyncMock()
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# This is a message without endpoint >:(
|
||||
fake_socket.recv_json = AsyncMock(
|
||||
@@ -481,43 +507,45 @@ async def test_listen_behaviour_ping_no_endpoint(caplog):
|
||||
)
|
||||
|
||||
agent = RICommunicationAgent("test@server", "password")
|
||||
agent.req_socket = fake_socket
|
||||
agent._req_socket = fake_socket
|
||||
agent.connected = True
|
||||
|
||||
behaviour = agent.ListenBehaviour()
|
||||
agent.add_behaviour(behaviour)
|
||||
|
||||
# Run once (CyclicBehaviour normally loops)
|
||||
with caplog.at_level("ERROR"):
|
||||
await behaviour.run()
|
||||
await behaviour.run()
|
||||
|
||||
assert "No received endpoint in message, excepted ping endpoint." in caplog.text
|
||||
fake_socket.send_json.assert_awaited()
|
||||
fake_socket.recv_json.assert_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_setup_unexpected_exception(zmq_context, caplog):
|
||||
async def test_setup_unexpected_exception(zmq_context):
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
# Simulate unexpected exception during recv_json()
|
||||
fake_socket.recv_json = AsyncMock(side_effect=Exception("boom!"))
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=False
|
||||
"test@server",
|
||||
"password",
|
||||
address="tcp://localhost:5555",
|
||||
bind=False,
|
||||
)
|
||||
|
||||
with caplog.at_level("ERROR"):
|
||||
await agent.setup(max_retries=1)
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
# Ensure that the error was logged
|
||||
assert "Unexpected error during negotiation: boom!" in caplog.text
|
||||
assert not any(isinstance(b, agent.ListenBehaviour) for b in agent.behaviours)
|
||||
assert not agent.connected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_setup_unpacking_exception(zmq_context, caplog):
|
||||
async def test_setup_unpacking_exception(zmq_context):
|
||||
# --- Arrange ---
|
||||
fake_socket = zmq_context.return_value.socket.return_value
|
||||
fake_socket.send_json = AsyncMock()
|
||||
fake_socket.send_multipart = AsyncMock()
|
||||
|
||||
# Make recv_json return malformed negotiation data to trigger unpacking exception
|
||||
malformed_data = {
|
||||
@@ -534,15 +562,15 @@ async def test_setup_unpacking_exception(zmq_context, caplog):
|
||||
fake_agent_instance.start = AsyncMock()
|
||||
|
||||
agent = RICommunicationAgent(
|
||||
"test@server", "password", address="tcp://localhost:5555", bind=False
|
||||
"test@server",
|
||||
"password",
|
||||
address="tcp://localhost:5555",
|
||||
bind=False,
|
||||
)
|
||||
|
||||
# --- Act & Assert ---
|
||||
with caplog.at_level("ERROR"):
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
# Ensure the unpacking exception was logged
|
||||
assert "Error unpacking negotiation data" in caplog.text
|
||||
await agent.setup(max_retries=1)
|
||||
|
||||
# Ensure no command agent was started
|
||||
fake_agent_instance.start.assert_not_awaited()
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from control_backend.api.v1.endpoints import command
|
||||
from control_backend.schemas.ri_message import SpeechCommand
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
"""
|
||||
Creates a FastAPI test app and attaches the router under test.
|
||||
Also sets up a mock internal_comm_socket.
|
||||
"""
|
||||
app = FastAPI()
|
||||
app.include_router(command.router)
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
"""Create a test client for the app."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_receive_command_success(client):
|
||||
"""
|
||||
Test for successful reception of a command. Ensures the status code is 202 and the response body
|
||||
is correct. It also verifies that the ZeroMQ socket's send_multipart method is called with the
|
||||
expected data.
|
||||
"""
|
||||
# Arrange
|
||||
mock_pub_socket = AsyncMock()
|
||||
client.app.state.endpoints_pub_socket = mock_pub_socket
|
||||
|
||||
command_data = {"endpoint": "actuate/speech", "data": "This is a test"}
|
||||
speech_command = SpeechCommand(**command_data)
|
||||
|
||||
# Act
|
||||
response = client.post("/command", json=command_data)
|
||||
|
||||
# Assert
|
||||
assert response.status_code == 202
|
||||
assert response.json() == {"status": "Command received"}
|
||||
|
||||
# Verify that the ZMQ socket was used correctly
|
||||
mock_pub_socket.send_multipart.assert_awaited_once_with(
|
||||
[b"command", speech_command.model_dump_json().encode()]
|
||||
)
|
||||
|
||||
|
||||
def test_receive_command_invalid_payload(client):
|
||||
"""
|
||||
Test invalid data handling (schema validation).
|
||||
"""
|
||||
# Missing required field(s)
|
||||
bad_payload = {"invalid": "data"}
|
||||
response = client.post("/command", json=bad_payload)
|
||||
assert response.status_code == 422 # validation error
|
||||
156
test/integration/api/endpoints/test_robot_endpoint.py
Normal file
156
test/integration/api/endpoints/test_robot_endpoint.py
Normal file
@@ -0,0 +1,156 @@
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from control_backend.api.v1.endpoints import robot
|
||||
from control_backend.schemas.ri_message import SpeechCommand
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
"""
|
||||
Creates a FastAPI test app and attaches the router under test.
|
||||
Also sets up a mock internal_comm_socket.
|
||||
"""
|
||||
app = FastAPI()
|
||||
app.include_router(robot.router)
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
"""Create a test client for the app."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_receive_command_success(client):
|
||||
"""
|
||||
Test for successful reception of a command. Ensures the status code is 202 and the response body
|
||||
is correct. It also verifies that the ZeroMQ socket's send_multipart method is called with the
|
||||
expected data.
|
||||
"""
|
||||
# Arrange
|
||||
mock_pub_socket = AsyncMock()
|
||||
client.app.state.endpoints_pub_socket = mock_pub_socket
|
||||
|
||||
command_data = {"endpoint": "actuate/speech", "data": "This is a test"}
|
||||
speech_command = SpeechCommand(**command_data)
|
||||
|
||||
# Act
|
||||
response = client.post("/command", json=command_data)
|
||||
|
||||
# Assert
|
||||
assert response.status_code == 202
|
||||
assert response.json() == {"status": "Command received"}
|
||||
|
||||
# Verify that the ZMQ socket was used correctly
|
||||
mock_pub_socket.send_multipart.assert_awaited_once_with(
|
||||
[b"command", speech_command.model_dump_json().encode()]
|
||||
)
|
||||
|
||||
|
||||
def test_receive_command_invalid_payload(client):
|
||||
"""
|
||||
Test invalid data handling (schema validation).
|
||||
"""
|
||||
# Missing required field(s)
|
||||
bad_payload = {"invalid": "data"}
|
||||
response = client.post("/command", json=bad_payload)
|
||||
assert response.status_code == 422 # validation error
|
||||
|
||||
|
||||
def test_ping_check_returns_none(client):
|
||||
"""Ensure /ping_check returns 200 and None (currently unimplemented)."""
|
||||
response = client.get("/ping_check")
|
||||
assert response.status_code == 200
|
||||
assert response.json() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ping_stream_yields_ping_event(monkeypatch):
|
||||
"""Test that ping_stream yields a proper SSE message when a ping is received."""
|
||||
mock_sub_socket = AsyncMock()
|
||||
mock_sub_socket.connect = MagicMock()
|
||||
mock_sub_socket.setsockopt = MagicMock()
|
||||
mock_sub_socket.recv_multipart = AsyncMock(return_value=[b"ping", b"true"])
|
||||
|
||||
mock_context = MagicMock()
|
||||
mock_context.socket.return_value = mock_sub_socket
|
||||
monkeypatch.setattr(robot.Context, "instance", lambda: mock_context)
|
||||
|
||||
mock_request = AsyncMock()
|
||||
mock_request.is_disconnected = AsyncMock(side_effect=[False, True])
|
||||
|
||||
response = await robot.ping_stream(mock_request)
|
||||
generator = aiter(response.body_iterator)
|
||||
|
||||
event = await anext(generator)
|
||||
event_text = event.decode() if isinstance(event, bytes) else str(event)
|
||||
assert event_text.strip() == "data: true"
|
||||
|
||||
with pytest.raises(StopAsyncIteration):
|
||||
await anext(generator)
|
||||
|
||||
mock_sub_socket.connect.assert_called_once()
|
||||
mock_sub_socket.setsockopt.assert_called_once_with(robot.zmq.SUBSCRIBE, b"ping")
|
||||
mock_sub_socket.recv_multipart.assert_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ping_stream_handles_timeout(monkeypatch):
|
||||
"""Test that ping_stream continues looping on TimeoutError."""
|
||||
mock_sub_socket = AsyncMock()
|
||||
mock_sub_socket.connect = MagicMock()
|
||||
mock_sub_socket.setsockopt = MagicMock()
|
||||
mock_sub_socket.recv_multipart.side_effect = TimeoutError()
|
||||
|
||||
mock_context = MagicMock()
|
||||
mock_context.socket.return_value = mock_sub_socket
|
||||
monkeypatch.setattr(robot.Context, "instance", lambda: mock_context)
|
||||
|
||||
mock_request = AsyncMock()
|
||||
mock_request.is_disconnected = AsyncMock(return_value=True)
|
||||
|
||||
response = await robot.ping_stream(mock_request)
|
||||
generator = aiter(response.body_iterator)
|
||||
|
||||
with pytest.raises(StopAsyncIteration):
|
||||
await anext(generator)
|
||||
|
||||
mock_sub_socket.connect.assert_called_once()
|
||||
mock_sub_socket.setsockopt.assert_called_once_with(robot.zmq.SUBSCRIBE, b"ping")
|
||||
mock_sub_socket.recv_multipart.assert_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ping_stream_yields_json_values(monkeypatch):
|
||||
"""Ensure ping_stream correctly parses and yields JSON body values."""
|
||||
mock_sub_socket = AsyncMock()
|
||||
mock_sub_socket.connect = MagicMock()
|
||||
mock_sub_socket.setsockopt = MagicMock()
|
||||
mock_sub_socket.recv_multipart = AsyncMock(
|
||||
return_value=[b"ping", json.dumps({"connected": True}).encode()]
|
||||
)
|
||||
|
||||
mock_context = MagicMock()
|
||||
mock_context.socket.return_value = mock_sub_socket
|
||||
monkeypatch.setattr(robot.Context, "instance", lambda: mock_context)
|
||||
|
||||
mock_request = AsyncMock()
|
||||
mock_request.is_disconnected = AsyncMock(side_effect=[False, True])
|
||||
|
||||
response = await robot.ping_stream(mock_request)
|
||||
generator = aiter(response.body_iterator)
|
||||
|
||||
event = await anext(generator)
|
||||
event_text = event.decode() if isinstance(event, bytes) else str(event)
|
||||
|
||||
assert "connected" in event_text
|
||||
assert "true" in event_text
|
||||
|
||||
mock_sub_socket.connect.assert_called_once()
|
||||
mock_sub_socket.setsockopt.assert_called_once_with(robot.zmq.SUBSCRIBE, b"ping")
|
||||
mock_sub_socket.recv_multipart.assert_awaited()
|
||||
Reference in New Issue
Block a user