Skip to content

Commit

Permalink
More specific messages for required keys
Browse files Browse the repository at this point in the history
  • Loading branch information
alexkalderimis authored and skryukov committed Oct 31, 2024
1 parent 9397261 commit 137058e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
15 changes: 13 additions & 2 deletions lib/json_skooma/keywords/validation/required.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,20 @@ class Required < Base
self.instance_types = "object"

def evaluate(instance, result)
return if json.value.all? { |val| instance.key?(val) }
missing = required_keys.reject { |key| instance.key?(key) }
return if missing.none?

result.failure("The object is missing required properties #{json.value.join(", ")}")
result.failure(missing_keys_message(missing))
end

private

def required_keys
json.value
end

def missing_keys_message(missing)
"The object requires the following keys: #{required_keys.join(", ")}. Missing keys: #{missing.join(", ")}"
end
end
end
Expand Down
23 changes: 23 additions & 0 deletions spec/json_skooma/json_schema_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@

it { is_expected.to be_valid }

context "with required keys" do
before do
schema_data["required"] = %w[foo bar]
schema_data["properties"]["bar"] = {"type" => "integer"}
end

it { is_expected.not_to be_valid }

it "informs us which key is missing" do
errors = subject.output(:detailed)["errors"].map { |e| e["error"] }

expect(errors).to contain_exactly(
"The object requires the following keys: foo, bar. Missing keys: bar"
)
end

context "with valid instance" do
let(:instance) { {foo: "baz", bar: 123} }

it { is_expected.to be_valid }
end
end

context "with ref option" do
let(:ref) { "#/$defs/FooBaz" }

Expand Down

0 comments on commit 137058e

Please sign in to comment.