Best Inspec_ruby code snippet using InspecPlugins.Habitat.build_hart
profile.rb
Source:profile.rb
...25 'or does not exist.')26 end27 duplicated_profile = duplicate_profile(@path, working_dir)28 prepare_profile!(duplicated_profile)29 hart_file = build_hart(working_dir, habitat_config)30 logger.debug("Copying artifact to #{output_dir}...")31 destination = File.join(output_dir, File.basename(hart_file))32 FileUtils.cp(hart_file, destination)33 logger.info("Habitat artifact '#{@destination}' created.")34 destination35 rescue => e36 logger.debug(e.backtrace.join("\n"))37 exit_with_error('Unable to create Habitat artifact.')38 ensure39 if Dir.exist?(working_dir)40 logger.debug("Deleting working directory #{working_dir}")41 FileUtils.rm_rf(working_dir)42 end43 end44 def setup(profile = profile_from_path(@path))45 path = profile.root_path46 logger.debug("Setting up #{path} for Habitat...")47 plan_file = File.join(path, 'habitat', 'plan.sh')48 logger.info("Generating Habitat plan at #{plan_file}...")49 vars = {50 profile: profile,51 habitat_origin: read_habitat_config['origin'],52 }53 create_file_from_template(plan_file, 'plan.sh.erb', vars)54 run_hook_file = File.join(path, 'habitat', 'hooks', 'run')55 logger.info("Generating a Habitat run hook at #{run_hook_file}...")56 create_file_from_template(run_hook_file, 'hooks/run.erb')57 default_toml = File.join(path, 'habitat', 'default.toml')58 logger.info("Generating a Habitat default.toml at #{default_toml}...")59 create_file_from_template(default_toml, 'default.toml.erb')60 config = File.join(path, 'habitat', 'config', 'inspec_exec_config.json')61 logger.info("Generating #{config} for `inspec exec`...")62 create_file_from_template(config, 'config/inspec_exec_config.json.erb')63 end64 def upload65 habitat_config = read_habitat_config66 if habitat_config['auth_token'].nil?67 exit_with_error(68 'Unable to determine Habitat auth token for uploading.',69 'Run `hab setup` or set the HAB_AUTH_TOKEN environment variable.',70 )71 end72 # Run create command to create habitat artifact73 hart = create74 logger.info("Uploading Habitat artifact #{hart}...")75 upload_hart(hart, habitat_config)76 logger.info("Habitat artifact #{hart} uploaded.")77 rescue => e78 logger.debug(e.backtrace.join("\n"))79 exit_with_error('Unable to upload Habitat artifact.')80 end81 private82 def create_working_dir83 working_dir = Dir.mktmpdir84 logger.debug("Generated working directory #{working_dir}")85 working_dir86 end87 def duplicate_profile(path, working_dir)88 profile = profile_from_path(path)89 copy_profile_to_working_dir(profile, working_dir)90 profile_from_path(working_dir)91 end92 def prepare_profile!(profile)93 vendored_profile = vendor_profile_dependencies!(profile)94 verify_profile(vendored_profile)95 setup(vendored_profile)96 end97 def profile_from_path(path)98 Inspec::Profile.for_target(99 path,100 backend: Inspec::Backend.create(Inspec::Config.mock),101 )102 end103 def copy_profile_to_working_dir(profile, working_dir)104 logger.debug('Copying profile contents to the working directory...')105 profile.files.each do |profile_file|106 next if File.extname(profile_file) == '.hart'107 src = File.join(profile.root_path, profile_file)108 dst = File.join(working_dir, profile_file)109 if File.directory?(profile_file)110 logger.debug("Creating directory #{dst}")111 FileUtils.mkdir_p(dst)112 else113 logger.debug("Copying file #{src} to #{dst}")114 FileUtils.cp_r(src, dst)115 end116 end117 end118 def verify_profile(profile)119 logger.debug('Checking to see if the profile is valid...')120 unless profile.check[:summary][:valid]121 exit_with_error('Profile check failed. Please fix the profile ' \122 'before creating a Habitat artifact.')123 end124 logger.debug('Profile is valid.')125 end126 def vendor_profile_dependencies!(profile)127 profile_vendor = Inspec::ProfileVendor.new(profile.root_path)128 if profile_vendor.lockfile.exist? && profile_vendor.cache_path.exist?129 logger.debug("Profile's dependencies are already vendored, skipping " \130 'vendor process.')131 else132 logger.debug("Vendoring the profile's dependencies...")133 profile_vendor.vendor!134 logger.debug('Ensuring all vendored content has read permissions...')135 profile_vendor.make_readable136 end137 # Return new profile since it has changed138 Inspec::Profile.for_target(139 profile.root_path,140 backend: Inspec::Backend.create(Inspec::Config.mock),141 )142 end143 def verify_habitat_setup(habitat_config)144 logger.debug('Checking to see if Habitat is installed...')145 cmd = Mixlib::ShellOut.new('hab --version')146 cmd.run_command147 if cmd.error?148 exit_with_error('Unable to run Habitat commands.', cmd.stderr)149 end150 if habitat_config['origin'].nil?151 exit_with_error(152 'Unable to determine Habitat origin name.',153 'Run `hab setup` or set the HAB_ORIGIN environment variable.',154 )155 end156 end157 def create_file_from_template(file, template, vars = {})158 FileUtils.mkdir_p(File.dirname(file))159 template_path = File.join(__dir__, '../../templates/habitat', template)160 contents = ERB.new(File.read(template_path))161 .result(OpenStruct.new(vars).instance_eval { binding })162 File.write(file, contents)163 end164 def build_hart(working_dir, habitat_config)165 logger.debug('Building our Habitat artifact...')166 env = {167 'TERM' => 'vt100',168 'HAB_ORIGIN' => habitat_config['origin'],169 'HAB_NONINTERACTIVE' => 'true',170 }171 env['RUST_LOG'] = 'debug' if logger.level == :debug172 # TODO: Would love to use Mixlib::ShellOut here, but it doesn't173 # seem to preserve the STDIN tty, and docker gets angry.174 Dir.chdir(working_dir) do175 unless system(env, 'hab pkg build .')176 exit_with_error('Unable to build the Habitat artifact.')177 end178 end...
profile_test.rb
Source:profile_test.rb
...47 def test_create48 file_count = Dir.glob(File.join(@test_profile_path, "**/*")).count49 @hab_profile.stub :read_habitat_config, @mock_hab_config do50 @hab_profile.stub :verify_habitat_setup, nil do51 @hab_profile.stub :build_hart, @fake_hart_file do52 @hab_profile.create53 end54 end55 end56 # It should not modify target profile57 new_file_count = Dir.glob(File.join(@test_profile_path, "**/*")).count58 assert_equal new_file_count, file_count59 # It should create 1 Habitat artifact60 output_files = Dir.glob(File.join(@output_dir, "**/*"))61 assert_equal 1, output_files.count62 assert_equal "fake-hart.hart", File.basename(output_files.first)63 end64 def test_create_rasies_if_habitat_is_not_installed65 cmd = Minitest::Mock.new66 cmd.expect(:error?, true)67 cmd.expect(:run_command, nil)68 Mixlib::ShellOut.stub :new, cmd, "hab --version" do69 assert_raises(SystemExit) { @hab_profile.create }70 # TODO: Figure out how to capture and validate `Inspec::Log.error`71 end72 cmd.verify73 end74 def test_upload75 @hab_profile.stub :read_habitat_config, @mock_hab_config do76 @hab_profile.stub :create, @fake_hart_file do77 @hab_profile.stub :upload_hart, nil do78 @hab_profile.upload79 # TODO: Figure out how to capture and validate `Inspec::Log.error`80 end81 end82 end83 end84 def test_upload_raises_if_no_habitat_auth_token_is_found85 @hab_profile.stub :read_habitat_config, {} do86 assert_raises(SystemExit) { @hab_profile.upload }87 # TODO: Figure out how to capture and validate `Inspec::Log.error`88 end89 end90 def test_create_working_dir91 Dir.stub :mktmpdir, "/tmp/fakedir" do92 assert_equal "/tmp/fakedir", @hab_profile.send(:create_working_dir)93 end94 end95 def test_duplicate_profile96 current_profile = @test_profile97 duplicated_profile = @hab_profile.send(:duplicate_profile,98 @test_profile_path,99 @tmpdir)100 assert duplicated_profile.is_a?(Inspec::Profile)101 assert duplicated_profile.sha256 == current_profile.sha256.to_s102 refute_same duplicated_profile.root_path, current_profile.root_path103 end104 def test_profile_from_path105 profile = @hab_profile.send(:profile_from_path, @test_profile_path)106 assert profile.is_a?(Inspec::Profile)107 end108 def test_copy_profile_to_working_dir109 duplicated_profile = @hab_profile.send(:duplicate_profile,110 @test_profile_path,111 @tmpdir)112 dst = File.join(@tmpdir, "working_dir")113 FileUtils.mkdir_p(dst)114 @hab_profile.send(:copy_profile_to_working_dir, duplicated_profile, dst)115 expected_files = %w{116 README.md117 inspec.yml118 example.rb119 }120 actual_files = Dir.glob(File.join(dst, "**/*")).map do |path|121 next unless File.file?(path)122 File.basename(path)123 end.compact124 assert(actual_files.sort == expected_files.sort)125 end126 def test_verify_profile_raises_if_profile_is_not_valid127 bad_profile_path = File.join(@tmpdir, "bad_profile")128 FileUtils.mkdir_p(File.join(bad_profile_path))129 FileUtils.touch(File.join(bad_profile_path, "inspec.yml"))130 bad_profile = Inspec::Profile.for_target(131 bad_profile_path,132 backend: Inspec::Backend.create(Inspec::Config.mock)133 )134 assert_raises(SystemExit) { @hab_profile.send(:verify_profile, bad_profile) }135 # TODO: Figure out how to capture and validate `Inspec::Log.error`136 end137 def test_vendor_profile_dependencies_does_not_vendor_if_already_vendored138 mock_lock_file = Minitest::Mock.new139 mock_lock_file.expect(:exist?, true)140 mock_cache_path = Minitest::Mock.new141 mock_cache_path.expect(:exist?, true)142 mock = Minitest::Mock.new143 mock.expect(:lockfile, mock_lock_file)144 mock.expect(:cache_path, mock_cache_path)145 Inspec::ProfileVendor.stub :new, mock do146 new_profile = @hab_profile.send(:vendor_profile_dependencies!,147 @test_profile)148 assert new_profile.is_a?(Inspec::Profile)149 end150 end151 def test_vendor_profile_dependencies152 mock_lock_file = Minitest::Mock.new153 mock_lock_file.expect(:exist?, false)154 mock = Minitest::Mock.new155 mock.expect(:lockfile, mock_lock_file)156 mock.expect(:vendor!, nil)157 mock.expect(:make_readable, nil)158 Inspec::ProfileVendor.stub :new, mock do159 new_profile = @hab_profile.send(:vendor_profile_dependencies!,160 @test_profile)161 assert new_profile.is_a?(Inspec::Profile)162 end163 mock.verify164 end165 def test_verify_habitat_setup_raises_if_hab_version_errors166 mock = Minitest::Mock.new167 mock.expect(:run_command, nil)168 mock.expect(:error?, true)169 mock.expect(:stderr, "This would be an error message")170 Mixlib::ShellOut.stub(:new, mock) do171 assert_raises(SystemExit) { @hab_profile.send(:verify_habitat_setup, {}) }172 # TODO: Figure out how to capture and validate `Inspec::Log.error`173 end174 mock.verify175 end176 def test_verify_habitat_setup_raises_if_not_habitat_origin177 mock = Minitest::Mock.new178 mock.expect(:run_command, nil)179 mock.expect(:error?, false)180 Mixlib::ShellOut.stub(:new, mock) do181 assert_raises(SystemExit) { @hab_profile.send(:verify_habitat_setup, {}) }182 # TODO: Figure out how to capture and validate `Inspec::Log.error`183 end184 mock.verify185 end186 # TODO: Figure out how to stub system()187 # def test_build_hart188 # end189 def test_upload_hart_raises_if_hab_pkg_upload_fails190 mock = Minitest::Mock.new191 mock.expect(:run_command, nil)192 mock.expect(:error?, true)193 mock.expect(:stdout, "This would contain output from `hab`")194 mock.expect(:stderr, "This would be an error message")195 Mixlib::ShellOut.stub(:new, mock) do196 assert_raises(SystemExit) { @hab_profile.send(:upload_hart, @fake_hart_file, {}) }197 # TODO: Figure out how to capture and validate `Inspec::Log.error`198 end199 end200end...
build_hart
Using AI Code Generation
1 class Habitat < Inspec.plugin(2)2 def build_hart(path, options)3 def build_hart(path, options)4 def build_hart(path, options = {})5 def build_hart(path, options = {})6 def build_hart(path, options = {})7 def build_hart(path, options = {})8 def build_hart(path, options = {})
build_hart
Using AI Code Generation
1describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do2 it { should exist }3describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do4 it { should exist }5describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do6 it { should exist }7describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do8 it { should exist }9describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do10 it { should exist }11describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do12 it { should exist }13describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do14 it { should exist }15describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do16 it { should exist }17describe habitat.build_hart('my_app', '0.1.0', 'x86_64-linux') do18 it { should exist }
build_hart
Using AI Code Generation
1describe habitat.build_hart('someorigin/somepackage') do2 its('version') { should eq '1.0.0' }3describe habitat.build_hart('someorigin/somepackage', '1.0.0') do4 its('version') { should eq '1.0.0' }5describe habitat.build_hart('someorigin/somepackage', '1.0.0', 'somedir') do6 its('version') { should eq '1.0.0' }7describe habitat.build_hart('someorigin/somepackage', '1.0.0', 'somedir', 'somechannel') do8 its('version') { should eq '1.0.0' }9describe habitat.build_hart('someorigin/somepackage', '1.0.0', 'somedir', 'somechannel', 'sometarget') do10 its('version') { should eq '1.0.0' }11describe habitat.build_hart('someorigin/somepackage', '1.0.0', 'somedir', 'somechannel', 'sometarget', 'somesup') do12 its('version') { should eq '1.0.0' }13describe habitat.build_hart('someorigin/somepackage', '1.0.0', 'somedir', 'somechannel', 'sometarget', 'somesup', 'somepath') do14 its('version') { should eq '1.0.0' }
build_hart
Using AI Code Generation
1InspecPlugins::Habitat::build_hart('/hab/pkgs/core/redis/3.2.1/20170514150850', '/tmp/redis_hart')2InspecPlugins::Habitat::build_hart('/hab/pkgs/core/redis/3.2.1/20170514150850', '/tmp/redis_hart')3InspecPlugins::Habitat::build_hart('/hab/pkgs/core/redis/3.2.1/20170514150850', '/tmp/redis_hart')4InspecPlugins::Habitat::build_hart('/hab/pkgs/core/redis/3.2.1/20170514150850', '/tmp/redis_hart')5InspecPlugins::Habitat::build_hart('/hab/pkgs/core/redis/3.2.1/20170514150850', '/tmp/redis_hart')6InspecPlugins::Habitat::build_hart('/hab/pkgs/core/redis/3.2.1/20170514150850', '/tmp/redis_hart')
build_hart
Using AI Code Generation
1plugin_lib_path = File.expand_path( File.join( File.dirname(__FILE__), '..', 'lib' ) )2$LOAD_PATH.unshift(plugin_lib_path)3Traceback (most recent call last):
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!!