json resource: ensure params is not nil in even of read/parse failure (#2354)

When the JSON resource (and those that subclass off of it) were modified
to properly throw exceptions in the event of failure, this caused the
`params` method to return nil instead of what it used to be, an empty
hash.

This is fine in the case of a describe block, but it's not okay when used
outside of a describe, as it will cause users trying to pluck from the
hash to throw a dreaded-and-unhelpful NilClass error.

This change pre-populates the params to be an empty hash, and if the
read/parse steps fail, it will still be one.

Signed-off-by: Adam Leff <adam@leff.co>
This commit is contained in:
Adam Leff 2017-11-29 16:31:06 -05:00 committed by GitHub
parent a3954dec1b
commit 12fec238f7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 1 deletions

View file

@ -29,6 +29,12 @@ module Inspec::Resources
attr_reader :params, :raw_content
def initialize(opts)
# pre-initialize @params to an empty hash. In the event that reading/parsing the data
# throws an exception, this allows the resource to still be called outside of a
# describe/test and not throw errors when a caller attempts to fetch a value from the params.
@params = {}
# load the raw content from the source, and then parse it
@raw_content = load_raw_content(opts)
@params = parse(@raw_content)
end

View file

@ -33,12 +33,17 @@ describe 'Inspec::Resources::JSON' do
_(resource.send(:'x.y.z')).must_be_nil
end
end
describe 'when loading a nonexistent file' do
let (:resource) { load_resource('json', 'nonexistent.json') }
let(:resource) { load_resource('json', 'nonexistent.json') }
it 'produces an error' do
_(resource.resource_exception_message).must_equal 'No such file: nonexistent.json'
end
it 'still provides an empty hash for params' do
_(resource.params).must_equal({})
end
end
describe '#load_raw_from_file' do