Best Inspec_ruby code snippet using Inspec.backend
helpers.rb
Source:helpers.rb
...109 begin110 # https://www.rubydoc.info/gems/train/0.14.1/Train%2FTransports%2FLocal%2FConnection:run_command111 # Train.Plugins.Transport.Connection train.connection.run_command112 Timeout.timeout(sec_timeout) do113 @my_result = JSON.parse(backend::backend.run_command(ps_cmd).stdout) if type == 'json'114 @my_result =YAML.safe_load(backend::backend.run_command(ps_cmd).stdout) if type == 'yaml'115 end116 rescue => e117 Inspec::Log.debug("`#{e.message}`, target may be rebooting after highstate. Remaining retries: #{max_retries - retries}")118 puts("`#{e.message}`, target may be rebooting after highstate. Remaining retries: #{max_retries - retries}")119 if (retries += 1) < max_retries120 retry121 else122 begin123 backend::backend.run_command('whoami').stdout124 rescue => e125 msg = "Unable to get whoami from backend::backend.run_command: #{e.message}"126 puts(msg)127 Inspec::Log.debug(msg)128 end129 if OS.windows?130 pwsh_cmd = '$test_path=".kitchen/kitchen-vagrant/$(Get-ChildItem -Path .kitchen/logs/*.log | Where-Object {$_.Name -ne "kitchen.log"} | Sort-Object -Property @{Expression = {$_.LastWriteTime}; Descending = $True} | Select-Object -Property BaseName -First 1 -expandproperty BaseName)"; Set-Location -Path $test_path; $test_vagrantfile = "$test_path/Vagrantfile"; Set-Content -Path $test_vagrantfile -Value (get-content -Path $test_vagrantfile | Select-String -Pattern "vagrant_vb_guest.rb" -NotMatch); Set-Location -Path $test_path; vagrant winrm'131 cmd = "powershell -command '#{pwsh_cmd}'"132 else133 cmd = "cd .kitchen/kitchen-vagrant/$(ls -t .kitchen/logs/*.log | grep -v .kitchen/logs/kitchen.log | head -n1 | cut -f3 -d/ | awk -F. '{print $1}'); vagrant winrm"134 end135 if system( cmd )136 puts('Successfully connected via `vagrant winrm`')137 Inspec::Log.debug('Successfully connected via `vagrant winrm`')138 else139 msg = 'Failed to connect via `vagrant winrm`'...
audit_report_spec.rb
Source:audit_report_spec.rb
...21require_relative '../../../files/default/handler/audit_report'22require_relative '../../data/mock'23describe 'Chef::Handler::AuditReport methods' do24 let(:mynode) { Chef::Node.new }25 def set_inspec_backend_cache(status = false)26 mynode.default['audit']['inspec_backend_cache'] = status27 allow(@audit_report).to receive(:node).and_return(mynode)28 end29 before :each do30 @audit_report = Chef::Handler::AuditReport.new31 end32 describe ReportHelpers do33 let(:helpers) { Class.new { extend ReportHelpers } }34 before :each do35 @interval = 144036 @interval_time = 144037 interval_enabled = true38 write_to_file = false39 @helpers.create_timestamp_file40 end41 describe 'report when interval settings are set to default (disabled)' do42 interval_enabled = false43 it 'returns true for check_interval_settings' do44 status = @audit_report.check_interval_settings(@interval, interval_enabled, @interval_time)45 expect(status).to eq(true)46 end47 end48 describe 'report when interval settings are enabled' do49 interval_enabled = true50 it 'returns false for check_interval_settings' do51 status = @audit_report.check_interval_settings(@interval, interval_enabled, @interval_time)52 expect(status).to eq(false)53 end54 end55 end56 describe 'validate_inspec_version method' do57 before :each do58 require 'inspec'59 end60 it 'inspec min version fail' do61 stub_const('Inspec::VERSION', '1.20.0')62 expect { @audit_report.validate_inspec_version }63 .to raise_error(RuntimeError)64 .with_message('This audit cookbook version requires InSpec 1.25.1 or newer, aborting compliance scan...')65 end66 it 'inspec version warn for backend_cache' do67 stub_const('Inspec::VERSION', '1.46.0')68 set_inspec_backend_cache(true)69 expect(Chef::Log).to receive(:warn)70 .with('inspec_backend_cache requires InSpec version >= 1.47.0')71 .and_return('captured')72 expect(@audit_report.validate_inspec_version).to eq('captured')73 end74 it 'inspec version passes all requirements' do75 stub_const('Inspec::VERSION', '1.47.0')76 set_inspec_backend_cache(true)77 expect(Chef::Log).to_not receive(:warn)78 expect { @audit_report.validate_inspec_version }.to_not raise_error79 end80 end81 describe 'get_opts method' do82 it 'sets the format to json-min' do83 format = 'json-min'84 quiet = true85 set_inspec_backend_cache(true)86 opts = @audit_report.get_opts(format, quiet, {})87 expect(opts['report']).to be true88 expect(opts['format']).to eq('json-min')89 expect(opts['output']).to eq('/dev/null')90 expect(opts['logger']).to eq(Chef::Log)91 expect(opts[:waiver_file]).to eq([])92 expect(opts[:backend_cache]).to be true93 expect(opts[:attributes].empty?).to be true94 end95 it 'sets the format to json' do96 allow(File).to receive(:exist?).with('/tmp/exists.yaml').and_return(true)97 allow(File).to receive(:exist?).with('/tmp/missing.yaml').and_return(false)98 format = 'json'99 quiet = true100 set_inspec_backend_cache(true)101 mynode.default['audit']['waiver_file'] = ['/tmp/exists.yaml', '/tmp/missing.yaml']102 opts = @audit_report.get_opts(format, quiet, {})103 expect(opts['report']).to be true104 expect(opts['format']).to eq('json')105 expect(opts['output']).to eq('/dev/null')106 expect(opts['logger']).to eq(Chef::Log)107 expect(opts[:waiver_file]).to eq(['/tmp/exists.yaml'])108 expect(opts[:backend_cache]).to be true109 expect(opts[:attributes].empty?).to be true110 end111 it 'sets the backend_cache to false' do112 format = 'json'113 quiet = true114 set_inspec_backend_cache(false)115 opts = @audit_report.get_opts(format, quiet, {})116 expect(opts['report']).to be true117 expect(opts['format']).to eq('json')118 expect(opts['output']).to eq('/dev/null')119 expect(opts['logger']).to eq(Chef::Log)120 expect(opts[:backend_cache]).to be false121 expect(opts[:attributes].empty?).to be true122 end123 it 'sets the attributes' do124 format = 'json-min'125 quiet = true126 attributes = {127 first: 'value1',128 second: 'value2',129 }130 set_inspec_backend_cache(true)131 opts = @audit_report.get_opts(format, quiet, attributes)132 expect(opts[:attributes][:first]).to eq('value1')133 expect(opts[:attributes][:second]).to eq('value2')134 end135 end136 describe 'call' do137 it 'given a profile, returns a json report' do138 opts = { 'report' => true, 'format' => 'json', 'output' => '/dev/null' }139 path = File.expand_path('../../data/mock_profile.rb', __dir__)140 profiles = [{ 'name': 'example', 'path': path }]141 # we circumvent the default load mechanisms, therefore we have to require inspec142 require 'inspec'143 report = @audit_report.call(opts, profiles)144 expected_report = /^.*profiles.*controls.*version.*statistics.*duration.*controls.*/145 expect(report.to_json).to match(expected_report)146 end147 it 'given a profile, returns a json-min report' do148 require 'inspec'149 opts = { 'report' => true, 'format' => 'json-min', 'output' => '/dev/null' }150 path = File.expand_path('../../data/mock_profile.rb', __dir__)151 profiles = [{ 'name': 'example', 'path': path }]152 # we circumvent the default load mechanisms, therefore we have to require inspec153 require 'inspec'154 report = @audit_report.call(opts, profiles)155 expect(report[:controls].length).to eq(2)156 end157 it 'given an unfetchable profile, returns a min failed report' do158 require 'inspec'159 opts = { 'report' => true, 'format' => 'json-automate', 'output' => '/dev/null' }160 profiles = [{ 'name': 'example', 'path': '/tmp/missing-in-action-profile' }]161 # we circumvent the default load mechanisms, therefore we have to require inspec162 require 'inspec'163 report = @audit_report.call(opts, profiles)164 expect(report[:profiles].length).to eq(0)165 expect(report[:status]).to eq('failed')166 expect(report[:platform]).to eq({ 'name': 'unknown', 'release': 'unknown' })167 expected_status_message = /^Cannot fetch all profiles.*does not exist$/168 expect(report[:status_message]).to match(expected_status_message)169 end170 it 'given a bad InSpec config, returns a min failed report' do171 require 'inspec'172 opts = { 'backend' => 'ssh', 'report' => true, 'format' => 'json-automate', 'output' => '/dev/null' }173 path = File.expand_path('../../data/mock_profile.rb', __dir__)174 profiles = [{ 'name': 'example', 'path': path }]175 # we circumvent the default load mechanisms, therefore we have to require inspec176 require 'inspec'177 report = @audit_report.call(opts, profiles)178 expect(report[:profiles].length).to eq(0)179 expect(report[:status]).to eq('failed')180 expect(report[:platform]).to eq({ 'name': 'unknown', 'release': 'unknown' })181 expected_status_message = /^Client error. can't connect.*/182 expect(report[:status_message]).to match(expected_status_message)183 end184 end185end...
erb_helpers.rb
Source:erb_helpers.rb
...11 #12 # @param [String] cmd Command to execute13 # @return [Train::Extras::CommandResult] Command result (.stdout/.stderr/.exit_status)14 def remote_command(cmd)15 runner.backend.backend.run_command(cmd)16 end17 # Retrieve remote file contents.18 #19 # @param [String] remote_file Path to the remote file20 # @return [String] Contents of the file21 def remote_file_content(remote_file)22 runner.backend.backend.file(remote_file).content23 end24 # Allow access to all InSpec resources from the report.25 #26 # @return [Inspec::Backend] The InSpec backend27 def inspec_resource28 runner.backend29 end30 # Return InSpec OS resource results.31 #32 # @return [Class] Look into documentation for properties (.arch/.family/.name/...)33 # @see https://github.com/inspec/inspec/blob/master/lib/inspec/resources/os.rb34 def os35 runner.backend.os36 end37 # Return InSpec SysInfo resource results.38 #39 # @return [Class] Look into documentation for properteis (.domain/.fqdn/.hostname/.ip_address/.model/...)40 # @see https://github.com/inspec/inspec/blob/master/lib/inspec/resources/sys_info.rb41 def sys_info42 runner.backend.sys_info43 end44 # Return if all results of a control have passed/skipped/waived.45 #46 # @param [Hash] control Data of a control run47 # @return [Boolean] If all passed checks48 def control_passed?(control)49 control[:results].any? { |result| result[:status] == "failed" }50 end51 # Map InSpec status to cleartext52 #53 # @param [String] inspec_status One of the valid InSpec result status.54 # @return [Strint] "ok"/"not ok" depending on status55 def status_to_pass(inspec_status)56 case inspec_status...
backend
Using AI Code Generation
1 describe file('/etc/passwd') do2 it { should exist }3 describe file('/etc/passwd') do4 it { should exist }5 describe file('/etc/passwd') do6 it { should exist }7 describe file('/etc/passwd') do8 it { should exist }9 describe file('/etc/passwd') do10 it { should exist }11 describe file('/etc/passwd') do12 it { should exist }13 describe file('/etc/passwd') do14 it { should exist }15 describe file('/etc/passwd') do16 it { should exist }17 describe file('/etc/passwd') do18 it { should exist }
backend
Using AI Code Generation
1describe inspec.command('ls -al /') do2 its('stdout') { should match /root/ }3 its('stderr') { should eq '' }4 its('exit_status') { should eq 0 }5 its('command('ls -al /').stdout') { should match /root/ }6 its('command('ls -al /').stderr') { should eq '' }7 its('command('ls -al /').exit_status') { should eq 0 }8 it { should match /root/ }9describe command('ls -al /') do10 its('stdout') { should match /root/ }11 its('stderr') { should eq '' }12 its('exit_status') { should eq 0 }13 its('command('ls -al /').stdout') { should match /root/ }14 its('command('ls -al /').stderr') { should eq '' }15 its('command('ls -al /').exit_status') { should eq 0 }16 it { should match /root/ }17describe command('ls -al /') do18 its('stdout') { should match /root/ }19 its('stderr') { should eq '' }20 its('exit_status') { should eq 0 }21 its('command('ls -al /
backend
Using AI Code Generation
1result = inspec.command('ls -la /etc').stdout2result = inspec.command('ls -la /etc').stdout3result = inspec.command('ls -la /etc').stdout4result = inspec.command('ls -la /etc').stdout5result = inspec.command('ls -la /etc').stdout6result = inspec.command('ls -la /etc').stdout7result = inspec.command('ls -la /etc').stdout8result = inspec.command('ls -la /etc').stdout9result = inspec.command('ls -la /etc').stdout10result = inspec.command('ls -la /etc').stdout11result = inspec.command('ls -la /etc').stdout12result = inspec.command('ls -la /etc').stdout
backend
Using AI Code Generation
1puts inspec.backend.run_command('ls').stdout2puts inspec.backend.run_command('cat /etc/os-release').stdout3puts inspec.backend.run_command('cat /etc/os-release').exit_status4puts inspec.backend.run_command('cat /etc/os-release').stderr5puts inspec.backend.run_command('cat /etc/os-release').exit_status6puts inspec.backend.run_command('cat /etc/os-release').exit_signal7puts inspec.backend.run_command('cat /etc/os-release').timeout?8puts inspec.backend.run_command('cat /etc/os-release').command9puts inspec.backend.run_command('cat /etc/os-release').start_time10puts inspec.backend.run_command('cat /etc/os-release').end_time11puts inspec.backend.run_command('cat /etc/os-release').duration12puts inspec.backend.run_command('cat /etc/os-release').pid13puts inspec.backend.run_command('cat /etc/os-release').stdout14puts inspec.backend.run_command('cat /etc/os-release').stderr15puts inspec.backend.run_command('cat /etc/os-release').exit_status16puts inspec.backend.run_command('cat /etc/os-release').exit_signal
backend
Using AI Code Generation
1resource = Inspec::Resources::File.new(backend, '/etc/hosts')2control = Inspec::Control.new(backend, 'test')3profile = Inspec::Profile.new(backend, 'test')4runner = Inspec::Runner.new(backend)5reporter = Inspec::Reporter::Json.new(backend)6reporter = Inspec::Reporter::Json.new(backend)
backend
Using AI Code Generation
1puts Inspec.backend.command('hostname').stdout2puts JSON.parse(Inspec.backend.command('hostname').stdout)3puts JSON.parse(Inspec.backend.command('hostname').stdout)['hostname']4puts JSON.parse(Inspec.backend.command('hostname').stdout)['hostname']5puts JSON.parse(Inspec.backend.command('hostname').stdout)['hostname'].upcase6puts JSON.parse(Inspec.backend.command('hostname').stdout)['hostname'].upcase.downcase7puts JSON.parse(Inspec.backend.command('hostname').stdout)['hostname'].upcase.downcase.reverse
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!!