@@ -25,29 +25,50 @@ def has_service(host="localhost", port=22):
25
25
tcp_ip .close ()
26
26
27
27
28
- def cached_fun (cache , cached = ct .cached ):
28
+ def cached_fun (cache , cached = ct .cached , key = ct . keys . hashkey ):
29
29
"""return a cached function with basic types."""
30
30
31
- @cached (cache = cache )
31
+ @cached (cache = cache , key = key )
32
32
def fun (i : int , s : str | None , b : bool ) -> int :
33
33
return i + (10 * len (s ) if s is not None else - 20 ) + (100 if b else 0 )
34
34
35
35
return fun
36
36
37
+ # reset cache contents and stats
38
+ def reset_cache (cache ):
39
+ try :
40
+ cache .clear ()
41
+ except : # fails on redis
42
+ pass
43
+ if hasattr (cache , "_cache" ) and hasattr (cache ._cache , "reset" ):
44
+ cache ._cache .reset ()
45
+ if hasattr (cache , "_cache2" ) and hasattr (cache ._cache2 , "reset" ):
46
+ cache ._cache2 .reset ()
47
+
48
+
49
+ def run_cached_keys (cache ):
50
+
51
+ for cached in (ct .cached , ctu .cached ):
52
+ for keyfun in (ct .keys .hashkey , ct .keys .typedkey , ctu .hash_json_key , ctu .json_key ):
53
+ reset_cache (cache )
54
+ fun = cached_fun (cache , cached , key = keyfun )
55
+ x = 0
56
+ for n in range (10 ):
57
+ for i in range (5 ):
58
+ for s in ["a" , "bb" , "ccc" , "" , None ]:
59
+ for b in [False , True ]:
60
+ v = fun (i , s , b )
61
+ # log.debug(f"fun{(i, s, b)} = {v} {type(v)}")
62
+ x += v
63
+ assert x == 30000
64
+
37
65
38
66
def run_cached (cache ):
39
67
"""run something on a cached function."""
40
68
41
69
for cached in (ct .cached , ctu .cached ):
42
70
# reset cache contents and stats
43
- try :
44
- cache .clear ()
45
- except : # fails on redis
46
- pass
47
- if hasattr (cache ._cache , "reset" ):
48
- cache ._cache .reset ()
49
- if hasattr (cache , "_cache2" ) and hasattr (cache ._cache2 , "reset" ):
50
- cache ._cache2 .reset ()
71
+ reset_cache (cache )
51
72
fun = cached_fun (cache , cached )
52
73
x = 0
53
74
for n in range (10 ):
@@ -145,6 +166,14 @@ def test_stats_ct():
145
166
setgetdel (cache )
146
167
147
168
169
+ def test_caches ():
170
+ n = 0
171
+ for Cache in (ct .LRUCache , ct .FIFOCache , ct .LFUCache , ct .RRCache ):
172
+ n += 1
173
+ cache = Cache (maxsize = 1024 )
174
+ run_cached_keys (cache )
175
+ assert n == 4
176
+
148
177
@pytest .mark .skipif (
149
178
not has_service (port = 11211 ),
150
179
reason = "no local memcached service available for testing" ,
0 commit comments