forked from ruby-concurrency/concurrent-ruby
/
set_spec.rb
87 lines (73 loc) · 2.47 KB
/
set_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
require 'set'
module Concurrent
RSpec.describe Set do
let!(:set) { described_class.new }
describe '.[]' do
describe 'when initializing with no arguments' do
it do
expect(described_class[]).to be_empty
end
end
describe 'when initializing with arguments' do
it 'creates a set with the given objects' do
expect(described_class[:hello, :world]).to eq ::Set.new([:hello, :world])
end
end
end
describe '.new' do
describe 'when initializing with no arguments' do
it do
expect(described_class.new).to be_empty
end
end
describe 'when initializing with an enumerable object' do
let(:enumerable_object) { [:hello, :world] }
it 'creates a set with the contents of the enumerable object' do
expect(described_class.new(enumerable_object)).to eq ::Set.new([:hello, :world])
end
describe 'when initializing with a block argument' do
let(:block_argument) { proc { |value| :"#{value}_ruby" } }
it 'creates a set with the contents of the enumerable object' do
expect(described_class.new(enumerable_object, &block_argument)).to eq ::Set.new([:hello_ruby, :world_ruby])
end
end
end
end
context 'concurrency' do
it 'simple' do
(1..Concurrent::ThreadSafe::Test::THREADS).map do |i|
in_thread do
1000.times do
v = i
set << v
expect(set).not_to be_empty
set.delete(v)
end
end
end.map(&:join)
expect(set).to be_empty
end
it 'force context switch' do
barrier = Concurrent::CyclicBarrier.new(2)
# methods like include? or delete? are implemented for CRuby in Ruby itself
# @see https://github.com/ruby/ruby/blob/master/lib/set.rb
set.clear
# add a single element
set.add(1)
# This thread should start and `Set#reject!` in CRuby should cache a value of `0` for size
thread_reject = in_thread do
# we expect this to return nil since nothing should have changed.
expect(set.reject! do |v|
barrier.wait
v == 1 # only delete the 1 value
end).to eq set
end
thread_add = in_thread do
barrier.wait
expect(set.add?(1)).to eq set
end
join_with [thread_reject, thread_add]
end
end
end
end