From 1a30325420372f4cfeb88df66fffe6574ac4e57b Mon Sep 17 00:00:00 2001 From: Kyungmin Bae Date: Mon, 27 May 2024 20:17:32 +0900 Subject: [PATCH 1/2] Return empty array for SRANDMEMBER on nonexistent key If the count argument is given, Redis returns an empty array if the key does not exist, unlike single call which returns nil. Mimic this behavior more precisely. --- cmd_set.go | 4 ++++ cmd_set_test.go | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/cmd_set.go b/cmd_set.go index 2aaa7b0..abcd1ba 100644 --- a/cmd_set.go +++ b/cmd_set.go @@ -582,6 +582,10 @@ func (m *Miniredis) cmdSrandmember(c *server.Peer, cmd string, args []string) { db := m.db(ctx.selectedDB) if !db.exists(key) { + if withCount { + c.WriteLen(0) + return + } c.WriteNull() return } diff --git a/cmd_set_test.go b/cmd_set_test.go index caefbfd..7923f0e 100644 --- a/cmd_set_test.go +++ b/cmd_set_test.go @@ -381,6 +381,12 @@ func TestSrandmember(t *testing.T) { "SRANDMEMBER", "nosuch", ) + // a nonexisting key with count + mustDo(t, c, + "SRANDMEMBER", "nosuch", "1", + proto.Strings(), + ) + t.Run("errors", func(t *testing.T) { s.SetAdd("chk", "aap", "noot") s.Set("str", "value") From c007f55180555e9e2fa3d0bfa45806e742505f32 Mon Sep 17 00:00:00 2001 From: Kyungmin Bae Date: Mon, 27 May 2024 22:42:08 +0900 Subject: [PATCH 2/2] Add integration test for SRANDMEMBER on nonexistent key --- integration/set_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/integration/set_test.go b/integration/set_test.go index 2e53e9f..54f9fb9 100644 --- a/integration/set_test.go +++ b/integration/set_test.go @@ -191,7 +191,8 @@ func TestSetSrandmember(t *testing.T) { c.Do("SRANDMEMBER", "s", "-5") c.Do("SRANDMEMBER", "s", "0") - c.Do("SPOP", "nosuch") + c.Do("SRANDMEMBER", "nosuch") + c.Do("SRANDMEMBER", "nosuch", "1") // failure cases c.Error("wrong number", "SRANDMEMBER")