From 4631306ef1a0a8be220271e8e9c6f70867fba052 Mon Sep 17 00:00:00 2001 From: Jerry Aldrich Date: Wed, 28 Feb 2018 09:22:55 -1000 Subject: [PATCH] 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 --- lib/resources/virtualization.rb | 12 ++++-------- test/unit/resources/virtualization_test.rb | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) create mode 100644 test/unit/resources/virtualization_test.rb diff --git a/lib/resources/virtualization.rb b/lib/resources/virtualization.rb index 34d319f9d..aa0a562e7 100644 --- a/lib/resources/virtualization.rb +++ b/lib/resources/virtualization.rb @@ -5,7 +5,7 @@ require 'hashie/mash' module Inspec::Resources class Virtualization < Inspec.resource(1) 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' example " describe virtualization do @@ -25,11 +25,8 @@ module Inspec::Resources " def initialize - unless inspec.os.linux? - skip_resource 'The `virtualization` resource is not supported on your OS yet.' - else - collect_data_linux - end + @virtualization_data = Hashie::Mash.new + collect_data_linux end # add helper methods for easy access of properties @@ -229,8 +226,7 @@ module Inspec::Resources end 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 - @virtualization_data ||= Hashie::Mash.new + # This avoids doing multiple detections in a single test return unless @virtualization_data.empty? # each detect method will return true if it matched and was successfully diff --git a/test/unit/resources/virtualization_test.rb b/test/unit/resources/virtualization_test.rb new file mode 100644 index 000000000..6369c58b7 --- /dev/null +++ b/test/unit/resources/virtualization_test.rb @@ -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