Skip to content

Commit b408931

Browse files
committed
Fix cache panel miss counting
The cache panel was not counting misses for the get_many() cache method, because it assumed that all keys would be present in the returned dict (with a value of None if not present in the cache) while in reality only keys present in the cache are present in the returned dict. Correct the miss counting logic, and add a test for tracking hits and misses.
1 parent 8269153 commit b408931

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed

debug_toolbar/panels/cache.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,12 @@ def _store_call_info(
101101
else:
102102
self.hits += 1
103103
elif name == "get_many":
104-
for key, value in return_value.items():
105-
if value is None:
106-
self.misses += 1
107-
else:
108-
self.hits += 1
104+
if "keys" in kwargs:
105+
keys = kwargs["keys"]
106+
else:
107+
keys = args[0]
108+
self.hits += len(return_value)
109+
self.misses += len(keys) - len(return_value)
109110
time_taken *= 1000
110111

111112
self.total_time += time_taken

docs/changes.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ Change log
77
dictionaries nor ``QueryDict`` instances. Using anything but ``QueryDict``
88
instances isn't a valid use of Django but, again, django-debug-toolbar
99
shouldn't crash.
10+
* Fixed the cache panel to correctly count cache misses from the get_many()
11+
cache method.
1012

1113
3.4.0 (2022-05-03)
1214
------------------

tests/panels/test_cache.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,23 @@ def test_recording_caches(self):
2626
second_cache.get("foo")
2727
self.assertEqual(len(self.panel.calls), 2)
2828

29+
def test_hits_and_misses(self):
30+
cache.cache.clear()
31+
cache.cache.get("foo")
32+
self.assertEqual(self.panel.hits, 0)
33+
self.assertEqual(self.panel.misses, 1)
34+
cache.cache.set("foo", 1)
35+
cache.cache.get("foo")
36+
self.assertEqual(self.panel.hits, 1)
37+
self.assertEqual(self.panel.misses, 1)
38+
cache.cache.get_many(["foo", "bar"])
39+
self.assertEqual(self.panel.hits, 2)
40+
self.assertEqual(self.panel.misses, 2)
41+
cache.cache.set("bar", 2)
42+
cache.cache.get_many(keys=["foo", "bar"])
43+
self.assertEqual(self.panel.hits, 4)
44+
self.assertEqual(self.panel.misses, 2)
45+
2946
def test_get_or_set_value(self):
3047
cache.cache.get_or_set("baz", "val")
3148
self.assertEqual(cache.cache.get("baz"), "val")

0 commit comments

Comments
 (0)