python怎么模拟app_如何在Python中模拟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.

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)

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)

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

Any advice please?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值