"""Tests for the Redis broker.""" import pytest import json from unittest.mock import AsyncMock, patch @pytest.mark.asyncio async def test_broker_publish(): """Test that publish calls xadd on the redis connection.""" with patch("redis.asyncio.from_url") as mock_from_url: mock_redis = AsyncMock() mock_from_url.return_value = mock_redis from shared.broker import RedisBroker broker = RedisBroker("redis://localhost:6379") data = {"type": "CANDLE", "symbol": "BTCUSDT"} await broker.publish("candles", data) mock_redis.xadd.assert_called_once() call_args = mock_redis.xadd.call_args assert call_args[0][0] == "candles" payload = call_args[0][1] assert "payload" in payload parsed = json.loads(payload["payload"]) assert parsed["type"] == "CANDLE" @pytest.mark.asyncio async def test_broker_subscribe_returns_messages(): """Test that read parses xread response correctly.""" with patch("redis.asyncio.from_url") as mock_from_url: mock_redis = AsyncMock() mock_from_url.return_value = mock_redis payload_data = {"type": "CANDLE", "symbol": "ETHUSDT"} mock_redis.xread.return_value = [ [ b"candles", [ (b"1234567890-0", {b"payload": json.dumps(payload_data).encode()}), ], ] ] from shared.broker import RedisBroker broker = RedisBroker("redis://localhost:6379") messages = await broker.read("candles", last_id="$") mock_redis.xread.assert_called_once() assert len(messages) == 1 assert messages[0]["type"] == "CANDLE" assert messages[0]["symbol"] == "ETHUSDT" @pytest.mark.asyncio async def test_broker_close(): """Test that close calls aclose on the redis connection.""" with patch("redis.asyncio.from_url") as mock_from_url: mock_redis = AsyncMock() mock_from_url.return_value = mock_redis from shared.broker import RedisBroker broker = RedisBroker("redis://localhost:6379") await broker.close() mock_redis.aclose.assert_called_once()