-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathtest_async_redis_core.py
More file actions
299 lines (224 loc) · 9.51 KB
/
test_async_redis_core.py
File metadata and controls
299 lines (224 loc) · 9.51 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
"""Tests for async Redis client with async functions."""
import asyncio
from datetime import datetime, timedelta
from random import random
import pytest
from cachier import cachier
from cachier.core import _is_async_redis_client
from cachier.cores.redis import _RedisCore
from tests.redis_tests.clients import (
_AsyncInMemoryRedis,
_NoMethodsObject,
_PartialAsyncRedis,
_SyncInMemoryRedis,
)
@pytest.mark.redis
def test_async_client_over_sync_async_functions():
pytest.importorskip("redis")
async def get_async_client():
return _AsyncInMemoryRedis()
@cachier(backend="redis", redis_client=get_async_client)
async def async_cached_redis_with_async_client(_: int) -> int:
return 1
assert callable(async_cached_redis_with_async_client)
with pytest.raises(TypeError, match="Async redis_client callable requires an async cached function."):
@cachier(backend="redis", redis_client=get_async_client)
def sync_cached_redis_with_async_client(_: int) -> int:
return 1
async_client_instance = _AsyncInMemoryRedis()
@cachier(backend="redis", redis_client=async_client_instance)
async def async_cached_redis_with_async_client_instance(_: int) -> int:
return 1
assert callable(async_cached_redis_with_async_client_instance)
with pytest.raises(TypeError, match="Async Redis client requires an async cached function."):
@cachier(backend="redis", redis_client=async_client_instance)
def sync_cached_redis_with_async_client_instance(_: int) -> int:
return 1
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_client_factory():
pytest.importorskip("redis")
client = _AsyncInMemoryRedis()
async def get_redis_client():
return client
@cachier(backend="redis", redis_client=get_redis_client)
async def async_cached_redis(x: int) -> float:
await asyncio.sleep(0.01)
return random() + x
val1 = await async_cached_redis(3)
val2 = await async_cached_redis(3)
assert val1 == val2
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_client_factory_method_args_and_kwargs():
pytest.importorskip("redis")
client = _AsyncInMemoryRedis()
async def get_redis_client():
return client
call_count = 0
class _RedisMethods:
@cachier(backend="redis", redis_client=get_redis_client, allow_non_static_methods=True)
async def async_cached_redis_method_args_kwargs(self, x: int, y: int) -> int:
nonlocal call_count
call_count += 1
await asyncio.sleep(0.01)
return call_count
obj = _RedisMethods()
val1 = await obj.async_cached_redis_method_args_kwargs(1, 2)
val2 = await obj.async_cached_redis_method_args_kwargs(y=2, x=1)
assert val1 == val2 == 1
assert call_count == 1
def _build_async_core(client: _AsyncInMemoryRedis) -> _RedisCore:
"""Build a Redis core configured for async tests."""
core = _RedisCore(hash_func=None, redis_client=client, wait_for_calc_timeout=10)
def _func(x: int) -> int:
return x
core.set_func(_func)
return core
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_core_helpers_and_client_resolution():
pytest.importorskip("redis")
assert _RedisCore._get_bool_field({"processing": "true"}, "processing") is True
client = _AsyncInMemoryRedis()
core = _build_async_core(client)
assert await core._resolve_redis_client_async() is client
async def async_client_factory():
return client
core_with_async_factory = _RedisCore(
hash_func=None,
redis_client=async_client_factory,
wait_for_calc_timeout=10,
)
core_with_async_factory.set_func(lambda x: x)
assert await core_with_async_factory._resolve_redis_client_async() is client
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_core_entry_read_write_paths():
pytest.importorskip("redis")
client = _AsyncInMemoryRedis()
core = _build_async_core(client)
assert await core.aset_entry("k1", {"value": 1}) is True
_, entry = await core.aget_entry_by_key("k1")
assert entry is not None
assert entry.value == {"value": 1}
_, none_entry = await core.aget_entry_by_key("missing")
assert none_entry is None
redis_key = core._get_redis_key("invalid-ts")
await client.hset(
redis_key,
mapping={
"timestamp": b"\xff",
"stale": "false",
"processing": "false",
"completed": "true",
},
)
with pytest.warns(UserWarning, match="Redis get_entry_by_key failed"):
result = await core.aget_entry_by_key("invalid-ts")
assert result[1] is None
redis_key_nonbytes = core._get_redis_key("nonbytes-ts")
await client.hset(
redis_key_nonbytes,
mapping={
"timestamp": 12345,
"stale": "false",
"processing": "false",
"completed": "true",
},
)
with pytest.warns(UserWarning, match="Redis get_entry_by_key failed"):
nonbytes_result = await core.aget_entry_by_key("nonbytes-ts")
assert nonbytes_result[1] is None
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_core_entry_write_exceptions_and_should_store_guard():
pytest.importorskip("redis")
client = _AsyncInMemoryRedis()
core = _build_async_core(client)
core._should_store = lambda _value: False
assert await core.aset_entry("ignored", None) is False
failing_client = _AsyncInMemoryRedis()
failing_client.fail_hset = True
failing_core = _build_async_core(failing_client)
with pytest.warns(UserWarning, match="Redis set_entry failed"):
assert await failing_core.aset_entry("k2", "v2") is False
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_core_mark_and_clear_paths():
pytest.importorskip("redis")
client = _AsyncInMemoryRedis()
core = _build_async_core(client)
await core.amark_entry_being_calculated("calc")
_, entry = await core.aget_entry_by_key("calc")
assert entry is not None
assert entry._processing is True
await core.amark_entry_not_calculated("calc")
_, entry = await core.aget_entry_by_key("calc")
assert entry is not None
assert entry._processing is False
await core.aset_entry("cleanup-1", 1)
await core.aset_entry("cleanup-2", 2)
await core.aclear_being_calculated()
_, clean1 = await core.aget_entry_by_key("cleanup-1")
_, clean2 = await core.aget_entry_by_key("cleanup-2")
assert clean1 is not None
assert clean2 is not None
assert clean1._processing is False
assert clean2._processing is False
await core.aclear_cache()
_, cleared = await core.aget_entry_by_key("cleanup-1")
assert cleared is None
await core.aclear_cache()
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_core_mark_and_clear_exceptions():
pytest.importorskip("redis")
client = _AsyncInMemoryRedis()
core = _build_async_core(client)
client.fail_hset = True
with pytest.warns(UserWarning, match="Redis mark_entry_being_calculated failed"):
await core.amark_entry_being_calculated("k")
with pytest.warns(UserWarning, match="Redis mark_entry_not_calculated failed"):
await core.amark_entry_not_calculated("k")
client.fail_hset = False
client.fail_keys = True
with pytest.warns(UserWarning, match="Redis clear_being_calculated failed"):
await core.aclear_being_calculated()
with pytest.warns(UserWarning, match="Redis clear_cache failed"):
await core.aclear_cache()
@pytest.mark.redis
@pytest.mark.asyncio
async def test_async_redis_core_delete_stale_entries_paths():
pytest.importorskip("redis")
client = _AsyncInMemoryRedis()
core = _build_async_core(client)
now = datetime.now()
stale_ts = (now - timedelta(hours=2)).isoformat()
fresh_ts = (now - timedelta(minutes=10)).isoformat()
stale_key = core._get_redis_key("stale")
fresh_key = core._get_redis_key("fresh")
bad_key = core._get_redis_key("bad-ts")
bad_bytes_key = core._get_redis_key("bad-bytes-ts")
none_key = core._get_redis_key("none-ts")
await client.hset(stale_key, mapping={"timestamp": stale_ts, "processing": "false", "completed": "true"})
await client.hset(fresh_key, mapping={"timestamp": fresh_ts, "processing": "false", "completed": "true"})
await client.hset(bad_key, mapping={"timestamp": "invalid", "processing": "false", "completed": "true"})
await client.hset(bad_bytes_key, mapping={"timestamp": b"\xff", "processing": "false", "completed": "true"})
await client.hset(none_key, mapping={"processing": "false", "completed": "true"})
with pytest.warns(UserWarning, match="Redis timestamp parse failed"):
await core.adelete_stale_entries(timedelta(hours=1))
_, stale_entry = await core.aget_entry_by_key("stale")
_, fresh_entry = await core.aget_entry_by_key("fresh")
assert stale_entry is None
assert fresh_entry is not None
client.fail_keys = True
with pytest.warns(UserWarning, match="Redis delete_stale_entries failed"):
await core.adelete_stale_entries(timedelta(hours=1))
@pytest.mark.redis
def test_is_async_redis_client_detection():
"""_is_async_redis_client correctly identifies async vs non-async clients."""
assert _is_async_redis_client(_AsyncInMemoryRedis()) is True
assert _is_async_redis_client(_SyncInMemoryRedis()) is False
assert _is_async_redis_client(_PartialAsyncRedis()) is False
assert _is_async_redis_client(_NoMethodsObject()) is False