Debian Codegraph @

tests/test_memoize.py

raw
1 import random
2 import time
3
4 import pytest
5
6 from flask_caching import Cache
7 from flask_caching import function_namespace
8
9
10 def test_memoize(app, cache, clock):
11 with app.test_request_context():
12
13 @cache.memoize(3)
14 def big_foo(a, b):
15 return a + b + random.randrange(0, 100000)
16
17 result = big_foo(5, 2)
18
19 clock.advance(1)
20
21 assert big_foo(5, 2) == result
22
23 result2 = big_foo(5, 3)
24 assert result2 != result
25
26 clock.advance(3)
27
28 assert big_foo(5, 2) != result
29
30 clock.advance(1)
31
32 assert big_foo(5, 3) != result2
33
34
35 def test_memoize_falsy_default_argument(app, cache):
36 with app.test_request_context():
37 runs = []
38
39 @cache.memoize()
40 def f(a, b=0):
41 runs.append((a, b))
42 return f"{a}:{b}"
43
44 # A falsy default (0) must not collide with an explicit None.
45 assert f(1, None) == "1:None"
46 assert f(1) == "1:0"
47 assert f(1, 0) == "1:0"
48 assert f(1, b=0) == "1:0"
49 # None and the default 0 are distinct; the three b=0 forms share a key.
50 assert runs == [(1, None), (1, 0)]
51
52
53 def test_memoize_hashes(app, cache, hash_method, clock):
54 with app.test_request_context():
55
56 @cache.memoize(3, hash_method=hash_method)
57 def big_foo(a, b):
58 return a + b + random.randrange(0, 100000)
59
60 result = big_foo(5, 2)
61
62 clock.advance(1)
63
64 assert big_foo(5, 2) == result
65
66 result2 = big_foo(5, 3)
67 assert result2 != result
68
69 clock.advance(3)
70
71 assert big_foo(5, 2) != result
72
73 clock.advance(1)
74
75 assert big_foo(5, 3) != result2
76
77
78 def test_memoize_timeout(app, clock):
79 app.config["CACHE_DEFAULT_TIMEOUT"] = 1
80 cache = Cache(app)
81
82 with app.test_request_context():
83
84 @cache.memoize()
85 def big_foo(a, b):
86 return a + b + random.randrange(0, 100000)
87
88 result = big_foo(5, 2)
89 assert big_foo(5, 2) == result
90 clock.advance(2)
91 assert big_foo(5, 2) != result
92
93
94 def test_memoize_entry_written_late_keeps_its_own_timeout(app, cache, clock):
95 with app.test_request_context():
96 runs = []
97
98 @cache.memoize(timeout=60)
99 def f(param):
100 runs.append(param)
101 return param.upper()
102
103 assert f("icecream") == "ICECREAM"
104 clock.advance(59)
105 assert f("waffles") == "WAFFLES"
106
107 # t=61: the version key used to expire here and orphan both entries.
108 clock.advance(2)
109 assert f("waffles") == "WAFFLES"
110 assert runs == ["icecream", "waffles"]
111
112 # t=120: past this entry's own timeout, so it expires normally.
113 clock.advance(59)
114 assert f("waffles") == "WAFFLES"
115 assert runs == ["icecream", "waffles", "waffles"]
116
117
118 def test_memoize_version_key_outlives_newest_entry(app, cache, clock):
119 with app.test_request_context():
120
121 @cache.memoize(timeout=60)
122 def f(param):
123 return param.upper()
124
125 version_key = cache._memvname(function_namespace(f.uncached)[0])
126
127 f("a")
128 clock.advance(50)
129 # t=50: this entry expires at t=110, so the version key has to as well.
130 f("b")
131
132 clock.advance(59)
133 # t=109: entry "b" still has a second left, so its version must be live.
134 assert cache.get(version_key) is not None
135
136
137 def test_memoize_version_key_expires_once_its_entries_have(app, cache, clock):
138 with app.test_request_context():
139
140 @cache.memoize(timeout=60)
141 def f(param):
142 return param.upper()
143
144 f("a")
145 version_key = cache._memvname(function_namespace(f.uncached)[0])
146 assert cache.get(version_key) is not None
147
148 clock.advance(61)
149 assert cache.get(version_key) is None
150
151
152 def test_memoize_delete_resets_version_key(app, cache, clock):
153 with app.test_request_context():
154 runs = []
155
156 @cache.memoize(timeout=60)
157 def f(param):
158 runs.append(param)
159 return param.upper()
160
161 f("a")
162 assert runs == ["a"]
163
164 cache.delete_memoized(f)
165 assert f("a") == "A"
166 assert runs == ["a", "a"]
167
168 clock.advance(3600)
169 f("b")
170 clock.advance(30)
171 assert f("b") == "B"
172 assert runs == ["a", "a", "b"]
173
174
175 def test_memoize_annotated(app, cache):
176 with app.test_request_context():
177
178 @cache.memoize(50)
179 def big_foo_annotated(a, b):
180 return a + b + random.randrange(0, 100000)
181
182 big_foo_annotated.__annotations__ = {
183 "a": int,
184 "b": int,
185 "return": int,
186 }
187
188 result = big_foo_annotated(5, 2)
189
190 assert big_foo_annotated(5, 2) == result
191
192
193 def test_memoize_utf8_arguments(app, cache):
194 with app.test_request_context():
195
196 @cache.memoize()
197 def big_foo(a, b):
198 return f"{a}-{b}"
199
200 big_foo("æøå", "chars")
201
202
203 def test_memoize_unicode_arguments(app, cache):
204 with app.test_request_context():
205
206 @cache.memoize()
207 def big_foo(a, b):
208 return f"{a}-{b}"
209
210 big_foo("æøå", "chars")
211
212
213 def test_memoize_delete(app, cache):
214 with app.test_request_context():
215
216 @cache.memoize(5)
217 def big_foo(a, b):
218 return a + b + random.randrange(0, 100000)
219
220 result = big_foo(5, 2)
221 result2 = big_foo(5, 3)
222
223 assert big_foo(5, 2) == result
224 assert big_foo(5, 2) == result
225 assert big_foo(5, 3) != result
226 assert big_foo(5, 3) == result2
227
228 cache.delete_memoized(big_foo)
229
230 assert big_foo(5, 2) != result
231 assert big_foo(5, 3) != result2
232
233
234 def test_memoize_delete_via_attribute(app, cache):
235 with app.test_request_context():
236
237 @cache.memoize(5)
238 def big_foo(a, b):
239 return a + b + random.randrange(0, 100000)
240
241 result = big_foo(5, 2)
242 assert big_foo(5, 2) == result
243
244 big_foo.delete_memoized()
245
246 assert big_foo(5, 2) != result
247
248
249 def test_memoize_classfunc_delete_via_attribute(app, cache):
250 with app.test_request_context():
251
252 class Adder:
253 def __init__(self, initial):
254 self.initial = initial
255
256 @cache.memoize(5)
257 def add(self, b):
258 return self.initial + b + random.random()
259
260 adder1 = Adder(1)
261 adder2 = Adder(2)
262
263 a1 = adder1.add(3)
264 a2 = adder2.add(3)
265
266 assert adder1.add(3) == a1
267 assert adder2.add(3) == a2
268
269 # the attribute takes no arguments, so it resets the version for
270 # every instance, not just adder1
271 adder1.add.delete_memoized()
272
273 assert adder1.add(3) != a1
274 assert adder2.add(3) != a2
275
276
277 def test_memoize_no_timeout_delete(app, cache):
278 with app.test_request_context():
279
280 @cache.memoize()
281 def big_foo(a, b):
282 return a + b + random.randrange(0, 100000)
283
284 result_a = big_foo(5, 1)
285 result_b = big_foo(5, 2)
286
287 assert big_foo(5, 1) == result_a
288 assert big_foo(5, 2) == result_b
289 cache.delete_memoized(big_foo, 5, 2)
290
291 assert big_foo(5, 1) == result_a
292 assert big_foo(5, 2) != result_b
293
294 # Cleanup bigfoo 5,1 5,2 or it might conflict with
295 # following run if it also uses memecache
296 cache.delete_memoized(big_foo, 5, 2)
297 cache.delete_memoized(big_foo, 5, 1)
298
299
300 def test_memoize_verhash_delete(app, cache):
301 with app.test_request_context():
302
303 @cache.memoize(5)
304 def big_foo(a, b):
305 return a + b + random.randrange(0, 100000)
306
307 result = big_foo(5, 2)
308 result2 = big_foo(5, 3)
309
310 assert big_foo(5, 2) == result
311 assert big_foo(5, 2) == result
312 assert big_foo(5, 3) != result
313 assert big_foo(5, 3) == result2
314
315 cache.delete_memoized_verhash(big_foo)
316
317 _fname, _fname_instance = function_namespace(big_foo)
318 version_key = cache._memvname(_fname)
319 assert cache.get(version_key) is None
320
321 assert big_foo(5, 2) != result
322 assert big_foo(5, 3) != result2
323
324 assert cache.get(version_key) is not None
325
326
327 def test_memoize_annotated_delete(app, cache):
328 with app.test_request_context():
329
330 @cache.memoize(5)
331 def big_foo_annotated(a, b):
332 return a + b + random.randrange(0, 100000)
333
334 big_foo_annotated.__annotations__ = {"a": int, "b": int, "return": int}
335
336 result = big_foo_annotated(5, 2)
337 result2 = big_foo_annotated(5, 3)
338
339 assert big_foo_annotated(5, 2) == result
340 assert big_foo_annotated(5, 2) == result
341 assert big_foo_annotated(5, 3) != result
342 assert big_foo_annotated(5, 3) == result2
343
344 cache.delete_memoized_verhash(big_foo_annotated)
345
346 _fname, _fname_instance = function_namespace(big_foo_annotated)
347 version_key = cache._memvname(_fname)
348 assert cache.get(version_key) is None
349
350 assert big_foo_annotated(5, 2) != result
351 assert big_foo_annotated(5, 3) != result2
352
353 assert cache.get(version_key) is not None
354
355
356 def test_memoize_args(app, cache):
357 with app.test_request_context():
358
359 @cache.memoize()
360 def big_foo(a, b):
361 return sum(a) + sum(b) + random.randrange(0, 100000)
362
363 result_a = big_foo([5, 3, 2], [1])
364 result_b = big_foo([3, 3], [3, 1])
365
366 assert big_foo([5, 3, 2], [1]) == result_a
367 assert big_foo([3, 3], [3, 1]) == result_b
368
369 cache.delete_memoized(big_foo, [5, 3, 2], [1])
370
371 assert big_foo([5, 3, 2], [1]) != result_a
372 assert big_foo([3, 3], [3, 1]) == result_b
373
374 # Cleanup bigfoo 5,1 5,2 or it might conflict with
375 # following run if it also uses memecache
376 cache.delete_memoized(big_foo, [5, 3, 2], [1])
377 cache.delete_memoized(big_foo, [3, 3], [1])
378
379
380 def test_memoize_kwargs(app, cache):
381 with app.test_request_context():
382
383 @cache.memoize()
384 def big_foo(a, b=None):
385 return a + sum(b.values()) + random.randrange(0, 100000)
386
387 result_a = big_foo(1, dict(one=1, two=2))
388 result_b = big_foo(5, dict(three=3, four=4))
389
390 assert big_foo(1, dict(one=1, two=2)) == result_a
391 assert big_foo(5, dict(three=3, four=4)) == result_b
392
393 cache.delete_memoized(big_foo, 1, dict(one=1, two=2))
394
395 assert big_foo(1, dict(one=1, two=2)) != result_a
396 assert big_foo(5, dict(three=3, four=4)) == result_b
397
398
399 def test_memoize_kwargonly(app, cache):
400 with app.test_request_context():
401
402 @cache.memoize()
403 def big_foo(a=None):
404 if a is None:
405 a = 0
406 return a + random.random()
407
408 result_a = big_foo()
409 result_b = big_foo(5)
410
411 assert big_foo() == result_a
412 assert big_foo() < 1
413 assert big_foo(5) == result_b
414 assert big_foo(5) >= 5 and big_foo(5) < 6
415
416
417 def test_memoize_arg_kwarg(app, cache):
418 with app.test_request_context():
419
420 @cache.memoize()
421 def f(a, b, c=1):
422 return a + b + c + random.randrange(0, 100000)
423
424 assert f(1, 2) == f(1, 2, c=1)
425 assert f(1, 2) == f(1, 2, 1)
426 assert f(1, 2) == f(1, 2)
427 assert f(1, 2, 3) != f(1, 2)
428
429 with pytest.raises(TypeError):
430 f(1)
431
432
433 def test_memoize_arg_kwarg_var_keyword(app, cache):
434 with app.test_request_context():
435
436 @cache.memoize()
437 def f(a, b, c=1, **kwargs):
438 return a + b + c + random.randrange(0, 100000) + sum(list(kwargs.values()))
439
440 assert f(1, 2) == f(1, 2, c=1)
441 assert f(1, 2) == f(1, 2, 1)
442 assert f(1, 2) == f(1, 2)
443 assert f(1, 2, d=5, e=8) == f(1, 2, e=8, d=5)
444 assert f(1, b=2, c=3, d=5, e=8) == f(1, 2, e=8, d=5, b=2, c=3)
445 assert f(1, 2, 3) != f(1, 2)
446 assert f(1, 2, 3) != f(1, 2)
447
448 with pytest.raises(TypeError):
449 f(1)
450
451
452 def test_memoize_classarg(app, cache):
453 @cache.memoize()
454 def bar(a):
455 return a.value + random.random()
456
457 class Adder:
458 def __init__(self, value):
459 self.value = value
460
461 adder = Adder(15)
462 adder2 = Adder(20)
463
464 y = bar(adder)
465 z = bar(adder2)
466
467 assert y != z
468 assert bar(adder) == y
469 assert bar(adder) != z
470 adder.value = 14
471 assert bar(adder) == y
472 assert bar(adder) != z
473
474 assert bar(adder) != bar(adder2)
475 assert bar(adder2) == z
476
477
478 def test_memoize_classfunc(app, cache):
479 class Adder:
480 def __init__(self, initial):
481 self.initial = initial
482
483 @cache.memoize()
484 def add(self, b):
485 return self.initial + b
486
487 adder1 = Adder(1)
488 adder2 = Adder(2)
489
490 x = adder1.add(3)
491 assert adder1.add(3) == x
492 assert adder1.add(4) != x
493 assert adder1.add(3) != adder2.add(3)
494
495
496 def test_memoize_classfunc_repr(app, cache):
497 class Adder:
498 def __init__(self, initial):
499 self.initial = initial
500
501 @cache.memoize()
502 def add(self, b):
503 return self.initial + b + random.random()
504
505 def __repr__(self):
506 return "42"
507
508 def __caching_id__(self):
509 return self.initial
510
511 adder1 = Adder(1)
512 adder2 = Adder(2)
513
514 x = adder1.add(3)
515 assert adder1.add(3) == x
516 assert adder1.add(4) != x
517 assert adder1.add(3) != adder2.add(3)
518
519
520 def test_memoize_classfunc_delete(app, cache):
521 with app.test_request_context():
522
523 class Adder:
524 def __init__(self, initial):
525 self.initial = initial
526
527 @cache.memoize()
528 def add(self, b):
529 return self.initial + b + random.random()
530
531 adder1 = Adder(1)
532 adder2 = Adder(2)
533
534 a1 = adder1.add(3)
535 a2 = adder2.add(3)
536
537 assert a1 != a2
538 assert adder1.add(3) == a1
539 assert adder2.add(3) == a2
540
541 cache.delete_memoized(adder1.add)
542
543 a3 = adder1.add(3)
544 a4 = adder2.add(3)
545
546 assert not a1 == a3
547 # self.assertNotEqual(a1, a3)
548
549 assert a1 != a3
550
551 assert a2 == a4
552 # self.assertEqual(a2, a4)
553
554 cache.delete_memoized(Adder.add)
555
556 a5 = adder1.add(3)
557 a6 = adder2.add(3)
558
559 assert not a5 == a6
560 # self.assertNotEqual(a5, a6)
561 assert not a3 == a5
562 # self.assertNotEqual(a3, a5)
563 assert not a4 == a6
564 # self.assertNotEqual(a4, a6)
565
566
567 def test_memoize_classfunc_delete_with_args(app, cache):
568 """A bound method carries its own instance, so ``delete_memoized`` only
569 needs the arguments that follow it."""
570 with app.test_request_context():
571
572 class Adder:
573 @cache.memoize(5)
574 def add(self, b):
575 return b + random.random()
576
577 adder1 = Adder()
578 adder2 = Adder()
579
580 a1 = adder1.add(3)
581 a2 = adder1.add(4)
582 a3 = adder2.add(3)
583
584 cache.delete_memoized(adder1.add, 3)
585
586 # only ``adder1.add(3)`` is gone
587 assert adder1.add(3) != a1
588 assert adder1.add(4) == a2
589 assert adder2.add(3) == a3
590
591
592 def test_memoize_classfunc_delete_with_explicit_instance(app, cache):
593 """Passing the instance explicitly keeps working, so that code written
594 against the previous behaviour is not broken."""
595 with app.test_request_context():
596
597 class Adder:
598 @cache.memoize(5)
599 def add(self, b):
600 return b + random.random()
601
602 adder1 = Adder()
603 adder2 = Adder()
604
605 a1 = adder1.add(3)
606 a2 = adder1.add(4)
607 a3 = adder2.add(3)
608
609 cache.delete_memoized(adder1.add, adder1, 3)
610
611 assert adder1.add(3) != a1
612 assert adder1.add(4) == a2
613 assert adder2.add(3) == a3
614
615 # ... and so does reaching the method through the class
616 a1 = adder1.add(3)
617 cache.delete_memoized(Adder.add, adder1, 3)
618
619 assert adder1.add(3) != a1
620 assert adder2.add(3) == a3
621
622
623 def test_memoize_classfunc_delete_with_args_to_ignore_self(app, cache):
624 with app.test_request_context():
625
626 class Adder:
627 @cache.memoize(5, args_to_ignore=["self"])
628 def add(self, b):
629 return b + random.random()
630
631 adder1 = Adder()
632 adder2 = Adder()
633
634 a1 = adder1.add(3)
635 a2 = adder1.add(4)
636
637 # ``self`` is not part of the key, so both instances share it
638 assert adder2.add(3) == a1
639
640 cache.delete_memoized(adder1.add, 3)
641
642 assert adder1.add(3) != a1
643 assert adder1.add(4) == a2
644
645
646 def test_memoize_classfunc_delete_with_kwargs_only(app, cache):
647 with app.test_request_context():
648
649 class Adder:
650 @cache.memoize(5)
651 def add(self, b):
652 return b + random.random()
653
654 adder1 = Adder()
655
656 a1 = adder1.add(3)
657
658 cache.delete_memoized(adder1.add, b=3)
659
660 assert adder1.add(3) != a1
661
662 # reached through the class there is no instance to fall back on
663 with pytest.raises(ValueError):
664 cache.delete_memoized(Adder.add, b=3)
665
666
667 def test_memoize_classmethod_delete(app, cache):
668 with app.test_request_context():
669
670 class Mock:
671 @classmethod
672 @cache.memoize(5)
673 def big_foo(cls, a, b):
674 return a + b + random.randrange(0, 100000)
675
676 result = Mock.big_foo(5, 2)
677 result2 = Mock.big_foo(5, 3)
678
679 assert Mock.big_foo(5, 2) == result
680 assert Mock.big_foo(5, 2) == result
681 assert Mock.big_foo(5, 3) != result
682 assert Mock.big_foo(5, 3) == result2
683
684 cache.delete_memoized(Mock.big_foo)
685
686 assert Mock.big_foo(5, 2) != result
687 assert Mock.big_foo(5, 3) != result2
688
689
690 def test_memoize_classmethod_delete_with_args(app, cache):
691 with app.test_request_context():
692
693 class Mock:
694 @classmethod
695 @cache.memoize(5)
696 def big_foo(cls, a, b):
697 return a + b + random.randrange(0, 100000)
698
699 result = Mock.big_foo(5, 2)
700 result2 = Mock.big_foo(5, 3)
701
702 assert Mock.big_foo(5, 2) == result
703 assert Mock.big_foo(5, 2) == result
704 assert Mock.big_foo(5, 3) != result
705 assert Mock.big_foo(5, 3) == result2
706
707 with pytest.raises(ValueError):
708 cache.delete_memoized(Mock.big_foo, 5, 2)
709
710 assert Mock.big_foo(5, 2) == result
711 assert Mock.big_foo(5, 3) == result2
712
713 cache.delete_memoized(Mock.big_foo, Mock, 5, 2)
714
715 assert Mock.big_foo(5, 2) != result
716 assert Mock.big_foo(5, 3) == result2
717
718
719 def test_memoize_forced_update(app, cache):
720 with app.test_request_context():
721 forced_update = False
722
723 @cache.memoize(5, forced_update=lambda: forced_update)
724 def big_foo(a, b):
725 return a + b + random.randrange(0, 100000)
726
727 result = big_foo(5, 2)
728 assert big_foo(5, 2) == result
729
730 forced_update = True
731 new_result = big_foo(5, 2)
732 assert new_result != result
733
734 forced_update = False
735 assert big_foo(5, 2) == new_result
736
737
738 def test_memoize_forced_update_parameters(app, cache):
739 from collections import Counter
740
741 with app.test_request_context():
742 call_counter = Counter()
743 call_params = {}
744 forced_update = False
745
746 def forced_update_func(a, b):
747 call_counter[1] += 1
748 call_params[call_counter[1] - 1] = (a, b)
749
750 return forced_update
751
752 @cache.memoize(5, forced_update=forced_update_func)
753 def memoized_func(a, b):
754 return a + b + random.randrange(0, 100000)
755
756 # Save the value for later inspection
757 result = memoized_func(5, 2)
758 # forced_update_func should have been called once by memoize itself.
759 assert call_counter[1] == 1
760 # …with the values we called the function with
761 assert call_params[0] == (5, 2)
762
763 # Calling the function again should return the cached value
764 assert memoized_func(5, 2) == result
765 # forced_update_func should have been called one more time…
766 assert call_counter[1] == 2
767 # …with the values we called the function with
768 assert call_params[1] == (5, 2)
769
770 # Tell forced_update_func to return True next time
771 forced_update = True
772 # Save the new result…
773 new_result = memoized_func(5, 2)
774 # …which, due to the random number in the function, should be different
775 # from the old one
776 assert new_result != result
777 # forced_update_func should have been called one more time again…
778 assert call_counter[1] == 3
779 # …with the values we called the function with
780 assert call_params[2] == (5, 2)
781
782 # Now stop forced updating again
783 forced_update = False
784 # The function should return the same value as it did last time
785 assert memoized_func(5, 2) == new_result
786 # forced_update_func should have been called one more time again…
787 assert call_counter[1] == 4
788 # …with the values we called the function with
789 assert call_params[3] == (5, 2)
790
791
792 def test_memoize_is_stale(app, cache):
793 with app.test_request_context():
794 stale = False
795 cached_values = []
796
797 def is_stale(value):
798 cached_values.append(value)
799
800 return stale
801
802 @cache.memoize(5, is_stale=is_stale)
803 def big_foo(a, b):
804 return a + b + random.randrange(0, 100000)
805
806 result = big_foo(5, 2)
807 # is_stale is only consulted on a cache hit
808 assert cached_values == []
809
810 assert big_foo(5, 2) == result
811 assert cached_values == [result]
812
813 stale = True
814 new_result = big_foo(5, 2)
815 assert new_result != result
816 assert cached_values == [result, result]
817
818 stale = False
819 assert big_foo(5, 2) == new_result
820 assert cached_values == [result, result, new_result]
821
822
823 def test_memoize_is_stale_parameters(app, cache):
824 with app.test_request_context():
825 call_params = []
826
827 def is_stale(value, a, b):
828 call_params.append((value, a, b))
829
830 return False
831
832 @cache.memoize(5, is_stale=is_stale)
833 def memoized_func(a, b):
834 return a + b + random.randrange(0, 100000)
835
836 result = memoized_func(5, 2)
837 assert call_params == []
838
839 assert memoized_func(5, 2) == result
840 # the cached value comes first, followed by the call's own arguments
841 assert call_params == [(result, 5, 2)]
842
843
844 def test_memoize_multiple_arg_kwarg_calls(app, cache):
845 with app.test_request_context():
846
847 @cache.memoize()
848 def big_foo(a, b, c=None, d=None):
849 if c is None:
850 c = [1, 1]
851 if d is None:
852 d = [1, 1]
853 return sum(a) + sum(b) + sum(c) + sum(d) + random.randrange(0, 100000)
854
855 result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
856
857 assert big_foo([5, 3, 2], [1], d=[3, 3], c=[3, 3]) == result_a
858 assert big_foo(b=[1], a=[5, 3, 2], c=[3, 3], d=[3, 3]) == result_a
859 assert big_foo([5, 3, 2], [1], [3, 3], [3, 3]) == result_a
860
861
862 def test_memoize_multiple_arg_kwarg_delete(app, cache):
863 with app.test_request_context():
864
865 @cache.memoize()
866 def big_foo(a, b, c=None, d=None):
867 if c is None:
868 c = [1, 1]
869 if d is None:
870 d = [1, 1]
871 return sum(a) + sum(b) + sum(c) + sum(d) + random.randrange(0, 100000)
872
873 result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
874 cache.delete_memoized(big_foo, [5, 3, 2], [1], [3, 3], [3, 3])
875 result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
876 assert result_a != result_b
877
878 cache.delete_memoized(big_foo, [5, 3, 2], b=[1], c=[3, 3], d=[3, 3])
879 result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
880 assert result_a != result_b
881
882 cache.delete_memoized(big_foo, [5, 3, 2], [1], c=[3, 3], d=[3, 3])
883 result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
884 assert result_a != result_b
885
886 cache.delete_memoized(big_foo, [5, 3, 2], b=[1], c=[3, 3], d=[3, 3])
887 result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
888 assert result_a != result_b
889
890 cache.delete_memoized(big_foo, [5, 3, 2], [1], c=[3, 3], d=[3, 3])
891 result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
892 assert result_a != result_b
893
894 cache.delete_memoized(big_foo, [5, 3, 2], [1], [3, 3], [3, 3])
895 result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3])
896 assert result_a != result_b
897
898
899 def test_memoize_kwargs_to_args(app, cache):
900 with app.test_request_context():
901
902 def big_foo(a, b, c=None, d=None):
903 return sum(a) + sum(b) + random.randrange(0, 100000)
904
905 expected = (1, 2, "foo", "bar")
906
907 args, kwargs = cache._memoize_kwargs_to_args(big_foo, 1, 2, "foo", "bar")
908 assert args == expected
909 args, kwargs = cache._memoize_kwargs_to_args(big_foo, 2, "foo", "bar", a=1)
910 assert args == expected
911 args, kwargs = cache._memoize_kwargs_to_args(
912 big_foo, a=1, b=2, c="foo", d="bar"
913 )
914 assert args == expected
915 args, kwargs = cache._memoize_kwargs_to_args(
916 big_foo, d="bar", b=2, a=1, c="foo"
917 )
918 assert args == expected
919 args, kwargs = cache._memoize_kwargs_to_args(big_foo, 1, 2, d="bar", c="foo")
920 assert args == expected
921
922
923 def test_memoize_when_using_args_unpacking(app, cache):
924 with app.test_request_context():
925
926 @cache.memoize()
927 def big_foo(*args):
928 return sum(args) + random.randrange(0, 100000)
929
930 result_a = big_foo(1, 2)
931 result_b = big_foo(1, 3)
932
933 assert big_foo(1, 2) == result_a
934 assert big_foo(1, 3) == result_b
935 assert big_foo(1, 2) != result_b
936 assert big_foo(1, 3) != result_a
937
938 cache.delete_memoized(big_foo)
939
940 assert big_foo(1, 2) != result_a
941 assert big_foo(1, 3) != result_b
942
943
944 def test_memoize_when_using_variable_mix_args_unpacking(app, cache):
945 with app.test_request_context():
946
947 @cache.memoize()
948 def big_foo(a, b, *args, **kwargs):
949 return (
950 sum([a, b])
951 + sum(args)
952 + sum(kwargs.values())
953 + random.randrange(0, 100000)
954 )
955
956 result_a = big_foo(1, 2, 3, 4, x=2, y=5)
957 result_b = big_foo(4, 7, 7, 2, x=1, y=4)
958
959 assert big_foo(1, 2, 3, 4, x=2, y=5) == result_a
960 assert big_foo(4, 7, 7, 2, x=1, y=4) == result_b
961 assert big_foo(1, 2, 3, 4, x=2, y=5) != result_b
962 assert big_foo(4, 7, 7, 2, x=1, y=4) != result_a
963
964 cache.delete_memoized(big_foo)
965
966 assert big_foo(1, 2, 3, 4, x=2, y=5) != result_a
967 assert big_foo(4, 7, 7, 2, x=1, y=4) != result_b
968
969
970 def test_memoize_none(app, cache):
971 with app.test_request_context():
972 from collections import Counter
973
974 call_counter = Counter()
975
976 @cache.memoize(cache_none=True)
977 def memoize_none(param):
978 call_counter[param] += 1
979
980 memoize_none(1)
981
982 # The memoized function should have been called
983 assert call_counter[1] == 1
984
985 # Next time we call the function, the value should be coming from the
986 # cache...
987 assert memoize_none(1) is None
988
989 # …thus, the call counter should remain 1
990 assert call_counter[1] == 1
991
992 cache.clear()
993
994 memoize_none(1)
995 assert call_counter[1] == 2
996
997
998 def test_memoize_never_accept_none(app, cache):
999 """Asserting that when cache_none is False, we always
1000 assume a None value returned from .get() means the key is not found
1001 """
1002 with app.test_request_context():
1003 from collections import Counter
1004
1005 call_counter = Counter()
1006
1007 @cache.memoize()
1008 def memoize_none(param):
1009 call_counter[param] += 1
1010
1011 memoize_none(1)
1012
1013 # The memoized function should have been called
1014 assert call_counter[1] == 1
1015
1016 # Next time we call the function, the value should be coming from the
1017 # cache…
1018 # But the value is None and so we treat it as uncached.
1019 assert memoize_none(1) is None
1020
1021 # …thus, the call counter should increment to 2
1022 assert call_counter[1] == 2
1023
1024 cache.clear()
1025
1026 memoize_none(1)
1027 assert call_counter[1] == 3
1028
1029
1030 def test_memoize_with_source_check_enabled(app, cache):
1031 with app.test_request_context():
1032
1033 @cache.memoize(source_check=True)
1034 def big_foo(a, b):
1035 return str(time.time())
1036
1037 first_try = big_foo(5, 2)
1038
1039 second_try = big_foo(5, 2)
1040
1041 assert second_try == first_try
1042
1043 @cache.memoize(source_check=True)
1044 def big_foo(a, b):
1045 return str(time.time())
1046
1047 third_try = big_foo(5, 2)
1048
1049 assert third_try[0] != first_try
1050
1051 @cache.memoize(source_check=True)
1052 def big_foo(a, b):
1053 return str(time.time())
1054
1055 forth_try = big_foo(5, 2)
1056
1057 assert forth_try == first_try
1058
1059
1060 def test_memoize_with_source_check_disabled(app, cache):
1061 with app.test_request_context():
1062
1063 @cache.memoize(source_check=False)
1064 def big_foo(a, b):
1065 return str(time.time())
1066
1067 first_try = big_foo(5, 2)
1068
1069 second_try = big_foo(5, 2)
1070
1071 assert second_try == first_try
1072
1073 @cache.memoize(source_check=False)
1074 def big_foo(a, b):
1075 return time.time()
1076
1077 third_try = big_foo(5, 2)
1078
1079 assert third_try == first_try
1080
1081
1082 def test_memoize_source_check_from_config(app):
1083 """``CACHE_SOURCE_CHECK`` applies when the decorator doesn't override it."""
1084 app.config["CACHE_SOURCE_CHECK"] = True
1085 cache = Cache(app)
1086
1087 with app.test_request_context():
1088
1089 @cache.memoize()
1090 def big_foo(a, b):
1091 return str(time.time())
1092
1093 first_try = big_foo(5, 2)
1094 assert big_foo(5, 2) == first_try
1095
1096 @cache.memoize()
1097 def big_foo(a, b): # noqa: F811
1098 return str(time.time())
1099
1100 assert big_foo(5, 2) != first_try
1101
1102
1103 def test_memoize_delete_with_source_check_from_config(app):
1104 """``CACHE_SOURCE_CHECK`` must reach the ``make_cache_key`` attribute.
1105
1106 ``delete_memoized`` builds the key through ``make_cache_key``, which is
1107 created when the decorator is applied. Resolving the config value later
1108 than that made the two keys disagree, so nothing was deleted.
1109 """
1110 app.config["CACHE_SOURCE_CHECK"] = True
1111 cache = Cache(app)
1112
1113 with app.test_request_context():
1114
1115 @cache.memoize(50)
1116 def big_foo(a, b):
1117 return a + b + random.randrange(0, 100000)
1118
1119 first_try = big_foo(5, 2)
1120 assert big_foo(5, 2) == first_try
1121
1122 cache.delete_memoized(big_foo, 5, 2)
1123
1124 assert big_foo(5, 2) != first_try
1125
1126
1127 def test_cached_source_check_from_config_applies_to_first_call(app):
1128 """The source hash must be part of the key from the very first call."""
1129 app.config["CACHE_SOURCE_CHECK"] = True
1130 cache = Cache(app)
1131
1132 @cache.cached(key_prefix="MyBits")
1133 def get_random_bits():
1134 return [random.randrange(0, 2) for i in range(50)]
1135
1136 with app.test_request_context():
1137 key_before_call = get_random_bits.make_cache_key()
1138 get_random_bits()
1139
1140 assert key_before_call != "MyBits"
1141 assert get_random_bits.make_cache_key() == key_before_call
1142
1143
1144 def test_memoize_ignore_args(app, cache):
1145 with app.test_request_context():
1146
1147 @cache.memoize(50, args_to_ignore=["b"])
1148 def big_foo(a, b):
1149 return a + b + random.randrange(0, 100000)
1150
1151 result = big_foo(5, 2)
1152 assert big_foo(5, 3) == result
1153
1154
1155 def test_memoize_method_ignore_self_arg(app, cache):
1156 with app.test_request_context():
1157
1158 class Foo:
1159 @cache.memoize(50, args_to_ignore=["self"])
1160 def big_foo(self, a, b):
1161 return a + b + random.randrange(0, 100000)
1162
1163 assert Foo().big_foo(5, 2) == Foo().big_foo(5, 2)
1164
1165
1166 def test_memoize_function_ignore_kwarg(app, cache):
1167 with app.test_request_context():
1168
1169 @cache.memoize(50, args_to_ignore=["b"])
1170 def big_foo(a, b):
1171 return a + b + random.randrange(0, 100000)
1172
1173 assert big_foo(5, 2) == big_foo(5, b=3)