46 lines
1.2 KiB
Python
46 lines
1.2 KiB
Python
import json
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
from control_backend.api.v1.endpoints import message
|
|
|
|
|
|
@pytest.fixture
|
|
def client():
|
|
"""FastAPI TestClient for the message router."""
|
|
from fastapi import FastAPI
|
|
|
|
app = FastAPI()
|
|
app.include_router(message.router)
|
|
return TestClient(app)
|
|
|
|
|
|
def test_receive_message_post(client, monkeypatch):
|
|
"""Test POST /message endpoint sends message to pub socket."""
|
|
|
|
# Dummy pub socket to capture sent messages
|
|
class DummyPubSocket:
|
|
def __init__(self):
|
|
self.sent = []
|
|
|
|
async def send_multipart(self, msg):
|
|
self.sent.append(msg)
|
|
|
|
dummy_socket = DummyPubSocket()
|
|
|
|
# Patch app.state.endpoints_pub_socket
|
|
client.app.state.endpoints_pub_socket = dummy_socket
|
|
|
|
data = {"message": "Hello world"}
|
|
response = client.post("/message", json=data)
|
|
|
|
assert response.status_code == 202
|
|
assert response.json() == {"status": "Message received"}
|
|
|
|
# Ensure the message was sent via pub_socket
|
|
assert len(dummy_socket.sent) == 1
|
|
topic, body = dummy_socket.sent[0]
|
|
parsed = json.loads(body.decode("utf-8"))
|
|
assert parsed["message"] == "Hello world"
|