@@ -25,29 +25,50 @@ def has_service(host="localhost", port=22):
2525 tcp_ip .close ()
2626
2727
28- def cached_fun (cache , cached = ct .cached ):
28+ def cached_fun (cache , cached = ct .cached , key = ct . keys . hashkey ):
2929 """return a cached function with basic types."""
3030
31- @cached (cache = cache )
31+ @cached (cache = cache , key = key )
3232 def fun (i : int , s : str | None , b : bool ) -> int :
3333 return i + (10 * len (s ) if s is not None else - 20 ) + (100 if b else 0 )
3434
3535 return fun
3636
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+
3765
3866def run_cached (cache ):
3967 """run something on a cached function."""
4068
4169 for cached in (ct .cached , ctu .cached ):
4270 # 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 )
5172 fun = cached_fun (cache , cached )
5273 x = 0
5374 for n in range (10 ):
@@ -145,6 +166,14 @@ def test_stats_ct():
145166 setgetdel (cache )
146167
147168
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+
148177@pytest .mark .skipif (
149178 not has_service (port = 11211 ),
150179 reason = "no local memcached service available for testing" ,
0 commit comments