From 81a6838902d2e36ba79a3392ec3cdda55d272b8f Mon Sep 17 00:00:00 2001 From: Rene Last Date: Sun, 8 Mar 2015 10:43:12 +0100 Subject: [PATCH] (#MODULES-865) validate_re cannot match numeric regex in all cases The validate_re function now tries to convert it's first argument to a string. This will ensure that numeric, boolean, symbols, arrays and hashes can be matched by a regex since regex matching can only happen on strings. validate_re(1, '^\d+$') would previously fail because the first argument is a Fixnum. This patch ensures the first argument is cast to a string so this would match as one would expect. --- lib/puppet/parser/functions/validate_re.rb | 10 ++++++++-- spec/functions/validate_re_spec.rb | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/puppet/parser/functions/validate_re.rb b/lib/puppet/parser/functions/validate_re.rb index ca25a702c..5af8e83cf 100644 --- a/lib/puppet/parser/functions/validate_re.rb +++ b/lib/puppet/parser/functions/validate_re.rb @@ -28,12 +28,18 @@ module Puppet::Parser::Functions raise Puppet::ParseError, ("validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)") end - msg = args[2] || "validate_re(): #{args[0].inspect} does not match #{args[1].inspect}" + input = args[0] + msg = args[2] || "validate_re(): #{input.inspect} does not match #{args[1].inspect}" # We're using a flattened array here because we can't call String#any? in # Ruby 1.9 like we can in Ruby 1.8 raise Puppet::ParseError, (msg) unless [args[1]].flatten.any? do |re_str| - args[0] =~ Regexp.compile(re_str) + begin + s = input.to_s + rescue TypeError + s = input + end + s =~ Regexp.compile(re_str) end end diff --git a/spec/functions/validate_re_spec.rb b/spec/functions/validate_re_spec.rb index d29988bf0..0fbfcfe70 100755 --- a/spec/functions/validate_re_spec.rb +++ b/spec/functions/validate_re_spec.rb @@ -59,6 +59,24 @@ end end end + describe 'Convert input to String' do + inputs = [ + [ 1, '^\d+$' ], # Fixnum + [ 3.14, '^\d+\.\d+$' ], # Float + [ nil, '^$' ], # NilClass + [ true, '^true$' ], # TrueClass + [ false, '^false$' ], # FalseClass + [ ["10"], '\["\d+"\]'], # Array + [ :key, '^key$' ], # Symbol + [ {:key=>"val"}, ':\w+=>"\w+"' ], # Hash + ] + + inputs.each do |input| + it "validate_re(#{input.inspect}) should work" do + expect { subject.call input }.not_to raise_error + end + end + end describe "Nicer Error Messages" do # The intent here is to make sure the function returns the 3rd argument # in the exception thrown