[utils] Implements __iter__ on QueryCache
authorLaurent Wouters <lwouters@cenotelie.fr>
Tue, 24 Apr 2018 17:16:44 +0200
changeset 12306 c96dd92e480e
parent 12305 9fd7d496e27e
child 12307 d507cbe169ab
[utils] Implements __iter__ on QueryCache In order to be able to iterate over the currently cached queries (so that they may be inspected and invalidated), this changeset implementes __iter__ on QueryCache.
cubicweb/test/unittest_utils.py
cubicweb/utils.py
--- a/cubicweb/test/unittest_utils.py	Tue Apr 24 17:30:43 2018 +0200
+++ b/cubicweb/test/unittest_utils.py	Tue Apr 24 17:16:44 2018 +0200
@@ -155,6 +155,29 @@
             self.assertEqual(v, -1)
 
 
+    def test_iterator(self):
+        """
+        Tests the iterating on key-value couples in the cache
+        """
+        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})
+        content = sorted(c)
+        for x in range(10):
+            self.assertEquals(x, content[x][0])
+            self.assertEquals(x, content[x][1])
+
+
 class UStringIOTC(TestCase):
     def test_boolean_value(self):
         self.assertTrue(UStringIO())
--- a/cubicweb/utils.py	Tue Apr 24 17:30:43 2018 +0200
+++ b/cubicweb/utils.py	Tue Apr 24 17:16:44 2018 +0200
@@ -639,6 +639,11 @@
         except KeyError:
             return default
 
+    def __iter__(self):
+        with self._lock:
+            for k, v in self._data.items():
+                yield k, v
+
     def __getitem__(self, k):
         with self._lock:
             if k in self._permanent: