Skip to content

Commit cc8feed

Browse files
committed
fix(cache): preserve get defaults and LRU order
1 parent 5785377 commit cc8feed

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

‎aws_lambda_powertools/shared/cache_dict.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33

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

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

2727
def get(self, key, *args, **kwargs):
2828
item = super().get(key, *args, **kwargs)
29-
if item:
29+
if key in self:
3030
self.move_to_end(key=key)
3131
return item

‎tests/unit/test_lru_cache.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,26 @@ def test_cache_order_get(populated_cache):
4343
assert last_item == f"key_{random_value}"
4444

4545

46+
def test_cache_get_missing_key_returns_default():
47+
cache = LRUDict(max_items=2)
48+
cache["existing"] = "value"
49+
50+
assert cache.get("missing", "fallback") == "fallback"
51+
assert list(cache) == ["existing"]
52+
53+
54+
@pytest.mark.parametrize("value", [False, 0, None, ""])
55+
def test_cache_get_falsey_value_updates_recency(value):
56+
cache = LRUDict(max_items=2)
57+
cache["falsey"] = value
58+
cache["other"] = "value"
59+
60+
assert cache.get("falsey") == value
61+
cache["new"] = "value"
62+
63+
assert list(cache) == ["falsey", "new"]
64+
65+
4666
def test_cache_evict_over_max_items(populated_cache):
4767
assert "key_0" in populated_cache
4868
assert len(populated_cache) == MAX_CACHE_ITEMS

0 commit comments

Comments
 (0)