예제 #1
0
def test_cache_set_ttl_default(cache: Cache, timer: Timer):
    """Test that cache.set() uses a default TTL if initialized with one."""
    default_ttl = 2
    cache.configure(ttl=default_ttl)

    cache.set("key", "value")
    assert cache.has("key")

    timer.time = default_ttl - 1
    assert cache.has("key")

    timer.time = default_ttl
    assert not cache.has("key")
예제 #2
0
def test_cache_set_ttl_override(cache: Cache, timer: Timer):
    """Test that cache.set() can override the default TTL."""
    default_ttl = 1
    cache.configure(ttl=default_ttl)

    cache.set("key1", "value1")
    cache.set("key2", "value2", ttl=default_ttl + 1)

    timer.time = default_ttl
    assert not cache.has("key1")
    assert cache.has("key2")

    timer.time = default_ttl + 1
    assert not cache.has("key2")
예제 #3
0
def test_cache_evict(cache: Cache):
    """Test that cache.evict() will remove cache keys to make room."""
    maxsize = 5
    cache.configure(maxsize=maxsize)

    for key in range(maxsize):
        cache.set(key, key)

    assert len(cache) == maxsize
    assert cache.has(0)

    for key in range(maxsize):
        next_key = -(key + 1)
        cache.set(next_key, next_key)

        assert len(cache) == maxsize
        assert not cache.has(key)
예제 #4
0
def test_cache_full_unbounded(cache: Cache):
    """Test that cache.full() always returns False for an unbounded cache."""
    cache.configure(maxsize=0)
    for n in range(1000):
        cache.set(n, n)
        assert not cache.full()
예제 #5
0
cache.delete(1)
assert cache.get(1) is None

# 清除整个缓存
print(len(cache))
cache.clear()
assert len(cache) == 0

# 为get, set, delete设置了批量方法
cache.set_many({"a": 1, "b": 2, "c": 3})
assert cache.get_many(["a", "b", "c"])
print(len(cache))
assert cache.delete_many(["a", "b", "c"])
print(len(cache))

# 重置已经初始化的缓存对象
cache.configure(maxsize=1000, ttl=5 * 60)
cache.set_many({'a': 1, 'b': 2, 'c': 3})
assert list(cache.keys()) == ['a', 'b', 'c']
assert list(cache.values()) == [1, 2, 3]
assert list(cache.items()) == [('a', 1), ('b', 2), ('c', 3)]

# 迭代整个缓存的key
for key in cache:
    print(key, cache.get(key))
    # 'a' 1
    # 'b' 2
    # 'c' 3

assert cache.has('a')
assert 'a' in cache