How To Mock A Redis Client In Python?
I just found that a bunch of unit tests are failing, due a developer hasn't mocked out the dependency to a redis client within the test. I'm trying to give a hand in this matter bu
Solution 1:
Think you can use side effect to set and get value in a local dict
data = {}
def set(key, val):
data[key] = val
def get(key):
returndata[key]
mock_redis_set.side_effect = set
mock_redis_get.side_effect = get
not tested this but I think it should do what you want
Solution 2:
If you want something more complete, you can try fakeredis
@patch("redis.Redis", return_value=fakeredis.FakeStrictRedis())deftest_something():
....
Solution 3:
I think you can do something like this.
redis_cache = {
"key1": (b'\x80\x04\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04test\x94.', "test"),
"key2": (None, None),
}
defget(redis_key):
if redis_key in redis_cache:
return redis_cache[redis_key][0]
else:
returnNone
mock = MagicMock()
mock.get = Mock(side_effect=get)
with patch('redis.StrictRedis', return_value=mock) as p:
for key in redis_cache:
result = self.MyClass.my_function(key)
self.assertEqual(result, redis_cache[key][1])
Post a Comment for "How To Mock A Redis Client In Python?"