Class: APIReaper::Checker

Inherits:
Object
  • Object
show all
Defined in:
lib/apireaper/checker.rb

Overview

This is an API response and data structure checker.

Instance Method Summary collapse

Constructor Details

#initialize(method, url, opts) ⇒ Checker

Class constructor method



27
28
29
30
# File 'lib/apireaper/checker.rb', line 27

def initialize(method, url, opts)
  @requester = APIReaper::Requester.new(method, url, opts)
  @opts = opts
end

Instance Method Details

#checkObject

Main method to run the check



33
34
35
36
37
38
39
# File 'lib/apireaper/checker.rb', line 33

def check
  res = @requester.request
  check_response_code(res.code)
  check_data_structure(res.body)
  File.write(@opts['outfile'], res.body) unless @opts['outfile'].nil?
  puts 'All checks passed' unless @opts['quiet']
end

#check_data_structure(data) ⇒ Object

Check data structure



42
43
44
45
46
47
# File 'lib/apireaper/checker.rb', line 42

def check_data_structure(data)
  JSON::Validator.validate!(find_schema_source, data)
  puts 'Response body is valid' unless @opts['quiet']
rescue JSON::Schema::ValidationError => e
  exit_with_error(2, e.message)
end

#check_response_code(code) ⇒ Object

Check respose code



50
51
52
53
54
55
56
# File 'lib/apireaper/checker.rb', line 50

def check_response_code(code)
  if code.to_i.between?(200, 299)
    puts "Response code is valid: #{code}" unless @opts['quiet']
  else
    exit_with_error(2, "Response code is invalid: #{code}")
  end
end

#exit_with_error(errno, message) ⇒ Object

Exit with the specified errno and message



59
60
61
62
# File 'lib/apireaper/checker.rb', line 59

def exit_with_error(errno, message)
  puts message unless @opts['quiet']
  exit errno
end

#find_schema_sourceObject

Get the data structure schema source



65
66
67
68
69
70
71
72
73
# File 'lib/apireaper/checker.rb', line 65

def find_schema_source
  if @opts['schema_file'].nil?
    JSON.parse(
      @opts['schema'].gsub(/:([a-zA-z]+)/, '"\\1"').gsub('=>', ': ')
    )
  else
    @opts['schema_file']
  end
end