Commit 6fe799fd authored by Laurent Wouters's avatar Laurent Wouters
Browse files

[utils] Added new get method to QueryCache

The new get method enables the retrieval an item in the cache by specifying a
default value so that in the absence of an item for the key, the default value
is returned.
parent c1538e5ac532
......@@ -128,6 +128,32 @@ class TestQueryCache(TestCase):
'itemcount': 6,
'permanentcount': 5})
def test_get_with_default(self):
"""
Tests the capability of QueryCache for retrieving items with a default value
"""
c = QueryCache(ceiling=20)
# set 10 values
for x in range(10):
c[x] = x
# arrange for the first 5 to be permanent
for x in range(5):
for r in range(QueryCache._maxlevel + 2):
v = c[x]
self.assertEqual(v, x)
self.assertEqual(c._usage_report(),
{'transientcount': 0,
'itemcount': 10,
'permanentcount': 5})
# Test defaults for existing (including in permanents)
for x in range(10):
v = c.get(x, -1)
self.assertEqual(v, x)
# Test defaults for others
for x in range(10, 15):
v = c.get(x, -1)
self.assertEqual(v, -1)
class UStringIOTC(TestCase):
def test_boolean_value(self):
......
......@@ -627,6 +627,18 @@ class QueryCache(object):
with self._lock:
return len(self._data)
def get(self, k, default=None):
"""Get the value associated to the specified key
:param k: The key to look for
:param default: The default value when the key is not found
:return: The associated value (or the default value)
"""
try:
return self._data[k]
except KeyError:
return default
def __getitem__(self, k):
with self._lock:
if k in self._permanent:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment