Skip to content

Commit d7b4afe

Browse files
author
Michael Brewer
authored
feat(idempotency): Fix KeyError when local_cache is True and an error is raised in the lambda handler (#300)
1 parent fe53a2e commit d7b4afe

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

Diff for: aws_lambda_powertools/utilities/idempotency/persistence/base.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,8 @@ def _retrieve_from_cache(self, idempotency_key: str):
272272
def _delete_from_cache(self, idempotency_key: str):
273273
if not self.use_local_cache:
274274
return
275-
del self._cache[idempotency_key]
275+
if idempotency_key in self._cache:
276+
del self._cache[idempotency_key]
276277

277278
def save_success(self, event: Dict[str, Any], result: dict) -> None:
278279
"""

Diff for: tests/functional/idempotency/test_idempotency.py

+11
Original file line numberDiff line numberDiff line change
@@ -627,3 +627,14 @@ def test_user_local_disabled(persistence_store):
627627
# THEN raise AttributeError
628628
# AND don't have a _cache attribute
629629
assert not hasattr("persistence_store", "_cache")
630+
631+
632+
@pytest.mark.parametrize("persistence_store", [{"use_local_cache": True}], indirect=True)
633+
def test_delete_from_cache_when_empty(persistence_store):
634+
# GIVEN use_local_cache is True AND the local cache is empty
635+
try:
636+
# WHEN we _delete_from_cache
637+
persistence_store._delete_from_cache("key_does_not_exist")
638+
except KeyError:
639+
# THEN we should not get a KeyError
640+
pytest.fail("KeyError should not happen")

Diff for: tests/unit/test_lru_cache.py

+22
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,25 @@ def test_setitem_moves_to_end(populated_cache):
5656

5757
assert last_item == f"key_{random_value}"
5858
assert populated_cache[f"key_{random_value}"] == f"new_val_{random_value}"
59+
60+
61+
def test_lru_pop_failing():
62+
cache = LRUDict()
63+
key = "test"
64+
cache[key] = "value"
65+
try:
66+
cache.pop(key, None)
67+
pytest.fail("GitHub #300: LRUDict pop bug has been fixed :)")
68+
except KeyError as e:
69+
assert e.args[0] == key
70+
71+
72+
def test_lru_del():
73+
cache = LRUDict()
74+
key = "test"
75+
cache[key] = "value"
76+
assert len(cache) == 1
77+
if key in cache:
78+
del cache[key]
79+
assert key not in cache
80+
assert len(cache) == 0

0 commit comments

Comments
 (0)