How to use finalize method of Inspec Package

Best Inspec_ruby code snippet using Inspec.finalize

metadata.rb

Source:metadata.rb Github

copy

Full Screen

...8require 'semverse'9require 'utils/spdx'10module Inspec11 # Extract metadata.rb information12 # A Metadata object may be created and finalized with invalid data.13 # This allows the check CLI command to analyse the issues.14 # Use valid? to determine if the metadata is coherent.15 class Metadata16 attr_reader :ref17 attr_accessor :params, :content18 def initialize(ref, logger = nil)19 @ref = ref20 @logger = logger || Logger.new(nil)21 @content = ''22 @params = {}23 @missing_methods = []24 end25 %w{26 name27 title28 maintainer29 maintainer_email30 copyright31 copyright_email32 license33 summary34 description35 version36 inspec_version37 }.each do |name|38 define_method name.to_sym do |arg|39 params[name.to_sym] = arg40 end41 end42 def dependencies43 params[:depends] || []44 end45 def supports(sth, version = nil)46 # Ignore supports with metadata.rb. This file is legacy and the way it47 # it handles `supports` deprecated. A deprecation warning will be printed48 # already.49 end50 def inspec_requirement51 inspec_in_supports = params[:supports].find { |x| !x[:inspec].nil? }52 if inspec_in_supports53 warn '[DEPRECATED] The use of inspec.yml `supports:inspec` is deprecated and will be removed in InSpec 2.0. Please use `inspec_version` instead.'54 Gem::Requirement.create(inspec_in_supports[:inspec])55 else56 # using Gem::Requirement here to allow nil values which57 # translate to [">= 0"]58 Gem::Requirement.create(params[:inspec_version])59 end60 end61 def supports_runtime?62 running = Gem::Version.new(Inspec::VERSION)63 inspec_requirement.satisfied_by?(running)64 end65 def supports_platform?(backend)66 backend.platform.supported?(params[:supports])67 end68 # return all warn and errors69 def valid # rubocop:disable Metrics/AbcSize70 errors = []71 warnings = []72 %w{name version}.each do |field|73 next unless params[field.to_sym].nil?74 errors.push("Missing profile #{field} in #{ref}")75 end76 if params[:name] =~ %r{[\/\\]}77 warnings.push("Your profile name (#{params[:name]}) contains a slash " \78 'which will not be permitted in InSpec 2.0. Please change your profile ' \79 'name in the `inspec.yml` file.')80 end81 # if version is set, ensure it is correct82 if !params[:version].nil? && !valid_version?(params[:version])83 errors.push('Version needs to be in SemVer format')84 end85 %w{title summary maintainer copyright license}.each do |field|86 next unless params[field.to_sym].nil?87 warnings.push("Missing profile #{field} in #{ref}")88 end89 # if version is set, ensure it is in SPDX format90 if !params[:license].nil? && !Spdx.valid_license?(params[:license])91 warnings.push("License '#{params[:license]}' needs to be in SPDX format. See https://spdx.org/licenses/.")92 end93 [errors, warnings]94 end95 # returns true or false96 def valid?97 errors, _warnings = valid98 errors.empty? && unsupported.empty?99 end100 def valid_version?(value)101 Semverse::Version.new(value)102 true103 rescue Semverse::InvalidVersionFormat104 false105 end106 def method_missing(sth, *args)107 @logger.warn "#{ref} doesn't support: #{sth} #{args}"108 @missing_methods.push(sth)109 end110 def unsupported111 @missing_methods112 end113 def self.symbolize_keys(obj)114 return obj.map { |i| symbolize_keys(i) } if obj.is_a?(Array)115 return obj unless obj.is_a?(Hash)116 obj.each_with_object({}) do |(k, v), h|117 v = symbolize_keys(v) if v.is_a?(Hash)118 v = symbolize_keys(v) if v.is_a?(Array)119 h[k.to_sym] = v120 end121 end122 def self.finalize_supports_elem(elem, logger)123 case x = elem124 when Hash125 x[:release] = x[:release].to_s if x[:release]126 x127 when Array128 logger.warn(129 'Failed to read supports entry that is an array. Please use '\130 'the `supports: {os-family: xyz}` syntax.',131 )132 nil133 when nil then nil134 else135 logger ||= Logger.new(nil)136 logger.warn(137 "Do not use deprecated `supports: #{x}` syntax. Instead use:\n"\138 "supports:\n - os-family: #{x}\n\n",139 )140 { :'os-family' => x } # rubocop:disable Style/HashSyntax141 end142 end143 def self.finalize_supports(supports, logger)144 case x = supports145 when Hash then [finalize_supports_elem(x, logger)]146 when Array then x.map { |e| finalize_supports_elem(e, logger) }.compact147 when nil then []148 else149 logger ||= Logger.new(nil)150 logger.warn(151 "Do not use deprecated `supports: #{x}` syntax. Instead use:\n"\152 "supports:\n - os-family: #{x}\n\n",153 )154 [{ :'os-family' => x }] # rubocop:disable Style/HashSyntax155 end156 end157 def self.finalize_name(metadata, profile_id, original_target)158 # profile_id always overwrites whatever already exists as the name159 unless profile_id.to_s.empty?160 metadata.params[:name] = profile_id.to_s161 return162 end163 # don't overwrite an existing name164 return unless metadata.params[:name].nil?165 # if there's a title, there is no need to set a name too166 return unless metadata.params[:title].nil?167 # create a new name based on the original target if it exists168 # Crudely slug the target to not contain slashes, to avoid breaking169 # unit tests that look for warning sequences170 return if original_target.to_s.empty?171 metadata.params[:title] = "tests from #{original_target}"172 metadata.params[:name] = metadata.params[:title].gsub(%r{[\\\/]}, '.')173 end174 def self.finalize(metadata, profile_id, options, logger = nil)175 return nil if metadata.nil?176 param = metadata.params || {}177 options ||= {}178 param['version'] = param['version'].to_s unless param['version'].nil?179 metadata.params = symbolize_keys(param)180 metadata.params[:supports] = finalize_supports(metadata.params[:supports], logger)181 finalize_name(metadata, profile_id, options[:target])182 metadata183 end184 def self.from_yaml(ref, content, profile_id, logger = nil)185 res = Metadata.new(ref, logger)186 res.params = YAML.load(content)187 res.content = content188 finalize(res, profile_id, {}, logger)189 end190 def self.from_ruby(ref, content, profile_id, logger = nil)191 res = Metadata.new(ref, logger)192 res.instance_eval(content, ref, 1)193 res.content = content194 finalize(res, profile_id, {}, logger)195 end196 def self.from_ref(ref, content, profile_id, logger = nil)197 # NOTE there doesn't have to exist an actual file, it may come from an198 # archive (i.e., content)199 case File.basename(ref)200 when 'inspec.yml'201 from_yaml(ref, content, profile_id, logger)202 when 'metadata.rb'203 from_ruby(ref, content, profile_id, logger)204 else205 logger ||= Logger.new(nil)206 logger.error "Don't know how to handle metadata in #{ref}"207 nil208 end...

Full Screen

Full Screen

metadata_test.rb

Source:metadata_test.rb Github

copy

Full Screen

...9 def supports_meta(params)10 res = Inspec::Metadata.from_yaml('mock', "---", nil, logger)11 # manually inject supported parameters12 res.params[:supports] = params13 Inspec::Metadata.finalize(res, 'mock', empty_options, logger)14 res15 end16 describe 'running on ubuntu 14.04' do17 let (:backend) { MockLoader.new(:ubuntu1404).backend }18 it 'provides all metadata content' do19 s = "---\nname: hello #{rand}"20 res = Inspec::Metadata.from_yaml('mock', s, nil)21 Inspec::Metadata.finalize(res, 'mock', empty_options)22 res.content.must_equal(s)23 end24 it 'finalizes a loaded metadata via Profile ID' do25 res = Inspec::Metadata.from_yaml('mock', '---', nil)26 Inspec::Metadata.finalize(res, 'mock', empty_options)27 res.params[:name].must_equal('mock')28 end29 it 'finalizes a loaded metadata via Profile ID and overwrites the ID' do30 res = Inspec::Metadata.from_yaml('mock', "---\nname: hello", nil)31 Inspec::Metadata.finalize(res, 'mock', empty_options)32 res.params[:name].must_equal('mock')33 end34 it 'reads the version from metadata' do35 res = Inspec::Metadata.from_yaml('mock', "---\nversion: '1.1.0'", nil)36 Inspec::Metadata.finalize(res, 'mock', empty_options)37 res.params[:version].must_equal('1.1.0')38 res.valid_version?(res.params[:version]).must_equal(true)39 end40 it 'does not accept invalid version from metadata' do41 res = Inspec::Metadata.from_yaml('mock', "---\nversion: '1.1.0.1'", nil)42 Inspec::Metadata.finalize(res, 'mock', empty_options)43 res.params[:version].must_equal('1.1.0.1')44 res.valid_version?(res.params[:version]).must_equal(false)45 end46 it 'finalizes a loaded metadata by turning strings into symbols' do47 res = Inspec::Metadata.from_yaml('mock', "---\nauthor: world", nil)48 Inspec::Metadata.finalize(res, 'mock', empty_options)49 res.params[:author].must_equal('world')50 end51 it 'sets a default name with the original target if there is no name, title, or profile_id' do52 res = Inspec::Metadata.from_yaml('mock', '---', nil, logger)53 options = { target: '/path/to/tests' }54 Inspec::Metadata.finalize(res, nil, options, logger)55 res.params[:name].must_equal('tests from /path/to/tests')56 end57 it 'does not overwrite an existing name when name exists and profile_id is nil' do58 res = Inspec::Metadata.from_yaml('mock', "\nname: my_name", nil)59 options = { target: '/path/to/tests' }60 Inspec::Metadata.finalize(res, nil, options, logger)61 res.params[:name].must_equal('my_name')62 end63 it 'does not set a default name if a title is provided and profile_id is nil' do64 res = Inspec::Metadata.from_yaml('mock', "\ntitle: my_title", nil)65 options = { target: '/path/to/tests' }66 Inspec::Metadata.finalize(res, nil, options, logger)67 res.params[:title].must_equal('my_title')68 res.params[:name].must_be_nil69 end70 it 'loads the support field from metadata' do71 res = Inspec::Metadata.from_yaml('mock',72 "---\nsupports:\n - os: ubuntu", nil)73 res.params[:supports].must_equal([{ os: 'ubuntu' }])74 end75 it 'makes sure the supports release field is a string' do76 res = Inspec::Metadata.from_yaml('mock',77 "---\nsupports:\n - release: 12.02", nil)78 res.params[:supports].must_equal([{ release: '12.02' }])79 end80 it 'makes sure the supports release field is nil if not configured' do...

Full Screen

Full Screen

finalize

Using AI Code Generation

copy

Full Screen

1Inspec::Runner.override_runner(Inspec::Runner.new({ reporter: [MyReporter.new] }))2Inspec::Runner.new({ reporter: [MyReporter.new] }).finalize3Inspec::Runner.new({ reporter: [MyReporter.new] }).run4Inspec::Runner.new({ reporter: [MyReporter.new] }).run5Inspec::Runner.new({ reporter: [MyReporter.new] }).run6Inspec::Runner.new({ reporter: [MyReporter.new] }).run

Full Screen

Full Screen

finalize

Using AI Code Generation

copy

Full Screen

1report.to_json('control_id')2report.to_html('control_id')3report.to_json('control_id', ['file', 'package'])4report.to_html('control_id', ['file', 'package'])5report.to_json('control_id', ['file', 'package'], 'cisa')6report.to_html('control_id', ['file', 'package'], 'cisa')7report.to_json('control_id', ['file', 'package'], 'cisa', 'docker')8report.to_html('control_id', ['file', 'package'], 'cisa', 'docker')9report.to_json('control_id', ['file', 'package'], 'cisa', 'docker', 'v1.0')10report.to_html('control_id', ['file', 'package'], 'cisa', 'docker', 'v1.0')11report.to_json('control_id', ['file', 'package'], 'cisa', 'docker', 'v1.0', 'http://localhost:8080')12report.to_html('control_id', ['file', 'package'], 'cisa',

Full Screen

Full Screen

finalize

Using AI Code Generation

copy

Full Screen

1inspec.add_profile('profile1')2report = {3 {4 },5}6 next unless resource.method_property?(method_name)7 value = instance.send(method_name)8 report[:profiles][0][:controls] << {9 :tags => {},10 {11 },12 }13File.open('report.json', 'w') do |f|14 f.write(JSON.pretty_generate(report))

Full Screen

Full Screen

finalize

Using AI Code Generation

copy

Full Screen

1Inspec::Runner.override_runner(Inspec::Runner.new({ reporter: [MyReporter.new] }))2Inspec::Runner.new({ reporter: [MyReporter.new] }).finalize3Inspec::Runner.new({ reporter: [MyReporter.new] }).run4Inspec::Runner.new({ reporter: [MyReporter.new] }).run5Inspec::Runner.new({ reporter: [MyReporter.new] }).run6Inspec::Runner.new({ reporter: [MyReporter.new] }).run

Full Screen

Full Screen

finalize

Using AI Code Generation

copy

Full Screen

1inspec.add_profile('profile1')2report = {3 {4 },5}6 next unless resource.method_property?(method_name)7 value = instance.send(method_name)8 report[:profiles][0][:controls] << {9 :tags => {},10 {11 },12 }13File.open('report.json', 'w') do |f|14 f.write(JSON.pretty_generate(report))

Full Screen

Full Screen

finalize

Using AI Code Generation

copy

Full Screen

1class Inspec::Resources::MyCustomResource < Inspec.resource(1)2 it { should exist }3 its('content') { should eq 'my custom resource content' }4 @exists = inspec.file(@file_path).exist?5 @content = inspec.file(@file_path).content if exists?6Inspec::Plugins::ResourceRegistration.instance.register_resource(:my_custom_resource, Inspec::Resources::MyCustomResource)7 it { should exist }8 its('content') { should eq 'my custom resource content' }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Inspec_ruby automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful