Class: Jason::Spec

Inherits:
Object
  • Object
show all
Defined in:
lib/jason/spec.rb

Overview

Class for holding and checking specifications for a JSON structure

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(specs) ⇒ Spec

Returns a new instance of Spec.

Parameters:

  • specs (Hash)

    Specifications for testing

Options Hash (specs):

  • :type (Class)

    Type of the actual

  • :size (Integer)

    Size of the actual

  • :each (Array)

    Each element in actual should have these fields

  • :fields (Array)

    Fields that should be present in actual



23
24
25
26
# File 'lib/jason/spec.rb', line 23

def initialize(specs)
  @specs = specs
  @misses = []
end

Instance Attribute Details

#missesArray (readonly)

List of collected failures

Returns:

  • (Array)

    the current value of misses



13
14
15
# File 'lib/jason/spec.rb', line 13

def misses
  @misses
end

#specsHash (readonly)

Stored specifications

Returns:

  • (Hash)

    the current value of specs



13
14
15
# File 'lib/jason/spec.rb', line 13

def specs
  @specs
end

Instance Method Details

#fits?(actual) ⇒ Boolean

Check if the specs fit the actual

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/jason/spec.rb', line 32

def fits?(actual)
  @misses = [] # reset misses
  @specs.each do |key, value|
    method = :"match_#{key}"
    if !respond_to?(method)
      @misses << "Unknown spec: #{key}"
      break
    end

    begin
      self.send(method, value, actual)
    rescue => ex
      @misses << "Error in #{key} check: #{ex.class}: #{ex.message}"
    end

    break if @misses.any?
  end

  @misses.empty?
end

#match_any(fields, value) ⇒ Object

Wrapper around #match_each



187
188
189
# File 'lib/jason/spec.rb', line 187

def match_any(fields, value)
  match_each(fields, value, :any)
end

#match_each(mapping, value, type = :each, root = "") ⇒ void

This method returns an undefined value.

Does the array contain each of the requested specs

Examples:

Shallow check for key

match_each([ :id ], [ { 'id' => 1 }])

Shallow check for key with any

match_each([ :id ], [ { 'id' => 1 }, { 'bar' => 'beer' } ], :any )

Shallow check for key with none

not match_each([ :id ], [ { 'id' => 1 }, { 'bar' => 'beer' } ], :any )

Deep check

match_each(
  { item: [ :id, :name ] }
  [ { "item" => { "id" => "one", "name" => "two" } } ]
)

Parameters:

  • mapping (Hash, Array, Jason::Spec)

    What the array should contain

  • value (Array)

    Array to check

  • type (Symbol) (defaults to: :each)

    How to check:

    • :each - all items must match)

    • :any - at least one item must match)

    • :none - no item may match

  • root (String) (defaults to: "")

    Root for recursive checks



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/jason/spec.rb', line 134

def match_each(mapping, value, type=:each, root="")
  misses = []
  if mapping.is_a?(Array)
    misses = match_each_shallow(mapping, value)
  else
    value.each_with_index do |val, index|
      if !val.is_a?(Hash)
        misses << "Each check failed. #{val} is no hash at #{root}[#{index}]"
        break
      end

      mapping.each do |key, fields|
        key = key.to_s
        miss_key = root == "" ? key : "#{root}.#{key}"

        if !val[key]
          misses << "Each check failed. Key #{miss_key} is missing at #{root}[#{index}]"
        end

        if !val[key].is_a?(Hash)
          misses << "Each check failed. #{miss_key} is no hash at #{root}[#{index}]"
        end

        if fields.is_a?(Hash)
          match_each(fields,val[key],type,miss_key)
          next
        end

        fields.each do |attr|
          if !val[key].has_key?(attr.to_s)
            misses << "Each check failed. #{miss_key}[#{attr}] is missing at #{root}[#{index}]"
          end
        end
      end
    end
  end

  case type
  when :each
    @misses += misses.compact
  when :any
    if misses.compact.size == value.size
      @misses << "Shallow any check failed: #{misses}"
    end
  when :none
    if misses.compact.size != value.size
      @misses << "Shallow none check failed: #{misses}"
    end
  end
end

#match_each_shallow(fields, value) ⇒ void

This method returns an undefined value.

Match each only for fields

Parameters:

  • fields (Array<Symbol>)

    list of required fields

  • list (Array)

    of objects that carry fields



203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/jason/spec.rb', line 203

def match_each_shallow(fields, value)
  misses = []
  value.each_with_index do |val, index|
    fields.each do |attr|
      if !val.has_key?(attr.to_s)
        misses[index] = "Shallow each check failed. Key #{attr} is missing at [#{index}]"
        break
      end
    end
  end

  return misses
end

#match_fields(fields, value, type = :each) ⇒ void

This method returns an undefined value.

Match fields on a hash

Examples:

Using array (each)

# every field must be present
spec = Jason.spec(fields: [ :id, :name ])
spec.fits({ 'id' => 1, 'name' => "jason" })
not spec.fits({ 'id' => 1 })

Using each

# same as passing the array
spec = Jason.spec(fields: { each: [ :id, :name ] })
spec.fits({ 'id' => 1, 'name' => "jason" })
not spec.fits({ 'id' => 1 })

Using any

spec = Jason.spec(fields: { any: [ :id, :name ] })
spec.fits({ 'id' => 1 })

Using none

spec = Jason.spec(fields: { none: [ :id, :name ] })
not spec.fits({ 'id' => 1 })

Parameters:

  • fields (Hash, Array<Symbol>)

    list of required fields

  • value (Hash)

    Hash to check fields in



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/jason/spec.rb', line 242

def match_fields(fields, value, type=:each)
  if fields.is_a?(Hash)
    fields.each do |type, v_fields|
      match_fields(v_fields, value, type)
    end
    return
  end

  fields.map!(&:to_s)
  res = fields & value.keys

  case type
  when :each
    @misses << "Field(s) #{res - fields} are missing" if res.sort != fields.sort
  when :any
    @misses << "None of the fields #{fields} where found" if res.empty?
  when :none
    @misses << "Fields #{res} found, none of them where expected" if res.any?
  end
end

#match_none(fields, value) ⇒ Object

Wrapper around #match_each



193
194
195
# File 'lib/jason/spec.rb', line 193

def match_none(fields, value)
  match_each(fields, value, :none)
end

#match_size(size, value) ⇒ void

This method returns an undefined value.

Does the value match the requested size. Populates @misses in failure

Parameters:

  • size (Integer)

    The needed size

  • value (Object)


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/jason/spec.rb', line 90

def match_size(size, value)
  if !value.respond_to?(:size)
    @misses << "Size mismatch; #{value} has no size"
    return
  end

  hit = if size.is_a?(Fixnum)
    value.size == size
  elsif size.is_a?(Range)
    size.cover?(value.size)
  elsif size.is_a?(Array)
    size.include?(value.size)
  end

  @misses << "Size mismatch; Expected #{size}, got #{value.size}" if !hit
end

#match_type(type, value) ⇒ void

This method returns an undefined value.

Does the value match the requested type, populates @misses in failure

Examples:

Hash

match_type(:hash,   { foo: "bar" }) # match
match_type("array", [0,1,2])        # match
match_type(String,  "meh")          # match
match_tyoe(:booelean, false)        # match

Parameters:

  • type (Symbol, String, Class)

    What type should the value be. Supported strings are: hash, array, string or boolean

  • value (Object)


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/jason/spec.rb', line 67

def match_type(type, value)
  matched = case type
  when :array, :Array, "array", "Array"
    value.is_a?(Array)
  when :hash, :Hash, "hash", "Hash"
    value.is_a?(Hash)
  when :string, "string", "String"
    value.is_a?(String)
  when :boolean, :Boolean, "boolean", "Boolean"
    value.is_a?(TrueClass) || value.is_a?(FalseClass)
  else
    value.is_a?(type)
  end

  @misses << "Type mismatch; Expected #{type}, got #{value.class}: #{value}" if !matched
end