Skip to content

Instantly share code, notes, and snippets.

@glarizza
Created August 28, 2013 16:43
Show Gist options
  • Save glarizza/6368215 to your computer and use it in GitHub Desktop.
Save glarizza/6368215 to your computer and use it in GitHub Desktop.
----------FUNCTION----------
Puppet::Parser::Functions.newfunction(:extract, :type => :rvalue, :doc => "Extract it!") do |args|
raise Puppet::ParseError, "Please pass 2 arguments to the extract function, not #{args.length}" unless args.length == 2
yaml_file = args[0]
yaml_field = args[1]
raise Puppet::ParseError, "File #{yaml_file} not accessible to the extract function" unless File.exist?(yaml_file) and File.readable?(yaml_file)
yaml_hash = YAML.load_file(yaml_file)
yaml_hash[yaml_field] || 'VALUE NOT FOUND'
end
----------SPEC TEST---------
require 'puppet'
require 'rspec-puppet'
RSpec.configure { |config| config.mock_with :mocha }
describe Puppet::Parser::Functions.function(:extract) do
let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
let(:filename) { '/tmp/myfile.yaml' }
let(:field) { 'name' }
let(:yamldata) { { 'name' => 'gary', 'color' => 'blue' } }
it 'should return a value from a yaml file' do
File.stubs(:exist?).with(filename).returns(true)
File.stubs(:readable?).with(filename).returns(true)
YAML.stubs(:load_file).with(filename).returns(yamldata)
scope.function_extract([filename, field]).should == 'gary'
end
end
----------RSPEC RUN------------
Failures:
1) function_extract should return a value from a yaml file
Failure/Error: scope.function_extract([filename, field]).should == 'gary'
Mocha::ExpectationError:
unexpected invocation: File.exist?('/opt/puppet/lib/ruby/gems/1.9.1/gems/trollop-1.16.2/lib/puppet/parser/functions/extract.rb')
satisfied expectations:
- allowed any number of times, not yet invoked: File.readable?('/tmp/myfile.yaml')
- allowed any number of times, not yet invoked: File.exist?('/tmp/myfile.yaml')
- allowed any number of times, not yet invoked: Psych.load_file('/tmp/myfile.yaml')
# ./custom_functions/spec/unit/puppet/parser/functions/extract_spec.rb:17:in `block (2 levels) in <top (required)>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment