From b242659b0708a03a31474da590b7c17e079f6191 Mon Sep 17 00:00:00 2001 From: Joshua Van Deren <22926257+jvanderen1@users.noreply.github.com> Date: Thu, 14 Nov 2024 16:10:37 -0700 Subject: [PATCH] Fix `hset` for Array of Key / Value Pairs (#312) Fixes https://github.com/sds/mock_redis/issues/310 This resolves an issue where `Redis` and `MockRedis` were storing values slightly differently: ## With Redis: ```ruby require 'redis' redis = Redis.new hash = {:name=>"job", :namespace=>"default", :klass=>"Job"} redis.hset("key", hash.flatten) redis.hgetall("key") => {"name"=>"job", "namespace"=>"default", "klass"=>"Job"} ``` ## With MockRedis (with this change): ```ruby require 'mock_redis' mock_redis = MockRedis.new hash = {:name=>"job", :namespace=>"default", :klass=>"Job"} mock_redis.hset("key", hash.flatten) mock_redis.hgetall("key") => {"name"=>"job", "namespace"=>"default", "klass"=>"Job"} ``` --- lib/mock_redis/hash_methods.rb | 1 + spec/commands/hset_spec.rb | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/lib/mock_redis/hash_methods.rb b/lib/mock_redis/hash_methods.rb index b400510..530cd2d 100644 --- a/lib/mock_redis/hash_methods.rb +++ b/lib/mock_redis/hash_methods.rb @@ -137,6 +137,7 @@ def hscan_each(key, opts = {}, &block) def hset(key, *args) added = 0 + args.flatten!(1) with_hash_at(key) do |hash| if args.length == 1 && args[0].is_a?(Hash) args = args[0].to_a.flatten diff --git a/spec/commands/hset_spec.rb b/spec/commands/hset_spec.rb index bc6506c..1a10b96 100644 --- a/spec/commands/hset_spec.rb +++ b/spec/commands/hset_spec.rb @@ -38,5 +38,17 @@ expect(@redises.hset(@key, { 'k1' => 'v1', 'k2' => 'v2' })).to eq(2) end + it 'stores array values correctly' do + @redises.hset(@key, %w[k1 v1 k2 v2]) + expect(@redises.hget(@key, 'k1')).to eq('v1') + expect(@redises.hget(@key, 'k2')).to eq('v2') + end + + it 'stores multiple arguments correctly' do + @redises.hset(@key, 'k1', 'v1', 'k2', 'v2') + expect(@redises.hget(@key, 'k1')).to eq('v1') + expect(@redises.hget(@key, 'k2')).to eq('v2') + end + it_should_behave_like 'a hash-only command' end