2019-04-30 08:27:42 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-07-29 10:25:19 +08:00
|
|
|
describe DistributedMemoizer do
|
2022-04-06 01:29:58 +08:00
|
|
|
after do
|
2019-12-03 17:05:53 +08:00
|
|
|
Discourse.redis.del(DistributedMemoizer.redis_key("hello"))
|
|
|
|
Discourse.redis.del(DistributedMemoizer.redis_lock_key("hello"))
|
2013-07-29 10:25:19 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def memoize(&block)
|
|
|
|
DistributedMemoizer.memoize("hello", duration = 120, &block)
|
|
|
|
end
|
|
|
|
|
|
|
|
it "returns the value of a block" do
|
2022-04-06 01:29:58 +08:00
|
|
|
expect(memoize { "abc" }).to eq("abc")
|
2013-07-29 10:25:19 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
it "return the old value once memoized" do
|
|
|
|
memoize do
|
|
|
|
"abc"
|
|
|
|
end
|
|
|
|
|
2022-04-06 01:29:58 +08:00
|
|
|
expect(memoize { "world" }).to eq("abc")
|
2013-07-29 10:25:19 +08: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-10 00:34:37 +08:00
|
|
|
expect(results.uniq.length).to eq(1)
|
|
|
|
expect(results.count).to eq(5)
|
2013-07-29 10:25:19 +08:00
|
|
|
end
|
|
|
|
end
|