From 331a0ce65d90a033d7c816fbdca1a16320e723e2 Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Wed, 28 Dec 2022 15:40:00 +0000 Subject: [PATCH] moar tests --- src/textual/_cache.py | 18 +++++++++++++----- tests/test_cache.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/src/textual/_cache.py b/src/textual/_cache.py index de4e96286..3127bd22d 100644 --- a/src/textual/_cache.py +++ b/src/textual/_cache.py @@ -14,7 +14,7 @@ where the overhead of the cache is a small fraction of the total processing time from __future__ import annotations -from typing import Dict, Generic, KeysView, TypeVar, overload +from typing import cast, Dict, Generic, KeysView, TypeVar, overload CacheKey = TypeVar("CacheKey") CacheValue = TypeVar("CacheValue") @@ -257,16 +257,24 @@ class FIFOCache(Generic[CacheKey, CacheValue]): Returns: 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: try: - return self._cache[key] + result = self._cache[key] except KeyError: self.misses += 1 raise KeyError(key) from None - finally: + else: self.hits += 1 + return result - def __container__(self, key: CacheKey) -> bool: + def __contains__(self, key: CacheKey) -> bool: return key in self._cache diff --git a/tests/test_cache.py b/tests/test_cache.py index e27a4924b..9a4bb2ef3 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -152,7 +152,9 @@ def test_lru_cache_len(keys: list[str], expected_len: int): def test_fifo_cache(): cache = FIFOCache(4) assert not cache + assert "foo" not in cache cache["foo"] = 1 + assert "foo" in cache assert cache cache["bar"] = 2 cache["baz"] = 3 @@ -171,3 +173,35 @@ def test_fifo_cache(): cache.clear() assert len(cache) == 0 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) == ""