virtualization_resource: Fix NoMethodError on nil:NilClass (#2603)

* Move instance variable to avoid `NoMethodError`

Methods for `role` and `system` properties are dynamically generated and
return values from the `@virtualization_data` Mash. Therefor, we must
ensure `@virtualization_data` exists before calling these methods.

* Move supports logic to `supports platform: linux`

Signed-off-by: Jerry Aldrich <jerryaldrichiii@gmail.com>
This commit is contained in:
Jerry Aldrich 2018-02-28 09:22:55 -10:00 committed by Jared Quick
parent 48958a8924
commit 4631306ef1
2 changed files with 22 additions and 8 deletions

View file

@ -5,7 +5,7 @@ require 'hashie/mash'
module Inspec::Resources module Inspec::Resources
class Virtualization < Inspec.resource(1) class Virtualization < Inspec.resource(1)
name 'virtualization' name 'virtualization'
supports platform: 'unix' supports platform: 'linux'
desc 'Use the virtualization InSpec audit resource to test the virtualization platform on which the system is running' desc 'Use the virtualization InSpec audit resource to test the virtualization platform on which the system is running'
example " example "
describe virtualization do describe virtualization do
@ -25,11 +25,8 @@ module Inspec::Resources
" "
def initialize def initialize
unless inspec.os.linux? @virtualization_data = Hashie::Mash.new
skip_resource 'The `virtualization` resource is not supported on your OS yet.' collect_data_linux
else
collect_data_linux
end
end end
# add helper methods for easy access of properties # add helper methods for easy access of properties
@ -229,8 +226,7 @@ module Inspec::Resources
end end
def collect_data_linux # rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity def collect_data_linux # rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
# cache data in an instance var to avoid doing multiple detections for a single test # This avoids doing multiple detections in a single test
@virtualization_data ||= Hashie::Mash.new
return unless @virtualization_data.empty? return unless @virtualization_data.empty?
# each detect method will return true if it matched and was successfully # each detect method will return true if it matched and was successfully

View file

@ -0,0 +1,18 @@
# encoding: utf-8
require 'helper'
require 'inspec/resource'
describe 'Inspec::Resources::Virtualization' do
let(:resource) { MockLoader.new(:ubuntu).load_resource('virtualization') }
it 'skips the resource if OS is not Linux' do
resource = MockLoader.new(:windows).load_resource('virtualization')
resource.resource_skipped?.must_equal true
end
it 'returns nil for all properties if no virutalization platform is found' do
resource.system.must_be_nil
resource.role.must_be_nil
end
end