I'm trying to mock redis class using mockredis as show below. But the original redis class is not getting masked.
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()
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))
Where am I making the mistake?
When you import hitcount module you build redis.StrictRedis() object and assign it to r. After this import every patch of redis.StrictRedis class cannot have effect on r reference at least you patch some redis.StrictRedis's methods.
So what you need to do is patch hitcount.r instance. Follow (untested) code do the job by replace hitcount.r instance with your desired mock object:
@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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With