How to use source_reader method of Inspec Package

Best Inspec_ruby code snippet using Inspec.source_reader

profile.rb

Source:profile.rb Github

copy

Full Screen

...6require 'digest'7require 'inspec/polyfill'8require 'inspec/cached_fetcher'9require 'inspec/file_provider'10require 'inspec/source_reader'11require 'inspec/metadata'12require 'inspec/backend'13require 'inspec/rule'14require 'inspec/log'15require 'inspec/profile_context'16require 'inspec/runtime_profile'17require 'inspec/method_source'18require 'inspec/dependencies/cache'19require 'inspec/dependencies/lockfile'20require 'inspec/dependencies/dependency_set'21module Inspec22 class Profile # rubocop:disable Metrics/ClassLength23 extend Forwardable24 def self.resolve_target(target, cache)25 Inspec::Log.debug "Resolve #{target} into cache #{cache.path}"26 Inspec::CachedFetcher.new(target, cache)27 end28 # Check if the profile contains a vendored cache, move content into global cache29 # TODO: use relative file provider30 # TODO: use source reader for Cache as well31 def self.copy_deps_into_cache(file_provider, opts)32 # filter content33 cache = file_provider.files.find_all do |entry|34 entry.start_with?('vendor')35 end36 content = Hash[cache.map { |x| [x, file_provider.read(x)] }]37 keys = content.keys38 keys.each do |key|39 next if content[key].nil?40 # remove prefix41 rel = Pathname.new(key).relative_path_from(Pathname.new('vendor')).to_s42 tar = Pathname.new(opts[:cache].path).join(rel)43 FileUtils.mkdir_p tar.dirname.to_s44 Inspec::Log.debug "Copy #{tar} to cache directory"45 File.write(tar.to_s, content[key].force_encoding('UTF-8'))46 end47 end48 def self.for_path(path, opts)49 file_provider = FileProvider.for_path(path)50 rp = file_provider.relative_provider51 # copy embedded dependecies into global cache52 copy_deps_into_cache(rp, opts) unless opts[:cache].nil?53 reader = Inspec::SourceReader.resolve(rp)54 if reader.nil?55 raise("Don't understand inspec profile in #{path}, it " \56 "doesn't look like a supported profile structure.")57 end58 new(reader, opts)59 end60 def self.for_fetcher(fetcher, opts)61 opts[:cache] = opts[:cache] || Cache.new62 path, writable = fetcher.fetch63 for_path(path, opts.merge(target: fetcher.target, writable: writable))64 end65 def self.for_target(target, opts = {})66 opts[:cache] = opts[:cache] || Cache.new67 fetcher = resolve_target(target, opts[:cache])68 for_fetcher(fetcher, opts)69 end70 attr_reader :source_reader, :backend, :runner_context71 def_delegator :@source_reader, :tests72 def_delegator :@source_reader, :libraries73 def_delegator :@source_reader, :metadata74 # rubocop:disable Metrics/AbcSize75 def initialize(source_reader, options = {})76 @source_reader = source_reader77 @target = options[:target]78 @logger = options[:logger] || Logger.new(nil)79 @locked_dependencies = options[:dependencies]80 @controls = options[:controls] || []81 @writable = options[:writable] || false82 @profile_id = options[:id]83 @cache = options[:cache] || Cache.new84 @backend = options[:backend] || Inspec::Backend.create(options.select { |k, _| k != 'target' })85 @attr_values = options[:attributes]86 @tests_collected = false87 @libraries_loaded = false88 Metadata.finalize(@source_reader.metadata, @profile_id, options)89 @runtime_profile = RuntimeProfile.new(self)90 @backend.profile = @runtime_profile91 @runner_context =92 options[:profile_context] ||93 Inspec::ProfileContext.for_profile(self, @backend, @attr_values)94 end95 def name96 metadata.params[:name]97 end98 def version99 metadata.params[:version]100 end101 def writable?102 @writable103 end104 #105 # Is this profile is supported on the current platform of the106 # backend machine and the current inspec version.107 #108 # @returns [TrueClass, FalseClass]109 #110 def supported?111 supports_os? && supports_runtime?112 end113 def supports_os?114 metadata.supports_transport?(@backend)115 end116 def supports_runtime?117 metadata.supports_runtime?118 end119 def params120 @params ||= load_params121 end122 def collect_tests(include_list = @controls)123 if !@tests_collected124 locked_dependencies.each(&:collect_tests)125 tests.each do |path, content|126 next if content.nil? || content.empty?127 abs_path = source_reader.target.abs_path(path)128 @runner_context.load_control_file(content, abs_path, nil)129 end130 @tests_collected = true131 end132 filter_controls(@runner_context.all_rules, include_list)133 end134 def filter_controls(controls_array, include_list)135 return controls_array if include_list.nil? || include_list.empty?136 controls_array.select do |c|137 id = ::Inspec::Rule.rule_id(c)138 include_list.include?(id)139 end140 end141 def load_libraries142 return @runner_context if @libraries_loaded143 locked_dependencies.each do |d|144 c = d.load_libraries145 @runner_context.add_resources(c)146 end147 libs = libraries.map do |path, content|148 [content, path]149 end150 @runner_context.load_libraries(libs)151 @libraries_loaded = true152 @runner_context153 end154 def to_s155 "Inspec::Profile<#{name}>"156 end157 # return info using uncached params158 def info!159 info(load_params.dup)160 end161 def info(res = params.dup)162 # add information about the controls163 res[:controls] = res[:controls].map do |id, rule|164 next if id.to_s.empty?165 data = rule.dup166 data.delete(:checks)167 data[:impact] ||= 0.5168 data[:impact] = 1.0 if data[:impact] > 1.0169 data[:impact] = 0.0 if data[:impact] < 0.0170 data[:id] = id171 data172 end.compact173 # resolve hash structure in groups174 res[:groups] = res[:groups].map do |id, group|175 group[:id] = id176 group177 end178 # add information about the required attributes179 res[:attributes] = res[:attributes].map(&:to_hash) unless res[:attributes].nil? || res[:attributes].empty?180 res[:sha256] = sha256181 res182 end183 # Check if the profile is internally well-structured. The logger will be184 # used to print information on errors and warnings which are found.185 #186 # @return [Boolean] true if no errors were found, false otherwise187 def check # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength188 # initial values for response object189 result = {190 summary: {191 valid: false,192 timestamp: Time.now.iso8601,193 location: @target,194 profile: nil,195 controls: 0,196 },197 errors: [],198 warnings: [],199 }200 entry = lambda { |file, line, column, control, msg|201 {202 file: file,203 line: line,204 column: column,205 control_id: control,206 msg: msg,207 }208 }209 warn = lambda { |file, line, column, control, msg|210 @logger.warn(msg)211 result[:warnings].push(entry.call(file, line, column, control, msg))212 }213 error = lambda { |file, line, column, control, msg|214 @logger.error(msg)215 result[:errors].push(entry.call(file, line, column, control, msg))216 }217 @logger.info "Checking profile in #{@target}"218 meta_path = @source_reader.target.abs_path(@source_reader.metadata.ref)219 if meta_path =~ /metadata\.rb$/220 warn.call(@target, 0, 0, nil, 'The use of `metadata.rb` is deprecated. Use `inspec.yml`.')221 end222 # verify metadata223 m_errors, m_warnings = metadata.valid224 m_errors.each { |msg| error.call(meta_path, 0, 0, nil, msg) }225 m_warnings.each { |msg| warn.call(meta_path, 0, 0, nil, msg) }226 m_unsupported = metadata.unsupported227 m_unsupported.each { |u| warn.call(meta_path, 0, 0, nil, "doesn't support: #{u}") }228 @logger.info 'Metadata OK.' if m_errors.empty? && m_unsupported.empty?229 # extract profile name230 result[:summary][:profile] = metadata.params[:name]231 # check if the profile is using the old test directory instead of the232 # new controls directory233 if @source_reader.tests.keys.any? { |x| x =~ %r{^test/$} }234 warn.call(@target, 0, 0, nil, 'Profile uses deprecated `test` directory, rename it to `controls`.')235 end236 count = controls_count237 result[:summary][:controls] = count238 if count == 0239 warn.call(nil, nil, nil, nil, 'No controls or tests were defined.')240 else241 @logger.info("Found #{count} controls.")242 end243 # iterate over hash of groups244 params[:controls].each { |id, control|245 sfile = control[:source_location][:ref]246 sline = control[:source_location][:line]247 error.call(sfile, sline, nil, id, 'Avoid controls with empty IDs') if id.nil? or id.empty?248 next if id.start_with? '(generated '249 warn.call(sfile, sline, nil, id, "Control #{id} has no title") if control[:title].to_s.empty?250 warn.call(sfile, sline, nil, id, "Control #{id} has no description") if control[:desc].to_s.empty?251 warn.call(sfile, sline, nil, id, "Control #{id} has impact > 1.0") if control[:impact].to_f > 1.0252 warn.call(sfile, sline, nil, id, "Control #{id} has impact < 0.0") if control[:impact].to_f < 0.0253 warn.call(sfile, sline, nil, id, "Control #{id} has no tests defined") if control[:checks].nil? or control[:checks].empty?254 }255 # profile is valid if we could not find any error256 result[:summary][:valid] = result[:errors].empty?257 @logger.info 'Control definitions OK.' if result[:warnings].empty?258 result259 end260 def controls_count261 params[:controls].values.length262 end263 # generates a archive of a folder profile264 # assumes that the profile was checked before265 def archive(opts)266 # check if file exists otherwise overwrite the archive267 dst = archive_name(opts)268 if dst.exist? && !opts[:overwrite]269 @logger.info "Archive #{dst} exists already. Use --overwrite."270 return false271 end272 # remove existing archive273 File.delete(dst) if dst.exist?274 @logger.info "Generate archive #{dst}."275 # filter files that should not be part of the profile276 # TODO ignore all .files, but add the files to debug output277 # display all files that will be part of the archive278 @logger.debug 'Add the following files to archive:'279 files.each { |f| @logger.debug ' ' + f }280 if opts[:zip]281 # generate zip archive282 require 'inspec/archive/zip'283 zag = Inspec::Archive::ZipArchiveGenerator.new284 zag.archive(root_path, files, dst)285 else286 # generate tar archive287 require 'inspec/archive/tar'288 tag = Inspec::Archive::TarArchiveGenerator.new289 tag.archive(root_path, files, dst)290 end291 @logger.info 'Finished archive generation.'292 true293 end294 def locked_dependencies295 @locked_dependencies ||= load_dependencies296 end297 def lockfile_exists?298 @source_reader.target.files.include?('inspec.lock')299 end300 def lockfile_path301 File.join(cwd, 'inspec.lock')302 end303 def root_path304 @source_reader.target.prefix305 end306 def files307 @source_reader.target.files308 end309 #310 # TODO(ssd): Relative path handling really needs to be carefully311 # thought through, especially with respect to relative paths in312 # tarballs.313 #314 def cwd315 @target.is_a?(String) && File.directory?(@target) ? @target : './'316 end317 def lockfile318 @lockfile ||= if lockfile_exists?319 Inspec::Lockfile.from_content(@source_reader.target.read('inspec.lock'))320 else321 generate_lockfile322 end323 end324 #325 # Generate an in-memory lockfile. This won't render the lock file326 # to disk, it must be explicitly written to disk by the caller.327 #328 # @param vendor_path [String] Path to the on-disk vendor dir329 # @return [Inspec::Lockfile]330 #331 def generate_lockfile332 res = Inspec::DependencySet.new(cwd, @cache, nil, @backend)333 res.vendor(metadata.dependencies)334 Inspec::Lockfile.from_dependency_set(res)335 end336 def load_dependencies337 Inspec::DependencySet.from_lockfile(lockfile, cwd, @cache, @backend, { attributes: @attr_values })338 end339 # Calculate this profile's SHA256 checksum. Includes metadata, dependencies,340 # libraries, data files, and controls.341 #342 # @return [Type] description of returned object343 def sha256344 # get all dependency checksums345 deps = Hash[locked_dependencies.list.map { |k, v| [k, v.profile.sha256] }]346 res = Digest::SHA256.new347 files = source_reader.tests.to_a + source_reader.libraries.to_a +348 source_reader.data_files.to_a +349 [['inspec.yml', source_reader.metadata.content]] +350 [['inspec.lock.deps', YAML.dump(deps)]]351 files.sort { |a, b| a[0] <=> b[0] }352 .map { |f| res << f[0] << "\0" << f[1] << "\0" }353 res.hexdigest354 end355 private356 # Create an archive name for this profile and an additional options357 # configuration. Either use :output or generate the name from metadata.358 #359 # @param [Hash] configuration options360 # @return [Pathname] path for the archive361 def archive_name(opts)362 if (name = opts[:output])363 return Pathname.new(name)364 end365 name = params[:name] ||366 raise('Cannot create an archive without a profile name! Please '\367 'specify the name in metadata or use --output to create the archive.')368 version = params[:version] ||369 raise('Cannot create an archive without a profile version! Please '\370 'specify the version in metadata or use --output to create the archive.')371 ext = opts[:zip] ? 'zip' : 'tar.gz'372 slug = name.downcase.strip.tr(' ', '-').gsub(/[^\w-]/, '_')373 Pathname.new(Dir.pwd).join("#{slug}-#{version}.#{ext}")374 end375 def load_params376 params = @source_reader.metadata.params377 params[:name] = @profile_id unless @profile_id.nil?378 load_checks_params(params)379 @profile_id ||= params[:name]380 params381 end382 def load_checks_params(params)383 load_libraries384 tests = collect_tests385 params[:controls] = controls = {}386 params[:groups] = groups = {}387 prefix = @source_reader.target.prefix || ''388 tests.each do |rule|389 next if rule.nil?390 f = load_rule_filepath(prefix, rule)391 load_rule(rule, f, controls, groups)392 end393 params[:attributes] = @runner_context.attributes394 params395 end396 def load_rule_filepath(prefix, rule)397 file = rule.instance_variable_get(:@__file)398 file = file[prefix.length..-1] if file.start_with?(prefix)399 file400 end401 def load_rule(rule, file, controls, groups)402 id = Inspec::Rule.rule_id(rule)403 location = rule.instance_variable_get(:@__source_location)404 controls[id] = {405 title: rule.title,406 desc: rule.desc,407 impact: rule.impact,408 refs: rule.ref,409 tags: rule.tag,410 checks: Inspec::Rule.checks(rule),411 code: Inspec::MethodSource.code_at(location, source_reader),412 source_location: location,413 }414 groups[file] ||= {415 title: rule.instance_variable_get(:@__group_title),416 controls: [],417 }418 groups[file][:controls].push(id)419 end420 end421end...

Full Screen

Full Screen

source_reader

Using AI Code Generation

copy

Full Screen

1source = Inspec::SourceReader.resolve('./myprofile')2ctx = Inspec::ProfileContext.new('./myprofile')3source = Inspec::SourceReader.resolve('./myprofile')

Full Screen

Full Screen

source_reader

Using AI Code Generation

copy

Full Screen

1class MyResource < Inspec.resource(1)2 @params = {}3class MyControl < Inspec.resource(1)4 @params = {}5class MyProfile < Inspec.resource(1)6 @params = {}7 it { should exist }8 it { should exist }9 it { should exist }10 it { should exist }11 it { should exist }12describe my_profile, '1.0.0', 'My Profile', { 'my_attribute' => 'my_value' } do13 it { should exist }14 it { should exist }15 it { should exist }16describe my_control, '1.0.0', 'My Control', { 'my_attribute' => 'my_value' } do17 it { should exist }18 it { should exist }

Full Screen

Full Screen

source_reader

Using AI Code Generation

copy

Full Screen

1reader = Inspec.source_reader('test.rb')2describe Inspec.resource(1, 'test.rb') do3 its('name') { should eq 'test' }4describe Inspec.resource_dsl('test') do5 it { should eq 'test' }6Inspec.plugin(1, 'test.rb')7Inspec.plugin_dsl('test', 'test')8Inspec::Runner.new('test.rb').run9Inspec::Runner.new('test.rb').run_dsl10Inspec::Reporter.new('test.rb').run11Inspec::Reporter.new('test.rb').run_dsl

Full Screen

Full Screen

source_reader

Using AI Code Generation

copy

Full Screen

1source = inspec.source_reader.read('inspec/resources/file.rb')2source = inspec.source_reader.read('inspec/resources/file.rb')3source = inspec.source_reader.read('inspec/resources/file.rb')4source = inspec.source_reader.read('inspec/resources/file.rb')5source = inspec.source_reader.read('inspec/resources/file.rb')

Full Screen

Full Screen

source_reader

Using AI Code Generation

copy

Full Screen

1file = Inspec::Resource.create_resource('file', 'C:\Users\shweta\Desktop\Inspec\1.rb')2content = Inspec::FileContent.new(file)3 return @content if defined?(@content)4 return @file.content if @file.respond_to?(:content)5 return @file.content if @file.respond_to?(:content)6 return @file.content if @file.respond_to?(:content)7 return @file.content if @file.respond_to?(:content)8 return @file.content if @file.respond_to?(:content)9 return @file.content if @file.respond_to?(:content)10 return @file.content if @file.respond_to?(:content)11 return @file.content if @file.respond_to?(:content)12 return @file.content if @file.respond_to?(:content)13 return @file.content if @file.respond_to?(:content)14 return @file.content if @file.respond_to?(:content)15 return @file.content if @file.respond_to?(:content)

Full Screen

Full Screen

source_reader

Using AI Code Generation

copy

Full Screen

1source = inspec.source_reader.read('inspec/resources/file.rb')2source = inspec.source_reader.read('inspec/resources/file.rb')3source = inspec.source_reader.read('inspec/resources/file.rb')4source = inspec.source_reader.read('inspec/resources/file.rb')5source = inspec.source_reader.read('inspec/resources/file.rb')

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:

YouTube

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?

Helpful

NotHelpful