摘要:我正在做一个实验,试图创建一个简单的mock来替换redis。我正在尝试做的事情应该从代码中显而易见。简短的版本是,模拟不起作用 - 它仍然会 redis 并创建密钥。
测试.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)
实用程序.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()
现在,我期望的是,当我运行测试时,没有设置 redis 键。以下是实际发生的情况:
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"
简单的问题:为什么 mock.patch 不符合我的预期?