inspec/test/unit/mock/profiles/profile-with-resource-exceptions/libraries/example_resource.rb
Jerry Aldrich III 71057675de Allow skipping/failing resources in FilterTable (#2349)
* Allow skipping/failing resources in FilterTable

`FilterTable` is commonly used in the class body of a resource and is
evaluated during an `instance_eval`. This means that if you raise an
exception (e.g. SkipResource) it will halt `inspec exec` and
`inspec check`.

This adds an `ExceptionCatcher` class that will postpone evaluation
until test execution.

This allows `inspec check` and `inspec exec` to perform as intended when
skipping/failing a resource in `FilterTable`

Huge thanks to @adamleff for providing the starting code/ideas!

Signed-off-by: Jerry Aldrich <jerryaldrichiii@gmail.com>

* Comment why `ExceptionCatcher` doesn't raise

Signed-off-by: Jerry Aldrich <jerryaldrichiii@gmail.com>

* Remove `accessor` from `ExceptionCatcher`

Signed-off-by: Jerry Aldrich <jerryaldrichiii@gmail.com>

* Return the existing ExceptionCatcher object rather than creating new

Signed-off-by: Adam Leff <adam@leff.co>
2017-11-29 07:32:40 -05:00

76 lines
2 KiB
Ruby

# encoding: utf-8
class ExceptionResourceTest < Inspec.resource(1)
name 'exception_resource_test'
desc '
Used to test resource exceptions.
'
example "
# Should execute always and pass
describe exception_resource_test('foo') do
its('value') { should eq 'foo' }
end
# Should execute always and fail
describe exception_resource_test('foo') do
its('value') { should eq 'bar' }
end
# Should raise Inspec::Exceptions::SkipResource but not halt run
# Example: Command not found
describe exception_resource_test('foo', :skip_me) do
its('value') { should eq 'foo' }
end
# Should raise Inspec::Exceptions::FailResource but not halt run
# Example: Command failed
describe exception_resource_test('foo', :fail_me) do
its('value') { should eq 'foo' }
end
"
attr_reader :value
def initialize(value, qualifier = nil)
@value = value
@inside_matcher = inside_matcher
case qualifier
when :skip_me
raise Inspec::Exceptions::ResourceSkipped, 'Skipping because reasons'
when :fail_me
raise Inspec::Exceptions::ResourceFailed, 'Failing because reasons'
end
end
filter = FilterTable.create
filter.add_accessor(:where)
.add_accessor(:entries)
.add(:matters, field: 'matters')
.add(:another_filter, field: 'another_filter')
.connect(self, :filters_example)
private
def filters_example
case @value
when 'skip_me'
raise Inspec::Exceptions::ResourceSkipped, 'Skipping inside FilterTable'
when 'fail_me'
raise Inspec::Exceptions::ResourceFailed, 'Failing inside FilterTable'
end
[{ 'matters' => 'it really does', 'another_filter' => 'example' }]
end
def inside_matcher
case @value
when 'fail inside matcher'
raise Inspec::Exceptions::ResourceFailed, 'Failing inside matcher'
when 'skip inside matcher'
raise Inspec::Exceptions::ResourceSkipped, 'Skipping inside matcher'
else
'inside_matcher'
end
end
end