Fixed #33061 -- Fixed handling nonexistent keys with negative deltas in incr()/decr() in memcached backends.

Thanks Chris Jerdonek for the review.
This commit is contained in:
Sondre Lillebø Gundersen 2021-08-30 16:12:05 +03:00 committed by Mariusz Felisiak
parent 96ab3a1379
commit 2c912c3488
2 changed files with 10 additions and 6 deletions

View File

@ -105,11 +105,11 @@ class BaseMemcachedCache(BaseCache):
self._cache.disconnect_all() self._cache.disconnect_all()
def incr(self, key, delta=1, version=None): 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 # memcached doesn't support a negative delta
if delta < 0: 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: try:
val = self._cache.incr(key, delta) val = self._cache.incr(key, delta)
@ -122,11 +122,11 @@ class BaseMemcachedCache(BaseCache):
return val return val
def decr(self, key, delta=1, version=None): 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 # memcached doesn't support a negative delta
if delta < 0: 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: try:
val = self._cache.decr(key, delta) val = self._cache.decr(key, delta)

View File

@ -382,6 +382,8 @@ class BaseCacheTests:
self.assertEqual(cache.incr('answer', -10), 42) self.assertEqual(cache.incr('answer', -10), 42)
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
cache.incr('does_not_exist') cache.incr('does_not_exist')
with self.assertRaises(ValueError):
cache.incr('does_not_exist', -1)
cache.set('null', None) cache.set('null', None)
with self.assertRaises(self.incr_decr_type_error): with self.assertRaises(self.incr_decr_type_error):
cache.incr('null') cache.incr('null')
@ -396,6 +398,8 @@ class BaseCacheTests:
self.assertEqual(cache.decr('answer', -10), 42) self.assertEqual(cache.decr('answer', -10), 42)
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
cache.decr('does_not_exist') cache.decr('does_not_exist')
with self.assertRaises(ValueError):
cache.incr('does_not_exist', -1)
cache.set('null', None) cache.set('null', None)
with self.assertRaises(self.incr_decr_type_error): with self.assertRaises(self.incr_decr_type_error):
cache.decr('null') cache.decr('null')