Skip to content

Commit

Permalink
Add support for Redis' logger option (#211)
Browse files Browse the repository at this point in the history
  • Loading branch information
jdelStrother committed May 13, 2021
1 parent 62ad386 commit 0dc409c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
33 changes: 32 additions & 1 deletion lib/mock_redis.rb
Expand Up @@ -22,6 +22,7 @@ class MockRedis
:path => nil,
:timeout => 5.0,
:password => nil,
:logger => nil,
:db => 0,
:time_class => Time,
}.freeze
Expand Down Expand Up @@ -65,6 +66,10 @@ def db
options[:db]
end

def logger
options[:logger]
end

def time_at(timestamp)
options[:time_class].at(timestamp)
end
Expand All @@ -86,7 +91,9 @@ def respond_to?(method, include_private = false)
end

ruby2_keywords def method_missing(method, *args, &block)
@db.send(method, *args, &block)
logging([[method, *args]]) do
@db.send(method, *args, &block)
end
end

def initialize_copy(source)
Expand Down Expand Up @@ -139,4 +146,28 @@ def _parse_options(options)

options
end

def logging(commands)
return yield unless logger&.debug?

begin
commands.each do |name, *args|
logged_args = args.map do |a|
if a.respond_to?(:inspect) then a.inspect
elsif a.respond_to?(:to_s) then a.to_s
else
# handle poorly-behaved descendants of BasicObject
klass = a.instance_exec { (class << self; self end).superclass }
"\#<#{klass}:#{a.__id__}>"
end
end
logger.debug("[MockRedis] command=#{name.to_s.upcase} args=#{logged_args.join(' ')}")
end

t1 = Time.now
yield
ensure
logger.debug("[MockRedis] call_time=%0.2f ms" % ((Time.now - t1) * 1000)) if t1
end
end
end
9 changes: 9 additions & 0 deletions spec/mock_redis_spec.rb
Expand Up @@ -81,4 +81,13 @@
end
end
end

describe 'supplying a logger' do
it 'logs redis commands' do
logger = double('Logger', debug?: true, debug: nil)
mock_redis = MockRedis.new(logger: logger)
expect(logger).to receive(:debug).with(/command=HMGET args="hash" "key1" "key2"/)
mock_redis.hmget("hash", "key1", "key2")
end
end
end

0 comments on commit 0dc409c

Please sign in to comment.