From cc8feed3c746b30d5d17fb731efc6cd8badaf327 Mon Sep 17 00:00:00 2001 From: Vlad Cristea <302628818+Vl4dC@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:57:38 +0100 Subject: [PATCH] fix(cache): preserve get defaults and LRU order --- aws_lambda_powertools/shared/cache_dict.py | 6 +++--- tests/unit/test_lru_cache.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/aws_lambda_powertools/shared/cache_dict.py b/aws_lambda_powertools/shared/cache_dict.py index c45d704655a..ba417ffa341 100644 --- a/aws_lambda_powertools/shared/cache_dict.py +++ b/aws_lambda_powertools/shared/cache_dict.py @@ -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): @@ -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 diff --git a/tests/unit/test_lru_cache.py b/tests/unit/test_lru_cache.py index 2424d629533..8a6888b84a5 100644 --- a/tests/unit/test_lru_cache.py +++ b/tests/unit/test_lru_cache.py @@ -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