|
| 1 | +require 'spec_helper' |
| 2 | + |
| 3 | +describe Ref::SoftReference do |
| 4 | + describe '#object' do |
| 5 | + context 'when has not garbage collected objects' do |
| 6 | + it 'gets the object' do |
| 7 | + obj = Object.new |
| 8 | + ref = Ref::SoftReference.new(obj) |
| 9 | + |
| 10 | + expect(obj).to eq ref.object |
| 11 | + expect(obj.object_id).to eq ref.referenced_object_id |
| 12 | + end |
| 13 | + end |
| 14 | + |
| 15 | + context 'when has a lot of objects' do |
| 16 | + # Since we can't reliably control the garbage collector, this is a brute force test. |
| 17 | + # It might not always fail if the garbage collector and memory allocator don't |
| 18 | + # cooperate, but it should fail often enough on continuous integration to |
| 19 | + # hilite any problems. Set the environment variable QUICK_TEST to "true" if you |
| 20 | + # want to make the tests run quickly. |
| 21 | + it 'get the correct object' do |
| 22 | + id_to_ref = {} |
| 23 | + (ENV["QUICK_TEST"] == "true" ? 1000 : 100000).times do |i| |
| 24 | + obj = Object.new |
| 25 | + if id_to_ref.key?(obj.object_id) |
| 26 | + ref = id_to_ref[obj.object_id] |
| 27 | + if ref.object |
| 28 | + fail "soft reference found with a live reference to an object that was not the one it was created with" |
| 29 | + break |
| 30 | + end |
| 31 | + end |
| 32 | + |
| 33 | + %w(Here are a bunch of objects that are allocated and can then be cleaned up by the garbage collector) |
| 34 | + id_to_ref[obj.object_id] = Ref::SoftReference.new(obj) |
| 35 | + if i % 1000 == 0 |
| 36 | + GC.start |
| 37 | + sleep(0.01) |
| 38 | + end |
| 39 | + end |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + context 'when references are not collected immediately' do |
| 44 | + it "the object can't be nil" do |
| 45 | + ref = Ref::SoftReference.new(Object.new) |
| 46 | + 9.times{ arr = %w(allocate some memory on the heap); arr *= 100; GC.start } |
| 47 | + expect(ref.object).to_not be_nil |
| 48 | + end |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + describe '#inspect' do |
| 53 | + context 'when GC is called' do |
| 54 | + it 'inspects not be nil' do |
| 55 | + ref = Ref::SoftReference.new(Object.new) |
| 56 | + expect(ref.inspect).to_not be_nil |
| 57 | + GC.start |
| 58 | + GC.start |
| 59 | + expect(ref.inspect).to_not be_nil |
| 60 | + end |
| 61 | + end |
| 62 | + end |
| 63 | +end |
0 commit comments