使用缓存装饰器在Python中运行单元测试

时间:2015-01-13 00:16:26

标签: python django unit-testing caching django-models

所以我正在开发一个应用程序,在导入某些记录时,需要重新计算某些字段。为防止数据库读取每个检查,有一个缓存装饰器,因此数据库读取仅在导入期间每n秒执行一次。构建测试用例会带来麻烦。以下确实有效,但它的睡眠很难看。

# The decorator I need to patch

@cache_function_call(2.0)
def _latest_term_modified():
    return PrimaryTerm.objects.latest('object_modified').object_modified


# The 2.0 sets the TTL of the decorator. So I need to switch out 
# self.ttl for this decorated function before 
# this test. Right now I'm just using a sleep, which works

    @mock.patch.object(models.Student, 'update_anniversary')
    def test_import_on_term_update(self, mock_update):
        self._import_student()
        latest_term = self._latest_term_mod()
        latest_term.save()
        time.sleep(3)
        self._import_student()
        self.assertEqual(mock_update.call_count, 2)

装饰器本身如下所示:

class cache_function_call(object):
    """Cache an argument-less function call for 'ttl' seconds."""
    def __init__(self, ttl):
        self.cached_result = None
        self.timestamp = 0
        self.ttl = ttl

    def __call__(self, func):
        @wraps(func)
        def inner():
            now = time.time()
            if now > self.timestamp + self.ttl:
                self.cached_result = func()
                self.timestamp = now
            return self.cached_result
        return inner

我试图在导入模型之前设置装饰器:

decorators.cache_function_call = lambda x : x
import models

但是即使在文件的顶部,django仍然在运行我的tests.py之前初始化模型,并且该函数仍然使用缓存装饰器而不是我的lambda / noop装饰。

写这个测试的最佳方式是什么,所以我不会睡觉。我可以在以某种方式运行导入之前设置装饰器的ttl吗?

1 个答案:

答案 0 :(得分:1)

您可以稍微更改装饰器类。

decorators.py的模块级别设置全局

BAILOUT = False

并在装饰器类中更改:

def __call__(self, func):
    @wraps(func)
    def inner():
        now = time.time()
        if BAILOUT or now > self.timestamp + self.ttl:
            self.cached_result = func()
            self.timestamp = now
        return self.cached_result
    return inner

然后在你的测试中设置decorators.BAILOUT = True,并且,嘿presto! - )