summaryrefslogtreecommitdiff
path: root/jni/ruby/test/test_weakref.rb
blob: d21b431abb54f3e06b1690b3877681ab9f0c2b62 (plain)
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
require 'test/unit'
require 'weakref'

class TestWeakRef < Test::Unit::TestCase
  def make_weakref(level = 10)
    if level > 0
      make_weakref(level - 1)
    else
      WeakRef.new(Object.new)
    end
  end

  def test_ref
    obj = Object.new
    weak = WeakRef.new(obj)
    assert_equal(obj.to_s, weak.to_s)
    assert_predicate(weak, :weakref_alive?)
  end

  def test_recycled
    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
    assert_raise(WeakRef::RefError) {weak.to_s}
    assert_not_predicate(weak, :weakref_alive?)
  end

  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

  def test_repeated_object_leak
    bug10537 = '[ruby-core:66428]'
    assert_no_memory_leak(%w(-rweakref), '', <<-'end;', bug10537, timeout: 60)
      a = Object.new
      150_000.times { WeakRef.new(a) }
    end;
  end
end