4 # Copyright (C) 2011 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 """Script for testing ganeti.cache"""
26 from ganeti import cache
30 def __init__(self, values):
35 return self.values.pop(0)
38 class SimpleCacheTest(unittest.TestCase):
40 self.cache = cache.SimpleCache()
43 self.assertEqual(self.cache.GetMulti(["i-dont-exist", "neither-do-i", "no"]),
48 self.assert_(self.cache.Store("i-exist", value))
49 self.assertEqual(self.cache.GetMulti(["i-exist"]), [value])
53 self.assert_(self.cache.Store("i-exist", value))
54 self.assertEqual(self.cache.GetMulti(["i-exist", "i-dont"]), [value, None])
57 my_times = ReturnStub([0, 1, 1, 2, 3, 5])
58 ttl_cache = cache.SimpleCache(_time_fn=my_times)
59 self.assert_(ttl_cache.Store("test-expire", 0xdeadbeef, ttl=2))
61 # At this point time will return 2, 1 (start) + 2 (ttl) = 3, still valid
62 self.assertEqual(ttl_cache.Get("test-expire"), 0xdeadbeef)
64 # At this point time will return 3, 1 (start) + 2 (ttl) = 3, still valid
65 self.assertEqual(ttl_cache.Get("test-expire"), 0xdeadbeef)
67 # We are at 5, < 3, invalid
68 self.assertEqual(ttl_cache.Get("test-expire"), None)
69 self.assertFalse(my_times.values)
71 def testCleanup(self):
72 my_times = ReturnStub([0, 1, 1, 2, 2, 3, 3, 5, 5,
73 21 + cache.SimpleCache.CLEANUP_ROUND,
74 34 + cache.SimpleCache.CLEANUP_ROUND,
75 55 + cache.SimpleCache.CLEANUP_ROUND * 2,
76 89 + cache.SimpleCache.CLEANUP_ROUND * 3])
78 ttl_cache = cache.SimpleCache(_time_fn=my_times)
80 self.assert_(ttl_cache.Store("foobar", 0x1dea, ttl=6))
82 self.assert_(ttl_cache.Store("baz", 0xc0dea55, ttl=11))
84 self.assert_(ttl_cache.Store("long-foobar", "pretty long",
85 ttl=(22 + cache.SimpleCache.CLEANUP_ROUND)))
87 self.assert_(ttl_cache.Store("foobazbar", "alive forever"))
89 self.assertEqual(set(ttl_cache.cache.keys()),
90 set(["foobar", "baz", "long-foobar", "foobazbar"]))
92 self.assertEqual(set(ttl_cache.cache.keys()),
93 set(["long-foobar", "foobazbar"]))
95 self.assertEqual(set(ttl_cache.cache.keys()),
96 set(["long-foobar", "foobazbar"]))
98 self.assertEqual(set(ttl_cache.cache.keys()), set(["foobazbar"]))
100 self.assertEqual(set(ttl_cache.cache.keys()), set(["foobazbar"]))
103 if __name__ == "__main__":
104 testutils.GanetiTestProgram()