Files
crypto_trader/tests/unit/core/test_redis.py

93 lines
2.8 KiB
Python
Raw Normal View History

"""Tests for Redis client wrapper."""
import pytest
from unittest.mock import Mock, patch, MagicMock, AsyncMock
class TestRedisClient:
"""Tests for RedisClient class."""
@patch('src.core.redis.get_config')
def test_get_client_creates_connection(self, mock_config):
"""Test that get_client creates a Redis connection."""
# Setup mock config
mock_config.return_value.get.return_value = {
"host": "localhost",
"port": 6379,
"db": 0,
"password": None,
"socket_connect_timeout": 5
}
from src.core.redis import RedisClient
client = RedisClient()
# Should not have connected yet
assert client._client is None
# Get client should trigger connection
with patch('src.core.redis.redis.ConnectionPool') as mock_pool:
with patch('src.core.redis.redis.Redis') as mock_redis:
redis_client = client.get_client()
mock_pool.assert_called_once()
mock_redis.assert_called_once()
@patch('src.core.redis.get_config')
def test_get_client_reuses_existing(self, mock_config):
"""Test that get_client reuses existing connection."""
mock_config.return_value.get.return_value = {
"host": "localhost",
"port": 6379,
"db": 0,
}
from src.core.redis import RedisClient
client = RedisClient()
# Pre-set a mock client
mock_redis = Mock()
client._client = mock_redis
# Should return existing
result = client.get_client()
assert result is mock_redis
@patch('src.core.redis.get_config')
@pytest.mark.asyncio
async def test_close_connection(self, mock_config):
"""Test closing Redis connection."""
mock_config.return_value.get.return_value = {"host": "localhost"}
from src.core.redis import RedisClient
client = RedisClient()
mock_redis = AsyncMock()
client._client = mock_redis
await client.close()
mock_redis.aclose.assert_called_once()
class TestGetRedisClient:
"""Tests for get_redis_client singleton."""
@patch('src.core.redis.get_config')
def test_returns_singleton(self, mock_config):
"""Test that get_redis_client returns same instance."""
mock_config.return_value.get.return_value = {"host": "localhost"}
# Reset the global
import src.core.redis as redis_module
redis_module._redis_client = None
from src.core.redis import get_redis_client
client1 = get_redis_client()
client2 = get_redis_client()
assert client1 is client2