How to use finalize_options method of Inspec Package

Best Inspec_ruby code snippet using Inspec.finalize_options


Source:config.rb Github


Full Screen

...39 @cli_opts = cli_opts.dup40 cfg_io = resolve_cfg_io(@cli_opts, cfg_io)41 @cfg_file_contents = read_cfg_file_io(cfg_io)42 @merged_options = merge_options43 @final_options = finalize_options44 self.class.cached = self45 end46 def diagnose47 return unless self[:diagnose]48 puts "InSpec version: #{Inspec::VERSION}"49 puts "Train version: #{Train::VERSION}"50 puts 'Command line configuration:'51 pp @cli_opts52 puts 'JSON configuration file:'53 pp @cfg_file_contents54 puts 'Merged configuration:'55 pp @merged_options56 puts57 end58 #-----------------------------------------------------------------------#59 # Train Credential Handling60 #-----------------------------------------------------------------------#61 # Returns a Hash with Symbol keys as follows:62 # backend: machine name of the Train transport needed63 # If present, any of the GENERIC_CREDENTIALS.64 # All other keys are specific to the backend.65 #66 # The credentials are gleaned from:67 # * the Train transport defaults. Train handles this on transport creation,68 # so this method doesn't load defaults.69 # * individual InSpec CLI options (which in many cases may have the70 # transport name prefixed, which is stripped before being added71 # to the creds hash)72 # * the --target CLI option, which is interpreted:73 # - as a transport://credset format, which looks up the creds in74 # the config file in the credentials section75 # - as an arbitrary URI, which is parsed by Train.unpack_target_from_uri76 def unpack_train_credentials77 # Internally, use indifferent access while we build the creds78 credentials ={})79 # Helper methods prefixed with _utc_ (Unpack Train Credentials)80 credentials.merge!(_utc_generic_credentials)81 _utc_determine_backend(credentials)82 transport_name = credentials[:backend].to_s83 _utc_merge_credset(credentials, transport_name)84 _utc_merge_transport_options(credentials, transport_name)85 # Convert to all-Symbol keys86 credentials.each_with_object({}) do |(option, value), creds|87 creds[option.to_sym] = value88 creds89 end90 end91 private92 def _utc_merge_transport_options(credentials, transport_name)93 # Ask Train for the names of the transport options94 transport_options = Train.options(transport_name) # If there are any options with those (unprefixed) names, merge them in.96 unprefixed_transport_options = do |option_name, _value|97 transport_options.include? option_name # e.g., 'host'98 end99 credentials.merge!(unprefixed_transport_options)100 # If there are any prefixed options, merge them in, stripping the prefix.101 transport_prefix ='-', '_') + '_'102 transport_options.each do |bare_option_name|103 prefixed_option_name = transport_prefix + bare_option_name.to_s104 if final_options.key?(prefixed_option_name)105 credentials[bare_option_name.to_s] = final_options[prefixed_option_name]106 end107 end108 end109 # fetch any info that applies to all transports (like sudo information)110 def _utc_generic_credentials111 { |option, _value| GENERIC_CREDENTIALS.include?(option) }112 end113 def _utc_determine_backend(credentials)114 return if credentials.key?(:backend)115 # Default to local116 unless @final_options.key?(:target)117 credentials[:backend] = 'local'118 return119 end120 # Look into target121 %r{^(?<transport_name>[a-z_\-0-9]+)://.*$} =~ final_options[:target]122 unless transport_name123 raise ArgumentError, "Could not recognize a backend from the target #{final_options[:target]} - use a URI format with the backend name as the URI schema. Example: 'ssh://' or 'transport://credset' or 'transport://' if credentials are provided outside of InSpec."124 end125 credentials[:backend] = transport_name.to_s # these are indeed stored in Train as Strings.126 end127 def _utc_merge_credset(credentials, transport_name)128 # Look for Config File credentials/transport_name/credset129 credset_name = _utc_find_credset_name(credentials, transport_name)130 if credset_name131 credset = @cfg_file_contents.dig('credentials', transport_name, credset_name)132 if credset133 credentials.merge!(credset)134 else135 # OK, we had a target that looked like transport://something136 # But we don't know what that something is - there was no137 # matching credset with it. Let train parse it.138 credentials.merge!(Train.unpack_target_from_uri(final_options[:target]))139 end140 elsif final_options.key?(:target)141 # Not sure what target looked like at all!142 # Let train parse it.143 credentials.merge!(Train.unpack_target_from_uri(final_options[:target]))144 end145 end146 def _utc_find_credset_name(_credentials, transport_name)147 return nil unless final_options[:target]148 match = final_options[:target].match(%r{^#{transport_name}://(?<credset_name>[\w\d\-]+)$})149 match ? match[:credset_name] : nil150 end151 #-----------------------------------------------------------------------#152 # Reading Config Files153 #-----------------------------------------------------------------------#154 # Regardless of our situation, end up with a readable IO object155 def resolve_cfg_io(cli_opts, cfg_io)156 raise(ArgumentError, 'Inspec::Config must use an IO to read from') if cfg_io && !cfg_io.respond_to?(:read)157 cfg_io ||= check_for_piped_config(cli_opts)158 return cfg_io if cfg_io159 path = determine_cfg_path(cli_opts)160 cfg_io = if path161 cfg_io ||'{ "version": "1.1" }')162 end163 def check_for_piped_config(cli_opts)164 cli_opt = cli_opts[:config] || cli_opts[:json_config]165 Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)166 return nil unless cli_opt167 return nil unless cli_opt == '-'168 # This warning is here so that if a user invokes inspec with --config=-,169 # they will have an explanation for why it appears to hang.170 Inspec::Log.warn 'Reading JSON config from standard input' if STDIN.tty?171 STDIN172 end173 def determine_cfg_path(cli_opts)174 path = cli_opts[:config] || cli_opts[:json_config]175 Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)176 if path.nil?177 default_path = File.join(Inspec.config_dir, 'config.json')178 path = default_path if File.exist?(default_path)179 elsif !File.exist?(path)180 raise ArgumentError, "Could not read configuration file at #{path}"181 end182 path183 end184 # When reading STDIN, read it once into a class variable and cache it.185 # Don't cache other IO objects though, as we use several different StringIOs186 # during unit testing. Refs #3792187 def self.stdin_contents # rubocop: disable Lint/IneffectiveAccessModifier188 @stdin_content ||= STDIN.read189 end190 def read_cfg_file_io(cfg_io)191 contents = cfg_io == STDIN ? self.class.stdin_contents : cfg_io.read192 begin193 @cfg_file_contents = JSON.parse(contents)194 validate_config_file_contents!195 rescue JSON::ParserError => e196 raise Inspec::ConfigError::MalformedJson, "Failed to load JSON configuration: #{e}\nConfig was: #{contents}"197 end198 @cfg_file_contents199 end200 def file_version201 @cfg_file_contents['version'] || :legacy202 end203 def legacy_file?204 file_version == :legacy205 end206 def config_file_cli_options207 if legacy_file?208 # Assume everything in the file is a CLI option209 @cfg_file_contents210 else211 @cfg_file_contents['cli_options'] || {}212 end213 end214 def config_file_reporter_options215 # This is assumed to be top-level in both legacy and 1.1.216 # Technically, you could sneak it in the 1.1 cli opts area.217 @cfg_file_contents.key?('reporter') ? { 'reporter' => @cfg_file_contents['reporter'] } : {}218 end219 #-----------------------------------------------------------------------#220 # Validation221 #-----------------------------------------------------------------------#222 def validate_config_file_contents!223 version = @cfg_file_contents['version']224 # Assume legacy format, which is unconstrained225 return unless version226 unless version == '1.1'227 raise Inspec::ConfigError::Invalid, "Unsupported config file version '#{version}' - currently supported versions: 1.1"228 end229 valid_fields = %w{version cli_options credentials compliance reporter}.sort230 @cfg_file_contents.keys.each do |seen_field|231 unless valid_fields.include?(seen_field)232 raise Inspec::ConfigError::Invalid, "Unrecognized top-level configuration field #{seen_field}. Recognized fields: #{valid_fields.join(', ')}"233 end234 end235 end236 def validate_reporters!(reporters)237 return if reporters.nil?238 # TODO: move this into a reporter plugin type system239 valid_types = [240 'automate',241 'cli',242 'documentation',243 'html',244 'json',245 'json-automate',246 'json-min',247 'json-rspec',248 'junit',249 'progress',250 'yaml',251 ]252 reporters.each do |reporter_name, reporter_config|253 raise NotImplementedError, "'#{reporter_name}' is not a valid reporter type." unless valid_types.include?(reporter_name)254 next unless reporter_name == 'automate'255 %w{token url}.each do |option|256 raise Inspec::ReporterError, "You must specify a automate #{option} via the config file." if reporter_config[option].nil?257 end258 end259 # check to make sure we are only reporting one type to stdout260 stdout_reporters = 0261 reporters.each_value do |reporter_config|262 stdout_reporters += 1 if reporter_config['stdout'] == true263 end264 raise ArgumentError, 'The option --reporter can only have a single report outputting to stdout.' if stdout_reporters > 1265 end266 #-----------------------------------------------------------------------#267 # Merging Options268 #-----------------------------------------------------------------------#269 def merge_options270 options ={})271 # Lowest precedence: default, which may vary by command272 options.merge!(@defaults)273 # Middle precedence: merge in any CLI options defined from the config file274 options.merge!(config_file_cli_options)275 # Reporter options may be defined top-level.276 options.merge!(config_file_reporter_options)277 # Highest precedence: merge in any options defined via the CLI278 options.merge!(@cli_opts)279 options280 end281 #-----------------------------------------------------------------------#282 # Finalization283 #-----------------------------------------------------------------------#284 def finalize_options285 options = @merged_options.dup286 finalize_set_top_level_command(options)287 finalize_parse_reporters(options)288 finalize_handle_sudo(options)289 finalize_compliance_login(options)290 end292 def finalize_set_top_level_command(options)293 options[:type] = @command_name294 Inspec::BaseCLI.inspec_cli_command = @command_name # TODO: move to a more relevant location295 end296 def finalize_parse_reporters(options) # rubocop:disable Metrics/AbcSize297 # default to cli report for ad-hoc runners298 options['reporter'] = ['cli'] if options['reporter'].nil?...

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:


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?