Skip to content

Commit

Permalink
Add test for a race-condition
Browse files Browse the repository at this point in the history
  • Loading branch information
exAspArk committed Nov 6, 2017
1 parent 3105f95 commit fed3c12
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/batch_loader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ def self.for(item)
new(item: item)
end

def initialize(item:)
def initialize(item:, executor_proxy: nil)
@item = item
@__executor_proxy = executor_proxy
end

def batch(default_value: nil, cache: true, &batch_block)
Expand Down Expand Up @@ -76,7 +77,7 @@ def __ensure_batched
return if __executor_proxy.value_loaded?(item: @item)

items = __executor_proxy.list_items
loader = -> (item, value = (no_value = true; nil), &block) {
loader = -> (item, value = (no_value = true; nil), &block) do
if no_value && !block
raise ArgumentError, "Please pass a value or a block"
elsif block && !no_value
Expand All @@ -85,7 +86,7 @@ def __ensure_batched

next_value = block ? block.call(__executor_proxy.loaded_value(item: item)) : value
__executor_proxy.load(item: item, value: next_value)
}
end

@batch_block.call(items, loader)
items.each do |item|
Expand Down
14 changes: 14 additions & 0 deletions spec/batch_loader_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,20 @@
expect(lazy).to eq(2)
end

it 'is thread-safe' do
batch_block = Proc.new do |ids, loader|
ids.each do |id|
thread = Thread.new { loader.call(id) { |value| value << id } }
loader.call(id) { |value| value << id + 1 }
thread.join
end
end
slow_executor_proxy = SlowExecutorProxy.new([], &batch_block)
lazy = BatchLoader.new(item: 1, executor_proxy: slow_executor_proxy).batch(default_value: [], &batch_block)

expect(lazy).to eq([1, 2])
end

it 'supports alternative default values' do
lazy = BatchLoader.for(1).batch(default_value: 123) do |nums, loader|
# No-op, so default is returned
Expand Down
8 changes: 8 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@
require_relative "./fixtures/models"
require_relative "./fixtures/graphql_schema"

class SlowExecutorProxy < BatchLoader::ExecutorProxy
def value_loaded?(item:)
result = loaded.key?(item)
sleep 0.5
result
end
end

RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
Expand Down

0 comments on commit fed3c12

Please sign in to comment.