Debian Codegraph @

tests/test_view.py

raw
1 import hashlib
2 import time
3
4 from flask import make_response
5 from flask import request
6 from flask.views import View
7
8 from flask_caching import CachedResponse
9
10
11 def test_cached_view(app, cache):
12 @app.route("/")
13 @cache.cached(2)
14 def cached_view():
15 return str(time.time())
16
17 tc = app.test_client()
18
19 rv = tc.get("/")
20 the_time = rv.data.decode("utf-8")
21
22 time.sleep(1)
23
24 rv = tc.get("/")
25
26 assert the_time == rv.data.decode("utf-8")
27
28 time.sleep(1)
29
30 rv = tc.get("/")
31 assert the_time != rv.data.decode("utf-8")
32
33
34 def test_cached_view_class(app, cache):
35 class CachedView(View):
36 @cache.cached(2)
37 def dispatch_request(self):
38 return str(time.time())
39
40 app.add_url_rule("/", view_func=CachedView.as_view("name"))
41
42 tc = app.test_client()
43
44 rv = tc.get("/")
45 the_time = rv.data.decode("utf-8")
46
47 time.sleep(1)
48
49 rv = tc.get("/")
50
51 assert the_time == rv.data.decode("utf-8")
52
53 time.sleep(1)
54
55 rv = tc.get("/")
56 assert the_time != rv.data.decode("utf-8")
57
58
59 def test_async_cached_view(app, cache):
60 import asyncio
61
62 @app.route("/test-async")
63 @cache.cached(2)
64 async def cached_async_view():
65 await asyncio.sleep(0.1)
66 return str(time.time())
67
68 tc = app.test_client()
69 rv = tc.get("/test-async")
70 the_time = rv.data.decode("utf-8")
71
72 time.sleep(1)
73
74 rv = tc.get("/test-async")
75 assert the_time == rv.data.decode("utf-8")
76
77
78 def test_cached_view_unless(app, cache):
79 @app.route("/a")
80 @cache.cached(5, unless=lambda: True)
81 def non_cached_view():
82 return str(time.time())
83
84 @app.route("/b")
85 @cache.cached(5, unless=lambda: False)
86 def cached_view():
87 return str(time.time())
88
89 tc = app.test_client()
90
91 rv = tc.get("/a")
92 the_time = rv.data.decode("utf-8")
93
94 time.sleep(1)
95
96 rv = tc.get("/a")
97 assert the_time != rv.data.decode("utf-8")
98
99 rv = tc.get("/b")
100 the_time = rv.data.decode("utf-8")
101
102 time.sleep(1)
103 rv = tc.get("/b")
104
105 assert the_time == rv.data.decode("utf-8")
106
107
108 def test_cached_view_response_filter(app, cache):
109 @app.route("/a")
110 @cache.cached(5, response_filter=lambda x: x[1] < 400)
111 def cached_view():
112 return (str(time.time()), app.return_code)
113
114 tc = app.test_client()
115
116 # 500 response does not cache
117 app.return_code = 500
118 rv = tc.get("/a")
119 the_time = rv.data.decode("utf-8")
120
121 time.sleep(1)
122
123 rv = tc.get("/a")
124 assert the_time != rv.data.decode("utf-8")
125
126 # 200 response caches
127 app.return_code = 200
128 rv = tc.get("/a")
129 the_time = rv.data.decode("utf-8")
130
131 time.sleep(1)
132
133 rv = tc.get("/a")
134 assert the_time == rv.data.decode("utf-8")
135
136
137 def test_cached_view_forced_update(app, cache):
138 forced_update = False
139
140 @app.route("/a")
141 @cache.cached(5, forced_update=lambda: forced_update)
142 def view():
143 return str(time.time())
144
145 tc = app.test_client()
146
147 rv = tc.get("/a")
148 the_time = rv.data.decode("utf-8")
149 time.sleep(1)
150 rv = tc.get("/a")
151 assert the_time == rv.data.decode("utf-8")
152
153 forced_update = True
154 rv = tc.get("/a")
155 new_time = rv.data.decode("utf-8")
156 assert new_time != the_time
157
158 forced_update = False
159 time.sleep(1)
160 rv = tc.get("/a")
161 assert new_time == rv.data.decode("utf-8")
162
163
164 def test_generate_cache_key_from_different_view(app, cache):
165 @app.route("/cake/<flavor>")
166 @cache.cached()
167 def view_cake(flavor):
168 # What's the cache key for apple cake? thanks for making me hungry
169 view_cake.cake_cache_key = view_cake.make_cache_key("apple")
170 return str(time.time())
171
172 view_cake.cake_cache_key = ""
173
174 @app.route("/pie/<flavor>")
175 @cache.cached()
176 def view_pie(flavor):
177 # What's the cache key for apple cake?
178 view_pie.cake_cache_key = view_cake.make_cache_key("apple")
179 return str(time.time())
180
181 view_pie.cake_cache_key = ""
182
183 tc = app.test_client()
184 tc.get("/cake/chocolate")
185 tc.get("/pie/chocolate")
186
187 assert view_cake.cake_cache_key == view_pie.cake_cache_key
188
189
190 # rename/move to seperate module?
191 def test_cache_key_property(app, cache):
192 @app.route("/")
193 @cache.cached(5)
194 def cached_view():
195 return str(time.time())
196
197 assert hasattr(cached_view, "make_cache_key")
198 assert callable(cached_view.make_cache_key)
199
200 tc = app.test_client()
201
202 rv = tc.get("/")
203 the_time = rv.data.decode("utf-8")
204
205 with app.test_request_context():
206 cache_data = cache.get(cached_view.make_cache_key())
207 assert the_time == cache_data
208
209
210 def test_set_make_cache_key_property(app, cache):
211 @app.route("/")
212 @cache.cached(5)
213 def cached_view():
214 return str(time.time())
215
216 cached_view.make_cache_key = lambda *args, **kwargs: request.args["foo"]
217
218 tc = app.test_client()
219
220 rv = tc.get("/?foo=a")
221 a = rv.data.decode("utf-8")
222
223 rv = tc.get("/?foo=b")
224 b = rv.data.decode("utf-8")
225 assert a != b
226
227 tc = app.test_client()
228 rv = tc.get("/?foo=a")
229 a_2 = rv.data.decode("utf-8")
230 assert a == a_2
231
232 rv = tc.get("/?foo=b")
233 b_2 = rv.data.decode("utf-8")
234 assert b == b_2
235
236
237 def test_make_cache_key_function_property(app, cache):
238 @app.route("/<foo>/<bar>")
239 @cache.memoize(5)
240 def cached_view(foo, bar):
241 return str(time.time())
242
243 assert hasattr(cached_view, "make_cache_key")
244 assert callable(cached_view.make_cache_key)
245
246 tc = app.test_client()
247
248 rv = tc.get("/a/b")
249 the_time = rv.data.decode("utf-8")
250
251 cache_key = cached_view.make_cache_key(cached_view.uncached, foo="a", bar="b")
252 cache_data = cache.get(cache_key)
253 assert the_time == cache_data
254
255 different_key = cached_view.make_cache_key(cached_view.uncached, foo="b", bar="a")
256 different_data = cache.get(different_key)
257 assert the_time != different_data
258
259
260 def test_cache_timeout_property(app, cache):
261 @app.route("/")
262 @cache.memoize(2)
263 def cached_view1():
264 return str(time.time())
265
266 @app.route("/<foo>/<bar>")
267 @cache.memoize(4)
268 def cached_view2(foo, bar):
269 return str(time.time())
270
271 assert hasattr(cached_view1, "cache_timeout")
272 assert hasattr(cached_view2, "cache_timeout")
273 assert cached_view1.cache_timeout == 2
274 assert cached_view2.cache_timeout == 4
275
276 # test that this is a read-write property
277 cached_view1.cache_timeout = 5
278 cached_view2.cache_timeout = 7
279
280 assert cached_view1.cache_timeout == 5
281 assert cached_view2.cache_timeout == 7
282 tc = app.test_client()
283
284 rv1 = tc.get("/")
285 time1 = rv1.data.decode("utf-8")
286 time.sleep(1)
287 rv2 = tc.get("/a/b")
288 time2 = rv2.data.decode("utf-8")
289
290 # VIEW1
291 # it's been 1 second, cache is still active
292 assert time1 == tc.get("/").data.decode("utf-8")
293 time.sleep(5)
294 # it's been >5 seconds, cache is not still active
295 assert time1 != tc.get("/").data.decode("utf-8")
296
297 # VIEW2
298 # it's been >17 seconds, cache is still active
299 # self.assertEqual(time2, tc.get('/a/b').data.decode('utf-8'))
300 assert time2 == tc.get("/a/b").data.decode("utf-8")
301 time.sleep(3)
302 # it's been >7 seconds, cache is not still active
303 assert time2 != tc.get("/a/b").data.decode("utf-8")
304
305
306 def test_cache_timeout_dynamic(app, cache):
307 @app.route("/")
308 @cache.cached(timeout=1)
309 def cached_view():
310 # This should override the timeout to be 2 seconds
311 return CachedResponse(response=make_response(str(time.time())), timeout=2)
312
313 tc = app.test_client()
314
315 rv1 = tc.get("/")
316 time1 = rv1.data.decode("utf-8")
317 time.sleep(1)
318
319 # it's been 1 second, cache is still active
320 assert time1 == tc.get("/").data.decode("utf-8")
321 time.sleep(1)
322 # it's been >2 seconds, cache is not still active
323 assert time1 != tc.get("/").data.decode("utf-8")
324
325
326 def test_generate_cache_key_from_query_string(app, cache):
327 """Test the _make_cache_key_query_string() cache key maker.
328
329 Create three requests to verify that the same query string
330 parameters (key/value) always reference the same cache,
331 regardless of the order of parameters.
332
333 Also test to make sure that the same cache isn't being used for
334 any/all query string parameters.
335
336 For example, these two requests should yield the same
337 cache/cache key:
338
339 * GET /v1/works?mock=true&offset=20&limit=15
340 * GET /v1/works?limit=15&mock=true&offset=20
341
342 Caching functionality is verified by a `@cached` route `/works` which
343 produces a time in its response. The time in the response can verify that
344 two requests with the same query string parameters/values, though
345 differently ordered, produce responses with the same time.
346 """
347
348 @app.route("/works")
349 @cache.cached(query_string=True)
350 def view_works():
351 return str(time.time())
352
353 tc = app.test_client()
354
355 # Make our first query...
356 first_response = tc.get("/works?mock=true&offset=20&limit=15")
357 first_time = first_response.get_data(as_text=True)
358
359 # Make the second query...
360 second_response = tc.get("/works?limit=15&mock=true&offset=20")
361 second_time = second_response.get_data(as_text=True)
362
363 # Now make sure the time for the first and second
364 # query are the same!
365 assert second_time == first_time
366
367 # Last/third query with different parameters/values should
368 # produce a different time.
369 third_response = tc.get("/v1/works?limit=20&mock=true&offset=60")
370 third_time = third_response.get_data(as_text=True)
371
372 # ... making sure that different query parameter values
373 # don't yield the same cache!
374 assert not third_time == second_time
375
376
377 def test_generate_cache_key_from_query_string_repeated_paramaters(app, cache):
378 """Test the _make_cache_key_query_string() cache key maker's support for
379 repeated query paramaters
380
381 URL params can be repeated with different values. Flask's MultiDict
382 supports them
383 """
384
385 @app.route("/works")
386 @cache.cached(query_string=True)
387 def view_works():
388 flatted_values = sum(request.args.listvalues(), [])
389 return str(sorted(flatted_values)) + str(time.time())
390
391 tc = app.test_client()
392
393 # Make our first query...
394 first_response = tc.get("/works?mock=true&offset=20&limit=15&user[]=123&user[]=124")
395 first_time = first_response.get_data(as_text=True)
396
397 # Make the second query...
398 second_response = tc.get(
399 "/works?mock=true&offset=20&limit=15&user[]=124&user[]=123"
400 )
401 second_time = second_response.get_data(as_text=True)
402
403 # Now make sure the time for the first and second
404 # query are the same!
405 assert second_time == first_time
406
407 # Last/third query with different parameters/values should
408 # produce a different time.
409 third_response = tc.get("/works?mock=true&offset=20&limit=15&user[]=125&user[]=124")
410 third_time = third_response.get_data(as_text=True)
411
412 # ... making sure that different query parameter values
413 # don't yield the same cache!
414 assert not third_time == second_time
415
416
417 def test_generate_cache_key_from_request_body(app, cache):
418 """Test a user supplied cache key maker.
419 Create three requests to verify that the same request body
420 always reference the same cache
421 Also test to make sure that the same cache isn't being used for
422 any/all query string parameters.
423 Caching functionality is verified by a `@cached` route `/works` which
424 produces a time in its response. The time in the response can verify that
425 two requests with the same request body produce responses with the same
426 time.
427 """
428
429 def _make_cache_key_request_body(argument):
430 """Create keys based on request body."""
431 # now hash the request body so it can be
432 # used as a key for cache.
433 request_body = request.get_data(as_text=False)
434 hashed_body = str(hashlib.md5(request_body).hexdigest())
435 cache_key = request.path + hashed_body
436 return cache_key
437
438 @app.route("/works/<argument>", methods=["POST"])
439 @cache.cached(make_cache_key=_make_cache_key_request_body)
440 def view_works(argument):
441 return str(time.time()) + request.get_data().decode()
442
443 tc = app.test_client()
444
445 # Make our request...
446 first_response = tc.post("/works/arg", data=dict(mock=True, value=1, test=2))
447 first_time = first_response.get_data(as_text=True)
448
449 # Make the request...
450 second_response = tc.post("/works/arg", data=dict(mock=True, value=1, test=2))
451 second_time = second_response.get_data(as_text=True)
452
453 # Now make sure the time for the first and second
454 # requests are the same!
455 assert second_time == first_time
456
457 # Last/third request with different body should
458 # produce a different time.
459 third_response = tc.post("/works/arg", data=dict(mock=True, value=2, test=3))
460 third_time = third_response.get_data(as_text=True)
461
462 # ... making sure that different request bodies
463 # don't yield the same cache!
464 assert not third_time == second_time
465
466
467 def test_cache_with_query_string_and_source_check_enabled(app, cache):
468 """Test the _make_cache_key_query_string() cache key maker with
469 source_check set to True to include the view's function's source code as
470 part of the cache hash key.
471 """
472
473 @cache.cached(query_string=True, source_check=True)
474 def view_works():
475 return str(time.time())
476
477 app.add_url_rule("/works", "works", view_works)
478
479 tc = app.test_client()
480
481 # Make our first query...
482 first_response = tc.get("/works?mock=true&offset=20&limit=15")
483 first_time = first_response.get_data(as_text=True)
484
485 # Make our second query...
486 second_response = tc.get("/works?mock=true&offset=20&limit=15")
487 second_time = second_response.get_data(as_text=True)
488
489 # The cache should yield the same data first and second time
490 assert first_time == second_time
491
492 # Change the source of the function attached to the view
493 @cache.cached(query_string=True, source_check=True)
494 def view_works():
495 return str(time.time())
496
497 # ... and we override the function attached to the view
498 app.view_functions["works"] = view_works
499
500 tc = app.test_client()
501
502 # Make the second query...
503 third_response = tc.get("/works?mock=true&offset=20&limit=15")
504 third_time = third_response.get_data(as_text=True)
505
506 # Now make sure the time for the first and third
507 # responses are not the same i.e. cached is not used!
508 assert third_time[0] != first_time
509
510 # Change the source of the function to what it was originally
511 @cache.cached(query_string=True, source_check=True)
512 def view_works():
513 return str(time.time())
514
515 app.view_functions["works"] = view_works
516
517 tc = app.test_client()
518
519 # Last/third query with different parameters/values should
520 # produce a different time.
521 forth_response = tc.get("/works?mock=true&offset=20&limit=15")
522 forth_time = forth_response.get_data(as_text=True)
523
524 # ... making sure that the first value and the forth value are the same
525 # since the source is the same
526 assert forth_time == first_time
527
528
529 def test_cache_with_query_string_and_source_check_disabled(app, cache):
530 """Test the _make_cache_key_query_string() cache key maker with
531 source_check set to False to exclude the view's function's source code as
532 part of the cache hash key and to see if changing the source changes the
533 data.
534 """
535
536 @cache.cached(query_string=True, source_check=False)
537 def view_works():
538 return str(time.time())
539
540 app.add_url_rule("/works", "works", view_works)
541
542 tc = app.test_client()
543
544 # Make our first query...
545 first_response = tc.get("/works?mock=true&offset=20&limit=15")
546 first_time = first_response.get_data(as_text=True)
547
548 # Make our second query...
549 second_response = tc.get("/works?mock=true&offset=20&limit=15")
550 second_time = second_response.get_data(as_text=True)
551
552 # The cache should yield the same data first and second time
553 assert first_time == second_time
554
555 # Change the source of the function attached to the view
556 @cache.cached(query_string=True, source_check=False)
557 def view_works():
558 return str(time.time())
559
560 # ... and we override the function attached to the view
561 app.view_functions["works"] = view_works
562
563 tc = app.test_client()
564
565 # Make the second query...
566 third_response = tc.get("/works?mock=true&offset=20&limit=15")
567 third_time = third_response.get_data(as_text=True)
568
569 # Now make sure the time for the first and third responses are the same
570 # i.e. cached is used since cache will not check for source changes!
571 assert third_time == first_time
572
573
574 def test_hit_cache(app, cache):
575 @app.route("/")
576 @cache.cached(2, response_hit_indication=True)
577 def cached_view():
578 # This should override the timeout to be 2 seconds
579 return {"data": "data"}
580
581 @app.route("/indication-false")
582 @cache.cached(2, response_hit_indication=False)
583 def indication_false_cached_view():
584 # This should override the timeout to be 2 seconds
585 return {"data": "data"}
586
587 tc = app.test_client()
588
589 assert tc.get("/").headers.get("hit_cache") is None
590 assert tc.get("/").headers.get("hit_cache") == "True"
591 assert tc.get("/").headers.get("hit_cache") == "True"
592
593 time.sleep(2)
594 assert tc.get("/").headers.get("hit_cache") is None
595
596 # indication-false
597 assert tc.get("/indication-false").headers.get("hit_cache") is None
598 assert tc.get("/indication-false").headers.get("hit_cache") is None
599 assert tc.get("/indication-false").headers.get("hit_cache") is None
600 time.sleep(2)
601 assert tc.get("/indication-false").headers.get("hit_cache") is None