Summary : I am doing an experiment to try to create a simple mock to replace redis. What I'm trying to do should be obvious from the code. Short version is, the mock doesn't work - It's still going to redis and creating keys.
tests.py:
from django.test import TestCase
import mock
from redis_mock.simple_redis_mock import redisMockGetRedis, redisMockFlushDB
from account.util import get_redis
class SimpleTest(TestCase):
def setUp(self):
redisMockFlushDB()
@mock.patch("account.util.get_redis", redisMockGetRedis)
def test_redis(self):
key = "hello123"
value = "world123"
r = get_redis()
r.set(key, value)
value2 = r.get(key)
self.assertEqual(value, value2)
util.py:
import redis
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DEFAULT_DB = 0
def get_redis():
print "account.util.get_redis"
return redis.StrictRedis(
REDIS_HOST,
REDIS_PORT,
REDIS_DEFAULT_DB
)
simple_redis_mock.py:
"""
A simple mock for Redis. Just mocks set, get and expire commands.
"""
class SimpleRedisMockDB:
db = {}
def redisMockFlushDB():
"""
Helper function to flush the RedisMock db between test runs
"""
print "redisMockFlushDB"
SimpleRedisMock.db = {}
class SimpleRedisMock:
def get(self, key):
val = None
try:
val = SimpleRedisMockDB.db[key]
except:
pass
print "SimpleRedisMock get(" + str(key) + "):" + str(val)
return val
def set(self, key, val):
print "SimpleRedisMock set(" + str(key) + "," + str(val) +")"
SimpleRedisMockDB.db[key] = val
def expire(self, key):
pass
def redisMockGetRedis():
print "redisMockGetRedis"
return SimpleRedisMock()
Now, what I expect is that when I run my test, no redis keys are set. Here's what actually happens:
twang$ redis-cli
redis 127.0.0.1:6379> del hello123
(integer) 1
redis 127.0.0.1:6379> exit
twang$ ./manage.py test account
Creating test database for alias 'default'...
redisMockFlushDB
account.util.get_redis
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Destroying test database for alias 'default'...
twang$ redis-cli
redis 127.0.0.1:6379> get hello123
"world123"
Simple question : Why isn't mock.patch doing what I expect?