ForcePilot/backend/test/unit/channel/startup/test_redis_cache.py
Kris 6c95dc006a test: 新增渠道模块全链路单元测试用例与目录结构
完成渠道模块的单元测试目录搭建,新增多个领域模型、端口、中间件、事件、服务以及基础设施层的单元测试文件,同时补充了conftest.py的环境变量配置,完善测试基础环境。
2026-05-30 21:55:35 +08:00

73 lines
2.2 KiB
Python

from __future__ import annotations
from unittest.mock import AsyncMock
import pytest
from yuxi.channel.infrastructure.cache.redis_cache import RedisCache
class TestRedisCache:
@pytest.fixture
def mock_redis(self):
return AsyncMock()
@pytest.fixture
def cache(self, mock_redis):
return RedisCache(redis=mock_redis)
@pytest.mark.asyncio
async def test_get(self, cache, mock_redis):
mock_redis.get.return_value = b'{"data": "test"}'
result = await cache.get("key1")
assert result == {"data": "test"}
mock_redis.get.assert_awaited_once_with("key1")
@pytest.mark.asyncio
async def test_get_none(self, cache, mock_redis):
mock_redis.get.return_value = None
result = await cache.get("key1")
assert result is None
@pytest.mark.asyncio
async def test_set(self, cache, mock_redis):
await cache.set("key1", {"data": "test"}, ttl=60)
mock_redis.setex.assert_awaited_once()
@pytest.mark.asyncio
async def test_delete(self, cache, mock_redis):
await cache.delete("key1")
mock_redis.delete.assert_awaited_once_with("key1")
@pytest.mark.asyncio
async def test_exists(self, cache, mock_redis):
mock_redis.exists.return_value = 1
result = await cache.exists("key1")
assert result is True
@pytest.mark.asyncio
async def test_exists_false(self, cache, mock_redis):
mock_redis.exists.return_value = 0
result = await cache.exists("key1")
assert result is False
@pytest.mark.asyncio
async def test_incr(self, cache, mock_redis):
mock_redis.incr.return_value = 5
result = await cache.incr("counter")
assert result == 5
mock_redis.incr.assert_awaited_once_with("counter")
@pytest.mark.asyncio
async def test_expire(self, cache, mock_redis):
mock_redis.expire.return_value = True
result = await cache.expire("key1", 60)
assert result is True
mock_redis.expire.assert_awaited_once_with("key1", 60)
@pytest.mark.asyncio
async def test_get_json_decode_error(self, cache, mock_redis):
mock_redis.get.return_value = b"invalid json"
result = await cache.get("key1")
assert result is None