inspec/lib/resources/json.rb

84 lines
1.8 KiB
Ruby
Raw Normal View History

2015-09-21 07:51:00 +00:00
# encoding: utf-8
2015-10-06 16:55:44 +00:00
# author: Christoph Hartmann
# author: Dominik Richter
2015-09-21 07:51:00 +00:00
# Parses a json document
# Usage:
2015-09-21 11:05:17 +00:00
# describe json('policyfile.lock.json') do
2015-09-21 07:51:00 +00:00
# its('cookbook_locks.omnibus.version') { should eq('2.2.0') }
# end
2015-10-26 03:04:18 +00:00
class JsonConfig < Inspec.resource(1)
2015-09-21 07:51:00 +00:00
name 'json'
# make params readable
attr_reader :params
def initialize(path)
@path = path
@file = inspec.file(@path)
@file_content = @file.content
# check if file is available
if !@file.file?
skip_resource "Can't find file \"#{@conf_path}\""
return @params = {}
end
# check if file is readable
if @file_content.empty? && @file.size > 0
skip_resource "Can't read file \"#{@conf_path}\""
return @params = {}
end
2015-09-21 07:51:00 +00:00
@params = parse(@file_content)
end
def parse(content)
2015-09-21 08:31:31 +00:00
require 'json'
JSON.parse(content)
2015-09-21 07:51:00 +00:00
end
2015-11-24 12:02:50 +00:00
def value(key)
extract_value(key, @params)
end
# Shorthand to retrieve a parameter name via `#its`.
# Example: describe json('file') { its('paramX') { should eq 'Y' } }
#
# @param [String] name name of the field to retrieve
# @return [Object] the value stored at this position
def method_missing(*keys)
# catch bahavior of rspec its implementation
# @see https://github.com/rspec/rspec-its/blob/master/lib/rspec/its.rb#L110
keys.shift if keys.is_a?(Array) && keys[0] == :[]
value(keys)
end
def to_s
"Json #{@path}"
end
private
2015-09-21 07:51:00 +00:00
def extract_value(keys, value)
key = keys.shift
return nil if key.nil?
# if value is an array, iterate over each child
2015-11-24 12:02:50 +00:00
if value.is_a?(Array)
2015-09-21 07:51:00 +00:00
value = value.map { |i|
extract_value([key], i)
}
else
2015-11-24 12:02:50 +00:00
value = value[key.to_s].nil? ? nil : value[key.to_s]
2015-09-21 07:51:00 +00:00
end
# check if further keys exist
if !keys.first.nil?
return extract_value(keys.clone, value)
else
return value
end
end
end