simple-redis-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.
- simple_redis_cache-0.1.0/LICENSE +21 -0
- simple_redis_cache-0.1.0/PKG-INFO +63 -0
- simple_redis_cache-0.1.0/README.md +53 -0
- simple_redis_cache-0.1.0/pyproject.toml +20 -0
- simple_redis_cache-0.1.0/setup.cfg +4 -0
- simple_redis_cache-0.1.0/src/__init__.py +0 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache/__init__.py +0 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache/cache.py +146 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache/encoder.py +17 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache/key_generator.py +45 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache.egg-info/PKG-INFO +63 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache.egg-info/SOURCES.txt +16 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache.egg-info/dependency_links.txt +1 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache.egg-info/requires.txt +1 -0
- simple_redis_cache-0.1.0/src/simple_redis_cache.egg-info/top_level.txt +2 -0
- simple_redis_cache-0.1.0/tests/test_cache.py +221 -0
- simple_redis_cache-0.1.0/tests/test_encoder.py +82 -0
- simple_redis_cache-0.1.0/tests/test_key_generator.py +166 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hotpotato89
|
|
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,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simple-redis-cache
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A library that simplifies working with Redis in Python
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: redis>=8.0.1
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# simple-redis-cache
|
|
12
|
+
|
|
13
|
+
[](https://hotpotato89.github.io/simple-redis-cache/coverage/)
|
|
14
|
+
|
|
15
|
+
Простой декоратор для кэширования асинхронных функций в Redis.
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Особенности
|
|
19
|
+
|
|
20
|
+
- **Автоматическая генерация ключей** — ключи создаются на основе имени функции и аргументов
|
|
21
|
+
- **Инвалидация по префиксу** — очищайте кэш группами
|
|
22
|
+
- **Кастомный JSON-энкодер** — поддерживает `datetime`, `Decimal`, `UUID`, Pydantic-модели
|
|
23
|
+
- **Устойчивость к ошибкам** — ошибки Redis не ломают приложение
|
|
24
|
+
- **Гибкая настройка** — можно передать свой логгер
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
## Установка
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install simple-redis-cache
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Пример
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from redis.asyncio import Redis
|
|
38
|
+
from simple_redis_cache import Cache
|
|
39
|
+
|
|
40
|
+
redis = Redis()
|
|
41
|
+
cache = Cache(redis)
|
|
42
|
+
|
|
43
|
+
@cache.cache(ttl=60, prefix="user")
|
|
44
|
+
async def get_user(user_id: int):
|
|
45
|
+
return {"id": user_id, "name": "Alice"}
|
|
46
|
+
|
|
47
|
+
# Первый вызов — вычисляется, второй — из кэша
|
|
48
|
+
r1 = await get_user(1)
|
|
49
|
+
r2 = await get_user(1)
|
|
50
|
+
|
|
51
|
+
# Одинаковый результат
|
|
52
|
+
print(r1 == r2)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Инвалидация
|
|
56
|
+
```python
|
|
57
|
+
await cache.invalidate_cache(prefix="user")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Лицензия
|
|
61
|
+
[**MIT**](LICENSE)
|
|
62
|
+
## Автор
|
|
63
|
+
[**hotpotato89**](https://github.com/hotpotato89)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# simple-redis-cache
|
|
2
|
+
|
|
3
|
+
[](https://hotpotato89.github.io/simple-redis-cache/coverage/)
|
|
4
|
+
|
|
5
|
+
Простой декоратор для кэширования асинхронных функций в Redis.
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
## Особенности
|
|
9
|
+
|
|
10
|
+
- **Автоматическая генерация ключей** — ключи создаются на основе имени функции и аргументов
|
|
11
|
+
- **Инвалидация по префиксу** — очищайте кэш группами
|
|
12
|
+
- **Кастомный JSON-энкодер** — поддерживает `datetime`, `Decimal`, `UUID`, Pydantic-модели
|
|
13
|
+
- **Устойчивость к ошибкам** — ошибки Redis не ломают приложение
|
|
14
|
+
- **Гибкая настройка** — можно передать свой логгер
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Установка
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install simple-redis-cache
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Пример
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from redis.asyncio import Redis
|
|
28
|
+
from simple_redis_cache import Cache
|
|
29
|
+
|
|
30
|
+
redis = Redis()
|
|
31
|
+
cache = Cache(redis)
|
|
32
|
+
|
|
33
|
+
@cache.cache(ttl=60, prefix="user")
|
|
34
|
+
async def get_user(user_id: int):
|
|
35
|
+
return {"id": user_id, "name": "Alice"}
|
|
36
|
+
|
|
37
|
+
# Первый вызов — вычисляется, второй — из кэша
|
|
38
|
+
r1 = await get_user(1)
|
|
39
|
+
r2 = await get_user(1)
|
|
40
|
+
|
|
41
|
+
# Одинаковый результат
|
|
42
|
+
print(r1 == r2)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Инвалидация
|
|
46
|
+
```python
|
|
47
|
+
await cache.invalidate_cache(prefix="user")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Лицензия
|
|
51
|
+
[**MIT**](LICENSE)
|
|
52
|
+
## Автор
|
|
53
|
+
[**hotpotato89**](https://github.com/hotpotato89)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "simple-redis-cache"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A library that simplifies working with Redis in Python"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"redis>=8.0.1",
|
|
9
|
+
]
|
|
10
|
+
|
|
11
|
+
[dependency-groups]
|
|
12
|
+
dev = [
|
|
13
|
+
"fakeredis>=2.36.2",
|
|
14
|
+
"pytest-asyncio>=1.4.0",
|
|
15
|
+
"pytest-cov>=7.1.0",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[tool.pytest.ini_options]
|
|
19
|
+
testpaths = ["tests"]
|
|
20
|
+
asyncio_mode = "auto"
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from functools import wraps
|
|
3
|
+
import hashlib
|
|
4
|
+
import inspect
|
|
5
|
+
import json
|
|
6
|
+
from logging import Logger, getLogger
|
|
7
|
+
from typing import Callable, TypeVar, ParamSpec, cast
|
|
8
|
+
|
|
9
|
+
from redis.asyncio import Redis
|
|
10
|
+
|
|
11
|
+
from src.simple_redis_cache.encoder import CustomJSONEncoder
|
|
12
|
+
from src.simple_redis_cache.key_generator import clean_args
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
P = ParamSpec("P")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Cache:
|
|
20
|
+
__slots__ = ("redis_client", "logger")
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self, redis_client: Redis, logger: Logger = getLogger(__name__)
|
|
24
|
+
) -> None:
|
|
25
|
+
self.redis_client = redis_client
|
|
26
|
+
self.logger = logger
|
|
27
|
+
|
|
28
|
+
def _gen_cache_key(
|
|
29
|
+
self,
|
|
30
|
+
func: Callable,
|
|
31
|
+
args: tuple,
|
|
32
|
+
kwargs: dict,
|
|
33
|
+
prefix: str | None = None,
|
|
34
|
+
) -> str:
|
|
35
|
+
cleaned_args = clean_args(args, func)
|
|
36
|
+
sorted_kwargs = dict(sorted(kwargs.items()))
|
|
37
|
+
|
|
38
|
+
data = {
|
|
39
|
+
"func_name": func.__name__,
|
|
40
|
+
"args": cleaned_args,
|
|
41
|
+
"kwargs": sorted_kwargs,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
key_hash = hashlib.sha256(
|
|
45
|
+
json.dumps(data, cls=CustomJSONEncoder, sort_keys=True).encode()
|
|
46
|
+
).hexdigest()
|
|
47
|
+
|
|
48
|
+
base_key = f"cache:{key_hash}"
|
|
49
|
+
if prefix:
|
|
50
|
+
return f"cache:{prefix}:{key_hash}"
|
|
51
|
+
return base_key
|
|
52
|
+
|
|
53
|
+
def cache(
|
|
54
|
+
self, ttl: int, prefix: str | None = None
|
|
55
|
+
) -> Callable[[Callable[P, T]], Callable[P, T]]:
|
|
56
|
+
def wrapper(func: Callable[P, T]) -> Callable[P, T]:
|
|
57
|
+
if not inspect.iscoroutinefunction(func):
|
|
58
|
+
raise TypeError(
|
|
59
|
+
f"@cache can only be used on async functions. "
|
|
60
|
+
f"'{func.__name__}' is sync."
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
@wraps(func)
|
|
64
|
+
async def inner(*args: P.args, **kwargs: P.kwargs) -> T:
|
|
65
|
+
cache_key = self._gen_cache_key(func, args, kwargs, prefix)
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
cached = await self.redis_client.get(cache_key)
|
|
69
|
+
if cached:
|
|
70
|
+
self.logger.debug("Cache HIT: %s", cache_key)
|
|
71
|
+
if cached == "__NULL__":
|
|
72
|
+
return None # type: ignore # pragma: no cover
|
|
73
|
+
return json.loads(cached)
|
|
74
|
+
except Exception as exc:
|
|
75
|
+
self.logger.warning(
|
|
76
|
+
"Failed cache get for key: %s",
|
|
77
|
+
cache_key,
|
|
78
|
+
exc_info=exc,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
result = await func(*args, **kwargs)
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
if result is None:
|
|
85
|
+
data_to_cache = "__NULL__"
|
|
86
|
+
else:
|
|
87
|
+
data_to_cache = json.dumps(result, cls=CustomJSONEncoder)
|
|
88
|
+
await self.redis_client.set(cache_key, data_to_cache, ex=ttl)
|
|
89
|
+
self.logger.debug("Cache saved: %s", cache_key)
|
|
90
|
+
except Exception as exc: # pragma: no cover
|
|
91
|
+
self.logger.warning(
|
|
92
|
+
"Failed cache set for key: %s",
|
|
93
|
+
cache_key,
|
|
94
|
+
exc_info=exc,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
return result
|
|
98
|
+
|
|
99
|
+
return cast(Callable[P, T], inner)
|
|
100
|
+
|
|
101
|
+
return wrapper
|
|
102
|
+
|
|
103
|
+
async def invalidate_cache(
|
|
104
|
+
self, prefix: str = "*", timeout_seconds: int = 30
|
|
105
|
+
) -> int:
|
|
106
|
+
if prefix == "*":
|
|
107
|
+
pattern = "cache:*"
|
|
108
|
+
else:
|
|
109
|
+
pattern = f"cache:{prefix}:*"
|
|
110
|
+
|
|
111
|
+
self.logger.debug("Starting cache invalidation by pattern: %s", pattern)
|
|
112
|
+
|
|
113
|
+
deleted_count = 0
|
|
114
|
+
cursor = 0
|
|
115
|
+
start_time = asyncio.get_event_loop().time()
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
while True:
|
|
119
|
+
if asyncio.get_event_loop().time() - start_time > timeout_seconds: # pragma: no cover
|
|
120
|
+
self.logger.warning(
|
|
121
|
+
"Cache invalidation timed out (%s)", timeout_seconds
|
|
122
|
+
)
|
|
123
|
+
break
|
|
124
|
+
|
|
125
|
+
cursor, keys = await self.redis_client.scan(
|
|
126
|
+
cursor,
|
|
127
|
+
match=pattern,
|
|
128
|
+
count=100,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
if keys:
|
|
132
|
+
await self.redis_client.delete(*keys)
|
|
133
|
+
deleted_count += len(keys)
|
|
134
|
+
|
|
135
|
+
if cursor == 0:
|
|
136
|
+
break
|
|
137
|
+
|
|
138
|
+
self.logger.info("Cache invalidated (%s keys)", deleted_count)
|
|
139
|
+
return deleted_count
|
|
140
|
+
|
|
141
|
+
except Exception as exc: # pragma: no cover
|
|
142
|
+
self.logger.error(
|
|
143
|
+
"Failed to invalidate cache",
|
|
144
|
+
exc_info=exc,
|
|
145
|
+
)
|
|
146
|
+
return deleted_count
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CustomJSONEncoder(json.JSONEncoder):
|
|
8
|
+
def default(self, obj: Any) -> Any:
|
|
9
|
+
if isinstance(obj, datetime):
|
|
10
|
+
return obj.isoformat()
|
|
11
|
+
if hasattr(obj, "model_dump"):
|
|
12
|
+
return obj.model_dump()
|
|
13
|
+
if hasattr(obj, "hex"):
|
|
14
|
+
return str(obj)
|
|
15
|
+
if isinstance(obj, Decimal):
|
|
16
|
+
return float(obj)
|
|
17
|
+
return super().default(obj)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import inspect
|
|
3
|
+
import json
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
from src.simple_redis_cache.encoder import CustomJSONEncoder
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def clean_args(args: tuple, func: Callable) -> tuple:
|
|
10
|
+
"""Remove 'self/cls/mcs' from args"""
|
|
11
|
+
if not args:
|
|
12
|
+
return args
|
|
13
|
+
|
|
14
|
+
sig = inspect.signature(func)
|
|
15
|
+
params = list(sig.parameters.keys())
|
|
16
|
+
|
|
17
|
+
if params and params[0] in ("self", "cls", "mcs"):
|
|
18
|
+
return args[1:]
|
|
19
|
+
|
|
20
|
+
return args
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def gen_cache_key(
|
|
24
|
+
func: Callable,
|
|
25
|
+
args: tuple,
|
|
26
|
+
kwargs: dict,
|
|
27
|
+
prefix: str | None = None,
|
|
28
|
+
) -> str:
|
|
29
|
+
cleaned_args = clean_args(args, func)
|
|
30
|
+
sorted_kwargs = dict(sorted(kwargs.items()))
|
|
31
|
+
|
|
32
|
+
data = {
|
|
33
|
+
"func_name": func.__name__,
|
|
34
|
+
"args": cleaned_args,
|
|
35
|
+
"kwargs": sorted_kwargs,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
key_hash = hashlib.sha256(
|
|
39
|
+
json.dumps(data, cls=CustomJSONEncoder, sort_keys=True).encode()
|
|
40
|
+
).hexdigest()
|
|
41
|
+
|
|
42
|
+
base_key = f"cache:{key_hash}"
|
|
43
|
+
if prefix:
|
|
44
|
+
return f"cache:{prefix}:{key_hash}"
|
|
45
|
+
return base_key
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simple-redis-cache
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A library that simplifies working with Redis in Python
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: redis>=8.0.1
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# simple-redis-cache
|
|
12
|
+
|
|
13
|
+
[](https://hotpotato89.github.io/simple-redis-cache/coverage/)
|
|
14
|
+
|
|
15
|
+
Простой декоратор для кэширования асинхронных функций в Redis.
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Особенности
|
|
19
|
+
|
|
20
|
+
- **Автоматическая генерация ключей** — ключи создаются на основе имени функции и аргументов
|
|
21
|
+
- **Инвалидация по префиксу** — очищайте кэш группами
|
|
22
|
+
- **Кастомный JSON-энкодер** — поддерживает `datetime`, `Decimal`, `UUID`, Pydantic-модели
|
|
23
|
+
- **Устойчивость к ошибкам** — ошибки Redis не ломают приложение
|
|
24
|
+
- **Гибкая настройка** — можно передать свой логгер
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
## Установка
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install simple-redis-cache
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Пример
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from redis.asyncio import Redis
|
|
38
|
+
from simple_redis_cache import Cache
|
|
39
|
+
|
|
40
|
+
redis = Redis()
|
|
41
|
+
cache = Cache(redis)
|
|
42
|
+
|
|
43
|
+
@cache.cache(ttl=60, prefix="user")
|
|
44
|
+
async def get_user(user_id: int):
|
|
45
|
+
return {"id": user_id, "name": "Alice"}
|
|
46
|
+
|
|
47
|
+
# Первый вызов — вычисляется, второй — из кэша
|
|
48
|
+
r1 = await get_user(1)
|
|
49
|
+
r2 = await get_user(1)
|
|
50
|
+
|
|
51
|
+
# Одинаковый результат
|
|
52
|
+
print(r1 == r2)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Инвалидация
|
|
56
|
+
```python
|
|
57
|
+
await cache.invalidate_cache(prefix="user")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Лицензия
|
|
61
|
+
[**MIT**](LICENSE)
|
|
62
|
+
## Автор
|
|
63
|
+
[**hotpotato89**](https://github.com/hotpotato89)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/__init__.py
|
|
5
|
+
src/simple_redis_cache/__init__.py
|
|
6
|
+
src/simple_redis_cache/cache.py
|
|
7
|
+
src/simple_redis_cache/encoder.py
|
|
8
|
+
src/simple_redis_cache/key_generator.py
|
|
9
|
+
src/simple_redis_cache.egg-info/PKG-INFO
|
|
10
|
+
src/simple_redis_cache.egg-info/SOURCES.txt
|
|
11
|
+
src/simple_redis_cache.egg-info/dependency_links.txt
|
|
12
|
+
src/simple_redis_cache.egg-info/requires.txt
|
|
13
|
+
src/simple_redis_cache.egg-info/top_level.txt
|
|
14
|
+
tests/test_cache.py
|
|
15
|
+
tests/test_encoder.py
|
|
16
|
+
tests/test_key_generator.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
redis>=8.0.1
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from unittest.mock import patch
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from src.simple_redis_cache.cache import Cache
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TestCacheDecorator:
|
|
10
|
+
async def test_cache_hit(self, fake_cache: Cache) -> None:
|
|
11
|
+
@fake_cache.cache(ttl=60)
|
|
12
|
+
async def test_func(x: int) -> int:
|
|
13
|
+
return x * 2
|
|
14
|
+
|
|
15
|
+
result1 = await test_func(5)
|
|
16
|
+
assert result1 == 10
|
|
17
|
+
|
|
18
|
+
result2 = await test_func(5)
|
|
19
|
+
assert result2 == 10
|
|
20
|
+
|
|
21
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
22
|
+
assert len(keys) == 1
|
|
23
|
+
|
|
24
|
+
async def test_cache_different_args(self, fake_cache: Cache) -> None:
|
|
25
|
+
@fake_cache.cache(ttl=60)
|
|
26
|
+
async def test_func(x: int) -> int:
|
|
27
|
+
return x * 2
|
|
28
|
+
|
|
29
|
+
await test_func(5)
|
|
30
|
+
await test_func(10)
|
|
31
|
+
|
|
32
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
33
|
+
assert len(keys) == 2
|
|
34
|
+
|
|
35
|
+
async def test_cache_none(self, fake_cache: Cache) -> None:
|
|
36
|
+
@fake_cache.cache(ttl=60)
|
|
37
|
+
async def test_func(x: int):
|
|
38
|
+
if x == 0:
|
|
39
|
+
return None
|
|
40
|
+
return x * 2
|
|
41
|
+
|
|
42
|
+
result = await test_func(0)
|
|
43
|
+
assert result is None
|
|
44
|
+
|
|
45
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
46
|
+
assert len(keys) == 1
|
|
47
|
+
|
|
48
|
+
cached = await fake_cache.redis_client.get(keys[0])
|
|
49
|
+
assert cached == b"__NULL__"
|
|
50
|
+
|
|
51
|
+
async def test_cache_ttl(self, fake_cache: Cache) -> None:
|
|
52
|
+
@fake_cache.cache(ttl=1)
|
|
53
|
+
async def test_func(x: int) -> int:
|
|
54
|
+
return x * 2
|
|
55
|
+
|
|
56
|
+
await test_func(5)
|
|
57
|
+
|
|
58
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
59
|
+
assert len(keys) == 1
|
|
60
|
+
|
|
61
|
+
await asyncio.sleep(1.5)
|
|
62
|
+
|
|
63
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
64
|
+
assert len(keys) == 0
|
|
65
|
+
|
|
66
|
+
async def test_cache_prefix(self, fake_cache: Cache) -> None:
|
|
67
|
+
@fake_cache.cache(ttl=60, prefix="user")
|
|
68
|
+
async def test_func(x: int) -> int:
|
|
69
|
+
return x * 2
|
|
70
|
+
|
|
71
|
+
await test_func(5)
|
|
72
|
+
|
|
73
|
+
keys = await fake_cache.redis_client.keys("cache:user:*")
|
|
74
|
+
assert len(keys) == 1
|
|
75
|
+
|
|
76
|
+
async def test_cache_default_ttl(self, fake_cache: Cache) -> None:
|
|
77
|
+
@fake_cache.cache(ttl=10)
|
|
78
|
+
async def test_func(x: int) -> int:
|
|
79
|
+
return x * 2
|
|
80
|
+
|
|
81
|
+
await test_func(5)
|
|
82
|
+
|
|
83
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
84
|
+
assert len(keys) == 1
|
|
85
|
+
|
|
86
|
+
ttl = await fake_cache.redis_client.ttl(keys[0])
|
|
87
|
+
assert ttl == 10
|
|
88
|
+
|
|
89
|
+
async def test_cache_kwargs(self, fake_cache: Cache) -> None:
|
|
90
|
+
@fake_cache.cache(ttl=60)
|
|
91
|
+
async def test_func(a: int, b: int) -> int:
|
|
92
|
+
return a + b
|
|
93
|
+
|
|
94
|
+
await test_func(a=1, b=2)
|
|
95
|
+
await test_func(b=2, a=1)
|
|
96
|
+
|
|
97
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
98
|
+
assert len(keys) == 1
|
|
99
|
+
|
|
100
|
+
async def test_cache_method(self, fake_cache: Cache) -> None:
|
|
101
|
+
class TestClass:
|
|
102
|
+
async def method(self, x: int) -> int:
|
|
103
|
+
return x * 2
|
|
104
|
+
|
|
105
|
+
obj = TestClass()
|
|
106
|
+
decorated = fake_cache.cache(ttl=60)(obj.method)
|
|
107
|
+
|
|
108
|
+
await decorated(10)
|
|
109
|
+
await decorated(10)
|
|
110
|
+
|
|
111
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
112
|
+
assert len(keys) == 1
|
|
113
|
+
|
|
114
|
+
async def test_cache_redis_error(self, fake_cache: Cache) -> None:
|
|
115
|
+
@fake_cache.cache(ttl=60)
|
|
116
|
+
async def test_func(x: int) -> int:
|
|
117
|
+
return x * 2
|
|
118
|
+
|
|
119
|
+
original_get = fake_cache.redis_client.get
|
|
120
|
+
|
|
121
|
+
async def failing_get(*args, **kwargs):
|
|
122
|
+
raise Exception("Redis connection error")
|
|
123
|
+
|
|
124
|
+
fake_cache.redis_client.get = failing_get
|
|
125
|
+
|
|
126
|
+
result = await test_func(5)
|
|
127
|
+
assert result == 10
|
|
128
|
+
|
|
129
|
+
fake_cache.redis_client.get = original_get
|
|
130
|
+
|
|
131
|
+
def test_cache_sync_function_error(self, fake_cache: Cache) -> None:
|
|
132
|
+
def sync_func():
|
|
133
|
+
return 42
|
|
134
|
+
|
|
135
|
+
with pytest.raises(TypeError) as exc:
|
|
136
|
+
fake_cache.cache(ttl=60)(sync_func)
|
|
137
|
+
|
|
138
|
+
assert "async" in str(exc.value)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class TestCacheInvalidation:
|
|
142
|
+
async def test_invalidate_by_prefix(self, fake_cache: Cache) -> None:
|
|
143
|
+
@fake_cache.cache(ttl=60, prefix="user")
|
|
144
|
+
async def user_func(x: int) -> int:
|
|
145
|
+
return x * 2
|
|
146
|
+
|
|
147
|
+
@fake_cache.cache(ttl=60, prefix="admin")
|
|
148
|
+
async def admin_func(x: int) -> int:
|
|
149
|
+
return x * 2
|
|
150
|
+
|
|
151
|
+
await user_func(5)
|
|
152
|
+
await admin_func(10)
|
|
153
|
+
|
|
154
|
+
user_keys = await fake_cache.redis_client.keys("cache:user:*")
|
|
155
|
+
admin_keys = await fake_cache.redis_client.keys("cache:admin:*")
|
|
156
|
+
assert len(user_keys) == 1
|
|
157
|
+
assert len(admin_keys) == 1
|
|
158
|
+
|
|
159
|
+
deleted = await fake_cache.invalidate_cache(prefix="user")
|
|
160
|
+
assert deleted == 1
|
|
161
|
+
|
|
162
|
+
user_keys = await fake_cache.redis_client.keys("cache:user:*")
|
|
163
|
+
admin_keys = await fake_cache.redis_client.keys("cache:admin:*")
|
|
164
|
+
assert len(user_keys) == 0
|
|
165
|
+
assert len(admin_keys) == 1
|
|
166
|
+
|
|
167
|
+
async def test_invalidate_all(self, fake_cache: Cache) -> None:
|
|
168
|
+
@fake_cache.cache(ttl=60, prefix="test")
|
|
169
|
+
async def test_func(x: int) -> int:
|
|
170
|
+
return x * 2
|
|
171
|
+
|
|
172
|
+
await test_func(5)
|
|
173
|
+
await test_func(10)
|
|
174
|
+
|
|
175
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
176
|
+
assert len(keys) == 2
|
|
177
|
+
|
|
178
|
+
deleted = await fake_cache.invalidate_cache()
|
|
179
|
+
assert deleted == 2
|
|
180
|
+
|
|
181
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
182
|
+
assert len(keys) == 0
|
|
183
|
+
|
|
184
|
+
async def test_invalidate_timeout(self, fake_cache: Cache) -> None:
|
|
185
|
+
@fake_cache.cache(ttl=60, prefix="test")
|
|
186
|
+
async def test_func(x: int) -> int:
|
|
187
|
+
return x * 2
|
|
188
|
+
|
|
189
|
+
for i in range(10):
|
|
190
|
+
await test_func(i)
|
|
191
|
+
|
|
192
|
+
async def slow_scan(*args, **kwargs):
|
|
193
|
+
await asyncio.sleep(1)
|
|
194
|
+
return 0, []
|
|
195
|
+
|
|
196
|
+
with patch.object(fake_cache.redis_client, "scan", side_effect=slow_scan):
|
|
197
|
+
deleted = await fake_cache.invalidate_cache(
|
|
198
|
+
prefix="test", timeout_seconds=1
|
|
199
|
+
)
|
|
200
|
+
assert deleted == 0
|
|
201
|
+
|
|
202
|
+
async def test_invalidate_empty(self, fake_cache: Cache) -> None:
|
|
203
|
+
deleted = await fake_cache.invalidate_cache(prefix="nonexistent")
|
|
204
|
+
assert deleted == 0
|
|
205
|
+
|
|
206
|
+
async def test_invalidate_no_prefix(self, fake_cache: Cache) -> None:
|
|
207
|
+
@fake_cache.cache(ttl=60)
|
|
208
|
+
async def test_func(x: int) -> int:
|
|
209
|
+
return x * 2
|
|
210
|
+
|
|
211
|
+
await test_func(5)
|
|
212
|
+
await test_func(10)
|
|
213
|
+
|
|
214
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
215
|
+
assert len(keys) == 2
|
|
216
|
+
|
|
217
|
+
deleted = await fake_cache.invalidate_cache()
|
|
218
|
+
assert deleted == 2
|
|
219
|
+
|
|
220
|
+
keys = await fake_cache.redis_client.keys("cache:*")
|
|
221
|
+
assert len(keys) == 0
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from decimal import Decimal
|
|
4
|
+
from uuid import uuid4
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from src.simple_redis_cache.encoder import CustomJSONEncoder
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TestCustomJSONEncoder:
|
|
12
|
+
def test_datetime_serialization(self):
|
|
13
|
+
dt = datetime(2026, 7, 10, 15, 30, 0)
|
|
14
|
+
result = json.dumps({"date": dt}, cls=CustomJSONEncoder)
|
|
15
|
+
assert result == '{"date": "2026-07-10T15:30:00"}'
|
|
16
|
+
|
|
17
|
+
def test_decimal_serialization(self):
|
|
18
|
+
dec = Decimal("10.5")
|
|
19
|
+
result = json.dumps({"price": dec}, cls=CustomJSONEncoder)
|
|
20
|
+
assert result == '{"price": 10.5}'
|
|
21
|
+
|
|
22
|
+
def test_uuid_serialization(self):
|
|
23
|
+
uid = uuid4()
|
|
24
|
+
result = json.dumps({"id": uid}, cls=CustomJSONEncoder)
|
|
25
|
+
expected = f'{{"id": "{str(uid)}"}}'
|
|
26
|
+
assert result == expected
|
|
27
|
+
|
|
28
|
+
def test_pydantic_model_serialization(self):
|
|
29
|
+
class TestModel:
|
|
30
|
+
def __init__(self, name: str, age: int):
|
|
31
|
+
self.name = name
|
|
32
|
+
self.age = age
|
|
33
|
+
|
|
34
|
+
def model_dump(self):
|
|
35
|
+
return {"name": self.name, "age": self.age}
|
|
36
|
+
|
|
37
|
+
obj = TestModel("Alice", 30)
|
|
38
|
+
result = json.dumps({"user": obj}, cls=CustomJSONEncoder)
|
|
39
|
+
assert result == '{"user": {"name": "Alice", "age": 30}}'
|
|
40
|
+
|
|
41
|
+
def test_dict_with_model_dump(self):
|
|
42
|
+
class TestModel:
|
|
43
|
+
def __init__(self, name: str):
|
|
44
|
+
self.name = name
|
|
45
|
+
|
|
46
|
+
def model_dump(self):
|
|
47
|
+
return {"name": self.name}
|
|
48
|
+
|
|
49
|
+
obj = TestModel("Bob")
|
|
50
|
+
result = json.dumps({"user": obj}, cls=CustomJSONEncoder)
|
|
51
|
+
assert result == '{"user": {"name": "Bob"}}'
|
|
52
|
+
|
|
53
|
+
def test_unknown_type_raises_error(self):
|
|
54
|
+
class UnknownType:
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
obj = UnknownType()
|
|
58
|
+
with pytest.raises(TypeError) as exc:
|
|
59
|
+
json.dumps({"data": obj}, cls=CustomJSONEncoder)
|
|
60
|
+
assert "is not JSON serializable" in str(exc.value)
|
|
61
|
+
|
|
62
|
+
def test_none_serialization(self):
|
|
63
|
+
result = json.dumps({"value": None}, cls=CustomJSONEncoder)
|
|
64
|
+
assert result == '{"value": null}'
|
|
65
|
+
|
|
66
|
+
def test_list_of_mixed_types(self):
|
|
67
|
+
dt = datetime(2026, 7, 10, 15, 30, 0)
|
|
68
|
+
dec = Decimal("10.5")
|
|
69
|
+
data = [dt, dec, "text", 42]
|
|
70
|
+
result = json.dumps(data, cls=CustomJSONEncoder)
|
|
71
|
+
assert result == '["2026-07-10T15:30:00", 10.5, "text", 42]'
|
|
72
|
+
|
|
73
|
+
def test_nested_structures(self):
|
|
74
|
+
dt = datetime(2026, 7, 10, 15, 30, 0)
|
|
75
|
+
data = {
|
|
76
|
+
"user": {"name": "Alice", "created_at": dt, "balance": Decimal("100.50")}
|
|
77
|
+
}
|
|
78
|
+
result = json.dumps(data, cls=CustomJSONEncoder)
|
|
79
|
+
assert (
|
|
80
|
+
result
|
|
81
|
+
== '{"user": {"name": "Alice", "created_at": "2026-07-10T15:30:00", "balance": 100.5}}'
|
|
82
|
+
)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from src.simple_redis_cache.key_generator import clean_args, gen_cache_key
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TestCleanArgs:
|
|
7
|
+
def test_clean_args_no_args(self):
|
|
8
|
+
def test_func():
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
result = clean_args((), test_func)
|
|
12
|
+
assert result == ()
|
|
13
|
+
|
|
14
|
+
def test_clean_args_no_self(self):
|
|
15
|
+
def test_func(x: int, y: int) -> int:
|
|
16
|
+
return x + y
|
|
17
|
+
|
|
18
|
+
result = clean_args((1, 2), test_func)
|
|
19
|
+
assert result == (1, 2)
|
|
20
|
+
|
|
21
|
+
def test_clean_args_with_self(self):
|
|
22
|
+
class TestClass:
|
|
23
|
+
def method(self, x: int) -> int:
|
|
24
|
+
return x * 2
|
|
25
|
+
|
|
26
|
+
obj = TestClass()
|
|
27
|
+
result = clean_args((obj, 5), TestClass.method)
|
|
28
|
+
assert result == (5,)
|
|
29
|
+
|
|
30
|
+
def test_clean_args_with_cls(self):
|
|
31
|
+
class TestClass:
|
|
32
|
+
@classmethod
|
|
33
|
+
def class_method(cls, x: int) -> int:
|
|
34
|
+
return x * 2
|
|
35
|
+
|
|
36
|
+
result = clean_args((5,), TestClass.class_method)
|
|
37
|
+
assert result == (5,)
|
|
38
|
+
|
|
39
|
+
def test_clean_args_with_static_method(self):
|
|
40
|
+
class TestClass:
|
|
41
|
+
@staticmethod
|
|
42
|
+
def static_method(x: int) -> int:
|
|
43
|
+
return x * 2
|
|
44
|
+
|
|
45
|
+
result = clean_args((5,), TestClass.static_method)
|
|
46
|
+
assert result == (5,)
|
|
47
|
+
|
|
48
|
+
def test_clean_args_multiple_args(self):
|
|
49
|
+
def test_func(a: int, b: int, c: int) -> int:
|
|
50
|
+
return a + b + c
|
|
51
|
+
|
|
52
|
+
result = clean_args((1, 2, 3), test_func)
|
|
53
|
+
assert result == (1, 2, 3)
|
|
54
|
+
|
|
55
|
+
def test_clean_args_empty_tuple(self):
|
|
56
|
+
def test_func(x: int) -> int:
|
|
57
|
+
return x
|
|
58
|
+
|
|
59
|
+
result = clean_args((), test_func)
|
|
60
|
+
assert result == ()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class TestGenCacheKey:
|
|
64
|
+
def test_gen_key_without_args(self):
|
|
65
|
+
def test_func() -> int:
|
|
66
|
+
return 42
|
|
67
|
+
|
|
68
|
+
key = gen_cache_key(test_func, (), {})
|
|
69
|
+
assert key.startswith("cache:")
|
|
70
|
+
assert len(key) > 10
|
|
71
|
+
|
|
72
|
+
def test_gen_key_with_positional_args(self):
|
|
73
|
+
def test_func(a: int, b: int) -> int:
|
|
74
|
+
return a + b
|
|
75
|
+
|
|
76
|
+
key1 = gen_cache_key(test_func, (1, 2), {})
|
|
77
|
+
key2 = gen_cache_key(test_func, (3, 4), {})
|
|
78
|
+
assert key1 != key2
|
|
79
|
+
assert key1.startswith("cache:")
|
|
80
|
+
assert key2.startswith("cache:")
|
|
81
|
+
|
|
82
|
+
def test_gen_key_with_kwargs(self):
|
|
83
|
+
def test_func(a: int, b: int) -> int:
|
|
84
|
+
return a + b
|
|
85
|
+
|
|
86
|
+
key1 = gen_cache_key(test_func, (), {"a": 1, "b": 2})
|
|
87
|
+
key2 = gen_cache_key(test_func, (), {"a": 3, "b": 4})
|
|
88
|
+
assert key1 != key2
|
|
89
|
+
|
|
90
|
+
def test_gen_key_with_mixed_args(self):
|
|
91
|
+
def test_func(a: int, b: int, c: int = 0) -> int:
|
|
92
|
+
return a + b + c
|
|
93
|
+
|
|
94
|
+
key1 = gen_cache_key(test_func, (1, 2), {"c": 3})
|
|
95
|
+
key2 = gen_cache_key(test_func, (1, 2), {"c": 4})
|
|
96
|
+
assert key1 != key2
|
|
97
|
+
|
|
98
|
+
def test_gen_key_with_prefix(self):
|
|
99
|
+
def test_func(x: int) -> int:
|
|
100
|
+
return x * 2
|
|
101
|
+
|
|
102
|
+
key = gen_cache_key(test_func, (5,), {}, prefix="test")
|
|
103
|
+
assert key.startswith("cache:test:")
|
|
104
|
+
assert len(key) > 10
|
|
105
|
+
|
|
106
|
+
def test_gen_key_without_prefix(self):
|
|
107
|
+
def test_func(x: int) -> int:
|
|
108
|
+
return x * 2
|
|
109
|
+
|
|
110
|
+
key = gen_cache_key(test_func, (5,), {})
|
|
111
|
+
assert key.startswith("cache:")
|
|
112
|
+
assert "test" not in key
|
|
113
|
+
|
|
114
|
+
def test_gen_key_consistency(self):
|
|
115
|
+
def test_func(x: int) -> int:
|
|
116
|
+
return x * 2
|
|
117
|
+
|
|
118
|
+
key1 = gen_cache_key(test_func, (5,), {})
|
|
119
|
+
key2 = gen_cache_key(test_func, (5,), {})
|
|
120
|
+
assert key1 == key2
|
|
121
|
+
|
|
122
|
+
def test_gen_key_different_functions(self):
|
|
123
|
+
def func1(x: int) -> int:
|
|
124
|
+
return x * 2
|
|
125
|
+
|
|
126
|
+
def func2(x: int) -> int:
|
|
127
|
+
return x * 3
|
|
128
|
+
|
|
129
|
+
key1 = gen_cache_key(func1, (5,), {})
|
|
130
|
+
key2 = gen_cache_key(func2, (5,), {})
|
|
131
|
+
assert key1 != key2
|
|
132
|
+
|
|
133
|
+
def test_gen_key_with_self(self):
|
|
134
|
+
class TestClass:
|
|
135
|
+
def method(self, x: int) -> int:
|
|
136
|
+
return x * 2
|
|
137
|
+
|
|
138
|
+
obj = TestClass()
|
|
139
|
+
method = obj.method
|
|
140
|
+
|
|
141
|
+
key = gen_cache_key(method, (5,), {})
|
|
142
|
+
assert key.startswith("cache:")
|
|
143
|
+
|
|
144
|
+
def test_gen_key_with_str_arg(self):
|
|
145
|
+
def test_func(name: str) -> str:
|
|
146
|
+
return f"Hello, {name}"
|
|
147
|
+
|
|
148
|
+
key1 = gen_cache_key(test_func, ("Alice",), {})
|
|
149
|
+
key2 = gen_cache_key(test_func, ("Bob",), {})
|
|
150
|
+
assert key1 != key2
|
|
151
|
+
|
|
152
|
+
def test_gen_key_with_bool_arg(self):
|
|
153
|
+
def test_func(flag: bool) -> bool:
|
|
154
|
+
return flag
|
|
155
|
+
|
|
156
|
+
key1 = gen_cache_key(test_func, (True,), {})
|
|
157
|
+
key2 = gen_cache_key(test_func, (False,), {})
|
|
158
|
+
assert key1 != key2
|
|
159
|
+
|
|
160
|
+
def test_gen_key_with_none_arg(self):
|
|
161
|
+
def test_func(value: int | None) -> int | None:
|
|
162
|
+
return value
|
|
163
|
+
|
|
164
|
+
key1 = gen_cache_key(test_func, (None,), {})
|
|
165
|
+
key2 = gen_cache_key(test_func, (5,), {})
|
|
166
|
+
assert key1 != key2
|