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

Use error collection for validation, require manual calls to validate #72

Merged
merged 3 commits into from
Sep 11, 2024
Merged
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
37 changes: 22 additions & 15 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2024-09-08 11:19:50 UTC using RuboCop version 1.66.1.
# on 2024-09-10 23:53:08 UTC using RuboCop version 1.66.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: Severity, Include.
# Include: **/*.gemspec
Gemspec/RequireMFA:
Exclude:
- 'lutaml-model.gemspec'

# Offense count: 66
# Offense count: 88
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: Max, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns.
# URISchemes: http, https
Layout/LineLength:
Enabled: false

# Offense count: 10
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: AllowInHeredoc.
Layout/TrailingWhitespace:
Exclude:
- 'lib/lutaml/model/schema_location.rb'

# Offense count: 11
# Configuration parameters: AllowedMethods.
# AllowedMethods: enums
Lint/ConstantDefinitionInBlock:
Expand All @@ -30,6 +29,7 @@ Lint/ConstantDefinitionInBlock:
- 'spec/lutaml/model/schema/relaxng_schema_spec.rb'
- 'spec/lutaml/model/schema/xsd_schema_spec.rb'
- 'spec/lutaml/model/schema/yaml_schema_spec.rb'
- 'spec/lutaml/model/validation_spec.rb'
- 'spec/lutaml/model/xml_adapter/xml_namespace_spec.rb'

# Offense count: 1
Expand Down Expand Up @@ -100,7 +100,7 @@ RSpec/ContextWording:
- 'spec/lutaml/model/xml_adapter/ox_adapter_spec.rb'
- 'spec/lutaml/model/xml_adapter/xml_namespace_spec.rb'

# Offense count: 89
# Offense count: 101
# Configuration parameters: CountAsOne.
RSpec/ExampleLength:
Max: 57
Expand All @@ -111,13 +111,14 @@ RSpec/IndexedLet:
Exclude:
- 'spec/address_spec.rb'

# Offense count: 18
# Offense count: 19
RSpec/LeakyConstantDeclaration:
Exclude:
- 'spec/lutaml/model/schema/json_schema_spec.rb'
- 'spec/lutaml/model/schema/relaxng_schema_spec.rb'
- 'spec/lutaml/model/schema/xsd_schema_spec.rb'
- 'spec/lutaml/model/schema/yaml_schema_spec.rb'
- 'spec/lutaml/model/validation_spec.rb'
- 'spec/lutaml/model/xml_adapter/xml_namespace_spec.rb'

# Offense count: 4
Expand All @@ -128,7 +129,7 @@ RSpec/MultipleDescribes:
- 'spec/lutaml/model/xml_adapter/xml_namespace_spec.rb'
- 'spec/lutaml/model/xml_adapter_spec.rb'

# Offense count: 75
# Offense count: 88
RSpec/MultipleExpectations:
Max: 11

Expand All @@ -137,10 +138,11 @@ RSpec/MultipleExpectations:
RSpec/MultipleMemoizedHelpers:
Max: 9

# Offense count: 4
# Offense count: 7
RSpec/PendingWithoutReason:
Exclude:
- 'spec/lutaml/model/mixed_content_spec.rb'
- 'spec/lutaml/model/validation_spec.rb'
- 'spec/lutaml/model/xml_adapter/oga_adapter_spec.rb'
- 'spec/lutaml/model/xml_adapter/xml_namespace_spec.rb'
- 'spec/lutaml/model/xml_adapter_spec.rb'
Expand All @@ -163,6 +165,11 @@ Security/CompoundHash:
Exclude:
- 'lib/lutaml/model/comparable_model.rb'

# Offense count: 1
Style/MissingRespondToMissing:
Exclude:
- 'lib/lutaml/model/serialize.rb'

# Offense count: 1
# Configuration parameters: AllowedMethods.
# AllowedMethods: respond_to_missing?
Expand Down
95 changes: 95 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1709,6 +1709,101 @@ In this example:
====


== Validation

=== General

Lutaml::Model provides a way to validate data models using the `validate` and
`validate!` methods.

* The `validate` method sets an `errors` array in the model instance that
contains all the validation errors. This method is used for checking the
validity of the model silently.

* The `validate!` method raises a `Lutaml::Model::ValidationError` that contains
all the validation errors. This method is used for forceful validation of the
model through raising an error.

Lutaml::Model supports the following validation methods:

* `collection`:: Validates collection size range.
* `values`:: Validates the value of an attribute from a set of fixed values.

[example]
====
The following class will validate the `degree_settings` attribute to ensure that
it has at least one element and that the `description` attribute is one of the
values in the set `[one, two, three]`.

[source,ruby]
----
class Klin < Lutaml::Model::Serializable
attribute :name, :string
attribute :degree_settings, :integer, collection: (1..)
attribute :description, :string, values: %w[one two three]

xml do
map_element 'name', to: :name
map_attribute 'degree_settings', to: :degree_settings
end
end

klin = Klin.new(name: "Klin", degree_settings: [100, 200, 300], description: "one")
klin.validate
# => []

klin = Klin.new(name: "Klin", degree_settings: [], description: "four")
klin.validate
# => [
# #<Lutaml::Model::CollectionSizeError: degree_settings must have at least 1 element>,
# #<Lutaml::Model::ValueError: description must be one of [one, two, three]>
# ]

e = klin.validate!
# => Lutaml::Model::ValidationError: [
# degree_settings must have at least 1 element,
# description must be one of [one, two, three]
# ]
e.errors
# => [
# #<Lutaml::Model::CollectionSizeError: degree_settings must have at least 1 element>,
# #<Lutaml::Model::ValueError: description must be one of [one, two, three]>
# ]
----
====

=== Custom validation

To add custom validation, override the `validate` method in the model class.
Additional errors should be added to the `errors` array.

[example]
====
The following class validates the `degree_settings` attribute when the `type` is
`glass` to ensure that the value is less than 1300.

[source,ruby]
----
class Klin < Lutaml::Model::Serializable
attribute :name, :string
attribute :type, :string, values: %w[glass ceramic]
attribute :degree_settings, :integer, collection: (1..)

def validate
errors = super
if type == "glass" && degree_settings.any? { |d| d > 1300 }
errors << Lutaml::Model::Error.new("Degree settings for glass must be less than 1300")
end
end
end

klin = Klin.new(name: "Klin", type: "glass", degree_settings: [100, 200, 1400])
klin.validate
# => [#<Lutaml::Model::Error: Degree settings for glass must be less than 1300>]
----
====


== Adapters

=== General
Expand Down
58 changes: 24 additions & 34 deletions lib/lutaml/model/attribute.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,35 +60,25 @@ def enum_values
# e.g if collection: 0..5 is set then the value greater then 5
# will raise `Lutaml::Model::CollectionCountOutOfRangeError`
def validate_value!(value)
# return true if none of the validations are present
return true if enum_values.empty? && singular?

# Use the default value if the value is nil
value = default if value.nil?

valid_value!(value) && valid_collection!(value)
end

def valid_value?(value)
return true unless options[:values]

options[:values].include?(value)
valid_value!(value)
valid_collection!(value)
end

def valid_value!(value)
return true if value.nil? && !collection?
return true if enum_values.empty?

unless valid_value?(value)
raise Lutaml::Model::InvalidValueError.new(name, value, enum_values)
end

true
end

def valid_collection?(value)
return true unless collection?
return false unless value.is_a?(Array)
return collection? if [true, false].include?(options[:collection])
def valid_value?(value)
return true unless options[:values]

options[:collection].include?(value.count)
options[:values].include?(value)
end

def validate_value!(value)
Expand Down Expand Up @@ -127,7 +117,12 @@ def validate_collection_range

def valid_collection!(value)
return true unless collection?
return true if value.nil? # Allow nil values for collections during initialization

# Allow nil values for collections during initialization
return true if value.nil?

# Allow any value for unbounded collections
return true if options[:collection] == true

unless value.is_a?(Array)
raise Lutaml::Model::CollectionCountOutOfRangeError.new(
Expand All @@ -138,28 +133,23 @@ def valid_collection!(value)
end

range = options[:collection]
if range.is_a?(Range)
if range.end.nil?
if value.size < range.begin
raise Lutaml::Model::CollectionCountOutOfRangeError.new(
name,
value,
range,
)
end
elsif !range.cover?(value.size)
return true unless range.is_a?(Range)

if range.end.nil?
if value.size < range.begin
raise Lutaml::Model::CollectionCountOutOfRangeError.new(
name,
value,
range,
)
end
elsif range == true && value.empty?
# Allow empty arrays for unbounded collections
return true
elsif !range.cover?(value.size)
raise Lutaml::Model::CollectionCountOutOfRangeError.new(
name,
value,
range,
)
end

true
end

def serialize(value, format, options = {})
Expand Down
1 change: 1 addition & 0 deletions lib/lutaml/model/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ class Error < StandardError
require_relative "error/invalid_value_error"
require_relative "error/unknown_adapter_type_error"
require_relative "error/collection_count_out_of_range_error"
require_relative "error/validation_error"
21 changes: 21 additions & 0 deletions lib/lutaml/model/error/validation_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# lib/lutaml/model/error/validation_error.rb
module Lutaml
module Model
class ValidationError < Error
attr_reader :errors

def initialize(errors)
@errors = errors
super(errors.join(", "))
end

def include?(error_class)
errors.any?(error_class)
end

def error_messages
errors.map(&:message)
end
end
end
end
3 changes: 2 additions & 1 deletion lib/lutaml/model/schema_location.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ class SchemaLocation

attr_reader :namespace, :prefix, :schema_location

def initialize(schema_location:, prefix: "xsi", namespace: DEFAULT_NAMESPACE)
def initialize(schema_location:, prefix: "xsi",
namespace: DEFAULT_NAMESPACE)
@original_schema_location = schema_location
@schema_location = parsed_schema_locations(schema_location)
@prefix = prefix
Expand Down
Loading
Loading