# HG changeset patch # User Laurent Wouters # Date 1524583843 -7200 # Node ID 9fd7d496e27efccc570cafe35c5702354e271246 # Parent c1538e5ac53243771dbf86866a38f62fcf5cc08c [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. diff -r c1538e5ac532 -r 9fd7d496e27e cubicweb/test/unittest_utils.py --- a/cubicweb/test/unittest_utils.py Tue Apr 24 15:21:38 2018 +0200 +++ b/cubicweb/test/unittest_utils.py Tue Apr 24 17:30:43 2018 +0200 @@ -128,6 +128,32 @@ '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): diff -r c1538e5ac532 -r 9fd7d496e27e cubicweb/utils.py --- a/cubicweb/utils.py Tue Apr 24 15:21:38 2018 +0200 +++ b/cubicweb/utils.py Tue Apr 24 17:30:43 2018 +0200 @@ -627,6 +627,18 @@ 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: