From 7c129f74cdf92aad311d0727d764b9a86b009b18 Mon Sep 17 00:00:00 2001 From: Ted Johansson Date: Thu, 17 Jun 2021 14:18:01 +0800 Subject: [PATCH] Fix key validator false negatives on empty collections --- lib/dry/schema/key_validator.rb | 7 ++++++- spec/integration/schema/unexpected_keys_spec.rb | 10 ++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/dry/schema/key_validator.rb b/lib/dry/schema/key_validator.rb index 3634f6e48..e7c64580a 100644 --- a/lib/dry/schema/key_validator.rb +++ b/lib/dry/schema/key_validator.rb @@ -51,9 +51,14 @@ def key_paths(hash) hash.flat_map { |key, _| case (value = hash[key]) when Hash + next key.to_s if value.empty? + [key].product(key_paths(hash[key])).map { |keys| keys.join(DOT) } when Array - hashes_or_arrays = value.select { |e| e.is_a?(Array) || e.is_a?(Hash) } + hashes_or_arrays = value.select { |e| (e.is_a?(Array) || e.is_a?(Hash)) && !e.empty? } + + next key.to_s if hashes_or_arrays.empty? + hashes_or_arrays.flat_map.with_index { |el, idx| key_paths(el).map { |path| ["#{key}[#{idx}]", *path].join(DOT) } } diff --git a/spec/integration/schema/unexpected_keys_spec.rb b/spec/integration/schema/unexpected_keys_spec.rb index 84eb2ed0d..e83dd4495 100644 --- a/spec/integration/schema/unexpected_keys_spec.rb +++ b/spec/integration/schema/unexpected_keys_spec.rb @@ -25,7 +25,10 @@ foo: "unexpected", name: "Jane", ids: [1, 2, 3, 4], - address: {bar: "unexpected", city: "NYC", zipcode: "1234"}, + qux: [], + quux: [{}], + hoge: {}, + address: {bar: "unexpected", baz: [1], city: "NYC", zipcode: "1234"}, roles: [ {name: "admin", expires_at: Date.today}, {name: "editor", foo: "unexpected", expires_at: Date.today} @@ -35,7 +38,10 @@ expect(schema.(input).errors.to_h) .to eql( foo: ["is not allowed"], - address: {bar: ["is not allowed"]}, + qux: ["is not allowed"], + quux: ["is not allowed"], + hoge: ["is not allowed"], + address: {bar: ["is not allowed"], baz: ["is not allowed"]}, roles: {1 => {foo: ["is not allowed"]}} ) end