"""Unit tests for caching utils.""" import datetime import time from sound_recordings.connectors import redis from sound_recordings.utils.cache import cache_in_redis def test_cache_in_redis(): """Test the cache_in_redis decorator.""" # Fakeredis stores state at the module level, so we use .flushall() # to ensure we have a clean slate every time we run the unit test. redis.client.flushall() assert "FakeStrictRedis" in str(redis.client) @cache_in_redis(ttl=1, key=None) def _sample_func(arg1=2, arg2={"test": 1, "prop": 2}): nonlocal x x += 1 return 1 x = 0 y = 0 @cache_in_redis(ttl=1, key=None) def _date_time_func(): return test_result test_result = [ {"store_id": 1, "date": datetime.date(2018, 7, 5), "dl": 1}, {"store_id": 1, "date": datetime.date(2018, 7, 6), "dl": 2}, {"store_id": 496, "date": datetime.date(2018, 7, 5), "dl": 3}, {"store_id": 496, "date": datetime.date(2018, 7, 6), "dl": 4}, ] @cache_in_redis(ttl=1, key=None) def _none_func(): return None y += _sample_func() # both incremented, function's body was executed assert x == 1 assert y == 1 y += _sample_func() # only result incremented, function's body wasn't executed assert x == 1 assert y == 2 time.sleep(2) # wait until cache invalidated y += _sample_func() # both incremented, function's body was executed assert x == 2 assert y == 3 result1 = _date_time_func() assert result1 == _date_time_func() # we expect one cache_key to exist for the _sample_func() # and one cache_key to exist for the _date_time_func() assert len(redis.client.keys()) == 2 result2 = _none_func() assert result2 == _none_func() # the result from _none_func() is None so we expect it not to be cached # therefore we expect no new cache_key for the result of this function assert len(redis.client.keys()) == 2