-1

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
cynkiller
  • 73
  • 9
  • What's the implementation of `timed_lru_cache` like? It should be possible to make sure you can call `cache_clear` from its return value – rdas Jun 09 '22 at 09:59
  • @rdas I added the implementation of `timed_lru_cache` in the description for your reference. I cannot call cache_clear directly. – cynkiller Jun 09 '22 at 10:05
  • Try adding `wrapped_func.cache_clear = func.cache_clear` in the implementation of `wrapper_cache` that should allow you to call it – rdas Jun 09 '22 at 10:12
  • Found another way to clear global cache to save the effort of adding cache clear one by one. https://stackoverflow.com/a/50699209/7225657 – cynkiller Jun 09 '22 at 10:17

1 Answers1

0

You can use this

someclass.method2.fget.cache_clear()
Akshay Kumar
  • 367
  • 5
  • 15