1 # frozen_string_literal: false
4 class TestWeakKeyMap < Test::Unit::TestCase
6 @wm = ObjectSpace::WeakKeyMap.new
13 assert_same(x, @wm[k])
14 assert_same(x, @wm["FOO".downcase])
19 assert_raise(ArgumentError) { @wm[true] = x }
20 assert_raise(ArgumentError) { @wm[false] = x }
21 assert_raise(ArgumentError) { @wm[nil] = x }
22 assert_raise(ArgumentError) { @wm[42] = x }
23 assert_raise(ArgumentError) { @wm[2**128] = x }
24 assert_raise(ArgumentError) { @wm[1.23] = x }
25 assert_raise(ArgumentError) { @wm[:foo] = x }
26 assert_raise(ArgumentError) { @wm["foo#{rand}".to_sym] = x }
32 assert_same(k, @wm.getkey("FOO".downcase))
36 assert_weak_include(:key?, "foo")
37 assert_not_send([@wm, :key?, "bar"])
44 assert_equal x1, @wm[k1]
45 assert_equal x1, @wm.delete(k1)
47 assert_nil @wm.delete(k1)
49 fallback = @wm.delete(k1) do |key|
53 assert_equal 42, fallback
60 assert_same @wm, @wm.clear
64 def test_clear_bug_20691
65 assert_normal_exit(<<~RUBY)
66 map = ObjectSpace::WeakKeyMap.new
82 assert_match(/\A\#<#{@wm.class.name}:[\dxa-f]+ size=\d+>\z/, @wm.inspect)
85 @wm[i.to_s] = Object.new
88 assert_match(/\A\#<#{@wm.class.name}:[\dxa-f]+ size=\d+>\z/, @wm.inspect)
91 def test_no_hash_method
93 assert_raise NoMethodError do
98 def test_frozen_object
100 assert_nothing_raised(FrozenError) {@wm[o] = 'foo'}
101 assert_nothing_raised(FrozenError) {@wm['foo'] = o}
104 def test_inconsistent_hash_key_memory_leak
105 assert_no_memory_leak [], '', <<~RUBY
117 wm = ObjectSpace::WeakKeyMap.new
126 omit "compaction is not supported on this platform" unless GC.respond_to?(:compact)
128 assert_separately(%w(-robjspace), <<-'end;')
129 wm = ObjectSpace::WeakKeyMap.new
134 GC.verify_compaction_references(expand_heap: true, toward: :empty)
136 assert_equal(val, wm[key])
140 def test_gc_compact_stress
141 omit "compaction doesn't work well on s390x" if RUBY_PLATFORM =~ /s390x/ # https://github.com/ruby/ruby/pull/5077
142 EnvUtil.under_gc_compact_stress { ObjectSpace::WeakKeyMap.new }
147 def assert_weak_include(m, k, n = 100)
149 return assert_weak_include(m, k, n-1)
154 assert_send([@wm, m, k])
155 assert_send([@wm, m, "FOO".downcase])