Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock @patch does not patch redis class

I'm trying to mock redis class using mockredis as show below. But the original redis class is not getting masked.

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))

Where am I making the mistake?

like image 412
jude m Avatar asked Apr 14 '26 15:04

jude m


1 Answers

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"))
like image 73
Michele d'Amico Avatar answered Apr 17 '26 05:04

Michele d'Amico