【发布时间】:2014-04-28 22:19:30
【问题描述】:
我确实有以下装饰器:
def memo(f):
"""Decorator that caches the return value for each call to f(args).
Then when called again with same args, we can just look it up."""
cache = {}
def _f(*args):
try:
return cache[args]
except KeyError:
cache[args] = result = f(*args)
return result
except TypeError:
# some element of args can't be a dict key
return f(args)
return _f
我需要编写一些测试来了解它是否有效。我怎样才能测试这样的装饰器? 我只设法编写了性能测试,以了解它是否可以加快功能。
def test_memo(self):
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
@memo
def cached_fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return cached_fib(n - 1) + cached_fib(n - 2)
t0 = time.clock()
fib(20)
t = time.clock() - t0
t1 = time.clock()
cached_fib(20)
t2 = time.clock() - t1
self.assertGreater(t, t2)
也许测试它是否在缓存中存储一些值是明智的,但我不知道如何在 python 中实现它。有什么想法吗?
【问题讨论】:
标签: python unit-testing testing memoization python-decorators