2017-01-26 18:14:00 +03:00
|
|
|
# frozen_string_literal: true
|
2012-03-13 07:37:06 +04:00
|
|
|
require 'test/unit'
|
|
|
|
require 'weakref'
|
|
|
|
|
|
|
|
class TestWeakRef < Test::Unit::TestCase
|
2012-03-14 06:29:48 +04:00
|
|
|
def make_weakref(level = 10)
|
2013-12-12 10:17:23 +04:00
|
|
|
if level > 0
|
|
|
|
make_weakref(level - 1)
|
|
|
|
else
|
|
|
|
WeakRef.new(Object.new)
|
|
|
|
end
|
2012-03-13 07:37:06 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
def test_ref
|
2013-12-12 10:17:23 +04:00
|
|
|
obj = Object.new
|
|
|
|
weak = WeakRef.new(obj)
|
|
|
|
assert_equal(obj.to_s, weak.to_s)
|
|
|
|
assert_predicate(weak, :weakref_alive?)
|
2012-03-13 07:37:06 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
def test_recycled
|
2014-01-10 13:42:31 +04:00
|
|
|
weaks = []
|
|
|
|
weak = nil
|
|
|
|
100.times do
|
|
|
|
weaks << make_weakref
|
|
|
|
ObjectSpace.garbage_collect
|
|
|
|
ObjectSpace.garbage_collect
|
|
|
|
break if weak = weaks.find {|w| !w.weakref_alive?}
|
|
|
|
end
|
2012-03-13 07:37:06 +04:00
|
|
|
assert_raise(WeakRef::RefError) {weak.to_s}
|
2013-10-19 03:50:13 +04:00
|
|
|
assert_not_predicate(weak, :weakref_alive?)
|
2012-03-13 07:37:06 +04:00
|
|
|
end
|
2012-11-24 16:26:54 +04:00
|
|
|
|
|
|
|
def test_not_reference_different_object
|
|
|
|
bug7304 = '[ruby-core:49044]'
|
|
|
|
weakrefs = []
|
|
|
|
3.times do
|
|
|
|
obj = Object.new
|
|
|
|
def obj.foo; end
|
|
|
|
weakrefs << WeakRef.new(obj)
|
|
|
|
ObjectSpace.garbage_collect
|
|
|
|
end
|
|
|
|
assert_nothing_raised(NoMethodError, bug7304) {
|
|
|
|
weakrefs.each do |weak|
|
|
|
|
begin
|
|
|
|
weak.foo
|
|
|
|
rescue WeakRef::RefError
|
|
|
|
end
|
|
|
|
end
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
def test_weakref_finalize
|
|
|
|
bug7304 = '[ruby-core:49044]'
|
|
|
|
assert_normal_exit %q{
|
|
|
|
require 'weakref'
|
|
|
|
obj = Object.new
|
|
|
|
3.times do
|
|
|
|
WeakRef.new(obj)
|
|
|
|
ObjectSpace.garbage_collect
|
|
|
|
end
|
|
|
|
}, bug7304
|
|
|
|
end
|
2014-12-13 04:28:18 +03:00
|
|
|
|
2015-09-03 08:22:41 +03:00
|
|
|
def test_repeated_object_memory_leak
|
2014-12-13 04:28:18 +03:00
|
|
|
bug10537 = '[ruby-core:66428]'
|
2014-12-19 23:20:33 +03:00
|
|
|
assert_no_memory_leak(%w(-rweakref), '', <<-'end;', bug10537, timeout: 60)
|
2014-12-13 04:28:18 +03:00
|
|
|
a = Object.new
|
|
|
|
150_000.times { WeakRef.new(a) }
|
|
|
|
end;
|
|
|
|
end
|
2012-03-13 07:37:06 +04:00
|
|
|
end
|