refactor: ZMQ context and proxy
Use ZMQ's global context instance and setup an XPUB/XSUB proxy intermediary to allow for easier multi-pubs. close: N25B-217
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from control_backend.api.v1.endpoints import command
|
||||
from control_backend.schemas.ri_message import SpeechCommand
|
||||
@@ -15,7 +16,6 @@ def app():
|
||||
"""
|
||||
app = FastAPI()
|
||||
app.include_router(command.router)
|
||||
app.state.internal_comm_socket = MagicMock() # mock ZMQ socket
|
||||
return app
|
||||
|
||||
|
||||
@@ -25,12 +25,42 @@ def client(app):
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_receive_command_endpoint(client, app):
|
||||
@pytest.mark.asyncio
|
||||
@patch("control_backend.api.endpoints.command.Context.instance")
|
||||
async def test_receive_command_success(mock_context_instance, async_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()
|
||||
mock_context_instance.return_value.socket.return_value = mock_pub_socket
|
||||
|
||||
command_data = {"command": "test_command", "text": "This is a test"}
|
||||
speech_command = SpeechCommand(**command_data)
|
||||
|
||||
# Act
|
||||
response = await async_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_context_instance.return_value.socket.assert_called_once_with(1) # zmq.PUB is 1
|
||||
mock_pub_socket.connect.assert_called_once()
|
||||
mock_pub_socket.send_multipart.assert_awaited_once_with(
|
||||
[b"command", speech_command.model_dump_json().encode()]
|
||||
)
|
||||
|
||||
|
||||
def test_receive_command_endpoint(client, app, mocker):
|
||||
"""
|
||||
Test that a POST to /command sends the right multipart message
|
||||
and returns a 202 with the expected JSON body.
|
||||
"""
|
||||
mock_socket = app.state.internal_comm_socket
|
||||
mock_socket = mocker.patch.object()
|
||||
|
||||
# Prepare test payload that matches SpeechCommand
|
||||
payload = {"endpoint": "actuate/speech", "data": "yooo"}
|
||||
|
||||
Reference in New Issue
Block a user