From 41a2fc8ed78354d79f756710749c7b853e5cdbc8 Mon Sep 17 00:00:00 2001 From: Dan Bode Date: Wed, 1 Aug 2012 15:35:23 -0700 Subject: [PATCH] Add support for pre_condition with functions This commit adds support for using the pre_condition hook to specify the source code that should be used to compile a catalog that can be introspected by functions for testing purposes. This allows users to test functions that need access to catalog contents. This allows the following snippet to test a function that needs access to the catalog generated by pre_condition: describe 'defined_with_params' do #describe 'when resource is passed as a string' do let :pre_condition do 'user { "dan": }' end it { should run.with_params('User[dan]', {}).and_return('true') } end --- .../example/function_example_group.rb | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/rspec-puppet/example/function_example_group.rb b/lib/rspec-puppet/example/function_example_group.rb index c907e12..7933832 100644 --- a/lib/rspec-puppet/example/function_example_group.rb +++ b/lib/rspec-puppet/example/function_example_group.rb @@ -9,9 +9,36 @@ module RSpec::Puppet Puppet[:libdir] = Dir["#{Puppet[:modulepath]}/*/lib"].entries.join(File::PATH_SEPARATOR) Puppet::Parser::Functions.autoloader.loadall - scope = Puppet::Parser::Scope.new + # if we specify a pre_condition, we should ensure that we compile that code + # into a catalog that is accessible from the scope where the function is called + if self.respond_to? :pre_condition + Puppet[:code] = pre_condition + nodename = self.respond_to?(:node) ? node : Puppet[:certname] + facts_val = { + 'hostname' => nodename.split('.').first, + 'fqdn' => nodename, + 'domain' => nodename.split('.').last, + } + facts_val.merge!(munge_facts(facts)) if self.respond_to?(:facts) + # we need to get a compiler, b/c we can attach that to a scope + @compiler = build_compiler(nodename, facts_val) + else + @compiler = nil + end + + scope = Puppet::Parser::Scope.new(:compiler => @compiler) scope.method "function_#{function_name}".to_sym end + + def compiler + @compiler + end + # get a compiler with an attached compiled catalog + def build_compiler(node_name, fact_values) + compiler = Puppet::Parser::Compiler.new(Puppet::Node.new(node_name, :parameters => fact_values)) + compiler.compile + compiler + end end end