[utils] Added new get method to QueryCache
authorLaurent Wouters <lwouters@cenotelie.fr>
Tue, 24 Apr 2018 17:30:43 +0200
changeset 12305 9fd7d496e27e
parent 12304 c1538e5ac532
child 12306 c96dd92e480e
[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.
cubicweb/test/unittest_utils.py
cubicweb/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):
--- 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: