Skip to content

Commit

Permalink
Restore counter tests from main
Browse files Browse the repository at this point in the history
  • Loading branch information
lewispb committed Aug 13, 2023
1 parent ea5a2ad commit d06629f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
15 changes: 13 additions & 2 deletions lib/kredis/default_values.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# frozen_string_literal: true

module Kredis::DefaultValues
extend ActiveSupport::Concern

prepended do
attr_writer :default, :default_context
attr_writer :default

# proxying :watch, :unwatch, :exists?

def default
case @default
Expand All @@ -20,6 +24,13 @@ def set_default

def initialize(...)
super
set_default if default.present? && !exists?

if default
proxy.watch do
set_default unless proxy.exists?

proxy.unwatch
end
end
end
end
36 changes: 34 additions & 2 deletions test/types/counter_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require "test_helper"
require "active_support/core_ext/integer"

class CounterTest < ActiveSupport::TestCase
setup { @counter = Kredis.counter "mycounter" }
Expand Down Expand Up @@ -81,10 +82,41 @@ class CounterTest < ActiveSupport::TestCase
end

test "default value" do
@counter = Kredis.counter "mycounter", default: 5
@counter = Kredis.counter "mycounter", default: 10
assert_equal 10, @counter.value
end

test "expiring counter with default" do
@counter = Kredis.counter "mycounter", default: ->() { 10 }, expires_in: 1.second

@counter.increment
assert_equal 11, @counter.value

sleep 0.5.seconds

@counter.increment
assert_equal 12, @counter.value

sleep 0.5.seconds

# Defaults are only set on initialization
assert_equal 0, @counter.value
end

test "default via proc" do
@counter = Kredis.counter "mycounter", default: ->() { 10 }
assert_equal 10, @counter.value
@counter.decrement
assert_equal 9, @counter.value
end

test "concurrent initialization with default" do
5.times.map do
Thread.new do
Kredis.counter("mycounter", default: 5).increment
end
end.each(&:join)

assert_equal 6, @counter.value
assert_equal 10, Kredis.counter("mycounter").value
end
end

0 comments on commit d06629f

Please sign in to comment.