Ejemplo n.º 1
0
def test_lock(cache: RedisCache):
    key = 'test_key_8'
    lock = cache.lock(key)
    lock.acquire(blocking=True)
    assert cache.has_key(key)
    lock.release()
    assert not cache.has_key(key)
Ejemplo n.º 2
0
    def test_iter_keys(
        self, key_prefix_cache: RedisCache, with_prefix_cache: RedisCache
    ):
        if isinstance(key_prefix_cache.client, ShardClient):
            pytest.skip("ShardClient doesn't support iter_keys")

        key_prefix_cache.set("a", "1")
        with_prefix_cache.set("b", "2")
        assert list(key_prefix_cache.iter_keys("*")) == ["a"]
Ejemplo n.º 3
0
def test_setnx(cache: RedisCache):
    assert isinstance(cache, RedisSentinelCache)
    key = 'test_key_nx'
    cache.delete(key)
    assert cache.get(key) is None
    assert cache.set(key, 1, nx=True)
    assert not cache.set(key, 2, nx=True)
    assert cache.get(key) == 1
    cache.delete(key)
    assert cache.get(key) is None
Ejemplo n.º 4
0
 def test_delete_pattern(
     self, key_prefix_cache: RedisCache, with_prefix_cache: RedisCache
 ):
     key_prefix_cache.set("a", "1")
     with_prefix_cache.set("b", "2")
     key_prefix_cache.delete_pattern("*")
     assert key_prefix_cache.has_key("a") is False
     assert with_prefix_cache.get("b") == "2"
Ejemplo n.º 5
0
def test_django_redis_custom_key_fun(cache: RedisCache):
    assert isinstance(cache, RedisSentinelCache)
    for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]:
        cache.set(key, "foo")
    res = cache.delete_pattern("*foo-a*")
    assert res

    keys = cache.keys("foo*")
    assert set(keys) == {"foo-bb", "foo-bc"}
    # ensure our custom function was actually called
    try:
        assert (set(k.decode('utf-8') for k in cache.raw_client.keys('*')),
                {':1:foo-bc', ':1:foo-bb'})
    except (NotImplementedError, AttributeError):
        # not all clients support .keys()
        pass
Ejemplo n.º 6
0
def test_save_str(cache: RedisCache):
    assert isinstance(cache, RedisSentinelCache)
    key = 'test_key_4'
    str1 = "hello" * 1000
    cache.set(key, str1)
    assert cache.get(key) == str1
    str2 = "2"
    cache.set(key, str2)
    assert cache.get(key) == str2

    str3 = "some chinese 有一些中文"
    cache.set(key, str3)
    assert cache.get(key) == str3
Ejemplo n.º 7
0
 def __init__(self, server, params):
     """
     Instantiate the Redis Cache with server and params
     and retrieve the cache with alias "fallback"
     """
     super().__init__(params)
     self._redis_cache = RedisCache(server, params)
     self._fallback_cache = caches["fallback"]
Ejemplo n.º 8
0
def test_setnx_timeout(cache: RedisCache):
    assert isinstance(cache, RedisSentinelCache)
    # test timeout works
    key = 'test_key_nx2'
    assert cache.set(key, 1, timeout=2, nx=True)
    time.sleep(3)
    assert cache.get(key) is None
    # test timeout will not affect key,if it was there
    cache.set(key, 1)
    assert not cache.set(key, 2, timeout=2, nx=True)
    time.sleep(3)
    assert cache.get(key) == 1
    cache.delete(key)
    assert cache.get(key) is None
Ejemplo n.º 9
0
def test_custom_key_function(cache: RedisCache, settings: SettingsWrapper):
    caches_setting = copy.deepcopy(settings.CACHES)
    caches_setting["default"]["KEY_FUNCTION"] = "test_cache_options.make_key"
    caches_setting["default"]["REVERSE_KEY_FUNCTION"] = "test_cache_options.reverse_key"
    settings.CACHES = caches_setting

    if isinstance(cache.client, ShardClient):
        pytest.skip("ShardClient doesn't support get_client")

    for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]:
        cache.set(key, "foo")

    res = cache.delete_pattern("*foo-a*")
    assert bool(res) is True

    keys = cache.keys("foo*")
    assert set(keys) == {"foo-bb", "foo-bc"}
    # ensure our custom function was actually called
    assert {k.decode() for k in cache.client.get_client(write=False).keys("*")} == (
        {"#1#foo-bc", "#1#foo-bb"}
    )
Ejemplo n.º 10
0
class NRRedisCache(object):

    _redis: RedisCache = RedisCache(settings.REDIS_SERVER, {})

    @classmethod
    def get(cls, key, default_value=None, timeout=REDIS_DEFAULT_TIMEOUT):
        return cls._redis.get_or_set(key,
                                     default=default_value,
                                     timeout=timeout)

    @classmethod
    def get_from_json(cls,
                      key,
                      default_value=None,
                      timeout=REDIS_DEFAULT_TIMEOUT):
        r = cls._redis.get_or_set(key, default=default_value, timeout=timeout)
        if r is not None:
            r = JsonUtil.deserialize(r)
        return r

    @classmethod
    def set(cls, key, data, timeout=REDIS_DEFAULT_TIMEOUT):
        cls._redis.set(key, data, timeout=timeout)

    @classmethod
    def set_to_json(cls, key, data, timeout=REDIS_DEFAULT_TIMEOUT):
        cls._redis.set(key, JsonUtil.serialize(data), timeout=timeout)

    @classmethod
    def has_key(cls, key):
        return cls._redis.has_key(key)

    @classmethod
    def expire(cls, key, timeout):
        cls._redis.expire(key, timeout)

    @classmethod
    def ttl(cls, key):
        return cls._redis.ttl(key)
Ejemplo n.º 11
0
from string import ascii_lowercase
from timeit import timeit

from django.core.cache.backends.locmem import LocMemCache
from django_redis.cache import RedisCache
from shared_memory_dict.caches.django import SharedMemoryCache

cache_smc_django = SharedMemoryCache(
    'django', params={'OPTIONS': {
        'MEMORY_BLOCK_SIZE': 64
    }})
cache_django_redis = RedisCache(server='redis://127.0.0.1:6379/1', params={})
cache_django_locmem = LocMemCache('locmem', params={})


def agressive(cache):
    for c in ascii_lowercase:
        for i in range(5):
            cache.set(f'{c}{i}', '1')
        for i in range(10, 0, -1):
            cache.get(f'{c}{i}')


def fun(cache):
    cache.set('fun', 'uhull')
    for _ in range(3):
        cache.get('fun')


def collect(cache_var_name):
    time_of_agressive = timeit(stmt=f'agressive({cache_var_name})',
Ejemplo n.º 12
0
def test_expire(cache: RedisCache):
    key = 'test_key_7'
    cache.set(key, 'bar', timeout=None)
    cache.expire(key, 20)
    ttl = cache.ttl(key)
    assert 18 < ttl <= 20
Ejemplo n.º 13
0
def test_persist(cache: RedisCache):
    key = 'test_key_6'
    cache.set(key, 'bar', timeout=20)
    cache.persist(key)
    assert cache.ttl(key) is None
Ejemplo n.º 14
0
def test_get_django_omit_exceptions(ignore_exceptions_cache: RedisCache):
    assert ignore_exceptions_cache._ignore_exceptions is True
    assert ignore_exceptions_cache.get("key") is None
    assert ignore_exceptions_cache.get("key", "default") == "default"
    assert ignore_exceptions_cache.get("key", default="default") == "default"
Ejemplo n.º 15
0
def test_get_django_omit_exceptions_many_returns_default_arg(
    ignore_exceptions_cache: RedisCache,
):
    assert ignore_exceptions_cache._ignore_exceptions is True
    assert ignore_exceptions_cache.get_many(["key1", "key2", "key3"]) == {}
Ejemplo n.º 16
0
def test_save_and_int(cache: RedisCache):
    assert isinstance(cache, RedisSentinelCache)
    key = 'test_key_3'
    cache.set(key, 2)
    res = cache.get(key, 'astr')
    assert res == 2
Ejemplo n.º 17
0
 def test_keys(self, key_prefix_cache: RedisCache, with_prefix_cache: RedisCache):
     key_prefix_cache.set("a", "1")
     with_prefix_cache.set("b", "2")
     keys = key_prefix_cache.keys("*")
     assert "a" in keys
     assert "b" not in keys
Ejemplo n.º 18
0
def test_save_dict(cache: RedisCache):
    key = 'test_key_5'
    d1 = {"id": 1, "name": "CodeTalks", "memo": "生活真美好"}
    cache.set(key, d1)
    assert cache.get(key) == d1