recall-cache 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.so
5
+ .Python
6
+ build/
7
+ develop-eggs/
8
+ dist/
9
+ downloads/
10
+ eggs/
11
+ .eggs/
12
+ lib/
13
+ lib64/
14
+ parts/
15
+ sdist/
16
+ var/
17
+ wheels/
18
+ *.egg-info/
19
+ .installed.cfg
20
+ *.egg
21
+ .pytest_cache/
22
+ .coverage
23
+ htmlcov/
24
+ .tox/
25
+ .venv
26
+ venv/
27
+ ENV/
28
+ env/
29
+ .cache/
30
+ *.cache
31
+ .github/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hermes-telegram
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.5
2
+ Name: recall-cache
3
+ Version: 0.1.0
4
+ Summary: Smart caching for any function — simple as requests
5
+ Project-URL: Homepage, https://github.com/hermes-telegram/recall
6
+ Author-email: hermes-telegram <hermes_tm@agentmail.to>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Keywords: cache,caching,diskcache,memoize,redis,ttl
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Requires-Python: >=3.8
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest; extra == 'dev'
16
+ Requires-Dist: redis; extra == 'dev'
17
+ Provides-Extra: redis
18
+ Requires-Dist: redis>=4.0; extra == 'redis'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # recall
22
+
23
+ Smart caching for any function — simple as requests.
24
+
25
+ ```python
26
+ from recall import cache
27
+
28
+ @cache(ttl="1h")
29
+ def get_user(user_id):
30
+ return db.query(user_id)
31
+ ```
32
+
33
+ ## Features
34
+
35
+ - **Simple API** — just `@cache(ttl="1h")` on any function
36
+ - **Multiple backends** — Memory, Disk, Redis
37
+ - **TTL shorthand** — `"30m"`, `"1h"`, `"7d"` instead of raw seconds
38
+ - **LRU eviction** — automatic cleanup when maxsize is reached
39
+ - **Thread-safe** — works in concurrent environments
40
+ - **Zero dependencies** — Redis backend optional
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install recall
46
+ # With Redis support:
47
+ pip install recall[redis]
48
+ ```
49
+
50
+ ## Quick Start
51
+
52
+ ```python
53
+ from recall import cache
54
+ import time
55
+
56
+ @cache(ttl="1h", maxsize=1000)
57
+ def expensive_func(x):
58
+ time.sleep(2)
59
+ return x * 2
60
+
61
+ # First call: computes
62
+ result = expensive_func(5) # takes 2 seconds
63
+
64
+ # Second call: instant (from cache)
65
+ result = expensive_func(5) # returns immediately
66
+ ```
67
+
68
+ ## Backends
69
+
70
+ ### Memory (default)
71
+
72
+ ```python
73
+ @cache(ttl="1h", maxsize=1000)
74
+ def func(x):
75
+ return x * 2
76
+ ```
77
+
78
+ ### Disk (persistent)
79
+
80
+ ```python
81
+ from recall import DiskBackend
82
+
83
+ @cache(ttl="1h", backend=DiskBackend("/tmp/my_cache"))
84
+ def func(x):
85
+ return x * 2
86
+ ```
87
+
88
+ ### Redis
89
+
90
+ ```python
91
+ from recall import RedisBackend
92
+
93
+ @cache(ttl="1h", backend=RedisBackend("redis://localhost:6379"))
94
+ def func(x):
95
+ return x * 2
96
+ ```
97
+
98
+ ## Cache Management
99
+
100
+ ```python
101
+ # Clear all cached values
102
+ expensive_func.cache_clear()
103
+
104
+ # Delete specific key
105
+ expensive_func.cache_delete(42)
106
+
107
+ # Custom key function
108
+ @cache(ttl="1h", key_fn=lambda f, a, k: f"{a}_{k.get('mode', '')}")
109
+ def custom(data, mode):
110
+ return f"{data}_{mode}"
111
+ ```
112
+
113
+ ## TTL Formats
114
+
115
+ | Shorthand | Meaning |
116
+ |-----------|---------|
117
+ | `"30s"` | 30 seconds |
118
+ | `"5m"` | 5 minutes |
119
+ | `"1h"` | 1 hour |
120
+ | `"1d"` | 1 day |
121
+ | `"1w"` | 1 week |
122
+ | `3600` | raw seconds (int/float) |
123
+
124
+ ## Why recall?
125
+
126
+ | Tool | Issue |
127
+ |------|-------|
128
+ | `functools.lru_cache` | No TTL, no persistence |
129
+ | `cachetools` | Complex API, no disk/Redis |
130
+ | `redis` alone | Manual key management |
131
+ | `dogpile.cache` | Overkill for simple use |
132
+
133
+ **recall** = simple API + real backends + TTL done right.
134
+
135
+ ## License
136
+
137
+ MIT
@@ -0,0 +1,117 @@
1
+ # recall
2
+
3
+ Smart caching for any function — simple as requests.
4
+
5
+ ```python
6
+ from recall import cache
7
+
8
+ @cache(ttl="1h")
9
+ def get_user(user_id):
10
+ return db.query(user_id)
11
+ ```
12
+
13
+ ## Features
14
+
15
+ - **Simple API** — just `@cache(ttl="1h")` on any function
16
+ - **Multiple backends** — Memory, Disk, Redis
17
+ - **TTL shorthand** — `"30m"`, `"1h"`, `"7d"` instead of raw seconds
18
+ - **LRU eviction** — automatic cleanup when maxsize is reached
19
+ - **Thread-safe** — works in concurrent environments
20
+ - **Zero dependencies** — Redis backend optional
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install recall
26
+ # With Redis support:
27
+ pip install recall[redis]
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ```python
33
+ from recall import cache
34
+ import time
35
+
36
+ @cache(ttl="1h", maxsize=1000)
37
+ def expensive_func(x):
38
+ time.sleep(2)
39
+ return x * 2
40
+
41
+ # First call: computes
42
+ result = expensive_func(5) # takes 2 seconds
43
+
44
+ # Second call: instant (from cache)
45
+ result = expensive_func(5) # returns immediately
46
+ ```
47
+
48
+ ## Backends
49
+
50
+ ### Memory (default)
51
+
52
+ ```python
53
+ @cache(ttl="1h", maxsize=1000)
54
+ def func(x):
55
+ return x * 2
56
+ ```
57
+
58
+ ### Disk (persistent)
59
+
60
+ ```python
61
+ from recall import DiskBackend
62
+
63
+ @cache(ttl="1h", backend=DiskBackend("/tmp/my_cache"))
64
+ def func(x):
65
+ return x * 2
66
+ ```
67
+
68
+ ### Redis
69
+
70
+ ```python
71
+ from recall import RedisBackend
72
+
73
+ @cache(ttl="1h", backend=RedisBackend("redis://localhost:6379"))
74
+ def func(x):
75
+ return x * 2
76
+ ```
77
+
78
+ ## Cache Management
79
+
80
+ ```python
81
+ # Clear all cached values
82
+ expensive_func.cache_clear()
83
+
84
+ # Delete specific key
85
+ expensive_func.cache_delete(42)
86
+
87
+ # Custom key function
88
+ @cache(ttl="1h", key_fn=lambda f, a, k: f"{a}_{k.get('mode', '')}")
89
+ def custom(data, mode):
90
+ return f"{data}_{mode}"
91
+ ```
92
+
93
+ ## TTL Formats
94
+
95
+ | Shorthand | Meaning |
96
+ |-----------|---------|
97
+ | `"30s"` | 30 seconds |
98
+ | `"5m"` | 5 minutes |
99
+ | `"1h"` | 1 hour |
100
+ | `"1d"` | 1 day |
101
+ | `"1w"` | 1 week |
102
+ | `3600` | raw seconds (int/float) |
103
+
104
+ ## Why recall?
105
+
106
+ | Tool | Issue |
107
+ |------|-------|
108
+ | `functools.lru_cache` | No TTL, no persistence |
109
+ | `cachetools` | Complex API, no disk/Redis |
110
+ | `redis` alone | Manual key management |
111
+ | `dogpile.cache` | Overkill for simple use |
112
+
113
+ **recall** = simple API + real backends + TTL done right.
114
+
115
+ ## License
116
+
117
+ MIT
@@ -0,0 +1,117 @@
1
+ # ریکال — کش هوشمند برای هر تابعی
2
+
3
+ کش هوشمند برای هر تابعی — ساده مثل requests.
4
+
5
+ ```python
6
+ from recall import cache
7
+
8
+ @cache(ttl="1h")
9
+ def get_user(user_id):
10
+ return db.query(user_id)
11
+ ```
12
+
13
+ ## ویژگی‌ها
14
+
15
+ - **API ساده** — فقط با `@cache(ttl="1h")` هر تابعی رو کش کن
16
+ - **چندین بک‌اند** — حافظه، دیسک، ردیس
17
+ - **انقدا ساده** — `"30m"`، `"1h"`، `"7d"` به جای ثانیه
18
+ - **حذف LRU** — تمیز کردن خودکار وقتی به حداکثر رسیدی
19
+ - **ایمن برای ترد** — در محیط‌های همزمان کار می‌کنه
20
+ - **بدون وابستگی** — بک‌اند ردیس اختیاریه
21
+
22
+ ## نصب
23
+
24
+ ```bash
25
+ pip install recall
26
+ # با پشتیبانی ردیس:
27
+ pip install recall[redis]
28
+ ```
29
+
30
+ ## شروع سریع
31
+
32
+ ```python
33
+ from recall import cache
34
+ import time
35
+
36
+ @cache(ttl="1h", maxsize=1000)
37
+ def expensive_func(x):
38
+ time.sleep(2)
39
+ return x * 2
40
+
41
+ # اولین فراخوانی: محاسبه می‌کنه
42
+ result = expensive_func(5) # ۲ ثانیه طول می‌کشه
43
+
44
+ # دومین فراخوانی: فوری (از کش)
45
+ result = expensive_func(5) # فوری برمی‌گردونه
46
+ ```
47
+
48
+ ## بک‌اند‌ها
49
+
50
+ ### حافظه (پیش‌فرض)
51
+
52
+ ```python
53
+ @cache(ttl="1h", maxsize=1000)
54
+ def func(x):
55
+ return x * 2
56
+ ```
57
+
58
+ ### دیسک (دائمی)
59
+
60
+ ```python
61
+ from recall import DiskBackend
62
+
63
+ @cache(ttl="1h", backend=DiskBackend("/tmp/my_cache"))
64
+ def func(x):
65
+ return x * 2
66
+ ```
67
+
68
+ ### ردیس
69
+
70
+ ```python
71
+ from recall import RedisBackend
72
+
73
+ @cache(ttl="1h", backend=RedisBackend("redis://localhost:6379"))
74
+ def func(x):
75
+ return x * 2
76
+ ```
77
+
78
+ ## مدیریت کش
79
+
80
+ ```python
81
+ # پاک کردن همه مقادیر کش شده
82
+ expensive_func.cache_clear()
83
+
84
+ # حذف یک کلید خاص
85
+ expensive_func.cache_delete(42)
86
+
87
+ # تابع کلید سفارشی
88
+ @cache(ttl="1h", key_fn=lambda f, a, k: f"{a}_{k.get('mode', '')}")
89
+ def custom(data, mode):
90
+ return f"{data}_{mode}"
91
+ ```
92
+
93
+ ## فرمت‌های انقضا
94
+
95
+ | مختصر | معنی |
96
+ |--------|------|
97
+ | `"30s"` | ۳۰ ثانیه |
98
+ | `"5m"` | ۵ دقیقه |
99
+ | `"1h"` | ۱ ساعت |
100
+ | `"1d"` | ۱ روز |
101
+ | `"1w"` | ۱ هفته |
102
+ | `3600` | ثانیه خام (int/float) |
103
+
104
+ ## چرا ریکال؟
105
+
106
+ | ابزار | مشکل |
107
+ |--------|------|
108
+ | `functools.lru_cache` | بدون انقضا، بدون دائمی بودن |
109
+ | `cachetools` | API پیچیده، بدون دیسک/ردیس |
110
+ | `redis` به تنهایی | مدیریت دستی کلید |
111
+ | `dogpile.cache` | بیش از حد ساده برای استفاده ساده |
112
+
113
+ **ریکال** = API ساده + بک‌اند واقعی + انقضا درست انجام شده.
114
+
115
+ ## مجوز
116
+
117
+ MIT
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "recall-cache"
7
+ version = "0.1.0"
8
+ description = "Smart caching for any function — simple as requests"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.8"
12
+ authors = [
13
+ { name = "hermes-telegram", email = "hermes_tm@agentmail.to" },
14
+ ]
15
+ keywords = ["cache", "caching", "ttl", "memoize", "redis", "diskcache"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Topic :: Software Development :: Libraries",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.optional-dependencies]
24
+ redis = ["redis>=4.0"]
25
+ dev = ["pytest", "redis"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/hermes-telegram/recall"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/recall"]
@@ -0,0 +1,6 @@
1
+ """recall — smart caching for any function, simple as requests."""
2
+
3
+ from .cache import cache, CacheBackend, MemoryBackend, DiskBackend, RedisBackend
4
+
5
+ __all__ = ["cache", "CacheBackend", "MemoryBackend", "DiskBackend", "RedisBackend"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,217 @@
1
+ """Core cache decorator and backends for recall."""
2
+
3
+ import functools
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import pickle
8
+ import time
9
+ from abc import ABC, abstractmethod
10
+ from typing import Any, Callable, Optional, Union
11
+
12
+
13
+ class CacheBackend(ABC):
14
+ """Abstract base class for cache backends."""
15
+
16
+ @abstractmethod
17
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
18
+ """Return (expire_time, value) or None."""
19
+ ...
20
+
21
+ @abstractmethod
22
+ def set(self, key: str, value: Any, ttl: float) -> None:
23
+ """Store value with TTL in seconds."""
24
+ ...
25
+
26
+ @abstractmethod
27
+ def delete(self, key: str) -> None:
28
+ """Delete a key."""
29
+ ...
30
+
31
+ @abstractmethod
32
+ def clear(self) -> None:
33
+ """Clear all cached values."""
34
+ ...
35
+
36
+
37
+ class MemoryBackend(CacheBackend):
38
+ """In-memory cache with TTL and maxsize (LRU eviction)."""
39
+
40
+ def __init__(self, maxsize: int = 1000):
41
+ self._cache: dict[str, tuple[float, Any]] = {}
42
+ self._access: dict[str, float] = {}
43
+ self.maxsize = maxsize
44
+
45
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
46
+ if key in self._cache:
47
+ expire_time, value = self._cache[key]
48
+ if expire_time > time.time():
49
+ self._access[key] = time.time()
50
+ return (expire_time, value)
51
+ else:
52
+ del self._cache[key]
53
+ del self._access[key]
54
+ return None
55
+
56
+ def set(self, key: str, value: Any, ttl: float) -> None:
57
+ if len(self._cache) >= self.maxsize and key not in self._cache:
58
+ self._evict()
59
+ self._cache[key] = (time.time() + ttl, value)
60
+ self._access[key] = time.time()
61
+
62
+ def delete(self, key: str) -> None:
63
+ self._cache.pop(key, None)
64
+ self._access.pop(key, None)
65
+
66
+ def clear(self) -> None:
67
+ self._cache.clear()
68
+ self._access.clear()
69
+
70
+ def _evict(self):
71
+ """Evict least recently used item."""
72
+ if self._access:
73
+ oldest = min(self._access, key=self._access.get)
74
+ del self._cache[oldest]
75
+ del self._access[oldest]
76
+
77
+
78
+ class DiskBackend(CacheBackend):
79
+ """Persistent disk cache using pickle files."""
80
+
81
+ def __init__(self, directory: str = ".recall_cache"):
82
+ self.directory = directory
83
+ os.makedirs(directory, exist_ok=True)
84
+
85
+ def _path(self, key: str) -> str:
86
+ safe = hashlib.sha256(key.encode()).hexdigest()[:16]
87
+ return os.path.join(self.directory, f"{safe}.cache")
88
+
89
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
90
+ path = self._path(key)
91
+ if os.path.exists(path):
92
+ try:
93
+ with open(path, "rb") as f:
94
+ expire_time, value = pickle.load(f)
95
+ if expire_time > time.time():
96
+ return (expire_time, value)
97
+ else:
98
+ os.remove(path)
99
+ except (pickle.PickleError, OSError):
100
+ pass
101
+ return None
102
+
103
+ def set(self, key: str, value: Any, ttl: float) -> None:
104
+ path = self._path(key)
105
+ with open(path, "wb") as f:
106
+ pickle.dump((time.time() + ttl, value), f)
107
+
108
+ def delete(self, key: str) -> None:
109
+ path = self._path(key)
110
+ if os.path.exists(path):
111
+ os.remove(path)
112
+
113
+ def clear(self) -> None:
114
+ for f in os.listdir(self.directory):
115
+ if f.endswith(".cache"):
116
+ os.remove(os.path.join(self.directory, f))
117
+
118
+
119
+ class RedisBackend(CacheBackend):
120
+ """Redis cache backend."""
121
+
122
+ def __init__(self, url: str = "redis://localhost:6379", prefix: str = "recall:"):
123
+ import redis
124
+ self.client = redis.from_url(url)
125
+ self.prefix = prefix
126
+
127
+ def _key(self, key: str) -> str:
128
+ return f"{self.prefix}{key}"
129
+
130
+ def get(self, key: str) -> Optional[tuple[float, Any]]:
131
+ raw = self.client.get(self._key(key))
132
+ if raw:
133
+ return pickle.loads(raw)
134
+ return None
135
+
136
+ def set(self, key: str, value: Any, ttl: float) -> None:
137
+ data = pickle.dumps((time.time() + ttl, value))
138
+ self.client.setex(self._key(key), int(ttl), data)
139
+
140
+ def delete(self, key: str) -> None:
141
+ self.client.delete(self._key(key))
142
+
143
+ def clear(self) -> None:
144
+ keys = self.client.keys(f"{self.prefix}*")
145
+ if keys:
146
+ self.client.delete(*keys)
147
+
148
+
149
+ def _make_key(func: Callable, args: tuple, kwargs: dict) -> str:
150
+ """Generate a unique cache key from function and arguments."""
151
+ key_data = json.dumps({
152
+ "func": f"{func.__module__}.{func.__qualname__}",
153
+ "args": args,
154
+ "kwargs": kwargs,
155
+ }, sort_keys=True, default=str)
156
+ return hashlib.sha256(key_data.encode()).hexdigest()
157
+
158
+
159
+ def cache(
160
+ ttl: Union[str, float] = "1h",
161
+ maxsize: int = 1000,
162
+ backend: Optional[CacheBackend] = None,
163
+ key_fn: Optional[Callable] = None,
164
+ ):
165
+ """
166
+ Decorator that caches function results with TTL.
167
+
168
+ Args:
169
+ ttl: Time-to-live in seconds, or shorthand like "1h", "30m", "7d".
170
+ maxsize: Maximum number of cached items (memory backend only).
171
+ backend: Custom backend (MemoryBackend, DiskBackend, RedisBackend).
172
+ key_fn: Custom key function f(func, args, kwargs) -> str.
173
+
174
+ Usage:
175
+ @cache(ttl="1h")
176
+ def get_user(user_id):
177
+ return db.query(user_id)
178
+
179
+ @cache(ttl=300, backend=DiskBackend("/tmp/cache"))
180
+ def expensive_computation(x, y):
181
+ return x ** y
182
+ """
183
+ # Parse TTL shorthand
184
+ if isinstance(ttl, str):
185
+ multipliers = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
186
+ ttl = float(ttl[:-1]) * multipliers.get(ttl[-1].lower(), 1)
187
+
188
+ if backend is None:
189
+ backend = MemoryBackend(maxsize=maxsize)
190
+
191
+ def decorator(func: Callable) -> Callable:
192
+ @functools.wraps(func)
193
+ def wrapper(*args, **kwargs):
194
+ if key_fn:
195
+ k = key_fn(func, args, kwargs)
196
+ else:
197
+ k = _make_key(func, args, kwargs)
198
+
199
+ result = backend.get(k)
200
+ if result is not None:
201
+ _, value = result
202
+ return value
203
+
204
+ value = func(*args, **kwargs)
205
+ backend.set(k, value, ttl)
206
+ return value
207
+
208
+ # Attach cache management methods
209
+ wrapper.cache_backend = backend
210
+ wrapper.cache_clear = backend.clear
211
+ wrapper.cache_delete = lambda *a, **kw: backend.delete(
212
+ key_fn(func, a, kw) if key_fn else _make_key(func, a, kw)
213
+ )
214
+
215
+ return wrapper
216
+
217
+ return decorator
@@ -0,0 +1,452 @@
1
+ """Comprehensive tests for recall."""
2
+
3
+ import os
4
+ import shutil
5
+ import time
6
+ import pytest
7
+ from recall import cache, MemoryBackend, DiskBackend
8
+
9
+
10
+ # ============================================================
11
+ # Memory Backend Tests
12
+ # ============================================================
13
+
14
+ class TestMemoryBackend:
15
+ def test_set_and_get(self):
16
+ be = MemoryBackend()
17
+ be.set("key1", "value1", ttl=60)
18
+ result = be.get("key1")
19
+ assert result is not None
20
+ _, value = result
21
+ assert value == "value1"
22
+
23
+ def test_get_missing(self):
24
+ be = MemoryBackend()
25
+ assert be.get("nonexistent") is None
26
+
27
+ def test_expiration(self):
28
+ be = MemoryBackend()
29
+ be.set("key1", "value1", ttl=0.1)
30
+ time.sleep(0.15)
31
+ assert be.get("key1") is None
32
+
33
+ def test_delete(self):
34
+ be = MemoryBackend()
35
+ be.set("key1", "value1", ttl=60)
36
+ be.delete("key1")
37
+ assert be.get("key1") is None
38
+
39
+ def test_clear(self):
40
+ be = MemoryBackend()
41
+ be.set("k1", "v1", ttl=60)
42
+ be.set("k2", "v2", ttl=60)
43
+ be.clear()
44
+ assert be.get("k1") is None
45
+ assert be.get("k2") is None
46
+
47
+ def test_maxsize_eviction(self):
48
+ be = MemoryBackend(maxsize=3)
49
+ for i in range(5):
50
+ be.set(f"k{i}", f"v{i}", ttl=60)
51
+ # Only 3 should remain
52
+ count = sum(1 for i in range(5) if be.get(f"k{i}") is not None)
53
+ assert count == 3
54
+
55
+ def test_lru_eviction(self):
56
+ be = MemoryBackend(maxsize=3)
57
+ be.set("a", 1, ttl=60)
58
+ be.set("b", 2, ttl=60)
59
+ be.set("c", 3, ttl=60)
60
+ # Access "a" to make it recently used
61
+ be.get("a")
62
+ # Add "d" — should evict "b" (least recently used)
63
+ be.set("d", 4, ttl=60)
64
+ assert be.get("a") is not None
65
+ assert be.get("b") is None
66
+ assert be.get("c") is not None
67
+ assert be.get("d") is not None
68
+
69
+ def test_overwrite(self):
70
+ be = MemoryBackend()
71
+ be.set("key1", "old", ttl=60)
72
+ be.set("key1", "new", ttl=60)
73
+ _, value = be.get("key1")
74
+ assert value == "new"
75
+
76
+ def test_various_types(self):
77
+ be = MemoryBackend()
78
+ be.set("int", 42, ttl=60)
79
+ be.set("list", [1, 2, 3], ttl=60)
80
+ be.set("dict", {"a": 1}, ttl=60)
81
+ be.set("none", None, ttl=60)
82
+ be.set("tuple", (1, 2), ttl=60)
83
+ assert be.get("int")[1] == 42
84
+ assert be.get("list")[1] == [1, 2, 3]
85
+ assert be.get("dict")[1] == {"a": 1}
86
+ assert be.get("none")[1] is None
87
+ assert be.get("tuple")[1] == (1, 2)
88
+
89
+
90
+ # ============================================================
91
+ # Disk Backend Tests
92
+ # ============================================================
93
+
94
+ class TestDiskBackend:
95
+ def setup_method(self):
96
+ self.dir = ".test_recall_cache"
97
+
98
+ def teardown_method(self):
99
+ if os.path.exists(self.dir):
100
+ shutil.rmtree(self.dir)
101
+
102
+ def test_set_and_get(self):
103
+ be = DiskBackend(self.dir)
104
+ be.set("key1", "value1", ttl=60)
105
+ result = be.get("key1")
106
+ assert result is not None
107
+ assert result[1] == "value1"
108
+
109
+ def test_get_missing(self):
110
+ be = DiskBackend(self.dir)
111
+ assert be.get("nonexistent") is None
112
+
113
+ def test_expiration(self):
114
+ be = DiskBackend(self.dir)
115
+ be.set("key1", "value1", ttl=0.1)
116
+ time.sleep(0.15)
117
+ assert be.get("key1") is None
118
+
119
+ def test_delete(self):
120
+ be = DiskBackend(self.dir)
121
+ be.set("key1", "value1", ttl=60)
122
+ be.delete("key1")
123
+ assert be.get("key1") is None
124
+
125
+ def test_clear(self):
126
+ be = DiskBackend(self.dir)
127
+ be.set("k1", "v1", ttl=60)
128
+ be.set("k2", "v2", ttl=60)
129
+ be.clear()
130
+ assert be.get("k1") is None
131
+ assert be.get("k2") is None
132
+
133
+ def test_persistence(self):
134
+ be = DiskBackend(self.dir)
135
+ be.set("key1", {"complex": "data"}, ttl=60)
136
+ # Create new backend instance (simulates restart)
137
+ be2 = DiskBackend(self.dir)
138
+ result = be2.get("key1")
139
+ assert result is not None
140
+ assert result[1] == {"complex": "data"}
141
+
142
+ def test_various_types(self):
143
+ be = DiskBackend(self.dir)
144
+ be.set("int", 42, ttl=60)
145
+ be.set("list", [1, 2, 3], ttl=60)
146
+ be.set("dict", {"a": 1}, ttl=60)
147
+ be.set("none", None, ttl=60)
148
+ assert be.get("int")[1] == 42
149
+ assert be.get("list")[1] == [1, 2, 3]
150
+ assert be.get("dict")[1] == {"a": 1}
151
+ assert be.get("none")[1] is None
152
+
153
+
154
+ # ============================================================
155
+ # Decorator Tests
156
+ # ============================================================
157
+
158
+ class TestCacheDecorator:
159
+ def test_basic_caching(self):
160
+ call_count = 0
161
+
162
+ @cache(ttl="1h")
163
+ def add(a, b):
164
+ nonlocal call_count
165
+ call_count += 1
166
+ return a + b
167
+
168
+ assert add(2, 3) == 5
169
+ assert add(2, 3) == 5 # Should use cache
170
+ assert call_count == 1
171
+
172
+ def test_different_args(self):
173
+ call_count = 0
174
+
175
+ @cache(ttl="1h")
176
+ def add(a, b):
177
+ nonlocal call_count
178
+ call_count += 1
179
+ return a + b
180
+
181
+ assert add(2, 3) == 5
182
+ assert add(3, 4) == 7
183
+ assert call_count == 2
184
+
185
+ def test_ttl_expiration(self):
186
+ call_count = 0
187
+
188
+ @cache(ttl=0.1)
189
+ def add(a, b):
190
+ nonlocal call_count
191
+ call_count += 1
192
+ return a + b
193
+
194
+ assert add(2, 3) == 5
195
+ time.sleep(0.15)
196
+ assert add(2, 3) == 5 # Recomputed
197
+ assert call_count == 2
198
+
199
+ def test_cache_clear(self):
200
+ call_count = 0
201
+
202
+ @cache(ttl="1h")
203
+ def add(a, b):
204
+ nonlocal call_count
205
+ call_count += 1
206
+ return a + b
207
+
208
+ add(2, 3)
209
+ add.cache_clear()
210
+ add(2, 3)
211
+ assert call_count == 2
212
+
213
+ def test_cache_delete(self):
214
+ call_count = 0
215
+
216
+ @cache(ttl="1h")
217
+ def add(a, b):
218
+ nonlocal call_count
219
+ call_count += 1
220
+ return a + b
221
+
222
+ add(2, 3)
223
+ add.cache_delete(2, 3)
224
+ add(2, 3)
225
+ assert call_count == 2
226
+
227
+ def test_kwargs_caching(self):
228
+ call_count = 0
229
+
230
+ @cache(ttl="1h")
231
+ def greet(name, greeting="Hello"):
232
+ nonlocal call_count
233
+ call_count += 1
234
+ return f"{greeting}, {name}!"
235
+
236
+ assert greet("Alice") == "Hello, Alice!"
237
+ assert greet("Alice") == "Hello, Alice!"
238
+ assert greet("Alice", greeting="Hi") == "Hi, Alice!"
239
+ assert call_count == 2
240
+
241
+ def test_custom_key_fn(self):
242
+ call_count = 0
243
+
244
+ @cache(ttl="1h", key_fn=lambda f, a, k: f"{a[0]}_{k.get('mode', '')}")
245
+ def process(data, mode):
246
+ nonlocal call_count
247
+ call_count += 1
248
+ return f"{data}_{mode}"
249
+
250
+ assert process("x", mode="y") == "x_y"
251
+ assert process("x", mode="z") == "x_z" # Different key
252
+ assert call_count == 2
253
+
254
+ def test_custom_backend(self):
255
+ be = MemoryBackend()
256
+ call_count = 0
257
+
258
+ @cache(ttl="1h", backend=be)
259
+ def add(a, b):
260
+ nonlocal call_count
261
+ call_count += 1
262
+ return a + b
263
+
264
+ add(2, 3)
265
+ # Verify backend has the key
266
+ assert len(be._cache) == 1
267
+
268
+ def test_functools_wraps(self):
269
+ @cache(ttl="1h")
270
+ def my_func(a, b):
271
+ """My docstring."""
272
+ return a + b
273
+
274
+ assert my_func.__name__ == "my_func"
275
+ assert my_func.__doc__ == "My docstring."
276
+
277
+ def test_exception_not_cached(self):
278
+ call_count = 0
279
+
280
+ @cache(ttl="1h")
281
+ def fail():
282
+ nonlocal call_count
283
+ call_count += 1
284
+ raise ValueError("oops")
285
+
286
+ with pytest.raises(ValueError):
287
+ fail()
288
+ with pytest.raises(ValueError):
289
+ fail()
290
+ assert call_count == 2 # Not cached
291
+
292
+ def test_none_return(self):
293
+ call_count = 0
294
+
295
+ @cache(ttl="1h")
296
+ def return_none():
297
+ nonlocal call_count
298
+ call_count += 1
299
+ return None
300
+
301
+ assert return_none() is None
302
+ assert return_none() is None
303
+ assert call_count == 1 # Cached
304
+
305
+ def test_ttl_parsing(self):
306
+ # Test various TTL formats
307
+ call_count = 0
308
+
309
+ @cache(ttl="1s")
310
+ def f1():
311
+ nonlocal call_count
312
+ call_count += 1
313
+ return 1
314
+
315
+ @cache(ttl="5m")
316
+ def f2():
317
+ nonlocal call_count
318
+ call_count += 1
319
+ return 2
320
+
321
+ @cache(ttl="2h")
322
+ def f3():
323
+ nonlocal call_count
324
+ call_count += 1
325
+ return 3
326
+
327
+ @cache(ttl="1d")
328
+ def f4():
329
+ nonlocal call_count
330
+ call_count += 1
331
+ return 4
332
+
333
+ @cache(ttl="1w")
334
+ def f5():
335
+ nonlocal call_count
336
+ call_count += 1
337
+ return 5
338
+
339
+ @cache(ttl=3600) # raw seconds
340
+ def f6():
341
+ nonlocal call_count
342
+ call_count += 1
343
+ return 6
344
+
345
+ f1(); f2(); f3(); f4(); f5(); f6()
346
+ assert call_count == 6
347
+
348
+ def test_nested_decorator(self):
349
+ @cache(ttl="1h")
350
+ @staticmethod
351
+ def add(a, b):
352
+ return a + b
353
+
354
+ assert add(2, 3) == 5
355
+
356
+ def test_method_caching(self):
357
+ class Calculator:
358
+ def __init__(self):
359
+ self.calls = 0
360
+
361
+ @cache(ttl="1h")
362
+ def add(self, a, b):
363
+ self.calls += 1
364
+ return a + b
365
+
366
+ calc = Calculator()
367
+ assert calc.add(2, 3) == 5
368
+ assert calc.add(2, 3) == 5
369
+ assert calc.calls == 1
370
+
371
+ def test_concurrent_access(self):
372
+ import threading
373
+
374
+ @cache(ttl="1h")
375
+ def slow_func(x):
376
+ time.sleep(0.01)
377
+ return x * 2
378
+
379
+ results = []
380
+ def worker():
381
+ results.append(slow_func(5))
382
+
383
+ threads = [threading.Thread(target=worker) for _ in range(10)]
384
+ for t in threads:
385
+ t.start()
386
+ for t in threads:
387
+ t.join()
388
+
389
+ assert all(r == 10 for r in results)
390
+
391
+
392
+ # ============================================================
393
+ # Integration Tests
394
+ # ============================================================
395
+
396
+ class TestIntegration:
397
+ def test_memory_to_disk(self):
398
+ """Test that data can be cached in memory and retrieved from disk."""
399
+ mem_be = MemoryBackend()
400
+ disk_be = DiskBackend(".test_integration_cache")
401
+
402
+ try:
403
+ @cache(ttl="1h", backend=mem_be)
404
+ def compute(x):
405
+ return x * 2
406
+
407
+ result = compute(5)
408
+ assert result == 10
409
+
410
+ # Verify it's in memory
411
+ assert mem_be.get("some_key") is None # Different key
412
+ finally:
413
+ shutil.rmtree(".test_integration_cache", ignore_errors=True)
414
+
415
+ def test_real_world_pattern(self):
416
+ """Simulate real-world usage: API call caching."""
417
+ api_calls = []
418
+
419
+ @cache(ttl="5m")
420
+ def fetch_user(user_id):
421
+ api_calls.append(user_id)
422
+ return {"id": user_id, "name": f"User {user_id}"}
423
+
424
+ # First call hits the API
425
+ user = fetch_user(1)
426
+ assert user["name"] == "User 1"
427
+ assert len(api_calls) == 1
428
+
429
+ # Second call uses cache
430
+ user = fetch_user(1)
431
+ assert user["name"] == "User 1"
432
+ assert len(api_calls) == 1
433
+
434
+ # Different user hits the API
435
+ user = fetch_user(2)
436
+ assert user["name"] == "User 2"
437
+ assert len(api_calls) == 2
438
+
439
+ def test_cache_invalidation_pattern(self):
440
+ """Test manual cache invalidation."""
441
+ @cache(ttl="1h")
442
+ def get_config(key):
443
+ return f"value_for_{key}"
444
+
445
+ get_config("db_host")
446
+ get_config("db_port")
447
+
448
+ # Invalidate one
449
+ get_config.cache_delete("db_host")
450
+
451
+ # db_host should be gone, db_port should remain
452
+ # (we can't easily check this without accessing backend directly)