2019-04-29 20:27:42 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-07-28 22:25:19 -04:00
|
|
|
describe DistributedMemoizer do
|
|
|
|
|
|
|
|
before do
|
2019-12-03 04:05:53 -05:00
|
|
|
Discourse.redis.del(DistributedMemoizer.redis_key("hello"))
|
|
|
|
Discourse.redis.del(DistributedMemoizer.redis_lock_key("hello"))
|
|
|
|
Discourse.redis.unwatch
|
2013-07-28 22:25:19 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# NOTE we could use a mock redis here, but I think it makes sense to test the real thing
|
|
|
|
# let(:mock_redis) { MockRedis.new }
|
|
|
|
|
|
|
|
def memoize(&block)
|
|
|
|
DistributedMemoizer.memoize("hello", duration = 120, &block)
|
|
|
|
end
|
|
|
|
|
|
|
|
it "returns the value of a block" do
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(memoize do
|
2013-07-28 22:25:19 -04:00
|
|
|
"abc"
|
2015-01-09 11:34:37 -05:00
|
|
|
end).to eq("abc")
|
2013-07-28 22:25:19 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
it "return the old value once memoized" do
|
|
|
|
|
|
|
|
memoize do
|
|
|
|
"abc"
|
|
|
|
end
|
|
|
|
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(memoize do
|
2013-07-28 22:25:19 -04:00
|
|
|
"world"
|
2015-01-09 11:34:37 -05:00
|
|
|
end).to eq("abc")
|
2013-07-28 22:25:19 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
it "memoizes correctly when used concurrently" do
|
|
|
|
results = []
|
|
|
|
threads = []
|
|
|
|
|
|
|
|
5.times do
|
|
|
|
threads << Thread.new do
|
|
|
|
results << memoize do
|
|
|
|
sleep 0.001
|
|
|
|
SecureRandom.hex
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
threads.each(&:join)
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(results.uniq.length).to eq(1)
|
|
|
|
expect(results.count).to eq(5)
|
2013-07-28 22:25:19 -04:00
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|