Skip to content
This repository has been archived by the owner on Feb 21, 2023. It is now read-only.

Commit

Permalink
Merge pull request #485 from cleverdec/master
Browse files Browse the repository at this point in the history
add a count to spop
  • Loading branch information
popravich committed Nov 2, 2018
2 parents b1cd04c + b3d2497 commit 10ac4cb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
9 changes: 6 additions & 3 deletions aioredis/commands/set.py
Expand Up @@ -43,9 +43,12 @@ def smove(self, sourcekey, destkey, member):
"""Move a member from one set to another."""
return self.execute(b'SMOVE', sourcekey, destkey, member)

def spop(self, key, *, encoding=_NOTSET):
"""Remove and return a random member from a set."""
return self.execute(b'SPOP', key, encoding=encoding)
def spop(self, key, count=None, *, encoding=_NOTSET):
"""Remove and return one or multiple random members from a set."""
args = [key]
if count is not None:
args.append(count)
return self.execute(b'SPOP', *args, encoding=encoding)

def srandmember(self, key, count=None, *, encoding=_NOTSET):
"""Get one or multiple random members from a set."""
Expand Down
38 changes: 38 additions & 0 deletions tests/set_commands_test.py
@@ -1,5 +1,7 @@
import pytest

from aioredis import ReplyError


async def add(redis, key, members):
ok = await redis.connection.execute(b'sadd', key, members)
Expand Down Expand Up @@ -277,6 +279,42 @@ async def test_spop(redis):
await redis.spop(None)


@pytest.redis_version(
3, 2, 0,
reason="The count argument in SPOP is available since redis>=3.2.0"
)
@pytest.mark.run_loop
async def test_spop_count(redis):
key = b'key:spop:1'
members1 = b'one', b'two', b'three'
await redis.sadd(key, *members1)

# fetch 3 random members
test_result1 = await redis.spop(key, 3)
assert len(test_result1) == 3
assert set(test_result1).issubset(members1) is True

members2 = 'four', 'five', 'six'
await redis.sadd(key, *members2)

# test with encoding, fetch 3 random members
test_result2 = await redis.spop(key, 3, encoding='utf-8')
assert len(test_result2) == 3
assert set(test_result2).issubset(members2) is True

# try to pop data from empty set
test_result = await redis.spop(b'not:' + key, 2)
assert len(test_result) == 0

# test with negative counter
with pytest.raises(ReplyError):
await redis.spop(key, -2)

# test with counter is zero
test_result3 = await redis.spop(key, 0)
assert len(test_result3) == 0


@pytest.mark.run_loop
async def test_srandmember(redis):
key = b'key:srandmember:1'
Expand Down

0 comments on commit 10ac4cb

Please sign in to comment.