I'm developing a python project. I need to add unittests for one class. In this class, all the methods are class methods, so that I won't need to get a class instance to call these methods. The methods have cache configured, so that the result of the methods would be cached.
Here's the problem. I'm writing unittests, in unittests I would need to mock different response of the same method. But since these methods have cache configured, so I always got the same result. Is there any convenient way to clear the cache on all class methods under this class in the unittests?
class someclass(object):
@classmethod
@timed_lru_cache(seconds=7200, maxsize=1)
def method1(cls):
return do_something()
@classmethod
@timed_lru_cache(seconds=7200, maxsize=1)
def method2(cls):
return do_something()
......
Note the cache decorator is a wrapper based on lru_cache, so I cannot use cache_clear() on the class method itself as well.
The implementation of timed_lru_cache
:
def timed_lru_cache(seconds, maxsize):
def wrapper_cache(func):
func = lru_cache(maxsize=maxsize)(func)
func.lifetime = timedelta(seconds=seconds)
func.expiration = datetime.utcnow() + func.lifetime
@wraps(func)
def wrapped_func(*args, **kwargs):
if datetime.utcnow() >= func.expiration:
func.cache_clear()
func.expiration = datetime.utcnow() + func.lifetime
return func(*args, **kwargs)
return wrapped_func
return wrapper_cache