1 # frozen_string_literal: true
2 require_relative 'helper'
5 class TestHash < TestCase
9 class HashWithIvar < Hash
21 class HashWithCustomInit < Hash
28 class HashWithCustomInitNoIvar < Hash
39 def test_hash_with_ivar
42 t2 = Psych.unsafe_load(Psych.dump(t1))
47 def test_referenced_hash_with_ivar
49 t1 = [HashWithCustomInit.new(a)]
54 def test_custom_initialized
56 t1 = HashWithCustomInit.new(a)
57 t2 = Psych.unsafe_load(Psych.dump(t1))
62 def test_custom_initialize_no_ivar
63 t1 = HashWithCustomInitNoIvar.new(nil)
64 t2 = Psych.unsafe_load(Psych.dump(t1))
69 def test_hash_subclass_with_ivars
72 x.instance_variable_set :@foo, 'bar'
73 dup = Psych.unsafe_load Psych.dump x
75 assert_equal 'bar', dup.instance_variable_get(:@foo)
76 assert_equal X, dup.class
79 def test_load_with_class_syck_compatibility
80 hash = Psych.unsafe_load "--- !ruby/object:Hash\n:user_id: 7\n:username: Lucas\n"
81 assert_equal({ user_id: 7, username: 'Lucas'}, hash)
84 def test_empty_subclass
85 assert_match "!ruby/hash:#{X}", Psych.dump(X.new)
86 x = Psych.unsafe_load Psych.dump X.new
87 assert_equal X, x.class
91 x = Psych.unsafe_load "--- !map:#{X} { }\n"
92 assert_equal X, x.class
95 def test_self_referential
105 hash = Psych.unsafe_load(<<~eoyml)
112 assert_equal({"foo"=>{"hello"=>"world"}, "bar"=>{"hello"=>"world"}}, hash)
115 def test_anchor_reuse
116 hash = Psych.unsafe_load(<<~eoyml)
122 assert_equal({"foo"=>{"hello"=>"world"}, "bar"=>{"hello"=>"world"}}, hash)
123 assert_same(hash.fetch("foo"), hash.fetch("bar"))
126 def test_raises_if_anchor_not_defined
127 assert_raise(Psych::AnchorNotDefined) do
128 Psych.unsafe_load(<<~eoyml)
137 def test_recursive_hash
139 h["recursive_reference"] = h
141 loaded = Psych.load(Psych.dump(h), aliases: true)
143 assert_same loaded, loaded.fetch("recursive_reference")
146 def test_recursive_hash_uses_alias
148 h["recursive_reference"] = h
150 assert_raise(AliasesNotEnabled) do
151 Psych.load(Psych.dump(h), aliases: false)
155 def test_key_deduplication
156 unless String.method_defined?(:-@) && (-("a" * 20)).equal?((-("a" * 20)))
157 pend "This Ruby implementation doesn't support string deduplication"
160 hashes = Psych.load(<<~eoyml)
162 - unique_identifier: 1
163 - unique_identifier: 2
166 assert_same hashes[0].keys.first, hashes[1].keys.first