Test if a function/region is cached in Beaker/Dogpile

453 views Asked by At

Using the python modules Beaker or Dogpile for caching, is it possible to test if a region with a particular key value is already present in the cache or not?

1

There are 1 answers

0
reading_ant On

Let's say you have a method that's cached with beaker:

@cache_region('foo_term')
def cached_method(bar):
   return actual_method(bar)

Then in your test you can patch out method_to_test and assert it is called / not called:

def test_cache():
    with patch('package.module.actual_method') as m:
        cached_method(foo)
        assert m.call_args_list = [call(foo)] # Asserting it is not cached the first time

        cached_method(foo)
        assert m.call_args_list = [call(foo)] # Now asserting it is cached

        cached_method(bar)
        assert m.call_args_list = [call(foo), call(bar)] # asserting `bar' is not cached

Note that you have to wrap the method you want to cache with a 'cached' version of the function, and put the beaker cache decorator on the cached version. Unless, of course, you find a way to make patch works with this black magic.