python 模拟Django在单元测试中的缓存

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 模拟Django在单元测试中的缓存相关的知识,希望对你有一定的参考价值。

"""
myapp/mymodule.py:

from django.core.cache import cache

def set_cache():
    cache.set('foo', 'bar')
    
def get_cache():
    return cache.get('foo')

"""
from myapp.mymodule import set_cache, get_cache


with patch('myapp.mymodule.cache') as mock_cache:
    cache = {}
    
    def get(key, default=None):
      return cache.get(key, default)
    
    def _set(key, value, timeout=60):
      cache[key] = value
    
    mock_cache.get = get
    mock_cache.set = _set
    
    set_cache()
    
    self.assertEqual(cache['foo'], 'bar')
    self.assertEqual(get_cache(), 'bar')

以上是关于python 模拟Django在单元测试中的缓存的主要内容,如果未能解决你的问题,请参考以下文章