Best Inspec_ruby code snippet using Inspec.Plugins.tests
inspec.rb
Source:inspec.rb
...35 # Chef InSpec is based on RSpec, which is not thread safe36 # (https://github.com/rspec/rspec-core/issues/1254)37 # Tell test kitchen not to multithread the verify step38 no_parallel_for :verify39 default_config :inspec_tests, []40 default_config :load_plugins, true41 default_config :plugin_config, {}42 default_config :backend_cache, true43 # A lifecycle method that should be invoked when the object is about44 # ready to be used. A reference to an Instance is required as45 # configuration dependant data may be access through an Instance. This46 # also acts as a hook point where the object may wish to perform other47 # last minute checks, validations, or configuration expansions.48 #49 # @param instance [Instance] an associated instance50 # @return [self] itself, for use in chaining51 # @raise [ClientError] if instance parameter is nil52 def finalize_config!(instance)53 super54 # We want to switch kitchen-inspec to look for its tests in55 # `cookbook_dir/test/recipes` instead of `cookbook_dir/test/integration`56 # Unfortunately there is no way to read `test_base_path` from the57 # .kitchen.yml, it can only be provided on the CLI.58 # See https://github.com/test-kitchen/test-kitchen/issues/107759 inspec_test_dir = File.join(config[:kitchen_root], "test", "recipes")60 if File.directory?(inspec_test_dir)61 config[:test_base_path] = inspec_test_dir62 end63 self64 end65 # (see Base#call)66 def call(state)67 logger.debug("Initialize InSpec")68 # gather connection options69 opts = runner_options(instance.transport, state, instance.platform.name, instance.suite.name)70 logger.debug "Options #{opts.inspect}"71 # add inputs and waivers72 setup_inputs(opts, config)73 setup_waivers(opts, config)74 # setup Inspec75 ::Inspec::Log.init(STDERR)76 ::Inspec::Log.level = Kitchen::Util.from_logger_level(logger.level)77 load_plugins # Must load plugins prior to config validation78 inspec_config = ::Inspec::Config.new(opts)79 # handle plugins80 setup_plugin_config(inspec_config)81 # initialize runner82 runner = ::Inspec::Runner.new(inspec_config)83 # add each profile to runner84 tests = collect_tests85 profile_ctx = nil86 tests.each do |target|87 profile_ctx = runner.add_target(target)88 end89 profile_ctx ||= []90 profile_ctx.each do |profile|91 logger.info("Loaded #{profile.name} ")92 end93 exit_code = runner.run94 # 101 is a success as well (exit with no fails but has skipped controls)95 return if exit_code == 0 || exit_code == 10196 raise ActionFailed, "InSpec Runner returns #{exit_code}"97 end98 private99 def setup_waivers(opts, config)100 # InSpec expects the singular inflection101 opts[:waiver_file] = config[:waiver_files] || []102 end103 def setup_inputs(opts, config)104 inspec_version = Gem::Version.new(::Inspec::VERSION)105 # Handle input files106 if config[:attrs]107 logger.warn("kitchen-inspec: please use 'input-files' instead of 'attrs'")108 config[:input_files] = config[:attrs]109 end110 if config[:input_files]111 # Note that inspec expects the singular inflection, input_file112 files_key = inspec_version >= Gem::Version.new("3.10") ? :input_file : :attrs113 opts[files_key] = config[:input_files]114 end115 # Handle YAML => Hash inputs116 if config[:attributes]117 logger.warn("kitchen-inspec: please use 'inputs' instead of 'attributes'")118 config[:inputs] = config[:attributes]119 end120 if config[:inputs]121 # Version here is dependent on https://github.com/inspec/inspec/issues/3856122 inputs_key = inspec_version >= Gem::Version.new("4.10") ? :inputs : :attributes123 opts[inputs_key] = Hashie.stringify_keys config[:inputs]124 end125 end126 def load_plugins127 return unless config[:load_plugins]128 v2_loader = ::Inspec::Plugin::V2::Loader.new129 v2_loader.load_all130 v2_loader.exit_on_load_error131 # Suppress input caching or all suites will get identical inputs, not different ones132 if ::Inspec::InputRegistry.instance.respond_to?(:cache_inputs=) && config[:cache_inputs]133 ::Inspec::InputRegistry.instance.cache_inputs = !!config[:cache_inputs]134 end135 end136 def setup_plugin_config(inspec_config)137 return unless config[:load_plugins]138 unless inspec_config.respond_to?(:merge_plugin_config)139 logger.warn("kitchen-inspec: skipping `plugin_config` which requires InSpec version 4.26.2 or higher. Your version: #{::Inspec::VERSION}")140 return141 end142 config[:plugin_config].each do |plugin_name, plugin_config|143 inspec_config.merge_plugin_config(plugin_name, plugin_config)144 end145 end146 # (see Base#load_needed_dependencies!)147 def load_needed_dependencies!148 require "inspec"149 # TODO: this should be easier. I would expect to load a single class here150 # load supermarket plugin, this is part of the inspec gem151 require "bundles/inspec-supermarket/api"152 require "bundles/inspec-supermarket/target"153 # load the compliance plugin154 require "bundles/inspec-compliance/configuration"155 require "bundles/inspec-compliance/support"156 require "bundles/inspec-compliance/http"157 require "bundles/inspec-compliance/api"158 require "bundles/inspec-compliance/target"159 end160 # Returns an Array of test suite filenames for the related suite currently161 # residing on the local workstation. Any special provisioner-specific162 # directories (such as a Chef roles/ directory) are excluded.163 #164 # we support the base directories165 # - test/integration166 # - test/integration/inspec (preferred if used with other test environments)167 #168 # we do not filter for specific directories, this is core of inspec169 #170 # @return [Array<String>] array of suite directories171 # @api private172 def local_suite_files173 base = File.join(config[:test_base_path], config[:suite_name])174 legacy_mode = false175 # check for testing frameworks, we may need to add more176 %w{inspec serverspec bats pester rspec cucumber minitest bash}.each do |fw|177 if Pathname.new(File.join(base, fw)).exist?178 logger.info("Detected alternative framework tests for `#{fw}`")179 legacy_mode = true180 end181 end182 base = File.join(base, "inspec") if legacy_mode183 # only return the directory if it exists184 Pathname.new(base).exist? ? [{ path: base }] : []185 end186 # Takes config[:inspec_tests] and modifies any value with a key of :path by adding the full path187 # @return [Array] array of modified hashes188 # @api private189 def resolve_config_inspec_tests190 config[:inspec_tests].map do |test_item|191 if test_item.is_a?(Hash)192 # replace the "path" key with an absolute path193 test_item[:path] = File.expand_path(test_item[:path]) if test_item.key?(:path)194 # delete any unnecessary keys to ensure deduplication in #collect_tests isn't195 # foiled by extra stuff. However, if the only entry is a "name" key, then196 # leave it alone so it can default to resolving to the Supermarket.197 unless test_item.keys == [:name]198 type_keys = [:path, :url, :git, :compliance, :supermarket]199 git_keys = [:branch, :tag, :ref, :relative_path]200 supermarket_keys = [:supermarket_url]201 test_item.delete_if { |k, v| !(type_keys + git_keys + supermarket_keys).include?(k) }202 end203 elsif File.exist?(test_item)204 # if the entry is a path to something on disk, rewrite as a Hash entry with a path key.205 # This is necessary to ensure that auto-detected local suite files found with206 # #local_suite_files are de-duplicated with relative path entries supplied by the user207 # in the inspec_tests array.208 #209 # If the path doesn't exist, it could be a URL, or it could simply be an error.210 # We will let it fall through and let InSpec raise the appropriate exception.211 test_item = { path: File.expand_path(test_item) }212 end213 test_item unless test_item.nil? || test_item.empty?214 end215 end216 # Returns an array of test profiles217 # @return [Array<String>] array of suite directories or remote urls218 # @api private219 def collect_tests220 # get local tests and get run list of profiles221 (local_suite_files + resolve_config_inspec_tests).compact.uniq222 end223 # Returns a configuration Hash that can be passed to a `Inspec::Runner`.224 #225 # @return [Hash] a configuration hash of string-based keys226 # @api private227 def runner_options(transport, state = {}, platform = nil, suite = nil) # rubocop:disable Metrics/AbcSize228 transport_data = transport.diagnose.merge(state)229 if respond_to?("runner_options_for_#{transport.name.downcase}", true)230 send("runner_options_for_#{transport.name.downcase}", transport_data)231 else232 raise Kitchen::UserError, "Verifier #{name} does not support the #{transport.name} Transport"233 end.tap do |runner_options|234 # default color to true to match InSpec behavior235 runner_options["color"] = (config[:color].nil? ? true : config[:color])...
cli.rb
Source:cli.rb
...60 exit 161 end62 desc 'exec PROFILE', 'executes a Chef Compliance profile'63 exec_options64 def exec(*tests)65 config = InspecPlugins::Compliance::Configuration.new66 return if !loggedin(config)67 o = opts(:exec).dup68 diagnose(o)69 configure_logger(o)70 # iterate over tests and add compliance scheme71 tests = tests.map { |t| 'compliance://' + InspecPlugins::Compliance::API.sanitize_profile_name(t) }72 runner = Inspec::Runner.new(o)73 tests.each { |target| runner.add_target(target) }74 exit runner.run75 rescue ArgumentError, RuntimeError, Train::UserError => e76 $stderr.puts e.message77 exit 178 end79 desc 'download PROFILE', 'downloads a profile from Chef Compliance'80 option :name, type: :string,81 desc: 'Name of the archive filename (file type will be added)'82 def download(profile_name)83 o = options.dup84 configure_logger(o)85 config = InspecPlugins::Compliance::Configuration.new86 return if !loggedin(config)87 profile_name = InspecPlugins::Compliance::API.sanitize_profile_name(profile_name)...
reporter.rb
Source:reporter.rb
...18 statistics = mushy_report.statistics19 version = mushy_report.version20 # Some pass/fail information21 test_results = profiles.map(&:controls).flatten.map(&:results).flatten.map(&:status)22 passed_tests = test_results.select { |text| text == "passed" }.count23 failed_tests = test_results.count - passed_tests24 percent_pass = 100.0 * passed_tests / test_results.count25 percent_fail = 100.0 - percent_pass26 # Detailed OS27 platform_arch = runner.backend.backend.os.arch28 platform_name = runner.backend.backend.os.title29 # Allow template-based settings30 template_config = config.fetch("template_config", {})31 # ... also can use all InSpec resources via "inspec_resource.NAME.PROPERTY"32 output(template.result(binding))33 end34 # Return Constraints.35 #36 # @return [String] Always "~> 0.0"37 def self.run_data_schema_constraints38 "~> 0.0"39 end40 private41 # Read contents of requested template.42 #43 # @return [String] ERB Template44 # @raise [IOError]45 def template_contents46 @template_contents ||= File.read full_path(config["template_file"])47 end48 # Initialize configuration with defaults and Plugin config.49 #50 # @return [Hash] Configuration data after merge51 def config52 @config unless @config.nil?53 # Defaults54 @config = {55 "template_file" => "templates/flex.erb",56 }57 @config.merge! inspec_config.fetch_plugin_config("inspec-reporter-flex")58 @config.merge! config_environment59 logger.debug format("Configuration: %<config>s", config: @config)60 @config61 end62 # Allow (top-level) setting overrides from environment.63 #64 # @return [Hash] Configuration data from environment65 def config_environment66 env_reporter = env.select { |var, _| var.start_with?(ENV_PREFIX) }67 env_reporter.transform_keys { |key| key.delete_prefix(ENV_PREFIX).downcase }68 end69 # Return environment variables.70 #71 # @return [Hash] Mapping of environment variables72 def env73 @env ||= ENV74 end75 # Return InSpec Config object.76 #77 # @return [Inspec::Config] The InSpec config object78 def inspec_config79 @inspec_config ||= Inspec::Config.cached80 end81 # Return InSpec logger.82 #83 # @return [Inspec:Log] The Logger object84 def logger85 @logger ||= Inspec::Log86 end87 # Return InSpec Runner for further inspection.88 #89 # @return [Inspec::Runner] Runner instance90 def runner91 require "binding_of_caller"92 binding.callers.find { |b| b.frame_description == "run_tests" }.receiver93 end94 end95end...
tests
Using AI Code Generation
1 its('tests') { should include 'test1' }2 its('tests') { should include 'test1' }3 its('tests') { should include 'test2' }4 its('tests') { should include 'test3' }5 its('tests') { should include 'test4' }6 its('tests') { should include 'test5' }7 its('tests') { should include 'test6' }8 its('tests') { should include 'test7' }9 its('tests') { should include 'test8' }10 its('tests') { should include 'test9' }11 its('tests') { should include 'test10' }12 its('tests') { should include 'test11' }13 its('tests') { should include 'test12' }
tests
Using AI Code Generation
1 its('tests') { should include 'test1' }2 its('tests') { should include 'test1' }3 its('tests') { should include 'test2' }4 its('tests') { should include 'test3' }5 its('tests') { should include 'test4' }6 its('tests') { should include 'test5' }7 its('tests') { should include 'test6' }8 its('tests') { should include 'test7' }9 its('tests') { should include 'test8' }10 its('tests') { should include 'test9' }11 its('tests') { should include 'test10' }12 its('tests') { should include 'test11' }13 its('tests') { should include 'test12' }
tests
Using AI Code Generation
1tests = {}2test = {}3test[:params] = { 'param1' => 'value1' }4test[:result] = { 'result1' => 'value1' }5test = {}6test[:params] = { 'param2' => 'value2' }7test[:result] = { 'result2' => 'value2' }8test = {}9test[:params] = { 'param3' => 'value3' }10test[:result] = { '
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!