Create is_service_default function

This change creates a parser function that can be used to check if a
value is set to the '<SERVICE DEFAULT>' string. The is_service_default
function will return true if the parameter passed in is '<SERVICE
DEFAULT>' otherwise it returns false.

Checks like:
  if ($our_param == '<SERVICE DEFAULT>') { ... }

Should be replaced with:
  if is_service_default($our_param) { ... }

This change will also be useful if we ever refactor the default value
string or have different values as this function could be updated to
support multiple values without having to adjust the calling code.

Change-Id: I07b8b9b54ed1e88891f74da9b930e4f39876a607
This commit is contained in:
Alex Schultz 2015-09-15 11:08:41 -05:00
parent 745dccbfcd
commit 74de9e1d34
2 changed files with 67 additions and 0 deletions
lib/puppet/parser/functions
spec/functions

@ -0,0 +1,27 @@
#
# is_service_default.rb
#
# This function can be used to check if a variable is set to the default value
# of '<SERVICE DEFAULT>'
#
# For reference:
# http://lists.openstack.org/pipermail/openstack-dev/2015-July/069823.html
# https://github.com/openstack/puppet-openstacklib/commit/3b85306d042292713d0fd89fa508e0a0fbf99671
#
module Puppet::Parser::Functions
newfunction(:is_service_default, :type => :rvalue, :doc => <<-EOS
Returns true if the variable passed to this function is '<SERVICE DEFAULT>'
EOS
) do |arguments|
raise(Puppet::ParseError, "is_service_default(): Wrong number of arguments" +
"given (#{arguments.size} for 1)") if arguments.size != 1
value = arguments[0]
unless value.is_a?(String)
return false
end
return (value == '<SERVICE DEFAULT>')
end
end

@ -0,0 +1,40 @@
require 'spec_helper'
describe 'is_service_default' do
it 'refuses without at least one argument' do
is_expected.to run.with_params().\
and_raise_error(Puppet::ParseError, /Wrong number of arguments/)
end
it 'refuses too many arguments' do
is_expected.to run.with_params('foo', 'bar').\
and_raise_error(Puppet::ParseError, /Wrong number of arguments/)
end
context 'is_service_default' do
it 'with <SERVICE DEFAULT>' do
is_expected.to run.with_params('<SERVICE DEFAULT>').and_return(true)
end
it 'with string != <SERVICE DEFAULT>' do
is_expected.to run.with_params('a value').and_return(false)
end
it 'with array' do
is_expected.to run.with_params([1,2,3]).and_return(false)
end
it 'with hash' do
is_expected.to run.with_params({'foo' => 'bar'}).and_return(false)
end
it 'with integer' do
is_expected.to run.with_params(1234).and_return(false)
end
it 'with boolean' do
is_expected.to run.with_params(false).and_return(false)
end
end
end