from unittest.mock import AsyncMock 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