如何在 Python 中模拟 redis 客户端?

How to mock a redis client in Python?(如何在 Python 中模拟 redis 客户端?)
本文介绍了如何在 Python 中模拟 redis 客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我刚刚发现一堆单元测试失败了,因为开发人员没有在测试中模拟出对 redis 客户端的依赖.我正在努力解决这个问题,但我自己也遇到了困难.

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 but have difficulties myself.

该方法写入一个redis客户端:

The method writes to a redis client:

redis_client = get_redis_client()
redis_client.set('temp-facility-data', cPickle.dumps(df))

稍后在断言中检索结果:

Later in the assert the result is retrieved:

res = cPickle.loads(get_redis_client().get('temp-facility-data'))
expected = pd.Series([set([1, 2, 3, 4, 5])], index=[1])
assert_series_equal(res.variation_pks, expected)

我成功地修补了redis客户端的get()和set().

I managed to patch the redis client's get() and set() successfully.

@mock.patch('redis.StrictRedis.get')
@mock.patch('redis.StrictRedis.set')
def test_identical(self, mock_redis_set, mock_redis_get):
    mock_redis_get.return_value = ???
    f2 = deepcopy(self.f)
    f3 = deepcopy(self.f)
    f2.pk = 2
    f3.pk = 3
    self.one_row(f2, f3)

但我不知道如何将 get()return_value 设置为 set() 将在代码中设置的值,以便测试通过.

but I don't know how to set the return_value of get() to what the set() would set in the code, so that the test would pass.

现在这条线没有通过测试:

Right now this line fails the test:

res = cPickle.loads(get_redis_client().get('temp-facility-data'))
TypeError: must be string, not MagicMock

有什么建议吗?

推荐答案

认为你可以使用副作用在本地字典中设置和获取值

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):
    return data[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

这篇关于如何在 Python 中模拟 redis 客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)