Skip to content

Commit 813cfbf

Browse files
living180tim-schilling
authored andcommitted
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 69b1a66 commit 813cfbf

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed

debug_toolbar/panels/cache.py

+6-5
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

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ Change log
88
instances isn't a valid use of Django but, again, django-debug-toolbar
99
shouldn't crash.
1010
* Added pyflame (for flame graphs) to the list of third-party panels.
11+
* Fixed the cache panel to correctly count cache misses from the get_many()
12+
cache method.
1113

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

tests/panels/test_cache.py

+17
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)