Module: GreeJson

Defined in:
lib/rest-object/gree_json.rb

Class Method Summary collapse

Class Method Details

._validate_json(expected, actual) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rest-object/gree_json.rb', line 31

def self._validate_json(expected, actual)
    if actual.nil?
        raise "missing field(s) in response: expected=#{expected} - actual == nil"
    end
    expected.each do |k, v|
        a = actual[k.to_s]
        #if a.nil?
        if !actual.has_key?(k.to_s)
            raise "missing \"#{k}\" property in JSON response, expected: #{v.inspect}"
        end
        case v
            when Hash
                if a.class != Hash
                    raise "got #{a.class} instead of JSON object for #{k}"
                end
                _validate_json(v, a)
            when Array
                if a.class != Array
                    raise "got JSON object instead of array for #{k}"
                end
                _validate_json_array(v, a, k.to_s)
            when Regexp
                a.should match v
            else
                a.should == v unless v == :any
        end
   end
end

._validate_json_array(expected, actual, k) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rest-object/gree_json.rb', line 60

def self._validate_json_array(expected, actual, k)
    if actual.class != Array
        raise "#{k} in response is not an array as expected"
    end
    if expected.count != actual.count
        raise "Error in #{k} array: expected #{expected.count} items, got #{actual.count}"
    end
    expected.each_index do |i|
        _validate_json(expected[i], actual[i])
    end
end

._validate_json_or_json_array(expected, actual) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/rest-object/gree_json.rb', line 23

def self._validate_json_or_json_array(expected, actual)
    if actual.class == Array
        _validate_json_array(expected, actual, actual.count)
    else
        _validate_json(expected, actual)
    end
end

.check_json_response(expected, response) ⇒ Object

Validate a JSON response, comparing to an expected hash TODO: add strict parm to check for extra keys



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rest-object/gree_json.rb', line 10

def self.check_json_response(expected, response)
    begin
        result = JSON.parse(response)
        _validate_json_or_json_array(expected, result)
    rescue => ex
        GreeLog.puts "EXCEPTION: #{ex.message}\n"
        GreeLog.puts "EXPECTED\n#{expected.inspect}\n"
        GreeLog.puts "ACTUAL\n#{response}\nEND"
        # rethrow the message to remove the recursive stack trace
        raise ex.message
    end
end