問題描述
我剛剛發現一堆單元測試失敗了,因為開發人員沒有在測試中模擬出對 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 客戶端?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!