fakeredis between multiple django views

Issue

I have a test which involve multiple Django views

It seems that the fakeredis isn’t shared between multiple views
I tried running the following code:

import fakeredis
from testfixtures import Replacer


class TestWithFakeRedis(TestCase):
    def setup_redis(self, test_func):
        fake_redis = fakeredis.FakeStrictRedis()
        with Replacer() as replace:
            replace('app1.views.redis_connection', fake_redis)
            replace("app2.views.redis_connection", fake_redis)
            replace("app2.views.redis_connection", fake_redis)
            test_func(fake_redis)

    def test_something(self):
         def test_func(redis_connection):
            # some testing coded here
            pass
         self.setup_redis(test_func)

the fakeredis can’t be passed between multiple views and it’s something that I need

Thanks in advance,

Nadav

Solution

my solution involved using unittest.mock.patch:

import fakeredis
fake_redis = fakeredis.FakeRedis()

@patch("app_name1.views.redis_connection", fake_redis)
@patch("app_name2.views.redis_connection", fake_redis)
@patch("app_name3.views.redis_connection", fake_redis)
class TestSomethingWithRedis(TestCase):
    pass

if you want to check query inside your test(s)
use fake_redis

Answered By – Nadav

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published