Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions aws_lambda_powertools/shared/cache_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

class LRUDict(OrderedDict):
"""
Cache implementation based on ordered dict with a maximum number of items. Last accessed item will be evicted
first. Currently used by idempotency utility.
Cache implementation based on ordered dict with a maximum number of items. Least recently used item will be
evicted first. Currently used by idempotency utility.
"""

def __init__(self, max_items=1024, *args, **kwargs):
Expand All @@ -26,6 +26,6 @@ def __setitem__(self, key, value):

def get(self, key, *args, **kwargs):
item = super().get(key, *args, **kwargs)
if item:
if key in self:
self.move_to_end(key=key)
return item
20 changes: 20 additions & 0 deletions tests/unit/test_lru_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,26 @@ def test_cache_order_get(populated_cache):
assert last_item == f"key_{random_value}"


def test_cache_get_missing_key_returns_default():
cache = LRUDict(max_items=2)
cache["existing"] = "value"

assert cache.get("missing", "fallback") == "fallback"
assert list(cache) == ["existing"]


@pytest.mark.parametrize("value", [False, 0, None, ""])
def test_cache_get_falsey_value_updates_recency(value):
cache = LRUDict(max_items=2)
cache["falsey"] = value
cache["other"] = "value"

assert cache.get("falsey") == value
cache["new"] = "value"

assert list(cache) == ["falsey", "new"]


def test_cache_evict_over_max_items(populated_cache):
assert "key_0" in populated_cache
assert len(populated_cache) == MAX_CACHE_ITEMS
Expand Down