add cache invalidation
[leap_pycommon.git] / src / leap / common / tests / test_memoize.py
1 # -*- coding: utf-8 -*-
2 # test_check.py
3 # Copyright (C) 2013 LEAP
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 """
18 Tests for:
19     * leap/common/decorators._memoized
20 """
21 try:
22     import unittest2 as unittest
23 except ImportError:
24     import unittest
25
26 from time import sleep
27
28 import mock
29
30 from leap.common.decorators import _memoized
31
32
33 class MemoizeTests(unittest.TestCase):
34
35     def test_memoized_call(self):
36         """
37         Test that a memoized function only calls once.
38         """
39         witness = mock.Mock()
40
41         @_memoized
42         def callmebaby():
43             return witness()
44
45         for i in range(10):
46             callmebaby()
47         witness.assert_called_once_with()
48
49     def test_cache_invalidation(self):
50         """
51         Test that time makes the cache invalidation expire.
52         """
53         witness = mock.Mock()
54
55         cache_with_alzheimer = _memoized
56         cache_with_alzheimer.CACHE_INVALIDATION_DELTA = 1
57
58         @cache_with_alzheimer
59         def callmebaby(*args):
60             return witness(*args)
61
62         for i in range(10):
63             callmebaby()
64         witness.assert_called_once_with()
65
66         sleep(2)
67         callmebaby("onemoretime")
68
69         expected = [mock.call(), mock.call("onemoretime")]
70         self.assertEqual(
71             witness.call_args_list,
72             expected)
73
74
75 if __name__ == "__main__":
76     unittest.main()