我正在尝试使用 mockredis 模拟 redis 类,如下所示。但是原始的 redis 类没有被屏蔽。
测试命中数.py
import unittest
from mock import patch
import mockredis
import hitcount
class HitCountTest(unittest.TestCase):
@patch('redis.StrictRedis', mockredis.mock_strict_redis_client)
def testOneHit(self):
# increase the hit count for user peter
hitcount.hit("pr")
# ensure that the hit count for peter is just 1
self.assertEqual(b'0', hitcount.getHit("pr"))
if __name__ == '__main__':
unittest.main()
点击次数.py
import redis
r = redis.StrictRedis(host='0.0.0.0', port=6379, db=0)
def hit(key):
r.incr(key)
def getHit(key):
return (r.get(key))
我哪里出错了?
最佳答案
当您import hitcount
模块时,您构建redis.StrictRedis()
对象并将其分配给r
。在这个导入
之后,redis.StrictRedis
类的每个补丁都不能对r
引用产生影响,至少你修补了一些redis.StrictRedis
的方法。
所以你需要做的是修补 hitcount.r
实例。按照(未经测试的)代码通过将 hitcount.r
实例替换为您想要的模拟对象来完成工作:
@patch('hitcount.r', mockredis.mock_strict_redis_client(host='0.0.0.0', port=6379, db=0))
def testOneHit(self):
# increase the hit count for user peter
hitcount.hit("pr")
# ensure that the hit count for peter is just 1
self.assertEqual(b'0', hitcount.getHit("pr"))
关于python-3.x - mock @patch 不修补 redis 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863081/