Skip to content

Commit

Permalink
Changed add redis to use set with not existing flag (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
argaen authored Jan 30, 2017
1 parent 24de129 commit 6691248
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
5 changes: 3 additions & 2 deletions aiocache/backends/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,11 @@ async def _add(self, key, value, ttl=None):
"""

with await self._connect() as redis:
if await redis.exists(key):
was_set = await redis.set(key, value, expire=ttl, exist=redis.SET_IF_NOT_EXIST)
if not was_set:
raise ValueError(
"Key {} already exists, use .set to update the value".format(key))
return await redis.set(key, value, expire=ttl)
return was_set

async def _exists(self, key):
"""
Expand Down
11 changes: 8 additions & 3 deletions tests/ut/backends/test_redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,12 @@ def set_settings():

class FakePool:

SET_IF_NOT_EXIST = 'SET_IF_NOT_EXIST'

def __init__(self):
self.client = CoroutineMock()
client = CoroutineMock()
client.SET_IF_NOT_EXIST = self.SET_IF_NOT_EXIST
self.client = client
self.transaction = MagicMock()
self.client.multi_exec = MagicMock(return_value=self.transaction)
self.client.multi_exec.return_value.execute = CoroutineMock()
Expand Down Expand Up @@ -156,13 +160,14 @@ async def test_multi_set_with_ttl(self, redis):
@pytest.mark.asyncio
async def test_add(self, redis):
cache, pool = redis
pool.client.exists.return_value = False
await cache._add(pytest.KEY, "value")
pool.client.set.assert_called_with(pytest.KEY, "value", expire=None)
pool.client.set.assert_called_with(
pytest.KEY, "value", expire=None, exist=pool.SET_IF_NOT_EXIST)

@pytest.mark.asyncio
async def test_add_existing(self, redis):
cache, pool = redis
pool.client.set.return_value = False
with pytest.raises(ValueError):
await cache._add(pytest.KEY, "value")

Expand Down

0 comments on commit 6691248

Please sign in to comment.