Skip to content

Commit

Permalink
Expand references of DocuemntStore schemas
Browse files Browse the repository at this point in the history
This is a fix for thoughtbot#92.

Calls `expand_references!` on loaded schemas before adding them to the
`DocumentStore`.  This is intended to fix a bug where complex schemas
that include more than one level of cross-file use of `$ref`s are not
being validated correctly.

This commit includes new test cases that reproduce this issue and show
the effectiveness of the proposed fix.

The inspiration for this fix comes from a command included in the
`json_schema` gem.  In that gem, the stand-alone validator command
expands references within schemas before adding them to the store.
It seems reasonable to do the same here.

See https://github.com/brandur/json_schema/blob/20ccb82d7e18140d88ded508edd6c003865c98a0/lib/commands/validate_schema.rb#L92.
  • Loading branch information
richardlarocque committed Jan 30, 2019
1 parent 4ee7fac commit bfe92e4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/json_matchers/matcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ def build_and_populate_document_store
map { |schema_path| Parser.new(schema_path).parse }.
each { |schema| document_store.add_schema(schema) }

document_store.to_a.each do |_k, schema|
schema.expand_references!(store: document_store)
end

document_store
end
end
Expand Down
1 change: 1 addition & 0 deletions spec/factories.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@

initialize_with do
FakeSchema.new(name, {
"id": "file:/#{name}.json#",
"$schema": "https://json-schema.org/draft-04/schema#",
"type": "array",
"items": { "$ref": "file:/#{items.name}.json#" },
Expand Down
18 changes: 18 additions & 0 deletions spec/json_matchers/match_json_schema_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,24 @@
expect(json_as_array).not_to match_json_schema(schema)
end

it "validates against a schema that uses nested $refs" do
schema = create(:schema, :referencing_locations,
items: create(:schema, :referencing_locations))
json = build(:response, :location)
json_as_array = [[json.to_h]]

expect(json_as_array).to match_json_schema(schema)
end

it "fails against a schema that uses nested $refs" do
schema = create(:schema, :referencing_locations,
items: create(:schema, :referencing_locations))
json = build(:response, :invalid_location)
json_as_array = [[json.to_h]]

expect(json_as_array).not_to match_json_schema(schema)
end

it "validates against a schema referencing with 'definitions'" do
schema = create(:schema, :referencing_definitions)

Expand Down

0 comments on commit bfe92e4

Please sign in to comment.