From 2665966d4d42ba7fe4c69bf2ef52bbab607726d9 Mon Sep 17 00:00:00 2001 From: Jason Penny Date: Wed, 24 Jan 2024 14:47:27 -0500 Subject: [PATCH] Add support for `memory usage ...` command (#301) `MEMORY USAGE key` currently results in `NoMethodError: undefined method 'memory' for # m = MockRedis.new > m.call(["memory", "usage", "foo"]) => nil > m.set("foo", "anything") => "OK" > m.call(["memory", "usage", "foo"]) => 160 ``` --- lib/mock_redis/database.rb | 2 ++ lib/mock_redis/memory_method.rb | 11 +++++++++++ spec/commands/memory_spec.rb | 23 +++++++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 lib/mock_redis/memory_method.rb create mode 100644 spec/commands/memory_spec.rb diff --git a/lib/mock_redis/database.rb b/lib/mock_redis/database.rb index 25da212..ef6933b 100644 --- a/lib/mock_redis/database.rb +++ b/lib/mock_redis/database.rb @@ -12,6 +12,7 @@ require 'mock_redis/geospatial_methods' require 'mock_redis/stream_methods' require 'mock_redis/connection_method' +require 'mock_redis/memory_method' class MockRedis class Database @@ -26,6 +27,7 @@ class Database include GeospatialMethods include StreamMethods include ConnectionMethod + include MemoryMethod attr_reader :data, :expire_times diff --git a/lib/mock_redis/memory_method.rb b/lib/mock_redis/memory_method.rb new file mode 100644 index 0000000..f3c0873 --- /dev/null +++ b/lib/mock_redis/memory_method.rb @@ -0,0 +1,11 @@ +class MockRedis + module MemoryMethod + def memory(usage, key = nil, *_options) + raise ArgumentError, "unhandled command `memory #{usage}`" if usage != 'usage' + + return nil unless @data.key?(key) + + 160 + end + end +end diff --git a/spec/commands/memory_spec.rb b/spec/commands/memory_spec.rb new file mode 100644 index 0000000..acdfd85 --- /dev/null +++ b/spec/commands/memory_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' + +RSpec.describe '#memory usage [mock only]' do + it 'only handles the usage subcommand' do + expect { @redises.mock.call(%w[memory stats]) }.to raise_error(ArgumentError) + end + + context 'when the key does not exist' do + before { @redises.real.del('foo') } + + it 'returns nil' do + expect(@redises.call(%w[memory usage foo])).to be_nil + end + end + + context 'when the key does exist' do + before { @redises.set('foo', 'a' * 100) } + + it 'returns the memory usage' do + expect(@redises.call(%w[memory usage foo])).to be_a(Integer) + end + end +end