Class: ApiValidator::JsonSchema

Inherits:
Base
  • Object
show all
Defined in:
lib/api-validator/json_schema.rb

Constant Summary collapse

SchemaNotFoundError =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#assertions

Constructor Details

#initialize(expected, root_path = nil) ⇒ JsonSchema

Returns a new instance of JsonSchema.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/api-validator/json_schema.rb', line 9

def initialize(expected, root_path = nil)
  @expected, @root_path = expected, root_path

  if Hash === expected
    schema = expected
  else
    unless schema = JsonSchemas[expected]
      raise SchemaNotFoundError.new("Unable to locate schema: #{expected.inspect}")
    end
  end

  @schema = schema

  initialize_assertions(schema)
end

Instance Attribute Details

#root_pathObject (readonly)

Returns the value of attribute root_path.



8
9
10
# File 'lib/api-validator/json_schema.rb', line 8

def root_path
  @root_path
end

Instance Method Details

#assertion_valid?(assertion, actual) ⇒ Boolean

Returns:

  • (Boolean)


139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/api-validator/json_schema.rb', line 139

def assertion_valid?(assertion, actual)
  type = assertion.type
  case type
  when "array"
    Array === actual
  when "boolean"
    (TrueClass === actual) || (FalseClass === actual)
  when "integer"
    Fixnum === actual
  when "number"
    Numeric === actual
  when "null"
    NilClass === actual
  when "object"
    Hash === actual
  when "string"
    String === actual
  else
    super
  end
end

#class_for_schema_type(type) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/api-validator/json_schema.rb', line 208

def class_for_schema_type(type)
  case type
  when "array"
    Array
  when "boolean"
    [TrueClass, FalseClass]
  when "integer"
    Fixnum
  when "number"
    Numeric
  when "null"
    NilClass
  when "object"
    Hash
  when "string"
    String
  end
end

#diff(actual, _failed_assertions) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/api-validator/json_schema.rb', line 56

def diff(actual, _failed_assertions)
  _diff = _failed_assertions.inject([]) do |memo, assertion|
    pointer = JsonPointer.new(actual, assertion.path)
    if !pointer.exists?
      assertion = assertion.to_hash
      actual_value = nil
      assertion[:op] = "add"
      assertion[:value] = value_for_schema_type(assertion[:type], actual_value)
      assertion[:message] = wrong_type_message(assertion[:type], schema_type(actual_value))
      memo << assertion
    end
    memo
  end

  _diff + schema_diff(@schema, actual)
end

#failed_assertions(actual) ⇒ Object



49
50
51
52
53
54
# File 'lib/api-validator/json_schema.rb', line 49

def failed_assertions(actual)
  assertions.select do |assertion|
    pointer = JsonPointer.new(actual, assertion.path)
    !pointer.exists? || !assertion_valid?(assertion, pointer.value)
  end
end

#initialize_assertions(schema, parent_path = "") ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/api-validator/json_schema.rb', line 37

def initialize_assertions(schema, parent_path = "")
  parent_path = root_path if root_path && parent_path == ""
  (schema["properties"] || {}).each_pair do |key, val|
    next unless val["required"] == true
    path = [parent_path, key].join("/")
    assertions << Assertion.new(path, nil, :type => val["type"])
    if val["type"] == "object"
      initialize_assertions(val, path)
    end
  end
end

#schema_diff(schema, actual, parent_path = "") ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/api-validator/json_schema.rb', line 73

def schema_diff(schema, actual, parent_path = "")
  properties = schema["properties"]

  return [] unless Hash === actual

  if root_path && parent_path == ""
    pointer = JsonPointer.new(actual, root_path)
    return [] unless pointer.exists?
    actual = pointer.value

    parent_path = root_path
  end

  actual.inject([]) do |memo, (key, val)|
    path = [parent_path, key].join("/")
    if property = properties[key.to_s]
      schema_property_diff(property, val, path) do |diff_item|
        memo << diff_item
      end
    elsif schema['additionalProperties'] == false
      memo << { :op => "remove", :path => path }
    end
    memo
  end
end

#schema_property_diff(property, actual, path, &block) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/api-validator/json_schema.rb', line 99

def schema_property_diff(property, actual, path, &block)
  assertion = Assertion.new(path, nil, :type => property["type"], :format => property["format"])

  if !assertion_valid?(assertion, actual)
    yield({
      :op => "replace",
      :path => path,
      :value => value_for_schema_type(assertion.type, actual),
      :current_value => actual,
      :type => assertion.type,
      :message => wrong_type_message(assertion.type, schema_type(actual))
    })
  elsif !assertion_format_valid?(assertion, actual)
    yield({
      :op => "replace",
      :path => path,
      :value => value_for_schema_format(assertion.format, actual),
      :current_value => actual,
      :type => assertion.type,
      :format => assertion.format,
      :message => wrong_format_message(assertion.format)
    })
  elsif (property["type"] == "object") && (Hash === property["properties"])
    schema_diff(property, actual, path).each { |d| yield(d) }
  elsif (property['type'] == 'array') && (Hash === property['items'])
    array_property = property['items']
    actual.each_with_index do |val, index|
      schema_property_diff(array_property, val, path + "/#{index}", &block)
    end
  end
end

#schema_type(value) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/api-validator/json_schema.rb', line 161

def schema_type(value)
  case value
  when Array
    "array"
  when TrueClass, FalseClass
    "boolean"
  when Fixnum
    "integer"
  when Numeric
    "number"
  when NilClass
    "null"
  when Hash
    "object"
  when String
    "string"
  else
    "unknown"
  end
end

#validate(response) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/api-validator/json_schema.rb', line 25

def validate(response)
  response_body = response.body.respond_to?(:to_hash) ? response.body.to_hash : response.body
  _failed_assertions = failed_assertions(response_body)
  _diff = diff(response_body, _failed_assertions)
  super.merge(
    :key => :response_body,
    :failed_assertions => _failed_assertions.map(&:to_hash),
    :diff => _diff,
    :valid => _diff.empty?
  )
end

#value_for_schema_format(format, value) ⇒ Object



201
202
203
204
205
206
# File 'lib/api-validator/json_schema.rb', line 201

def value_for_schema_format(format, value)
  case format
  when 'uri'
    "https://example.com"
  end
end

#value_for_schema_type(type, value) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/api-validator/json_schema.rb', line 182

def value_for_schema_type(type, value)
  klass = class_for_schema_type(type)
  if klass == Array
    value.respond_to?(:to_a) ? value.to_a : Array.new
  elsif klass == [TrueClass, FalseClass]
    !!value
  elsif klass == Fixnum
    value.respond_to?(:to_i) ? value.to_i : 0
  elsif klass == Numeric
    value.respond_to?(:to_f) ? value.to_f : 0.0
  elsif klass == Hash
    value.respond_to?(:to_hash) ? value.to_hash : Hash.new
  elsif klass == String
    value.respond_to?(:to_s) ? value.to_s : ""
  else
    nil
  end
end

#wrong_format_message(expected_format) ⇒ Object



135
136
137
# File 'lib/api-validator/json_schema.rb', line 135

def wrong_format_message(expected_format)
  "expected #{expected_format} format"
end

#wrong_type_message(expected_type, actual_type) ⇒ Object



131
132
133
# File 'lib/api-validator/json_schema.rb', line 131

def wrong_type_message(expected_type, actual_type)
  "expected type #{expected_type}, got #{actual_type}"
end