test_weakref.rb

Unit tests for WeakRef - Brian Durand, 12/18/2010 01:57 AM

Download (2.39 KB)

 
1
require 'test/unit'
2
require 'weakref'
3

    
4
class TestWeakRef < Test::Unit::TestCase
5
  def test_can_get_non_garbage_collected_objects
6
    obj = Object.new
7
    ref = WeakRef.new(obj)
8
    assert_equal obj, ref.__getobj__
9
    assert_equal true, ref.weakref_alive?
10
  end
11

    
12
  def test_get_the_correct_object
13
    # Since we can't reliably control the garbage collector, this is a brute force test.
14
    # It might not always fail if the garbage collector and memory allocator don't
15
    # cooperate, but it should fail often enough on continuous integration to
16
    # hilite any problems.
17
    id_to_ref = {}
18
    50000.times do |i|
19
      obj = Object.new
20
      if id_to_ref.key?(obj.object_id)
21
        ref = id_to_ref[obj.object_id]
22
        refobj = ref.__getobj__ rescue nil
23
        if refobj
24
          flunk "weak reference found with a live reference to an object that was not the one it was created with"
25
          break
26
        end
27
      end
28
      %w(Here are a bunch of objects that are allocated and can then be cleaned up by the garbage collector)
29
      id_to_ref[obj.object_id] = WeakRef.new(obj)
30
      if i % 1000 == 0
31
        GC.start
32
        sleep(0.01)
33
      end
34
    end
35
  end
36
end
37

    
38
class TestWeakReference < Test::Unit::TestCase
39
  def test_can_get_non_garbage_collected_objects
40
    obj = Object.new
41
    ref = WeakReference.new(obj)
42
    assert_equal obj, ref.object
43
    assert_equal obj.object_id, ref.referenced_object_id
44
  end
45

    
46
  def test_get_the_correct_object
47
    # Since we can't reliably control the garbage collector, this is a brute force test.
48
    # It might not always fail if the garbage collector and memory allocator don't
49
    # cooperate, but it should fail often enough on continuous integration to
50
    # hilite any problems.
51
    id_to_ref = {}
52
    50000.times do |i|
53
      obj = Object.new
54
      if id_to_ref.key?(obj.object_id)
55
        ref = id_to_ref[obj.object_id]
56
        if ref.object
57
          flunk "weak reference found with a live reference to an object that was not the one it was created with"
58
          break
59
        end
60
      end
61
      %w(Here are a bunch of objects that are allocated and can then be cleaned up by the garbage collector)
62
      id_to_ref[obj.object_id] = WeakReference.new(obj)
63
      if i % 1000 == 0
64
        GC.start
65
        sleep(0.01)
66
      end
67
    end
68
  end
69

    
70
  def test_inspect
71
    ref = WeakReference.new(Object.new)
72
    assert ref.inspect
73
    GC.start
74
    GC.start
75
    assert ref.inspect
76
  end
77
end