0

如何模拟以下连接到 Redis 的函数?

import redis

class RedisCache:
    redis_instance = None

    @classmethod
    def set_connect(cls):
        redis_instance = redis.StrictRedis(host='0.0.0.0', port=6379, password='xyz', charset='utf-8', decode_responses=True, socket_timeout=30)
        return redis_instance

    @classmethod
    def get_conn(cls):
        cls.redis_instance = cls.set_connect()
        return cls.redis_instance

我寻找了一些解决方案,但它们基本上是使用 fakeredis 模块。我想有一种更简单的方法来模拟这些函数。

注意 - 函数返回的数据:Redis<ConnectionPool<Connection<host=127.0.0.1,port=6379,db=0>>>

4

1 回答 1

1

您可以使用patch()函数来模拟redis.StrictRedis类。查看补丁的位置

例如

redis_cache.py

import redis


class RedisCache:
    redis_instance = None

    @classmethod
    def set_connect(cls):
        redis_instance = redis.StrictRedis(host='0.0.0.0', port=6379, password='xyz',
                                           charset='utf-8', decode_responses=True, socket_timeout=30)
        return redis_instance

    @classmethod
    def get_conn(cls):
        cls.redis_instance = cls.set_connect()
        return cls.redis_instance

test_redis_cache.py

from unittest import TestCase
import unittest
from unittest.mock import patch, Mock
from redis_cache import RedisCache


class TestRedisCache(TestCase):
    def test_set_connect(self):
        with patch('redis.StrictRedis') as mock_StrictRedis:
            mock_redis_instance = mock_StrictRedis.return_value
            actual = RedisCache.set_connect()
            self.assertEqual(actual, mock_redis_instance)
            mock_StrictRedis.assert_called_once_with(host='0.0.0.0', port=6379, password='xyz',
                                                     charset='utf-8', decode_responses=True, socket_timeout=30)

    @patch('redis.StrictRedis')
    def test_get_conn(self, mock_StrictRedis):
        mock_redis_instance = mock_StrictRedis.return_value
        RedisCache.get_conn()
        self.assertEqual(RedisCache.redis_instance, mock_redis_instance)


if __name__ == '__main__':
    unittest.main()

测试结果:

..
----------------------------------------------------------------------
Ran 2 tests in 0.004s

OK
Name                                             Stmts   Miss  Cover   Missing
------------------------------------------------------------------------------
src/stackoverflow/70016401/redis_cache.py           11      0   100%
src/stackoverflow/70016401/test_redis_cache.py      18      0   100%
------------------------------------------------------------------------------
TOTAL                                               29      0   100%
于 2021-12-03T03:06:26.533 回答