Best Inspec_ruby code snippet using Inspec.add_target
inspec_spec.rb
Source:inspec_spec.rb
...304 let(:runner) do305 instance_double("Inspec::Runner")306 end307 before do308 allow(runner).to receive(:add_target)309 allow(runner).to receive(:run).and_return 0310 end311 it "constructs a Inspec::Runner using transport config data and state" do312 config[:sudo] = "jellybeans"313 config[:sudo_command] = "allyourbase"314 config[:proxy_command] = "gateway"315 config[:forward_agent] = true316 expect(Inspec::Runner).to receive(:new)317 .with(318 hash_including(319 "backend" => "ssh",320 "logger" => logger,321 "sudo" => "jellybeans",322 "sudo_command" => "allyourbase",323 "host" => "boogie",324 "port" => 123,325 "user" => "dance",326 "keepalive" => "keepalive",327 "keepalive_interval" => "forever",328 "connection_timeout" => "nope",329 "connection_retries" => "thousand",330 "connection_retry_sleep" => "sleepy",331 "max_wait_until_ready" => 42,332 "compression" => "maxyo",333 "compression_level" => "pico",334 "key_files" => ["/backstage/pass"],335 "proxy_command" => "gateway",336 "forward_agent" => true337 )338 )339 .and_return(runner)340 verifier.call(port: 123)341 end342 it "constructs a Inspec::Runner using transport config data(host and port)" do343 config[:host] = "192.168.33.40"344 config[:port] = 222345 expect(Inspec::Runner).to receive(:new)346 .with(347 hash_including(348 "backend" => "ssh",349 "host" => "192.168.33.40",350 "port" => 222351 )352 )353 .and_return(runner)354 verifier.call(port: 123)355 end356 it "constructs an Inspec::Runner with a specified inspec output format" do357 config[:format] = "documentation"358 expect(Inspec::Runner).to receive(:new)359 .with(360 hash_including(361 "format" => "documentation"362 )363 )364 .and_return(runner)365 verifier.call(port: 123)366 end367 it "constructs an Inspec::Runner with a controls filter" do368 config[:controls] = %w{a control}369 expect(Inspec::Runner).to receive(:new)370 .with(371 hash_including(372 controls: %w{a control}373 )374 )375 .and_return(runner)376 verifier.call(port: 123)377 end378 it "does not send keys_only=true to InSpec (which breaks SSH Agent usage)" do379 expect(Inspec::Runner).to receive(:new)380 .with(381 hash_not_including(382 "keys_only" => true383 )384 )385 .and_return(runner)386 verifier.call(port: 123)387 end388 it "provide platform and test suite to build output path" do389 allow(Inspec::Runner).to receive(:new).and_return(runner)390 expect(verifier).to receive(:runner_options).with(391 transport,392 {},393 "default",394 "germany"395 ).and_return({})396 verifier.call({})397 end398 it "custom inspec output path" do399 ensure_suite_directory("germany")400 config[:output] = "/tmp/inspec_results.xml"401 allow(Inspec::Runner).to receive(:new).and_return(runner)402 expect(runner).to receive(:add_target).with({ path: File.join(403 config[:test_base_path],404 "germany"405 ) }, hash_including(406 "output" => "/tmp/inspec_results.xml"407 ))408 verifier.call({})409 end410 it "resolve template format for inspec output path" do411 ensure_suite_directory("germany")412 config[:output] = "/tmp/%{platform}_%{suite}.xml"413 allow(Inspec::Runner).to receive(:new).and_return(runner)414 expect(runner).to receive(:add_target).with({ path: File.join(415 config[:test_base_path],416 "germany"417 ) }, hash_including(418 "output" => "/tmp/default_germany.xml"419 ))420 verifier.call({})421 end422 it "find test directory for runner" do423 ensure_suite_directory("germany")424 allow(Inspec::Runner).to receive(:new).and_return(runner)425 expect(runner).to receive(:add_target).with({ path: File.join(426 config[:test_base_path],427 "germany"428 ) }, anything)429 verifier.call({})430 end431 it "find test directory for runner if legacy" do432 create_legacy_test_directories433 allow(Inspec::Runner).to receive(:new).and_return(runner)434 expect(runner).to receive(:add_target).with({ path: File.join(435 config[:test_base_path],436 "germany", "inspec"437 ) }, anything)438 verifier.call({})439 end440 it "non-existent test directory for runner" do441 allow(Inspec::Runner).to receive(:new).and_return(runner)442 expect(runner).to_not receive(:add_target).with(443 File.join(444 config[:test_base_path],445 "nobody"446 ), anything)447 verifier.call({})448 end449 it "calls #run on the runner" do450 allow(Inspec::Runner).to receive(:new).and_return(runner)451 expect(runner).to receive(:run)452 verifier.call({})453 end454 end455 context "with an remote profile" do456 let(:transport) do457 Kitchen::Transport::Ssh.new({})458 end459 let(:runner) do460 instance_double("Inspec::Runner")461 end462 let(:suite) do463 instance_double("Kitchen::Suite", { name: "local" })464 end465 let(:instance) do466 instance_double(467 "Kitchen::Instance",468 name: "coolbeans",469 logger: logger,470 platform: platform,471 suite: suite,472 transport: transport,473 to_str: "instance"474 )475 end476 let(:config) do477 {478 inspec_tests: [{ url: "https://github.com/nathenharvey/tmp_compliance_profile" }],479 kitchen_root: kitchen_root,480 test_base_path: File.join(kitchen_root, "test", "integration"),481 }482 end483 before do484 allow(runner).to receive(:add_target)485 allow(runner).to receive(:run).and_return 0486 end487 it "find test directory and remote profile" do488 ensure_suite_directory("local")489 allow(Inspec::Runner).to receive(:new).and_return(runner)490 expect(runner).to receive(:add_target).with({ path: File.join(config[:test_base_path], "local") }, anything)491 expect(runner).to receive(:add_target).with(492 { url: "https://github.com/nathenharvey/tmp_compliance_profile" }, anything)493 verifier.call({})494 end495 end496 context "with an winrm transport" do497 let(:transport_config) do498 {499 username: "dance",500 password: "party",501 connection_retries: "thousand",502 connection_retry_sleep: "sleepy",503 max_wait_until_ready: 42,504 }505 end506 let(:transport) do507 Kitchen::Transport::Winrm.new(transport_config)508 end509 let(:runner) do510 instance_double("Inspec::Runner")511 end512 before do513 allow(runner).to receive(:add_target)514 allow(runner).to receive(:run).and_return 0515 end516 it "constructs a Inspec::Runner using transport config data and state" do517 expect(Inspec::Runner).to receive(:new)518 .with(519 hash_including(520 "backend" => "winrm",521 "logger" => logger,522 "host" => "win.dows",523 "port" => 123,524 "user" => "dance",525 "password" => "party",526 "connection_retries" => "thousand",527 "connection_retry_sleep" => "sleepy",528 "max_wait_until_ready" => 42,529 "color" => true530 )531 )532 .and_return(runner)533 verifier.call(hostname: "win.dows", port: 123)534 end535 it "constructs a Inspec::Runner using transport config data(host and port)" do536 config[:host] = "192.168.56.40"537 config[:port] = 22538 expect(Inspec::Runner).to receive(:new)539 .with(540 hash_including(541 "backend" => "winrm",542 "host" => "192.168.56.40",543 "port" => 22544 )545 )546 .and_return(runner)547 verifier.call(hostname: "win.dows", port: 123)548 end549 end550 context "with an exec transport" do551 let(:transport) do552 Kitchen::Transport::Exec.new553 end554 let(:runner) do555 instance_double("Inspec::Runner")556 end557 before do558 allow(runner).to receive(:add_target)559 allow(runner).to receive(:run).and_return 0560 end561 it "constructs a Inspec::Runner using transport config data and state" do562 expect(Inspec::Runner).to receive(:new)563 .with(564 hash_including(565 "backend" => "local",566 "logger" => logger,567 "color" => true568 )569 )570 .and_return(runner)571 verifier.call({})572 end...
runner.rb
Source:runner.rb
...21 # and then call the run method:22 #23 # ```24 # r = Inspec::Runner.new()25 # r.add_target("/path/to/some/profile")26 # r.add_target("http://url/to/some/profile")27 # r.run28 # ```29 #30 class Runner # rubocop:disable Metrics/ClassLength31 extend Forwardable32 def_delegator :@test_collector, :report33 attr_reader :backend, :rules, :attributes34 def initialize(conf = {})35 @rules = []36 @conf = conf.dup37 @conf[:logger] ||= Logger.new(nil)38 @target_profiles = []39 @controls = @conf[:controls] || []40 @ignore_supports = @conf[:ignore_supports]41 @create_lockfile = @conf[:create_lockfile]42 @cache = Inspec::Cache.new(@conf[:cache])43 @test_collector = @conf.delete(:test_collector) || begin44 require 'inspec/runner_rspec'45 RunnerRspec.new(@conf)46 end47 # list of profile attributes48 @attributes = []49 load_attributes(@conf)50 configure_transport51 end52 def tests53 @test_collector.tests54 end55 def configure_transport56 @backend = Inspec::Backend.create(@conf)57 @test_collector.backend = @backend58 end59 def reset60 @test_collector.reset61 @target_profiles.each do |profile|62 profile.runner_context.rules = {}63 end64 @rules = []65 end66 def load67 all_controls = []68 @target_profiles.each do |profile|69 @test_collector.add_profile(profile)70 write_lockfile(profile) if @create_lockfile71 profile.locked_dependencies72 profile_context = profile.load_libraries73 profile_context.dependencies.list.values.each do |requirement|74 @test_collector.add_profile(requirement.profile)75 end76 @attributes |= profile.runner_context.attributes77 all_controls += profile.collect_tests78 end79 all_controls.each do |rule|80 register_rule(rule) unless rule.nil?81 end82 end83 def run(with = nil)84 Inspec::Log.debug "Starting run with targets: #{@target_profiles.map(&:to_s)}"85 load86 run_tests(with)87 end88 def write_lockfile(profile)89 return false if !profile.writable?90 if profile.lockfile_exists?91 Inspec::Log.debug "Using existing lockfile #{profile.lockfile_path}"92 else93 Inspec::Log.debug "Creating lockfile: #{profile.lockfile_path}"94 lockfile = profile.generate_lockfile95 File.write(profile.lockfile_path, lockfile.to_yaml)96 end97 end98 def run_tests(with = nil)99 @test_collector.run(with)100 end101 # determine all attributes before the execution, fetch data from secrets backend102 def load_attributes(options)103 options[:attributes] ||= {}104 secrets_targets = options[:attrs]105 return options[:attributes] if secrets_targets.nil?106 secrets_targets.each do |target|107 secrets = Inspec::SecretsBackend.resolve(target)108 if secrets.nil?109 raise Inspec::Exceptions::SecretsBackendNotFound,110 "Unable to find a parser for attributes file #{target}. " \111 'Check to make sure the file exists and has the appropriate extension.'112 end113 next if secrets.attributes.nil?114 options[:attributes].merge!(secrets.attributes)115 end116 options[:attributes]117 end118 #119 # add_target allows the user to add a target whose tests will be120 # run when the user calls the run method.121 #122 # A target is a path or URL that points to a profile. Using this123 # target we generate a Profile and a ProfileContext. The content124 # (libraries, tests, and attributes) from the Profile are loaded125 # into the ProfileContext.126 #127 # If the profile depends on other profiles, those profiles will be128 # loaded on-demand when include_content or required_content are129 # called using similar code in Inspec::DSL.130 #131 # Once the we've loaded all of the tests files in the profile, we132 # query the profile for the full list of rules. Those rules are133 # registered with the @test_collector which is ultimately134 # responsible for actually running the tests.135 #136 # TODO: Deduplicate/clarify the loading code that exists in here,137 # the ProfileContext, the Profile, and Inspec::DSL138 #139 # @params target [String] A path or URL to a profile or raw test.140 # @params _opts [Hash] Unused, but still here to avoid breaking kitchen-inspec141 #142 # @eturns [Inspec::ProfileContext]143 #144 def add_target(target, _opts = [])145 profile = Inspec::Profile.for_target(target,146 cache: @cache,147 backend: @backend,148 controls: @controls,149 attributes: @conf[:attributes])150 raise "Could not resolve #{target} to valid input." if profile.nil?151 @target_profiles << profile if supports_profile?(profile)152 end153 def supports_profile?(profile)154 return true if @ignore_supports155 if !profile.supports_runtime?156 raise 'This profile requires InSpec version '\157 "#{profile.metadata.inspec_requirement}. You are running "\158 "InSpec v#{Inspec::VERSION}.\n"159 end160 if !profile.supports_os?161 raise "This OS/platform (#{@backend.os[:name]}) is not supported by this profile."162 end163 true164 end165 # In some places we read the rules off of the runner, in other166 # places we read it off of the profile context. To keep the API's167 # the same, we provide an #all_rules method here as well.168 def all_rules169 @rules170 end171 def register_rules(ctx)172 new_tests = false173 ctx.rules.each do |rule_id, rule|174 next if block_given? && !(yield rule_id, rule)175 new_tests = true176 register_rule(rule)177 end178 new_tests179 end180 def eval_with_virtual_profile(command)181 require 'fetchers/mock'182 add_target({ 'inspec.yml' => 'name: inspec-shell' })183 our_profile = @target_profiles.first184 ctx = our_profile.runner_context185 ctx.load(command)186 end187 private188 def block_source_info(block)189 return {} if block.nil? || !block.respond_to?(:source_location)190 opts = {}191 file_path, line = block.source_location192 opts['file_path'] = file_path193 opts['line_number'] = line194 opts195 end196 def get_check_example(method_name, arg, block)...
add_target
Using AI Code Generation
1Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')2Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')3Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')4Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')5Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')6Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')7Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')8Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')9Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')10Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')11Inspec::Plugins::CLI.add_target('my_target', 'My Target', 'My Target Description')
add_target
Using AI Code Generation
1target = Inspec::Target.new('/tmp/1.rb')2Inspec::Inspec.add_target(target)3target = Inspec::Target.new('/tmp/1.rb')4Inspec::ProfileContext.add_target(target)5target = Inspec::Target.new('/tmp/2.rb')6Inspec::Inspec.add_target(target)7target = Inspec::Target.new('/tmp/2.rb')8Inspec::ProfileContext.add_target(target)9target = Inspec::Target.new('/tmp/3.rb')10Inspec::Inspec.add_target(target)11target = Inspec::Target.new('/tmp/3.rb')12Inspec::ProfileContext.add_target(target)13target = Inspec::Target.new('/tmp/4.rb')14Inspec::Inspec.add_target(target)15target = Inspec::Target.new('/tmp/4.rb')16Inspec::ProfileContext.add_target(target)17target = Inspec::Target.new('/tmp/5.rb')18Inspec::Inspec.add_target(target)19target = Inspec::Target.new('/tmp/5.rb')20Inspec::ProfileContext.add_target(target)21target = Inspec::Target.new('/tmp/6.rb')22Inspec::Inspec.add_target(target)23target = Inspec::Target.new('/tmp/6.rb')
add_target
Using AI Code Generation
1inspec.add_target('localhost')2Profile: tests from 1.rb (tests from 1.rb)3Version: (not specified)4inspec> command('uname -a').stdout5inspec> file('/etc/os-release').content
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!!