Skip to content

Commit e49fb34

Browse files
committed
refactor cache instantiation
only context manager is supported to instantiate ValkeyBackend
1 parent 6f2b231 commit e49fb34

File tree

3 files changed

+33
-43
lines changed

3 files changed

+33
-43
lines changed

aiocache/backends/valkey.py

+17-22
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
22
import time
3-
from typing import Any, Callable, Optional, TYPE_CHECKING, List
3+
from typing import Any, Callable, List, Optional, Self, TYPE_CHECKING
44

55
from glide import (
66
ConditionalChange,
@@ -24,14 +24,24 @@
2424

2525

2626
class ValkeyBackend(BaseCache[str]):
27-
def __init__(
28-
self,
29-
client: GlideClient,
30-
**kwargs,
31-
):
27+
def __init__(self, config: GlideClientConfiguration = None, **kwargs):
28+
self.config = config
3229
super().__init__(**kwargs)
3330

34-
self.client = client
31+
async def __aenter__(self) -> Self:
32+
if not self.config:
33+
raise AttributeError("Configuration must be provided for context manager")
34+
self.client = await self._connect(self.config)
35+
return self
36+
37+
async def __aexit__(self, *args, **kwargs) -> None:
38+
await self._disconnect()
39+
40+
async def _connect(self, config: GlideClientConfiguration) -> GlideClient:
41+
return await GlideClient.create(config=config)
42+
43+
async def _disconnect(self) -> None:
44+
await self.client.close()
3545

3646
async def _get(self, key, encoding="utf-8", _conn=None):
3747
value = await self.client.get(key)
@@ -203,32 +213,17 @@ class ValkeyCache(ValkeyBackend):
203213

204214
def __init__(
205215
self,
206-
client: Optional[GlideClient] = None,
207216
serializer: Optional["BaseSerializer"] = None,
208217
namespace: str = "",
209218
key_builder: Callable[[str, str], str] = lambda k, ns: f"{ns}:{k}" if ns else k,
210-
backend: type[GlideClient] = GlideClient,
211-
config: GlideClientConfiguration = None,
212219
**kwargs: Any,
213220
):
214221
super().__init__(
215-
client=client,
216222
serializer=serializer or JsonSerializer(),
217223
namespace=namespace,
218224
key_builder=key_builder,
219225
**kwargs,
220226
)
221-
self.backend = backend
222-
self.config = config
223-
224-
async def __aenter__(self):
225-
if not self.config:
226-
raise AttributeError("Configuration must be provided for context manager")
227-
self.client = await self.backend.create(config=self.config)
228-
return self
229-
230-
async def __aexit__(self, *args, **kwargs):
231-
await self.client.close()
232227

233228
@classmethod
234229
def parse_uri_path(cls, path):

tests/conftest.py

-11
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,3 @@ def valkey_config():
1919
conf = GlideClientConfiguration(addresses=addresses, database_id=0)
2020

2121
yield conf
22-
23-
24-
@pytest.fixture
25-
async def valkey_client(max_conns, decode_responses, valkey_config):
26-
from glide import GlideClient
27-
28-
client = await GlideClient.create(valkey_config)
29-
30-
yield client
31-
32-
await client.close()

tests/ut/backends/test_valkey.py

+16-10
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212

1313

1414
@pytest.fixture
15-
def valkey(valkey_client):
16-
valkey = ValkeyBackend(client=valkey_client)
15+
async def valkey(valkey_config):
16+
valkey = await ValkeyBackend(config=valkey_config).__aenter__()
1717
with patch.object(valkey, "client", autospec=True) as m:
1818
# These methods actually return an awaitable.
1919
for method in (
@@ -34,6 +34,8 @@ def valkey(valkey_client):
3434

3535
yield valkey
3636

37+
await valkey.__aexit__()
38+
3739

3840
class TestValkeyBackend:
3941
async def test_get(self, valkey):
@@ -55,7 +57,9 @@ async def test_set(self, valkey):
5557

5658
async def test_set_cas_token(self, mocker, valkey):
5759
mocker.patch.object(valkey, "_cas")
58-
await valkey._set(Keys.KEY, "value", _cas_token="old_value", _conn=valkey.client)
60+
await valkey._set(
61+
Keys.KEY, "value", _cas_token="old_value", _conn=valkey.client
62+
)
5963
valkey._cas.assert_called_with(
6064
Keys.KEY, "value", "old_value", ttl=None, _conn=valkey.client
6165
)
@@ -196,18 +200,18 @@ def set_test_namespace(self, valkey_cache):
196200
def test_name(self):
197201
assert ValkeyCache.NAME == "valkey"
198202

199-
def test_inheritance(self, valkey_client):
200-
assert isinstance(ValkeyCache(client=valkey_client), BaseCache)
203+
def test_inheritance(self, valkey_config):
204+
assert isinstance(ValkeyCache(config=valkey_config), BaseCache)
201205

202-
def test_default_serializer(self, valkey_client):
203-
assert isinstance(ValkeyCache(client=valkey_client).serializer, JsonSerializer)
206+
def test_default_serializer(self, valkey_config):
207+
assert isinstance(ValkeyCache(config=valkey_config).serializer, JsonSerializer)
204208

205209
@pytest.mark.parametrize(
206210
"path,expected",
207211
[("", {}), ("/", {}), ("/1", {"db": "1"}), ("/1/2/3", {"db": "1"})],
208212
)
209-
def test_parse_uri_path(self, path, expected, valkey_client):
210-
assert ValkeyCache(client=valkey_client).parse_uri_path(path) == expected
213+
def test_parse_uri_path(self, path, expected, valkey_config):
214+
assert ValkeyCache(config=valkey_config).parse_uri_path(path) == expected
211215

212216
@pytest.mark.parametrize(
213217
"namespace, expected",
@@ -217,7 +221,9 @@ def test_parse_uri_path(self, path, expected, valkey_client):
217221
["my_ns", "my_ns:" + ensure_key(Keys.KEY)],
218222
), # noqa: B950
219223
)
220-
def test_build_key_double_dot(self, set_test_namespace, valkey_cache, namespace, expected):
224+
def test_build_key_double_dot(
225+
self, set_test_namespace, valkey_cache, namespace, expected
226+
):
221227
assert valkey_cache.build_key(Keys.KEY, namespace) == expected
222228

223229
def test_build_key_no_namespace(self, valkey_cache):

0 commit comments

Comments
 (0)