Debian Codegraph @

tests/test_cache_memoize.py

raw
1 # -*- coding: utf-8 -*-
2 import random
3 from threading import Thread, Lock
4
5 import pytest
6 from django.core.cache import cache
7
8 from cache_memoize import cache_memoize
9
10 from .dummy_package import a as dummy_a
11 from .dummy_package import b as dummy_b
12
13
14 def test_the_setup():
15 """If this doesn't work, the settings' CACHES isn't working."""
16 cache.set("foo", "bar", 1)
17 assert cache.get("foo") == "bar"
18
19
20 def test_cache_memoize():
21 calls_made = []
22
23 @cache_memoize(10)
24 def runmeonce(a, b, k1="bla", k2=None):
25 calls_made.append((a, b, k1, k2))
26 return "{} {} {} {}".format(a, b, k1, k2) # sample implementation
27
28 runmeonce(1, 2)
29 runmeonce(1, 2)
30 assert len(calls_made) == 1
31 runmeonce(1, 3)
32 assert len(calls_made) == 2
33 # Should work with most basic types
34 runmeonce(1.1, "foo")
35 runmeonce(1.1, "foo")
36 assert len(calls_made) == 3
37 # Even more "advanced" types
38 runmeonce(1.1, "foo", k1=list("åäö"))
39 runmeonce(1.1, "foo", k1=list("åäö"))
40 assert len(calls_made) == 4
41 # And shouldn't be a problem even if the arguments are really long
42 runmeonce("A" * 200, "B" * 200, {"C" * 100: "D" * 100})
43 assert len(calls_made) == 5
44 # The order of the keyword arguments doesn't matter
45 runmeonce(1, 2, k1=3, k2=4)
46 runmeonce(1, 2, k2=4, k1=3)
47 assert len(calls_made) == 6
48
49
50 @pytest.mark.parametrize(
51 ("obj_1", "obj_2"),
52 [
53 # Check identically named entities from different modules
54 (dummy_a.func, dummy_b.func),
55 (dummy_a.decorated_func, dummy_b.decorated_func),
56 (dummy_a.DummyClass().func, dummy_b.DummyClass().func),
57 (dummy_a.DummyClass().decorated_func, dummy_b.DummyClass().decorated_func),
58 #
59 # Check identically named entities from different scopes
60 (dummy_a.func, dummy_a.DummyClass().func),
61 (dummy_a.func, dummy_a.func_factory()),
62 #
63 # Check decorated entities
64 (dummy_a.decorated_func, dummy_a.another_decorated_func),
65 (
66 dummy_a.DummyClass().decorated_func,
67 dummy_a.DummyClass().another_decorated_func,
68 ),
69 ],
70 )
71 def test_default_prefix_uniqueness(obj_1, obj_2):
72 assert obj_1.get_cache_key() != obj_2.get_cache_key()
73
74
75 def test_prefixes():
76 calls_made = []
77
78 # different prefixes
79 @cache_memoize(10, prefix="first")
80 def foo(value):
81 calls_made.append(value)
82 return "ho"
83
84 @cache_memoize(10, prefix="second")
85 def bar(value):
86 calls_made.append(value)
87 return "ho"
88
89 foo("hey")
90 assert len(calls_made) == 1
91 bar("hey")
92 assert len(calls_made) == 2
93
94
95 def test_no_store_result():
96 calls_made = []
97
98 # Test when you don't care about the result
99 @cache_memoize(10, store_result=False, prefix="different")
100 def returnnothing(a, b, k="bla"):
101 calls_made.append((a, b, k))
102 # note it returns None
103
104 returnnothing(1, 2)
105 returnnothing(1, 2)
106 assert len(calls_made) == 1
107
108
109 class TestDefaultCacheKeyQuoting:
110 @pytest.mark.parametrize(
111 "bits", [("a", "b", "c"), ("ä", "á", "ö"), ("ë".encode(), b"\02", b"i")]
112 )
113 def test_colons_quoting(self, bits):
114 calls_made = []
115
116 @cache_memoize(10)
117 def fun(a, b, k="bla"):
118 calls_made.append((a, b, k))
119 return (a, b, k)
120
121 sep = ":"
122 if isinstance(bits[0], bytes):
123 sep = sep.encode()
124 a1, a2 = (sep.join(bits[:2]), bits[2])
125 b1, b2 = (bits[0], sep.join(bits[1:]))
126 fun(a1, a2)
127 fun(b1, b2)
128 assert len(calls_made) == 2
129
130 @pytest.mark.parametrize(
131 ("arguments_1", "arguments_2"),
132 [
133 (
134 (("a", "b", "c"), {}),
135 (("a:b:c",), {}),
136 ),
137 (
138 (("a", "b"), {"c": "d"}),
139 (("a",), {"b:c": "d"}),
140 ),
141 (
142 (("a",), {"b": "c"}),
143 (("a", "b=c"), {}),
144 ),
145 (
146 ((), {"a": "b=c"}),
147 ((), {"a=b": "c"}),
148 ),
149 ],
150 )
151 def test_general_quoting(self, arguments_1, arguments_2):
152 calls_made = []
153
154 @cache_memoize(10)
155 def fun(*args, **kwargs):
156 calls_made.append((args, kwargs))
157
158 args, kwargs = arguments_1
159 fun(*args, **kwargs)
160
161 args, kwargs = arguments_2
162 fun(*args, **kwargs)
163
164 assert calls_made == [arguments_1, arguments_2]
165
166
167 def test_cache_memoize_hit_miss_callables():
168 hits = []
169 misses = []
170 calls_made = []
171
172 def hit_callable(arg):
173 hits.append(arg)
174
175 def miss_callable(arg):
176 misses.append(arg)
177
178 @cache_memoize(10, hit_callable=hit_callable, miss_callable=miss_callable)
179 def runmeonce(arg):
180 calls_made.append(arg)
181 return arg * 2
182
183 result = runmeonce(100)
184 assert result == 200
185 assert len(calls_made) == 1
186 assert len(hits) == 0
187 assert len(misses) == 1
188
189 result = runmeonce(100)
190 assert result == 200
191 assert len(calls_made) == 1
192 assert len(hits) == 1
193 assert len(misses) == 1
194
195 result = runmeonce(100)
196 assert result == 200
197 assert len(calls_made) == 1
198 assert len(hits) == 2
199 assert len(misses) == 1
200
201 result = runmeonce(200)
202 assert result == 400
203 assert len(calls_made) == 2
204 assert len(hits) == 2
205 assert len(misses) == 2
206
207
208 def test_cache_memoize_refresh():
209 calls_made = []
210
211 @cache_memoize(10)
212 def runmeonce(a):
213 calls_made.append(a)
214 return a * 2
215
216 runmeonce(10)
217 assert len(calls_made) == 1
218 runmeonce(10)
219 assert len(calls_made) == 1
220 runmeonce(10, _refresh=True)
221 assert len(calls_made) == 2
222
223
224 def test_cache_memoize_different_functions_same_arguments():
225 calls_made_1 = []
226 calls_made_2 = []
227
228 @cache_memoize(10)
229 def function_1(a):
230 calls_made_1.append(a)
231 return a * 2
232
233 @cache_memoize(10)
234 def function_2(a):
235 calls_made_2.append(a)
236 return a * 3
237
238 assert function_1(100) == 200
239 assert len(calls_made_1) == 1
240
241 assert function_1(100) == 200
242 assert len(calls_made_1) == 1
243
244 # Same arguments but to different function
245 assert function_2(100) == 300
246 assert len(calls_made_1) == 1
247 assert len(calls_made_2) == 1
248
249 assert function_2(100) == 300
250 assert len(calls_made_1) == 1
251 assert len(calls_made_2) == 1
252
253 assert function_2(1000) == 3000
254 assert len(calls_made_1) == 1
255 assert len(calls_made_2) == 2
256
257 # If you set the prefix, you can cross wire functions.
258 # Note sure why you'd ever want to do this though
259
260 @cache_memoize(
261 10, prefix=".".join((function_2.__module__, function_2.__qualname__))
262 )
263 def function_3(a):
264 raise Exception
265
266 assert function_3(100) == 300
267
268
269 def test_invalidate():
270 calls_made = []
271
272 @cache_memoize(10)
273 def function(argument):
274 calls_made.append(argument)
275 return random.random()
276
277 value = function(100)
278 assert value == function(100)
279 assert len(calls_made) == 1
280 function.invalidate(999) # different args
281 assert value == function(100)
282 assert len(calls_made) == 1
283 function.invalidate(100) # known args
284 assert value != function(100)
285 assert len(calls_made) == 2
286
287
288 def test_invalidate_with_refresh():
289 calls_made = []
290
291 @cache_memoize(10)
292 def function(argument):
293 calls_made.append(argument)
294 return random.random()
295
296 value = function(100, _refresh=False)
297 assert value == function(100, _refresh=False)
298 assert len(calls_made) == 1
299 new_value = function(100, _refresh=True)
300 assert value != new_value
301 assert len(calls_made) == 2
302
303 function.invalidate(999, _refresh=True) # different args
304 assert new_value == function(100, _refresh=False)
305 assert len(calls_made) == 2
306 function.invalidate(100, _refresh=0) # known args
307 assert new_value != function(100, _refresh=False)
308 assert len(calls_made) == 3
309
310
311 def test_get_cache_key():
312 @cache_memoize(10)
313 def funky(argument):
314 pass
315
316 assert funky.get_cache_key(100) == "eb96668ba0d14dc7748161fb1d000239"
317 assert funky.get_cache_key(100, _refresh=True) == "eb96668ba0d14dc7748161fb1d000239"
318
319
320 def test_cache_memoize_custom_alias():
321 calls_made = []
322
323 def runmeonce(a):
324 calls_made.append(a)
325 return a * 2
326
327 runmeonce_default = cache_memoize(10)(runmeonce)
328 runmeonce_locmem = cache_memoize(10, cache_alias="other")(runmeonce)
329
330 runmeonce_default(10)
331 assert len(calls_made) == 1
332 runmeonce_default(10)
333 assert len(calls_made) == 1
334 runmeonce_locmem(10)
335 assert len(calls_made) == 2
336 runmeonce_locmem(10)
337 assert len(calls_made) == 2
338
339
340 def test_cache_memoize_works_with_custom_key_generator():
341 calls_made = []
342
343 def key_generator(*args):
344 key = (":{}" * len(args)).format(*args)
345 return "custom_namespace:{}".format(key)
346
347 @cache_memoize(10, key_generator_callable=key_generator)
348 def runmeonce(arg1, arg2):
349 calls_made.append((arg1, arg2))
350 return arg1 + 1
351
352 runmeonce(1, 2)
353 runmeonce(1, 2)
354 assert len(calls_made) == 1
355 runmeonce(1, 3)
356 assert len(calls_made) == 2
357
358
359 def test_invalidate_with_custom_key_generator():
360 calls_made = []
361
362 def key_generator(*args):
363 key = (":{}" * len(args)).format(*args)
364 return "custom_namespace:{}".format(key)
365
366 @cache_memoize(10, key_generator_callable=key_generator)
367 def runmeonce(arg1, arg2):
368 calls_made.append((arg1, arg2))
369 return arg1 + 1
370
371 runmeonce(1, 2)
372 runmeonce(1, 2)
373 assert len(calls_made) == 1
374 runmeonce.invalidate(999, 10) # different args
375 assert runmeonce(1, 2)
376 assert len(calls_made) == 1
377
378 runmeonce.invalidate(1, 2) # known args
379 assert runmeonce(1, 2)
380 assert len(calls_made) == 2
381
382
383 def test_get_cache_key_with_custom_key_generator():
384 @cache_memoize(10, key_generator_callable=lambda x: x * 10)
385 def funky(argument):
386 pass
387
388 assert funky.get_cache_key("1") == "1111111111"
389
390
391 def test_get_cache_key_with_extra_components():
392 def funky(argument):
393 pass
394
395 fn1 = cache_memoize(10, extra={"version": 1})(funky)
396 fn2 = cache_memoize(10, extra={"version": 1})(funky)
397 fn3 = cache_memoize(10, extra={"version": 2})(funky)
398 fn4 = cache_memoize(10, extra=lambda x: x * 2)(funky)
399 fn5 = cache_memoize(10, extra=lambda x: x * 3)(funky)
400
401 assert fn1.get_cache_key(1) == fn2.get_cache_key(1)
402 assert fn2.get_cache_key(1) != fn3.get_cache_key(1)
403 assert fn4.get_cache_key(1) != fn5.get_cache_key(1)
404
405
406 def test_cache_memoize_none_value():
407 calls_made = []
408
409 @cache_memoize(10)
410 def runmeonce(a):
411 calls_made.append(a)
412
413 result = runmeonce(20)
414 assert len(calls_made) == 1
415 assert result is None
416 result = runmeonce(20)
417 assert len(calls_made) == 1
418 assert result is None
419
420
421 def test_cache_memoize_thread_safety():
422 calls_made = []
423
424 lock = Lock()
425
426 @cache_memoize(10, cache_alias="thread_local", args_rewrite=lambda *args: args[1:])
427 def runmeonce(_calls_made, a):
428 # Do not include _calls_made in the key.
429 # Because we're using threads, call_made cannot be used from the
430 # outer scope, so we need to inject it with the arguments.
431 with lock:
432 return _calls_made.append(a)
433
434 def func_that_calls_runmeonce(*args):
435 runmeonce(*args)
436
437 threads = [
438 Thread(target=func_that_calls_runmeonce, args=(calls_made, 1)) for x in range(2)
439 ]
440 for thread in threads:
441 thread.start()
442
443 for thread in threads:
444 thread.join()
445
446 assert len(calls_made) == 2
447
448
449 class TestException(Exception):
450 pass
451
452
453 class DerivedTestException(TestException):
454 pass
455
456
457 class SecondTestException(Exception):
458 pass
459
460
461 def test_dont_cache_exceptions():
462 calls_made = []
463
464 @cache_memoize(10, prefix="dont_cache_exceptions")
465 def raise_test_exception():
466 calls_made.append(1)
467 raise TestException
468
469 # Caching of exceptions i turned off. These should both call the function
470 # and propagate the exception.
471 with pytest.raises(TestException):
472 raise_test_exception()
473 with pytest.raises(TestException):
474 raise_test_exception()
475 assert len(calls_made) == 2
476
477
478 def test_cache_exception():
479 calls_made = []
480
481 @cache_memoize(10, cache_exceptions=TestException, prefix="cache_exceptions")
482 def raise_test_exception():
483 calls_made.append(1)
484 raise TestException
485
486 # The first call should be cached, raised and the second call should
487 # re-raise the cached exception without calling the cached function.
488 with pytest.raises(TestException):
489 raise_test_exception()
490 with pytest.raises(TestException):
491 raise_test_exception()
492 assert len(calls_made) == 1
493
494
495 def test_cache_exceptions():
496 calls_made = []
497
498 # It should be possible to specify a tuple of exceptions to cache.
499 @cache_memoize(
500 10,
501 cache_exceptions=(TestException, SecondTestException),
502 prefix="cache_exceptions",
503 )
504 def raise_test_exception():
505 calls_made.append(1)
506 raise TestException
507
508 with pytest.raises(TestException):
509 raise_test_exception()
510 with pytest.raises(TestException):
511 raise_test_exception()
512 assert len(calls_made) == 1
513
514
515 def test_cache_derived_exceptions():
516 calls_made = []
517
518 @cache_memoize(10, cache_exceptions=TestException, prefix="cache_exceptions")
519 def raise_test_exception():
520 calls_made.append(1)
521 raise DerivedTestException
522
523 # We're raising DerivedTestException, which is a subclass of TestException
524 # and should thus be cached.
525 with pytest.raises(DerivedTestException):
526 raise_test_exception()
527 with pytest.raises(DerivedTestException):
528 raise_test_exception()
529 assert len(calls_made) == 1
530
531
532 def test_dont_cache_unrelated_exceptions():
533 calls_made = []
534
535 @cache_memoize(10, cache_exceptions=TestException, prefix="cache_exceptions")
536 def raise_test_exception():
537 calls_made.append(1)
538 raise SecondTestException
539
540 # We're raising SecondTestException, which is not a subclass
541 # of TestException, so the calls shouldn't be cached.
542 with pytest.raises(SecondTestException):
543 raise_test_exception()
544 with pytest.raises(SecondTestException):
545 raise_test_exception()
546 assert len(calls_made) == 2