3

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?

1
  • 1
    Can you include the import line for StrictRedis as it's written in hitcount? Commented Mar 4, 2015 at 19:27

3 Answers 3

4

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"))
Sign up to request clarification or add additional context in comments.

Comments

0

You need to patch the exact thing that you imported in hitcount.

So if you imported import redis in hitcount then you need to @patch('hitcount.redis.StrictRedis').

If you imported from redis import StrictRedis then you need to @patch('hitcount.StrictRedis').

2 Comments

thanks a lot for the quick answer @Simeon. Unfortunately, no luck at all :( still having the same effect after changing the patch as below @patch('hitcount.redis.StrictRedis', mockredis.mock_strict_redis_client) <br/>
So if you imported import redis in hitcount then you need to @patch('hitcount.redis.StrictRedis'): this is not correct, in this case you can patch redis.StrictRedis also because import redis don't copy locally a reference to redis.StrictRedis.
0

I'd the same issue. What I did is uninstall all the old versions of python from my machine. I used only python3 and it worked. sudo apt-get remove python2.7 and I installed following sudo easy_install3 pip sudo apt-get install python3-setuptools

and then it worked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.