-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathtest_general.py
More file actions
505 lines (400 loc) · 13.1 KB
/
test_general.py
File metadata and controls
505 lines (400 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
"""Non-core-specific tests for cachier."""
import datetime
import functools
import os
import queue
import subprocess # nosec: B404
import threading
from contextlib import suppress
from random import random
from time import sleep, time
import pytest
import cachier
from cachier.core import (
DEFAULT_MAX_WORKERS,
MAX_WORKERS_ENVAR_NAME,
_get_executor,
_max_workers,
_set_max_workers,
)
from tests.mongo_tests.test_mongo_core import (
_test_mongetter,
)
MONGO_DELTA_LONG = datetime.timedelta(seconds=10)
def test_information():
print("\ncachier version: ", end="")
print(cachier.__version__)
def test_max_workers():
"""Just call this function for coverage."""
with suppress(KeyError):
del os.environ[MAX_WORKERS_ENVAR_NAME]
assert _max_workers() == DEFAULT_MAX_WORKERS
def test_get_executor():
"""Just call this function for coverage."""
_get_executor()
_get_executor(False)
_get_executor(True)
def test_set_max_workers():
"""Just call this function for coverage."""
_set_max_workers(9)
parametrize_keys = "mongetter,stale_after,separate_files"
parametrize_values = [
pytest.param(_test_mongetter, MONGO_DELTA_LONG, False, marks=pytest.mark.mongo),
(None, None, False),
(None, None, True),
]
@pytest.mark.parametrize(parametrize_keys, parametrize_values)
def test_wait_for_calc_timeout_ok(mongetter, stale_after, separate_files):
@cachier.cachier(
mongetter=mongetter,
stale_after=stale_after,
separate_files=separate_files,
next_time=False,
wait_for_calc_timeout=2,
)
def _wait_for_calc_timeout_fast(arg_1, arg_2):
"""Some function."""
sleep(1)
return random() + arg_1 + arg_2
def _calls_wait_for_calc_timeout_fast(res_queue):
res = _wait_for_calc_timeout_fast(1, 2)
res_queue.put(res)
""" Testing calls that avoid timeouts store the values in cache. """
_wait_for_calc_timeout_fast.clear_cache()
val1 = _wait_for_calc_timeout_fast(1, 2)
val2 = _wait_for_calc_timeout_fast(1, 2)
assert val1 == val2
res_queue = queue.Queue()
thread1 = threading.Thread(
target=_calls_wait_for_calc_timeout_fast,
kwargs={"res_queue": res_queue},
daemon=True,
)
thread2 = threading.Thread(
target=_calls_wait_for_calc_timeout_fast,
kwargs={"res_queue": res_queue},
daemon=True,
)
thread1.start()
thread2.start()
sleep(2)
thread1.join(timeout=2)
thread2.join(timeout=2)
assert res_queue.qsize() == 2
res1 = res_queue.get()
res2 = res_queue.get()
assert res1 == res2 # Timeout did not kick in, a single call was done
@pytest.mark.parametrize(parametrize_keys, parametrize_values)
def test_wait_for_calc_timeout_slow(mongetter, stale_after, separate_files):
@cachier.cachier(
mongetter=mongetter,
stale_after=stale_after,
separate_files=separate_files,
next_time=False,
wait_for_calc_timeout=2,
)
def _wait_for_calc_timeout_slow(arg_1, arg_2):
sleep(3)
return random() + arg_1 + arg_2
def _calls_wait_for_calc_timeout_slow(res_queue):
res = _wait_for_calc_timeout_slow(1, 2)
res_queue.put(res)
"""Testing for calls timing out to be performed twice when needed."""
_wait_for_calc_timeout_slow.clear_cache()
res_queue = queue.Queue()
thread1 = threading.Thread(
target=_calls_wait_for_calc_timeout_slow,
kwargs={"res_queue": res_queue},
daemon=True,
)
thread2 = threading.Thread(
target=_calls_wait_for_calc_timeout_slow,
kwargs={"res_queue": res_queue},
daemon=True,
)
thread1.start()
thread2.start()
sleep(1)
res3 = _wait_for_calc_timeout_slow(1, 2)
sleep(4)
thread1.join(timeout=4)
thread2.join(timeout=4)
assert res_queue.qsize() == 2
res1 = res_queue.get()
res2 = res_queue.get()
assert res1 != res2 # Timeout kicked in. Two calls were done
res4 = _wait_for_calc_timeout_slow(1, 2)
# One of the cached values is returned
assert res1 == res4 or res2 == res4 or res3 == res4
@pytest.mark.parametrize(
("mongetter", "backend"),
[
pytest.param(_test_mongetter, "mongo", marks=pytest.mark.mongo),
(None, "memory"),
(None, "pickle"),
],
)
def test_precache_value(mongetter, backend):
@cachier.cachier(backend=backend, mongetter=mongetter)
def dummy_func(arg_1, arg_2):
"""Some function."""
return arg_1 + arg_2
assert dummy_func.precache_value(2, 2, value_to_cache=5) == 5
assert dummy_func(2, 2) == 5
dummy_func.clear_cache()
assert dummy_func(2, 2) == 4
assert dummy_func.precache_value(2, arg_2=2, value_to_cache=5) == 5
assert dummy_func(2, arg_2=2) == 5
@pytest.mark.parametrize(
("mongetter", "backend"),
[
pytest.param(_test_mongetter, "mongo", marks=pytest.mark.mongo),
(None, "memory"),
(None, "pickle"),
],
)
def test_ignore_self_in_methods(mongetter, backend):
class DummyClass:
@cachier.cachier(backend=backend, mongetter=mongetter, allow_non_static_methods=True)
def takes_2_seconds(self, arg_1, arg_2):
"""Some function."""
sleep(2)
return arg_1 + arg_2
test_object_1 = DummyClass()
test_object_2 = DummyClass()
test_object_1.takes_2_seconds.clear_cache()
test_object_2.takes_2_seconds.clear_cache()
assert test_object_1.takes_2_seconds(1, 2) == 3
start = time()
assert test_object_2.takes_2_seconds(1, 2) == 3
end = time()
assert end - start < 1
def test_hash_params_deprecation():
with pytest.deprecated_call(match="hash_params will be removed"):
@cachier.cachier(hash_params=lambda a, k: "key")
def test():
return "value"
assert test() == "value"
def test_separate_processes():
test_args = ("python", "tests/standalone_script.py")
run_params = {"args": test_args, "capture_output": True, "text": True}
run_process = functools.partial(subprocess.run, **run_params)
result = run_process()
assert result.stdout.strip() == "two 2"
start = time()
result = run_process()
end = time()
assert result.stdout.strip() == "two 2"
assert end - start < 3
def test_global_disable():
@cachier.cachier()
def get_random() -> float:
return random()
get_random.clear_cache()
result_1 = get_random()
result_2 = get_random()
cachier.disable_caching()
assert cachier.config._global_params.caching_enabled is False
result_3 = get_random()
cachier.enable_caching()
assert cachier.config._global_params.caching_enabled is True
result_4 = get_random()
assert result_1 == result_2 == result_4
assert result_1 != result_3
def test_global_disable_function():
@cachier.cachier()
def test():
return True
cachier.disable_caching()
try:
assert test()
finally:
cachier.enable_caching()
def test_global_disable_method():
class Test:
@cachier.cachier(allow_non_static_methods=True)
def test(self):
return True
cachier.disable_caching()
try:
assert Test().test()
finally:
cachier.enable_caching()
def test_global_disable_method_with_args():
class Test:
@cachier.cachier(allow_non_static_methods=True)
def test(self, test):
return test
cachier.disable_caching()
try:
assert Test().test(1) == 1
finally:
cachier.enable_caching()
def test_global_disable_method_with_optional_parameters():
class Test:
def __init__(self, val):
self.val = val
@cachier.cachier(allow_non_static_methods=True)
def test(self, test=0):
return self.val + test
cachier.disable_caching()
try:
assert Test(1).test(test=1) == 2
finally:
cachier.enable_caching()
def test_global_disable_method_with_args_and_optional_parameters():
class Test:
def __init__(self, val):
self.val = val
@cachier.cachier(allow_non_static_methods=True)
def test(self, test1, test2=0):
return self.val + test1 + test2
cachier.disable_caching()
try:
assert Test(1).test(2, 3) == 6
finally:
cachier.enable_caching()
def test_none_not_cached_by_default():
count = 0
@cachier.cachier()
def do_operation():
nonlocal count
count += 1
return None
do_operation.clear_cache()
assert count == 0
do_operation()
do_operation()
assert count == 2
def test_allow_caching_none():
count = 0
@cachier.cachier(allow_none=True)
def do_operation():
nonlocal count
count += 1
return None
do_operation.clear_cache()
assert count == 0
do_operation()
do_operation()
assert count == 1
def test_identical_inputs():
count = 0
@cachier.cachier()
def dummy_func(a: int, b: int = 2, c: int = 3):
nonlocal count
count += 1
return a + b + c
dummy_func.clear_cache()
assert count == 0
assert dummy_func(1, 2, 3) == 6
assert dummy_func(1, 2, c=3) == 6
assert dummy_func(1, b=2, c=3) == 6
assert dummy_func(a=1, b=2, c=3) == 6
assert count == 1
def test_list_inputs():
count = 0
@cachier.cachier()
def dummy_func(a: list, b: list = [2]): # noqa: B006
nonlocal count
count += 1
return a + b
dummy_func.clear_cache()
assert count == 0
assert dummy_func([1]) == [1, 2]
assert dummy_func([1], [2]) == [1, 2]
assert dummy_func([1], b=[2]) == [1, 2]
assert dummy_func(a=[1], b=[2]) == [1, 2]
assert count == 1
def test_order_independent_kwargs_handling():
count = 0
@cachier.cachier()
def dummy_func(a, b):
nonlocal count
count += 1
return a + b
dummy_func.clear_cache()
assert count == 0
assert dummy_func(a=1, b=2) == 3
assert dummy_func(a=1, b=2) == 3
assert dummy_func(b=2, a=1) == 3
assert count == 1
@pytest.mark.parametrize("backend", ["memory", "pickle"])
def test_diff_functions_same_args(tmpdir, backend: str):
count_p = count_m = 0
@cachier.cachier(cache_dir=tmpdir, backend=backend)
def fn_plus(a, b=2):
nonlocal count_p
count_p += 1
return a + b
@cachier.cachier(cache_dir=tmpdir, backend=backend)
def fn_minus(a, b=2):
nonlocal count_m
count_m += 1
return a - b
assert count_p == count_m == 0
for fn, expected in [(fn_plus, 3), (fn_minus, -1)]:
assert fn(1) == expected
assert fn(a=1, b=2) == expected
assert count_p == 1
assert count_m == 1
@pytest.mark.parametrize("backend", ["memory", "pickle"])
def test_runtime_handling(tmpdir, backend):
count_p = count_m = 0
def fn_plus(a, b=2):
nonlocal count_p
count_p += 1
return a + b
def fn_minus(a, b=2):
nonlocal count_m
count_m += 1
return a - b
cachier_ = cachier.cachier(cache_dir=tmpdir, backend=backend)
assert count_p == count_m == 0
for fn, expected in [(fn_plus, 3), (fn_minus, -1)]:
assert cachier_(fn)(1, 2) == expected, f"for {fn.__name__} inline"
assert cachier_(fn)(a=1, b=2) == expected, f"for {fn.__name__} inline"
assert count_p == 1
assert count_m == 1
for fn, expected in [(fn_plus, 5), (fn_minus, 1)]:
assert cachier_(fn)(3, 2) == expected, f"for {fn.__name__} inline"
assert cachier_(fn)(a=3, b=2) == expected, f"for {fn.__name__} inline"
assert count_p == 2
assert count_m == 2
def test_partial_handling(tmpdir):
count_p = count_m = 0
def fn_plus(a, b=2):
nonlocal count_p
count_p += 1
return a + b
def fn_minus(a, b=2):
nonlocal count_m
count_m += 1
return a - b
cachier_ = cachier.cachier(cache_dir=tmpdir)
assert count_p == count_m == 0
for fn, expected in [(fn_plus, 3), (fn_minus, -1)]:
dummy_ = functools.partial(fn, 1)
assert cachier_(dummy_)() == expected, f"for {fn.__name__} wrapped"
dummy_ = functools.partial(fn, 1)
assert cachier_(dummy_)(2) == expected, f"for {fn.__name__} wrapped"
dummy_ = functools.partial(fn, a=1)
assert cachier_(dummy_)() == expected, f"for {fn.__name__} wrapped"
dummy_ = functools.partial(fn, b=2)
assert cachier_(dummy_)(1) == expected, f"for {fn.__name__} wrapped"
dummy_ = functools.partial(fn, b=2)
expected_str = f"for {fn.__name__} wrapped"
assert cachier_(dummy_)(1, b=2) == expected, expected_str
assert cachier_(fn)(1, 2) == expected, f"for {fn.__name__} inline"
assert cachier_(fn)(a=1, b=2) == expected, f"for {fn.__name__} inline"
assert count_p == 1
assert count_m == 1
@pytest.mark.parametrize("backend", ["memory", "pickle"])
def test_raise_exception(tmpdir, backend: str):
@cachier.cachier(cache_dir=tmpdir, backend=backend, allow_none=True)
def tmp_test(_):
raise RuntimeError("always raise")
with pytest.raises(RuntimeError):
tmp_test(123)
with pytest.raises(RuntimeError):
tmp_test(123)