-
Notifications
You must be signed in to change notification settings - Fork 2
/
test.py
508 lines (435 loc) · 13 KB
/
test.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#! /usr/bin/env python
import cachetools as ct
import CacheToolsUtils as ctu
import socket
import pytest
import logging
logging.basicConfig()
log = logging.getLogger("ctu-test")
# log.setLevel(logging.DEBUG)
def has_service(host="localhost", port=22):
"""check whether a network TCP/IP service is available."""
try:
tcp_ip = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_ip.settimeout(1)
res = tcp_ip.connect_ex((host, port))
return res == 0
except Exception as e:
log.info(f"connection to {(host, port)} failed: {e}")
return False
finally:
tcp_ip.close()
def cached_fun(cache, cached=ct.cached):
"""return a cached function with basic types."""
@cached(cache=cache)
def fun(i: int, s: str|None, b: bool) -> int:
return i + (10 * len(s) if s is not None else -20) + (100 if b else 0)
return fun
def run_cached(cache):
"""run something on a cached function."""
for cached in (ct.cached, ctu.cached):
# reset cache contents and stats
try:
cache.clear()
except: # fails on redis
pass
if hasattr(cache._cache, "reset"):
cache._cache.reset()
if hasattr(cache, "_cache2") and hasattr(cache._cache2, "reset"):
cache._cache2.reset()
fun = cached_fun(cache, cached)
x = 0
for n in range(10):
for i in range(5):
for s in ["a", "bb", "ccc", "", None]:
for b in [False, True]:
v = fun(i, s, b)
# log.debug(f"fun{(i, s, b)} = {v} {type(v)}")
x += v
assert x == 30000
KEY, VAL = "hello-world!", "Hello World…"
def setgetdel(cache):
# str keys and values
cache[KEY] = VAL
# assert KEY in cache
assert cache[KEY] == VAL
del cache[KEY]
# assert KEY not in cache
try:
val = cache[KEY]
assert False, "should raise KeyError"
except Exception as e:
assert isinstance(e, KeyError)
# int value
cache[KEY] = 65536
# assert KEY in cache
assert cache[KEY] == 65536
del cache[KEY]
# FIXME memcached error
# assert KEY not in cache
def setgetdel_bytes(cache):
key, val, cst = KEY.encode("UTF8"), VAL.encode("UTF8"), b"FOO"
cache.setdefault(key, val)
assert key in cache
assert cache.get(key) == val
assert cache.setdefault(key, cst) == val
assert cache.pop(key) == val
assert key not in cache
assert cache.get(key, cst) == cst
assert cache.pop(key, cst) == cst
try:
cache.pop(key)
assert False, "should raise KeyError"
except KeyError as e:
assert True, "KeyError was raised"
def test_key_ct():
c0 = ct.TTLCache(maxsize=100, ttl=100)
c1 = ctu.PrefixedCache(c0, "f.")
c2 = ctu.PrefixedCache(c0, "f.")
c3 = ctu.PrefixedCache(c0, "g.")
run_cached(c1)
run_cached(c2)
assert len(c0) == 50
assert "f.(0, 'a', False)" in c0
assert c1[(3, "bb", True)] == 123
assert "f.(4, None, True)" in c0
assert c2[(4, "ccc", True)] == 134
run_cached(c3)
assert len(c0) == 100
assert c3[(2, "", True)] == 102
c0.clear()
setgetdel(c0)
setgetdel(c1)
setgetdel(c2)
setgetdel(c3)
for key in c0:
assert key[0] in ("f", "g") and key[1] == "."
for key in c3:
assert key[0] in ("f", "g") and key[1] == "."
setgetdel_bytes(c0)
setgetdel_bytes(c1)
setgetdel_bytes(c2)
setgetdel_bytes(c3)
def test_stats_ct():
c0 = ct.TTLCache(maxsize=100, ttl=100)
cache = ctu.StatsCache(c0)
run_cached(cache)
assert len(cache) == 50
assert cache[(4, "a", True)] == 114
assert cache[(0, None, False)] == -20
assert cache.hits() > 0.8
assert isinstance(cache.stats(), dict)
cache.clear()
setgetdel(c0)
setgetdel(cache)
@pytest.mark.skipif(
not has_service(port=11211),
reason="no local memcached service available for testing",
)
def test_memcached():
import pymemcache as pmc
c0 = pmc.Client(server="localhost", serde=ctu.JsonSerde())
c1 = ctu.MemCached(c0)
run_cached(c1)
assert len(c1) >= 50
assert c1["(1, 'a', True)"] == 111
assert c1["(3, None, False)"] == -17
assert isinstance(c1.stats(), dict)
@pytest.mark.skipif(
not has_service(port=11211),
reason="no local memcached service available for testing",
)
def test_key_memcached():
import pymemcache as pmc
c0 = pmc.Client(server="localhost", serde=ctu.JsonSerde())
c1 = ctu.PrefixedMemCached(c0, "CacheToolsUtils.")
run_cached(c1)
assert len(c1) >= 50
assert c1["(1, 'a', True)"] == 111
assert c1["(3, None, False)"] == -17
@pytest.mark.skipif(
not has_service(port=11211),
reason="no local memcached service available for testing",
)
def test_stats_memcached():
import pymemcache as pmc
c0 = pmc.Client(server="localhost", serde=ctu.JsonSerde(), key_prefix=b"ctu.")
c1 = ctu.StatsMemCached(c0)
run_cached(c1)
assert len(c1) >= 50
assert c1["(1, 'a', True)"] == 111
assert c1["(3, None, False)"] == -17
assert c1.hits() > 0.0
assert isinstance(c1.stats(), dict)
setgetdel(c0)
setgetdel(c1)
@pytest.mark.skipif(
not has_service(port=6379), reason="no local redis service available for testing"
)
def test_redis():
import redis
import threading
c0 = redis.Redis(host="localhost")
c1 = ctu.RedisCache(c0)
c2 = ctu.LockedCache(c1, threading.RLock())
run_cached(c2)
assert len(c2) >= 50
assert c2[(1, "a", True)] == 111
assert c2[(3, None, False)] == -17
setgetdel(c2)
try:
c2.__iter__()
assert False, "should raise an Exception"
except Exception as e:
assert "not implemented yet" in str(e)
@pytest.mark.skipif(
not has_service(port=6379), reason="no local redis service available for testing"
)
def test_key_redis():
import redis
c0 = redis.Redis(host="localhost")
c1 = ctu.PrefixedRedisCache(c0, "CacheToolsUtils.")
run_cached(c1)
assert len(c1) >= 50
assert c1[(1, "a", True)] == 111
assert c1[(3, None, False)] == -17
setgetdel(c1)
c1.set("Hello", "World!")
assert c1["Hello"] == c1.get("Hello")
c1.delete("Hello")
assert "Hello" not in c1
@pytest.mark.skipif(
not has_service(port=6379), reason="no local redis service available for testing"
)
def test_stats_redis():
import redis
c0 = redis.Redis(host="localhost")
c1 = ctu.StatsRedisCache(c0)
run_cached(c1)
assert len(c1) >= 50
assert c1[(1, "a", True)] == 111
assert c1[(3, None, False)] == -17
assert c1.hits() > 0.0
assert isinstance(c1.stats(), dict)
setgetdel(c1)
@pytest.mark.skipif(
not has_service(port=6379), reason="no local redis service available for testing"
)
def test_stacked_redis():
import redis
c0 = redis.Redis(host="localhost")
c1 = ctu.RedisCache(c0)
c2 = ctu.StatsRedisCache(c1)
c3 = ctu.PrefixedRedisCache(c2, "CacheToolsUtilsTests.")
run_cached(c3)
assert len(c3) >= 50
assert c2.hits() > 0.0
assert isinstance(c2.stats(), dict)
setgetdel(c1)
setgetdel(c2)
setgetdel(c3)
def test_two_level_small():
# front cache is too small, always fallback
c0 = ct.TTLCache(100, ttl=60)
c1 = ct.LFUCache(10)
c0s = ctu.StatsCache(c0)
c1s = ctu.StatsCache(c1)
c2 = ctu.TwoLevelCache(c1s, c0s)
run_cached(c2)
assert len(c1s) == 10
assert len(c0s) == 50
assert c0s._reads == c1s._reads
assert c1s.hits() == 0.0
assert isinstance(c1s.stats(), dict)
assert c0s.hits() > 0.8
assert isinstance(c0s.stats(), dict)
assert c2.hits() > 0.0
assert isinstance(c2.stats(), dict)
c2.clear()
setgetdel(c0)
setgetdel(c1)
setgetdel(c0s)
setgetdel(c1s)
setgetdel(c2)
def test_two_level_ok():
# front cache is too small, always fallback
c0 = ct.LRUCache(200)
c1 = ct.LFUCache(100)
c0s = ctu.StatsCache(c0)
c1s = ctu.StatsCache(c1)
c2 = ctu.TwoLevelCache(c1s, c0s)
run_cached(c2)
assert len(c1s) == 50
assert len(c0s) == 50
assert c0s._reads == 50
# assert c0s._writes == 50
assert c0s._writes == 0
assert c1s._reads == 500
assert c1s.hits() == 0.9
assert isinstance(c1s.stats(), dict)
assert c0s.hits() == 1.0
assert isinstance(c0s.stats(), dict)
assert c2.hits() > 0.0
assert isinstance(c2.stats(), dict)
c2.clear()
setgetdel(c0)
setgetdel(c1)
setgetdel(c0s)
setgetdel(c1s)
setgetdel(c2)
# trigger a level-2 miss
c2[KEY] = VAL
del c0s[KEY]
del c2[KEY]
def test_twolevel_bad_stats():
c0 = ctu.DictCache()
c1 = ctu.DictCache()
c2 = ctu.TwoLevelCache(c0, c1)
assert isinstance(c2.stats(), dict)
assert c2.hits() is None
class Stuff:
"""Test class with cacheable methods."""
def __init__(self, name):
self._name = name
def __str__(self):
return f"Object {self._name}"
def sum_n2(self, n: int):
if n < 1:
return 0
else:
return n * n + self.sum_n2(n - 1)
def sum_n1(self, n: int):
if n < 0:
return 0
else:
return n + self.sum_n1(n - 1)
def test_methods():
s = Stuff("test_methods")
c = ct.TTLCache(1024, ttl=60)
cs = ctu.StatsCache(c)
ctu.cacheMethods(cs, s, sum_n1="1.", sum_n2="2.")
n2 = s.sum_n2(128)
n1 = s.sum_n1(128)
for i in range(1, 128):
n = s.sum_n2(i) + s.sum_n1(i)
n = s.sum_n2(i) + s.sum_n1(i)
assert len(c) == 259
assert cs.hits() > 0.6
assert isinstance(cs.stats(), dict)
ctu.cacheMethods(cs, s, sum_n1="x.")
try:
ctu.cacheMethods(cs, s, no_such_method="?.")
assert False, "exception must be raised"
except Exception as e:
assert "missing method" in str(e)
def sum_n2(n: int):
return n * n + sum_n2(n - 1) if n >= 1 else 0
def test_functions():
c = ct.TTLCache(1024, ttl=60.0)
cs = ctu.StatsCache(c)
ctu.cacheFunctions(cs, globals(), sum_n2="2.")
ctu.cacheFunctions(cs, globals(), sum_n2="2.")
assert hasattr(sum_n2, "__wrapped__")
n2 = sum_n2(128)
for i in range(1, 128):
n = sum_n2(i) + sum_n2(i) + sum_n2(i)
assert len(c) == 129
assert cs.hits() > 0.7
assert isinstance(cs.stats(), dict)
def test_corners():
# _MutMapMix coverage
c = ctu.DictCache()
cs = ctu.StatsCache(c)
run_cached(cs)
assert len(cs) > 0
cs["foo-bla-khan"] = 1
assert "foo-bla-khan" in cs
del cs["foo-bla-khan"]
assert "foo-bla-khan" not in cs
# raise JsonSerde flag error
try:
js = ctu.JsonSerde()
js.deserialize("foo", "bla", 42)
assert False, "exception must be raised"
except Exception as e:
assert "Unknown serialization format" in str(e)
class BrokenCache():
"""All Error Cache, for testing purposes."""
def __setitem__(self, key, val):
raise Exception("oops!")
def __getitem__(self, key):
raise Exception("oops!")
def __delitem__(self, key):
raise Exception("oops!")
def test_resilience():
d = ctu.DictCache()
b = BrokenCache()
# no resilience (default)
c = ctu.TwoLevelCache(d, b, False)
try:
c["foo"] = "bla"
assert False, "must raise an exception"
except Exception:
assert True, "expecting exception"
try:
c["foo"]
assert False, "must raise an exception"
except Exception:
assert True, "expecting exception"
try:
del c["foo"]
assert False, "must raise an exception"
except Exception:
assert True, "expecting exception"
# activate resilience
c._resilient = True
c["foo"] = "bla"
assert c["foo"] == "bla"
del c["foo"]
def test_locked():
import threading
c = ctu.LockedCache(ctu.DictCache(), threading.Lock())
c["hello"] = "world!"
assert "hello" in c
assert c["hello"] == "world!"
del c["hello"]
assert "hello" not in c
# just for coverage
try:
c.hits() == 0.0
except:
pass
try:
c.reset()
except:
pass
def test_cached():
cache = ctu.StatsCache(ctu.DictCache())
@ctu.cached(cache)
def cached(s: str, i: int):
return s[i]
assert not cached.cache_in("hello", 4)
assert cached("hello", 4) == "o"
cached("hello", 4)
assert cached.cache_in("hello", 4)
assert cache.hits() == 0.5
assert isinstance(cache.stats(), dict)
cached.cache_del("hello", 4)
assert not cached.cache_in("hello", 4)
def test_debug():
log = logging.getLogger("debug-test")
log.setLevel(logging.DEBUG)
cache = ctu.DebugCache(ctu.StatsCache(ctu.DictCache()), log, "test_debug")
run_cached(cache)
cache["Hello"] = "World!"
assert "Hello" in cache
assert len(cache) > 0
assert cache.hits() > 0.0
assert isinstance(cache.stats(), dict)
has_hello = False
for k in iter(cache):
if k == "Hello":
has_hello = True
assert has_hello
del cache["Hello"]
assert "Hello" not in cache