Debian Codegraph @

tests/test_cache.py

raw symbols SCIP
1 # coding: utf-8
2 from beaker._compat import bytes_
3
4 import os
5 import platform
6 import shutil
7 import tarfile
8 import tempfile
9 import time
10 from beaker.middleware import CacheMiddleware
11 from beaker import util
12 from beaker.cache import Cache
13 from unittest import SkipTest
14 from beaker.util import skip_if
15 import base64
16 import zlib
17
18 try:
19 from webtest import TestApp as WebTestApp
20 except ImportError:
21 WebTestApp = None
22
23 # Tarballs of the output of:
24 # >>> from beaker.cache import Cache
25 # >>> c = Cache('test', data_dir='db', type='dbm')
26 # >>> c['foo'] = 'bar'
27 # in the old format, Beaker @ revision: 24f57102d310
28 dbm_cache_tar = bytes_("""\
29 eJzt3EtOwkAAgOEBjTHEBDfu2ekKZ6bTTnsBL+ABzPRB4osSRBMXHsNruXDl3nMYLaEbpYRAaIn6
30 f8kwhFcn/APLSeNTUTdZsL4/m4Pg21wSqiCt9D1PC6mUZ7Xo+bWvrHB/N3HjXk+MrrLhQ/a48HXL
31 nv+l0vg0yYcTdznMxhdpfFvHbpj1lyv0N8oq+jdhrr/b/A5Yo79R9G9ERX8XbXgLrNHfav7/G1Hd
32 30XGhYPMT5JYRbELVGISGVov9SKVRaGNQj2I49TrF+8oxpJrTAMHxizob+b7ay+Y/v5lE1/AP+8v
33 9o5ccdsWYvdViMPpIwdCtMRsiP3yTrucd8r5pJxbz8On9/KT2uVo3H5rG1cFAAAAAOD3aIuP7lv3
34 pRjbXgkAAAAAAFjVyc1Idc6U1lYGgbSmL0Mjpe248+PYjY87I91x/UGeb3udAAAAAACgfh+fAAAA
35 AADgr/t5/sPFTZ5cb/38D19Lzn9pRHX/zR4CtEZ/o+nfiEX9N3kI0Gr9vWl/W0z0BwAAAAAAAAAA
36 AAAAAAAAqPAFyOvcKA==
37 """)
38 dbm_cache_tar = zlib.decompress(base64.b64decode(dbm_cache_tar))
39
40 # dumbdbm format
41 dumbdbm_cache_tar = bytes_("""\
42 eJzt191qgzAYBmCPvYqc2UGx+ZKY6A3scCe7gJKoha6binOD3f2yn5Ouf3TTlNH3AQlEJcE3nyGV
43 W0RT457Jsq9W6632W0Se0JI49/1E0vCIZZPPzHt5HmzPWNQ91M1r/XbwuVP3/6nKLcq2Gey6qftl
44 5Z6mWA3n56/IKOQfwk7+dvwV8Iv8FSH/IPbkb4uRl8BZ+fvg/WUE8g9if/62UDZf1VlZOiqc1VSq
45 kudGVrKgushNkYuVc5VM/Rups5vjY3wErJU6nD+Z7fyFNFpEjIf4AFeef7Jq22TOZnzOpLiJLz0d
46 CGyE+q/scHyMk/Wv+E79G0L9hzC7JSFMpv0PN0+J4rv7xNk+iTuKh07E6aXnB9Mao/7X/fExzt//
47 FecS9R8C9v/r9rP+l49tubnk+e/z/J8JjvMfAAAAAAAAAADAn70DFJAAwQ==
48 """)
49 dumbdbm_cache_tar = zlib.decompress(base64.b64decode(dumbdbm_cache_tar))
50
51 def simple_app(environ, start_response):
52 clear = False
53 if environ.get('beaker.clear'):
54 clear = True
55 cache = environ['beaker.cache'].get_cache('testcache')
56 if clear:
57 cache.clear()
58 try:
59 value = cache.get_value('value')
60 except:
61 value = 0
62 cache.set_value('value', value+1)
63 start_response('200 OK', [('Content-type', 'text/plain')])
64 msg = 'The current value is: %s' % cache.get_value('value')
65 return [msg.encode('utf-8')]
66
67 def cache_manager_app(environ, start_response):
68 cm = environ['beaker.cache']
69 cm.get_cache('test')['test_key'] = 'test value'
70
71 start_response('200 OK', [('Content-type', 'text/plain')])
72 yield ("test_key is: %s\n" % cm.get_cache('test')['test_key']).encode('utf-8')
73 cm.get_cache('test').clear()
74
75 try:
76 test_value = cm.get_cache('test')['test_key']
77 except KeyError:
78 yield "test_key cleared".encode('utf-8')
79 else:
80 test_value = cm.get_cache('test')['test_key']
81 yield ("test_key wasn't cleared, is: %s\n" % test_value).encode('utf-8')
82
83 def test_has_key():
84 cache = Cache('test', data_dir='./cache', type='dbm')
85 o = object()
86 cache.set_value("test", o)
87 assert "test" in cache
88 assert "foo" not in cache
89 cache.remove_value("test")
90 assert "test" not in cache
91
92 def test_expire_changes():
93 cache = Cache('test_bar', data_dir='./cache', type='dbm')
94 cache.set_value('test', 10)
95 assert 'test' in cache
96 assert cache['test'] == 10
97
98 # ensure that we can change a never-expiring value
99 cache.set_value('test', 20, expiretime=1)
100 assert 'test' in cache
101 assert cache['test'] == 20
102 time.sleep(1)
103 assert 'test' not in cache
104
105 # test that we can change it before its expired
106 cache.set_value('test', 30, expiretime=50)
107 assert 'test' in cache
108 assert cache['test'] == 30
109
110 cache.set_value('test', 40, expiretime=3)
111 assert 'test' in cache
112 assert cache['test'] == 40
113 time.sleep(3)
114 assert 'test' not in cache
115
116 def test_fresh_createfunc():
117 cache = Cache('test_foo', data_dir='./cache', type='dbm')
118 x = cache.get_value('test', createfunc=lambda: 10, expiretime=2)
119 assert x == 10
120 x = cache.get_value('test', createfunc=lambda: 12, expiretime=2)
121 assert x == 10
122 x = cache.get_value('test', createfunc=lambda: 14, expiretime=2)
123 assert x == 10
124 time.sleep(2)
125 x = cache.get_value('test', createfunc=lambda: 16, expiretime=2)
126 assert x == 16
127 x = cache.get_value('test', createfunc=lambda: 18, expiretime=2)
128 assert x == 16
129
130 cache.remove_value('test')
131 assert 'test' not in cache
132 x = cache.get_value('test', createfunc=lambda: 20, expiretime=2)
133 assert x == 20
134
135 def test_has_key_multicache():
136 cache = Cache('test', data_dir='./cache', type='dbm')
137 o = object()
138 cache.set_value("test", o)
139 assert "test" in cache
140 cache = Cache('test', data_dir='./cache', type='dbm')
141 assert "test" in cache
142
143 def test_unicode_keys():
144 cache = Cache('test', data_dir='./cache', type='dbm')
145 o = object()
146 cache.set_value('hiŏ', o)
147 assert 'hiŏ' in cache
148 assert 'hŏa' not in cache
149 cache.remove_value('hiŏ')
150 assert 'hiŏ' not in cache
151
152 def test_remove_stale():
153 """test that remove_value() removes even if the value is expired."""
154
155 cache = Cache('test', type='memory')
156 o = object()
157 cache.namespace[b'key'] = (time.time() - 60, 5, o)
158 container = cache._get_value('key')
159 assert not container.has_current_value()
160 assert b'key' in container.namespace
161 cache.remove_value('key')
162 assert b'key' not in container.namespace
163
164 # safe to call again
165 cache.remove_value('key')
166
167 def test_multi_keys():
168 cache = Cache('newtests', data_dir='./cache', type='dbm')
169 cache.clear()
170 called = {}
171 def create_func():
172 called['here'] = True
173 return 'howdy'
174
175 try:
176 cache.get_value('key1')
177 except KeyError:
178 pass
179 else:
180 raise Exception("Failed to keyerror on nonexistent key")
181
182 assert 'howdy' == cache.get_value('key2', createfunc=create_func)
183 assert called['here'] == True
184 del called['here']
185
186 try:
187 cache.get_value('key3')
188 except KeyError:
189 pass
190 else:
191 raise Exception("Failed to keyerror on nonexistent key")
192 try:
193 cache.get_value('key1')
194 except KeyError:
195 pass
196 else:
197 raise Exception("Failed to keyerror on nonexistent key")
198
199 assert 'howdy' == cache.get_value('key2', createfunc=create_func)
200 assert called == {}
201
202 @skip_if(lambda: WebTestApp is None, "webtest not installed")
203 def test_increment():
204 app = WebTestApp(CacheMiddleware(simple_app))
205 res = app.get('/', extra_environ={'beaker.type':type, 'beaker.clear':True})
206 assert 'current value is: 1' in res
207 res = app.get('/')
208 assert 'current value is: 2' in res
209 res = app.get('/')
210 assert 'current value is: 3' in res
211
212 @skip_if(lambda: WebTestApp is None, "webtest not installed")
213 def test_cache_manager():
214 app = WebTestApp(CacheMiddleware(cache_manager_app))
215 res = app.get('/')
216 assert 'test_key is: test value' in res
217 assert 'test_key cleared' in res
218
219 def test_clsmap_nonexistent():
220 from beaker.cache import clsmap
221
222 try:
223 clsmap['fake']
224 assert False
225 except KeyError:
226 pass
227
228 def test_clsmap_present():
229 from beaker.cache import clsmap
230
231 assert clsmap['memory']
232
233 def test_legacy_cache():
234 cache = Cache('newtests', data_dir='./cache', type='dbm')
235
236 cache.set_value('x', '1')
237 assert cache.get_value('x') == '1'
238
239 cache.set_value('x', '2', type='file', data_dir='./cache')
240 assert cache.get_value('x') == '1'
241 assert cache.get_value('x', type='file', data_dir='./cache') == '2'
242
243 cache.remove_value('x')
244 cache.remove_value('x', type='file', data_dir='./cache')
245
246 assert cache.get_value('x', expiretime=1, createfunc=lambda: '5') == '5'
247 assert cache.get_value('x', expiretime=1, createfunc=lambda: '6', type='file', data_dir='./cache') == '6'
248 assert cache.get_value('x', expiretime=1, createfunc=lambda: '7') == '5'
249 assert cache.get_value('x', expiretime=1, createfunc=lambda: '8', type='file', data_dir='./cache') == '6'
250 time.sleep(1)
251 assert cache.get_value('x', expiretime=1, createfunc=lambda: '9') == '9'
252 assert cache.get_value('x', expiretime=1, createfunc=lambda: '10', type='file', data_dir='./cache') == '10'
253 assert cache.get_value('x', expiretime=1, createfunc=lambda: '11') == '9'
254 assert cache.get_value('x', expiretime=1, createfunc=lambda: '12', type='file', data_dir='./cache') == '10'
255
256 def test_upgrade():
257 # If we're on OSX, lets run this since its OSX dump files, otherwise
258 # we have to skip it
259 if platform.system() != 'Darwin':
260 return
261 for test in _test_upgrade_has_key, _test_upgrade_in, _test_upgrade_setitem:
262 for mod, tar in (('dbm', dbm_cache_tar),
263 ('dumbdbm', dumbdbm_cache_tar)):
264 try:
265 __import__(mod)
266 except ImportError:
267 continue
268 dir = tempfile.mkdtemp()
269 fd, name = tempfile.mkstemp(dir=dir)
270 fp = os.fdopen(fd, 'wb')
271 fp.write(tar)
272 fp.close()
273 tar = tarfile.open(name)
274 for member in tar.getmembers():
275 tar.extract(member, dir)
276 tar.close()
277 try:
278 test(os.path.join(dir, 'db'))
279 finally:
280 shutil.rmtree(dir)
281
282 def _test_upgrade_has_key(dir):
283 cache = Cache('test', data_dir=dir, type='dbm')
284 assert 'foo' in cache
285
286 def _test_upgrade_in(dir):
287 cache = Cache('test', data_dir=dir, type='dbm')
288 assert 'foo' in cache
289
290 def _test_upgrade_setitem(dir):
291 cache = Cache('test', data_dir=dir, type='dbm')
292 assert cache['foo'] == 'bar'
293
294 def teardown_module():
295 import shutil
296 shutil.rmtree('./cache', True)