Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking redis in python

I am trying to mock redis to enable testing of my python app which is built in Django. All of my instances of redis come from a module named record, with the init.py file containing:

redis_client = redis.from_url(os.environ.get("REDIS_URL"))

I tried to patch the instance with mockredis, but it is not working. Here is mode code:

class TestReleaseDashboard(TestCase):
    def setUp(self):

        # patch redis
        redis_patcher = patch('record.redis_client', mock_redis_client())
        self.redis = redis_patcher.start()
        self.addCleanup(redis_patcher.stop)

        # add data
        self.redis.set('LATEST_UPDATE', 'Fall 2012')
        self.redis.set('NEXT_UPDATE', 'Spring 2013')

    def test_can_filter_pensions(self):
        print(redis_client)
        print(self.redis)

The result of those two print statements is:

Redis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
<mockredis.client.MockRedis object at 0x1132924d0>

What can I do to fix this and mock the instance?

like image 945
Casey Avatar asked Dec 12 '25 01:12

Casey


1 Answers

I just ran into the same problem, that is how I mocked my redis instance. Hopes it helps someone. Given the code from the original question, use:

import fakeredis

@patch("redis_instance", fakeredis.FakeStrictRedis())
def test_can_filter_pensions(self):
    print(redis_client)

Result:

FakeStrictRedis<ConnectionPool<FakeConnection<server=<fakeredis._server.FakeServer object at 0x7fe87eb99410>,db=0>>>
like image 140
Jana Avatar answered Dec 14 '25 15:12

Jana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!