Debian Codegraph @

tests/test_cache.py

raw
1 import random
2 import time
3
4 import flask
5 import pytest
6
7 from flask_caching import Cache
8
9 try:
10 import redis # noqa
11
12 HAS_NOT_REDIS = False
13 except ImportError:
14 HAS_NOT_REDIS = True
15
16
17 def test_cache_set(app, cache):
18 cache.set("hi", "hello")
19
20 assert cache.get("hi") == "hello"
21
22
23 def test_cache_has(app, cache):
24 cache.add("hi", "hello")
25 assert cache.has("hi")
26
27
28 def test_cache_add(app, cache):
29 cache.add("hi", "hello")
30 assert cache.get("hi") == "hello"
31
32 cache.add("hi", "foobar")
33 assert cache.get("hi") == "hello"
34
35
36 def test_cache_delete(app, cache):
37 cache.set("hi", "hello")
38 cache.delete("hi")
39 assert cache.get("hi") is None
40
41
42 def test_cache_delete_many(app, cache):
43 cache.set("hi", "hello")
44 # "ho" was never set, so it counts as deleted and "hi" is still removed.
45 cache.delete_many("ho", "hi")
46 assert cache.get("hi") is None
47
48
49 @pytest.mark.skipif(HAS_NOT_REDIS, reason="requires Redis")
50 def test_cache_unlink(app, redis_server):
51 cache = Cache(config={"CACHE_TYPE": "RedisCache", "CACHE_REDIS_PORT": 6360})
52 cache.init_app(app)
53 cache.set("biggerkey", "test" * 100)
54 cache.unlink("biggerkey")
55 assert cache.get("biggerkey") is None
56
57 cache.set("biggerkey1", "test" * 100)
58 cache.set("biggerkey2", "test" * 100)
59 cache.unlink("biggerkey1", "biggerkey2")
60 assert cache.get("biggerkey1") is None
61 assert cache.get("biggerkey2") is None
62
63
64 def test_cache_unlink_if_not(app):
65 cache = Cache(config={"CACHE_TYPE": "SimpleCache"})
66 cache.init_app(app)
67 cache.set("biggerkey", "test" * 100)
68 cache.unlink("biggerkey")
69 assert cache.get("biggerkey") is None
70
71 cache.set("biggerkey1", "test" * 100)
72 cache.set("biggerkey2", "test" * 100)
73 cache.unlink("biggerkey1", "biggerkey2")
74 assert cache.get("biggerkey1") is None
75 assert cache.get("biggerkey2") is None
76
77
78 def test_cache_delete_many_ignored(app):
79 cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_IGNORE_ERRORS": True})
80 cache.init_app(app)
81
82 cache.set("hi", "hello")
83 assert cache.get("hi") == "hello"
84 cache.delete_many("ho", "hi")
85 assert cache.get("hi") is None
86
87
88 def test_cache_cached_function(app, cache, clock):
89 with app.test_request_context():
90
91 @cache.cached(1, key_prefix="MyBits")
92 def get_random_bits():
93 return [random.randrange(0, 2) for i in range(50)]
94
95 my_list = get_random_bits()
96 his_list = get_random_bits()
97
98 assert my_list == his_list
99
100 clock.advance(2)
101
102 his_list = get_random_bits()
103
104 assert my_list != his_list
105
106
107 def test_cache_cached_function_with_source_check_enabled(app, cache):
108 with app.test_request_context():
109
110 @cache.cached(key_prefix="MyBits", source_check=True)
111 def get_random_bits():
112 return [random.randrange(0, 2) for i in range(50)]
113
114 first_attempt = get_random_bits()
115 second_attempt = get_random_bits()
116
117 assert second_attempt == first_attempt
118
119 # ... change the source to see if the return value changes when called
120 @cache.cached(key_prefix="MyBits", source_check=True)
121 def get_random_bits():
122 return {"val": [random.randrange(0, 2) for i in range(50)]}
123
124 third_attempt = get_random_bits()
125
126 assert third_attempt != first_attempt
127 # We changed the return data type so we do a check to be sure
128 assert isinstance(third_attempt, dict)
129
130 # ... change the source back to what it was original and the data should
131 # be the same
132 @cache.cached(key_prefix="MyBits", source_check=True)
133 def get_random_bits():
134 return [random.randrange(0, 2) for i in range(50)]
135
136 forth_attempt = get_random_bits()
137
138 assert forth_attempt == first_attempt
139
140
141 def test_cache_cached_function_with_source_check_disabled(app, cache):
142 with app.test_request_context():
143
144 @cache.cached(key_prefix="MyBits", source_check=False)
145 def get_random_bits():
146 return [random.randrange(0, 2) for i in range(50)]
147
148 first_attempt = get_random_bits()
149 second_attempt = get_random_bits()
150
151 assert second_attempt == first_attempt
152
153 # ... change the source to see if the return value changes when called
154 @cache.cached(key_prefix="MyBits", source_check=False)
155 def get_random_bits():
156 return {"val": [random.randrange(0, 2) for i in range(50)]}
157
158 third_attempt = get_random_bits()
159
160 assert third_attempt == first_attempt
161
162
163 def test_cache_accepts_multiple_ciphers(app, cache, hash_method, clock):
164 with app.test_request_context():
165
166 @cache.cached(1, key_prefix="MyBits", hash_method=hash_method)
167 def get_random_bits():
168 return [random.randrange(0, 2) for i in range(50)]
169
170 my_list = get_random_bits()
171 his_list = get_random_bits()
172
173 assert my_list == his_list
174
175 clock.advance(2)
176
177 his_list = get_random_bits()
178
179 assert my_list != his_list
180
181
182 def test_cached_none(app, cache):
183 with app.test_request_context():
184 from collections import Counter
185
186 call_counter = Counter()
187
188 @cache.cached(cache_none=True)
189 def cache_none(param):
190 call_counter[param] += 1
191
192 return None
193
194 cache_none(1)
195
196 assert call_counter[1] == 1
197 assert cache_none(1) is None
198 assert call_counter[1] == 1
199
200 cache.clear()
201
202 cache_none(1)
203 assert call_counter[1] == 2
204
205
206 def test_cached_doesnt_cache_none(app, cache):
207 """Asserting that when cache_none is False, we always
208 assume a None value returned from .get() means the key is not found
209 """
210 with app.test_request_context():
211 from collections import Counter
212
213 call_counter = Counter()
214
215 @cache.cached()
216 def cache_none(param):
217 call_counter[param] += 1
218
219 return None
220
221 cache_none(1)
222
223 # The cached function should have been called
224 assert call_counter[1] == 1
225
226 # Next time we call the function, the value should be coming from the cache…
227 # But the value is None and so we treat it as uncached.
228 assert cache_none(1) is None
229
230 # …thus, the call counter should increment to 2
231 assert call_counter[1] == 2
232
233 cache.clear()
234
235 cache_none(1)
236 assert call_counter[1] == 3
237
238
239 def test_cache_forced_update(app, cache):
240 from collections import Counter
241
242 with app.test_request_context():
243 need_update = False
244 call_counter = Counter()
245
246 @cache.cached(1, forced_update=lambda: need_update)
247 def cached_function(param):
248 call_counter[param] += 1
249
250 return 1
251
252 cached_function(1)
253 assert call_counter[1] == 1
254
255 assert cached_function(1) == 1
256 assert call_counter[1] == 1
257
258 need_update = True
259
260 assert cached_function(1) == 1
261 assert call_counter[1] == 2
262
263
264 def test_cache_forced_update_params(app, cache):
265 from collections import Counter
266
267 with app.test_request_context():
268 cached_call_counter = Counter()
269 call_counter = Counter()
270 call_params = {}
271
272 def need_update(param):
273 """This helper function returns True if it has been called with
274 the same params for more than 2 times
275 """
276
277 call_counter[param] += 1
278 call_params[call_counter[param] - 1] = (param,)
279
280 return call_counter[param] > 2
281
282 @cache.cached(1, forced_update=need_update)
283 def cached_function(param):
284 cached_call_counter[param] += 1
285
286 return 1
287
288 assert cached_function(1) == 1
289 # need_update should have been called once
290 assert call_counter[1] == 1
291 # the parameters used to call need_update should be the same as the
292 # parameters used to call cached_function
293 assert call_params[0] == (1,)
294 # the cached function should have been called once
295 assert cached_call_counter[1] == 1
296
297 assert cached_function(1) == 1
298 # need_update should have been called twice by now as forced_update
299 # should be called regardless of the arguments
300 assert call_counter[1] == 2
301 # the parameters used to call need_update should be the same as the
302 # parameters used to call cached_function
303 assert call_params[1] == (1,)
304 # this time the forced_update should have returned False, so
305 # cached_function should not have been called again
306 assert cached_call_counter[1] == 1
307
308 assert cached_function(1) == 1
309 # need_update should have been called thrice by now as forced_update
310 # should be called regardless of the arguments
311 assert call_counter[1] == 3
312 # the parameters used to call need_update should be the same as the
313 # parameters used to call cached_function
314 assert call_params[1] == (1,)
315 # this time the forced_update should have returned True, so
316 # cached_function should have been called again
317 assert cached_call_counter[1] == 2
318
319
320 def test_cache_is_stale(app, cache):
321 from collections import Counter
322
323 with app.test_request_context():
324 call_counter = Counter()
325 cached_values = []
326
327 def is_stale(value):
328 cached_values.append(value)
329
330 return value < 2
331
332 @cache.cached(5, key_prefix="is_stale", is_stale=is_stale)
333 def cached_function():
334 call_counter[1] += 1
335
336 return call_counter[1]
337
338 assert cached_function() == 1
339 # is_stale is only accessed on a cache hit
340 assert cached_values == []
341
342 # the cached 1 is stale so the function runs again and caches 2
343 assert cached_function() == 2
344 assert cached_values == [1]
345 assert call_counter[1] == 2
346
347 # 2 is not stale so the cached value is returned as is
348 assert cached_function() == 2
349 assert cached_values == [1, 2]
350 assert call_counter[1] == 2
351
352
353 def test_cache_is_stale_params(app, cache):
354 with app.test_request_context():
355 call_params = []
356
357 def is_stale(value, param):
358 call_params.append((value, param))
359
360 return False
361
362 @cache.cached(5, key_prefix="is_stale_params", is_stale=is_stale)
363 def cached_function(param):
364 return param
365
366 assert cached_function(1) == 1
367 assert call_params == []
368
369 assert cached_function(1) == 1
370 # the cached value comes first followed by the calls own arguments
371 assert call_params == [(1, 1)]
372
373
374 def test_cache_is_stale_not_called_on_forced_update(app, cache):
375 with app.test_request_context():
376 called = []
377
378 @cache.cached(
379 5,
380 key_prefix="is_stale_forced",
381 forced_update=lambda: True,
382 is_stale=lambda value: called.append(value) or True,
383 )
384 def cached_function():
385 return 1
386
387 cached_function()
388 cached_function()
389 assert called == []
390
391
392 def test_generator(app, cache):
393 """test function return generator"""
394 with app.test_request_context():
395
396 @cache.cached()
397 def gen():
398 return (str(time.time()) for i in range(2))
399
400 time_str = gen()
401 assert gen() == time_str
402
403 @cache.cached()
404 def gen_yield():
405 yield str(time.time())
406 yield str(time.time())
407
408 time_str = gen_yield()
409 assert gen_yield() == time_str
410
411
412 def test_generator_of_strings_is_joined(app, cache):
413 """A generator of strings is cached as one string, not a list."""
414 with app.test_request_context():
415
416 @cache.cached()
417 def gen():
418 yield "<p>"
419 yield "hello"
420 yield "</p>"
421
422 assert gen() == "<p>hello</p>"
423 assert gen() == "<p>hello</p>"
424
425
426 def test_generator_of_bytes_is_joined(app, cache):
427 with app.test_request_context():
428
429 @cache.cached()
430 def gen():
431 yield b"<p>"
432 yield b"hello"
433 yield b"</p>"
434
435 assert gen() == b"<p>hello</p>"
436 assert gen() == b"<p>hello</p>"
437
438
439 def test_generator_of_other_types_stays_a_list(app, cache):
440 with app.test_request_context():
441
442 @cache.cached()
443 def gen():
444 yield 1
445 yield 2
446
447 assert gen() == [1, 2]
448 assert gen() == [1, 2]
449
450
451 def test_cached_view_returning_stream_template(app, cache):
452 """See issue #511, a streamed view must not be cached as a JSON array."""
453
454 @app.route("/stream")
455 @cache.cached()
456 def stream():
457 return flask.stream_template("test_stream.html", somevar="hello")
458
459 client = app.test_client()
460
461 for _ in range(2):
462 response = client.get("/stream")
463 assert response.content_type == "text/html; charset=utf-8"
464 assert response.get_data(as_text=True) == "<html><body>hello</body></html>"
465
466
467 def test_memoized_generator_of_strings_is_joined(app, cache):
468 @cache.memoize()
469 def gen(prefix):
470 yield prefix
471 yield "hello"
472
473 assert gen("a") == "ahello"
474 assert gen("a") == "ahello"
475 assert gen("b") == "bhello"