mirror of
https://github.com/inspec/inspec
synced 2024-11-15 01:17:08 +00:00
24451469ca
Since #its has its(pun) own way of handling calls with a dot-notation, the full call is never passed to the resource. For example: ```ruby describe json('file') do its('a.b.c') { should eq 123 } end ``` This is resolved to calling `json('file').a.b.c` and thus doesnt work as an intended `json('file').send('a.b.c'). For now use regular its-behavior of calling `json('file').params ... its(%w{a b c}) { should ... }`. Its' behavior must be improved.
64 lines
1.4 KiB
Ruby
64 lines
1.4 KiB
Ruby
# encoding: utf-8
|
|
# author: Christoph Hartmann
|
|
# author: Dominik Richter
|
|
|
|
# Parses a json document
|
|
# Usage:
|
|
# describe json('policyfile.lock.json') do
|
|
# its('cookbook_locks.omnibus.version') { should eq('2.2.0') }
|
|
# end
|
|
class JsonConfig < Inspec.resource(1)
|
|
name 'json'
|
|
|
|
# make params readable
|
|
attr_reader :params
|
|
|
|
def initialize(path)
|
|
@path = path
|
|
@file_content = inspec.file(@path).content
|
|
@params = parse(@file_content)
|
|
end
|
|
|
|
def parse(content)
|
|
require 'json'
|
|
JSON.parse(content)
|
|
end
|
|
|
|
def extract_value(keys, value)
|
|
key = keys.shift
|
|
return nil if key.nil?
|
|
|
|
# check if key is a num, try to extract from array
|
|
if key.to_i.to_s == key
|
|
value = value[key.to_i]
|
|
# if value is an array, iterate over each child
|
|
elsif value.is_a?(Array)
|
|
value = value.map { |i|
|
|
extract_value([key], i)
|
|
}
|
|
# normal value extraction
|
|
else
|
|
value = value[key].nil? ? nil : value[key]
|
|
end
|
|
|
|
# check if further keys exist
|
|
if !keys.first.nil?
|
|
return extract_value(keys.clone, value)
|
|
else
|
|
return value
|
|
end
|
|
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(name)
|
|
@params[name.to_s]
|
|
end
|
|
|
|
def to_s
|
|
"Json #{@path}"
|
|
end
|
|
end
|