moar tests

This commit is contained in:
Will McGugan
2022-12-28 15:40:00 +00:00
parent f102fcb829
commit 331a0ce65d
2 changed files with 47 additions and 5 deletions

View File

@@ -14,7 +14,7 @@ where the overhead of the cache is a small fraction of the total processing time
from __future__ import annotations from __future__ import annotations
from typing import Dict, Generic, KeysView, TypeVar, overload from typing import cast, Dict, Generic, KeysView, TypeVar, overload
CacheKey = TypeVar("CacheKey") CacheKey = TypeVar("CacheKey")
CacheValue = TypeVar("CacheValue") CacheValue = TypeVar("CacheValue")
@@ -257,16 +257,24 @@ class FIFOCache(Generic[CacheKey, CacheValue]):
Returns: Returns:
Union[CacheValue, Optional[DefaultValue]]: Either the value or a default. Union[CacheValue, Optional[DefaultValue]]: Either the value or a default.
""" """
return self._cache.get(key, default) try:
result = self._cache[key]
except KeyError:
self.misses += 1
return default
else:
self.hits += 1
return result
def __getitem__(self, key: CacheKey) -> CacheValue: def __getitem__(self, key: CacheKey) -> CacheValue:
try: try:
return self._cache[key] result = self._cache[key]
except KeyError: except KeyError:
self.misses += 1 self.misses += 1
raise KeyError(key) from None raise KeyError(key) from None
finally: else:
self.hits += 1 self.hits += 1
return result
def __container__(self, key: CacheKey) -> bool: def __contains__(self, key: CacheKey) -> bool:
return key in self._cache return key in self._cache

View File

@@ -152,7 +152,9 @@ def test_lru_cache_len(keys: list[str], expected_len: int):
def test_fifo_cache(): def test_fifo_cache():
cache = FIFOCache(4) cache = FIFOCache(4)
assert not cache assert not cache
assert "foo" not in cache
cache["foo"] = 1 cache["foo"] = 1
assert "foo" in cache
assert cache assert cache
cache["bar"] = 2 cache["bar"] = 2
cache["baz"] = 3 cache["baz"] = 3
@@ -171,3 +173,35 @@ def test_fifo_cache():
cache.clear() cache.clear()
assert len(cache) == 0 assert len(cache) == 0
assert list(cache.keys()) == [] assert list(cache.keys()) == []
def test_fifo_cache_hits():
cache = FIFOCache(4)
assert cache.hits == 0
assert cache.misses == 0
try:
cache["foo"]
except KeyError:
assert cache.hits == 0
assert cache.misses == 1
cache["foo"] = 1
assert cache.hits == 0
assert cache.misses == 1
cache["foo"]
cache["foo"]
assert cache.hits == 2
assert cache.misses == 1
cache.get("bar")
assert cache.hits == 2
assert cache.misses == 2
cache.get("foo")
assert cache.hits == 3
assert cache.misses == 2
assert str(cache) == "<FIFOCache maxsize=4 hits=3 misses=2>"