From 2c912c348808ee66a4fd164bda68b494243c6c54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sondre=20Lilleb=C3=B8=20Gundersen?= Date: Mon, 30 Aug 2021 16:12:05 +0300 Subject: [PATCH] Fixed #33061 -- Fixed handling nonexistent keys with negative deltas in incr()/decr() in memcached backends. Thanks Chris Jerdonek for the review. --- django/core/cache/backends/memcached.py | 12 ++++++------ tests/cache/tests.py | 4 ++++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py index 112dbdd1ff2..0ca485903af 100644 --- a/django/core/cache/backends/memcached.py +++ b/django/core/cache/backends/memcached.py @@ -105,11 +105,11 @@ class BaseMemcachedCache(BaseCache): self._cache.disconnect_all() def incr(self, key, delta=1, version=None): - key = self.make_key(key, version=version) - self.validate_key(key) # memcached doesn't support a negative delta if delta < 0: - return self._cache.decr(key, -delta) + return self.decr(key, -delta, version=version) + key = self.make_key(key, version=version) + self.validate_key(key) try: val = self._cache.incr(key, delta) @@ -122,11 +122,11 @@ class BaseMemcachedCache(BaseCache): return val def decr(self, key, delta=1, version=None): - key = self.make_key(key, version=version) - self.validate_key(key) # memcached doesn't support a negative delta if delta < 0: - return self._cache.incr(key, -delta) + return self.incr(key, -delta, version=version) + key = self.make_key(key, version=version) + self.validate_key(key) try: val = self._cache.decr(key, delta) diff --git a/tests/cache/tests.py b/tests/cache/tests.py index 8a2926f3d77..cea70463d29 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -382,6 +382,8 @@ class BaseCacheTests: self.assertEqual(cache.incr('answer', -10), 42) with self.assertRaises(ValueError): cache.incr('does_not_exist') + with self.assertRaises(ValueError): + cache.incr('does_not_exist', -1) cache.set('null', None) with self.assertRaises(self.incr_decr_type_error): cache.incr('null') @@ -396,6 +398,8 @@ class BaseCacheTests: self.assertEqual(cache.decr('answer', -10), 42) with self.assertRaises(ValueError): cache.decr('does_not_exist') + with self.assertRaises(ValueError): + cache.incr('does_not_exist', -1) cache.set('null', None) with self.assertRaises(self.incr_decr_type_error): cache.decr('null')