2

I'm trying to test my app with pytest. The app uses Redis to store a variable, and changes to that variable are reported live to users connected with the app.

I want to create such a fixture, that will patch Redis() constructors in my app to connect with the local Redis database running in the background.

I've tried something like this in my conftest.py:

@pytest.fixture(autouse=True)
def redis_connection():
    r_conn = redis.Redis('127.0.0.1', 6337)
    with mock.patch('app.redis_utils.redis_connect') as redis_connect_mock:
        redis_connect_mock.return_value = r_conn
        yield redis_connect_mock
    r_conn.flushdb()

app.redis_utils.redis_connect contents:

def redis_connect() -> Redis:
    return Redis(**settings.REDIS_SETTINGS)

But this fails when my app tries to access data from redis database (I call .get() on redis instance).

AssertionError: assert <MagicMock name='redis_connect.get()' id='139688062779600'> is None

What can I do to force redis_connect function to return this particular instance: redis.Redis('127.0.0.1', 6337)?

umat
  • 607
  • 1
  • 13
  • 25
  • You probably should consider to use a redis mock library https://stackoverflow.com/questions/30531291/how-to-mock-a-redis-client-in-python – Anthony Kong Feb 02 '20 at 21:35

0 Answers0