Class: Minitest::OpenAPI::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/minitest/openapi/validator.rb

Overview

Validates a response body against the schema a test declared for it. OpenAPI schemas are JSON Schema with a few divergences; ‘nullable: true` is normalized to a “null” type so a standard JSON Schema validator can be used. $refs of the form #/components/schemas/X resolve against the base document’s components.

Defined Under Namespace

Classes: ResponseMismatch

Instance Method Summary collapse

Constructor Details

#initialize(components) ⇒ Validator

Returns a new instance of Validator.



15
16
17
# File 'lib/minitest/openapi/validator.rb', line 15

def initialize(components)
  @components = components || {}
end

Instance Method Details

#validate!(schema, body, context:) ⇒ Object

Raises ResponseMismatch if ‘body` does not satisfy `schema`.

Raises:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/minitest/openapi/validator.rb', line 20

def validate!(schema, body, context:)
  return if schema.nil?

  root = {
    "$schema" => "https://json-schema.org/draft/2020-12/schema",
    "allOf" => [normalize(schema)],
    "components" => normalize(@components)
  }
  errors = JSONSchemer.schema(root).validate(body).to_a
  return if errors.empty?

  raise ResponseMismatch, "#{context} response did not match its declared schema:\n" +
    errors.first(8).map { |e| "  #{format_error(e)}" }.join("\n")
end