-
Notifications
You must be signed in to change notification settings - Fork 148
/
test_decorators.py
489 lines (379 loc) · 18.2 KB
/
test_decorators.py
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
import asyncio
import sys
import pytest
import random
import inspect
import asynctest
from asynctest import MagicMock, CoroutineMock, ANY
from aiocache.base import BaseCache
from aiocache import cached, cached_stampede, multi_cached, SimpleMemoryCache
from aiocache.decorators import _get_args_dict
from aiocache.serializers import JsonSerializer
async def stub(*args, value=None, seconds=0, **kwargs):
await asyncio.sleep(seconds)
if value:
return str(value)
return str(random.randint(1, 50))
class TestCached:
@pytest.fixture
def decorator(self, mocker, mock_cache):
with asynctest.patch("aiocache.decorators._get_cache", return_value=mock_cache):
yield cached()
@pytest.fixture
def decorator_call(self, decorator):
d = decorator(stub)
yield d
@pytest.fixture(autouse=True)
def spy_stub(self, mocker):
module = sys.modules[globals()['__name__']]
mocker.spy(module, 'stub')
def test_init(self):
c = cached(
ttl=1, key="key", key_from_attr="key_attr", cache=SimpleMemoryCache,
plugins=None, alias=None, noself=False, namespace="test")
assert c.ttl == 1
assert c.key == "key"
assert c.key_builder is None
assert c.key_from_attr == "key_attr"
assert c.cache is None
assert c._cache == SimpleMemoryCache
assert c._serializer == JsonSerializer
assert c._kwargs == {'namespace': 'test'}
def test_fails_at_instantiation(self):
with pytest.raises(TypeError):
@cached(wrong_param=1)
async def fn(n):
return n
def test_alias_takes_precedence(self, mock_cache):
with asynctest.patch(
"aiocache.decorators.caches.create",
MagicMock(return_value=mock_cache)) as mock_create:
c = cached(alias='default', cache=SimpleMemoryCache, namespace='test')
c(stub)
mock_create.assert_called_with('default')
assert c.cache is mock_cache
def test_get_cache_key_with_key(self, decorator):
decorator.key = "key"
decorator.key_from_attr = "ignore_me"
assert decorator.get_cache_key(stub, (1, 2), {'a': 1, 'b': 2}) == 'key'
def test_get_cache_key_with_key_attr(self, decorator):
decorator.key_from_attr = "pick_me"
assert decorator.get_cache_key(stub, (1, 2), {'pick_me': "key"}) == 'key'
def test_get_cache_key_without_key_and_attr(self, decorator):
assert decorator.get_cache_key(
stub, (1, 2), {'a': 1, 'b': 2}) == "stub(1, 2)[('a', 1), ('b', 2)]"
def test_get_cache_key_without_key_and_attr_noself(self, decorator):
decorator.noself = True
assert decorator.get_cache_key(
stub, ('self', 1, 2), {'a': 1, 'b': 2}) == "stub(1, 2)[('a', 1), ('b', 2)]"
def test_get_cache_key_with_key_builder(self, decorator):
decorator.key_builder = lambda *args, **kwargs: kwargs['market'].upper()
assert decorator.get_cache_key(
stub, (), {'market': 'es'}) == 'ES'
@pytest.mark.asyncio
async def test_calls_get_and_returns(self, decorator, decorator_call):
decorator.cache.get = CoroutineMock(return_value=1)
await decorator_call()
decorator.cache.get.assert_called_with('stub()[]')
assert decorator.cache.set.call_count == 0
assert stub.call_count == 0
@pytest.mark.asyncio
async def test_get_from_cache_returns(self, decorator, decorator_call):
decorator.cache.get = CoroutineMock(return_value=1)
assert await decorator.get_from_cache("key") == 1
@pytest.mark.asyncio
async def test_get_from_cache_exception(self, decorator, decorator_call):
decorator.cache.get = CoroutineMock(side_effect=Exception)
assert await decorator.get_from_cache("key") is None
@pytest.mark.asyncio
async def test_get_from_cache_none(self, decorator, decorator_call):
decorator.cache.get = CoroutineMock(return_value=None)
assert await decorator.get_from_cache("key") is None
@pytest.mark.asyncio
async def test_calls_fn_set_when_get_none(self, mocker, decorator, decorator_call):
mocker.spy(decorator, 'get_from_cache')
mocker.spy(decorator, 'set_in_cache')
decorator.cache.get = CoroutineMock(return_value=None)
await decorator_call(value="value")
assert decorator.get_from_cache.call_count == 1
decorator.set_in_cache.assert_called_with("stub()[('value', 'value')]", "value")
stub.assert_called_once_with(value="value")
@pytest.mark.asyncio
async def test_calls_fn_raises_exception(self, mocker, decorator, decorator_call):
decorator.cache.get = CoroutineMock(return_value=None)
stub.side_effect = Exception()
with pytest.raises(Exception):
assert await decorator_call()
@pytest.mark.asyncio
async def test_set_calls_set(self, decorator, decorator_call):
await decorator.set_in_cache("key", "value")
decorator.cache.set.assert_called_with("key", "value", ttl=None)
@pytest.mark.asyncio
async def test_set_calls_set_ttl(self, decorator, decorator_call):
decorator.ttl = 10
await decorator.set_in_cache("key", "value")
decorator.cache.set.assert_called_with("key", "value", ttl=decorator.ttl)
@pytest.mark.asyncio
async def test_set_catches_exception(self, decorator, decorator_call):
decorator.cache.set = CoroutineMock(side_effect=Exception)
assert await decorator.set_in_cache("key", "value") is None
@pytest.mark.asyncio
async def test_decorate(self, mock_cache):
mock_cache.get = CoroutineMock(return_value=None)
with asynctest.patch("aiocache.decorators._get_cache", return_value=mock_cache):
@cached()
async def fn(n):
return n
assert await fn(1) == 1
assert await fn(2) == 2
@pytest.mark.asyncio
async def test_keeps_signature(self, mock_cache):
with asynctest.patch("aiocache.decorators._get_cache", return_value=mock_cache):
@cached()
async def what(self, a, b):
return "1"
assert what.__name__ == "what"
assert str(inspect.signature(what)) == '(self, a, b)'
assert inspect.getfullargspec(what.__wrapped__).args == ['self', 'a', 'b']
@pytest.mark.asyncio
async def test_reuses_cache_instance(self):
with asynctest.patch("aiocache.decorators._get_cache") as get_c:
cache = MagicMock(spec=BaseCache)
get_c.side_effect = [cache, None]
@cached()
async def what():
pass
await what()
await what()
assert get_c.call_count == 1
assert cache.get.call_count == 2
class TestCachedStampede:
@pytest.fixture
def decorator(self, mocker, mock_cache):
with asynctest.patch("aiocache.decorators._get_cache", return_value=mock_cache):
yield cached_stampede()
@pytest.fixture
def decorator_call(self, decorator):
yield decorator(stub)
@pytest.fixture(autouse=True)
def spy_stub(self, mocker):
module = sys.modules[globals()['__name__']]
mocker.spy(module, 'stub')
def test_inheritance(self):
assert isinstance(cached_stampede(), cached)
def test_init(self):
c = cached_stampede(
lease=3, ttl=1, key="key", key_from_attr="key_attr", cache=SimpleMemoryCache,
plugins=None, alias=None, noself=False, namespace="test")
assert c.ttl == 1
assert c.key == "key"
assert c.key_from_attr == "key_attr"
assert c.cache is None
assert c._cache == SimpleMemoryCache
assert c._serializer == JsonSerializer
assert c.lease == 3
assert c._kwargs == {'namespace': 'test'}
@pytest.mark.asyncio
async def test_calls_get_and_returns(self, decorator, decorator_call):
decorator.cache.get = CoroutineMock(return_value=1)
await decorator_call()
decorator.cache.get.assert_called_with('stub()[]')
assert decorator.cache.set.call_count == 0
assert stub.call_count == 0
@pytest.mark.asyncio
async def test_calls_fn_raises_exception(self, mocker, decorator, decorator_call):
decorator.cache.get = CoroutineMock(return_value=None)
stub.side_effect = Exception()
with pytest.raises(Exception):
assert await decorator_call()
@pytest.mark.asyncio
async def test_calls_redlock(self, decorator, decorator_call):
decorator.cache.get = CoroutineMock(return_value=None)
await decorator_call(value="value")
assert decorator.cache.get.call_count == 2
assert decorator.cache._redlock.call_count == 1
decorator.cache.set.assert_called_with(
"stub()[('value', 'value')]", "value", ttl=None)
stub.assert_called_once_with(value="value")
@pytest.mark.asyncio
async def test_calls_locked_client(self, decorator, decorator_call):
decorator.cache.get = CoroutineMock(side_effect=[None, None, None, "value"])
decorator.cache._add = CoroutineMock(side_effect=[True, ValueError])
decorator.cache._redlock_release = CoroutineMock(side_effect=[1, 0])
await asyncio.gather(decorator_call(value="value"), decorator_call(value="value"))
assert decorator.cache.get.call_count == 4
assert decorator.cache._redlock.call_count == 2
decorator.cache.set.assert_called_with(
"stub()[('value', 'value')]", "value", ttl=None)
assert stub.call_count == 1
async def stub_dict(*args, keys=None, **kwargs):
values = {
'a': random.randint(1, 50),
'b': random.randint(1, 50),
'c': random.randint(1, 50)
}
return {k: values.get(k) for k in keys}
class TestMultiCached:
@pytest.fixture
def decorator(self, mocker, mock_cache):
with asynctest.patch("aiocache.decorators._get_cache", return_value=mock_cache):
yield multi_cached(keys_from_attr="keys")
@pytest.fixture
def decorator_call(self, decorator):
d = decorator(stub_dict)
decorator._conn = decorator.cache.get_connection()
yield d
@pytest.fixture(autouse=True)
def spy_stub_dict(self, mocker):
module = sys.modules[globals()['__name__']]
mocker.spy(module, 'stub_dict')
def test_init(self):
mc = multi_cached(
keys_from_attr="keys", key_builder=None, ttl=1, cache=SimpleMemoryCache,
plugins=None, alias=None, namespace="test")
assert mc.ttl == 1
assert mc.key_builder('key') == 'key'
assert mc.keys_from_attr == "keys"
assert mc.cache is None
assert mc._cache == SimpleMemoryCache
assert mc._serializer == JsonSerializer
assert mc._kwargs == {'namespace': 'test'}
def test_fails_at_instantiation(self):
with pytest.raises(TypeError):
@multi_cached(wrong_param=1)
async def fn(n):
return n
def test_alias_takes_precedence(self, mock_cache):
with asynctest.patch(
"aiocache.decorators.caches.create",
MagicMock(return_value=mock_cache)) as mock_create:
mc = multi_cached(
keys_from_attr="keys", alias='default', cache=SimpleMemoryCache, namespace='test')
mc(stub_dict)
mock_create.assert_called_with('default')
assert mc.cache is mock_cache
def test_get_cache_keys(self, decorator):
assert decorator.get_cache_keys(
stub_dict, (), {'keys': ['a', 'b']}) == (['a', 'b'], ())
def test_get_cache_keys_empty_list(self, decorator):
assert decorator.get_cache_keys(stub_dict, (), {'keys': []}) == ([], ())
def test_get_cache_keys_missing_kwarg(self, decorator):
with pytest.raises(KeyError):
assert decorator.get_cache_keys(stub_dict, (), {})
def test_get_cache_keys_arg_key_from_attr(self, decorator):
def fake(keys, a=1, b=2):
pass
assert decorator.get_cache_keys(fake, (['a']), {}) == (['a'], (['a'],))
def test_get_cache_keys_with_none(self, decorator):
assert decorator.get_cache_keys(stub_dict, (), {'keys': None}) == ([], ())
def test_get_cache_keys_with_key_builder(self, decorator):
decorator.key_builder = lambda key, *args, **kwargs: kwargs['market'] + '_' + key.upper()
assert decorator.get_cache_keys(
stub_dict, (), {'keys': ['a', 'b'], 'market': 'ES'}) == (['ES_A', 'ES_B'], ())
@pytest.mark.asyncio
async def test_get_from_cache(self, decorator, decorator_call):
decorator.cache.multi_get = CoroutineMock(return_value=[1, 2, 3])
assert await decorator.get_from_cache('a', 'b', 'c') == [1, 2, 3]
decorator.cache.multi_get.assert_called_with(('a', 'b', 'c'))
@pytest.mark.asyncio
async def test_get_from_cache_no_keys(self, decorator, decorator_call):
assert await decorator.get_from_cache() == []
assert decorator.cache.multi_get.call_count == 0
@pytest.mark.asyncio
async def test_get_from_cache_exception(self, decorator, decorator_call):
decorator.cache.multi_get = CoroutineMock(side_effect=Exception)
assert await decorator.get_from_cache('a', 'b', 'c') == [None, None, None]
decorator.cache.multi_get.assert_called_with(('a', 'b', 'c'))
@pytest.mark.asyncio
async def test_get_from_cache_conn(self, decorator, decorator_call):
decorator._conn._conn = MagicMock()
decorator.cache.multi_get = CoroutineMock(return_value=[1, 2, 3])
assert await decorator.get_from_cache('a', 'b', 'c') == [1, 2, 3]
decorator.cache.multi_get.assert_called_with(('a', 'b', 'c'))
@pytest.mark.asyncio
async def test_calls_no_keys(self, decorator, decorator_call):
await decorator_call(keys=[])
assert decorator.cache.multi_get.call_count == 0
assert stub_dict.call_count == 1
@pytest.mark.asyncio
async def test_returns_from_multi_set(self, mocker, decorator, decorator_call):
mocker.spy(decorator, 'get_from_cache')
mocker.spy(decorator, 'set_in_cache')
decorator.cache.multi_get = CoroutineMock(return_value=[1, 2])
assert await decorator_call(1, keys=['a', 'b']) == {'a': 1, 'b': 2}
decorator.get_from_cache.assert_called_once_with('a', 'b')
assert decorator.set_in_cache.call_count == 0
assert stub_dict.call_count == 0
@pytest.mark.asyncio
async def test_calls_fn_multi_set_when_multi_get_none(self, mocker, decorator, decorator_call):
mocker.spy(decorator, 'get_from_cache')
mocker.spy(decorator, 'set_in_cache')
decorator.cache.multi_get = CoroutineMock(return_value=[None, None])
ret = await decorator_call(1, keys=['a', 'b'], value='value')
decorator.get_from_cache.assert_called_once_with('a', 'b')
decorator.set_in_cache.assert_called_with(ret, ANY, ANY)
stub_dict.assert_called_once_with(1, keys=['a', 'b'], value="value")
@pytest.mark.asyncio
async def test_calls_fn_with_only_missing_keys(self, mocker, decorator, decorator_call):
mocker.spy(decorator, 'set_in_cache')
decorator.cache.multi_get = CoroutineMock(return_value=[1, None])
assert await decorator_call(1, keys=['a', 'b'], value='value') == {'a': ANY, 'b': ANY}
decorator.set_in_cache.assert_called_once_with({'a': ANY, 'b': ANY}, ANY, ANY)
stub_dict.assert_called_once_with(1, keys=['b'], value="value")
@pytest.mark.asyncio
async def test_calls_fn_raises_exception(self, mocker, decorator, decorator_call):
decorator.cache.multi_get = CoroutineMock(return_value=[None])
stub_dict.side_effect = Exception()
with pytest.raises(Exception):
assert await decorator_call(keys=[])
@pytest.mark.asyncio
async def test_set_in_cache(self, decorator, decorator_call):
await decorator.set_in_cache({'a': 1, 'b': 2}, (), {})
call_args = decorator.cache.multi_set.call_args[0][0]
assert ('a', 1) in call_args
assert ('b', 2) in call_args
call_args = decorator.cache.multi_set.call_args[1]['ttl'] is None
@pytest.mark.asyncio
async def test_set_in_cache_with_ttl(self, decorator, decorator_call):
decorator.ttl = 10
await decorator.set_in_cache({'a': 1, 'b': 2}, (), {})
assert decorator.cache.multi_set.call_args[1]['ttl'] == decorator.ttl
@pytest.mark.asyncio
async def test_set_in_cache_exception(self, decorator, decorator_call):
decorator.cache.multi_set = CoroutineMock(side_effect=Exception)
assert await decorator.set_in_cache({'a': 1, 'b': 2}, (), {}) is None
@pytest.mark.asyncio
async def test_decorate(self, mock_cache):
mock_cache.multi_get = CoroutineMock(return_value=[None])
with asynctest.patch("aiocache.decorators._get_cache", return_value=mock_cache):
@multi_cached(keys_from_attr="keys")
async def fn(keys=None):
return {'test': 1}
assert await fn(keys=['test']) == {'test': 1}
assert await fn(keys=['test']) == {'test': 1}
@pytest.mark.asyncio
async def test_keeps_signature(self):
@multi_cached(keys_from_attr="keys")
async def what(self, keys=None, what=1):
return "1"
assert what.__name__ == "what"
assert str(inspect.signature(what)) == '(self, keys=None, what=1)'
assert inspect.getfullargspec(what.__wrapped__).args == ['self', 'keys', 'what']
@pytest.mark.asyncio
async def test_reuses_cache_instance(self):
with asynctest.patch("aiocache.decorators._get_cache") as get_c:
cache = MagicMock(spec=BaseCache)
cache.multi_get.return_value = [None]
get_c.side_effect = [cache, None]
@multi_cached("keys")
async def what(keys=None):
return {}
await what(keys=['a'])
await what(keys=['a'])
assert get_c.call_count == 1
assert cache.multi_get.call_count == 2
def test_get_args_dict():
def fn(a, b, *args, keys=None, **kwargs):
pass
args_dict = _get_args_dict(fn, ('a', 'b', 'c', 'd'), {'what': 'what'})
assert args_dict == {'a': 'a', 'b': 'b', 'keys': None, 'what': 'what'}