Skip to content

Commit 445d9dd

Browse files
committed
Add test cases for cachetools stubs
1 parent 1c29b6e commit 445d9dd

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
from __future__ import annotations
2+
3+
from collections.abc import Hashable
4+
from typing import Any
5+
from typing_extensions import assert_type
6+
7+
from cachetools import LRUCache, cached, keys as cachekeys
8+
from cachetools.func import fifo_cache, lfu_cache, lru_cache, rr_cache, ttl_cache
9+
10+
# Tests for cachetools.cached
11+
12+
# Explicitly parameterize the cache to avoid Unknown types
13+
cache_inst: LRUCache[int, int] = LRUCache(maxsize=128)
14+
15+
16+
@cached(cache_inst)
17+
def check_cached(x: int) -> int:
18+
return x * 2
19+
20+
21+
assert_type(check_cached(3), int)
22+
# Methods cache_info/cache_clear are only present when info=True; do not access them here.
23+
24+
25+
@cached(cache_inst, info=True)
26+
def check_cached_with_info(x: int) -> int:
27+
return x + 1
28+
29+
30+
assert_type(check_cached_with_info(4), int)
31+
assert_type(check_cached_with_info.cache_info().misses, int)
32+
check_cached_with_info.cache_clear()
33+
34+
35+
# Tests for cachetools.func decorators
36+
37+
38+
@lru_cache
39+
def lru_noparens(x: int) -> int:
40+
return x * 2
41+
42+
43+
@lru_cache(maxsize=32)
44+
def lru_with_maxsize(x: int) -> int:
45+
return x * 3
46+
47+
48+
assert_type(lru_noparens(3), int)
49+
assert_type(lru_with_maxsize(3), int)
50+
assert_type(lru_noparens.cache_info().hits, int)
51+
assert_type(lru_with_maxsize.cache_info().misses, int)
52+
assert_type(lru_with_maxsize.cache_parameters(), dict[str, Any])
53+
lru_with_maxsize.cache_clear()
54+
55+
56+
@fifo_cache
57+
def fifo_func(x: int) -> int:
58+
return x
59+
60+
61+
@lfu_cache
62+
def lfu_func(x: int) -> int:
63+
return x
64+
65+
66+
@rr_cache
67+
def rr_func(x: int) -> int:
68+
return x
69+
70+
71+
@ttl_cache
72+
def ttl_func(x: int) -> int:
73+
return x
74+
75+
76+
assert_type(fifo_func(1), int)
77+
assert_type(lfu_func(1), int)
78+
assert_type(rr_func(1), int)
79+
assert_type(ttl_func(1), int)
80+
assert_type(fifo_func.cache_info().currsize, int)
81+
assert_type(lfu_func.cache_parameters(), dict[str, Any])
82+
83+
84+
# Tests for cachetools.keys
85+
86+
k1 = cachekeys.hashkey(1, "a")
87+
assert_type(k1, tuple[Hashable, ...])
88+
89+
90+
class C:
91+
def method(self, a: int) -> int:
92+
return a
93+
94+
95+
inst = C()
96+
97+
k2 = cachekeys.methodkey(inst, 5)
98+
assert_type(k2, tuple[Hashable, ...])
99+
100+
k3 = cachekeys.typedkey(1, "x")
101+
assert_type(k3, tuple[Hashable, ...])
102+
103+
k4 = cachekeys.typedmethodkey(inst, 2)
104+
assert_type(k4, tuple[Hashable, ...])

0 commit comments

Comments
 (0)