Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise exception on duplicate keys #426

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/psych/handlers/document_stream.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ def end_document implicit_end = !streaming?
@last.implicit_end = implicit_end
@block.call pop
end

def end_mapping
mapping = pop
keys = {}
mapping.children.each_slice(2) do |(key_scalar, _)|
next if key_scalar.is_a?(Psych::Nodes::Sequence) or key_scalar.is_a?(Psych::Nodes::Alias) or key_scalar.is_a?(Psych::Nodes::Mapping)
key = key_scalar.value
raise Psych::Exception, "Duplicate key #{key} exists on this level" if keys.key? key
keys[key] = nil
end
mapping
end
end
end
end
10 changes: 10 additions & 0 deletions test/psych/test_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,16 @@ def test_map
assert_equal X, x.class
end

def test_error_on_same_key
assert_raises(Psych::Exception) do
Psych.load <<-EOF
-
same_key: 'value'
same_key: 'value'
EOF
end
end

def test_self_referential
@hash['self'] = @hash
assert_cycle(@hash)
Expand Down