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

Improve error messages for missing required keys #10

Merged
merged 2 commits into from
Oct 31, 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
2 changes: 2 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
require:
- standard
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
Loading