Skip to content

Commit

Permalink
Deepcopy and ensure get_all function always terminates
Browse files Browse the repository at this point in the history
  • Loading branch information
cmanallen committed Dec 5, 2024
1 parent fd56608 commit 2d67b97
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
14 changes: 11 additions & 3 deletions sentry_sdk/_lru_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"""

from copy import copy
from copy import copy, deepcopy

SENTINEL = object()

Expand Down Expand Up @@ -95,7 +95,7 @@ def __copy__(self):
cache = LRUCache(self.max_size)
cache.full = self.full
cache.cache = copy(self.cache)
cache.root = copy(self.root)
cache.root = deepcopy(self.root)
return cache

def set(self, key, value):
Expand Down Expand Up @@ -167,7 +167,15 @@ def get(self, key, default=None):
def get_all(self):
nodes = []
node = self.root[NEXT]
while node is not self.root:

# To ensure the loop always terminates we iterate to the maximum
# size of the LRU cache.
for _ in range(self.max_size):
# The cache may not be full. We exit early if we've wrapped
# around to the head.
if node is self.root:
break
nodes.append((node[KEY], node[VALUE]))
node = node[NEXT]

return nodes
18 changes: 18 additions & 0 deletions tests/test_lru_cache.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
from copy import copy

from sentry_sdk._lru_cache import LRUCache

Expand Down Expand Up @@ -58,3 +59,20 @@ def test_cache_get_all():
assert cache.get_all() == [(1, 1), (2, 2), (3, 3)]
cache.get(1)
assert cache.get_all() == [(2, 2), (3, 3), (1, 1)]


def test_cache_copy():
cache = LRUCache(3)
cache.set(0, 0)
cache.set(1, 1)

copied = copy(cache)
cache.set(2, 2)
cache.set(3, 3)
assert copied.get_all() == [(0, 0), (1, 1)]
assert cache.get_all() == [(1, 1), (2, 2), (3, 3)]

copied = copy(cache)
cache.get(1)
assert copied.get_all() == [(1, 1), (2, 2), (3, 3)]
assert cache.get_all() == [(2, 2), (3, 3), (1, 1)]

0 comments on commit 2d67b97

Please sign in to comment.