0

I have an application that uses python-redis. I'm trying to replace the redis functions with a mock.

app.py:

import redis

class MyApp:

    def readData(self):
        db = redis.Redis(decode_responses=True)
        return db.get('myKey')

This is the test code:

import sys
import unittest
from unittest.mock import patch, MagicMock, Mock
sys.path.append("./")
from app import MyApp


class MockRedis:
    def __init__(self, cache=dict()):
        print("Mock redis created")
        self.cache = cache

    def get(self, key):
        print("Mock redis get called")
        if key in self.cache:
            return self.cache[key]
        return None


class TestApp(unittest.TestCase):

    @patch("redis.Redis")
    def test_readData(self, mock):
        redisCache = {'myKey':'testValue'}
        db = MockRedis(redisCache)
        dbFunctions = MagicMock()
        dbFunctions.get = Mock(side_effect=db.get)
        mock.return_vaue = dbFunctions

        app = MyApp()
        self.assertEqual("testValue", app.readData())

The app.readData() internally calls redis.Redis.get(), which I'm trying to replace with MockRedis.get().

Test execution fails with below error:

# python -m unittest discover .
Mock redis created
F
======================================================================
FAIL: test_readData (testApp.TestApp)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.9/unittest/mock.py", line 1336, in patched
    return func(*newargs, **newkeywargs)
  File "/root/temp/testApp.py", line 31, in test_readData
    self.assertEqual("testValue", app.readData())
AssertionError: 'testValue' != <MagicMock name='Redis().get()' id='139679523837648'>

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (failures=1)

What am I doing wrong?

m.divya.mohan
  • 2,261
  • 4
  • 24
  • 34

0 Answers0