Sha256: 0471bff1805b934091630184267135ba69d351599580105b4a6ab0925fbd1226

Contents?: true

Size: 1.64 KB

Versions: 39

Compression:

Stored size: 1.64 KB

Contents

# encoding: utf-8
# author: Christoph Hartmann
# author: Dominik Richter

require 'utils/object_traversal'

module Inspec::Resources
  class JsonConfig < Inspec.resource(1)
    name 'json'
    desc 'Use the json InSpec audit resource to test data in a JSON file.'
    example "
      describe json('policyfile.lock.json') do
        its(['cookbook_locks','omnibus','version']) { should eq('2.2.0') }
      end
    "

    include ObjectTraverser

    # make params readable
    attr_reader :params

    def initialize(path)
      @path = path
      @file = inspec.file(@path)
      @file_content = @file.content

      # check if file is available
      if !@file.file?
        skip_resource "Can't find file \"#{@conf_path}\""
        return @params = {}
      end

      # check if file is readable
      if @file_content.empty? && @file.size > 0
        skip_resource "Can't read file \"#{@conf_path}\""
        return @params = {}
      end

      @params = parse(@file_content)
    end

    def parse(content)
      require 'json'
      JSON.parse(content)
    end

    def value(key)
      extract_value(key, @params)
    end

    # Shorthand to retrieve a parameter name via `#its`.
    # Example: describe json('file') { its('paramX') { should eq 'Y' } }
    #
    # @param [String] name name of the field to retrieve
    # @return [Object] the value stored at this position
    def method_missing(*keys)
      # catch bahavior of rspec its implementation
      # @see https://github.com/rspec/rspec-its/blob/master/lib/rspec/its.rb#L110
      keys.shift if keys.is_a?(Array) && keys[0] == :[]
      value(keys)
    end

    def to_s
      "Json #{@path}"
    end
  end
end

Version data entries

39 entries across 39 versions & 1 rubygems

Version Path
inspec-1.3.0 lib/resources/json.rb
inspec-1.2.1 lib/resources/json.rb
inspec-1.2.0 lib/resources/json.rb
inspec-1.1.0 lib/resources/json.rb
inspec-1.0.0 lib/resources/json.rb
inspec-1.0.0.beta3 lib/resources/json.rb
inspec-1.0.0.beta2 lib/resources/json.rb
inspec-0.35.0 lib/resources/json.rb
inspec-0.34.1 lib/resources/json.rb
inspec-0.34.0 lib/resources/json.rb
inspec-0.33.2 lib/resources/json.rb
inspec-0.33.1 lib/resources/json.rb
inspec-0.33.0 lib/resources/json.rb
inspec-0.32.0 lib/resources/json.rb
inspec-0.31.0 lib/resources/json.rb
inspec-0.30.0 lib/resources/json.rb
inspec-0.29.0 lib/resources/json.rb
inspec-0.28.1 lib/resources/json.rb
inspec-0.28.0 lib/resources/json.rb
inspec-0.27.1 lib/resources/json.rb