dry-rb / dry-schema

Coercion and validation for data structures
https://dry-rb.org/gems/dry-schema
MIT License
424 stars 110 forks source link

Unexpected key validation with schema composition #444

Open masterT opened 2 years ago

masterT commented 2 years ago

Describe the bug

When using schema composition or in a schema along with config.validate_keys = true, the errors for the keys are set considering all the composed schemas.

To Reproduce

require 'dry-schema'

strategy_foo_schema = Dry::Schema.define do
  required(:type).filled(:string, eql?: 'foo')
  required(:options).hash do
    required(:foo).filled(:string)
  end
end

strategy_bar_schema = Dry::Schema.define do
  required(:type).filled(:string, eql?: 'bar')
  required(:options).hash do
    required(:bar).filled(:string)
  end
end

configuration_schema = Dry::Schema.define do
  config.validate_keys = true

  required(:strategy).schema(strategy_foo_schema | strategy_bar_schema)
end

input = {
  strategy: {
    type: 'foo',
    options: {
      foo: 'foo'
    }
  }
}

puts configuration_schema.call(input)&.errors&.to_h
# => {:strategy=>{:options=>{:foo=>["is not allowed"]}}}

Expected behavior

I would expect the key validation to only apply to the matching schema of the composed schema.

My environment

solnic commented 1 year ago

Is it still an issue with dry-schema 1.13.0?

masterT commented 1 year ago

Is it still an issue with dry-schema 1.13.0?

Yes, it it still.