New validation method on the root that returns errors

This commit is contained in:
Mitchell Hashimoto 2013-01-18 12:14:40 -08:00
parent 0bd0752bf2
commit e6f9586d83
2 changed files with 65 additions and 16 deletions

View File

@ -39,24 +39,30 @@ module Vagrant
end end
end end
# Validates the configuration classes of this instance and raises an # This validates the configuration and returns a hash of error
# exception if they are invalid. If you are implementing a custom configuration # messages by section. If there are no errors, an empty hash
# class, the method you want to implement is {Base#validate}. This is # is returned.
# the method that checks all the validation, not one which defines #
# validation rules. # @param [Environment] env
def validate!(env) # @return [Hash]
# Validate each of the configured classes and store the results into def validate(env)
# a hash. # Go through each of the configuration keys and validate
errors = @keys.inject({}) do |container, data| errors = {}
key, instance = data @keys.each do |_key, instance|
recorder = ErrorRecorder.new if instance.respond_to?(:validate)
instance.validate(env, recorder) # Validate this single item, and if we have errors then
container[key.to_sym] = recorder if !recorder.errors.empty? # we merge them into our total errors list.
container result = instance.validate(env)
if result && !result.empty?
result.each do |key, value|
errors[key] ||= []
errors[key] += value
end
end
end
end end
return if errors.empty? errors
raise Errors::ConfigValidationFailed, :messages => Util::TemplateRenderer.render("config/validation_failed", :errors => errors)
end end
# Returns the internal state of the root object. This is used # Returns the internal state of the root object. This is used

View File

@ -31,4 +31,47 @@ describe Vagrant::Config::V2::Root do
"keys" => {} "keys" => {}
} }
end end
describe "validation" do
let(:instance) do
map = { :foo => Object, :bar => Object }
described_class.new(map)
end
it "should return nil if valid" do
instance.validate({}).should == {}
end
it "should return errors if invalid" do
errors = { "foo" => ["errors!"] }
env = { "errors" => errors }
foo = instance.foo
def foo.validate(env)
env["errors"]
end
instance.validate(env).should == errors
end
it "should merge errors via array concat if matching keys" do
errors = { "foo" => ["errors!"] }
env = { "errors" => errors }
foo = instance.foo
bar = instance.bar
def foo.validate(env)
env["errors"]
end
def bar.validate(env)
env["errors"].merge({ "bar" => ["bar"] })
end
expected_errors = {
"foo" => ["errors!", "errors!"],
"bar" => ["bar"]
}
instance.validate(env).should == expected_errors
end
end
end end