mock @patch 不修补 redis class
mock @patch does not patch redis class
我正在尝试使用 mockredis 模拟 redis class,如下所示。但是原来的redis class 并没有被屏蔽。
test_hitcount.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()
hitcount.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))
我哪里出错了?
您需要修补您在 hitcount
中导入的确切内容。
因此,如果您在 hitcount
中导入了 import redis
,那么您需要 @patch('hitcount.redis.StrictRedis')
。
如果您导入了 from redis import StrictRedis
,那么您需要 @patch('hitcount.StrictRedis')
。
当您 import hitcount
模块构建 redis.StrictRedis()
对象并将其分配给 r
。在此之后 import
redis.StrictRedis
class 的每个补丁都不能对 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。我只用了 python3 就成功了。
sudo apt-get remove python2.7
我安装了以下
须藤 easy_install3 点子
sudo apt-get install python3-setuptools
然后就成功了。
我正在尝试使用 mockredis 模拟 redis class,如下所示。但是原来的redis class 并没有被屏蔽。
test_hitcount.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()
hitcount.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))
我哪里出错了?
您需要修补您在 hitcount
中导入的确切内容。
因此,如果您在 hitcount
中导入了 import redis
,那么您需要 @patch('hitcount.redis.StrictRedis')
。
如果您导入了 from redis import StrictRedis
,那么您需要 @patch('hitcount.StrictRedis')
。
当您 import hitcount
模块构建 redis.StrictRedis()
对象并将其分配给 r
。在此之后 import
redis.StrictRedis
class 的每个补丁都不能对 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。我只用了 python3 就成功了。 sudo apt-get remove python2.7 我安装了以下 须藤 easy_install3 点子 sudo apt-get install python3-setuptools
然后就成功了。