diff --git a/lib/puppet/application/kick.rb b/lib/puppet/application/kick.rb index 604132818..da93c0182 100644 --- a/lib/puppet/application/kick.rb +++ b/lib/puppet/application/kick.rb @@ -1,353 +1,353 @@ require 'puppet/application' class Puppet::Application::Kick < Puppet::Application should_not_parse_config attr_accessor :hosts, :tags, :classes option("--all","-a") option("--foreground","-f") option("--debug","-d") option("--ping","-P") option("--test") option("--host HOST") do |arg| @hosts << arg end option("--tag TAG", "-t") do |arg| @tags << arg end option("--class CLASS", "-c") do |arg| @classes << arg end option("--no-fqdn", "-n") do |arg| options[:fqdn] = false end option("--parallel PARALLEL", "-p") do |arg| begin options[:parallel] = Integer(arg) rescue $stderr.puts "Could not convert #{arg.inspect} to an integer" exit(23) end end def help <<-HELP puppet-kick(8) -- Remotely control puppet agent ======== SYNOPSIS -------- Trigger a puppet agent run on a set of hosts. USAGE ----- puppet kick [-a|--all] [-c|--class ] [-d|--debug] [-f|--foreground] [-h|--help] [--host ] [--no-fqdn] [--ignoreschedules] [-t|--tag ] [--test] [-p|--ping] [ [...]] DESCRIPTION ----------- This script can be used to connect to a set of machines running 'puppet agent' and trigger them to run their configurations. The most common usage would be to specify a class of hosts and a set of tags, and 'puppet kick' would look up in LDAP all of the hosts matching that class, then connect to each host and trigger a run of all of the objects with the specified tags. If you are not storing your host configurations in LDAP, you can specify hosts manually. You will most likely have to run 'puppet kick' as root to get access to the SSL certificates. 'puppet kick' reads 'puppet master''s configuration file, so that it can copy things like LDAP settings. USAGE NOTES ----------- 'puppet kick' is useless unless 'puppet agent' is listening. See its documentation for more information, but the gist is that you must enable 'listen' on the 'puppet agent' daemon, either using '--listen' on the command line or adding 'listen = true' in its config file. In addition, you need to set the daemons up to specifically allow connections by creating the 'namespaceauth' file, normally at '/etc/puppet/namespaceauth.conf'. This file specifies who has access to each namespace; if you create the file you must add every namespace you want any Puppet daemon to allow -- it is currently global to all Puppet daemons. An example file looks like this: [fileserver] allow *.madstop.com [puppetmaster] allow *.madstop.com [puppetrunner] allow culain.madstop.com This is what you would install on your Puppet master; non-master hosts could leave off the 'fileserver' and 'puppetmaster' namespaces. OPTIONS ------- Note that any configuration parameter that's valid in the configuration file is also a valid long argument. For example, 'ssldir' is a valid configuration parameter, so you can specify '--ssldir ' as an argument. See the configuration file documentation at http://docs.puppetlabs.com/references/latest/configuration.html for the full list of acceptable parameters. A commented list of all configuration options can also be generated by running puppet master with '--genconfig'. * --all: Connect to all available hosts. Requires LDAP support at this point. * --class: Specify a class of machines to which to connect. This only works if you have LDAP configured, at the moment. * --debug: Enable full debugging. * --foreground: Run each configuration in the foreground; that is, when connecting to a host, do not return until the host has finished its run. The default is false. * --help: Print this help message * --host: A specific host to which to connect. This flag can be specified more than once. * --ignoreschedules: Whether the client should ignore schedules when running its configuration. This can be used to force the client to perform work it would not normally perform so soon. The default is false. * --parallel: How parallel to make the connections. Parallelization is provided by forking for each client to which to connect. The default is 1, meaning serial execution. * --tag: Specify a tag for selecting the objects to apply. Does not work with the --test option. * --test: Print the hosts you would connect to but do not actually connect. This option requires LDAP support at this point. * --ping: Do a ICMP echo against the target host. Skip hosts that don't respond to ping. EXAMPLE ------- $ sudo puppet kick -p 10 -t remotefile -t webserver host1 host2 AUTHOR ------ Luke Kanies COPYRIGHT --------- Copyright (c) 2005 Puppet Labs, LLC Licensed under the GNU Public License HELP end def run_command @hosts += command_line.args options[:test] ? test : main end def test puts "Skipping execution in test mode" exit(0) end def main require 'puppet/network/client' Puppet.warning "Failed to load ruby LDAP library. LDAP functionality will not be available" unless Puppet.features.ldap? require 'puppet/util/ldap/connection' todo = @hosts.dup failures = [] # Now do the actual work go = true while go # If we don't have enough children in process and we still have hosts left to # do, then do the next host. if @children.length < options[:parallel] and ! todo.empty? host = todo.shift pid = fork do run_for_host(host) end @children[pid] = host else # Else, see if we can reap a process. begin pid = Process.wait if host = @children[pid] # Remove our host from the list of children, so the parallelization # continues working. @children.delete(pid) failures << host if $CHILD_STATUS.exitstatus != 0 print "#{host} finished with exit code #{$CHILD_STATUS.exitstatus}\n" else $stderr.puts "Could not find host for PID #{pid} with status #{$CHILD_STATUS.exitstatus}" end rescue Errno::ECHILD # There are no children left, so just exit unless there are still # children left to do. next unless todo.empty? if failures.empty? puts "Finished" exit(0) else puts "Failed: #{failures.join(", ")}" exit(3) end end end end end def run_for_host(host) if options[:ping] out = %x{ping -c 1 #{host}} unless $CHILD_STATUS == 0 $stderr.print "Could not contact #{host}\n" - next + exit($CHILD_STATUS) end end require 'puppet/run' Puppet::Run.indirection.terminus_class = :rest port = Puppet[:puppetport] url = ["https://#{host}:#{port}", "production", "run", host].join('/') print "Triggering #{host}\n" begin run_options = { :tags => @tags, :background => ! options[:foreground], :ignoreschedules => options[:ignoreschedules] } run = Puppet::Run.indirection.save(Puppet::Run.new( run_options ), url) puts "Getting status" result = run.status puts "status is #{result}" rescue => detail puts detail.backtrace if Puppet[:trace] $stderr.puts "Host #{host} failed: #{detail}\n" exit(2) end case result when "success"; exit(0) when "running" $stderr.puts "Host #{host} is already running" exit(3) else $stderr.puts "Host #{host} returned unknown answer '#{result}'" exit(12) end end def initialize(*args) super @hosts = [] @classes = [] @tags = [] end def preinit [:INT, :TERM].each do |signal| Signal.trap(signal) do $stderr.puts "Cancelling" exit(1) end end options[:parallel] = 1 options[:verbose] = true options[:fqdn] = true options[:ignoreschedules] = false options[:foreground] = false end def setup if options[:debug] Puppet::Util::Log.level = :debug else Puppet::Util::Log.level = :info end # Now parse the config Puppet.parse_config if Puppet[:node_terminus] == "ldap" and (options[:all] or @classes) if options[:all] @hosts = Puppet::Node.indirection.search("whatever", :fqdn => options[:fqdn]).collect { |node| node.name } puts "all: #{@hosts.join(", ")}" else @hosts = [] @classes.each do |klass| list = Puppet::Node.indirection.search("whatever", :fqdn => options[:fqdn], :class => klass).collect { |node| node.name } puts "#{klass}: #{list.join(", ")}" @hosts += list end end elsif ! @classes.empty? $stderr.puts "You must be using LDAP to specify host classes" exit(24) end @children = {} # If we get a signal, then kill all of our children and get out. [:INT, :TERM].each do |signal| Signal.trap(signal) do Puppet.notice "Caught #{signal}; shutting down" @children.each do |pid, host| Process.kill("INT", pid) end waitall exit(1) end end end end diff --git a/lib/puppet/external/nagios/parser.rb b/lib/puppet/external/nagios/parser.rb index 5504f5818..17db5e307 100644 --- a/lib/puppet/external/nagios/parser.rb +++ b/lib/puppet/external/nagios/parser.rb @@ -1,775 +1,775 @@ # # DO NOT MODIFY!!!! # This file is automatically generated by racc 1.4.5 # from racc grammer file "grammar.ry". # # # parser.rb: generated by racc (runtime embedded) # ###### racc/parser.rb begin unless $LOADED_FEATURES.index 'racc/parser.rb' $LOADED_FEATURES.push 'racc/parser.rb' self.class.module_eval <<'..end racc/parser.rb modeval..id5256434e8a', 'racc/parser.rb', 1 # # $Id: parser.rb,v 1.7 2005/11/20 17:31:32 aamine Exp $ # # Copyright (c) 1999-2005 Minero Aoki # # This program is free software. # You can distribute/modify this program under the same terms of ruby. # # As a special exception, when this code is copied by Racc # into a Racc output file, you may use that output file # without restriction. # NotImplementedError = NotImplementError unless defined?(NotImplementedError) module Racc class ParseError < StandardError; end end ParseError = Racc::ParseError unless defined?(::ParseError) module Racc Racc_No_Extentions = false unless defined?(Racc_No_Extentions) class Parser Racc_Runtime_Version = '1.4.5' Racc_Runtime_Revision = '$Revision: 1.7 $'.split[1] Racc_Runtime_Core_Version_R = '1.4.5' Racc_Runtime_Core_Revision_R = '$Revision: 1.7 $'.split[1] begin require 'racc/cparse' # Racc_Runtime_Core_Version_C = (defined in extention) Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2] raise LoadError, 'old cparse.so' unless new.respond_to?(:_racc_do_parse_c, true) raise LoadError, 'selecting ruby version of racc runtime core' if Racc_No_Extentions Racc_Main_Parsing_Routine = :_racc_do_parse_c Racc_YY_Parse_Method = :_racc_yyparse_c Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C Racc_Runtime_Type = 'c' rescue LoadError Racc_Main_Parsing_Routine = :_racc_do_parse_rb Racc_YY_Parse_Method = :_racc_yyparse_rb Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R Racc_Runtime_Type = 'ruby' end def Parser.racc_runtime_type Racc_Runtime_Type end private def _racc_setup @yydebug = false unless self.class::Racc_debug_parser @yydebug ||= false if @yydebug @racc_debug_out ||= $stderr @racc_debug_out ||= $stderr end arg = self.class::Racc_arg arg[13] = true if arg.size < 14 arg end def _racc_init_sysvars @racc_state = [0] @racc_tstack = [] @racc_vstack = [] @racc_t = nil @racc_val = nil @racc_read_next = true @racc_user_yyerror = false @racc_error_status = 0 end ### ### do_parse ### def do_parse __send__(Racc_Main_Parsing_Routine, _racc_setup, false) end def next_token raise NotImplementedError, "#{self.class}\#next_token is not defined" end def _racc_do_parse_rb(arg, in_debug) action_table, action_check, action_default, action_pointer, goto_table, goto_check, goto_default, goto_pointer, nt_base, reduce_table, token_table, shift_n, reduce_n, use_result, * = arg _racc_init_sysvars tok = act = i = nil nerr = 0 catch(:racc_end_parse) { while true if i = action_pointer[@racc_state[-1]] if @racc_read_next if @racc_t != 0 # not EOF tok, @racc_val = next_token unless tok # EOF @racc_t = 0 else @racc_t = (token_table[tok] or 1) # error token end racc_read_token(@racc_t, tok, @racc_val) if @yydebug @racc_read_next = false end end i += @racc_t unless i >= 0 and act = action_table[i] and action_check[i] == @racc_state[-1] act = action_default[@racc_state[-1]] end else act = action_default[@racc_state[-1]] end while act = _racc_evalact(act, arg) ; end end } end ### ### yyparse ### def yyparse(recv, mid) __send__(Racc_YY_Parse_Method, recv, mid, _racc_setup, true) end def _racc_yyparse_rb(recv, mid, arg, c_debug) action_table, action_check, action_default, action_pointer, goto_table, goto_check, goto_default, goto_pointer, nt_base, reduce_table, token_table, shift_n, reduce_n, use_result, * = arg _racc_init_sysvars tok = nil act = nil i = nil nerr = 0 catch(:racc_end_parse) { until i = action_pointer[@racc_state[-1]] while act = _racc_evalact(action_default[@racc_state[-1]], arg) ; end end recv.__send__(mid) do |tok, val| unless tok @racc_t = 0 else @racc_t = (token_table[tok] or 1) # error token end @racc_val = val @racc_read_next = false i += @racc_t unless i >= 0 and act = action_table[i] and action_check[i] == @racc_state[-1] act = action_default[@racc_state[-1]] end while act = _racc_evalact(act, arg) ; end while not (i = action_pointer[@racc_state[-1]]) or not @racc_read_next or @racc_t == 0 # $ unless i and i += @racc_t and i >= 0 and act = action_table[i] and action_check[i] == @racc_state[-1] act = action_default[@racc_state[-1]] end while act = _racc_evalact(act, arg) ; end end end } end ### ### common ### def _racc_evalact(act, arg) action_table, action_check, action_default, action_pointer, goto_table, goto_check, goto_default, goto_pointer, nt_base, reduce_table, token_table, shift_n, reduce_n, use_result, * = arg nerr = 0 # tmp if act > 0 and act < shift_n # # shift # if @racc_error_status > 0 @racc_error_status -= 1 unless @racc_t == 1 # error token end @racc_vstack.push @racc_val @racc_state.push act @racc_read_next = true if @yydebug @racc_tstack.push @racc_t racc_shift @racc_t, @racc_tstack, @racc_vstack end elsif act < 0 and act > -reduce_n # # reduce # code = catch(:racc_jump) { @racc_state.push _racc_do_reduce(arg, act) false } if code case code when 1 # yyerror @racc_user_yyerror = true # user_yyerror return -reduce_n when 2 # yyaccept return shift_n else raise '[Racc Bug] unknown jump code' end end elsif act == shift_n # # accept # racc_accept if @yydebug throw :racc_end_parse, @racc_vstack[0] elsif act == -reduce_n # # error # case @racc_error_status when 0 unless arg[21] # user_yyerror nerr += 1 on_error @racc_t, @racc_val, @racc_vstack end when 3 if @racc_t == 0 # is $ throw :racc_end_parse, nil end @racc_read_next = true end @racc_user_yyerror = false @racc_error_status = 3 while true if i = action_pointer[@racc_state[-1]] i += 1 # error token if i >= 0 and (act = action_table[i]) and action_check[i] == @racc_state[-1] break end end throw :racc_end_parse, nil if @racc_state.size <= 1 @racc_state.pop @racc_vstack.pop if @yydebug @racc_tstack.pop racc_e_pop @racc_state, @racc_tstack, @racc_vstack end end return act else raise "[Racc Bug] unknown action #{act.inspect}" end racc_next_state(@racc_state[-1], @racc_state) if @yydebug nil end def _racc_do_reduce(arg, act) action_table, action_check, action_default, action_pointer, goto_table, goto_check, goto_default, goto_pointer, nt_base, reduce_table, token_table, shift_n, reduce_n, use_result, * = arg state = @racc_state vstack = @racc_vstack tstack = @racc_tstack i = act * -3 len = reduce_table[i] reduce_to = reduce_table[i+1] method_id = reduce_table[i+2] void_array = [] tmp_t = tstack[-len, len] if @yydebug tmp_v = vstack[-len, len] tstack[-len, len] = void_array if @yydebug vstack[-len, len] = void_array state[-len, len] = void_array # tstack must be updated AFTER method call if use_result vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0]) else vstack.push __send__(method_id, tmp_v, vstack) end tstack.push reduce_to racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug k1 = reduce_to - nt_base if i = goto_pointer[k1] i += state[-1] if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1 return curstate end end goto_default[k1] end def on_error(t, val, vstack) raise ParseError, sprintf("\nparse error on value %s (%s)", val.inspect, token_to_str(t) || '?') end def yyerror throw :racc_jump, 1 end def yyaccept throw :racc_jump, 2 end def yyerrok @racc_error_status = 0 end # # for debugging output # def racc_read_token(t, tok, val) @racc_debug_out.print 'read ' @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') ' @racc_debug_out.puts val.inspect @racc_debug_out.puts end def racc_shift(tok, tstack, vstack) @racc_debug_out.puts "shift #{racc_token2str tok}" racc_print_stacks tstack, vstack @racc_debug_out.puts end def racc_reduce(toks, sim, tstack, vstack) out = @racc_debug_out out.print 'reduce ' if toks.empty? out.print ' ' else toks.each {|t| out.print ' ', racc_token2str(t) } end out.puts " --> #{racc_token2str(sim)}" racc_print_stacks tstack, vstack @racc_debug_out.puts end def racc_accept @racc_debug_out.puts 'accept' @racc_debug_out.puts end def racc_e_pop(state, tstack, vstack) @racc_debug_out.puts 'error recovering mode: pop token' racc_print_states state racc_print_stacks tstack, vstack @racc_debug_out.puts end def racc_next_state(curstate, state) @racc_debug_out.puts "goto #{curstate}" racc_print_states state @racc_debug_out.puts end def racc_print_stacks(t, v) out = @racc_debug_out out.print ' [' t.each_index do |i| out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')' end out.puts ' ]' end def racc_print_states(s) out = @racc_debug_out out.print ' [' s.each {|st| out.print ' ', st } out.puts ' ]' end def racc_token2str(tok) self.class::Racc_token_to_s_table[tok] or raise "[Racc Bug] can't convert token #{tok} to string" end def token_to_str(t) self.class::Racc_token_to_s_table[t] end end end ..end racc/parser.rb modeval..id5256434e8a end ###### racc/parser.rb end module Nagios class Parser < Racc::Parser module_eval <<'..end grammar.ry modeval..idcb2ea30b34', 'grammar.ry', 57 class ::Nagios::Parser::SyntaxError < RuntimeError; end def parse(src) @src = src # state variables @invar = false @inobject = false @done = false @line = 0 @yydebug = true do_parse end # The lexer. Very simple. def token @src.sub!(/\A\n/,'') if $MATCH @line += 1 return [ :RETURN, "\n" ] end return nil if @done yytext = String.new # remove comments from this line @src.sub!(/\A[ \t]*;.*\n/,"\n") return [:INLINECOMMENT, ""] if $MATCH @src.sub!(/\A#.*\n/,"\n") return [:COMMENT, ""] if $MATCH @src.sub!(/#.*/,'') if @src.length == 0 @done = true return [false, '$'] end if @invar @src.sub!(/\A[ \t]+/,'') @src.sub!(/\A([^;\n]+)(\n|;)/,'\2') if $1 yytext += $1 end @invar = false return [:VALUE, yytext] else @src.sub!(/\A[\t ]*(\S+)([\t ]*|$)/,'') if $1 yytext = $1 case yytext when 'define' #puts "got define" return [:DEFINE, yytext] when '{' #puts "got {" @inobject = true return [:LCURLY, yytext] else unless @inobject #puts "got type: #{yytext}" if yytext =~ /\W/ giveback = yytext.dup giveback.sub!(/^\w+/,'') #puts "giveback #{giveback}" #puts "yytext #{yytext}" yytext.sub!(/\W.*$/,'') #puts "yytext #{yytext}" #puts "all [#{giveback} #{yytext} #{orig}]" @src = giveback + @src end return [:NAME, yytext] else if yytext == '}' #puts "got closure: #{yytext}" @inobject = false return [:RCURLY, '}'] end unless @invar @invar = true return [:PARAM, $1] else end end end end end end def next_token token end def yydebug 1 end def yywrap 0 end def on_error(token, value, vstack ) msg = "" unless value.nil? msg = "line #{@line}: syntax error at '#{value}'" else msg = "line #{@line}: syntax error at '#{token}'" end msg = "line #{@line}: Unexpected end of file" unless @src.size > 0 if token == '$end'.intern puts "okay, this is silly" else raise ::Nagios::Parser::SyntaxError, msg end end ..end grammar.ry modeval..idcb2ea30b34 ##### racc 1.4.5 generates ### racc_reduce_table = [ 0, 0, :racc_error, 1, 13, :_reduce_1, 2, 13, :_reduce_2, 1, 14, :_reduce_3, 1, 14, :_reduce_4, 1, 14, :_reduce_none, 2, 16, :_reduce_6, 6, 15, :_reduce_7, 1, 17, :_reduce_none, 2, 17, :_reduce_9, 4, 18, :_reduce_10, 1, 20, :_reduce_none, 2, 20, :_reduce_none, 0, 19, :_reduce_none, 1, 19, :_reduce_none ] racc_reduce_n = 15 racc_shift_n = 26 racc_action_table = [ 9, 15, 1, 20, 1, 14, 12, 13, 11, 6, 7, 6, 7, 15, 18, 8, 21, 23, 25 ] racc_action_check = [ 2, 16, 2, 16, 0, 12, 8, 9, 7, 2, 2, 0, 0, 14, 15, 1, 18, 22, 24 ] racc_action_pointer = [ 2, 12, 0, nil, nil, nil, nil, -1, 0, 7, nil, nil, -4, nil, 8, 6, -4, nil, 5, nil, nil, nil, 8, nil, 9, nil ] racc_action_default = [ -15, -15, -15, -1, -3, -5, -4, -15, -15, -15, -2, -6, -15, 26, -15, -15, -15, -8, -13, -9, -7, -14, -15, -11, -10, -12 ] racc_goto_table = [ 17, 3, 19, 10, 2, 16, 22, 24 ] racc_goto_check = [ 6, 2, 6, 2, 1, 5, 7, 8 ] racc_goto_pointer = [ nil, 4, 1, nil, nil, -9, -14, -12, -15 ] racc_goto_default = [ nil, nil, nil, 4, 5, nil, nil, nil, nil ] racc_token_table = { false => 0, Object.new => 1, :DEFINE => 2, :NAME => 3, :STRING => 4, :PARAM => 5, :LCURLY => 6, :RCURLY => 7, :VALUE => 8, :RETURN => 9, :COMMENT => 10, :INLINECOMMENT => 11 } racc_use_result_var = true racc_nt_base = 12 Racc_arg = [ racc_action_table, racc_action_check, racc_action_default, racc_action_pointer, racc_goto_table, racc_goto_check, racc_goto_default, racc_goto_pointer, racc_nt_base, racc_reduce_table, racc_token_table, racc_shift_n, racc_reduce_n, racc_use_result_var ] Racc_token_to_s_table = [ '$end', 'error', 'DEFINE', 'NAME', 'STRING', 'PARAM', 'LCURLY', 'RCURLY', 'VALUE', 'RETURN', 'COMMENT', 'INLINECOMMENT', '$start', 'decls', 'decl', 'object', 'comment', 'vars', 'var', 'icomment', 'returns'] Racc_debug_parser = false ##### racc system variables end ##### # reduce 0 omitted module_eval <<'.,.,', 'grammar.ry', 6 def _reduce_1( val, _values, result ) return val[0] if val[0] result end .,., module_eval <<'.,.,', 'grammar.ry', 18 def _reduce_2( val, _values, result ) if val[1].nil? result = val[0] else if val[0].nil? result = val[1] else result = [ val[0], val[1] ].flatten end end result end .,., module_eval <<'.,.,', 'grammar.ry', 20 def _reduce_3( val, _values, result ) result = [val[0]] result end .,., module_eval <<'.,.,', 'grammar.ry', 21 def _reduce_4( val, _values, result ) result = nil result end .,., # reduce 5 omitted module_eval <<'.,.,', 'grammar.ry', 25 def _reduce_6( val, _values, result ) result = nil result end .,., module_eval <<'.,.,', 'grammar.ry', 31 def _reduce_7( val, _values, result ) result = Nagios::Base.create(val[1],val[4]) result end .,., # reduce 8 omitted module_eval <<'.,.,', 'grammar.ry', 40 def _reduce_9( val, _values, result ) val[1].each {|p,v| val[0][p] = v } result = val[0] result end .,., module_eval <<'.,.,', 'grammar.ry', 42 def _reduce_10( val, _values, result ) -result = {val[0],val[1]} +result = {val[0] => val[1]} result end .,., # reduce 11 omitted # reduce 12 omitted # reduce 13 omitted # reduce 14 omitted def _reduce_none( val, _values, result ) result end end end diff --git a/lib/puppet/indirector/exec.rb b/lib/puppet/indirector/exec.rb index fa789442b..4683eda0f 100644 --- a/lib/puppet/indirector/exec.rb +++ b/lib/puppet/indirector/exec.rb @@ -1,49 +1,48 @@ require 'puppet/indirector/terminus' require 'puppet/util' class Puppet::Indirector::Exec < Puppet::Indirector::Terminus # Look for external node definitions. def find(request) # Run the command. unless output = query(request.key) return nil end # Translate the output to ruby. output end private # Proxy the execution, so it's easier to test. def execute(command) Puppet::Util.execute(command) end # Call the external command and see if it returns our output. def query(name) external_command = command # Make sure it's an arry raise Puppet::DevError, "Exec commands must be an array" unless external_command.is_a?(Array) # Make sure it's fully qualified. raise ArgumentError, "You must set the exec parameter to a fully qualified command" unless external_command[0][0] == File::SEPARATOR[0] # Add our name to it. external_command << name begin output = execute(external_command) rescue Puppet::ExecutionFailure => detail - Puppet.err "Failed to find #{name} via exec: #{detail}" - return nil + raise Puppet::Error, "Failed to find #{name} via exec: #{detail}" end if output =~ /\A\s*\Z/ # all whitespace Puppet.debug "Empty response for #{name} from exec #{self.name} terminus" return nil else return output end end end diff --git a/lib/puppet/parameter.rb b/lib/puppet/parameter.rb index ff7cab22b..29d60fc66 100644 --- a/lib/puppet/parameter.rb +++ b/lib/puppet/parameter.rb @@ -1,302 +1,304 @@ require 'puppet/util/methodhelper' require 'puppet/util/log_paths' require 'puppet/util/logging' require 'puppet/util/docs' require 'puppet/util/cacher' class Puppet::Parameter include Puppet::Util include Puppet::Util::Errors include Puppet::Util::LogPaths include Puppet::Util::Logging include Puppet::Util::MethodHelper include Puppet::Util::Cacher require 'puppet/parameter/value_collection' class << self include Puppet::Util include Puppet::Util::Docs attr_reader :validater, :munger, :name, :default, :required_features, :value_collection attr_accessor :metaparam # Define the default value for a given parameter or parameter. This # means that 'nil' is an invalid default value. This defines # the 'default' instance method. def defaultto(value = nil, &block) if block define_method(:default, &block) else if value.nil? raise Puppet::DevError, "Either a default value or block must be provided" end define_method(:default) do value end end end # Return a documentation string. If there are valid values, # then tack them onto the string. def doc @doc ||= "" unless defined?(@addeddocvals) @doc += value_collection.doc if f = self.required_features @doc += " Requires features #{f.flatten.collect { |f| f.to_s }.join(" ")}." end @addeddocvals = true end @doc end def nodefault undef_method :default if public_method_defined? :default end # Store documentation for this parameter. def desc(str) @doc = str end def initvars @value_collection = ValueCollection.new end # This is how we munge the value. Basically, this is our # opportunity to convert the value from one form into another. def munge(&block) # I need to wrap the unsafe version in begin/rescue parameterments, # but if I directly call the block then it gets bound to the # class's context, not the instance's, thus the two methods, # instead of just one. define_method(:unsafe_munge, &block) end # Does the parameter supports reverse munge? # This will be called when something wants to access the parameter # in a canonical form different to what the storage form is. def unmunge(&block) define_method(:unmunge, &block) end # Mark whether we're the namevar. def isnamevar @isnamevar = true @required = true end # Is this parameter the namevar? Defaults to false. def isnamevar? @isnamevar end # This parameter is required. def isrequired @required = true end # Specify features that are required for this parameter to work. def required_features=(*args) @required_features = args.flatten.collect { |a| a.to_s.downcase.intern } end # Is this parameter required? Defaults to false. def required? @required end # Verify that we got a good value def validate(&block) define_method(:unsafe_validate, &block) end # Define a new value for our parameter. def newvalues(*names) @value_collection.newvalues(*names) end def aliasvalue(name, other) @value_collection.aliasvalue(name, other) end end # Just a simple method to proxy instance methods to class methods def self.proxymethods(*values) values.each { |val| define_method(val) do self.class.send(val) end } end # And then define one of these proxies for each method in our # ParamHandler class. proxymethods("required?", "isnamevar?") attr_accessor :resource # LAK 2007-05-09: Keep the @parent around for backward compatibility. attr_accessor :parent [:line, :file, :version].each do |param| define_method(param) do resource.send(param) end end def devfail(msg) self.fail(Puppet::DevError, msg) end def expirer resource.catalog end def fail(*args) type = nil if args[0].is_a?(Class) type = args.shift else type = Puppet::Error end error = type.new(args.join(" ")) error.line = @resource.line if @resource and @resource.line error.file = @resource.file if @resource and @resource.file raise error end # Basic parameter initialization. def initialize(options = {}) options = symbolize_options(options) if resource = options[:resource] self.resource = resource options.delete(:resource) else raise Puppet::DevError, "No resource set for #{self.class.name}" end set_options(options) end def log(msg) send_log(resource[:loglevel], msg) end # Is this parameter a metaparam? def metaparam? self.class.metaparam end # each parameter class must define the name method, and parameter # instances do not change that name this implicitly means that a given # object can only have one parameter instance of a given parameter # class def name self.class.name end # for testing whether we should actually do anything def noop @noop ||= false tmp = @noop || self.resource.noop || Puppet[:noop] || false #debug "noop is #{tmp}" tmp end # return the full path to us, for logging and rollback; not currently # used def pathbuilder if @resource return [@resource.pathbuilder, self.name] else return [self.name] end end # If the specified value is allowed, then munge appropriately. # If the developer uses a 'munge' hook, this method will get overridden. def unsafe_munge(value) self.class.value_collection.munge(value) end # no unmunge by default def unmunge(value) value end # A wrapper around our munging that makes sure we raise useful exceptions. def munge(value) begin ret = unsafe_munge(value) rescue Puppet::Error => detail Puppet.debug "Reraising #{detail}" raise rescue => detail raise Puppet::DevError, "Munging failed for value #{value.inspect} in class #{self.name}: #{detail}", detail.backtrace end ret end # Verify that the passed value is valid. # If the developer uses a 'validate' hook, this method will get overridden. def unsafe_validate(value) self.class.value_collection.validate(value) end # A protected validation method that only ever raises useful exceptions. def validate(value) begin unsafe_validate(value) rescue ArgumentError => detail fail detail.to_s rescue Puppet::Error, TypeError raise rescue => detail raise Puppet::DevError, "Validate method failed for class #{self.name}: #{detail}", detail.backtrace end end def remove @resource = nil end def value unmunge(@value) unless @value.nil? end # Store the value provided. All of the checking should possibly be # late-binding (e.g., users might not exist when the value is assigned # but might when it is asked for). def value=(value) validate(value) @value = munge(value) end # Retrieve the resource's provider. Some types don't have providers, in which # case we return the resource object itself. def provider @resource.provider end # The properties need to return tags so that logs correctly collect them. def tags unless defined?(@tags) @tags = [] # This might not be true in testing @tags = @resource.tags if @resource.respond_to? :tags @tags << self.name.to_s end @tags end def to_s name.to_s end end + +require 'puppet/parameter/path' diff --git a/lib/puppet/parameter/path.rb b/lib/puppet/parameter/path.rb new file mode 100644 index 000000000..44886afd0 --- /dev/null +++ b/lib/puppet/parameter/path.rb @@ -0,0 +1,42 @@ +require 'puppet/parameter' + +class Puppet::Parameter::Path < Puppet::Parameter + def self.accept_arrays(bool = true) + @accept_arrays = !!bool + end + def self.arrays? + @accept_arrays + end + + def validate_path(paths) + if paths.is_a?(Array) and ! self.class.arrays? then + fail "#{name} only accepts a single path, not an array of paths" + end + + # We *always* support Unix path separators, as Win32 does now too. + absolute = "[/#{::Regexp.quote(::File::SEPARATOR)}]" + win32 = Puppet.features.microsoft_windows? + + Array(paths).each do |path| + next if path =~ %r{^#{absolute}} + next if win32 and path =~ %r{^(?:[a-zA-Z]:)?#{absolute}} + fail("#{name} must be a fully qualified path") + end + + paths + end + + # This will be overridden if someone uses the validate option, which is why + # it just delegates to the other, useful, method. + def unsafe_validate(paths) + validate_path(paths) + end + + # Likewise, this might be overridden, but by default... + def unsafe_munge(paths) + if paths.is_a?(Array) and ! self.class.arrays? then + fail "#{name} only accepts a single path, not an array of paths" + end + paths + end +end diff --git a/lib/puppet/parser/lexer.rb b/lib/puppet/parser/lexer.rb index 9a25263f6..4050adeb8 100644 --- a/lib/puppet/parser/lexer.rb +++ b/lib/puppet/parser/lexer.rb @@ -1,582 +1,582 @@ # the scanner/lexer require 'strscan' require 'puppet' module Puppet class LexError < RuntimeError; end end module Puppet::Parser; end class Puppet::Parser::Lexer attr_reader :last, :file, :lexing_context, :token_queue attr_accessor :line, :indefine def lex_error msg raise Puppet::LexError.new(msg) end class Token attr_accessor :regex, :name, :string, :skip, :incr_line, :skip_text, :accumulate def initialize(regex, name) if regex.is_a?(String) @name, @string = name, regex @regex = Regexp.new(Regexp.escape(@string)) else @name, @regex = name, regex end end # MQR: Why not just alias? %w{skip accumulate}.each do |method| define_method(method+"?") do self.send(method) end end def to_s if self.string @string else @name.to_s end end def acceptable?(context={}) # By default tokens are aceeptable in any context true end end # Maintain a list of tokens. class TokenList attr_reader :regex_tokens, :string_tokens def [](name) @tokens[name] end # Create a new token. def add_token(name, regex, options = {}, &block) token = Token.new(regex, name) raise(ArgumentError, "Token #{name} already exists") if @tokens.include?(name) @tokens[token.name] = token if token.string @string_tokens << token @tokens_by_string[token.string] = token else @regex_tokens << token end options.each do |name, option| token.send(name.to_s + "=", option) end token.meta_def(:convert, &block) if block_given? token end def initialize @tokens = {} @regex_tokens = [] @string_tokens = [] @tokens_by_string = {} end # Look up a token by its value, rather than name. def lookup(string) @tokens_by_string[string] end # Define more tokens. def add_tokens(hash) hash.each do |regex, name| add_token(name, regex) end end # Sort our tokens by length, so we know once we match, we're done. # This helps us avoid the O(n^2) nature of token matching. def sort_tokens @string_tokens.sort! { |a, b| b.string.length <=> a.string.length } end end TOKENS = TokenList.new TOKENS.add_tokens( '[' => :LBRACK, ']' => :RBRACK, '{' => :LBRACE, '}' => :RBRACE, '(' => :LPAREN, ')' => :RPAREN, '=' => :EQUALS, '+=' => :APPENDS, '==' => :ISEQUAL, '>=' => :GREATEREQUAL, '>' => :GREATERTHAN, '<' => :LESSTHAN, '<=' => :LESSEQUAL, '!=' => :NOTEQUAL, '!' => :NOT, ',' => :COMMA, '.' => :DOT, ':' => :COLON, '@' => :AT, '<<|' => :LLCOLLECT, '->' => :IN_EDGE, '<-' => :OUT_EDGE, '~>' => :IN_EDGE_SUB, '<~' => :OUT_EDGE_SUB, '|>>' => :RRCOLLECT, '<|' => :LCOLLECT, '|>' => :RCOLLECT, ';' => :SEMIC, '?' => :QMARK, '\\' => :BACKSLASH, '=>' => :FARROW, '+>' => :PARROW, '+' => :PLUS, '-' => :MINUS, '/' => :DIV, '*' => :TIMES, '<<' => :LSHIFT, '>>' => :RSHIFT, '=~' => :MATCH, '!~' => :NOMATCH, %r{([a-z][-\w]*)?(::[a-z][-\w]*)+} => :CLASSNAME, # Require '::' in the class name, else we'd compete with NAME %r{((::){0,1}[A-Z][-\w]*)+} => :CLASSREF, "" => :STRING, "" => :DQPRE, "" => :DQMID, "" => :DQPOST, "" => :BOOLEAN ) TOKENS.add_token :NUMBER, %r{\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b} do |lexer, value| [TOKENS[:NAME], value] end #:stopdoc: # Issue #4161 def (TOKENS[:NUMBER]).acceptable?(context={}) ![:DQPRE,:DQMID].include? context[:after] end #:startdoc: TOKENS.add_token :NAME, %r{[a-z0-9][-\w]*} do |lexer, value| string_token = self # we're looking for keywords here if tmp = KEYWORDS.lookup(value) string_token = tmp if [:TRUE, :FALSE].include?(string_token.name) value = eval(value) string_token = TOKENS[:BOOLEAN] end end [string_token, value] end [:NAME,:CLASSNAME,:CLASSREF].each { |name_token| #:stopdoc: # Issue #4161 def (TOKENS[name_token]).acceptable?(context={}) ![:DQPRE,:DQMID].include? context[:after] end #:startdoc: } TOKENS.add_token :COMMENT, %r{#.*}, :accumulate => true, :skip => true do |lexer,value| value.sub!(/# ?/,'') [self, value] end TOKENS.add_token :MLCOMMENT, %r{/\*(.*?)\*/}m, :accumulate => true, :skip => true do |lexer, value| lexer.line += value.count("\n") value.sub!(/^\/\* ?/,'') value.sub!(/ ?\*\/$/,'') [self,value] end TOKENS.add_token :REGEX, %r{/[^/\n]*/} do |lexer, value| # Make sure we haven't matched an escaped / while value[-2..-2] == '\\' other = lexer.scan_until(%r{/}) value += other end regex = value.sub(%r{\A/}, "").sub(%r{/\Z}, '').gsub("\\/", "/") [self, Regexp.new(regex)] end #:stopdoc: # Issue #4161 def (TOKENS[:REGEX]).acceptable?(context={}) [:NODE,:LBRACE,:RBRACE,:MATCH,:NOMATCH,:COMMA].include? context[:after] end #:startdoc: TOKENS.add_token :RETURN, "\n", :skip => true, :incr_line => true, :skip_text => true TOKENS.add_token :SQUOTE, "'" do |lexer, value| [TOKENS[:STRING], lexer.slurpstring(value,["'"],:ignore_invalid_escapes).first ] end DQ_initial_token_types = {'$' => :DQPRE,'"' => :STRING} DQ_continuation_token_types = {'$' => :DQMID,'"' => :DQPOST} TOKENS.add_token :DQUOTE, /"/ do |lexer, value| lexer.tokenize_interpolated_string(DQ_initial_token_types) end TOKENS.add_token :DQCONT, /\}/ do |lexer, value| lexer.tokenize_interpolated_string(DQ_continuation_token_types) end #:stopdoc: # Issue #4161 def (TOKENS[:DQCONT]).acceptable?(context={}) context[:string_interpolation_depth] > 0 end #:startdoc: TOKENS.add_token :DOLLAR_VAR, %r{\$(\w*::)*\w+} do |lexer, value| [TOKENS[:VARIABLE],value[1..-1]] end TOKENS.add_token :VARIABLE, %r{(\w*::)*\w+} #:stopdoc: # Issue #4161 def (TOKENS[:VARIABLE]).acceptable?(context={}) [:DQPRE,:DQMID].include? context[:after] end #:startdoc: TOKENS.sort_tokens @@pairs = { "{" => "}", "(" => ")", "[" => "]", "<|" => "|>", "<<|" => "|>>" } KEYWORDS = TokenList.new KEYWORDS.add_tokens( "case" => :CASE, "class" => :CLASS, "default" => :DEFAULT, "define" => :DEFINE, "import" => :IMPORT, "if" => :IF, "elsif" => :ELSIF, "else" => :ELSE, "inherits" => :INHERITS, "node" => :NODE, "and" => :AND, "or" => :OR, "undef" => :UNDEF, "false" => :FALSE, "true" => :TRUE, "in" => :IN ) def clear initvars end def expected return nil if @expected.empty? name = @expected[-1] TOKENS.lookup(name) or lex_error "Could not find expected token #{name}" end # scan the whole file # basically just used for testing def fullscan array = [] self.scan { |token, str| # Ignore any definition nesting problems @indefine = false array.push([token,str]) } array end def file=(file) @file = file @line = 1 @scanner = StringScanner.new(File.read(file)) end def shift_token @token_queue.shift end def find_string_token # We know our longest string token is three chars, so try each size in turn # until we either match or run out of chars. This way our worst-case is three # tries, where it is otherwise the number of string token we have. Also, # the lookups are optimized hash lookups, instead of regex scans. # s = @scanner.peek(3) token = TOKENS.lookup(s[0,3]) || TOKENS.lookup(s[0,2]) || TOKENS.lookup(s[0,1]) [ token, token && @scanner.scan(token.regex) ] end # Find the next token that matches a regex. We look for these first. def find_regex_token @regex += 1 best_token = nil best_length = 0 # I tried optimizing based on the first char, but it had # a slightly negative affect and was a good bit more complicated. TOKENS.regex_tokens.each do |token| if length = @scanner.match?(token.regex) and token.acceptable?(lexing_context) # We've found a longer match if length > best_length best_length = length best_token = token end end end return best_token, @scanner.scan(best_token.regex) if best_token end # Find the next token, returning the string and the token. def find_token @find += 1 shift_token || find_regex_token || find_string_token end def indefine? if defined?(@indefine) @indefine else false end end def initialize @find = 0 @regex = 0 initvars end def initvars @line = 1 @previous_token = nil @scanner = nil @file = nil # AAARRGGGG! okay, regexes in ruby are bloody annoying # no one else has "\n" =~ /\s/ @skip = %r{[ \t\r]+} @namestack = [] @token_queue = [] @indefine = false @expected = [] @commentstack = [ ['', @line] ] @lexing_context = { :after => nil, :start_of_line => true, :string_interpolation_depth => 0 } end # Make any necessary changes to the token and/or value. def munge_token(token, value) @line += 1 if token.incr_line skip if token.skip_text return if token.skip and not token.accumulate? token, value = token.convert(self, value) if token.respond_to?(:convert) return unless token if token.accumulate? comment = @commentstack.pop comment[0] << value + "\n" @commentstack.push(comment) end return if token.skip return token, { :value => value, :line => @line } end # Go up one in the namespace. def namepop @namestack.pop end # Collect the current namespace. def namespace @namestack.join("::") end # This value might have :: in it, but we don't care -- it'll be # handled normally when joining, and when popping we want to pop # this full value, however long the namespace is. def namestack(value) @namestack << value end def rest @scanner.rest end # this is the heart of the lexer def scan #Puppet.debug("entering scan") lex_error "Invalid or empty string" unless @scanner # Skip any initial whitespace. skip until token_queue.empty? and @scanner.eos? do yielded = false matched_token, value = find_token # error out if we didn't match anything at all lex_error "Could not match #{@scanner.rest[/^(\S+|\s+|.*)/]}" unless matched_token newline = matched_token.name == :RETURN # this matches a blank line; eat the previously accumulated comments getcomment if lexing_context[:start_of_line] and newline lexing_context[:start_of_line] = newline final_token, token_value = munge_token(matched_token, value) unless final_token skip next end lexing_context[:after] = final_token.name unless newline lexing_context[:string_interpolation_depth] += 1 if final_token.name == :DQPRE lexing_context[:string_interpolation_depth] -= 1 if final_token.name == :DQPOST value = token_value[:value] if match = @@pairs[value] and final_token.name != :DQUOTE and final_token.name != :SQUOTE @expected << match elsif exp = @expected[-1] and exp == value and final_token.name != :DQUOTE and final_token.name != :SQUOTE @expected.pop end if final_token.name == :LBRACE or final_token.name == :LPAREN commentpush end if final_token.name == :RPAREN commentpop end yield [final_token.name, token_value] if @previous_token namestack(value) if @previous_token.name == :CLASS and value != '{' if @previous_token.name == :DEFINE if indefine? msg = "Cannot nest definition #{value} inside #{@indefine}" self.indefine = false raise Puppet::ParseError, msg end @indefine = value end end @previous_token = final_token skip end @scanner = nil # This indicates that we're done parsing. yield [false,false] end # Skip any skipchars in our remaining string. def skip @scanner.skip(@skip) end # Provide some limited access to the scanner, for those # tokens that need it. def scan_until(regex) @scanner.scan_until(regex) end # we've encountered the start of a string... # slurp in the rest of the string and return it def slurpstring(terminators,escapes=%w{ \\ $ ' " n t s }+["\n"],ignore_invalid_escapes=false) # we search for the next quote that isn't preceded by a # backslash; the caret is there to match empty strings str = @scanner.scan_until(/([^\\]|^|[^\\])([\\]{2})*[#{terminators}]/) or lex_error "Unclosed quote after '#{last}' in '#{rest}'" @line += str.count("\n") # literal carriage returns add to the line count. str.gsub!(/\\(.)/m) { ch = $1 if escapes.include? ch case ch when 'n'; "\n" when 't'; "\t" when 's'; " " - when "\n": '' + when "\n"; '' else ch end else Puppet.warning "Unrecognised escape sequence '\\#{ch}'#{file && " in file #{file}"}#{line && " at line #{line}"}" unless ignore_invalid_escapes "\\#{ch}" end } [ str[0..-2],str[-1,1] ] end def tokenize_interpolated_string(token_type,preamble='') value,terminator = slurpstring('"$') token_queue << [TOKENS[token_type[terminator]],preamble+value] if terminator != '$' or @scanner.scan(/\{/) token_queue.shift elsif var_name = @scanner.scan(%r{(\w*::)*\w+|[0-9]}) token_queue << [TOKENS[:VARIABLE],var_name] tokenize_interpolated_string(DQ_continuation_token_types) else tokenize_interpolated_string(token_type,token_queue.pop.last + terminator) end end # just parse a string, not a whole file def string=(string) @scanner = StringScanner.new(string) end # returns the content of the currently accumulated content cache def commentpop @commentstack.pop[0] end def getcomment(line = nil) comment = @commentstack.last if line.nil? or comment[1] <= line @commentstack.pop @commentstack.push(['', @line]) return comment[0] end '' end def commentpush @commentstack.push(['', @line]) end end diff --git a/lib/puppet/provider/exec/posix.rb b/lib/puppet/provider/exec/posix.rb new file mode 100644 index 000000000..92dbd8c98 --- /dev/null +++ b/lib/puppet/provider/exec/posix.rb @@ -0,0 +1,112 @@ +Puppet::Type.type(:exec).provide :posix do + include Puppet::Util::Execution + + confine :feature => :posix + defaultfor :feature => :posix + + desc "Execute external binaries directly, on POSIX systems. +This does not pass through a shell, or perform any interpolation, but +only directly calls the command with the arguments given." + + def run(command, check = false) + output = nil + status = nil + dir = nil + + checkexe(command) + + if dir = resource[:cwd] + unless File.directory?(dir) + if check + dir = nil + else + self.fail "Working directory '#{dir}' does not exist" + end + end + end + + dir ||= Dir.pwd + + debug "Executing#{check ? " check": ""} '#{command}'" + begin + # Do our chdir + Dir.chdir(dir) do + environment = {} + + environment[:PATH] = resource[:path].join(":") if resource[:path] + + if envlist = resource[:environment] + envlist = [envlist] unless envlist.is_a? Array + envlist.each do |setting| + if setting =~ /^(\w+)=((.|\n)+)$/ + env_name = $1 + value = $2 + if environment.include?(env_name) || environment.include?(env_name.to_sym) + warning "Overriding environment setting '#{env_name}' with '#{value}'" + end + environment[env_name] = value + else + warning "Cannot understand environment setting #{setting.inspect}" + end + end + end + + withenv environment do + Timeout::timeout(resource[:timeout]) do + output, status = Puppet::Util::SUIDManager. + run_and_capture([command], resource[:user], resource[:group]) + end + # The shell returns 127 if the command is missing. + if status.exitstatus == 127 + raise ArgumentError, output + end + end + end + rescue Errno::ENOENT => detail + self.fail detail.to_s + end + + return output, status + end + + # Verify that we have the executable + def checkexe(command) + exe = extractexe(command) + + if resource[:path] + if Puppet.features.posix? and !File.exists?(exe) + withenv :PATH => resource[:path].join(File::PATH_SEPARATOR) do + exe = which(exe) || raise(ArgumentError,"Could not find command '#{exe}'") + end + elsif Puppet.features.microsoft_windows? and !File.exists?(exe) + resource[:path].each do |path| + [".exe", ".ps1", ".bat", ".com", ""].each do |extension| + file = File.join(path, exe+extension) + return if File.exists?(file) + end + end + end + end + + raise ArgumentError, "Could not find command '#{exe}'" unless File.exists?(exe) + unless File.executable?(exe) + raise ArgumentError, + "'#{exe}' is not executable" + end + end + + def extractexe(command) + # easy case: command was quoted + if command =~ /^"([^"]+)"/ + $1 + else + command.split(/ /)[0] + end + end + + def validatecmd(command) + exe = extractexe(command) + # if we're not fully qualified, require a path + self.fail "'#{command}' is not qualified and no path was specified. Please qualify the command or specify a path." if File.expand_path(exe) != exe and resource[:path].nil? + end +end diff --git a/lib/puppet/provider/exec/shell.rb b/lib/puppet/provider/exec/shell.rb new file mode 100644 index 000000000..98f309e8f --- /dev/null +++ b/lib/puppet/provider/exec/shell.rb @@ -0,0 +1,17 @@ +Puppet::Type.type(:exec).provide :shell, :parent => :posix do + include Puppet::Util::Execution + + confine :feature => :posix + + desc "Execute external binaries directly, on POSIX systems. +passing through a shell so that shell built ins are available." + + def run(command, check = false) + command = %Q{/bin/sh -c "#{command.gsub(/"/,'\"')}"} + super(command, check) + end + + def validatecmd(command) + true + end +end diff --git a/lib/puppet/provider/package/pip.rb b/lib/puppet/provider/package/pip.rb new file mode 100644 index 000000000..5abbc135a --- /dev/null +++ b/lib/puppet/provider/package/pip.rb @@ -0,0 +1,109 @@ +# Puppet package provider for Python's `pip` package management frontend. +# + +require 'puppet/provider/package' +require 'xmlrpc/client' + +Puppet::Type.type(:package).provide :pip, + :parent => ::Puppet::Provider::Package do + + desc "Python packages via `pip`." + + has_feature :installable, :uninstallable, :upgradeable, :versionable + + # Parse lines of output from `pip freeze`, which are structured as + # _package_==_version_. + def self.parse(line) + if line.chomp =~ /^([^=]+)==([^=]+)$/ + {:ensure => $2, :name => $1, :provider => name} + else + nil + end + end + + # Return an array of structured information about every installed package + # that's managed by `pip` or an empty array if `pip` is not available. + def self.instances + packages = [] + pip_cmd = which('pip') or return [] + execpipe "#{pip_cmd} freeze" do |process| + process.collect do |line| + next unless options = parse(line) + packages << new(options) + end + end + packages + end + + # Return structured information about a particular package or `nil` if + # it is not installed or `pip` itself is not available. + def query + self.class.instances.each do |provider_pip| + return provider_pip.properties if @resource[:name] == provider_pip.name + end + return nil + end + + # Ask the PyPI API for the latest version number. There is no local + # cache of PyPI's package list so this operation will always have to + # ask the web service. + def latest + client = XMLRPC::Client.new2("http://pypi.python.org/pypi") + client.http_header_extra = {"Content-Type" => "text/xml"} + result = client.call("package_releases", @resource[:name]) + result.first + end + + # Install a package. The ensure parameter may specify installed, + # latest, a version number, or, in conjunction with the source + # parameter, an SCM revision. In that case, the source parameter + # gives the fully-qualified URL to the repository. + def install + args = %w{install -q} + if @resource[:source] + args << "-e" + if String === @resource[:ensure] + args << "#{@resource[:source]}@#{@resource[:ensure]}#egg=#{ + @resource[:name]}" + else + args << "#{@resource[:source]}#egg=#{@resource[:name]}" + end + else + case @resource[:ensure] + when String + args << "#{@resource[:name]}==#{@resource[:ensure]}" + when :latest + args << "--upgrade" << @resource[:name] + else + args << @resource[:name] + end + end + lazy_pip *args + end + + # Uninstall a package. Uninstall won't work reliably on Debian/Ubuntu + # unless this issue gets fixed. + # + def uninstall + lazy_pip "uninstall", "-y", "-q", @resource[:name] + end + + def update + install + end + + # Execute a `pip` command. If Puppet doesn't yet know how to do so, + # try to teach it and if even that fails, raise the error. + private + def lazy_pip(*args) + pip *args + rescue NoMethodError => e + if pathname = which('pip') + self.class.commands :pip => pathname + pip *args + else + raise e + end + end + +end diff --git a/lib/puppet/provider/service/daemontools.rb b/lib/puppet/provider/service/daemontools.rb index bbb962a71..f5a073329 100644 --- a/lib/puppet/provider/service/daemontools.rb +++ b/lib/puppet/provider/service/daemontools.rb @@ -1,194 +1,194 @@ # Daemontools service management # # author Brice Figureau Puppet::Type.type(:service).provide :daemontools, :parent => :base do desc "Daemontools service management. This provider manages daemons running supervised by D.J.Bernstein daemontools. It tries to detect the service directory, with by order of preference: * /service * /etc/service * /var/lib/svscan The daemon directory should be placed in a directory that can be by default in: * /var/lib/service * /etc or this can be overriden in the service resource parameters:: service { \"myservice\": provider => \"daemontools\", path => \"/path/to/daemons\", } This provider supports out of the box: * start/stop (mapped to enable/disable) * enable/disable * restart * status If a service has `ensure => \"running\"`, it will link /path/to/daemon to /path/to/service, which will automatically enable the service. If a service has `ensure => \"stopped\"`, it will only down the service, not remove the /path/to/service link. " commands :svc => "/usr/bin/svc", :svstat => "/usr/bin/svstat" class << self attr_writer :defpath # Determine the daemon path. def defpath(dummy_argument=:work_arround_for_ruby_GC_bug) unless @defpath ["/var/lib/service", "/etc"].each do |path| if FileTest.exist?(path) @defpath = path break end end raise "Could not find the daemon directory (tested [/var/lib/service,/etc])" unless @defpath end @defpath end end attr_writer :servicedir # returns all providers for all existing services in @defpath # ie enabled or not def self.instances path = self.defpath unless FileTest.directory?(path) Puppet.notice "Service path #{path} does not exist" - next + return end # reject entries that aren't either a directory # or don't contain a run file Dir.entries(path).reject { |e| fullpath = File.join(path, e) e =~ /^\./ or ! FileTest.directory?(fullpath) or ! FileTest.exist?(File.join(fullpath,"run")) }.collect do |name| new(:name => name, :path => path) end end # returns the daemon dir on this node def self.daemondir self.defpath end # find the service dir on this node def servicedir unless @servicedir ["/service", "/etc/service","/var/lib/svscan"].each do |path| if FileTest.exist?(path) @servicedir = path break end end raise "Could not find service directory" unless @servicedir end @servicedir end # returns the full path of this service when enabled # (ie in the service directory) def service File.join(self.servicedir, resource[:name]) end # returns the full path to the current daemon directory # note that this path can be overriden in the resource # definition def daemon File.join(resource[:path], resource[:name]) end def status begin output = svstat self.service if output =~ /:\s+up \(/ return :running end rescue Puppet::ExecutionFailure => detail raise Puppet::Error.new( "Could not get status for service #{resource.ref}: #{detail}" ) end :stopped end def setupservice if resource[:manifest] Puppet.notice "Configuring #{resource[:name]}" command = [ resource[:manifest], resource[:name] ] #texecute("setupservice", command) rv = system("#{command}") end rescue Puppet::ExecutionFailure => detail raise Puppet::Error.new( "Cannot config #{self.service} to enable it: #{detail}" ) end def enabled? case self.status when :running # obviously if the daemon is running then it is enabled return :true else # the service is enabled if it is linked return FileTest.symlink?(self.service) ? :true : :false end end def enable if ! FileTest.directory?(self.daemon) Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}" self.setupservice end if self.daemon if ! FileTest.symlink?(self.service) Puppet.notice "Enabling #{self.service}: linking #{self.daemon} -> #{self.service}" File.symlink(self.daemon, self.service) end end rescue Puppet::ExecutionFailure => detail raise Puppet::Error.new( "No daemon directory found for #{self.service}") end def disable begin if ! FileTest.directory?(self.daemon) Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}" self.setupservice end if self.daemon if FileTest.symlink?(self.service) Puppet.notice "Disabling #{self.service}: removing link #{self.daemon} -> #{self.service}" File.unlink(self.service) end end rescue Puppet::ExecutionFailure => detail raise Puppet::Error.new( "No daemon directory found for #{self.service}") end self.stop end def restart svc "-t", self.service end def start enable unless enabled? == :true svc "-u", self.service end def stop svc "-d", self.service end end diff --git a/lib/puppet/provider/service/launchd.rb b/lib/puppet/provider/service/launchd.rb index 07c549a8b..9d813bd5a 100644 --- a/lib/puppet/provider/service/launchd.rb +++ b/lib/puppet/provider/service/launchd.rb @@ -1,266 +1,266 @@ require 'facter/util/plist' Puppet::Type.type(:service).provide :launchd, :parent => :base do desc "launchd service management framework. This provider manages jobs with launchd, which is the default service framework for Mac OS X and is potentially available for use on other platforms. See: * http://developer.apple.com/macosx/launchd.html * http://launchd.macosforge.org/ This provider reads plists out of the following directories: * /System/Library/LaunchDaemons * /System/Library/LaunchAgents * /Library/LaunchDaemons * /Library/LaunchAgents ...and builds up a list of services based upon each plist's \"Label\" entry. This provider supports: * ensure => running/stopped, * enable => true/false * status * restart Here is how the Puppet states correspond to launchd states: * stopped --- job unloaded * started --- job loaded * enabled --- 'Disable' removed from job plist file * disabled --- 'Disable' added to job plist file Note that this allows you to do something launchctl can't do, which is to be in a state of \"stopped/enabled\ or \"running/disabled\". " commands :launchctl => "/bin/launchctl" commands :sw_vers => "/usr/bin/sw_vers" commands :plutil => "/usr/bin/plutil" defaultfor :operatingsystem => :darwin confine :operatingsystem => :darwin has_feature :enableable Launchd_Paths = ["/Library/LaunchAgents", "/Library/LaunchDaemons", "/System/Library/LaunchAgents", "/System/Library/LaunchDaemons",] Launchd_Overrides = "/var/db/launchd.db/com.apple.launchd/overrides.plist" # Read a plist, whether its format is XML or in Apple's "binary1" # format. def self.read_plist(path) Plist::parse_xml(plutil('-convert', 'xml1', '-o', '/dev/stdout', path)) end # returns a label => path map for either all jobs, or just a single # job if the label is specified def self.jobsearch(label=nil) label_to_path_map = {} Launchd_Paths.each do |path| if FileTest.exists?(path) Dir.entries(path).each do |f| next if f =~ /^\..*$/ next if FileTest.directory?(f) fullpath = File.join(path, f) if FileTest.file?(fullpath) and job = read_plist(fullpath) and job.has_key?("Label") if job["Label"] == label return { label => fullpath } else label_to_path_map[job["Label"]] = fullpath end end end end end # if we didn't find the job above and we should have, error. raise Puppet::Error.new("Unable to find launchd plist for job: #{label}") if label # if returning all jobs label_to_path_map end def self.instances jobs = self.jobsearch jobs.keys.collect do |job| new(:name => job, :provider => :launchd, :path => jobs[job]) end end def self.get_macosx_version_major return @macosx_version_major if defined?(@macosx_version_major) begin # Make sure we've loaded all of the facts Facter.loadfacts if Facter.value(:macosx_productversion_major) product_version_major = Facter.value(:macosx_productversion_major) else # TODO: remove this code chunk once we require Facter 1.5.5 or higher. Puppet.warning("DEPRECATION WARNING: Future versions of the launchd provider will require Facter 1.5.5 or newer.") product_version = Facter.value(:macosx_productversion) fail("Could not determine OS X version from Facter") if product_version.nil? product_version_major = product_version.scan(/(\d+)\.(\d+)./).join(".") end fail("#{product_version_major} is not supported by the launchd provider") if %w{10.0 10.1 10.2 10.3}.include?(product_version_major) @macosx_version_major = product_version_major return @macosx_version_major rescue Puppet::ExecutionFailure => detail fail("Could not determine OS X version: #{detail}") end end # finds the path for a given label and returns the path and parsed plist # as an array of [path, plist]. Note plist is really a Hash here. def plist_from_label(label) job = self.class.jobsearch(label) job_path = job[label] if FileTest.file?(job_path) job_plist = self.class.read_plist(job_path) else raise Puppet::Error.new("Unable to parse launchd plist at path: #{job_path}") end [job_path, job_plist] end def status # launchctl list exits zero if the job is loaded # and non-zero if it isn't. Simple way to check... but is only # available on OS X 10.5 unfortunately, so we grab the whole list # and check if our resource is included. The output formats differ # between 10.4 and 10.5, thus the necessity for splitting begin output = launchctl :list raise Puppet::Error.new("launchctl list failed to return any data.") if output.nil? output.split("\n").each do |j| return :running if j.split(/\s/).last == resource[:name] end return :stopped rescue Puppet::ExecutionFailure raise Puppet::Error.new("Unable to determine status of #{resource[:name]}") end end # start the service. To get to a state of running/enabled, we need to # conditionally enable at load, then disable by modifying the plist file # directly. def start job_path, job_plist = plist_from_label(resource[:name]) did_enable_job = false cmds = [] cmds << :launchctl << :load if self.enabled? == :false # launchctl won't load disabled jobs cmds << "-w" did_enable_job = true end cmds << job_path begin execute(cmds) rescue Puppet::ExecutionFailure raise Puppet::Error.new("Unable to start service: #{resource[:name]} at path: #{job_path}") end # As load -w clears the Disabled flag, we need to add it in after self.disable if did_enable_job and resource[:enable] == :false end def stop job_path, job_plist = plist_from_label(resource[:name]) did_disable_job = false cmds = [] cmds << :launchctl << :unload if self.enabled? == :true # keepalive jobs can't be stopped without disabling cmds << "-w" did_disable_job = true end cmds << job_path begin execute(cmds) rescue Puppet::ExecutionFailure raise Puppet::Error.new("Unable to stop service: #{resource[:name]} at path: #{job_path}") end # As unload -w sets the Disabled flag, we need to add it in after self.enable if did_disable_job and resource[:enable] == :true end # launchd jobs are enabled by default. They are only disabled if the key # "Disabled" is set to true, but it can also be set to false to enable it. # In 10.6, the Disabled key in the job plist is consulted, but only if there # is no entry in the global overrides plist. # We need to draw a distinction between undefined, true and false for both # locations where the Disabled flag can be defined. def enabled? job_plist_disabled = nil overrides_disabled = nil job_path, job_plist = plist_from_label(resource[:name]) job_plist_disabled = job_plist["Disabled"] if job_plist.has_key?("Disabled") - if self.class.get_macosx_version_major == "10.6": + if self.class.get_macosx_version_major == "10.6" if FileTest.file?(Launchd_Overrides) and overrides = self.class.read_plist(Launchd_Overrides) if overrides.has_key?(resource[:name]) overrides_disabled = overrides[resource[:name]]["Disabled"] if overrides[resource[:name]].has_key?("Disabled") end end end if overrides_disabled.nil? if job_plist_disabled.nil? or job_plist_disabled == false return :true end elsif overrides_disabled == false return :true end :false end # enable and disable are a bit hacky. We write out the plist with the appropriate value # rather than dealing with launchctl as it is unable to change the Disabled flag # without actually loading/unloading the job. # In 10.6 we need to write out a disabled key to the global overrides plist, in earlier # versions this is stored in the job plist itself. def enable if self.class.get_macosx_version_major == "10.6" overrides = self.class.read_plist(Launchd_Overrides) overrides[resource[:name]] = { "Disabled" => false } Plist::Emit.save_plist(overrides, Launchd_Overrides) else job_path, job_plist = plist_from_label(resource[:name]) if self.enabled? == :false job_plist.delete("Disabled") Plist::Emit.save_plist(job_plist, job_path) end end end def disable if self.class.get_macosx_version_major == "10.6" overrides = self.class.read_plist(Launchd_Overrides) overrides[resource[:name]] = { "Disabled" => true } Plist::Emit.save_plist(overrides, Launchd_Overrides) else job_path, job_plist = plist_from_label(resource[:name]) job_plist["Disabled"] = true Plist::Emit.save_plist(job_plist, job_path) end end end diff --git a/lib/puppet/rails.rb b/lib/puppet/rails.rb index 74805bb6f..f74e63f20 100644 --- a/lib/puppet/rails.rb +++ b/lib/puppet/rails.rb @@ -1,132 +1,132 @@ # Load the appropriate libraries, or set a class indicating they aren't available require 'facter' require 'puppet' require 'logger' module Puppet::Rails TIME_DEBUG = true def self.connect # This global init does not work for testing, because we remove # the state dir on every test. return if ActiveRecord::Base.connected? Puppet.settings.use(:main, :rails, :master) ActiveRecord::Base.logger = Logger.new(Puppet[:railslog]) begin loglevel = Logger.const_get(Puppet[:rails_loglevel].upcase) ActiveRecord::Base.logger.level = loglevel rescue => detail Puppet.warning "'#{Puppet[:rails_loglevel]}' is not a valid Rails log level; using debug" ActiveRecord::Base.logger.level = Logger::DEBUG end # As of ActiveRecord 2.2 allow_concurrency has been deprecated and no longer has any effect. ActiveRecord::Base.allow_concurrency = true if Puppet::Util.activerecord_version < 2.2 ActiveRecord::Base.verify_active_connections! begin args = database_arguments Puppet.info "Connecting to #{args[:adapter]} database: #{args[:database]}" ActiveRecord::Base.establish_connection(args) rescue => detail puts detail.backtrace if Puppet[:trace] raise Puppet::Error, "Could not connect to database: #{detail}" end end # The arguments for initializing the database connection. def self.database_arguments adapter = Puppet[:dbadapter] args = {:adapter => adapter, :log_level => Puppet[:rails_loglevel]} case adapter when "sqlite3" args[:database] = Puppet[:dblocation] when "mysql", "postgresql" args[:host] = Puppet[:dbserver] unless Puppet[:dbserver].to_s.empty? args[:port] = Puppet[:dbport] unless Puppet[:dbport].to_s.empty? args[:username] = Puppet[:dbuser] unless Puppet[:dbuser].to_s.empty? args[:password] = Puppet[:dbpassword] unless Puppet[:dbpassword].to_s.empty? args[:pool] = Puppet[:dbconnections].to_i unless Puppet[:dbconnections].to_i <= 0 args[:database] = Puppet[:dbname] args[:reconnect]= true socket = Puppet[:dbsocket] args[:socket] = socket unless socket.to_s.empty? - when "oracle_enhanced": + when "oracle_enhanced" args[:database] = Puppet[:dbname] unless Puppet[:dbname].to_s.empty? args[:username] = Puppet[:dbuser] unless Puppet[:dbuser].to_s.empty? args[:password] = Puppet[:dbpassword] unless Puppet[:dbpassword].to_s.empty? args[:pool] = Puppet[:dbconnections].to_i unless Puppet[:dbconnections].to_i <= 0 else raise ArgumentError, "Invalid db adapter #{adapter}" end args end # Set up our database connection. It'd be nice to have a "use" system # that could make callbacks. def self.init raise Puppet::DevError, "No activerecord, cannot init Puppet::Rails" unless Puppet.features.rails? connect unless ActiveRecord::Base.connection.tables.include?("resources") require 'puppet/rails/database/schema' Puppet::Rails::Schema.init end migrate if Puppet[:dbmigrate] end # Migrate to the latest db schema. def self.migrate dbdir = nil $LOAD_PATH.each { |d| tmp = File.join(d, "puppet/rails/database") if FileTest.directory?(tmp) dbdir = tmp break end } raise Puppet::Error, "Could not find Puppet::Rails database dir" unless dbdir raise Puppet::Error, "Database has problems, can't migrate." unless ActiveRecord::Base.connection.tables.include?("resources") Puppet.notice "Migrating" begin ActiveRecord::Migrator.migrate(dbdir) rescue => detail puts detail.backtrace if Puppet[:trace] raise Puppet::Error, "Could not migrate database: #{detail}" end end # Tear down the database. Mostly only used during testing. def self.teardown raise Puppet::DevError, "No activerecord, cannot init Puppet::Rails" unless Puppet.features.rails? Puppet.settings.use(:master, :rails) begin ActiveRecord::Base.establish_connection(database_arguments) rescue => detail puts detail.backtrace if Puppet[:trace] raise Puppet::Error, "Could not connect to database: #{detail}" end ActiveRecord::Base.connection.tables.each do |t| ActiveRecord::Base.connection.drop_table t end end end require 'puppet/rails/host' if Puppet.features.rails? diff --git a/lib/puppet/type/exec.rb b/lib/puppet/type/exec.rb index ae579502a..773df2bb4 100755 --- a/lib/puppet/type/exec.rb +++ b/lib/puppet/type/exec.rb @@ -1,642 +1,507 @@ module Puppet newtype(:exec) do include Puppet::Util::Execution require 'timeout' @doc = "Executes external commands. It is critical that all commands executed using this mechanism can be run multiple times without harm, i.e., they are *idempotent*. One useful way to create idempotent commands is to use the checks like `creates` to avoid running the command unless some condition is met. Note that you can restrict an `exec` to only run when it receives events by using the `refreshonly` parameter; this is a useful way to have your configuration respond to events with arbitrary commands. Note also that if an `exec` receives an event from another resource, it will get executed again (or execute the command specified in `refresh`, if there is one). There is a strong tendency to use `exec` to do whatever work Puppet can't already do; while this is obviously acceptable (and unavoidable) in the short term, it is highly recommended to migrate work from `exec` to native Puppet types as quickly as possible. If you find that you are doing a lot of work with `exec`, please at least notify us at Puppet Labs what you are doing, and hopefully we can work with you to get a native resource type for the work you are doing. - - **Autorequires:** If Puppet is managing an exec's cwd or the executable file used in an exec's command, the exec resource will autorequire those files. If Puppet is managing the user that an exec should run as, the exec resource will autorequire that user." - require 'open3' + **Autorequires:** If Puppet is managing an exec's cwd or the executable file used in an exec's command, the exec resource will autorequire those files. If Puppet is managing the user that an exec should run as, the exec resource will autorequire that user." # Create a new check mechanism. It's basically just a parameter that # provides one extra 'check' method. - def self.newcheck(name, &block) + def self.newcheck(name, options = {}, &block) @checks ||= {} - check = newparam(name, &block) + check = newparam(name, options, &block) @checks[name] = check end def self.checks @checks.keys end newproperty(:returns, :array_matching => :all, :event => :executed_command) do |property| include Puppet::Util::Execution munge do |value| value.to_s end def event_name :executed_command end defaultto "0" attr_reader :output desc "The expected return code(s). An error will be returned if the executed command returns something else. Defaults to 0. Can be specified as an array of acceptable return codes or a single value." # Make output a bit prettier def change_to_s(currentvalue, newvalue) "executed successfully" end # First verify that all of our checks pass. def retrieve - # Default to somethinng - - if @resource.check + # We need to return :notrun to trigger evaluation; when that isn't + # true, we *LIE* about what happened and return a "success" for the + # value, which causes us to be treated as in_sync?, which means we + # don't actually execute anything. I think. --daniel 2011-03-10 + if @resource.check_all_attributes return :notrun else return self.should end end # Actually execute the command. def sync olddir = nil # We need a dir to change to, even if it's just the cwd dir = self.resource[:cwd] || Dir.pwd event = :executed_command tries = self.resource[:tries] try_sleep = self.resource[:try_sleep] begin tries.times do |try| # Only add debug messages for tries > 1 to reduce log spam. debug("Exec try #{try+1}/#{tries}") if tries > 1 - @output, @status = @resource.run(self.resource[:command]) + @output, @status = provider.run(self.resource[:command]) break if self.should.include?(@status.exitstatus.to_s) if try_sleep > 0 and tries > 1 debug("Sleeping for #{try_sleep} seconds between tries") sleep try_sleep end end rescue Timeout::Error self.fail "Command exceeded timeout" % value.inspect end if log = @resource[:logoutput] case log when :true log = @resource[:loglevel] when :on_failure unless self.should.include?(@status.exitstatus.to_s) log = @resource[:loglevel] else log = :false end end unless log == :false @output.split(/\n/).each { |line| self.send(log, line) } end end unless self.should.include?(@status.exitstatus.to_s) self.fail("#{self.resource[:command]} returned #{@status.exitstatus} instead of one of [#{self.should.join(",")}]") end event end end newparam(:command) do isnamevar desc "The actual command to execute. Must either be fully qualified or a search path for the command must be provided. If the command succeeds, any output produced will be logged at the instance's normal log level (usually `notice`), but if the command fails (meaning its return code does not match the specified code) then any output is logged at the `err` log level." end newparam(:path) do desc "The search path used for command execution. Commands must be fully qualified if no path is specified. Paths - can be specified as an array or as a colon-separated list." + can be specified as an array or as a colon separated list." # Support both arrays and colon-separated fields. def value=(*values) @value = values.flatten.collect { |val| if val =~ /;/ # recognize semi-colon separated paths val.split(";") elsif val =~ /^\w:[^:]*$/ # heuristic to avoid splitting a driveletter away val else val.split(":") end }.flatten end end newparam(:user) do desc "The user to run the command as. Note that if you use this then any error output is not currently captured. This is because of a bug within Ruby. If you are using Puppet to create this user, the exec will automatically require the user, as long as it is specified by name." # Most validation is handled by the SUIDManager class. validate do |user| self.fail "Only root can execute commands as other users" unless Puppet.features.root? end end newparam(:group) do desc "The group to run the command as. This seems to work quite haphazardly on different platforms -- it is a platform issue not a Ruby or Puppet one, since the same variety exists when running commnands as different users in the shell." # Validation is handled by the SUIDManager class. end - newparam(:cwd) do + newparam(:cwd, :parent => Puppet::Parameter::Path) do desc "The directory from which to run the command. If this directory does not exist, the command will fail." - - validate do |dir| - unless dir =~ /^#{File::SEPARATOR}/ - self.fail("CWD must be a fully qualified path") - end - end - - munge do |dir| - dir = dir[0] if dir.is_a?(Array) - - dir - end end newparam(:logoutput) do desc "Whether to log output. Defaults to logging output at the loglevel for the `exec` resource. Use *on_failure* to only log the output when the command reports an error. Values are **true**, *false*, *on_failure*, and any legal log level." newvalues(:true, :false, :on_failure) end newparam(:refresh) do desc "How to refresh this command. By default, the exec is just called again when it receives an event from another resource, but this parameter allows you to define a different command for refreshing." validate do |command| - @resource.validatecmd(command) + provider.validatecmd(command) end end newparam(:environment) do desc "Any additional environment variables you want to set for a command. Note that if you use this to set PATH, it will override the `path` attribute. Multiple environment variables should be specified as an array." validate do |values| values = [values] unless values.is_a? Array values.each do |value| unless value =~ /\w+=/ raise ArgumentError, "Invalid environment setting '#{value}'" end end end end newparam(:timeout) do desc "The maximum time the command should take. If the command takes longer than the timeout, the command is considered to have failed and will be stopped. Use any negative number to disable the timeout. The time is specified in seconds." munge do |value| value = value.shift if value.is_a?(Array) if value.is_a?(String) unless value =~ /^[-\d.]+$/ raise ArgumentError, "The timeout must be a number." end Float(value) else value end end defaultto 300 end newparam(:tries) do desc "The number of times execution of the command should be tried. Defaults to '1'. This many attempts will be made to execute the command until an acceptable return code is returned. Note that the timeout paramater applies to each try rather than to the complete set of tries." munge do |value| if value.is_a?(String) unless value =~ /^[\d]+$/ raise ArgumentError, "Tries must be an integer" end value = Integer(value) end raise ArgumentError, "Tries must be an integer >= 1" if value < 1 value end defaultto 1 end newparam(:try_sleep) do desc "The time to sleep in seconds between 'tries'." munge do |value| if value.is_a?(String) unless value =~ /^[-\d.]+$/ raise ArgumentError, "try_sleep must be a number" end value = Float(value) end raise ArgumentError, "try_sleep cannot be a negative number" if value < 0 value end defaultto 0 end newcheck(:refreshonly) do desc "The command should only be run as a refresh mechanism for when a dependent object is changed. It only makes sense to use this option when this command depends on some other object; it is useful for triggering an action: # Pull down the main aliases file file { \"/etc/aliases\": source => \"puppet://server/module/aliases\" } # Rebuild the database, but only when the file changes exec { newaliases: path => [\"/usr/bin\", \"/usr/sbin\"], subscribe => File[\"/etc/aliases\"], refreshonly => true } Note that only `subscribe` and `notify` can trigger actions, not `require`, so it only makes sense to use `refreshonly` with `subscribe` or `notify`." newvalues(:true, :false) # We always fail this test, because we're only supposed to run # on refresh. def check(value) # We have to invert the values. if value == :true false else true end end end - newcheck(:creates) do + newcheck(:creates, :parent => Puppet::Parameter::Path) do desc "A file that this command creates. If this parameter is provided, then the command will only be run if the specified file does not exist: exec { \"tar xf /my/tar/file.tar\": cwd => \"/var/tmp\", creates => \"/var/tmp/myfile\", path => [\"/usr/bin\", \"/usr/sbin\"] } " - # FIXME if they try to set this and fail, then we should probably - # fail the entire exec, right? - validate do |files| - files = [files] unless files.is_a? Array - - files.each do |file| - self.fail("'creates' must be set to a fully qualified path") unless file - - unless file =~ %r{^#{File::SEPARATOR}} - self.fail "'creates' files must be fully qualified." - end - end - end + accept_arrays # If the file exists, return false (i.e., don't run the command), # else return true def check(value) ! FileTest.exists?(value) end end newcheck(:unless) do desc "If this parameter is set, then this `exec` will run unless the command returns 0. For example: exec { \"/bin/echo root >> /usr/lib/cron/cron.allow\": path => \"/usr/bin:/usr/sbin:/bin\", unless => \"grep root /usr/lib/cron/cron.allow 2>/dev/null\" } This would add `root` to the cron.allow file (on Solaris) unless `grep` determines it's already there. Note that this command follows the same rules as the main command, which is to say that it must be fully qualified if the path is not set. " validate do |cmds| cmds = [cmds] unless cmds.is_a? Array - cmds.each do |cmd| - @resource.validatecmd(cmd) + cmds.each do |command| + provider.validatecmd(command) end end # Return true if the command does not return 0. def check(value) begin - output, status = @resource.run(value, true) + output, status = provider.run(value, true) rescue Timeout::Error err "Check #{value.inspect} exceeded timeout" return false end status.exitstatus != 0 end end newcheck(:onlyif) do desc "If this parameter is set, then this `exec` will only run if the command returns 0. For example: exec { \"logrotate\": path => \"/usr/bin:/usr/sbin:/bin\", onlyif => \"test `du /var/log/messages | cut -f1` -gt 100000\" } This would run `logrotate` only if that test returned true. Note that this command follows the same rules as the main command, which is to say that it must be fully qualified if the path is not set. Also note that onlyif can take an array as its value, e.g.: onlyif => [\"test -f /tmp/file1\", \"test -f /tmp/file2\"] This will only run the exec if /all/ conditions in the array return true. " validate do |cmds| cmds = [cmds] unless cmds.is_a? Array - cmds.each do |cmd| - @resource.validatecmd(cmd) + cmds.each do |command| + provider.validatecmd(command) end end # Return true if the command returns 0. def check(value) begin - output, status = @resource.run(value, true) + output, status = provider.run(value, true) rescue Timeout::Error err "Check #{value.inspect} exceeded timeout" return false end status.exitstatus == 0 end end # Exec names are not isomorphic with the objects. @isomorphic = false validate do - validatecmd(self[:command]) + provider.validatecmd(self[:command]) end # FIXME exec should autorequire any exec that 'creates' our cwd autorequire(:file) do reqs = [] # Stick the cwd in there if we have it reqs << self[:cwd] if self[:cwd] self[:command].scan(/^(#{File::SEPARATOR}\S+)/) { |str| reqs << str } self[:command].scan(/^"([^"]+)"/) { |str| reqs << str } [:onlyif, :unless].each { |param| next unless tmp = self[param] tmp = [tmp] unless tmp.is_a? Array tmp.each do |line| # And search the command line for files, adding any we # find. This will also catch the command itself if it's # fully qualified. It might not be a bad idea to add # unqualified files, but, well, that's a bit more annoying # to do. reqs += line.scan(%r{(#{File::SEPARATOR}\S+)}) end } # For some reason, the += isn't causing a flattening reqs.flatten! reqs end autorequire(:user) do # Autorequire users if they are specified by name if user = self[:user] and user !~ /^\d+$/ user end end def self.instances [] end # Verify that we pass all of the checks. The argument determines whether # we skip the :refreshonly check, which is necessary because we now check # within refresh - def check(refreshing = false) + def check_all_attributes(refreshing = false) self.class.checks.each { |check| next if refreshing and check == :refreshonly if @parameters.include?(check) val = @parameters[check].value val = [val] unless val.is_a? Array val.each do |value| return false unless @parameters[check].check(value) end end } true end - # Verify that we have the executable - def checkexe(cmd) - exe = extractexe(cmd) - - if self[:path] - if Puppet.features.posix? and !File.exists?(exe) - withenv :PATH => self[:path].join(File::PATH_SEPARATOR) do - exe = which(exe) || raise(ArgumentError,"Could not find command '#{exe}'") - end - elsif Puppet.features.microsoft_windows? and !File.exists?(exe) - self[:path].each do |path| - [".exe", ".ps1", ".bat", ".com", ""].each do |extension| - file = File.join(path, exe+extension) - return if File.exists?(file) - end - end - end - end - - raise ArgumentError, "Could not find executable '#{exe}'" unless FileTest.exists?(exe) - unless FileTest.executable?(exe) - raise ArgumentError, - "'#{exe}' is not executable" - end - end - def output if self.property(:returns).nil? return nil else return self.property(:returns).output end end # Run the command, or optionally run a separately-specified command. def refresh - if self.check(true) + if self.check_all_attributes(true) if cmd = self[:refresh] - self.run(cmd) + provider.run(cmd) else self.property(:returns).sync end end end - - # Run a command. - def run(command, check = false) - output = nil - status = nil - - dir = nil - - checkexe(command) - - if dir = self[:cwd] - unless File.directory?(dir) - if check - dir = nil - else - self.fail "Working directory '#{dir}' does not exist" - end - end - end - - dir ||= Dir.pwd - - if check - debug "Executing check '#{command}'" - else - debug "Executing '#{command}'" - end - begin - # Do our chdir - Dir.chdir(dir) do - environment = {} - - environment[:PATH] = self[:path].join(":") if self[:path] - - if envlist = self[:environment] - envlist = [envlist] unless envlist.is_a? Array - envlist.each do |setting| - if setting =~ /^(\w+)=((.|\n)+)$/ - name = $1 - value = $2 - if environment.include? name - warning( - "Overriding environment setting '#{name}' with '#{value}'" - ) - end - environment[name] = value - else - warning "Cannot understand environment setting #{setting.inspect}" - end - end - end - - withenv environment do - Timeout::timeout(self[:timeout]) do - output, status = Puppet::Util::SUIDManager.run_and_capture( - [command], self[:user], self[:group] - ) - end - # The shell returns 127 if the command is missing. - if status.exitstatus == 127 - raise ArgumentError, output - end - end - end - rescue Errno::ENOENT => detail - self.fail detail.to_s - end - - return output, status - end - - def validatecmd(cmd) - exe = extractexe(cmd) - # if we're not fully qualified, require a path - self.fail "'#{cmd}' is not qualified and no path was specified. Please qualify the command or specify a path." if File.expand_path(exe) != exe and self[:path].nil? - end - - def extractexe(cmd) - # easy case: command was quoted - if cmd =~ /^"([^"]+)"/ - $1 - else - cmd.split(/ /)[0] - end - end end end diff --git a/lib/puppet/type/file.rb b/lib/puppet/type/file.rb index 16b1f962d..1a6d0c3ac 100644 --- a/lib/puppet/type/file.rb +++ b/lib/puppet/type/file.rb @@ -1,793 +1,793 @@ require 'digest/md5' require 'cgi' require 'etc' require 'uri' require 'fileutils' require 'puppet/network/handler' require 'puppet/util/diff' require 'puppet/util/checksums' require 'puppet/network/client' require 'puppet/util/backups' Puppet::Type.newtype(:file) do include Puppet::Util::MethodHelper include Puppet::Util::Checksums include Puppet::Util::Backups @doc = "Manages local files, including setting ownership and permissions, creation of both files and directories, and retrieving entire files from remote servers. As Puppet matures, it expected that the `file` resource will be used less and less to manage content, and instead native resources will be used to do so. If you find that you are often copying files in from a central location, rather than using native resources, please contact Puppet Labs and we can hopefully work with you to develop a native resource to support what you are doing. **Autorequires:** If Puppet is managing the user or group that owns a file, the file resource will autorequire them. If Puppet is managing any parent directories of a file, the file resource will autorequire them." def self.title_patterns [ [ /^(.*?)\/*\Z/m, [ [ :path, lambda{|x| x} ] ] ] ] end newparam(:path) do desc "The path to the file to manage. Must be fully qualified." isnamevar validate do |value| # accept various path syntaxes: lone slash, posix, win32, unc unless (Puppet.features.posix? and value =~ /^\//) or (Puppet.features.microsoft_windows? and (value =~ /^.:\// or value =~ /^\/\/[^\/]+\/[^\/]+/)) fail Puppet::Error, "File paths must be fully qualified, not '#{value}'" end end # convert the current path in an index into the collection and the last # path name. The aim is to use less storage for all common paths in a hierarchy munge do |value| - path, name = File.split(value.gsub(/\/+/,'/')) + path, name = ::File.split(value.gsub(/\/+/,'/')) { :index => Puppet::FileCollection.collection.index(path), :name => name } end # and the reverse unmunge do |value| basedir = Puppet::FileCollection.collection.path(value[:index]) # a lone slash as :name indicates a root dir on windows if value[:name] == '/' basedir else - File.join( basedir, value[:name] ) + ::File.join( basedir, value[:name] ) end end end newparam(:backup) do desc "Whether files should be backed up before being replaced. The preferred method of backing files up is via a `filebucket`, which stores files by their MD5 sums and allows easy retrieval without littering directories with backups. You can specify a local filebucket or a network-accessible server-based filebucket by setting `backup => bucket-name`. Alternatively, if you specify any value that begins with a `.` (e.g., `.puppet-bak`), then Puppet will use copy the file in the same directory with that value as the extension of the backup. Setting `backup => false` disables all backups of the file in question. Puppet automatically creates a local filebucket named `puppet` and defaults to backing up there. To use a server-based filebucket, you must specify one in your configuration filebucket { main: server => puppet } The `puppet master` daemon creates a filebucket by default, so you can usually back up to your main server with this configuration. Once you've described the bucket in your configuration, you can use it in any file file { \"/my/file\": source => \"/path/in/nfs/or/something\", backup => main } This will back the file up to the central server. At this point, the benefits of using a filebucket are that you do not have backup files lying around on each of your machines, a given version of a file is only backed up once, and you can restore any given file manually, no matter how old. Eventually, transactional support will be able to automatically restore filebucketed files. " defaultto "puppet" munge do |value| # I don't really know how this is happening. value = value.shift if value.is_a?(Array) case value when false, "false", :false false when true, "true", ".puppet-bak", :true ".puppet-bak" when String value else self.fail "Invalid backup type #{value.inspect}" end end end newparam(:recurse) do desc "Whether and how deeply to do recursive management." newvalues(:true, :false, :inf, :remote, /^[0-9]+$/) # Replace the validation so that we allow numbers in # addition to string representations of them. validate { |arg| } munge do |value| newval = super(value) case newval when :true, :inf; true when :false; false when :remote; :remote when Integer, Fixnum, Bignum self.warning "Setting recursion depth with the recurse parameter is now deprecated, please use recurselimit" # recurse == 0 means no recursion return false if value == 0 resource[:recurselimit] = value true when /^\d+$/ self.warning "Setting recursion depth with the recurse parameter is now deprecated, please use recurselimit" value = Integer(value) # recurse == 0 means no recursion return false if value == 0 resource[:recurselimit] = value true else self.fail "Invalid recurse value #{value.inspect}" end end end newparam(:recurselimit) do desc "How deeply to do recursive management." newvalues(/^[0-9]+$/) munge do |value| newval = super(value) case newval when Integer, Fixnum, Bignum; value when /^\d+$/; Integer(value) else self.fail "Invalid recurselimit value #{value.inspect}" end end end newparam(:replace, :boolean => true) do desc "Whether or not to replace a file that is sourced but exists. This is useful for using file sources purely for initialization." newvalues(:true, :false) aliasvalue(:yes, :true) aliasvalue(:no, :false) defaultto :true end newparam(:force, :boolean => true) do desc "Force the file operation. Currently only used when replacing directories with links." newvalues(:true, :false) defaultto false end newparam(:ignore) do desc "A parameter which omits action on files matching specified patterns during recursion. Uses Ruby's builtin globbing engine, so shell metacharacters are fully supported, e.g. `[a-z]*`. Matches that would descend into the directory structure are ignored, e.g., `*/*`." validate do |value| unless value.is_a?(Array) or value.is_a?(String) or value == false self.devfail "Ignore must be a string or an Array" end end end newparam(:links) do desc "How to handle links during file actions. During file copying, `follow` will copy the target file instead of the link, `manage` will copy the link itself, and `ignore` will just pass it by. When not copying, `manage` and `ignore` behave equivalently (because you cannot really ignore links entirely during local recursion), and `follow` will manage the file to which the link points." newvalues(:follow, :manage) defaultto :manage end newparam(:purge, :boolean => true) do desc "Whether unmanaged files should be purged. If you have a filebucket configured the purged files will be uploaded, but if you do not, this will destroy data. Only use this option for generated files unless you really know what you are doing. This option only makes sense when recursively managing directories. Note that when using `purge` with `source`, Puppet will purge any files that are not on the remote system." defaultto :false newvalues(:true, :false) end newparam(:sourceselect) do desc "Whether to copy all valid sources, or just the first one. This parameter is only used in recursive copies; by default, the first valid source is the only one used as a recursive source, but if this parameter is set to `all`, then all valid sources will have all of their contents copied to the local host, and for sources that have the same file, the source earlier in the list will be used." defaultto :first newvalues(:first, :all) end # Autorequire any parent directories. autorequire(:file) do - basedir = File.dirname(self[:path]) + basedir = ::File.dirname(self[:path]) if basedir != self[:path] basedir else nil end end # Autorequire the owner and group of the file. {:user => :owner, :group => :group}.each do |type, property| autorequire(type) do if @parameters.include?(property) # The user/group property automatically converts to IDs next unless should = @parameters[property].shouldorig val = should[0] if val.is_a?(Integer) or val =~ /^\d+$/ nil else val end end end end CREATORS = [:content, :source, :target] SOURCE_ONLY_CHECKSUMS = [:none, :ctime, :mtime] validate do creator_count = 0 CREATORS.each do |param| creator_count += 1 if self.should(param) end creator_count += 1 if @parameters.include?(:source) self.fail "You cannot specify more than one of #{CREATORS.collect { |p| p.to_s}.join(", ")}" if creator_count > 1 self.fail "You cannot specify a remote recursion without a source" if !self[:source] and self[:recurse] == :remote self.fail "You cannot specify source when using checksum 'none'" if self[:checksum] == :none && !self[:source].nil? SOURCE_ONLY_CHECKSUMS.each do |checksum_type| self.fail "You cannot specify content when using checksum '#{checksum_type}'" if self[:checksum] == checksum_type && !self[:content].nil? end self.warning "Possible error: recurselimit is set but not recurse, no recursion will happen" if !self[:recurse] and self[:recurselimit] end def self.[](path) return nil unless path super(path.gsub(/\/+/, '/').sub(/\/$/, '')) end def self.instances(base = '/') return self.new(:name => base, :recurse => true, :recurselimit => 1, :audit => :all).recurse_local.values end @depthfirst = false # Determine the user to write files as. def asuser if self.should(:owner) and ! self.should(:owner).is_a?(Symbol) writeable = Puppet::Util::SUIDManager.asuser(self.should(:owner)) { - FileTest.writable?(File.dirname(self[:path])) + FileTest.writable?(::File.dirname(self[:path])) } # If the parent directory is writeable, then we execute # as the user in question. Otherwise we'll rely on # the 'owner' property to do things. asuser = self.should(:owner) if writeable end asuser end def bucket return @bucket if @bucket backup = self[:backup] return nil unless backup return nil if backup =~ /^\./ unless catalog or backup == "puppet" fail "Can not find filebucket for backups without a catalog" end unless catalog and filebucket = catalog.resource(:filebucket, backup) or backup == "puppet" fail "Could not find filebucket #{backup} specified in backup" end return default_bucket unless filebucket @bucket = filebucket.bucket @bucket end def default_bucket Puppet::Type.type(:filebucket).mkdefaultbucket.bucket end # Does the file currently exist? Just checks for whether # we have a stat def exist? stat ? true : false end # We have to do some extra finishing, to retrieve our bucket if # there is one. def finish # Look up our bucket, if there is one bucket super end # Create any children via recursion or whatever. def eval_generate return [] unless self.recurse? recurse #recurse.reject do |resource| # catalog.resource(:file, resource[:path]) #end.each do |child| # catalog.add_resource child # catalog.relationship_graph.add_edge self, child #end end def flush # We want to make sure we retrieve metadata anew on each transaction. @parameters.each do |name, param| param.flush if param.respond_to?(:flush) end @stat = nil end def initialize(hash) # Used for caching clients @clients = {} super # If they've specified a source, we get our 'should' values # from it. unless self[:ensure] if self[:target] self[:ensure] = :symlink elsif self[:content] self[:ensure] = :file end end @stat = nil end # Configure discovered resources to be purged. def mark_children_for_purging(children) children.each do |name, child| next if child[:source] child[:ensure] = :absent end end # Create a new file or directory object as a child to the current # object. def newchild(path) - full_path = File.join(self[:path], path) + full_path = ::File.join(self[:path], path) # Add some new values to our original arguments -- these are the ones # set at initialization. We specifically want to exclude any param # values set by the :source property or any default values. # LAK:NOTE This is kind of silly, because the whole point here is that # the values set at initialization should live as long as the resource # but values set by default or by :source should only live for the transaction # or so. Unfortunately, we don't have a straightforward way to manage # the different lifetimes of this data, so we kludge it like this. # The right-side hash wins in the merge. options = @original_parameters.merge(:path => full_path).reject { |param, value| value.nil? } # These should never be passed to our children. [:parent, :ensure, :recurse, :recurselimit, :target, :alias, :source].each do |param| options.delete(param) if options.include?(param) end self.class.new(options) end # Files handle paths specially, because they just lengthen their # path names, rather than including the full parent's title each # time. def pathbuilder # We specifically need to call the method here, so it looks # up our parent in the catalog graph. if parent = parent() # We only need to behave specially when our parent is also # a file if parent.is_a?(self.class) # Remove the parent file name list = parent.pathbuilder list.pop # remove the parent's path info return list << self.ref else return super end else return [self.ref] end end # Should we be purging? def purge? @parameters.include?(:purge) and (self[:purge] == :true or self[:purge] == "true") end # Recursively generate a list of file resources, which will # be used to copy remote files, manage local files, and/or make links # to map to another directory. def recurse children = {} children = recurse_local if self[:recurse] != :remote if self[:target] recurse_link(children) elsif self[:source] recurse_remote(children) end # If we're purging resources, then delete any resource that isn't on the # remote system. mark_children_for_purging(children) if self.purge? result = children.values.sort { |a, b| a[:path] <=> b[:path] } remove_less_specific_files(result) end # This is to fix bug #2296, where two files recurse over the same # set of files. It's a rare case, and when it does happen you're # not likely to have many actual conflicts, which is good, because # this is a pretty inefficient implementation. def remove_less_specific_files(files) - mypath = self[:path].split(File::Separator) + mypath = self[:path].split(::File::Separator) other_paths = catalog.vertices. select { |r| r.is_a?(self.class) and r[:path] != self[:path] }. - collect { |r| r[:path].split(File::Separator) }. + collect { |r| r[:path].split(::File::Separator) }. select { |p| p[0,mypath.length] == mypath } return files if other_paths.empty? files.reject { |file| - path = file[:path].split(File::Separator) + path = file[:path].split(::File::Separator) other_paths.any? { |p| path[0,p.length] == p } } end # A simple method for determining whether we should be recursing. def recurse? return false unless @parameters.include?(:recurse) val = @parameters[:recurse].value !!(val and (val == true or val == :remote)) end # Recurse the target of the link. def recurse_link(children) perform_recursion(self[:target]).each do |meta| if meta.relative_path == "." self[:ensure] = :directory next end children[meta.relative_path] ||= newchild(meta.relative_path) if meta.ftype == "directory" children[meta.relative_path][:ensure] = :directory else children[meta.relative_path][:ensure] = :link children[meta.relative_path][:target] = meta.full_path end end children end # Recurse the file itself, returning a Metadata instance for every found file. def recurse_local result = perform_recursion(self[:path]) return {} unless result result.inject({}) do |hash, meta| next hash if meta.relative_path == "." hash[meta.relative_path] = newchild(meta.relative_path) hash end end # Recurse against our remote file. def recurse_remote(children) sourceselect = self[:sourceselect] total = self[:source].collect do |source| next unless result = perform_recursion(source) return if top = result.find { |r| r.relative_path == "." } and top.ftype != "directory" result.each { |data| data.source = "#{source}/#{data.relative_path}" } break result if result and ! result.empty? and sourceselect == :first result end.flatten # This only happens if we have sourceselect == :all unless sourceselect == :first found = [] total.reject! do |data| result = found.include?(data.relative_path) found << data.relative_path unless found.include?(data.relative_path) result end end total.each do |meta| if meta.relative_path == "." parameter(:source).metadata = meta next end children[meta.relative_path] ||= newchild(meta.relative_path) children[meta.relative_path][:source] = meta.source children[meta.relative_path][:checksum] = :md5 if meta.ftype == "file" children[meta.relative_path].parameter(:source).metadata = meta end children end def perform_recursion(path) Puppet::FileServing::Metadata.indirection.search( path, :links => self[:links], :recurse => (self[:recurse] == :remote ? true : self[:recurse]), :recurselimit => self[:recurselimit], :ignore => self[:ignore], :checksum_type => (self[:source] || self[:content]) ? self[:checksum] : :none ) end # Remove any existing data. This is only used when dealing with # links or directories. def remove_existing(should) return unless s = stat self.fail "Could not back up; will not replace" unless perform_backup unless should.to_s == "link" return if s.ftype.to_s == should.to_s end case s.ftype when "directory" if self[:force] == :true debug "Removing existing directory for replacement with #{should}" FileUtils.rmtree(self[:path]) else notice "Not removing directory; use 'force' to override" end when "link", "file" debug "Removing existing #{s.ftype} for replacement with #{should}" - File.unlink(self[:path]) + ::File.unlink(self[:path]) else self.fail "Could not back up files of type #{s.ftype}" end expire end def retrieve if source = parameter(:source) source.copy_source_values end super end # Set the checksum, from another property. There are multiple # properties that modify the contents of a file, and they need the # ability to make sure that the checksum value is in sync. def setchecksum(sum = nil) if @parameters.include? :checksum if sum @parameters[:checksum].checksum = sum else # If they didn't pass in a sum, then tell checksum to # figure it out. currentvalue = @parameters[:checksum].retrieve @parameters[:checksum].checksum = currentvalue end end end # Should this thing be a normal file? This is a relatively complex # way of determining whether we're trying to create a normal file, # and it's here so that the logic isn't visible in the content property. def should_be_file? return true if self[:ensure] == :file # I.e., it's set to something like "directory" return false if e = self[:ensure] and e != :present # The user doesn't really care, apparently if self[:ensure] == :present return true unless s = stat return(s.ftype == "file" ? true : false) end # If we've gotten here, then :ensure isn't set return true if self[:content] return true if stat and stat.ftype == "file" false end # Stat our file. Depending on the value of the 'links' attribute, we # use either 'stat' or 'lstat', and we expect the properties to use the # resulting stat object accordingly (mostly by testing the 'ftype' # value). cached_attr(:stat) do method = :stat # Files are the only types that support links if (self.class.name == :file and self[:links] != :follow) or self.class.name == :tidy method = :lstat end path = self[:path] begin - File.send(method, self[:path]) + ::File.send(method, self[:path]) rescue Errno::ENOENT => error return nil rescue Errno::EACCES => error warning "Could not stat; permission denied" return nil end end # We have to hack this just a little bit, because otherwise we'll get # an error when the target and the contents are created as properties on # the far side. def to_trans(retrieve = true) obj = super obj.delete(:target) if obj[:target] == :notlink obj end # Write out the file. Requires the property name for logging. # Write will be done by the content property, along with checksum computation def write(property) remove_existing(:file) use_temporary_file = write_temporary_file? if use_temporary_file path = "#{self[:path]}.puppettmp_#{rand(10000)}" - path = "#{self[:path]}.puppettmp_#{rand(10000)}" while File.exists?(path) or File.symlink?(path) + path = "#{self[:path]}.puppettmp_#{rand(10000)}" while ::File.exists?(path) or ::File.symlink?(path) else path = self[:path] end mode = self.should(:mode) # might be nil umask = mode ? 000 : 022 mode_int = mode ? mode.to_i(8) : nil - content_checksum = Puppet::Util.withumask(umask) { File.open(path, 'w', mode_int ) { |f| write_content(f) } } + content_checksum = Puppet::Util.withumask(umask) { ::File.open(path, 'w', mode_int ) { |f| write_content(f) } } # And put our new file in place if use_temporary_file # This is only not true when our file is empty. begin fail_if_checksum_is_wrong(path, content_checksum) if validate_checksum? - File.rename(path, self[:path]) + ::File.rename(path, self[:path]) rescue => detail fail "Could not rename temporary file #{path} to #{self[:path]}: #{detail}" ensure # Make sure the created file gets removed - File.unlink(path) if FileTest.exists?(path) + ::File.unlink(path) if FileTest.exists?(path) end end # make sure all of the modes are actually correct property_fix end private # Should we validate the checksum of the file we're writing? def validate_checksum? self[:checksum] !~ /time/ end # Make sure the file we wrote out is what we think it is. def fail_if_checksum_is_wrong(path, content_checksum) newsum = parameter(:checksum).sum_file(path) return if [:absent, nil, content_checksum].include?(newsum) self.fail "File written to disk did not match checksum; discarding changes (#{content_checksum} vs #{newsum})" end # write the current content. Note that if there is no content property # simply opening the file with 'w' as done in write is enough to truncate # or write an empty length file. def write_content(file) (content = property(:content)) && content.write(file) end private def write_temporary_file? # unfortunately we don't know the source file size before fetching it # so let's assume the file won't be empty (c = property(:content) and c.length) || (s = @parameters[:source] and 1) end # There are some cases where all of the work does not get done on # file creation/modification, so we have to do some extra checking. def property_fix properties.each do |thing| next unless [:mode, :owner, :group, :seluser, :selrole, :seltype, :selrange].include?(thing.name) # Make sure we get a new stat objct expire currentvalue = thing.retrieve thing.sync unless thing.safe_insync?(currentvalue) end end end # We put all of the properties in separate files, because there are so many # of them. The order these are loaded is important, because it determines # the order they are in the property lit. require 'puppet/type/file/checksum' require 'puppet/type/file/content' # can create the file require 'puppet/type/file/source' # can create the file require 'puppet/type/file/target' # creates a different type of file require 'puppet/type/file/ensure' # can create the file require 'puppet/type/file/owner' require 'puppet/type/file/group' require 'puppet/type/file/mode' require 'puppet/type/file/type' require 'puppet/type/file/selcontext' # SELinux file context require 'puppet/type/file/ctime' require 'puppet/type/file/mtime' diff --git a/lib/puppet/type/macauthorization.rb b/lib/puppet/type/macauthorization.rb index e89aa7c89..b16ab6dde 100644 --- a/lib/puppet/type/macauthorization.rb +++ b/lib/puppet/type/macauthorization.rb @@ -1,166 +1,166 @@ Puppet::Type.newtype(:macauthorization) do @doc = "Manage the Mac OS X authorization database. See the [Apple developer site](http://developer.apple.com/documentation/Security/Conceptual/Security_Overview/Security_Services/chapter_4_section_5.html) for more information. - + **Autorequires:** If Puppet is managing the `/etc/authorization` file, each macauthorization resource will autorequire it." ensurable autorequire(:file) do ["/etc/authorization"] end def munge_boolean(value) case value when true, "true", :true :true when false, "false", :false :false else fail("munge_boolean only takes booleans") end end def munge_integer(value) Integer(value) rescue ArgumentError fail("munge_integer only takes integers") end newparam(:name) do desc "The name of the right or rule to be managed. Corresponds to 'key' in Authorization Services. The key is the name of a rule. A key uses the same naming conventions as a right. The - Security Server uses a rule’s key to match the rule with a right. - Wildcard keys end with a ‘.’. The generic rule has an empty key value. + Security Server uses a rule's key to match the rule with a right. + Wildcard keys end with a '.'. The generic rule has an empty key value. Any rights that do not match a specific rule use the generic rule." isnamevar end newproperty(:auth_type) do desc "type - can be a 'right' or a 'rule'. 'comment' has not yet been implemented." newvalue(:right) newvalue(:rule) # newvalue(:comment) # not yet implemented. end newproperty(:allow_root, :boolean => true) do desc "Corresponds to 'allow-root' in the authorization store, renamed due to hyphens being problematic. Specifies whether a right should be allowed automatically if the requesting process is running with uid == 0. AuthorizationServices defaults this attribute to false if not specified" newvalue(:true) newvalue(:false) munge do |value| @resource.munge_boolean(value) end end newproperty(:authenticate_user, :boolean => true) do desc "Corresponds to 'authenticate-user' in the authorization store, renamed due to hyphens being problematic." newvalue(:true) newvalue(:false) munge do |value| @resource.munge_boolean(value) end end newproperty(:auth_class) do desc "Corresponds to 'class' in the authorization store, renamed due to 'class' being a reserved word." newvalue(:user) newvalue(:'evaluate-mechanisms') newvalue(:allow) newvalue(:deny) newvalue(:rule) end newproperty(:comment) do desc "The 'comment' attribute for authorization resources." end newproperty(:group) do desc "The user must authenticate as a member of this group. This attribute can be set to any one group." end newproperty(:k_of_n) do desc "k-of-n describes how large a subset of rule mechanisms must succeed for successful authentication. If there are 'n' mechanisms, then 'k' (the integer value of this parameter) mechanisms must succeed. The most common setting for this parameter is '1'. If k-of-n is not set, then 'n-of-n' mechanisms must succeed." munge do |value| @resource.munge_integer(value) end end newproperty(:mechanisms, :array_matching => :all) do desc "an array of suitable mechanisms." end newproperty(:rule, :array_matching => :all) do desc "The rule(s) that this right refers to." end newproperty(:session_owner, :boolean => true) do desc "Corresponds to 'session-owner' in the authorization store, renamed due to hyphens being problematic. Whether the session owner automatically matches this rule or right." newvalue(:true) newvalue(:false) munge do |value| @resource.munge_boolean(value) end end newproperty(:shared, :boolean => true) do desc "If this is set to true, then the Security Server marks the credentials used to gain this right as shared. The Security Server may use any shared credentials to authorize this right. For maximum security, set sharing to false so credentials stored by the Security Server for one application may not be used by another application." newvalue(:true) newvalue(:false) munge do |value| @resource.munge_boolean(value) end end newproperty(:timeout) do desc "The credential used by this rule expires in the specified number of seconds. For maximum security where the user must authenticate every time, set the timeout to 0. For minimum security, remove the timeout attribute so the user authenticates only once per session." munge do |value| @resource.munge_integer(value) end end newproperty(:tries) do desc "The number of tries allowed." munge do |value| @resource.munge_integer(value) end end end diff --git a/lib/puppet/util/classgen.rb b/lib/puppet/util/classgen.rb index ed69c5878..1e99aa873 100644 --- a/lib/puppet/util/classgen.rb +++ b/lib/puppet/util/classgen.rb @@ -1,197 +1,209 @@ module Puppet class ConstantAlreadyDefined < Error; end class SubclassAlreadyDefined < Error; end end module Puppet::Util::ClassGen include Puppet::Util::MethodHelper include Puppet::Util # Create a new subclass. Valid options are: # * :array: An array of existing classes. If specified, the new # class is added to this array. # * :attributes: A hash of attributes to set before the block is # evaluated. # * :block: The block to evaluate in the context of the class. # You can also just pass the block normally, but it will still be evaluated # with class_eval. # * :constant: What to set the constant as. Defaults to the # capitalized name. # * :hash: A hash of existing classes. If specified, the new # class is added to this hash, and it is also used for overwrite tests. # * :overwrite: Whether to overwrite an existing class. # * :parent: The parent class for the generated class. Defaults to # self. # * :prefix: The constant prefix. Default to nothing; if specified, # the capitalized name is appended and the result is set as the constant. def genclass(name, options = {}, &block) genthing(name, Class, options, block) end # Create a new module. Valid options are: # * :array: An array of existing classes. If specified, the new # class is added to this array. # * :attributes: A hash of attributes to set before the block is # evaluated. # * :block: The block to evaluate in the context of the class. # You can also just pass the block normally, but it will still be evaluated # with class_eval. # * :constant: What to set the constant as. Defaults to the # capitalized name. # * :hash: A hash of existing classes. If specified, the new # class is added to this hash, and it is also used for overwrite tests. # * :overwrite: Whether to overwrite an existing class. # * :prefix: The constant prefix. Default to nothing; if specified, # the capitalized name is appended and the result is set as the constant. def genmodule(name, options = {}, &block) genthing(name, Module, options, block) end # Remove an existing class def rmclass(name, options) options = symbolize_options(options) const = genconst_string(name, options) retval = false if const_defined?(const) remove_const(const) retval = true end if hash = options[:hash] and hash.include? name hash.delete(name) retval = true end # Let them know whether we did actually delete a subclass. retval end private # Generate the constant to create or remove. def genconst_string(name, options) unless const = options[:constant] prefix = options[:prefix] || "" const = prefix + name2const(name) end const end # This does the actual work of creating our class or module. It's just a # slightly abstract version of genclass. def genthing(name, type, options, block) options = symbolize_options(options) name = symbolize(name.to_s.downcase) if type == Module #evalmethod = :module_eval evalmethod = :class_eval # Create the class, with the correct name. klass = Module.new do class << self attr_reader :name end @name = name end else options[:parent] ||= self evalmethod = :class_eval # Create the class, with the correct name. klass = Class.new(options[:parent]) do @name = name end end # Create the constant as appropriation. handleclassconst(klass, name, options) # Initialize any necessary variables. initclass(klass, options) block ||= options[:block] # Evaluate the passed block if there is one. This should usually # define all of the work. klass.send(evalmethod, &block) if block klass.postinit if klass.respond_to? :postinit # Store the class in hashes or arrays or whatever. storeclass(klass, name, options) klass end + # const_defined? in Ruby 1.9 behaves differently in terms + # of which class hierarchy it polls for nested namespaces + # + # See http://redmine.ruby-lang.org/issues/show/1915 + def is_constant_defined?(const) + if ::RUBY_VERSION =~ /1.9/ + const_defined?(const, false) + else + const_defined?(const) + end + end + # Handle the setting and/or removing of the associated constant. def handleclassconst(klass, name, options) const = genconst_string(name, options) - if const_defined?(const) + if is_constant_defined?(const) if options[:overwrite] Puppet.info "Redefining #{name} in #{self}" remove_const(const) else raise Puppet::ConstantAlreadyDefined, "Class #{const} is already defined in #{self}" end end const_set(const, klass) const end # Perform the initializations on the class. def initclass(klass, options) klass.initvars if klass.respond_to? :initvars if attrs = options[:attributes] attrs.each do |param, value| method = param.to_s + "=" klass.send(method, value) if klass.respond_to? method end end [:include, :extend].each do |method| if set = options[method] set = [set] unless set.is_a?(Array) set.each do |mod| klass.send(method, mod) end end end klass.preinit if klass.respond_to? :preinit end # Convert our name to a constant. def name2const(name) name.to_s.capitalize end # Store the class in the appropriate places. def storeclass(klass, klassname, options) if hash = options[:hash] if hash.include? klassname and ! options[:overwrite] raise Puppet::SubclassAlreadyDefined, "Already a generated class named #{klassname}" end hash[klassname] = klass end # If we were told to stick it in a hash, then do so if array = options[:array] if (klass.respond_to? :name and array.find { |c| c.name == klassname } and ! options[:overwrite]) raise Puppet::SubclassAlreadyDefined, "Already a generated class named #{klassname}" end array << klass end end end diff --git a/lib/puppet/util/log/destinations.rb b/lib/puppet/util/log/destinations.rb index dd0d996bf..9550e2c3b 100644 --- a/lib/puppet/util/log/destinations.rb +++ b/lib/puppet/util/log/destinations.rb @@ -1,231 +1,231 @@ Puppet::Util::Log.newdesttype :syslog do def close Syslog.close end def initialize Syslog.close if Syslog.opened? name = Puppet[:name] name = "puppet-#{name}" unless name =~ /puppet/ options = Syslog::LOG_PID | Syslog::LOG_NDELAY # XXX This should really be configurable. str = Puppet[:syslogfacility] begin facility = Syslog.const_get("LOG_#{str.upcase}") rescue NameError raise Puppet::Error, "Invalid syslog facility #{str}" end @syslog = Syslog.open(name, options, facility) end def handle(msg) # XXX Syslog currently has a bug that makes it so you # cannot log a message with a '%' in it. So, we get rid # of them. if msg.source == "Puppet" @syslog.send(msg.level, msg.to_s.gsub("%", '%%')) else @syslog.send(msg.level, "(%s) %s" % [msg.source.to_s.gsub("%", ""), msg.to_s.gsub("%", '%%') ] ) end end end Puppet::Util::Log.newdesttype :file do match(/^\//) def close if defined?(@file) @file.close @file = nil end end def flush @file.flush if defined?(@file) end attr_accessor :autoflush def initialize(path) @name = path # first make sure the directory exists # We can't just use 'Config.use' here, because they've # specified a "special" destination. unless FileTest.exist?(File.dirname(path)) Puppet.recmkdir(File.dirname(path)) Puppet.info "Creating log directory #{File.dirname(path)}" end # create the log file, if it doesn't already exist file = File.open(path, File::WRONLY|File::CREAT|File::APPEND) @file = file @autoflush = Puppet[:autoflush] end def handle(msg) @file.puts("#{msg.time} #{msg.source} (#{msg.level}): #{msg}") @file.flush if @autoflush end end Puppet::Util::Log.newdesttype :console do RED = {:console => "", :html => "FFA0A0"} GREEN = {:console => "", :html => "00CD00"} YELLOW = {:console => "", :html => "FFFF60"} BLUE = {:console => "", :html => "80A0FF"} PURPLE = {:console => "", :html => "FFA500"} CYAN = {:console => "", :html => "40FFFF"} WHITE = {:console => "", :html => "FFFFFF"} HRED = {:console => "", :html => "FFA0A0"} HGREEN = {:console => "", :html => "00CD00"} HYELLOW = {:console => "", :html => "FFFF60"} HBLUE = {:console => "", :html => "80A0FF"} HPURPLE = {:console => "", :html => "FFA500"} HCYAN = {:console => "", :html => "40FFFF"} HWHITE = {:console => "", :html => "FFFFFF"} RESET = {:console => "", :html => "" } - @@colormap = { + Colormap = { :debug => WHITE, :info => GREEN, :notice => CYAN, :warning => YELLOW, :err => HPURPLE, :alert => RED, :emerg => HRED, :crit => HRED } def colorize(level, str) case Puppet[:color] when true, :ansi, "ansi", "yes"; console_color(level, str) when :html, "html"; html_color(level, str) else str end end def console_color(level, str) - @@colormap[level][:console] + str + RESET[:console] + Colormap[level][:console] + str + RESET[:console] end def html_color(level, str) - %{%s} % [@@colormap[level][:html], str] + %{%s} % [Colormap[level][:html], str] end def initialize # Flush output immediately. $stdout.sync = true end def handle(msg) if msg.source == "Puppet" puts colorize(msg.level, "#{msg.level}: #{msg}") else puts colorize(msg.level, "#{msg.level}: #{msg.source}: #{msg}") end end end Puppet::Util::Log.newdesttype :host do def initialize(host) Puppet.info "Treating #{host} as a hostname" args = {} if host =~ /:(\d+)/ args[:Port] = $1 args[:Server] = host.sub(/:\d+/, '') else args[:Server] = host end @name = host @driver = Puppet::Network::Client::LogClient.new(args) end def handle(msg) unless msg.is_a?(String) or msg.remote @hostname ||= Facter["hostname"].value unless defined?(@domain) @domain = Facter["domain"].value @hostname += ".#{@domain}" if @domain end if msg.source =~ /^\// msg.source = @hostname + ":#{msg.source}" elsif msg.source == "Puppet" msg.source = @hostname + " #{msg.source}" else msg.source = @hostname + " #{msg.source}" end begin #puts "would have sent #{msg}" #puts "would have sent %s" % # CGI.escape(YAML.dump(msg)) begin tmp = CGI.escape(YAML.dump(msg)) rescue => detail puts "Could not dump: #{detail}" return end # Add the hostname to the source @driver.addlog(tmp) rescue => detail puts detail.backtrace if Puppet[:trace] Puppet.err detail Puppet::Util::Log.close(self) end end end end # Log to a transaction report. Puppet::Util::Log.newdesttype :report do attr_reader :report match "Puppet::Transaction::Report" def initialize(report) @report = report end def handle(msg) @report << msg end end # Log to an array, just for testing. module Puppet::Test class LogCollector def initialize(logs) @logs = logs end def <<(value) @logs << value end end end Puppet::Util::Log.newdesttype :array do match "Puppet::Test::LogCollector" def initialize(messages) @messages = messages end def handle(msg) @messages << msg end end diff --git a/lib/puppet/util/rdoc/parser.rb b/lib/puppet/util/rdoc/parser.rb index 0f746e2ea..762ce25f0 100644 --- a/lib/puppet/util/rdoc/parser.rb +++ b/lib/puppet/util/rdoc/parser.rb @@ -1,487 +1,493 @@ # Puppet "parser" for the rdoc system # The parser uses puppet parser and traverse the AST to instruct RDoc about # our current structures. It also parses ruby files that could contain # either custom facts or puppet plugins (functions, types...) # rdoc mandatory includes require "rdoc/code_objects" require "puppet/util/rdoc/code_objects" require "rdoc/tokenstream" -require "rdoc/markup/simple_markup/preprocess" -require "rdoc/parsers/parserfactory" + +if ::RUBY_VERSION =~ /1.9/ + require "rdoc/markup/preprocess" + require "rdoc/parser" +else + require "rdoc/markup/simple_markup/preprocess" + require "rdoc/parsers/parserfactory" +end module RDoc class Parser - extend ParserFactory + extend ParserFactory unless ::RUBY_VERSION =~ /1.9/ SITE = "__site__" attr_accessor :input_file_name, :top_level # parser registration into RDoc parse_files_matching(/\.(rb|pp)$/) # called with the top level file def initialize(top_level, file_name, content, options, stats) @options = options @stats = stats @input_file_name = file_name @top_level = PuppetTopLevel.new(top_level) @progress = $stderr unless options.quiet end # main entry point def scan environment = Puppet::Node::Environment.new @known_resource_types = environment.known_resource_types unless environment.known_resource_types.watching_file?(@input_file_name) Puppet.info "rdoc: scanning #{@input_file_name}" if @input_file_name =~ /\.pp$/ @parser = Puppet::Parser::Parser.new(environment) @parser.file = @input_file_name @parser.parse.instantiate('').each do |type| @known_resource_types.add type end end end scan_top_level(@top_level) @top_level end # Due to a bug in RDoc, we need to roll our own find_module_named # The issue is that RDoc tries harder by asking the parent for a class/module # of the name. But by doing so, it can mistakenly use a module of same name # but from which we are not descendant. def find_object_named(container, name) return container if container.name == name container.each_classmodule do |m| return m if m.name == name end nil end # walk down the namespace and lookup/create container as needed def get_class_or_module(container, name) # class ::A -> A is in the top level if name =~ /^::/ container = @top_level end names = name.split('::') final_name = names.pop names.each do |name| prev_container = container container = find_object_named(container, name) container ||= prev_container.add_class(PuppetClass, name, nil) end [container, final_name] end # split_module tries to find if +path+ belongs to the module path # if it does, it returns the module name, otherwise if we are sure # it is part of the global manifest path, "__site__" is returned. # And finally if this path couldn't be mapped anywhere, nil is returned. def split_module(path) # find a module fullpath = File.expand_path(path) Puppet.debug "rdoc: testing #{fullpath}" if fullpath =~ /(.*)\/([^\/]+)\/(?:manifests|plugins|lib)\/.+\.(pp|rb)$/ modpath = $1 name = $2 Puppet.debug "rdoc: module #{name} into #{modpath} ?" Puppet::Module.modulepath.each do |mp| if File.identical?(modpath,mp) Puppet.debug "rdoc: found module #{name}" return name end end end if fullpath =~ /\.(pp|rb)$/ # there can be paths we don't want to scan under modules # imagine a ruby or manifest that would be distributed as part as a module # but we don't want those to be hosted under Puppet::Module.modulepath.each do |mp| # check that fullpath is a descendant of mp dirname = fullpath while (dirname = File.dirname(dirname)) != '/' return nil if File.identical?(dirname,mp) end end end # we are under a global manifests Puppet.debug "rdoc: global manifests" SITE end # create documentation for the top level +container+ def scan_top_level(container) # use the module README as documentation for the module comment = "" readme = File.join(File.dirname(File.dirname(@input_file_name)), "README") comment = File.open(readme,"r") { |f| f.read } if FileTest.readable?(readme) look_for_directives_in(container, comment) unless comment.empty? # infer module name from directory name = split_module(@input_file_name) if name.nil? # skip .pp files that are not in manifests directories as we can't guarantee they're part # of a module or the global configuration. container.document_self = false return end Puppet.debug "rdoc: scanning for #{name}" container.module_name = name container.global=true if name == SITE @stats.num_modules += 1 container, name = get_class_or_module(container,name) mod = container.add_module(PuppetModule, name) mod.record_location(@top_level) mod.comment = comment if @input_file_name =~ /\.pp$/ parse_elements(mod) elsif @input_file_name =~ /\.rb$/ parse_plugins(mod) end end # create documentation for include statements we can find in +code+ # and associate it with +container+ def scan_for_include_or_require(container, code) code = [code] unless code.is_a?(Array) code.each do |stmt| scan_for_include_or_require(container,stmt.children) if stmt.is_a?(Puppet::Parser::AST::ASTArray) if stmt.is_a?(Puppet::Parser::AST::Function) and ['include','require'].include?(stmt.name) stmt.arguments.each do |included| Puppet.debug "found #{stmt.name}: #{included}" container.send("add_#{stmt.name}",Include.new(included.to_s, stmt.doc)) end end end end # create documentation for realize statements we can find in +code+ # and associate it with +container+ def scan_for_realize(container, code) code = [code] unless code.is_a?(Array) code.each do |stmt| scan_for_realize(container,stmt.children) if stmt.is_a?(Puppet::Parser::AST::ASTArray) if stmt.is_a?(Puppet::Parser::AST::Function) and stmt.name == 'realize' stmt.arguments.each do |realized| Puppet.debug "found #{stmt.name}: #{realized}" container.add_realize(Include.new(realized.to_s, stmt.doc)) end end end end # create documentation for global variables assignements we can find in +code+ # and associate it with +container+ def scan_for_vardef(container, code) code = [code] unless code.is_a?(Array) code.each do |stmt| scan_for_vardef(container,stmt.children) if stmt.is_a?(Puppet::Parser::AST::ASTArray) if stmt.is_a?(Puppet::Parser::AST::VarDef) Puppet.debug "rdoc: found constant: #{stmt.name} = #{stmt.value}" container.add_constant(Constant.new(stmt.name.to_s, stmt.value.to_s, stmt.doc)) end end end # create documentation for resources we can find in +code+ # and associate it with +container+ def scan_for_resource(container, code) code = [code] unless code.is_a?(Array) code.each do |stmt| scan_for_resource(container,stmt.children) if stmt.is_a?(Puppet::Parser::AST::ASTArray) if stmt.is_a?(Puppet::Parser::AST::Resource) and !stmt.type.nil? begin type = stmt.type.split("::").collect { |s| s.capitalize }.join("::") stmt.instances.each do |inst| title = inst.title.is_a?(Puppet::Parser::AST::ASTArray) ? inst.title.to_s.gsub(/\[(.*)\]/,'\1') : inst.title.to_s Puppet.debug "rdoc: found resource: #{type}[#{title}]" param = [] inst.parameters.children.each do |p| res = {} res["name"] = p.param res["value"] = "#{p.value.to_s}" unless p.value.nil? param << res end container.add_resource(PuppetResource.new(type, title, stmt.doc, param)) end rescue => detail raise Puppet::ParseError, "impossible to parse resource in #{stmt.file} at line #{stmt.line}: #{detail}" end end end end def resource_stmt_to_ref(stmt) type = stmt.type.split("::").collect { |s| s.capitalize }.join("::") title = stmt.title.is_a?(Puppet::Parser::AST::ASTArray) ? stmt.title.to_s.gsub(/\[(.*)\]/,'\1') : stmt.title.to_s param = stmt.params.children.collect do |p| {"name" => p.param, "value" => p.value.to_s} end PuppetResource.new(type, title, stmt.doc, param) end # create documentation for a class named +name+ def document_class(name, klass, container) Puppet.debug "rdoc: found new class #{name}" container, name = get_class_or_module(container, name) superclass = klass.parent superclass = "" if superclass.nil? or superclass.empty? @stats.num_classes += 1 comment = klass.doc look_for_directives_in(container, comment) unless comment.empty? cls = container.add_class(PuppetClass, name, superclass) # it is possible we already encountered this class, while parsing some namespaces # from other classes of other files. But at that time we couldn't know this class superclass # so, now we know it and force it. cls.superclass = superclass cls.record_location(@top_level) # scan class code for include code = klass.code.children if klass.code.is_a?(Puppet::Parser::AST::ASTArray) code ||= klass.code unless code.nil? scan_for_include_or_require(cls, code) scan_for_realize(cls, code) scan_for_resource(cls, code) if Puppet.settings[:document_all] end cls.comment = comment rescue => detail raise Puppet::ParseError, "impossible to parse class '#{name}' in #{klass.file} at line #{klass.line}: #{detail}" end # create documentation for a node def document_node(name, node, container) Puppet.debug "rdoc: found new node #{name}" superclass = node.parent superclass = "" if superclass.nil? or superclass.empty? comment = node.doc look_for_directives_in(container, comment) unless comment.empty? n = container.add_node(name, superclass) n.record_location(@top_level) code = node.code.children if node.code.is_a?(Puppet::Parser::AST::ASTArray) code ||= node.code unless code.nil? scan_for_include_or_require(n, code) scan_for_realize(n, code) scan_for_vardef(n, code) scan_for_resource(n, code) if Puppet.settings[:document_all] end n.comment = comment rescue => detail raise Puppet::ParseError, "impossible to parse node '#{name}' in #{node.file} at line #{node.line}: #{detail}" end # create documentation for a define def document_define(name, define, container) Puppet.debug "rdoc: found new definition #{name}" # find superclas if any @stats.num_methods += 1 # find the parent # split define name by :: to find the complete module hierarchy container, name = get_class_or_module(container,name) # build up declaration declaration = "" define.arguments.each do |arg,value| declaration << "\$#{arg}" unless value.nil? declaration << " => " case value when Puppet::Parser::AST::Leaf declaration << "'#{value.value}'" when Puppet::Parser::AST::ASTArray declaration << "[#{value.children.collect { |v| "'#{v}'" }.join(", ")}]" else declaration << "#{value.to_s}" end end declaration << ", " end declaration.chop!.chop! if declaration.size > 1 # register method into the container meth = AnyMethod.new(declaration, name) meth.comment = define.doc container.add_method(meth) look_for_directives_in(container, meth.comment) unless meth.comment.empty? meth.params = "( #{declaration} )" meth.visibility = :public meth.document_self = true meth.singleton = false rescue => detail raise Puppet::ParseError, "impossible to parse definition '#{name}' in #{define.file} at line #{define.line}: #{detail}" end # Traverse the AST tree and produce code-objects node # that contains the documentation def parse_elements(container) Puppet.debug "rdoc: scanning manifest" @known_resource_types.hostclasses.values.sort { |a,b| a.name <=> b.name }.each do |klass| name = klass.name if klass.file == @input_file_name unless name.empty? document_class(name,klass,container) else # on main class document vardefs code = klass.code.children if klass.code.is_a?(Puppet::Parser::AST::ASTArray) code ||= klass.code scan_for_vardef(container, code) unless code.nil? end end end @known_resource_types.definitions.each do |name, define| if define.file == @input_file_name document_define(name,define,container) end end @known_resource_types.nodes.each do |name, node| if node.file == @input_file_name document_node(name.to_s,node,container) end end end # create documentation for plugins def parse_plugins(container) Puppet.debug "rdoc: scanning plugin or fact" if @input_file_name =~ /\/facter\/[^\/]+\.rb$/ parse_fact(container) else parse_puppet_plugin(container) end end # this is a poor man custom fact parser :-) def parse_fact(container) comments = "" current_fact = nil File.open(@input_file_name) do |of| of.each do |line| # fetch comments if line =~ /^[ \t]*# ?(.*)$/ comments += $1 + "\n" elsif line =~ /^[ \t]*Facter.add\(['"](.*?)['"]\)/ current_fact = Fact.new($1,{}) look_for_directives_in(container, comments) unless comments.empty? current_fact.comment = comments container.add_fact(current_fact) current_fact.record_location(@top_level) comments = "" Puppet.debug "rdoc: found custom fact #{current_fact.name}" elsif line =~ /^[ \t]*confine[ \t]*:(.*?)[ \t]*=>[ \t]*(.*)$/ current_fact.confine = { :type => $1, :value => $2 } unless current_fact.nil? else # unknown line type comments ="" end end end end # this is a poor man puppet plugin parser :-) # it doesn't extract doc nor desc :-( def parse_puppet_plugin(container) comments = "" current_plugin = nil File.open(@input_file_name) do |of| of.each do |line| # fetch comments if line =~ /^[ \t]*# ?(.*)$/ comments += $1 + "\n" elsif line =~ /^[ \t]*newfunction[ \t]*\([ \t]*:(.*?)[ \t]*,[ \t]*:type[ \t]*=>[ \t]*(:rvalue|:lvalue)\)/ current_plugin = Plugin.new($1, "function") container.add_plugin(current_plugin) look_for_directives_in(container, comments) unless comments.empty? current_plugin.comment = comments current_plugin.record_location(@top_level) comments = "" Puppet.debug "rdoc: found new function plugins #{current_plugin.name}" elsif line =~ /^[ \t]*Puppet::Type.newtype[ \t]*\([ \t]*:(.*?)\)/ current_plugin = Plugin.new($1, "type") container.add_plugin(current_plugin) look_for_directives_in(container, comments) unless comments.empty? current_plugin.comment = comments current_plugin.record_location(@top_level) comments = "" Puppet.debug "rdoc: found new type plugins #{current_plugin.name}" elsif line =~ /module Puppet::Parser::Functions/ # skip else # unknown line type comments ="" end end end end # look_for_directives_in scans the current +comment+ for RDoc directives def look_for_directives_in(context, comment) preprocess = SM::PreProcess.new(@input_file_name, @options.rdoc_include) preprocess.handle(comment) do |directive, param| case directive when "stopdoc" context.stop_doc "" when "startdoc" context.start_doc context.force_documentation = true "" when "enddoc" #context.done_documenting = true #"" throw :enddoc when "main" options = Options.instance options.main_page = param "" when "title" options = Options.instance options.title = param "" when "section" context.set_current_section(param, comment) comment.replace("") # 1.8 doesn't support #clear break else warn "Unrecognized directive '#{directive}'" break end end remove_private_comments(comment) end def remove_private_comments(comment) comment.gsub!(/^#--.*?^#\+\+/m, '') comment.sub!(/^#--.*/m, '') end end end diff --git a/spec/integration/indirector/catalog/compiler_spec.rb b/spec/integration/indirector/catalog/compiler_spec.rb index dcb7eb425..1146c20b0 100755 --- a/spec/integration/indirector/catalog/compiler_spec.rb +++ b/spec/integration/indirector/catalog/compiler_spec.rb @@ -1,68 +1,68 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require 'puppet/resource/catalog' Puppet::Resource::Catalog.indirection.terminus(:compiler) describe Puppet::Resource::Catalog::Compiler do before do Facter.stubs(:value).returns "something" @catalog = Puppet::Resource::Catalog.new @one = Puppet::Resource.new(:file, "/one") @two = Puppet::Resource.new(:file, "/two") @catalog.add_resource(@one, @two) end after { Puppet.settings.clear } it "should remove virtual resources when filtering" do @one.virtual = true Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.should == [ @two.ref ] end it "should not remove exported resources when filtering" do @one.exported = true Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.sort.should == [ @one.ref, @two.ref ] end it "should remove virtual exported resources when filtering" do @one.exported = true @one.virtual = true Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.should == [ @two.ref ] end it "should filter out virtual resources when finding a catalog" do @one.virtual = true request = stub 'request', :name => "mynode" Puppet::Resource::Catalog.indirection.terminus.stubs(:extract_facts_from_request) Puppet::Resource::Catalog.indirection.terminus.stubs(:node_from_request) Puppet::Resource::Catalog.indirection.terminus.stubs(:compile).returns(@catalog) Puppet::Resource::Catalog.indirection.find(request).resource_refs.should == [ @two.ref ] end it "should not filter out exported resources when finding a catalog" do @one.exported = true request = stub 'request', :name => "mynode" Puppet::Resource::Catalog.indirection.terminus.stubs(:extract_facts_from_request) Puppet::Resource::Catalog.indirection.terminus.stubs(:node_from_request) Puppet::Resource::Catalog.indirection.terminus.stubs(:compile).returns(@catalog) Puppet::Resource::Catalog.indirection.find(request).resource_refs.sort.should == [ @one.ref, @two.ref ] end it "should filter out virtual exported resources when finding a catalog" do @one.exported = true @one.virtual = true request = stub 'request', :name => "mynode" Puppet::Resource::Catalog.indirection.terminus.stubs(:extract_facts_from_request) Puppet::Resource::Catalog.indirection.terminus.stubs(:node_from_request) Puppet::Resource::Catalog.indirection.terminus.stubs(:compile).returns(@catalog) Puppet::Resource::Catalog.indirection.find(request).resource_refs.should == [ @two.ref ] end end diff --git a/spec/integration/indirector/catalog/queue_spec.rb b/spec/integration/indirector/catalog/queue_spec.rb index 4581e3062..237e489f9 100755 --- a/spec/integration/indirector/catalog/queue_spec.rb +++ b/spec/integration/indirector/catalog/queue_spec.rb @@ -1,58 +1,58 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require 'puppet/resource/catalog' describe "Puppet::Resource::Catalog::Queue", :if => Puppet.features.pson? do before do Puppet::Resource::Catalog.indirection.terminus(:queue) @catalog = Puppet::Resource::Catalog.new @one = Puppet::Resource.new(:file, "/one") @two = Puppet::Resource.new(:file, "/two") @catalog.add_resource(@one, @two) @catalog.add_edge(@one, @two) Puppet[:trace] = true end after { Puppet.settings.clear } it "should render catalogs to pson and send them via the queue client when catalogs are saved" do terminus = Puppet::Resource::Catalog.indirection.terminus(:queue) client = mock 'client' terminus.stubs(:client).returns client client.expects(:send_message).with(:catalog, @catalog.to_pson) request = Puppet::Indirector::Request.new(:catalog, :save, "foo", :instance => @catalog) terminus.save(request) end it "should intern catalog messages when they are passed via a subscription" do client = mock 'client' Puppet::Resource::Catalog::Queue.stubs(:client).returns client pson = @catalog.to_pson client.expects(:subscribe).with(:catalog).yields(pson) Puppet.expects(:err).never result = [] Puppet::Resource::Catalog::Queue.subscribe do |catalog| result << catalog end catalog = result.shift catalog.should be_instance_of(Puppet::Resource::Catalog) catalog.resource(:file, "/one").should be_instance_of(Puppet::Resource) catalog.resource(:file, "/two").should be_instance_of(Puppet::Resource) catalog.should be_edge(catalog.resource(:file, "/one"), catalog.resource(:file, "/two")) end end diff --git a/spec/integration/provider/package_spec.rb b/spec/integration/provider/package_spec.rb index 472662d6b..cc03c57a7 100755 --- a/spec/integration/provider/package_spec.rb +++ b/spec/integration/provider/package_spec.rb @@ -1,24 +1,24 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "Package Provider" do Puppet::Type.type(:package).providers.each do |name| provider = Puppet::Type.type(:package).provider(name) describe name, :if => provider.suitable? do it "should fail when asked to install an invalid package" do pending("This test hangs forever with recent versions of RubyGems") if provider.name == :gem pkg = Puppet::Type.newpackage :name => "nosuch#{provider.name}", :provider => provider.name lambda { pkg.provider.install }.should raise_error end it "should be able to get a list of existing packages" do provider.instances.each do |package| package.should be_instance_of(provider) package.properties[:provider].should == provider.name end end end end end diff --git a/spec/integration/provider/service/init_spec.rb b/spec/integration/provider/service/init_spec.rb index 2e2505bd4..c74ce29fe 100755 --- a/spec/integration/provider/service/init_spec.rb +++ b/spec/integration/provider/service/init_spec.rb @@ -1,26 +1,25 @@ #!/usr/bin/env ruby -# Find and load the spec file. -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') provider = Puppet::Type.type(:service).provider(:init) describe provider do describe "when running on FreeBSD", :if => (Facter.value(:operatingsystem) == "FreeBSD") do it "should set its default path to include /etc/init.d and /usr/local/etc/init.d" do provider.defpath.should == ["/etc/rc.d", "/usr/local/etc/rc.d"] end end describe "when running on HP-UX", :if => (Facter.value(:operatingsystem) == "HP-UX")do it "should set its default path to include /sbin/init.d" do provider.defpath.should == "/sbin/init.d" end end describe "when not running on FreeBSD or HP-UX", :if => (! %w{HP-UX FreeBSD}.include?(Facter.value(:operatingsystem))) do it "should set its default path to include /etc/init.d" do provider.defpath.should == "/etc/init.d" end end end diff --git a/spec/integration/reference/providers_spec.rb b/spec/integration/reference/providers_spec.rb index c2b1e17c5..d6e19cb59 100755 --- a/spec/integration/reference/providers_spec.rb +++ b/spec/integration/reference/providers_spec.rb @@ -1,17 +1,17 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/reference' reference = Puppet::Util::Reference.reference(:providers) describe reference do it "should exist" do reference.should_not be_nil end it "should be able to be rendered as markdown" do lambda { reference.to_markdown }.should_not raise_error end end diff --git a/spec/integration/transaction_spec.rb b/spec/integration/transaction_spec.rb index b5080b5c6..ff15e597d 100755 --- a/spec/integration/transaction_spec.rb +++ b/spec/integration/transaction_spec.rb @@ -1,284 +1,278 @@ #!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'puppet_spec/files' require 'puppet/transaction' require 'puppet_spec/files' describe Puppet::Transaction do include PuppetSpec::Files before do Puppet::Util::Storage.stubs(:store) end def mk_catalog(*resources) catalog = Puppet::Resource::Catalog.new(Puppet::Node.new("mynode")) resources.each { |res| catalog.add_resource res } catalog end it "should not apply generated resources if the parent resource fails" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => "/foo/bar", :backup => false catalog.add_resource resource child_resource = Puppet::Type.type(:file).new :path => "/foo/bar/baz", :backup => false resource.expects(:eval_generate).returns([child_resource]) transaction = Puppet::Transaction.new(catalog) resource.expects(:retrieve).raises "this is a failure" resource.stubs(:err) child_resource.expects(:retrieve).never transaction.evaluate end it "should not apply virtual resources" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => "/foo/bar", :backup => false resource.virtual = true catalog.add_resource resource transaction = Puppet::Transaction.new(catalog) resource.expects(:evaluate).never transaction.evaluate end it "should apply exported resources" do catalog = Puppet::Resource::Catalog.new path = tmpfile("exported_files") resource = Puppet::Type.type(:file).new :path => path, :backup => false, :ensure => :file resource.exported = true catalog.add_resource resource catalog.apply FileTest.should be_exist(path) end it "should not apply virtual exported resources" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => "/foo/bar", :backup => false resource.exported = true resource.virtual = true catalog.add_resource resource transaction = Puppet::Transaction.new(catalog) resource.expects(:evaluate).never transaction.evaluate end # Verify that one component requiring another causes the contained # resources in the requiring component to get refreshed. it "should propagate events from a contained resource through its container to its dependent container's contained resources" do transaction = nil file = Puppet::Type.type(:file).new :path => tmpfile("event_propagation"), :ensure => :present execfile = File.join(tmpdir("exec_event"), "exectestingness2") exec = Puppet::Type.type(:exec).new :command => "touch #{execfile}", :path => ENV['PATH'] catalog = mk_catalog(file) fcomp = Puppet::Type.type(:component).new(:name => "Foo[file]") catalog.add_resource fcomp catalog.add_edge(fcomp, file) ecomp = Puppet::Type.type(:component).new(:name => "Foo[exec]") catalog.add_resource ecomp catalog.add_resource exec catalog.add_edge(ecomp, exec) ecomp[:subscribe] = Puppet::Resource.new(:foo, "file") exec[:refreshonly] = true exec.expects(:refresh) catalog.apply end # Make sure that multiple subscriptions get triggered. it "should propagate events to all dependent resources" do path = tmpfile("path") file1 = tmpfile("file1") file2 = tmpfile("file2") - file = Puppet::Type.type(:file).new( - - :path => path, - + file = Puppet::Type.type(:file).new( + :path => path, :ensure => "file" ) - exec1 = Puppet::Type.type(:exec).new( - - :path => ENV["PATH"], + exec1 = Puppet::Type.type(:exec).new( + :path => ENV["PATH"], :command => "touch #{file1}", :refreshonly => true, - - :subscribe => Puppet::Resource.new(:file, path) + :subscribe => Puppet::Resource.new(:file, path) ) - exec2 = Puppet::Type.type(:exec).new( - - :path => ENV["PATH"], - :command => "touch #{file2}", + exec2 = Puppet::Type.type(:exec).new( + :path => ENV["PATH"], + :command => "touch #{file2}", :refreshonly => true, - - :subscribe => Puppet::Resource.new(:file, path) + :subscribe => Puppet::Resource.new(:file, path) ) catalog = mk_catalog(file, exec1, exec2) catalog.apply FileTest.should be_exist(file1) FileTest.should be_exist(file2) end it "should not let one failed refresh result in other refreshes failing" do path = tmpfile("path") newfile = tmpfile("file") file = Puppet::Type.type(:file).new( :path => path, :ensure => "file" ) exec1 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => "touch /this/cannot/possibly/exist", :logoutput => true, :refreshonly => true, :subscribe => file, :title => "one" ) exec2 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => "touch #{newfile}", :logoutput => true, :refreshonly => true, :subscribe => [file, exec1], :title => "two" ) exec1.stubs(:err) catalog = mk_catalog(file, exec1, exec2) catalog.apply FileTest.should be_exists(newfile) end it "should still trigger skipped resources" do catalog = mk_catalog catalog.add_resource(*Puppet::Type.type(:schedule).mkdefaultschedules) Puppet[:ignoreschedules] = false file = Puppet::Type.type(:file).new( :name => tmpfile("file"), :ensure => "file", :backup => false ) fname = tmpfile("exec") exec = Puppet::Type.type(:exec).new( :name => "touch #{fname}", :path => "/usr/bin:/bin", :schedule => "monthly", :subscribe => Puppet::Resource.new("file", file.name) ) catalog.add_resource(file, exec) # Run it once catalog.apply FileTest.should be_exists(fname) # Now remove it, so it can get created again File.unlink(fname) file[:content] = "some content" catalog.apply FileTest.should be_exists(fname) # Now remove it, so it can get created again File.unlink(fname) # And tag our exec exec.tag("testrun") # And our file, so it runs file.tag("norun") Puppet[:tags] = "norun" file[:content] = "totally different content" catalog.apply FileTest.should be_exists(fname) end it "should not attempt to evaluate resources with failed dependencies" do exec = Puppet::Type.type(:exec).new( :command => "/bin/mkdir /this/path/cannot/possibly/exit", :title => "mkdir" ) file1 = Puppet::Type.type(:file).new( :title => "file1", :path => tmpfile("file1"), :require => exec, :ensure => :file ) file2 = Puppet::Type.type(:file).new( :title => "file2", :path => tmpfile("file2"), :require => file1, :ensure => :file ) catalog = mk_catalog(exec, file1, file2) catalog.apply FileTest.should_not be_exists(file1[:path]) FileTest.should_not be_exists(file2[:path]) end # #801 -- resources only checked in noop should be rescheduled immediately. it "should immediately reschedule noop resources" do Puppet::Type.type(:schedule).mkdefaultschedules resource = Puppet::Type.type(:notify).new(:name => "mymessage", :noop => true) catalog = Puppet::Resource::Catalog.new catalog.add_resource resource trans = catalog.apply trans.resource_harness.should be_scheduled(trans.resource_status(resource), resource) end end diff --git a/spec/integration/util/autoload_spec.rb b/spec/integration/util/autoload_spec.rb index 8a5d66232..f9b913502 100755 --- a/spec/integration/util/autoload_spec.rb +++ b/spec/integration/util/autoload_spec.rb @@ -1,114 +1,114 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/autoload' require 'fileutils' class AutoloadIntegrator @things = [] def self.newthing(name) @things << name end def self.thing?(name) @things.include? name end def self.clear @things.clear end end require 'puppet_spec/files' describe Puppet::Util::Autoload do include PuppetSpec::Files def with_file(name, *path) path = File.join(*path) # Now create a file to load File.open(path, "w") { |f| f.puts "\nAutoloadIntegrator.newthing(:#{name.to_s})\n" } yield File.delete(path) end def with_loader(name, path) dir = tmpfile(name + path) $LOAD_PATH << dir Dir.mkdir(dir) rbdir = File.join(dir, path.to_s) Dir.mkdir(rbdir) loader = Puppet::Util::Autoload.new(name, path) yield rbdir, loader Dir.rmdir(rbdir) Dir.rmdir(dir) $LOAD_PATH.pop AutoloadIntegrator.clear end it "should make instances available by the loading class" do loader = Puppet::Util::Autoload.new("foo", "bar") Puppet::Util::Autoload["foo"].should == loader end it "should not fail when asked to load a missing file" do Puppet::Util::Autoload.new("foo", "bar").load(:eh).should be_false end it "should load and return true when it successfully loads a file" do with_loader("foo", "bar") { |dir,loader| with_file(:mything, dir, "mything.rb") { loader.load(:mything).should be_true loader.should be_loaded(:mything) AutoloadIntegrator.should be_thing(:mything) } } end it "should consider a file loaded when asked for the name without an extension" do with_loader("foo", "bar") { |dir,loader| with_file(:noext, dir, "noext.rb") { loader.load(:noext) loader.should be_loaded(:noext) } } end it "should consider a file loaded when asked for the name with an extension" do with_loader("foo", "bar") { |dir,loader| with_file(:noext, dir, "withext.rb") { loader.load(:withext) loader.should be_loaded("withext.rb") } } end it "should register the fact that the instance is loaded with the Autoload base class" do with_loader("foo", "bar") { |dir,loader| with_file(:baseload, dir, "baseload.rb") { loader.load(:baseload) Puppet::Util::Autoload.should be_loaded("bar/withext.rb") } } end it "should be able to load files directly from modules" do modulepath = tmpfile("autoload_module_testing") libdir = File.join(modulepath, "mymod", "lib", "foo") FileUtils.mkdir_p(libdir) file = File.join(libdir, "plugin.rb") Puppet[:modulepath] = modulepath with_loader("foo", "foo") do |dir, loader| with_file(:plugin, file.split("/")) do loader.load(:plugin) loader.should be_loaded("plugin.rb") end end end end diff --git a/spec/integration/util/feature_spec.rb b/spec/integration/util/feature_spec.rb index f1ada9057..b038cf308 100755 --- a/spec/integration/util/feature_spec.rb +++ b/spec/integration/util/feature_spec.rb @@ -1,54 +1,54 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/feature' require 'puppet_spec/files' describe Puppet::Util::Feature do include PuppetSpec::Files it "should be able to load features from disk" do libdir = tmpfile("feature_lib") Dir.mkdir(libdir) $LOAD_PATH << libdir $features = Puppet::Util::Feature.new("feature_lib") Dir.mkdir(File.join(libdir, "feature_lib")) File.open(File.join(libdir, "feature_lib", "able_to_load.rb"), "w") do |f| f.puts "$features.add(:able_to_load) { true }" end $features.should be_able_to_load end # TODO: Make this a spec test or remove it. def test_dynamic_loading $features = @features cleanup { $features = nil } # Now create a feature and make sure it loads. FileUtils.mkdir_p(@path) nope = File.join(@path, "nope.rb") File.open(nope, "w") { |f| f.puts "$features.add(:nope, :libs => %w{nosuchlib})" } assert_nothing_raised("Failed to autoload features") do assert(! @features.nope?, "'nope' returned true") end # First make sure "yep?" returns false assert_nothing_raised("Missing feature threw an exception") do assert(! @features.notyep?, "'notyep' returned true before definition") end yep = File.join(@path, "yep.rb") File.open(yep, "w") { |f| f.puts "$features.add(:yep, :libs => %w{puppet})" } assert(@features.yep?, "false 'yep' is apparently cached or feature could not be loaded") end end diff --git a/spec/integration/util/file_locking_spec.rb b/spec/integration/util/file_locking_spec.rb index 50613448b..1914fadf7 100755 --- a/spec/integration/util/file_locking_spec.rb +++ b/spec/integration/util/file_locking_spec.rb @@ -1,57 +1,57 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/file_locking' describe Puppet::Util::FileLocking do before :each do @file = Tempfile.new("puppetspec") filepath = @file.path @file.close!() @file = filepath @data = {:a => :b, :c => "A string", :d => "another string", :e => %w{an array of strings}} File.open(@file, "w") { |f| f.puts YAML.dump(@data) } end it "should be able to keep file corruption from happening when there are multiple writers threads" do threads = [] sync = Sync.new 9.times { |a| threads << Thread.new { 9.times { |b| sync.synchronize(Sync::SH) { Puppet::Util::FileLocking.readlock(@file) { |f| YAML.load(f.read).should == @data } } sleep 0.01 sync.synchronize(Sync::EX) { Puppet::Util::FileLocking.writelock(@file) { |f| f.puts YAML.dump(@data) } } } } } threads.each { |th| th.join } end it "should be able to keep file corruption from happening when there are multiple writers processes" do unless Process.fork 50.times { |b| Puppet::Util::FileLocking.writelock(@file) { |f| f.puts YAML.dump(@data) } sleep 0.01 } Kernel.exit! end 50.times { |c| Puppet::Util::FileLocking.readlock(@file) { |f| YAML.load(f.read).should == @data } } end end diff --git a/spec/integration/util/rdoc/parser_spec.rb b/spec/integration/util/rdoc/parser_spec.rb index 7d3b0ec3e..9cb0c9e4a 100755 --- a/spec/integration/util/rdoc/parser_spec.rb +++ b/spec/integration/util/rdoc/parser_spec.rb @@ -1,59 +1,59 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require 'puppet/resource/type_collection' require 'puppet/util/rdoc/parser' require 'puppet/util/rdoc' require 'puppet/util/rdoc/code_objects' require 'rdoc/options' require 'rdoc/rdoc' describe RDoc::Parser do require 'puppet_spec/files' include PuppetSpec::Files before :each do tmpdir = tmpfile('rdoc_parser_tmp') Dir.mkdir(tmpdir) @parsedfile = File.join(tmpdir, 'init.pp') File.open(@parsedfile, 'w') do |f| f.puts '# comment' f.puts 'class ::test {}' end @top_level = stub_everything 'toplevel', :file_relative_name => @parsedfile @module = stub_everything 'module' @puppet_top_level = RDoc::PuppetTopLevel.new(@top_level) RDoc::PuppetTopLevel.stubs(:new).returns(@puppet_top_level) @puppet_top_level.expects(:add_module).returns(@module) @parser = RDoc::Parser.new(@top_level, @parsedfile, nil, Options.instance, RDoc::Stats.new) end after(:each) do File.unlink(@parsedfile) end def get_test_class(toplevel) # toplevel -> main -> test toplevel.classes[0].classes[0] end it "should parse to RDoc data structure" do @parser.expects(:document_class).with { |n,k,c| n == "::test" and k.is_a?(Puppet::Resource::Type) } @parser.scan end it "should get a PuppetClass for the main class" do @parser.scan.classes[0].should be_a(RDoc::PuppetClass) end it "should produce a PuppetClass whose name is test" do get_test_class(@parser.scan).name.should == "test" end it "should produce a PuppetClass whose comment is 'comment'" do get_test_class(@parser.scan).comment.should == "comment\n" end end diff --git a/spec/lib/puppet_spec/verbose.rb b/spec/lib/puppet_spec/verbose.rb new file mode 100644 index 000000000..d9834f2d7 --- /dev/null +++ b/spec/lib/puppet_spec/verbose.rb @@ -0,0 +1,9 @@ +# Support code for running stuff with warnings disabled. +module Kernel + def with_verbose_disabled + verbose, $VERBOSE = $VERBOSE, nil + result = yield + $VERBOSE = verbose + return result + end +end diff --git a/spec/shared_behaviours/path_parameters.rb b/spec/shared_behaviours/path_parameters.rb new file mode 100644 index 000000000..b5a907900 --- /dev/null +++ b/spec/shared_behaviours/path_parameters.rb @@ -0,0 +1,185 @@ +# In order to use this correctly you must define a method to get an instance +# of the type being tested, so that this code can remain generic: +# +# it_should_behave_like "all path parameters", :path do +# def instance(path) +# Puppet::Type.type(:example).new( +# :name => 'foo', :require => 'bar', :path_param => path +# ) +# end +# +# That method will be invoked for each test to create the instance that we +# subsequently test through the system; you should ensure that the minimum of +# possible attributes are set to keep the tests clean. +# +# You must also pass the symbolic name of the parameter being tested to the +# block, and optionally can pass a hash of additional options to the block. +# +# The known options are: +# :array :: boolean, does this support arrays of paths, default true. + +shared_examples_for "all pathname parameters with arrays" do |win32| + path_types = { + "unix absolute" => "/foo/bar", + "unix relative" => "foo/bar", + "win32 absolute" => %q{\foo\bar}, + "win32 relative" => %q{foo\bar}, + "drive absolute" => %q{c:\foo\bar}, + "drive relative" => %q{c:foo\bar} + } + + describe "when given an array of paths" do + (1..path_types.length).each do |n| + path_types.keys.combination(n) do |set| + data = path_types.collect { |k, v| set.member?(k) ? v : nil } .compact + reject = true + only_absolute = set.find { |k| k =~ /relative/ } .nil? + only_unix = set.reject { |k| k =~ /unix/ } .length == 0 + + if only_absolute and (only_unix or win32) then + reject = false + end + + it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")}" do + if reject then + expect { instance(data) }. + should raise_error Puppet::Error, /fully qualified/ + else + instance = instance(data) + instance[@param].should == data + end + end + + it "should #{reject ? 'reject' : 'accept'} #{set.join(", ")} doubled" do + if reject then + expect { instance(data + data) }. + should raise_error Puppet::Error, /fully qualified/ + else + instance = instance(data + data) + instance[@param].should == (data + data) + end + end + end + end + end +end + + +shared_examples_for "all path parameters" do |param, options| + # Extract and process options to the block. + options ||= {} + array = options[:array].nil? ? true : options.delete(:array) + if options.keys.length > 0 then + fail "unknown options for 'all path parameters': " + + options.keys.sort.join(', ') + end + + def instance(path) + fail "we didn't implement the 'instance(path)' method in the it_should_behave_like block" + end + + ######################################################################## + # The actual testing code... + before :all do + @param = param + end + + before :each do + @file_separator = File::SEPARATOR + end + after :each do + with_verbose_disabled do + verbose, $VERBOSE = $VERBOSE, nil + File::SEPARATOR = @file_separator + $VERBOSE = verbose + end + end + + describe "on a Unix-like platform it" do + before :each do + with_verbose_disabled do + File::SEPARATOR = '/' + end + Puppet.features.stubs(:microsoft_windows?).returns(false) + Puppet.features.stubs(:posix?).returns(true) + end + + if array then + it_should_behave_like "all pathname parameters with arrays", false + end + + it "should accept a fully qualified path" do + path = File.join('', 'foo') + instance = instance(path) + instance[@param].should == path + end + + it "should give a useful error when the path is not absolute" do + path = 'foo' + expect { instance(path) }. + should raise_error Puppet::Error, /fully qualified/ + end + + { "Unix" => '/', "Win32" => '\\' }.each do |style, slash| + %w{q Q a A z Z c C}.sort.each do |drive| + it "should reject drive letter '#{drive}' with #{style} path separators" do + path = "#{drive}:#{slash}Program Files" + expect { instance(path) }. + should raise_error Puppet::Error, /fully qualified/ + end + end + end + end + + describe "on a Windows-like platform it" do + before :each do + with_verbose_disabled do + File::SEPARATOR = '\\' + end + Puppet.features.stubs(:microsoft_windows?).returns(true) + Puppet.features.stubs(:posix?).returns(false) + end + + if array then + it_should_behave_like "all pathname parameters with arrays", true + end + + it "should accept a fully qualified path" do + path = File.join('', 'foo') + instance = instance(path) + instance[@param].should == path + end + + it "should give a useful error when the path is not absolute" do + path = 'foo' + expect { instance(path) }. + should raise_error Puppet::Error, /fully qualified/ + end + + it "also accepts Unix style path separators" do + path = '/Program Files' + instance = instance(path) + instance[@param].should == path + end + + { "Unix" => '/', "Win32" => '\\' }.each do |style, slash| + %w{q Q a A z Z c C}.sort.each do |drive| + it "should accept drive letter '#{drive}' with #{style} path separators " do + path = "#{drive}:#{slash}Program Files" + instance = instance(path) + instance[@param].should == path + end + end + end + + { "UNC paths" => %q{\\foo\bar}, + "unparsed local paths" => %q{\\?\c:\foo}, + "unparsed UNC paths" => %q{\\?\foo\bar} + }.each do |name, path| + it "should accept #{name} as absolute" do + instance = instance(path) + instance[@param].should == path + end + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index d7f546b0b..13470428e 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,63 +1,69 @@ unless defined?(SPEC_HELPER_IS_LOADED) SPEC_HELPER_IS_LOADED = 1 dir = File.expand_path(File.dirname(__FILE__)) $LOAD_PATH.unshift("#{dir}/") $LOAD_PATH.unshift("#{dir}/lib") # a spec-specific test lib dir $LOAD_PATH.unshift("#{dir}/../lib") # Don't want puppet getting the command line arguments for rake or autotest ARGV.clear require 'puppet' require 'mocha' gem 'rspec', '>=2.0.0' # So everyone else doesn't have to include this base constant. module PuppetSpec FIXTURE_DIR = File.join(dir = File.expand_path(File.dirname(__FILE__)), "fixtures") unless defined?(FIXTURE_DIR) end +require 'pathname' +require 'lib/puppet_spec/verbose' require 'lib/puppet_spec/files' require 'lib/puppet_spec/fixtures' require 'monkey_patches/alias_should_to_must' require 'monkey_patches/publicize_methods' +Pathname.glob("#{dir}/shared_behaviours/**/*.rb") do |behaviour| + require behaviour.relative_path_from(Pathname.new(dir)) +end + RSpec.configure do |config| include PuppetSpec::Fixtures config.mock_with :mocha config.before :each do # these globals are set by Application $puppet_application_mode = nil $puppet_application_name = nil Signal.stubs(:trap) # Set the confdir and vardir to gibberish so that tests # have to be correctly mocked. Puppet[:confdir] = "/dev/null" Puppet[:vardir] = "/dev/null" # Avoid opening ports to the outside world Puppet.settings[:bindaddress] = "127.0.0.1" @logs = [] Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(@logs)) end config.after :each do Puppet.settings.clear Puppet::Node::Environment.clear Puppet::Util::Storage.clear Puppet::Util::ExecutionStub.reset PuppetSpec::Files.cleanup @logs.clear Puppet::Util::Log.close_all end end end diff --git a/spec/unit/application/agent_spec.rb b/spec/unit/application/agent_spec.rb index cc745d1fc..804057868 100755 --- a/spec/unit/application/agent_spec.rb +++ b/spec/unit/application/agent_spec.rb @@ -1,592 +1,593 @@ #!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/agent' require 'puppet/application/agent' require 'puppet/network/server' require 'puppet/daemon' require 'puppet/network/handler' describe Puppet::Application::Agent do before :each do @puppetd = Puppet::Application[:agent] @puppetd.stubs(:puts) @daemon = stub_everything 'daemon' Puppet::Daemon.stubs(:new).returns(@daemon) Puppet[:daemonize] = false @agent = stub_everything 'agent' Puppet::Agent.stubs(:new).returns(@agent) @puppetd.preinit Puppet::Util::Log.stubs(:newdestination) Puppet::Util::Log.stubs(:level=) Puppet::Node.indirection.stubs(:terminus_class=) Puppet::Node.indirection.stubs(:cache_class=) Puppet::Node::Facts.indirection.stubs(:terminus_class=) end it "should operate in agent run_mode" do @puppetd.class.run_mode.name.should == :agent end it "should ask Puppet::Application to parse Puppet configuration file" do @puppetd.should_parse_config?.should be_true end it "should declare a main command" do @puppetd.should respond_to(:main) end it "should declare a onetime command" do @puppetd.should respond_to(:onetime) end it "should declare a fingerprint command" do @puppetd.should respond_to(:fingerprint) end it "should declare a preinit block" do @puppetd.should respond_to(:preinit) end describe "in preinit" do it "should catch INT" do Signal.expects(:trap).with { |arg,block| arg == :INT } @puppetd.preinit end it "should init client to true" do @puppetd.preinit @puppetd.options[:client].should be_true end it "should init fqdn to nil" do @puppetd.preinit @puppetd.options[:fqdn].should be_nil end it "should init serve to []" do @puppetd.preinit @puppetd.options[:serve].should == [] end it "should use MD5 as default digest algorithm" do @puppetd.preinit @puppetd.options[:digest].should == :MD5 end it "should not fingerprint by default" do @puppetd.preinit @puppetd.options[:fingerprint].should be_false end end describe "when handling options" do before do @puppetd.command_line.stubs(:args).returns([]) end [:centrallogging, :disable, :enable, :debug, :fqdn, :test, :verbose, :digest].each do |option| it "should declare handle_#{option} method" do @puppetd.should respond_to("handle_#{option}".to_sym) end it "should store argument value when calling handle_#{option}" do @puppetd.options.expects(:[]=).with(option, 'arg') @puppetd.send("handle_#{option}".to_sym, 'arg') end end it "should set an existing handler on server" do Puppet::Network::Handler.stubs(:handler).with("handler").returns(true) @puppetd.handle_serve("handler") @puppetd.options[:serve].should == [ :handler ] end it "should set client to false with --no-client" do @puppetd.handle_no_client(nil) @puppetd.options[:client].should be_false end it "should set waitforcert to 0 with --onetime and if --waitforcert wasn't given" do Puppet[:onetime] = true Puppet::SSL::Host.any_instance.expects(:wait_for_cert).with(0) @puppetd.setup_host end it "should use supplied waitforcert when --onetime is specified" do Puppet[:onetime] = true @puppetd.handle_waitforcert(60) Puppet::SSL::Host.any_instance.expects(:wait_for_cert).with(60) @puppetd.setup_host end it "should use a default value for waitforcert when --onetime and --waitforcert are not specified" do Puppet::SSL::Host.any_instance.expects(:wait_for_cert).with(120) @puppetd.setup_host end it "should set the log destination with --logdest" do @puppetd.options.stubs(:[]=).with { |opt,val| opt == :setdest } Puppet::Log.expects(:newdestination).with("console") @puppetd.handle_logdest("console") end it "should put the setdest options to true" do @puppetd.options.expects(:[]=).with(:setdest,true) @puppetd.handle_logdest("console") end it "should parse the log destination from the command line" do @puppetd.command_line.stubs(:args).returns(%w{--logdest /my/file}) Puppet::Util::Log.expects(:newdestination).with("/my/file") @puppetd.parse_options end it "should store the waitforcert options with --waitforcert" do @puppetd.options.expects(:[]=).with(:waitforcert,42) @puppetd.handle_waitforcert("42") end it "should set args[:Port] with --port" do @puppetd.handle_port("42") @puppetd.args[:Port].should == "42" end end describe "during setup" do before :each do @puppetd.options.stubs(:[]) Puppet.stubs(:info) FileTest.stubs(:exists?).returns(true) Puppet[:libdir] = "/dev/null/lib" Puppet::SSL::Host.stubs(:ca_location=) Puppet::Transaction::Report.indirection.stubs(:terminus_class=) Puppet::Transaction::Report.indirection.stubs(:cache_class=) Puppet::Resource::Catalog.indirection.stubs(:terminus_class=) Puppet::Resource::Catalog.indirection.stubs(:cache_class=) Puppet::Node::Facts.indirection.stubs(:terminus_class=) @host = stub_everything 'host' Puppet::SSL::Host.stubs(:new).returns(@host) Puppet.stubs(:settraps) end describe "with --test" do before :each do #Puppet.settings.stubs(:handlearg) @puppetd.options.stubs(:[]=) end it "should call setup_test" do @puppetd.options.stubs(:[]).with(:test).returns(true) @puppetd.expects(:setup_test) @puppetd.setup end it "should set options[:verbose] to true" do @puppetd.options.expects(:[]=).with(:verbose,true) @puppetd.setup_test end it "should set options[:onetime] to true" do Puppet[:onetime] = false @puppetd.setup_test Puppet[:onetime].should == true end it "should set options[:detailed_exitcodes] to true" do @puppetd.options.expects(:[]=).with(:detailed_exitcodes,true) @puppetd.setup_test end end it "should call setup_logs" do @puppetd.expects(:setup_logs) @puppetd.setup end describe "when setting up logs" do before :each do Puppet::Util::Log.stubs(:newdestination) end it "should set log level to debug if --debug was passed" do @puppetd.options.stubs(:[]).with(:debug).returns(true) Puppet::Util::Log.expects(:level=).with(:debug) @puppetd.setup_logs end it "should set log level to info if --verbose was passed" do @puppetd.options.stubs(:[]).with(:verbose).returns(true) Puppet::Util::Log.expects(:level=).with(:info) @puppetd.setup_logs end [:verbose, :debug].each do |level| it "should set console as the log destination with level #{level}" do @puppetd.options.stubs(:[]).with(level).returns(true) Puppet::Util::Log.expects(:newdestination).with(:console) @puppetd.setup_logs end end it "should set syslog as the log destination if no --logdest" do @puppetd.options.stubs(:[]).with(:setdest).returns(false) Puppet::Util::Log.expects(:newdestination).with(:syslog) @puppetd.setup_logs end end it "should print puppet config if asked to in Puppet config" do @puppetd.stubs(:exit) Puppet[:configprint] = "pluginsync" Puppet.settings.expects(:print_configs) @puppetd.setup end it "should exit after printing puppet config if asked to in Puppet config" do - Puppet[:configprint] = "pluginsync" - + Puppet[:modulepath] = '/my/path' + Puppet[:configprint] = "modulepath" + Puppet::Util::Settings.any_instance.expects(:puts).with('/my/path') lambda { @puppetd.setup }.should raise_error(SystemExit) end it "should set a central log destination with --centrallogs" do @puppetd.options.stubs(:[]).with(:centrallogs).returns(true) Puppet[:server] = "puppet.reductivelabs.com" Puppet::Util::Log.stubs(:newdestination).with(:syslog) Puppet::Util::Log.expects(:newdestination).with("puppet.reductivelabs.com") @puppetd.setup end it "should use :main, :puppetd, and :ssl" do Puppet.settings.expects(:use).with(:main, :agent, :ssl) @puppetd.setup end it "should install a remote ca location" do Puppet::SSL::Host.expects(:ca_location=).with(:remote) @puppetd.setup end it "should install a none ca location in fingerprint mode" do @puppetd.options.stubs(:[]).with(:fingerprint).returns(true) Puppet::SSL::Host.expects(:ca_location=).with(:none) @puppetd.setup end it "should tell the report handler to use REST" do Puppet::Transaction::Report.indirection.expects(:terminus_class=).with(:rest) @puppetd.setup end it "should tell the report handler to cache locally as yaml" do Puppet::Transaction::Report.indirection.expects(:cache_class=).with(:yaml) @puppetd.setup end it "should change the catalog_terminus setting to 'rest'" do Puppet[:catalog_terminus] = :foo @puppetd.setup Puppet[:catalog_terminus].should == :rest end it "should tell the catalog handler to use cache" do Puppet::Resource::Catalog.indirection.expects(:cache_class=).with(:yaml) @puppetd.setup end it "should change the facts_terminus setting to 'facter'" do Puppet[:facts_terminus] = :foo @puppetd.setup Puppet[:facts_terminus].should == :facter end it "should create an agent" do Puppet::Agent.stubs(:new).with(Puppet::Configurer) @puppetd.setup end [:enable, :disable].each do |action| it "should delegate to enable_disable_client if we #{action} the agent" do @puppetd.options.stubs(:[]).with(action).returns(true) @puppetd.expects(:enable_disable_client).with(@agent) @puppetd.setup end end describe "when enabling or disabling agent" do [:enable, :disable].each do |action| it "should call client.#{action}" do @puppetd.stubs(:exit) @puppetd.options.stubs(:[]).with(action).returns(true) @agent.expects(action) @puppetd.enable_disable_client(@agent) end end it "should finally exit" do lambda { @puppetd.enable_disable_client(@agent) }.should raise_error(SystemExit) end end it "should inform the daemon about our agent if :client is set to 'true'" do @puppetd.options.expects(:[]).with(:client).returns true @daemon.expects(:agent=).with(@agent) @puppetd.setup end it "should not inform the daemon about our agent if :client is set to 'false'" do @puppetd.options[:client] = false @daemon.expects(:agent=).never @puppetd.setup end it "should daemonize if needed" do Puppet[:daemonize] = true @daemon.expects(:daemonize) @puppetd.setup end it "should wait for a certificate" do @puppetd.options.stubs(:[]).with(:waitforcert).returns(123) @host.expects(:wait_for_cert).with(123) @puppetd.setup end it "should not wait for a certificate in fingerprint mode" do @puppetd.options.stubs(:[]).with(:fingerprint).returns(true) @puppetd.options.stubs(:[]).with(:waitforcert).returns(123) @host.expects(:wait_for_cert).never @puppetd.setup end it "should setup listen if told to and not onetime" do Puppet[:listen] = true @puppetd.options.stubs(:[]).with(:onetime).returns(false) @puppetd.expects(:setup_listen) @puppetd.setup end describe "when setting up listen" do before :each do Puppet[:authconfig] = 'auth' FileTest.stubs(:exists?).with('auth').returns(true) File.stubs(:exist?).returns(true) @puppetd.options.stubs(:[]).with(:serve).returns([]) @puppetd.stubs(:exit) @server = stub_everything 'server' Puppet::Network::Server.stubs(:new).returns(@server) end it "should exit if no authorization file" do Puppet.stubs(:err) FileTest.stubs(:exists?).with(Puppet[:authconfig]).returns(false) @puppetd.expects(:exit) @puppetd.setup_listen end it "should create a server to listen on at least the Runner handler" do Puppet::Network::Server.expects(:new).with { |args| args[:xmlrpc_handlers] == [:Runner] } @puppetd.setup_listen end it "should create a server to listen for specific handlers" do @puppetd.options.stubs(:[]).with(:serve).returns([:handler]) Puppet::Network::Server.expects(:new).with { |args| args[:xmlrpc_handlers] == [:handler] } @puppetd.setup_listen end it "should use puppet default port" do Puppet[:puppetport] = 32768 Puppet::Network::Server.expects(:new).with { |args| args[:port] == 32768 } @puppetd.setup_listen end end end describe "when running" do before :each do @puppetd.agent = @agent @puppetd.daemon = @daemon @puppetd.options.stubs(:[]).with(:fingerprint).returns(false) end it "should dispatch to fingerprint if --fingerprint is used" do @puppetd.options.stubs(:[]).with(:fingerprint).returns(true) @puppetd.stubs(:fingerprint) @puppetd.run_command end it "should dispatch to onetime if --onetime is used" do @puppetd.options.stubs(:[]).with(:onetime).returns(true) @puppetd.stubs(:onetime) @puppetd.run_command end it "should dispatch to main if --onetime and --fingerprint are not used" do @puppetd.options.stubs(:[]).with(:onetime).returns(false) @puppetd.stubs(:main) @puppetd.run_command end describe "with --onetime" do before :each do @agent.stubs(:run).returns(:report) @puppetd.options.stubs(:[]).with(:client).returns(:client) @puppetd.options.stubs(:[]).with(:detailed_exitcodes).returns(false) @puppetd.stubs(:exit).with(0) Puppet.stubs(:newservice) end it "should exit if no defined --client" do $stderr.stubs(:puts) @puppetd.options.stubs(:[]).with(:client).returns(nil) @puppetd.expects(:exit).with(43) @puppetd.onetime end it "should setup traps" do @daemon.expects(:set_signal_traps) @puppetd.onetime end it "should let the agent run" do @agent.expects(:run).returns(:report) @puppetd.onetime end it "should finish by exiting with 0 error code" do @puppetd.expects(:exit).with(0) @puppetd.onetime end describe "and --detailed-exitcodes" do before :each do @puppetd.options.stubs(:[]).with(:detailed_exitcodes).returns(true) end it "should exit with report's computed exit status" do Puppet[:noop] = false report = stub 'report', :exit_status => 666 @agent.stubs(:run).returns(report) @puppetd.expects(:exit).with(666) @puppetd.onetime end it "should exit with the report's computer exit status, even if --noop is set." do Puppet[:noop] = true report = stub 'report', :exit_status => 666 @agent.stubs(:run).returns(report) @puppetd.expects(:exit).with(666) @puppetd.onetime end end end describe "with --fingerprint" do before :each do @cert = stub_everything 'cert' @puppetd.options.stubs(:[]).with(:fingerprint).returns(true) @puppetd.options.stubs(:[]).with(:digest).returns(:MD5) @host = stub_everything 'host' @puppetd.stubs(:host).returns(@host) end it "should fingerprint the certificate if it exists" do @host.expects(:certificate).returns(@cert) @cert.expects(:fingerprint).with(:MD5).returns "fingerprint" @puppetd.fingerprint end it "should fingerprint the certificate request if no certificate have been signed" do @host.expects(:certificate).returns(nil) @host.expects(:certificate_request).returns(@cert) @cert.expects(:fingerprint).with(:MD5).returns "fingerprint" @puppetd.fingerprint end it "should display the fingerprint" do @host.stubs(:certificate).returns(@cert) @cert.stubs(:fingerprint).with(:MD5).returns("DIGEST") Puppet.expects(:notice).with("DIGEST") @puppetd.fingerprint end end describe "without --onetime and --fingerprint" do before :each do Puppet.stubs(:notice) @puppetd.options.stubs(:[]).with(:client) end it "should start our daemon" do @daemon.expects(:start) @puppetd.main end end end end diff --git a/spec/unit/indirector/exec_spec.rb b/spec/unit/indirector/exec_spec.rb index c6726d4b9..d4fb22443 100755 --- a/spec/unit/indirector/exec_spec.rb +++ b/spec/unit/indirector/exec_spec.rb @@ -1,56 +1,55 @@ #!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/indirector/exec' describe Puppet::Indirector::Exec do before do @indirection = stub 'indirection', :name => :testing Puppet::Indirector::Indirection.expects(:instance).with(:testing).returns(@indirection) @exec_class = Class.new(Puppet::Indirector::Exec) do def self.to_s "Testing::Mytype" end attr_accessor :command end @searcher = @exec_class.new @searcher.command = ["/echo"] @request = stub 'request', :key => "foo" end it "should throw an exception if the command is not an array" do @searcher.command = "/usr/bin/echo" proc { @searcher.find(@request) }.should raise_error(Puppet::DevError) end it "should throw an exception if the command is not fully qualified" do @searcher.command = ["mycommand"] proc { @searcher.find(@request) }.should raise_error(ArgumentError) end it "should execute the command with the object name as the only argument" do @searcher.expects(:execute).with(%w{/echo foo}) @searcher.find(@request) end it "should return the output of the script" do @searcher.expects(:execute).with(%w{/echo foo}).returns("whatever") @searcher.find(@request).should == "whatever" end it "should return nil when the command produces no output" do @searcher.expects(:execute).with(%w{/echo foo}).returns(nil) @searcher.find(@request).should be_nil end - it "should return nil and log an error if there's an execution failure" do + it "should raise an exception if there's an execution failure" do @searcher.expects(:execute).with(%w{/echo foo}).raises(Puppet::ExecutionFailure.new("message")) - Puppet.expects(:err) - @searcher.find(@request).should be_nil + lambda {@searcher.find(@request)}.should raise_exception(Puppet::Error, 'Failed to find foo via exec: message') end end diff --git a/spec/unit/indirector/file_bucket_file/rest_spec.rb b/spec/unit/indirector/file_bucket_file/rest_spec.rb index 960f60ae7..d0f714751 100755 --- a/spec/unit/indirector/file_bucket_file/rest_spec.rb +++ b/spec/unit/indirector/file_bucket_file/rest_spec.rb @@ -1,11 +1,11 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require 'puppet/indirector/file_bucket_file/rest' describe Puppet::FileBucketFile::Rest do it "should be a sublcass of Puppet::Indirector::REST" do Puppet::FileBucketFile::Rest.superclass.should equal(Puppet::Indirector::REST) end end diff --git a/spec/unit/indirector/resource/rest_spec.rb b/spec/unit/indirector/resource/rest_spec.rb index 351aee33b..1285d338a 100755 --- a/spec/unit/indirector/resource/rest_spec.rb +++ b/spec/unit/indirector/resource/rest_spec.rb @@ -1,11 +1,11 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require 'puppet/indirector/resource/rest' describe Puppet::Resource::Rest do it "should be a sublcass of Puppet::Indirector::REST" do Puppet::Resource::Rest.superclass.should equal(Puppet::Indirector::REST) end end diff --git a/spec/unit/indirector/status/rest_spec.rb b/spec/unit/indirector/status/rest_spec.rb index 5eed5fc93..436c86881 100755 --- a/spec/unit/indirector/status/rest_spec.rb +++ b/spec/unit/indirector/status/rest_spec.rb @@ -1,11 +1,11 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require 'puppet/indirector/status/rest' describe Puppet::Indirector::Status::Rest do it "should be a sublcass of Puppet::Indirector::REST" do Puppet::Indirector::Status::Rest.superclass.should equal(Puppet::Indirector::REST) end end diff --git a/spec/unit/network/authstore_spec.rb b/spec/unit/network/authstore_spec.rb index 0b4dd21de..d477ee301 100644 --- a/spec/unit/network/authstore_spec.rb +++ b/spec/unit/network/authstore_spec.rb @@ -1,370 +1,370 @@ #!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/network/authconfig' describe Puppet::Network::AuthStore do describe "when checking if the acl has some entries" do before :each do @authstore = Puppet::Network::AuthStore.new end it "should be empty if no ACE have been entered" do @authstore.should be_empty end it "should not be empty if it is a global allow" do @authstore.allow('*') @authstore.should_not be_empty end it "should not be empty if at least one allow has been entered" do @authstore.allow('1.1.1.*') @authstore.should_not be_empty end it "should not be empty if at least one deny has been entered" do @authstore.deny('1.1.1.*') @authstore.should_not be_empty end end end describe Puppet::Network::AuthStore::Declaration do ['100.101.99.98','100.100.100.100','1.2.3.4','11.22.33.44'].each { |ip| describe "when the pattern is a simple numeric IP such as #{ip}" do before :each do @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,ip) end it "should match the specified IP" do @declaration.should be_match('www.testsite.org',ip) end it "should not match other IPs" do @declaration.should_not be_match('www.testsite.org','200.101.99.98') end end (1..3).each { |n| describe "when the pattern is a IP mask with #{n} numeric segments and a *" do before :each do @ip_pattern = ip.split('.')[0,n].join('.')+'.*' @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@ip_pattern) end it "should match an IP in the range" do @declaration.should be_match('www.testsite.org',ip) end it "should not match other IPs" do @declaration.should_not be_match('www.testsite.org','200.101.99.98') end it "should not match IPs that differ in the last non-wildcard segment" do other = ip.split('.') other[n-1].succ! @declaration.should_not be_match('www.testsite.org',other.join('.')) end end } } describe "when the pattern is a numeric IP with a back reference" do before :each do @ip = '100.101.$1' @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@ip).interpolate('12.34'.match(/(.*)/)) end it "should match an IP with the appropriate interpolation" do @declaration.should be_match('www.testsite.org',@ip.sub(/\$1/,'12.34')) end it "should not match other IPs" do @declaration.should_not be_match('www.testsite.org',@ip.sub(/\$1/,'66.34')) end end [ "02001:0000:1234:0000:0000:C1C0:ABCD:0876", "2001:0000:1234:0000:00001:C1C0:ABCD:0876", - " 2001:0000:1234:0000:0000:C1C0:ABCD:0876  0", + " 2001:0000:1234:0000:0000:C1C0:ABCD:0876 0", "2001:0000:1234: 0000:0000:C1C0:ABCD:0876", "3ffe:0b00:0000:0001:0000:0000:000a", "FF02:0000:0000:0000:0000:0000:0000:0000:0001", "3ffe:b00::1::a", "1:2:3::4:5::7:8", "12345::6:7:8", "1::5:400.2.3.4", "1::5:260.2.3.4", "1::5:256.2.3.4", "1::5:1.256.3.4", "1::5:1.2.256.4", "1::5:1.2.3.256", "1::5:300.2.3.4", "1::5:1.300.3.4", "1::5:1.2.300.4", "1::5:1.2.3.300", "1::5:900.2.3.4", "1::5:1.900.3.4", "1::5:1.2.900.4", "1::5:1.2.3.900", "1::5:300.300.300.300", "1::5:3000.30.30.30", "1::400.2.3.4", "1::260.2.3.4", "1::256.2.3.4", "1::1.256.3.4", "1::1.2.256.4", "1::1.2.3.256", "1::300.2.3.4", "1::1.300.3.4", "1::1.2.300.4", "1::1.2.3.300", "1::900.2.3.4", "1::1.900.3.4", "1::1.2.900.4", "1::1.2.3.900", "1::300.300.300.300", "1::3000.30.30.30", "::400.2.3.4", "::260.2.3.4", "::256.2.3.4", "::1.256.3.4", "::1.2.256.4", "::1.2.3.256", "::300.2.3.4", "::1.300.3.4", "::1.2.300.4", "::1.2.3.300", "::900.2.3.4", "::1.900.3.4", "::1.2.900.4", "::1.2.3.900", "::300.300.300.300", "::3000.30.30.30", "2001:DB8:0:0:8:800:200C:417A:221", # unicast, full "FF01::101::2" # multicast, compressed ].each { |invalid_ip| describe "when the pattern is an invalid IPv6 address such as #{invalid_ip}" do it "should raise an exception" do lambda { Puppet::Network::AuthStore::Declaration.new(:allow,invalid_ip) }.should raise_error end end } [ "1.2.3.4", "2001:0000:1234:0000:0000:C1C0:ABCD:0876", "3ffe:0b00:0000:0000:0001:0000:0000:000a", "FF02:0000:0000:0000:0000:0000:0000:0001", "0000:0000:0000:0000:0000:0000:0000:0001", "0000:0000:0000:0000:0000:0000:0000:0000", "::ffff:192.168.1.26", "2::10", "ff02::1", "fe80::", "2002::", "2001:db8::", "2001:0db8:1234::", "::ffff:0:0", "::1", "::ffff:192.168.1.1", "1:2:3:4:5:6:7:8", "1:2:3:4:5:6::8", "1:2:3:4:5::8", "1:2:3:4::8", "1:2:3::8", "1:2::8", "1::8", "1::2:3:4:5:6:7", "1::2:3:4:5:6", "1::2:3:4:5", "1::2:3:4", "1::2:3", "1::8", "::2:3:4:5:6:7:8", "::2:3:4:5:6:7", "::2:3:4:5:6", "::2:3:4:5", "::2:3:4", "::2:3", "::8", "1:2:3:4:5:6::", "1:2:3:4:5::", "1:2:3:4::", "1:2:3::", "1:2::", "1::", "1:2:3:4:5::7:8", "1:2:3:4::7:8", "1:2:3::7:8", "1:2::7:8", "1::7:8", "1:2:3:4:5:6:1.2.3.4", "1:2:3:4:5::1.2.3.4", "1:2:3:4::1.2.3.4", "1:2:3::1.2.3.4", "1:2::1.2.3.4", "1::1.2.3.4", "1:2:3:4::5:1.2.3.4", "1:2:3::5:1.2.3.4", "1:2::5:1.2.3.4", "1::5:1.2.3.4", "1::5:11.22.33.44", "fe80::217:f2ff:254.7.237.98", "fe80::217:f2ff:fe07:ed62", "2001:DB8:0:0:8:800:200C:417A", # unicast, full "FF01:0:0:0:0:0:0:101", # multicast, full "0:0:0:0:0:0:0:1", # loopback, full "0:0:0:0:0:0:0:0", # unspecified, full "2001:DB8::8:800:200C:417A", # unicast, compressed "FF01::101", # multicast, compressed "::1", # loopback, compressed, non-routable "::", # unspecified, compressed, non-routable "0:0:0:0:0:0:13.1.68.3", # IPv4-compatible IPv6 address, full, deprecated "0:0:0:0:0:FFFF:129.144.52.38", # IPv4-mapped IPv6 address, full "::13.1.68.3", # IPv4-compatible IPv6 address, compressed, deprecated "::FFFF:129.144.52.38", # IPv4-mapped IPv6 address, compressed "2001:0DB8:0000:CD30:0000:0000:0000:0000/60", # full, with prefix "2001:0DB8::CD30:0:0:0:0/60", # compressed, with prefix "2001:0DB8:0:CD30::/60", # compressed, with prefix #2 "::/128", # compressed, unspecified address type, non-routable "::1/128", # compressed, loopback address type, non-routable "FF00::/8", # compressed, multicast address type "FE80::/10", # compressed, link-local unicast, non-routable "FEC0::/10", # compressed, site-local unicast, deprecated "127.0.0.1", # standard IPv4, loopback, non-routable "0.0.0.0", # standard IPv4, unspecified, non-routable "255.255.255.255", # standard IPv4 "fe80:0000:0000:0000:0204:61ff:fe9d:f156", "fe80:0:0:0:204:61ff:fe9d:f156", "fe80::204:61ff:fe9d:f156", "fe80:0000:0000:0000:0204:61ff:254.157.241.086", "fe80:0:0:0:204:61ff:254.157.241.86", "fe80::204:61ff:254.157.241.86", "::1", "fe80::", "fe80::1" ].each { |ip| describe "when the pattern is a valid IP such as #{ip}" do before :each do @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,ip) end it "should match the specified IP" do @declaration.should be_match('www.testsite.org',ip) end it "should not match other IPs" do @declaration.should_not be_match('www.testsite.org','200.101.99.98') end end unless ip =~ /:.*\./ # Hybrid IPs aren't supported by ruby's ipaddr } { 'spirit.mars.nasa.gov' => 'a PQDN', 'ratchet.2ndsiteinc.com' => 'a PQDN with digits', 'a.c.ru' => 'a PQDN with short segments', }.each {|pqdn,desc| describe "when the pattern is #{desc}" do before :each do @host = pqdn @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@host) end it "should match the specified PQDN" do @declaration.should be_match(@host,'200.101.99.98') end it "should not match a similar FQDN" do pending "FQDN consensus" @declaration.should_not be_match(@host+'.','200.101.99.98') end end } ['abc.12seps.edu.phisher.biz','www.google.com','slashdot.org'].each { |host| (1...(host.split('.').length)).each { |n| describe "when the pattern is #{"*."+host.split('.')[-n,n].join('.')}" do before :each do @pattern = "*."+host.split('.')[-n,n].join('.') @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@pattern) end it "should match #{host}" do @declaration.should be_match(host,'1.2.3.4') end it "should not match www.testsite.gov" do @declaration.should_not be_match('www.testsite.gov','200.101.99.98') end it "should not match hosts that differ in the first non-wildcard segment" do other = host.split('.') other[-n].succ! @declaration.should_not be_match(other.join('.'),'1.2.3.4') end end } } describe "when the pattern is a FQDN" do before :each do @host = 'spirit.mars.nasa.gov.' @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,@host) end it "should match the specified FQDN" do pending "FQDN consensus" @declaration.should be_match(@host,'200.101.99.98') end it "should not match a similar PQDN" do @declaration.should_not be_match(@host[0..-2],'200.101.99.98') end end describe "when the pattern is an opaque string with a back reference" do before :each do @host = 'c216f41a-f902-4bfb-a222-850dd957bebb' @item = "/catalog/#{@host}" @pattern = %{^/catalog/([^/]+)$} @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,'$1') end it "should match an IP with the appropriate interpolation" do @declaration.interpolate(@item.match(@pattern)).should be_match(@host,'10.0.0.5') end end describe "when the pattern is an opaque string with a back reference and the matched data contains dots" do before :each do @host = 'admin.mgmt.nym1' @item = "/catalog/#{@host}" @pattern = %{^/catalog/([^/]+)$} @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,'$1') end it "should match a name with the appropriate interpolation" do @declaration.interpolate(@item.match(@pattern)).should be_match(@host,'10.0.0.5') end end describe "when the pattern is an opaque string with a back reference and the matched data contains dots with an initial prefix that looks like an IP address" do before :each do @host = '01.admin.mgmt.nym1' @item = "/catalog/#{@host}" @pattern = %{^/catalog/([^/]+)$} @declaration = Puppet::Network::AuthStore::Declaration.new(:allow,'$1') end it "should match a name with the appropriate interpolation" do @declaration.interpolate(@item.match(@pattern)).should be_match(@host,'10.0.0.5') end end describe "when comparing patterns" do before :each do @ip = Puppet::Network::AuthStore::Declaration.new(:allow,'127.0.0.1') @host_name = Puppet::Network::AuthStore::Declaration.new(:allow,'www.hard_knocks.edu') @opaque = Puppet::Network::AuthStore::Declaration.new(:allow,'hey_dude') end it "should consider ip addresses before host names" do (@ip < @host_name).should be_true end it "should consider ip addresses before opaque strings" do (@ip < @opaque).should be_true end it "should consider host_names before opaque strings" do (@host_name < @opaque).should be_true end end end diff --git a/spec/unit/network/http/api/v1_spec.rb b/spec/unit/network/http/api/v1_spec.rb index 25f6d8fe2..257eec5de 100644 --- a/spec/unit/network/http/api/v1_spec.rb +++ b/spec/unit/network/http/api/v1_spec.rb @@ -1,167 +1,167 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../../spec_helper') require 'puppet/network/http/api/v1' class V1RestApiTester include Puppet::Network::HTTP::API::V1 end describe Puppet::Network::HTTP::API::V1 do before do @tester = V1RestApiTester.new end it "should be able to convert a URI into a request" do @tester.should respond_to(:uri2indirection) end it "should be able to convert a request into a URI" do @tester.should respond_to(:indirection2uri) end describe "when converting a URI into a request" do before do @tester.stubs(:handler).returns "foo" end it "should require the http method, the URI, and the query parameters" do # Not a terribly useful test, but an important statement for the spec lambda { @tester.uri2indirection("/foo") }.should raise_error(ArgumentError) end it "should use the first field of the URI as the environment" do @tester.uri2indirection("GET", "/env/foo/bar", {})[3][:environment].should == "env" end it "should fail if the environment is not alphanumeric" do lambda { @tester.uri2indirection("GET", "/env ness/foo/bar", {}) }.should raise_error(ArgumentError) end it "should use the environment from the URI even if one is specified in the parameters" do @tester.uri2indirection("GET", "/env/foo/bar", {:environment => "otherenv"})[3][:environment].should == "env" end it "should use the second field of the URI as the indirection name" do @tester.uri2indirection("GET", "/env/foo/bar", {})[0].should == "foo" end it "should fail if the indirection name is not alphanumeric" do lambda { @tester.uri2indirection("GET", "/env/foo ness/bar", {}) }.should raise_error(ArgumentError) end it "should use the remainder of the URI as the indirection key" do @tester.uri2indirection("GET", "/env/foo/bar", {})[2].should == "bar" end it "should support the indirection key being a /-separated file path" do @tester.uri2indirection("GET", "/env/foo/bee/baz/bomb", {})[2].should == "bee/baz/bomb" end it "should fail if no indirection key is specified" do lambda { @tester.uri2indirection("GET", "/env/foo/", {}) }.should raise_error(ArgumentError) lambda { @tester.uri2indirection("GET", "/env/foo", {}) }.should raise_error(ArgumentError) end it "should choose 'find' as the indirection method if the http method is a GET and the indirection name is singular" do @tester.uri2indirection("GET", "/env/foo/bar", {})[1].should == :find end it "should choose 'head' as the indirection method if the http method is a HEAD and the indirection name is singular" do @tester.uri2indirection("HEAD", "/env/foo/bar", {})[1].should == :head end it "should choose 'search' as the indirection method if the http method is a GET and the indirection name is plural" do @tester.uri2indirection("GET", "/env/foos/bar", {})[1].should == :search end it "should choose 'find' as the indirection method if the http method is a GET and the indirection name is facts" do @tester.uri2indirection("GET", "/env/facts/bar", {})[1].should == :find end it "should choose 'save' as the indirection method if the http method is a PUT and the indirection name is facts" do @tester.uri2indirection("PUT", "/env/facts/bar", {})[1].should == :save end it "should choose 'search' as the indirection method if the http method is a GET and the indirection name is inventory" do @tester.uri2indirection("GET", "/env/inventory/search", {})[1].should == :search end it "should choose 'find' as the indirection method if the http method is a GET and the indirection name is facts" do @tester.uri2indirection("GET", "/env/facts/bar", {})[1].should == :find end it "should choose 'save' as the indirection method if the http method is a PUT and the indirection name is facts" do @tester.uri2indirection("PUT", "/env/facts/bar", {})[1].should == :save end it "should choose 'search' as the indirection method if the http method is a GET and the indirection name is inventory" do @tester.uri2indirection("GET", "/env/inventory/search", {})[1].should == :search end it "should choose 'search' as the indirection method if the http method is a GET and the indirection name is facts_search" do @tester.uri2indirection("GET", "/env/facts_search/bar", {})[1].should == :search end it "should change indirection name to 'facts' if the http method is a GET and the indirection name is facts_search" do @tester.uri2indirection("GET", "/env/facts_search/bar", {})[0].should == 'facts' end it "should not change indirection name from 'facts' if the http method is a GET and the indirection name is facts" do @tester.uri2indirection("GET", "/env/facts/bar", {})[0].should == 'facts' end it "should change indirection name to 'status' if the http method is a GET and the indirection name is statuses" do @tester.uri2indirection("GET", "/env/statuses/bar", {})[0].should == 'status' end it "should choose 'delete' as the indirection method if the http method is a DELETE and the indirection name is singular" do @tester.uri2indirection("DELETE", "/env/foo/bar", {})[1].should == :destroy end it "should choose 'save' as the indirection method if the http method is a PUT and the indirection name is singular" do @tester.uri2indirection("PUT", "/env/foo/bar", {})[1].should == :save end it "should fail if an indirection method cannot be picked" do lambda { @tester.uri2indirection("UPDATE", "/env/foo/bar", {}) }.should raise_error(ArgumentError) end it "should URI unescape the indirection key" do escaped = URI.escape("foo bar") indirection_name, method, key, params = @tester.uri2indirection("GET", "/env/foo/#{escaped}", {}) key.should == "foo bar" end end describe "when converting a request into a URI" do before do @request = Puppet::Indirector::Request.new(:foo, :find, "with spaces", :foo => :bar, :environment => "myenv") end it "should use the environment as the first field of the URI" do @tester.indirection2uri(@request).split("/")[1].should == "myenv" end it "should use the indirection as the second field of the URI" do @tester.indirection2uri(@request).split("/")[2].should == "foo" end it "should pluralize the indirection name if the method is 'search'" do @request.stubs(:method).returns :search @tester.indirection2uri(@request).split("/")[2].should == "foos" end it "should use the escaped key as the remainder of the URI" do escaped = URI.escape("with spaces") @tester.indirection2uri(@request).split("/")[3].sub(/\?.+/, '').should == escaped end it "should add the query string to the URI" do @request.expects(:query_string).returns "?query" @tester.indirection2uri(@request).should =~ /\?query$/ end end end diff --git a/spec/unit/network/xmlrpc/client_spec.rb b/spec/unit/network/xmlrpc/client_spec.rb index 8440d39fa..7498ca4cf 100755 --- a/spec/unit/network/xmlrpc/client_spec.rb +++ b/spec/unit/network/xmlrpc/client_spec.rb @@ -1,172 +1,172 @@ #!/usr/bin/env ruby require 'puppet/network/client' -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe Puppet::Network::XMLRPCClient do describe "when performing the rpc call" do before do Puppet::SSL::Host.any_instance.stubs(:certificate_matches_key?).returns true @client = Puppet::Network::Client.report.xmlrpc_client.new @client.stubs(:call).returns "foo" end it "should call the specified namespace and method, with the specified arguments" do @client.expects(:call).with("puppetreports.report", "eh").returns "foo" @client.report("eh") end it "should return the results from the call" do @client.expects(:call).returns "foo" @client.report("eh").should == "foo" end it "should always close the http connection if it is still open after the call" do http = mock 'http' @client.stubs(:http).returns http http.expects(:started?).returns true http.expects(:finish) @client.report("eh").should == "foo" end it "should always close the http connection if it is still open after a call that raises an exception" do http = mock 'http' @client.stubs(:http).returns http @client.expects(:call).raises RuntimeError http.expects(:started?).returns true http.expects(:finish) lambda { @client.report("eh") }.should raise_error end describe "when returning the http instance" do it "should use the http pool to create the instance" do @client.instance_variable_set("@http", nil) @client.expects(:host).returns "myhost" @client.expects(:port).returns "myport" Puppet::Network::HttpPool.expects(:http_instance).with("myhost", "myport", true).returns "http" @client.http.should == "http" end it "should reuse existing instances" do @client.http.should equal(@client.http) end end describe "when recycling the connection" do it "should close the existing instance if it's open" do http = mock 'http' @client.stubs(:http).returns http http.expects(:started?).returns true http.expects(:finish) @client.recycle_connection end it "should force creation of a new instance" do Puppet::Network::HttpPool.expects(:http_instance).returns "second_http" @client.recycle_connection @client.http.should == "second_http" end end describe "and an exception is raised" do it "should raise XMLRPCClientError if XMLRPC::FaultException is raised" do error = XMLRPC::FaultException.new("foo", "bar") @client.expects(:call).raises(error) lambda { @client.report("eh") }.should raise_error(Puppet::Network::XMLRPCClientError) end it "should raise XMLRPCClientError if Errno::ECONNREFUSED is raised" do @client.expects(:call).raises(Errno::ECONNREFUSED) lambda { @client.report("eh") }.should raise_error(Puppet::Network::XMLRPCClientError) end it "should log and raise XMLRPCClientError if Timeout::Error is raised" do Puppet.expects(:err) @client.expects(:call).raises(Timeout::Error) lambda { @client.report("eh") }.should raise_error(Puppet::Network::XMLRPCClientError) end it "should log and raise XMLRPCClientError if SocketError is raised" do Puppet.expects(:err) @client.expects(:call).raises(SocketError) lambda { @client.report("eh") }.should raise_error(Puppet::Network::XMLRPCClientError) end it "should log, recycle the connection, and retry if Errno::EPIPE is raised" do @client.expects(:call).times(2).raises(Errno::EPIPE).then.returns "eh" Puppet.expects(:info) @client.expects(:recycle_connection) @client.report("eh") end it "should log, recycle the connection, and retry if EOFError is raised" do @client.expects(:call).times(2).raises(EOFError).then.returns "eh" Puppet.expects(:info) @client.expects(:recycle_connection) @client.report("eh") end it "should log and retry if an exception containing 'Wrong size' is raised" do error = RuntimeError.new("Wrong size. Was 15, should be 30") @client.expects(:call).times(2).raises(error).then.returns "eh" Puppet.expects(:warning) @client.report("eh") end it "should raise XMLRPCClientError if OpenSSL::SSL::SSLError is raised" do @client.expects(:call).raises(OpenSSL::SSL::SSLError) lambda { @client.report("eh") }.should raise_error(Puppet::Network::XMLRPCClientError) end it "should log and raise XMLRPCClientError if OpenSSL::SSL::SSLError is raised with certificate issues" do error = OpenSSL::SSL::SSLError.new("hostname was not match") @client.expects(:call).raises(error) Puppet.expects(:warning) lambda { @client.report("eh") }.should raise_error(Puppet::Network::XMLRPCClientError) end it "should log, recycle the connection, and retry if OpenSSL::SSL::SSLError is raised containing 'bad write retry'" do error = OpenSSL::SSL::SSLError.new("bad write retry") @client.expects(:call).times(2).raises(error).then.returns "eh" @client.expects(:recycle_connection) Puppet.expects(:warning) @client.report("eh") end it "should log and raise XMLRPCClientError if any other exception is raised" do @client.expects(:call).raises(RuntimeError) Puppet.expects(:err) lambda { @client.report("eh") }.should raise_error(Puppet::Network::XMLRPCClientError) end end end end diff --git a/spec/unit/parameter/path_spec.rb b/spec/unit/parameter/path_spec.rb new file mode 100644 index 000000000..08a26de33 --- /dev/null +++ b/spec/unit/parameter/path_spec.rb @@ -0,0 +1,24 @@ +#!/usr/bin/env ruby +require File.expand_path(File.join(File.dirname(__FILE__), '../../spec_helper')) + +require 'puppet/parameter/path' + +[false, true].each do |arrays| + describe "Puppet::Parameter::Path with arrays #{arrays}" do + it_should_behave_like "all path parameters", :path, :array => arrays do + # The new type allows us a test that is guaranteed to go direct to our + # validation code, without passing through any "real type" overrides or + # whatever on the way. + Puppet::newtype(:test_puppet_parameter_path) do + newparam(:path, :parent => Puppet::Parameter::Path, :arrays => arrays) do + isnamevar + accept_arrays arrays + end + end + + def instance(path) + Puppet::Type.type(:test_puppet_parameter_path).new(:path => path) + end + end + end +end diff --git a/spec/unit/property/ensure_spec.rb b/spec/unit/property/ensure_spec.rb index f2722de89..d3029c658 100644 --- a/spec/unit/property/ensure_spec.rb +++ b/spec/unit/property/ensure_spec.rb @@ -1,13 +1,13 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/property/ensure' klass = Puppet::Property::Ensure describe klass do it "should be a subclass of Property" do klass.superclass.must == Puppet::Property end end diff --git a/spec/unit/property/keyvalue_spec.rb b/spec/unit/property/keyvalue_spec.rb index a44d891d7..a0175cfa3 100644 --- a/spec/unit/property/keyvalue_spec.rb +++ b/spec/unit/property/keyvalue_spec.rb @@ -1,168 +1,168 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/property/keyvalue' klass = Puppet::Property::KeyValue describe klass do it "should be a subclass of Property" do klass.superclass.must == Puppet::Property end describe "as an instance" do before do # Wow that's a messy interface to the resource. klass.initvars @resource = stub 'resource', :[]= => nil, :property => nil @property = klass.new(:resource => @resource) end it "should have a , as default delimiter" do @property.delimiter.should == ";" end it "should have a = as default separator" do @property.separator.should == "=" end it "should have a :membership as default membership" do @property.membership.should == :key_value_membership end it "should return the same value passed into should_to_s" do @property.should_to_s({:foo => "baz", :bar => "boo"}) == "foo=baz;bar=boo" end it "should return the passed in array values joined with the delimiter from is_to_s" do @property.is_to_s({"foo" => "baz" , "bar" => "boo"}).should == "foo=baz;bar=boo" end describe "when calling inclusive?" do it "should use the membership method to look up on the @resource" do @property.expects(:membership).returns(:key_value_membership) @resource.expects(:[]).with(:key_value_membership) @property.inclusive? end it "should return true when @resource[membership] == inclusive" do @property.stubs(:membership).returns(:key_value_membership) @resource.stubs(:[]).with(:key_value_membership).returns(:inclusive) @property.inclusive?.must == true end it "should return false when @resource[membership] != inclusive" do @property.stubs(:membership).returns(:key_value_membership) @resource.stubs(:[]).with(:key_value_membership).returns(:minimum) @property.inclusive?.must == false end end describe "when calling process_current_hash" do it "should return {} if hash is :absent" do @property.process_current_hash(:absent).must == {} end it "should set every key to nil if inclusive?" do @property.stubs(:inclusive?).returns(true) @property.process_current_hash({:foo => "bar", :do => "re"}).must == { :foo => nil, :do => nil } end it "should return the hash if !inclusive?" do @property.stubs(:inclusive?).returns(false) @property.process_current_hash({:foo => "bar", :do => "re"}).must == {:foo => "bar", :do => "re"} end end describe "when calling should" do it "should return nil if @should is nil" do @property.should.must == nil end it "should call process_current_hash" do @property.should = ["foo=baz", "bar=boo"] @property.stubs(:retrieve).returns({:do => "re", :mi => "fa" }) @property.expects(:process_current_hash).returns({}) @property.should end it "should return the hashed values of @should and the nilled values of retrieve if inclusive" do @property.should = ["foo=baz", "bar=boo"] @property.expects(:retrieve).returns({:do => "re", :mi => "fa" }) @property.expects(:inclusive?).returns(true) @property.should.must == { :foo => "baz", :bar => "boo", :do => nil, :mi => nil } end it "should return the hashed @should + the unique values of retrieve if !inclusive" do @property.should = ["foo=baz", "bar=boo"] @property.expects(:retrieve).returns({:foo => "diff", :do => "re", :mi => "fa"}) @property.expects(:inclusive?).returns(false) @property.should.must == { :foo => "baz", :bar => "boo", :do => "re", :mi => "fa" } end end describe "when calling retrieve" do before do @provider = mock("provider") @property.stubs(:provider).returns(@provider) end it "should send 'name' to the provider" do @provider.expects(:send).with(:keys) @property.expects(:name).returns(:keys) @property.retrieve end it "should return a hash with the provider returned info" do @provider.stubs(:send).with(:keys).returns({"do" => "re", "mi" => "fa" }) @property.stubs(:name).returns(:keys) @property.retrieve == {"do" => "re", "mi" => "fa" } end it "should return :absent when the provider returns :absent" do @provider.stubs(:send).with(:keys).returns(:absent) @property.stubs(:name).returns(:keys) @property.retrieve == :absent end end describe "when calling hashify" do it "should return the array hashified" do @property.hashify(["foo=baz", "bar=boo"]).must == { :foo => "baz", :bar => "boo" } end end describe "when calling safe_insync?" do before do @provider = mock("provider") @property.stubs(:provider).returns(@provider) @property.stubs(:name).returns(:prop_name) end it "should return true unless @should is defined and not nil" do @property.safe_insync?("foo") == true end it "should return true if the passed in values is nil" do @property.should = "foo" @property.safe_insync?(nil) == true end it "should return true if hashified should value == (retrieved) value passed in" do @provider.stubs(:prop_name).returns({ :foo => "baz", :bar => "boo" }) @property.should = ["foo=baz", "bar=boo"] @property.expects(:inclusive?).returns(true) @property.safe_insync?({ :foo => "baz", :bar => "boo" }).must == true end it "should return false if prepared value != should value" do @provider.stubs(:prop_name).returns({ "foo" => "bee", "bar" => "boo" }) @property.should = ["foo=baz", "bar=boo"] @property.expects(:inclusive?).returns(true) @property.safe_insync?({ "foo" => "bee", "bar" => "boo" }).must == false end end end end diff --git a/spec/unit/property/list_spec.rb b/spec/unit/property/list_spec.rb index c6c5db10e..704fbe3d9 100644 --- a/spec/unit/property/list_spec.rb +++ b/spec/unit/property/list_spec.rb @@ -1,166 +1,166 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/property/list' list_class = Puppet::Property::List describe list_class do it "should be a subclass of Property" do list_class.superclass.must == Puppet::Property end describe "as an instance" do before do # Wow that's a messy interface to the resource. list_class.initvars @resource = stub 'resource', :[]= => nil, :property => nil @property = list_class.new(:resource => @resource) end it "should have a , as default delimiter" do @property.delimiter.should == "," end it "should have a :membership as default membership" do @property.membership.should == :membership end it "should return the same value passed into should_to_s" do @property.should_to_s("foo") == "foo" end it "should return the passed in array values joined with the delimiter from is_to_s" do @property.is_to_s(["foo","bar"]).should == "foo,bar" end it "should be able to correctly convert ':absent' to a string" do @property.is_to_s(:absent).should == "absent" end describe "when adding should to current" do it "should add the arrays when current is an array" do @property.add_should_with_current(["foo"], ["bar"]).should == ["foo", "bar"] end it "should return should if current is not a array" do @property.add_should_with_current(["foo"], :absent).should == ["foo"] end it "should return only the uniq elements" do @property.add_should_with_current(["foo", "bar"], ["foo", "baz"]).should == ["foo", "bar", "baz"] end end describe "when calling inclusive?" do it "should use the membership method to look up on the @resource" do @property.expects(:membership).returns(:membership) @resource.expects(:[]).with(:membership) @property.inclusive? end it "should return true when @resource[membership] == inclusive" do @property.stubs(:membership).returns(:membership) @resource.stubs(:[]).with(:membership).returns(:inclusive) @property.inclusive?.must == true end it "should return false when @resource[membership] != inclusive" do @property.stubs(:membership).returns(:membership) @resource.stubs(:[]).with(:membership).returns(:minimum) @property.inclusive?.must == false end end describe "when calling should" do it "should return nil if @should is nil" do @property.should.must == nil end it "should return the sorted values of @should as a string if inclusive" do @property.should = ["foo", "bar"] @property.expects(:inclusive?).returns(true) @property.should.must == "bar,foo" end it "should return the uniq sorted values of @should + retrieve as a string if !inclusive" do @property.should = ["foo", "bar"] @property.expects(:inclusive?).returns(false) @property.expects(:retrieve).returns(["foo","baz"]) @property.should.must == "bar,baz,foo" end end describe "when calling retrieve" do before do @provider = mock("provider") @property.stubs(:provider).returns(@provider) end it "should send 'name' to the provider" do @provider.expects(:send).with(:group) @property.expects(:name).returns(:group) @property.retrieve end it "should return an array with the provider returned info" do @provider.stubs(:send).with(:group).returns("foo,bar,baz") @property.stubs(:name).returns(:group) @property.retrieve == ["foo", "bar", "baz"] end it "should return :absent when the provider returns :absent" do @provider.stubs(:send).with(:group).returns(:absent) @property.stubs(:name).returns(:group) @property.retrieve == :absent end end describe "when calling safe_insync?" do it "should return true unless @should is defined and not nil" do @property.must be_safe_insync("foo") end it "should return true unless the passed in values is not nil" do @property.should = "foo" @property.must be_safe_insync(nil) end it "should call prepare_is_for_comparison with value passed in and should" do @property.should = "foo" @property.expects(:prepare_is_for_comparison).with("bar") @property.expects(:should) @property.safe_insync?("bar") end it "should return true if 'is' value is array of comma delimited should values" do @property.should = "bar,foo" @property.expects(:inclusive?).returns(true) @property.must be_safe_insync(["bar","foo"]) end it "should return true if 'is' value is :absent and should value is empty string" do @property.should = "" @property.expects(:inclusive?).returns(true) @property.must be_safe_insync([]) end it "should return false if prepared value != should value" do @property.should = "bar,baz,foo" @property.expects(:inclusive?).returns(true) @property.must_not be_safe_insync(["bar","foo"]) end end describe "when calling dearrayify" do it "should sort and join the array with 'delimiter'" do array = mock "array" array.expects(:sort).returns(array) array.expects(:join).with(@property.delimiter) @property.dearrayify(array) end end end end diff --git a/spec/unit/property/ordered_list_spec.rb b/spec/unit/property/ordered_list_spec.rb index 7c8eceb0d..460bec79d 100644 --- a/spec/unit/property/ordered_list_spec.rb +++ b/spec/unit/property/ordered_list_spec.rb @@ -1,64 +1,64 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/property/ordered_list' ordered_list_class = Puppet::Property::OrderedList describe ordered_list_class do it "should be a subclass of List" do ordered_list_class.superclass.must == Puppet::Property::List end describe "as an instance" do before do # Wow that's a messy interface to the resource. ordered_list_class.initvars @resource = stub 'resource', :[]= => nil, :property => nil @property = ordered_list_class.new(:resource => @resource) end describe "when adding should to current" do it "should add the arrays when current is an array" do @property.add_should_with_current(["should"], ["current"]).should == ["should", "current"] end it "should return 'should' if current is not a array" do @property.add_should_with_current(["should"], :absent).should == ["should"] end it "should return only the uniq elements leading with the order of 'should'" do @property.add_should_with_current(["this", "is", "should"], ["is", "this", "current"]).should == ["this", "is", "should", "current"] end end describe "when calling should" do it "should return nil if @should is nil" do @property.should.must == nil end it "should return the values of @should (without sorting) as a string if inclusive" do @property.should = ["foo", "bar"] @property.expects(:inclusive?).returns(true) @property.should.must == "foo,bar" end it "should return the uniq values of @should + retrieve as a string if !inclusive with the @ values leading" do @property.should = ["foo", "bar"] @property.expects(:inclusive?).returns(false) @property.expects(:retrieve).returns(["foo","baz"]) @property.should.must == "foo,bar,baz" end end describe "when calling dearrayify" do it "should join the array with the delimiter" do array = mock "array" array.expects(:join).with(@property.delimiter) @property.dearrayify(array) end end end end diff --git a/spec/unit/provider/exec/posix_spec.rb b/spec/unit/provider/exec/posix_spec.rb new file mode 100755 index 000000000..d02099250 --- /dev/null +++ b/spec/unit/provider/exec/posix_spec.rb @@ -0,0 +1,120 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../../spec_helper' + +provider_class = Puppet::Type.type(:exec).provider(:posix) + +describe provider_class do + before :each do + @resource = Puppet::Resource.new(:exec, 'foo') + @provider = provider_class.new(@resource) + end + + ["posix", "microsoft_windows"].each do |feature| + describe "when in #{feature} environment" do + before :each do + if feature == "microsoft_windows" + Puppet.features.stubs(:microsoft_windows?).returns(true) + Puppet.features.stubs(:posix?).returns(false) + else + Puppet.features.stubs(:posix?).returns(true) + Puppet.features.stubs(:microsoft_windows?).returns(false) + end + end + + describe "#validatecmd" do + it "should fail if no path is specified and the command is not fully qualified" do + lambda { @provider.validatecmd("foo") }.should raise_error( + Puppet::Error, + "'foo' is not qualified and no path was specified. Please qualify the command or specify a path." + ) + end + + it "should pass if a path is given" do + @provider.resource[:path] = ['/bogus/bin'] + @provider.validatecmd("../foo") + end + + it "should pass if command is fully qualifed" do + @provider.resource[:path] = ['/bogus/bin'] + @provider.validatecmd("/bin/blah/foo") + end + end + + describe "#run" do + it "should fail if no path is specified and command does not exist" do + lambda { @provider.run("foo") }.should raise_error(ArgumentError, "Could not find command 'foo'") + end + + it "should fail if the command isn't in the path" do + @provider.resource[:path] = ['/bogus/bin'] + lambda { @provider.run("foo") }.should raise_error(ArgumentError, "Could not find command 'foo'") + end + + it "should fail if the command isn't executable" do + @provider.resource[:path] = ['/bogus/bin'] + File.stubs(:exists?).with("foo").returns(true) + + lambda { @provider.run("foo") }.should raise_error(ArgumentError, "'foo' is not executable") + end + + it "should not be able to execute shell builtins" do + @provider.resource[:path] = ['/bin'] + lambda { @provider.run("cd ..") }.should raise_error(ArgumentError, "Could not find command 'cd'") + end + + it "should execute the command if the command given includes arguments or subcommands" do + @provider.resource[:path] = ['/bogus/bin'] + File.stubs(:exists?).returns(false) + File.stubs(:exists?).with("foo").returns(true) + File.stubs(:executable?).with("foo").returns(true) + + Puppet::Util.expects(:execute).with() { |command, arguments| (command == ['foo bar --sillyarg=true --blah']) && (arguments.is_a? Hash) } + @provider.run("foo bar --sillyarg=true --blah") + end + + it "should fail if quoted command doesn't exist" do + @provider.resource[:path] = ['/bogus/bin'] + File.stubs(:exists?).returns(false) + File.stubs(:exists?).with("foo").returns(true) + File.stubs(:executable?).with("foo").returns(true) + + lambda { @provider.run('"foo bar --sillyarg=true --blah"') }.should raise_error(ArgumentError, "Could not find command 'foo bar --sillyarg=true --blah'") + end + + it "should execute the command if it finds it in the path and is executable" do + @provider.resource[:path] = ['/bogus/bin'] + File.stubs(:exists?).with("foo").returns(true) + File.stubs(:executable?).with("foo").returns(true) + Puppet::Util.expects(:execute).with() { |command, arguments| (command == ['foo']) && (arguments.is_a? Hash) } + + @provider.run("foo") + end + + if feature == "microsoft_windows" + [".exe", ".ps1", ".bat", ".com", ""].each do |extension| + it "should check file extension #{extension} when it can't find the executable" do + @provider.resource[:path] = ['/bogus/bin'] + File.stubs(:exists?).returns(false) + File.stubs(:exists?).with("/bogus/bin/foo#{extension}").returns(true) + File.stubs(:executable?).with("foo").returns(true) + Puppet::Util.expects(:execute).with() { |command, arguments| (command == ['foo']) && (arguments.is_a? Hash) } + + @provider.run("foo") + end + end + end + + it "should warn if you're overriding something in environment" do + @provider.resource[:environment] = ['WHATEVER=/something/else', 'WHATEVER=/foo'] + File.stubs(:exists?).returns(false) + File.stubs(:exists?).with("foo").returns(true) + File.stubs(:executable?).with("foo").returns(true) + + Puppet::Util.expects(:execute).with() { |command, arguments| (command == ['foo']) && (arguments.is_a? Hash) } + @provider.run("foo") + @logs.map {|l| "#{l.level}: #{l.message}" }.should == ["warning: Overriding environment setting 'WHATEVER' with '/foo'"] + end + end + end + end +end diff --git a/spec/unit/provider/exec/shell_spec.rb b/spec/unit/provider/exec/shell_spec.rb new file mode 100644 index 000000000..4bae354c9 --- /dev/null +++ b/spec/unit/provider/exec/shell_spec.rb @@ -0,0 +1,50 @@ +#!/usr/bin/env ruby +require File.dirname(__FILE__) + '/../../../spec_helper' + +provider_class = Puppet::Type.type(:exec).provider(:shell) + +describe provider_class do + before :each do + @resource = Puppet::Resource.new(:exec, 'foo') + @provider = provider_class.new(@resource) + end + + describe "#run" do + it "should be able to run builtin shell commands" do + output, status = @provider.run("if [ 1 = 1 ]; then echo 'blah'; fi") + status.exitstatus.should == 0 + output.should == "blah\n" + end + + it "should be able to run commands with single quotes in them" do + output, status = @provider.run("echo 'foo bar'") + status.exitstatus.should == 0 + output.should == "foo bar\n" + end + + it "should be able to run commands with double quotes in them" do + output, status = @provider.run('echo "foo bar"') + status.exitstatus.should == 0 + output.should == "foo bar\n" + end + + it "should be able to run multiple commands separated by a semicolon" do + output, status = @provider.run("echo 'foo' ; echo 'bar'") + status.exitstatus.should == 0 + output.should == "foo\nbar\n" + end + + it "should be able to read values from the environment parameter" do + @resource[:environment] = "FOO=bar" + output, status = @provider.run("echo $FOO") + status.exitstatus.should == 0 + output.should == "bar\n" + end + end + + describe "#validatecmd" do + it "should always return true because builtins don't need path or to be fully qualified" do + @provider.validatecmd('whateverdoesntmatter').should == true + end + end +end diff --git a/spec/unit/provider/package/apt_spec.rb b/spec/unit/provider/package/apt_spec.rb index 3c6bf62af..b0ce4f799 100755 --- a/spec/unit/provider/package/apt_spec.rb +++ b/spec/unit/provider/package/apt_spec.rb @@ -1,145 +1,145 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') provider = Puppet::Type.type(:package).provider(:apt) describe provider do before do @resource = stub 'resource', :[] => "asdf" @provider = provider.new(@resource) @fakeresult = "install ok installed asdf 1.0\n" end it "should be versionable" do provider.should be_versionable end it "should use :install to update" do @provider.expects(:install) @provider.update end it "should use 'apt-get remove' to uninstall" do @provider.expects(:aptget).with("-y", "-q", :remove, "asdf") @provider.uninstall end it "should use 'apt-get purge' and 'dpkg purge' to purge" do @provider.expects(:aptget).with("-y", "-q", :remove, "--purge", "asdf") @provider.expects(:dpkg).with("--purge", "asdf") @provider.purge end it "should use 'apt-cache policy' to determine the latest version of a package" do @provider.expects(:aptcache).with(:policy, "asdf").returns "asdf: Installed: 1:1.0 Candidate: 1:1.1 Version table: 1:1.0 650 http://ftp.osuosl.org testing/main Packages *** 1:1.1 100 /var/lib/dpkg/status" @provider.latest.should == "1:1.1" end it "should print and error and return nil if no policy is found" do @provider.expects(:aptcache).with(:policy, "asdf").returns "asdf:" @provider.expects(:err) @provider.latest.should be_nil end it "should be able to preseed" do @provider.should respond_to(:run_preseed) end it "should preseed with the provided responsefile when preseeding is called for" do @resource.expects(:[]).with(:responsefile).returns "/my/file" FileTest.expects(:exist?).with("/my/file").returns true @provider.expects(:info) @provider.expects(:preseed).with("/my/file") @provider.run_preseed end it "should not preseed if no responsefile is provided" do @resource.expects(:[]).with(:responsefile).returns nil @provider.expects(:info) @provider.expects(:preseed).never @provider.run_preseed end it "should fail if a cdrom is listed in the sources list and :allowcdrom is not specified" describe "when installing" do it "should preseed if a responsefile is provided" do @resource.expects(:[]).with(:responsefile).returns "/my/file" @provider.expects(:run_preseed) @provider.stubs(:aptget) @provider.install end it "should check for a cdrom" do @provider.expects(:checkforcdrom) @provider.stubs(:aptget) @provider.install end it "should use 'apt-get install' with the package name if no version is asked for" do @resource.expects(:[]).with(:ensure).returns :installed @provider.expects(:aptget).with { |*command| command[-1] == "asdf" and command[-2] == :install } @provider.install end it "should specify the package version if one is asked for" do @resource.expects(:[]).with(:ensure).returns "1.0" @provider.expects(:aptget).with { |*command| command[-1] == "asdf=1.0" } @provider.install end it "should use --force-yes if a package version is specified" do @resource.expects(:[]).with(:ensure).returns "1.0" @provider.expects(:aptget).with { |*command| command.include?("--force-yes") } @provider.install end it "should do a quiet install" do @provider.expects(:aptget).with { |*command| command.include?("-q") } @provider.install end it "should default to 'yes' for all questions" do @provider.expects(:aptget).with { |*command| command.include?("-y") } @provider.install end it "should keep config files if asked" do @resource.expects(:[]).with(:configfiles).returns :keep @provider.expects(:aptget).with { |*command| command.include?("DPkg::Options::=--force-confold") } @provider.install end it "should replace config files if asked" do @resource.expects(:[]).with(:configfiles).returns :replace @provider.expects(:aptget).with { |*command| command.include?("DPkg::Options::=--force-confnew") } @provider.install end end end diff --git a/spec/unit/provider/package/dpkg_spec.rb b/spec/unit/provider/package/dpkg_spec.rb index 47ac9766e..444fb31c1 100755 --- a/spec/unit/provider/package/dpkg_spec.rb +++ b/spec/unit/provider/package/dpkg_spec.rb @@ -1,225 +1,225 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') provider = Puppet::Type.type(:package).provider(:dpkg) describe provider do before do @resource = stub 'resource', :[] => "asdf" @provider = provider.new(@resource) @provider.expects(:execute).never # forbid "manual" executions @fakeresult = "install ok installed asdf 1.0\n" end it "should have documentation" do provider.doc.should be_instance_of(String) end describe "when listing all instances" do before do provider.stubs(:command).with(:dpkgquery).returns "myquery" end it "should use dpkg-query" do provider.expects(:command).with(:dpkgquery).returns "myquery" provider.expects(:execpipe).with("myquery -W --showformat '${Status} ${Package} ${Version}\\n'").returns @fakeresult provider.instances end it "should create and return an instance with each parsed line from dpkg-query" do pipe = mock 'pipe' pipe.expects(:each).yields @fakeresult provider.expects(:execpipe).yields pipe asdf = mock 'pkg1' provider.expects(:new).with(:ensure => "1.0", :error => "ok", :desired => "install", :name => "asdf", :status => "installed", :provider => :dpkg).returns asdf provider.instances.should == [asdf] end it "should warn on and ignore any lines it does not understand" do pipe = mock 'pipe' pipe.expects(:each).yields "foobar" provider.expects(:execpipe).yields pipe Puppet.expects(:warning) provider.expects(:new).never provider.instances.should == [] end end describe "when querying the current state" do it "should use dpkg-query" do @provider.expects(:dpkgquery).with("-W", "--showformat",'${Status} ${Package} ${Version}\\n', "asdf").returns @fakeresult @provider.query end it "should consider the package purged if dpkg-query fails" do @provider.expects(:dpkgquery).raises Puppet::ExecutionFailure.new("eh") @provider.query[:ensure].should == :purged end it "should return a hash of the found status with the desired state, error state, status, name, and 'ensure'" do @provider.expects(:dpkgquery).returns @fakeresult @provider.query.should == {:ensure => "1.0", :error => "ok", :desired => "install", :name => "asdf", :status => "installed", :provider => :dpkg} end it "should consider the package absent if the dpkg-query result cannot be interpreted" do @provider.expects(:dpkgquery).returns "somebaddata" @provider.query[:ensure].should == :absent end it "should fail if an error is discovered" do @provider.expects(:dpkgquery).returns @fakeresult.sub("ok", "error") lambda { @provider.query }.should raise_error(Puppet::Error) end it "should consider the package purged if it is marked 'not-installed'" do @provider.expects(:dpkgquery).returns @fakeresult.sub("installed", "not-installed") @provider.query[:ensure].should == :purged end it "should consider the package absent if it is marked 'config-files'" do @provider.expects(:dpkgquery).returns @fakeresult.sub("installed", "config-files") @provider.query[:ensure].should == :absent end it "should consider the package absent if it is marked 'half-installed'" do @provider.expects(:dpkgquery).returns @fakeresult.sub("installed", "half-installed") @provider.query[:ensure].should == :absent end it "should consider the package absent if it is marked 'unpacked'" do @provider.expects(:dpkgquery).returns @fakeresult.sub("installed", "unpacked") @provider.query[:ensure].should == :absent end it "should consider the package absent if it is marked 'half-configured'" do @provider.expects(:dpkgquery).returns @fakeresult.sub("installed", "half-configured") @provider.query[:ensure].should == :absent end it "should consider the package held if its state is 'hold'" do @provider.expects(:dpkgquery).returns @fakeresult.sub("install", "hold") @provider.query[:ensure].should == :held end end it "should be able to install" do @provider.should respond_to(:install) end describe "when installing" do before do @resource.stubs(:[]).with(:source).returns "mypkg" end it "should fail to install if no source is specified in the resource" do @resource.expects(:[]).with(:source).returns nil lambda { @provider.install }.should raise_error(ArgumentError) end it "should use 'dpkg -i' to install the package" do @resource.expects(:[]).with(:source).returns "mypackagefile" @provider.expects(:unhold) @provider.expects(:dpkg).with { |*command| command[-1] == "mypackagefile" and command[-2] == "-i" } @provider.install end it "should keep old config files if told to do so" do @resource.expects(:[]).with(:configfiles).returns :keep @provider.expects(:unhold) @provider.expects(:dpkg).with { |*command| command[0] == "--force-confold" } @provider.install end it "should replace old config files if told to do so" do @resource.expects(:[]).with(:configfiles).returns :replace @provider.expects(:unhold) @provider.expects(:dpkg).with { |*command| command[0] == "--force-confnew" } @provider.install end it "should ensure any hold is removed" do @provider.expects(:unhold).once @provider.expects(:dpkg) @provider.install end end describe "when holding or unholding" do before do @tempfile = stub 'tempfile', :print => nil, :close => nil, :flush => nil, :path => "/other/file" @tempfile.stubs(:write) Tempfile.stubs(:new).returns @tempfile end it "should install first if holding" do @provider.stubs(:execute) @provider.expects(:install).once @provider.hold end it "should execute dpkg --set-selections when holding" do @provider.stubs(:install) @provider.expects(:execute).with([:dpkg, '--set-selections'], {:stdinfile => @tempfile.path}).once @provider.hold end it "should execute dpkg --set-selections when unholding" do @provider.stubs(:install) @provider.expects(:execute).with([:dpkg, '--set-selections'], {:stdinfile => @tempfile.path}).once @provider.hold end end it "should use :install to update" do @provider.expects(:install) @provider.update end describe "when determining latest available version" do it "should return the version found by dpkg-deb" do @resource.expects(:[]).with(:source).returns "myfile" @provider.expects(:dpkg_deb).with { |*command| command[-1] == "myfile" }.returns "asdf\t1.0" @provider.latest.should == "1.0" end it "should warn if the package file contains a different package" do @provider.expects(:dpkg_deb).returns("foo\tversion") @provider.expects(:warning) @provider.latest end it "should cope with names containing ++" do @resource = stub 'resource', :[] => "asdf++" @provider = provider.new(@resource) @provider.expects(:dpkg_deb).returns "asdf++\t1.0" @provider.latest.should == "1.0" end end it "should use 'dpkg -r' to uninstall" do @provider.expects(:dpkg).with("-r", "asdf") @provider.uninstall end it "should use 'dpkg --purge' to purge" do @provider.expects(:dpkg).with("--purge", "asdf") @provider.purge end end diff --git a/spec/unit/provider/package/pip_spec.rb b/spec/unit/provider/package/pip_spec.rb new file mode 100644 index 000000000..8953b4b2c --- /dev/null +++ b/spec/unit/provider/package/pip_spec.rb @@ -0,0 +1,177 @@ +#!/usr/bin/env ruby + +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') + +provider_class = Puppet::Type.type(:package).provider(:pip) + +describe provider_class do + + before do + @resource = Puppet::Resource.new(:package, "sdsfdssdhdfyjymdgfcjdfjxdrssf") + @provider = provider_class.new(@resource) + end + + describe "parse" do + + it "should return a hash on valid input" do + provider_class.parse("Django==1.2.5").should == { + :ensure => "1.2.5", + :name => "Django", + :provider => :pip, + } + end + + it "should return nil on invalid input" do + provider_class.parse("foo").should == nil + end + + end + + describe "instances" do + + it "should return an array when pip is present" do + provider_class.expects(:which).with('pip').returns("/fake/bin/pip") + p = stub("process") + p.expects(:collect).yields("Django==1.2.5") + provider_class.expects(:execpipe).with("/fake/bin/pip freeze").yields(p) + provider_class.instances + end + + it "should return an empty array when pip is missing" do + provider_class.expects(:which).with('pip').returns nil + provider_class.instances.should == [] + end + + end + + describe "query" do + + before do + @resource[:name] = "Django" + end + + it "should return a hash when pip and the package are present" do + provider_class.expects(:instances).returns [provider_class.new({ + :ensure => "1.2.5", + :name => "Django", + :provider => :pip, + })] + + @provider.query.should == { + :ensure => "1.2.5", + :name => "Django", + :provider => :pip, + } + end + + it "should return nil when the package is missing" do + provider_class.expects(:instances).returns [] + @provider.query.should == nil + end + + end + + describe "latest" do + + it "should find a version number for Django" do + @resource[:name] = "Django" + @provider.latest.should_not == nil + end + + it "should not find a version number for sdsfdssdhdfyjymdgfcjdfjxdrssf" do + @resource[:name] = "sdsfdssdhdfyjymdgfcjdfjxdrssf" + @provider.latest.should == nil + end + + end + + describe "install" do + + before do + @resource[:name] = "sdsfdssdhdfyjymdgfcjdfjxdrssf" + @url = "git+https://example.com/sdsfdssdhdfyjymdgfcjdfjxdrssf.git" + end + + it "should install" do + @resource[:ensure] = :installed + @resource[:source] = nil + @provider.expects(:lazy_pip). + with("install", '-q', "sdsfdssdhdfyjymdgfcjdfjxdrssf") + @provider.install + end + + it "should install from SCM" do + @resource[:ensure] = :installed + @resource[:source] = @url + @provider.expects(:lazy_pip). + with("install", '-q', '-e', "#{@url}#egg=sdsfdssdhdfyjymdgfcjdfjxdrssf") + @provider.install + end + + it "should install a particular SCM revision" do + @resource[:ensure] = "0123456" + @resource[:source] = @url + @provider.expects(:lazy_pip). + with("install", "-q", "-e", "#{@url}@0123456#egg=sdsfdssdhdfyjymdgfcjdfjxdrssf") + @provider.install + end + + it "should install a particular version" do + @resource[:ensure] = "0.0.0" + @resource[:source] = nil + @provider.expects(:lazy_pip).with("install", "-q", "sdsfdssdhdfyjymdgfcjdfjxdrssf==0.0.0") + @provider.install + end + + it "should upgrade" do + @resource[:ensure] = :latest + @resource[:source] = nil + @provider.expects(:lazy_pip). + with("install", "-q", "--upgrade", "sdsfdssdhdfyjymdgfcjdfjxdrssf") + @provider.install + end + + end + + describe "uninstall" do + + it "should uninstall" do + @resource[:name] = "sdsfdssdhdfyjymdgfcjdfjxdrssf" + @provider.expects(:lazy_pip). + with('uninstall', '-y', '-q', 'sdsfdssdhdfyjymdgfcjdfjxdrssf') + @provider.uninstall + end + + end + + describe "update" do + + it "should just call install" do + @provider.expects(:install).returns(nil) + @provider.update + end + + end + + describe "lazy_pip" do + + it "should succeed if pip is present" do + @provider.stubs(:pip).returns(nil) + @provider.method(:lazy_pip).call "freeze" + end + + it "should retry if pip has not yet been found" do + @provider.expects(:pip).twice.with('freeze').raises(NoMethodError).then.returns(nil) + @provider.expects(:which).with('pip').returns("/fake/bin/pip") + @provider.method(:lazy_pip).call "freeze" + end + + it "should fail if pip is missing" do + @provider.expects(:pip).with('freeze').raises(NoMethodError) + @provider.expects(:which).with('pip').returns(nil) + expect { @provider.method(:lazy_pip).call("freeze") }.to raise_error(NoMethodError) + end + + end + +end diff --git a/spec/unit/provider/package/pkg_spec.rb b/spec/unit/provider/package/pkg_spec.rb index 1544b8b7e..3455c4c40 100644 --- a/spec/unit/provider/package/pkg_spec.rb +++ b/spec/unit/provider/package/pkg_spec.rb @@ -1,63 +1,63 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') provider = Puppet::Type.type(:package).provider(:pkg) describe provider do before do @resource = stub 'resource', :[] => "dummy" @provider = provider.new(@resource) @fakeresult = "install ok installed dummy 1.0\n" end def self.it_should_respond_to(*actions) actions.each do |action| it "should respond to :#{action}" do @provider.should respond_to(action) end end end it_should_respond_to :install, :uninstall, :update, :query, :latest it "should be versionable" do provider.should_not be_versionable end it "should use :install to update" do @provider.expects(:install) @provider.update end it "should parse a line correctly" do result = provider.parse_line("dummy 1.0@1.0-1.0 installed ----") result.should == {:name => "dummy", :version => "1.0@1.0-1.0", :ensure => :present, :status => "installed", :provider => :pkg, :error => "ok"} end it "should fail to parse an incorrect line" do result = provider.parse_line("foo") result.should be_nil end it "should fail to list a missing package" do @provider.expects(:pkg).with(:list, "-H", "dummy").returns "1" @provider.query.should == {:status=>"missing", :ensure=>:absent, :name=>"dummy", :error=>"ok"} end it "should fail to list a package when it can't parse the output line" do @provider.expects(:pkg).with(:list, "-H", "dummy").returns "failed" @provider.query.should == {:status=>"missing", :ensure=>:absent, :name=>"dummy", :error=>"ok"} end it "should list package correctly" do @provider.expects(:pkg).with(:list, "-H", "dummy").returns "dummy 1.0@1.0-1.0 installed ----" @provider.query.should == {:name => "dummy", :version => "1.0@1.0-1.0", :ensure => :present, :status => "installed", :provider => :pkg, :error => "ok"} end end diff --git a/spec/unit/provider/package/pkgdmg_spec.rb b/spec/unit/provider/package/pkgdmg_spec.rb index 1fd5b4ac4..86631e596 100755 --- a/spec/unit/provider/package/pkgdmg_spec.rb +++ b/spec/unit/provider/package/pkgdmg_spec.rb @@ -1,84 +1,84 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') provider = Puppet::Type.type(:package).provider(:pkgdmg) describe provider do before do @resource = stub 'resource', :[] => "dummypkgdmg" @provider = provider.new(@resource) @fakemountpoint = "/tmp/dmg.foo" @fakepkgfile = "/tmp/test.pkg" @fakehdiutilinfo = {"system-entities" => [{"mount-point" => @fakemountpoint}] } @fakehdiutilplist = Plist::Emit.dump(@fakehdiutilinfo) @hdiutilmountargs = ["mount", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", "/tmp"] end it "should not be versionable" do provider.versionable?.should be_false end it "should not be uninstallable" do provider.uninstallable?.should be_false end describe "when installing it should fail when" do it "no source is specified" do @resource.stubs(:[]).with(:source).returns nil lambda { @provider.install }.should raise_error(Puppet::Error) end it "no name is specified" do @resource.stubs(:[]).with(:name).returns nil lambda { @provider.install }.should raise_error(Puppet::Error) end it "the source does not end in .dmg or .pkg" do @resource.stubs(:[]).with(:source).returns "notendingindotdmgorpkg" lambda { @provider.install }.should raise_error(Puppet::Error) end it "a disk image with no system entities is mounted" do @provider.stubs(:[]).with(:hdiutil).returns "" lambda { @provider.install }.should raise_error(Puppet::Error) end end # These tests shouldn't be this messy. The pkgdmg provider needs work... describe "when installing a pkgdmg" do before do fh = mock 'filehandle' fh.stubs(:path).yields "/tmp/foo" @resource.stubs(:[]).with(:source).returns "foo.dmg" File.stubs(:open).yields fh end it "should call hdiutil to mount and eject the disk image" do Dir.stubs(:entries).returns [] @provider.class.expects(:hdiutil).with("eject", @fakemountpoint).returns 0 @provider.class.expects(:hdiutil).with("mount", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", "/tmp", nil).returns @fakehdiutilplist @provider.install end it "should call installpkg if a pkg/mpkg is found on the dmg" do Dir.stubs(:entries).returns ["foo.pkg"] @provider.class.stubs(:hdiutil).returns @fakehdiutilplist @provider.class.expects(:installpkg).with("#{@fakemountpoint}/foo.pkg", @resource[:name], "foo.dmg").returns "" @provider.install end end describe "when installing flat pkg file" do it "should call installpkg if a flat pkg file is found instead of a .dmg image" do @resource.stubs(:[]).with(:source).returns "/tmp/test.pkg" @resource.stubs(:[]).with(:name).returns "testpkg" @provider.class.expects(:installpkgdmg).with("#{@fakepkgfile}", "testpkg").returns "" @provider.install end end end diff --git a/spec/unit/provider/selboolean_spec.rb b/spec/unit/provider/selboolean_spec.rb index b37b44b45..02a39f2a7 100755 --- a/spec/unit/provider/selboolean_spec.rb +++ b/spec/unit/provider/selboolean_spec.rb @@ -1,37 +1,37 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') provider_class = Puppet::Type.type(:selboolean).provider(:getsetsebool) describe provider_class do before :each do @resource = stub("resource", :name => "foo") @resource.stubs(:[]).returns "foo" @provider = provider_class.new(@resource) end it "should return :on when getsebool returns on" do @provider.expects(:getsebool).with("foo").returns "foo --> on\n" @provider.value.should == :on end it "should return :off when getsebool returns on" do @provider.expects(:getsebool).with("foo").returns "foo --> off\n" @provider.value.should == :off end it "should call execpipe when updating boolean setting" do @provider.expects(:command).with(:setsebool).returns "/usr/sbin/setsebool" @provider.expects(:execpipe).with("/usr/sbin/setsebool foo off") @provider.value = :off end it "should call execpipe with -P when updating persistent boolean setting" do @resource.stubs(:[]).with(:persistent).returns :true @provider.expects(:command).with(:setsebool).returns "/usr/sbin/setsebool" @provider.expects(:execpipe).with("/usr/sbin/setsebool -P foo off") @provider.value = :off end end diff --git a/spec/unit/provider/selmodule_spec.rb b/spec/unit/provider/selmodule_spec.rb index fda6d0d78..cb143e993 100755 --- a/spec/unit/provider/selmodule_spec.rb +++ b/spec/unit/provider/selmodule_spec.rb @@ -1,66 +1,66 @@ #!/usr/bin/env ruby # Note: This unit test depends on having a sample SELinux policy file # in the same directory as this test called selmodule-example.pp # with version 1.5.0. The provided selmodule-example.pp is the first # 256 bytes taken from /usr/share/selinux/targeted/nagios.pp on Fedora 9 -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') provider_class = Puppet::Type.type(:selmodule).provider(:semodule) describe provider_class do before :each do @resource = stub("resource", :name => "foo") @resource.stubs(:[]).returns "foo" @provider = provider_class.new(@resource) end describe "exists? method" do it "should find a module if it is already loaded" do @provider.expects(:command).with(:semodule).returns "/usr/sbin/semodule" @provider.expects(:execpipe).with("/usr/sbin/semodule --list").yields ["bar\t1.2.3\n", "foo\t4.4.4\n", "bang\t1.0.0\n"] @provider.exists?.should == :true end it "should return nil if not loaded" do @provider.expects(:command).with(:semodule).returns "/usr/sbin/semodule" @provider.expects(:execpipe).with("/usr/sbin/semodule --list").yields ["bar\t1.2.3\n", "bang\t1.0.0\n"] @provider.exists?.should be_nil end it "should return nil if no modules are loaded" do @provider.expects(:command).with(:semodule).returns "/usr/sbin/semodule" @provider.expects(:execpipe).with("/usr/sbin/semodule --list").yields [] @provider.exists?.should be_nil end end describe "selmodversion_file" do it "should return 1.5.0 for the example policy file" do @provider.expects(:selmod_name_to_filename).returns "#{File.dirname(__FILE__)}/selmodule-example.pp" @provider.selmodversion_file.should == "1.5.0" end end describe "syncversion" do it "should return :true if loaded and file modules are in sync" do @provider.expects(:selmodversion_loaded).returns "1.5.0" @provider.expects(:selmodversion_file).returns "1.5.0" @provider.syncversion.should == :true end it "should return :false if loaded and file modules are not in sync" do @provider.expects(:selmodversion_loaded).returns "1.4.0" @provider.expects(:selmodversion_file).returns "1.5.0" @provider.syncversion.should == :false end it "should return before checking file version if no loaded policy" do @provider.expects(:selmodversion_loaded).returns nil @provider.syncversion.should == :false end end end diff --git a/spec/unit/reports/http_spec.rb b/spec/unit/reports/http_spec.rb index 70742f7dc..a62793ed5 100644 --- a/spec/unit/reports/http_spec.rb +++ b/spec/unit/reports/http_spec.rb @@ -1,56 +1,56 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/reports' # FakeHTTP fakes the behavior of Net::HTTP#request and acts as a sensor for an # otherwise difficult to trace method call. # class FakeHTTP REQUESTS = {} def self.request(req) REQUESTS[req.path] = req end end processor = Puppet::Reports.report(:http) describe processor do before { Net::HTTP.any_instance.stubs(:start).yields(FakeHTTP) } subject { Puppet::Transaction::Report.new("apply").extend(processor) } it { should respond_to(:process) } it "should use the reporturl setting's host and port" do uri = URI.parse(Puppet[:reporturl]) Net::HTTP.expects(:new).with(uri.host, uri.port).returns(stub_everything('http')) subject.process end describe "request" do before { subject.process } describe "path" do it "should use the path specified by the 'reporturl' setting" do reports_request.path.should == URI.parse(Puppet[:reporturl]).path end end describe "body" do it "should be the report as YAML" do reports_request.body.should == subject.to_yaml end end describe "content type" do it "should be 'application/x-yaml'" do reports_request.content_type.should == "application/x-yaml" end end end private def reports_request; FakeHTTP::REQUESTS[URI.parse(Puppet[:reporturl]).path] end end diff --git a/spec/unit/reports/rrdgraph_spec.rb b/spec/unit/reports/rrdgraph_spec.rb index ce2cf7905..5215f1dcc 100644 --- a/spec/unit/reports/rrdgraph_spec.rb +++ b/spec/unit/reports/rrdgraph_spec.rb @@ -1,31 +1,31 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/reports' processor = Puppet::Reports.report(:rrdgraph) describe processor do include PuppetSpec::Files before do Puppet[:rrddir] = tmpdir('rrdgraph') Puppet.settings.use :master end after do FileUtils.rm_rf(Puppet[:rrddir]) end it "should not error on 0.25.x report format" do report = YAML.load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report0.25.x.yaml')).extend processor report.expects(:mkhtml) lambda{ report.process }.should_not raise_error end it "should not error on 2.6.x report format" do report = YAML.load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report2.6.x.yaml')).extend processor report.expects(:mkhtml) lambda{ report.process }.should_not raise_error end end diff --git a/spec/unit/reports/store_spec.rb b/spec/unit/reports/store_spec.rb index 9d9042386..d48f6a846 100644 --- a/spec/unit/reports/store_spec.rb +++ b/spec/unit/reports/store_spec.rb @@ -1,31 +1,31 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/reports' require 'time' processor = Puppet::Reports.report(:store) describe processor do describe "#process" do include PuppetSpec::Files before :each do Puppet[:reportdir] = tmpdir('reports') << '/reports' @report = YAML.load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report2.6.x.yaml')).extend processor end it "should create a report directory for the client if one doesn't exist" do @report.process File.should be_directory(File.join(Puppet[:reportdir], @report.host)) end it "should write the report to the file in YAML" do Time.stubs(:now).returns(Time.parse("2011-01-06 12:00:00 UTC")) @report.process File.read(File.join(Puppet[:reportdir], @report.host, "201101061200.yaml")).should == @report.to_yaml end end end diff --git a/spec/unit/reports/tagmail_spec.rb b/spec/unit/reports/tagmail_spec.rb index fa8990ebb..716bcbc04 100755 --- a/spec/unit/reports/tagmail_spec.rb +++ b/spec/unit/reports/tagmail_spec.rb @@ -1,92 +1,92 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/reports' tagmail = Puppet::Reports.report(:tagmail) describe tagmail do before do @processor = Puppet::Transaction::Report.new("apply") @processor.extend(Puppet::Reports.report(:tagmail)) end passers = my_fixture "tagmail_passers.conf" File.readlines(passers).each do |line| it "should be able to parse '#{line.inspect}'" do @processor.parse(line) end end failers = my_fixture "tagmail_failers.conf" File.readlines(failers).each do |line| it "should not be able to parse '#{line.inspect}'" do lambda { @processor.parse(line) }.should raise_error(ArgumentError) end end { "tag: abuse@domain.com" => [%w{abuse@domain.com}, %w{tag}, []], "tag.localhost: abuse@domain.com" => [%w{abuse@domain.com}, %w{tag.localhost}, []], "tag, other: abuse@domain.com" => [%w{abuse@domain.com}, %w{tag other}, []], "tag-other: abuse@domain.com" => [%w{abuse@domain.com}, %w{tag-other}, []], "tag, !other: abuse@domain.com" => [%w{abuse@domain.com}, %w{tag}, %w{other}], "tag, !other, one, !two: abuse@domain.com" => [%w{abuse@domain.com}, %w{tag one}, %w{other two}], "tag: abuse@domain.com, other@domain.com" => [%w{abuse@domain.com other@domain.com}, %w{tag}, []] }.each do |line, results| it "should parse '#{line}' as #{results.inspect}" do @processor.parse(line).shift.should == results end end describe "when matching logs" do before do @processor << Puppet::Util::Log.new(:level => :notice, :message => "first", :tags => %w{one}) @processor << Puppet::Util::Log.new(:level => :notice, :message => "second", :tags => %w{one two}) @processor << Puppet::Util::Log.new(:level => :notice, :message => "third", :tags => %w{one two three}) end def match(pos = [], neg = []) pos = Array(pos) neg = Array(neg) result = @processor.match([[%w{abuse@domain.com}, pos, neg]]) actual_result = result.shift if actual_result actual_result[1] else nil end end it "should match all messages when provided the 'all' tag as a positive matcher" do results = match("all") %w{first second third}.each do |str| results.should be_include(str) end end it "should remove messages that match a negated tag" do match("all", "three").should_not be_include("third") end it "should find any messages tagged with a provided tag" do results = match("two") results.should be_include("second") results.should be_include("third") results.should_not be_include("first") end it "should allow negation of specific tags from a specific tag list" do results = match("two", "three") results.should be_include("second") results.should_not be_include("third") end it "should allow a tag to negate all matches" do results = match([], "one") results.should be_nil end end end diff --git a/spec/unit/type/cron_spec.rb b/spec/unit/type/cron_spec.rb index 03817d20e..5466b4d58 100755 --- a/spec/unit/type/cron_spec.rb +++ b/spec/unit/type/cron_spec.rb @@ -1,33 +1,481 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Puppet::Type.type(:cron) do before do - @cron = Puppet::Type.type(:cron).new( :name => "foo" ) - end + @class = Puppet::Type.type(:cron) + + # Init a fake provider + @provider_class = stub 'provider_class', :ancestors => [], :name => 'fake', :suitable? => true, :supports_parameter? => true + @class.stubs(:defaultprovider).returns @provider_class + @class.stubs(:provider).returns @provider_class + + @provider = stub 'provider', :class => @provider_class, :clean => nil + @provider.stubs(:is_a?).returns false + @provider_class.stubs(:new).returns @provider - it "it should accept an :environment that looks like a path" do - lambda do - @cron[:environment] = 'PATH=/bin:/usr/bin:/usr/sbin' - end.should_not raise_error + @cron = @class.new( :name => "foo" ) end - it "should not accept environment variables that do not contain '='" do - lambda do - @cron[:environment] = "INVALID" - end.should raise_error(Puppet::Error) + it "should have :name be its namevar" do + @class.key_attributes.should == [:name] end - it "should accept empty environment variables that do not contain '='" do - lambda do - @cron[:environment] = "MAILTO=" - end.should_not raise_error(Puppet::Error) + describe "when validating attributes" do + + [:name, :provider].each do |param| + it "should have a #{param} parameter" do + @class.attrtype(param).should == :param + end + end + + [:command, :special, :minute, :hour, :weekday, :month, :monthday, :environment, :user, :target].each do |property| + it "should have a #{property} property" do + @class.attrtype(property).should == :property + end + end + + [:command, :minute, :hour, :weekday, :month, :monthday].each do |cronparam| + it "should have #{cronparam} of type CronParam" do + @class.attrclass(cronparam).ancestors.should include CronParam + end + end + end - it "should accept 'absent'" do - lambda do - @cron[:environment] = 'absent' - end.should_not raise_error(Puppet::Error) + + describe "when validating attribute" do + + describe "ensure" do + it "should support present as a value for ensure" do + proc { @class.new(:name => 'foo', :ensure => :present) }.should_not raise_error + end + + it "should support absent as a value for ensure" do + proc { @class.new(:name => 'foo', :ensure => :present) }.should_not raise_error + end + end + + describe "minute" do + + it "should support absent" do + proc { @class.new(:name => 'foo', :minute => 'absent') }.should_not raise_error + end + + it "should support *" do + proc { @class.new(:name => 'foo', :minute => '*') }.should_not raise_error + end + + it "should translate absent to :absent" do + @class.new(:name => 'foo', :minute => 'absent')[:minute].should == :absent + end + + it "should translate * to :absent" do + @class.new(:name => 'foo', :minute => '*')[:minute].should == :absent + end + + it "should support valid single values" do + proc { @class.new(:name => 'foo', :minute => '0') }.should_not raise_error + proc { @class.new(:name => 'foo', :minute => '1') }.should_not raise_error + proc { @class.new(:name => 'foo', :minute => '59') }.should_not raise_error + end + + it "should not support non numeric characters" do + proc { @class.new(:name => 'foo', :minute => 'z59') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => '5z9') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => '59z') }.should raise_error(Puppet::Error) + end + + it "should not support single values out of range" do + + proc { @class.new(:name => 'foo', :minute => '-1') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => '60') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => '61') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => '120') }.should raise_error(Puppet::Error) + end + + it "should support valid multiple values" do + proc { @class.new(:name => 'foo', :minute => ['0','1','59'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :minute => ['40','30','20'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :minute => ['10','30','20'] ) }.should_not raise_error + end + + it "should not support multiple values if at least one is invalid" do + # one invalid + proc { @class.new(:name => 'foo', :minute => ['0','1','60'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => ['0','120','59'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => ['-1','1','59'] ) }.should raise_error(Puppet::Error) + # two invalid + proc { @class.new(:name => 'foo', :minute => ['0','61','62'] ) }.should raise_error(Puppet::Error) + # all invalid + proc { @class.new(:name => 'foo', :minute => ['-1','61','62'] ) }.should raise_error(Puppet::Error) + end + + it "should support valid step syntax" do + proc { @class.new(:name => 'foo', :minute => '*/2' ) }.should_not raise_error + proc { @class.new(:name => 'foo', :minute => '10-16/2' ) }.should_not raise_error + end + + it "should not support invalid steps" do + proc { @class.new(:name => 'foo', :minute => '*/A' ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :minute => '*/2A' ) }.should raise_error(Puppet::Error) + # As it turns out cron does not complaining about steps that exceed the valid range + # proc { @class.new(:name => 'foo', :minute => '*/120' ) }.should raise_error(Puppet::Error) + end + + end + + describe "hour" do + + it "should support absent" do + proc { @class.new(:name => 'foo', :hour => 'absent') }.should_not raise_error + end + + it "should support *" do + proc { @class.new(:name => 'foo', :hour => '*') }.should_not raise_error + end + + it "should translate absent to :absent" do + @class.new(:name => 'foo', :hour => 'absent')[:hour].should == :absent + end + + it "should translate * to :absent" do + @class.new(:name => 'foo', :hour => '*')[:hour].should == :absent + end + + it "should support valid single values" do + proc { @class.new(:name => 'foo', :hour => '0') }.should_not raise_error + proc { @class.new(:name => 'foo', :hour => '11') }.should_not raise_error + proc { @class.new(:name => 'foo', :hour => '12') }.should_not raise_error + proc { @class.new(:name => 'foo', :hour => '13') }.should_not raise_error + proc { @class.new(:name => 'foo', :hour => '23') }.should_not raise_error + end + + it "should not support non numeric characters" do + proc { @class.new(:name => 'foo', :hour => 'z15') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :hour => '1z5') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :hour => '15z') }.should raise_error(Puppet::Error) + end + + it "should not support single values out of range" do + proc { @class.new(:name => 'foo', :hour => '-1') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :hour => '24') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :hour => '120') }.should raise_error(Puppet::Error) + end + + it "should support valid multiple values" do + proc { @class.new(:name => 'foo', :hour => ['0','1','23'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :hour => ['5','16','14'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :hour => ['16','13','9'] ) }.should_not raise_error + end + + it "should not support multiple values if at least one is invalid" do + # one invalid + proc { @class.new(:name => 'foo', :hour => ['0','1','24'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :hour => ['0','-1','5'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :hour => ['-1','1','23'] ) }.should raise_error(Puppet::Error) + # two invalid + proc { @class.new(:name => 'foo', :hour => ['0','25','26'] ) }.should raise_error(Puppet::Error) + # all invalid + proc { @class.new(:name => 'foo', :hour => ['-1','24','120'] ) }.should raise_error(Puppet::Error) + end + + it "should support valid step syntax" do + proc { @class.new(:name => 'foo', :hour => '*/2' ) }.should_not raise_error + proc { @class.new(:name => 'foo', :hour => '10-18/4' ) }.should_not raise_error + end + + it "should not support invalid steps" do + proc { @class.new(:name => 'foo', :hour => '*/A' ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :hour => '*/2A' ) }.should raise_error(Puppet::Error) + # As it turns out cron does not complaining about steps that exceed the valid range + # proc { @class.new(:name => 'foo', :hour => '*/26' ) }.should raise_error(Puppet::Error) + end + + end + + describe "weekday" do + + it "should support absent" do + proc { @class.new(:name => 'foo', :weekday => 'absent') }.should_not raise_error + end + + it "should support *" do + proc { @class.new(:name => 'foo', :weekday => '*') }.should_not raise_error + end + + it "should translate absent to :absent" do + @class.new(:name => 'foo', :weekday => 'absent')[:weekday].should == :absent + end + + it "should translate * to :absent" do + @class.new(:name => 'foo', :weekday => '*')[:weekday].should == :absent + end + + it "should support valid numeric weekdays" do + proc { @class.new(:name => 'foo', :weekday => '0') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => '1') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => '6') }.should_not raise_error + # According to http://www.manpagez.com/man/5/crontab 7 is also valid (Sunday) + proc { @class.new(:name => 'foo', :weekday => '7') }.should_not raise_error + end + + it "should support valid weekdays as words (3 character version)" do + proc { @class.new(:name => 'foo', :weekday => 'Monday') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Tuesday') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Wednesday') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Thursday') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Friday') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Saturday') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Sunday') }.should_not raise_error + end + + it "should support valid weekdays as words (3 character version)" do + proc { @class.new(:name => 'foo', :weekday => 'Mon') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Tue') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Wed') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Thu') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Fri') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Sat') }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => 'Sun') }.should_not raise_error + end + + it "should not support numeric values out of range" do + proc { @class.new(:name => 'foo', :weekday => '-1') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :weekday => '8') }.should raise_error(Puppet::Error) + end + + it "should not support invalid weekday names" do + proc { @class.new(:name => 'foo', :weekday => 'Sar') }.should raise_error(Puppet::Error) + end + + it "should support valid multiple values" do + proc { @class.new(:name => 'foo', :weekday => ['0','1','6'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => ['Mon','Wed','Friday'] ) }.should_not raise_error + end + + it "should not support multiple values if at least one is invalid" do + # one invalid + proc { @class.new(:name => 'foo', :weekday => ['0','1','8'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :weekday => ['Mon','Fii','Sat'] ) }.should raise_error(Puppet::Error) + # two invalid + proc { @class.new(:name => 'foo', :weekday => ['Mos','Fii','Sat'] ) }.should raise_error(Puppet::Error) + # all invalid + proc { @class.new(:name => 'foo', :weekday => ['Mos','Fii','Saa'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :weekday => ['-1','8','11'] ) }.should raise_error(Puppet::Error) + end + + it "should support valid step syntax" do + proc { @class.new(:name => 'foo', :weekday => '*/2' ) }.should_not raise_error + proc { @class.new(:name => 'foo', :weekday => '0-4/2' ) }.should_not raise_error + end + + it "should not support invalid steps" do + proc { @class.new(:name => 'foo', :weekday => '*/A' ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :weekday => '*/2A' ) }.should raise_error(Puppet::Error) + # As it turns out cron does not complaining about steps that exceed the valid range + # proc { @class.new(:name => 'foo', :weekday => '*/9' ) }.should raise_error(Puppet::Error) + end + + end + + describe "month" do + + it "should support absent" do + proc { @class.new(:name => 'foo', :month => 'absent') }.should_not raise_error + end + + it "should support *" do + proc { @class.new(:name => 'foo', :month => '*') }.should_not raise_error + end + + it "should translate absent to :absent" do + @class.new(:name => 'foo', :month => 'absent')[:month].should == :absent + end + + it "should translate * to :absent" do + @class.new(:name => 'foo', :month => '*')[:month].should == :absent + end + + it "should support valid numeric values" do + proc { @class.new(:name => 'foo', :month => '1') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => '12') }.should_not raise_error + end + + it "should support valid months as words" do + proc { @class.new(:name => 'foo', :month => 'January') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'February') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'March') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'April') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'May') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'June') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'July') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'August') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'September') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'October') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'November') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'December') }.should_not raise_error + end + + it "should support valid months as words (3 character short version)" do + proc { @class.new(:name => 'foo', :month => 'Jan') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Feb') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Mar') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Apr') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'May') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Jun') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Jul') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Aug') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Sep') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Oct') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Nov') }.should_not raise_error + proc { @class.new(:name => 'foo', :month => 'Dec') }.should_not raise_error + end + + it "should not support numeric values out of range" do + proc { @class.new(:name => 'foo', :month => '-1') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => '0') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => '13') }.should raise_error(Puppet::Error) + end + + it "should not support words that are not valid months" do + proc { @class.new(:name => 'foo', :month => 'Jal') }.should raise_error(Puppet::Error) + end + + it "should not support single values out of range" do + + proc { @class.new(:name => 'foo', :month => '-1') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => '60') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => '61') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => '120') }.should raise_error(Puppet::Error) + end + + it "should support valid multiple values" do + proc { @class.new(:name => 'foo', :month => ['1','9','12'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :month => ['Jan','March','Jul'] ) }.should_not raise_error + end + + it "should not support multiple values if at least one is invalid" do + # one invalid + proc { @class.new(:name => 'foo', :month => ['0','1','12'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => ['1','13','10'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => ['Jan','Feb','Jxx'] ) }.should raise_error(Puppet::Error) + # two invalid + proc { @class.new(:name => 'foo', :month => ['Jan','Fex','Jux'] ) }.should raise_error(Puppet::Error) + # all invalid + proc { @class.new(:name => 'foo', :month => ['-1','0','13'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => ['Jax','Fex','Aux'] ) }.should raise_error(Puppet::Error) + end + + it "should support valid step syntax" do + proc { @class.new(:name => 'foo', :month => '*/2' ) }.should_not raise_error + proc { @class.new(:name => 'foo', :month => '1-12/3' ) }.should_not raise_error + end + + it "should not support invalid steps" do + proc { @class.new(:name => 'foo', :month => '*/A' ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :month => '*/2A' ) }.should raise_error(Puppet::Error) + # As it turns out cron does not complaining about steps that exceed the valid range + # proc { @class.new(:name => 'foo', :month => '*/13' ) }.should raise_error(Puppet::Error) + end + + end + + describe "monthday" do + + it "should support absent" do + proc { @class.new(:name => 'foo', :monthday => 'absent') }.should_not raise_error + end + + it "should support *" do + proc { @class.new(:name => 'foo', :monthday => '*') }.should_not raise_error + end + + it "should translate absent to :absent" do + @class.new(:name => 'foo', :monthday => 'absent')[:monthday].should == :absent + end + + it "should translate * to :absent" do + @class.new(:name => 'foo', :monthday => '*')[:monthday].should == :absent + end + + it "should support valid single values" do + proc { @class.new(:name => 'foo', :monthday => '1') }.should_not raise_error + proc { @class.new(:name => 'foo', :monthday => '30') }.should_not raise_error + proc { @class.new(:name => 'foo', :monthday => '31') }.should_not raise_error + end + + it "should not support non numeric characters" do + proc { @class.new(:name => 'foo', :monthday => 'z23') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :monthday => '2z3') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :monthday => '23z') }.should raise_error(Puppet::Error) + end + + it "should not support single values out of range" do + proc { @class.new(:name => 'foo', :monthday => '-1') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :monthday => '0') }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :monthday => '32') }.should raise_error(Puppet::Error) + end + + it "should support valid multiple values" do + proc { @class.new(:name => 'foo', :monthday => ['1','23','31'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :monthday => ['31','23','1'] ) }.should_not raise_error + proc { @class.new(:name => 'foo', :monthday => ['1','31','23'] ) }.should_not raise_error + end + + it "should not support multiple values if at least one is invalid" do + # one invalid + proc { @class.new(:name => 'foo', :monthday => ['1','23','32'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :monthday => ['-1','12','23'] ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :monthday => ['13','32','30'] ) }.should raise_error(Puppet::Error) + # two invalid + proc { @class.new(:name => 'foo', :monthday => ['-1','0','23'] ) }.should raise_error(Puppet::Error) + # all invalid + proc { @class.new(:name => 'foo', :monthday => ['-1','0','32'] ) }.should raise_error(Puppet::Error) + end + + it "should support valid step syntax" do + proc { @class.new(:name => 'foo', :monthday => '*/2' ) }.should_not raise_error + proc { @class.new(:name => 'foo', :monthday => '10-16/2' ) }.should_not raise_error + end + + it "should not support invalid steps" do + proc { @class.new(:name => 'foo', :monthday => '*/A' ) }.should raise_error(Puppet::Error) + proc { @class.new(:name => 'foo', :monthday => '*/2A' ) }.should raise_error(Puppet::Error) + # As it turns out cron does not complaining about steps that exceed the valid range + # proc { @class.new(:name => 'foo', :monthday => '*/32' ) }.should raise_error(Puppet::Error) + end + + end + + describe "environment" do + + it "it should accept an :environment that looks like a path" do + lambda do + @cron[:environment] = 'PATH=/bin:/usr/bin:/usr/sbin' + end.should_not raise_error + end + + it "should not accept environment variables that do not contain '='" do + lambda do + @cron[:environment] = "INVALID" + end.should raise_error(Puppet::Error) + end + + it "should accept empty environment variables that do not contain '='" do + lambda do + @cron[:environment] = "MAILTO=" + end.should_not raise_error(Puppet::Error) + end + + it "should accept 'absent'" do + lambda do + @cron[:environment] = 'absent' + end.should_not raise_error(Puppet::Error) + end + + end + end end diff --git a/spec/unit/type/exec_spec.rb b/spec/unit/type/exec_spec.rb index e980ec542..a1ffb1636 100755 --- a/spec/unit/type/exec_spec.rb +++ b/spec/unit/type/exec_spec.rb @@ -1,162 +1,648 @@ #!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Puppet::Type.type(:exec) do - - def create_resource(command, output, exitstatus, returns = 0) - @user_name = 'some_user_name' + def exec_tester(command, exitstatus = 0, rest = {}) + @user_name = 'some_user_name' @group_name = 'some_group_name' Puppet.features.stubs(:root?).returns(true) - @execer = Puppet::Type.type(:exec).new(:name => command, :path => @example_path, :user => @user_name, :group => @group_name, :returns => returns) - status = stub "process" - status.stubs(:exitstatus).returns(exitstatus) + output = rest.delete(:output) || '' + tries = rest[:tries] || 1 + + args = { + :name => command, + :path => @example_path, + :user => @user_name, + :group => @group_name, + :logoutput => false, + :loglevel => :err, + :returns => 0 + }.merge(rest) + + exec = Puppet::Type.type(:exec).new(args) + + status = stub "process", :exitstatus => exitstatus + Puppet::Util::SUIDManager.expects(:run_and_capture).times(tries). + with([command], @user_name, @group_name).returns([output, status]) - Puppet::Util::SUIDManager.expects(:run_and_capture).with([command], @user_name, @group_name).returns([output, status]) + return exec end - def create_logging_resource(command, output, exitstatus, logoutput, loglevel, returns = 0) - create_resource(command, output, exitstatus, returns) - @execer[:logoutput] = logoutput - @execer[:loglevel] = loglevel + before do + @command = Puppet.features.posix? ? '/bin/true whatever' : '"C:/Program Files/something.exe" whatever' end - def expect_output(output, loglevel) - output.split(/\n/).each do |line| - @execer.property(:returns).expects(loglevel).with(line) + describe "when not stubbing the provider" do + before do + @executable = Puppet.features.posix? ? '/bin/true' : 'C:/Program Files/something.exe' + File.stubs(:exists?).returns false + File.stubs(:exists?).with(@executable).returns true + File.stubs(:exists?).with('/bin/false').returns true + @example_path = Puppet.features.posix? ? %w{/usr/bin /bin} : [ "C:/Program Files/something/bin", "C:/Ruby/bin" ] + File.stubs(:exists?).with(File.join(@example_path[0],"true")).returns true + File.stubs(:exists?).with(File.join(@example_path[0],"false")).returns true + end + + it "should return :executed_command as its event" do + resource = Puppet::Type.type(:exec).new :command => @command + resource.parameter(:returns).event.name.should == :executed_command + end + + describe "when execing" do + it "should use the 'run_and_capture' method to exec" do + exec_tester("true").refresh.should == :executed_command + end + + it "should report a failure" do + proc { exec_tester('false', 1).refresh }. + should raise_error(Puppet::Error, /^false returned 1 instead of/) + end + + it "should not report a failure if the exit status is specified in a returns array" do + proc { exec_tester("false", 1, :returns => [0, 1]).refresh }.should_not raise_error + end + + it "should report a failure if the exit status is not specified in a returns array" do + proc { exec_tester('false', 1, :returns => [0, 100]).refresh }. + should raise_error(Puppet::Error, /^false returned 1 instead of/) + end + + it "should log the output on success" do + output = "output1\noutput2\n" + exec_tester('false', 0, :output => output, :logoutput => true).refresh + output.split("\n").each do |line| + log = @logs.shift + log.level.should == :err + log.message.should == line + end + end + + it "should log the output on failure" do + output = "output1\noutput2\n" + proc { exec_tester('false', 1, :output => output, :logoutput => true).refresh }. + should raise_error(Puppet::Error) + + output.split("\n").each do |line| + log = @logs.shift + log.level.should == :err + log.message.should == line + end + end + end + + describe "when logoutput=>on_failure is set" do + it "should log the output on failure" do + output = "output1\noutput2\n" + proc { exec_tester('false', 1, :output => output, :logoutput => :on_failure).refresh }. + should raise_error(Puppet::Error, /^false returned 1 instead of/) + + output.split("\n").each do |line| + log = @logs.shift + log.level.should == :err + log.message.should == line + end + end + + it "should log the output on failure when returns is specified as an array" do + output = "output1\noutput2\n" + + proc { + exec_tester('false', 1, :output => output, :returns => [0, 100], + :logoutput => :on_failure).refresh + }.should raise_error(Puppet::Error, /^false returned 1 instead of/) + + output.split("\n").each do |line| + log = @logs.shift + log.level.should == :err + log.message.should == line + end + end + + it "shouldn't log the output on success" do + exec_tester('true', 0, :output => "a\nb\nc\n", :logoutput => :on_failure).refresh + @logs.should == [] + end + end + + it "shouldn't log the output on success when non-zero exit status is in a returns array" do + exec_tester("true", 100, :output => "a\n", :logoutput => :on_failure, :returns => [1, 100]).refresh + @logs.should == [] + end + + describe " when multiple tries are set," do + it "should repeat the command attempt 'tries' times on failure and produce an error" do + tries = 5 + resource = exec_tester("false", 1, :tries => tries, :try_sleep => 0) + proc { resource.refresh }.should raise_error(Puppet::Error) + end end end - before do - @executable = Puppet.features.posix? ? '/bin/true' : 'C:/Program Files/something.exe' - @command = Puppet.features.posix? ? '/bin/true whatever' : '"C:/Program Files/something.exe" whatever' - File.stubs(:exists?).returns false - File.stubs(:exists?).with(@executable).returns true - @example_path = Puppet.features.posix? ? %w{/usr/bin /bin} : [ "C:/Program Files/something/bin", "C:/Ruby/bin" ] - File.stubs(:exists?).with(File.join(@example_path[0],"true")).returns true - File.stubs(:exists?).with(File.join(@example_path[0],"false")).returns true + it "should be able to autorequire files mentioned in the command" do + catalog = Puppet::Resource::Catalog.new + tmp = Puppet::Type.type(:file).new(:name => "/bin/foo") + catalog.add_resource tmp + execer = Puppet::Type.type(:exec).new(:name => "/bin/foo") + catalog.add_resource execer + + catalog.relationship_graph.dependencies(execer).should == [tmp] + end + + describe "when handling the path parameter" do + expect = %w{one two three four} + { "an array" => expect, + "a colon separated list" => "one:two:three:four", + "a semi-colon separated list" => "one;two;three;four", + "both array and colon lists" => ["one", "two:three", "four"], + "both array and semi-colon lists" => ["one", "two;three", "four"], + "colon and semi-colon lists" => ["one:two", "three;four"] + }.each do |test, input| + it "should accept #{test}" do + type = Puppet::Type.type(:exec).new(:name => @command, :path => input) + type[:path].should == expect + end + end end - it "should return :executed_command as its event" do - resource = Puppet::Type.type(:exec).new :command => @command - resource.parameter(:returns).event.name.should == :executed_command + describe "when setting user" do + it "should fail if we are not root" do + Puppet.features.stubs(:root?).returns(false) + expect { Puppet::Type.type(:exec).new(:name => @command, :user => 'input') }. + should raise_error Puppet::Error, /Parameter user failed/ + end + + ['one', 2, 'root', 4294967295, 4294967296].each do |value| + it "should accept '#{value}' as user if we are root" do + Puppet.features.stubs(:root?).returns(true) + type = Puppet::Type.type(:exec).new(:name => @command, :user => value) + type[:user].should == value + end + end end - describe "when execing" do + describe "when setting group" do + shared_examples_for "exec[:group]" do + ['one', 2, 'wheel', 4294967295, 4294967296].each do |value| + it "should accept '#{value}' without error or judgement" do + type = Puppet::Type.type(:exec).new(:name => @command, :group => value) + type[:group].should == value + end + end + end + + describe "when running as root" do + before :each do Puppet.features.stubs(:root?).returns(true) end + it_behaves_like "exec[:group]" + end + + describe "when not running as root" do + before :each do Puppet.features.stubs(:root?).returns(false) end + it_behaves_like "exec[:group]" + end + end + + describe "when setting cwd" do + it_should_behave_like "all path parameters", :cwd, :array => false do + def instance(path) + Puppet::Type.type(:exec).new(:name => '/bin/true', :cwd => path) + end + end + end + + shared_examples_for "all exec command parameters" do |param| + { "relative" => "example", "absolute" => "/bin/example" }.sort.each do |name, command| + describe "if command is #{name}" do + before :each do + @param = param + end + + def test(command, valid) + if @param == :name then + instance = Puppet::Type.type(:exec).new() + else + instance = Puppet::Type.type(:exec).new(:name => "/bin/true") + end + if valid then + instance.provider.expects(:validatecmd).returns(true) + else + instance.provider.expects(:validatecmd).raises(Puppet::Error, "from a stub") + end + instance[@param] = command + end + + it "should work if the provider calls the command valid" do + expect { test(command, true) }.should_not raise_error + end + + it "should fail if the provider calls the command invalid" do + expect { test(command, false) }. + should raise_error Puppet::Error, /Parameter #{@param} failed: from a stub/ + end + end + end + end + + shared_examples_for "all exec command parameters that take arrays" do |param| + describe "when given an array of inputs" do + before :each do + @test = Puppet::Type.type(:exec).new(:name => "/bin/true") + end + + it "should accept the array when all commands return valid" do + input = %w{one two three} + @test.provider.expects(:validatecmd).times(input.length).returns(true) + @test[param] = input + @test[param].should == input + end - it "should use the 'run_and_capture' method to exec" do - command = "true" - create_resource(command, "", 0) + it "should reject the array when any commands return invalid" do + input = %w{one two three} + @test.provider.expects(:validatecmd).with(input.first).returns(false) + input[1..-1].each do |cmd| + @test.provider.expects(:validatecmd).with(cmd).returns(true) + end + @test[param] = input + @test[param].should == input + end - @execer.refresh.should == :executed_command + it "should reject the array when all commands return invalid" do + input = %w{one two three} + @test.provider.expects(:validatecmd).times(input.length).returns(false) + @test[param] = input + @test[param].should == input + end end + end - it "should report a failure" do - command = "false" - create_resource(command, "", 1) + describe "when setting refresh" do + it_should_behave_like "all exec command parameters", :refresh + end - proc { @execer.refresh }.should raise_error(Puppet::Error) + describe "for simple parameters" do + before :each do + @exec = Puppet::Type.type(:exec).new(:name => '/bin/true') end - it "should not report a failure if the exit status is specified in a returns array" do - command = "false" - create_resource(command, "", 1, [0,1]) - proc { @execer.refresh }.should_not raise_error(Puppet::Error) + describe "when setting environment" do + { "single values" => "foo=bar", + "multiple values" => ["foo=bar", "baz=quux"], + }.each do |name, data| + it "should accept #{name}" do + @exec[:environment] = data + @exec[:environment].should == data + end + end + + { "single values" => "foo", + "only values" => ["foo", "bar"], + "any values" => ["foo=bar", "baz"] + }.each do |name, data| + it "should reject #{name} without assignment" do + expect { @exec[:environment] = data }. + should raise_error Puppet::Error, /Invalid environment setting/ + end + end + end + + describe "when setting timeout" do + [-3.5, -1, 0, 0.1, 1, 10, 4294967295].each do |valid| + it "should accept '#{valid}' as valid" do + @exec[:timeout] = valid + @exec[:timeout].should == valid + end + + it "should accept '#{valid}' in an array as valid" do + @exec[:timeout] = [valid] + @exec[:timeout].should == valid + end + end + + ['1/2', '1_000_000', '+12', '', 'foo'].each do |invalid| + it "should reject '#{invalid}' as invalid" do + expect { @exec[:timeout] = invalid }. + should raise_error Puppet::Error, /The timeout must be a number/ + end + + it "should reject '#{invalid}' in an array as invalid" do + expect { @exec[:timeout] = [invalid] }. + should raise_error Puppet::Error, /The timeout must be a number/ + end + end + + it "should fail if timeout is exceeded" do + File.stubs(:exists?).with('/bin/sleep').returns(true) + File.stubs(:exists?).with('sleep').returns(false) + sleep_exec = Puppet::Type.type(:exec).new(:name => 'sleep 1', :path => ['/bin'], :timeout => '0.2') + lambda { sleep_exec.refresh }.should raise_error Puppet::Error, "Command exceeded timeout" + end end - it "should report a failure if the exit status is not specified in a returns array" do - command = "false" - create_resource(command, "", 1, [0,100]) - proc { @execer.refresh }.should raise_error(Puppet::Error) + describe "when setting tries" do + [1, 10, 4294967295].each do |valid| + it "should accept '#{valid}' as valid" do + @exec[:tries] = valid + @exec[:tries].should == valid + end + + if "REVISIT: too much test log spam" == "a good thing" then + it "should accept '#{valid}' in an array as valid" do + pending "inconsistent, but this is not supporting arrays, unlike timeout" + @exec[:tries] = [valid] + @exec[:tries].should == valid + end + end + end + + [-3.5, -1, 0, 0.2, '1/2', '1_000_000', '+12', '', 'foo'].each do |invalid| + it "should reject '#{invalid}' as invalid" do + expect { @exec[:tries] = invalid }. + should raise_error Puppet::Error, /Tries must be an integer/ + end + + if "REVISIT: too much test log spam" == "a good thing" then + it "should reject '#{invalid}' in an array as invalid" do + pending "inconsistent, but this is not supporting arrays, unlike timeout" + expect { @exec[:tries] = [invalid] }. + should raise_error Puppet::Error, /Tries must be an integer/ + end + end + end end - it "should log the output on success" do - #Puppet::Util::Log.newdestination :console - command = "false" - output = "output1\noutput2\n" - create_logging_resource(command, output, 0, true, :err) - expect_output(output, :err) - @execer.refresh + describe "when setting try_sleep" do + [0, 0.2, 1, 10, 4294967295].each do |valid| + it "should accept '#{valid}' as valid" do + @exec[:try_sleep] = valid + @exec[:try_sleep].should == valid + end + + if "REVISIT: too much test log spam" == "a good thing" then + it "should accept '#{valid}' in an array as valid" do + pending "inconsistent, but this is not supporting arrays, unlike timeout" + @exec[:try_sleep] = [valid] + @exec[:try_sleep].should == valid + end + end + end + + { -3.5 => "cannot be a negative number", + -1 => "cannot be a negative number", + '1/2' => 'must be a number', + '1_000_000' => 'must be a number', + '+12' => 'must be a number', + '' => 'must be a number', + 'foo' => 'must be a number', + }.each do |invalid, error| + it "should reject '#{invalid}' as invalid" do + expect { @exec[:try_sleep] = invalid }. + should raise_error Puppet::Error, /try_sleep #{error}/ + end + + if "REVISIT: too much test log spam" == "a good thing" then + it "should reject '#{invalid}' in an array as invalid" do + pending "inconsistent, but this is not supporting arrays, unlike timeout" + expect { @exec[:try_sleep] = [invalid] }. + should raise_error Puppet::Error, /try_sleep #{error}/ + end + end + end end - it "should log the output on failure" do - #Puppet::Util::Log.newdestination :console - command = "false" - output = "output1\noutput2\n" - create_logging_resource(command, output, 1, true, :err) - expect_output(output, :err) + describe "when setting refreshonly" do + [:true, :false].each do |value| + it "should accept '#{value}'" do + @exec[:refreshonly] = value + @exec[:refreshonly].should == value + end + end - proc { @execer.refresh }.should raise_error(Puppet::Error) + [1, 0, "1", "0", "yes", "y", "no", "n"].each do |value| + it "should reject '#{value}'" do + expect { @exec[:refreshonly] = value }. + should raise_error(Puppet::Error, + /Invalid value #{value.inspect}\. Valid values are true, false/ + ) + end + end end + describe "when setting creates" do + it_should_behave_like "all path parameters", :creates, :array => true do + def instance(path) + Puppet::Type.type(:exec).new(:name => '/bin/true', :creates => path) + end + end + end end - describe "when logoutput=>on_failure is set" do + describe "when setting unless" do + it_should_behave_like "all exec command parameters", :unless + it_should_behave_like "all exec command parameters that take arrays", :unless + end - it "should log the output on failure" do - #Puppet::Util::Log.newdestination :console - command = "false" - output = "output1\noutput2\n" - create_logging_resource(command, output, 1, :on_failure, :err) - expect_output(output, :err) + describe "when setting onlyif" do + it_should_behave_like "all exec command parameters", :onlyif + it_should_behave_like "all exec command parameters that take arrays", :onlyif + end - proc { @execer.refresh }.should raise_error(Puppet::Error) + describe "#check" do + before :each do + @test = Puppet::Type.type(:exec).new(:name => "/bin/true") end - it "should log the output on failure when returns is specified as an array" do - #Puppet::Util::Log.newdestination :console - command = "false" - output = "output1\noutput2\n" - create_logging_resource(command, output, 1, :on_failure, :err, [0, 100]) - expect_output(output, :err) + describe ":refreshonly" do + { :true => false, :false => true }.each do |input, result| + it "should return '#{result}' when given '#{input}'" do + @test[:refreshonly] = input + @test.check_all_attributes.should == result + end + end + end + + describe ":creates" do + before :all do + @exist = "/" + @unexist = "/this/path/should/never/exist" + while FileTest.exist?(@unexist) do @unexist += "/foo" end + end + + context "with a single item" do + it "should run when the item does not exist" do + @test[:creates] = @unexist + @test.check_all_attributes.should == true + end - proc { @execer.refresh }.should raise_error(Puppet::Error) + it "should not run when the item exists" do + @test[:creates] = @exist + @test.check_all_attributes.should == false + end + end + + context "with an array with one item" do + it "should run when the item does not exist" do + @test[:creates] = [@unexist] + @test.check_all_attributes.should == true + end + + it "should not run when the item exists" do + @test[:creates] = [@exist] + @test.check_all_attributes.should == false + end + end + + context "with an array with multiple items" do + it "should run when all items do not exist" do + @test[:creates] = [@unexist] * 3 + @test.check_all_attributes.should == true + end + + it "should not run when one item exists" do + @test[:creates] = [@unexist, @exist, @unexist] + @test.check_all_attributes.should == false + end + + it "should not run when all items exist" do + @test[:creates] = [@exist] * 3 + end + end end - it "shouldn't log the output on success" do - #Puppet::Util::Log.newdestination :console - command = "true" - output = "output1\noutput2\n" - create_logging_resource(command, output, 0, :on_failure, :err) - @execer.property(:returns).expects(:err).never - @execer.refresh + { :onlyif => { :pass => false, :fail => true }, + :unless => { :pass => true, :fail => false }, + }.each do |param, sense| + describe ":#{param}" do + before :each do + @pass = "/magic/pass" + @fail = "/magic/fail" + + @pass_status = stub('status', :exitstatus => sense[:pass] ? 0 : 1) + @fail_status = stub('status', :exitstatus => sense[:fail] ? 0 : 1) + + @test.provider.stubs(:checkexe).returns(true) + [true, false].each do |check| + @test.provider.stubs(:run).with(@pass, check). + returns(['test output', @pass_status]) + @test.provider.stubs(:run).with(@fail, check). + returns(['test output', @fail_status]) + end + end + + context "with a single item" do + it "should run if the command exits non-zero" do + @test[param] = @fail + @test.check_all_attributes.should == true + end + + it "should not run if the command exits zero" do + @test[param] = @pass + @test.check_all_attributes.should == false + end + end + + context "with an array with a single item" do + it "should run if the command exits non-zero" do + @test[param] = [@fail] + @test.check_all_attributes.should == true + end + + it "should not run if the command exits zero" do + @test[param] = [@pass] + @test.check_all_attributes.should == false + end + end + + context "with an array with multiple items" do + it "should run if all the commands exits non-zero" do + @test[param] = [@fail] * 3 + @test.check_all_attributes.should == true + end + + it "should not run if one command exits zero" do + @test[param] = [@pass, @fail, @pass] + @test.check_all_attributes.should == false + end + + it "should not run if all command exits zero" do + @test[param] = [@pass] * 3 + @test.check_all_attributes.should == false + end + end + end end end - it "shouldn't log the output on success when non-zero exit status is in a returns array" do - #Puppet::Util::Log.newdestination :console - command = "true" - output = "output1\noutput2\n" - create_logging_resource(command, output, 100, :on_failure, :err, [1,100]) - @execer.property(:returns).expects(:err).never - @execer.refresh + describe "#retrieve" do + before :each do + @exec_resource = Puppet::Type.type(:exec).new(:name => "/bogus/cmd") + end + + it "should return :notrun when check_all_attributes returns true" do + @exec_resource.stubs(:check_all_attributes).returns true + @exec_resource.retrieve[:returns].should == :notrun + end + + it "should return default exit code 0 when check_all_attributes returns false" do + @exec_resource.stubs(:check_all_attributes).returns false + @exec_resource.retrieve[:returns].should == ['0'] + end + + it "should return the specified exit code when check_all_attributes returns false" do + @exec_resource.stubs(:check_all_attributes).returns false + @exec_resource[:returns] = 42 + @exec_resource.retrieve[:returns].should == ["42"] + end end - describe " when multiple tries are set," do + describe "#output" do + before :each do + @exec_resource = Puppet::Type.type(:exec).new(:name => "/bogus/cmd") + end + + it "should return the provider's run output" do + provider = stub 'provider' + status = stubs "process_status" + status.stubs(:exitstatus).returns("0") + provider.expects(:run).returns(["silly output", status]) + @exec_resource.stubs(:provider).returns(provider) - it "should repeat the command attempt 'tries' times on failure and produce an error" do - Puppet.features.stubs(:root?).returns(true) - command = "false" - user = "user" - group = "group" - tries = 5 - retry_exec = Puppet::Type.type(:exec).new(:name => command, :path => %w{/usr/bin /bin}, :user => user, :group => group, :returns => 0, :tries => tries, :try_sleep => 0) - status = stub "process" - status.stubs(:exitstatus).returns(1) - Puppet::Util::SUIDManager.expects(:run_and_capture).with([command], user, group).times(tries).returns(["", status]) - proc { retry_exec.refresh }.should raise_error(Puppet::Error) + @exec_resource.refresh + @exec_resource.output.should == 'silly output' end end - it "should be able to autorequire files mentioned in the command" do - catalog = Puppet::Resource::Catalog.new - catalog.add_resource Puppet::Type.type(:file).new(:name => @executable) - @execer = Puppet::Type.type(:exec).new(:name => @command) - catalog.add_resource @execer + describe "#refresh" do + before :each do + @exec_resource = Puppet::Type.type(:exec).new(:name => "/bogus/cmd") + end + + it "should call provider run with the refresh parameter if it is set" do + provider = stub 'provider' + @exec_resource.stubs(:provider).returns(provider) + @exec_resource.stubs(:[]).with(:refresh).returns('/myother/bogus/cmd') + provider.expects(:run).with('/myother/bogus/cmd') - rels = @execer.autorequire - rels[0].should be_instance_of(Puppet::Relationship) - rels[0].target.should equal(@execer) + @exec_resource.refresh + end + + it "should call provider run with the specified command if the refresh parameter is not set" do + provider = stub 'provider' + status = stubs "process_status" + status.stubs(:exitstatus).returns("0") + provider.expects(:run).with('/bogus/cmd').returns(["silly output", status]) + @exec_resource.stubs(:provider).returns(provider) + + @exec_resource.refresh + end + + it "should not run the provider if check_all_attributes is false" do + @exec_resource.stubs(:check_all_attributes).returns false + provider = stub 'provider' + provider.expects(:run).never + @exec_resource.stubs(:provider).returns(provider) + + @exec_resource.refresh + end end end diff --git a/spec/unit/type/file/checksum_spec.rb b/spec/unit/type/file/checksum_spec.rb index 8b9138b78..16e8e99e1 100644 --- a/spec/unit/type/file/checksum_spec.rb +++ b/spec/unit/type/file/checksum_spec.rb @@ -1,73 +1,73 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') checksum = Puppet::Type.type(:file).attrclass(:checksum) describe checksum do before do @resource = Puppet::Type.type(:file).new :path => "/foo/bar" @checksum = @resource.parameter(:checksum) end it "should be a parameter" do checksum.superclass.must == Puppet::Parameter end it "should use its current value when asked to sum content" do @checksum.value = :md5lite @checksum.expects(:md5lite).with("foobar").returns "yay" @checksum.sum("foobar") end it "should use :md5 to sum when no value is set" do @checksum.expects(:md5).with("foobar").returns "yay" @checksum.sum("foobar") end it "should return the summed contents with a checksum label" do sum = Digest::MD5.hexdigest("foobar") @resource[:checksum] = :md5 @checksum.sum("foobar").should == "{md5}#{sum}" end it "should use :md5 as its default type" do @checksum.default.should == :md5 end it "should use its current value when asked to sum a file's content" do @checksum.value = :md5lite @checksum.expects(:md5lite_file).with("/foo/bar").returns "yay" @checksum.sum_file("/foo/bar") end it "should use :md5 to sum a file when no value is set" do @checksum.expects(:md5_file).with("/foo/bar").returns "yay" @checksum.sum_file("/foo/bar") end it "should convert all sums to strings when summing files" do @checksum.value = :mtime @checksum.expects(:mtime_file).with("/foo/bar").returns Time.now lambda { @checksum.sum_file("/foo/bar") }.should_not raise_error end it "should return the summed contents of a file with a checksum label" do @resource[:checksum] = :md5 @checksum.expects(:md5_file).returns "mysum" @checksum.sum_file("/foo/bar").should == "{md5}mysum" end it "should return the summed contents of a stream with a checksum label" do @resource[:checksum] = :md5 @checksum.expects(:md5_stream).returns "mysum" @checksum.sum_stream.should == "{md5}mysum" end it "should yield the sum_stream block to the underlying checksum" do @resource[:checksum] = :md5 @checksum.expects(:md5_stream).yields("something").returns("mysum") @checksum.sum_stream do |sum| sum.should == "something" end end end diff --git a/spec/unit/type/file/content_spec.rb b/spec/unit/type/file/content_spec.rb index bd2b2adaf..7abc7c433 100755 --- a/spec/unit/type/file/content_spec.rb +++ b/spec/unit/type/file/content_spec.rb @@ -1,436 +1,436 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') content = Puppet::Type.type(:file).attrclass(:content) describe content do include PuppetSpec::Files before do @filename = tmpfile('testfile') @resource = Puppet::Type.type(:file).new :path => @filename File.open(@filename, 'w') {|f| f.write "initial file content"} content.stubs(:standalone?).returns(false) end describe "when determining the checksum type" do it "should use the type specified in the source checksum if a source is set" do @resource[:source] = "/foo" @resource.parameter(:source).expects(:checksum).returns "{md5lite}eh" @content = content.new(:resource => @resource) @content.checksum_type.should == :md5lite end it "should use the type specified by the checksum parameter if no source is set" do @resource[:checksum] = :md5lite @content = content.new(:resource => @resource) @content.checksum_type.should == :md5lite end end describe "when determining the actual content to write" do it "should use the set content if available" do @content = content.new(:resource => @resource) @content.should = "ehness" @content.actual_content.should == "ehness" end it "should not use the content from the source if the source is set" do source = mock 'source' @resource.expects(:parameter).never.with(:source).returns source @content = content.new(:resource => @resource) @content.actual_content.should be_nil end end describe "when setting the desired content" do it "should make the actual content available via an attribute" do @content = content.new(:resource => @resource) @content.stubs(:checksum_type).returns "md5" @content.should = "this is some content" @content.actual_content.should == "this is some content" end it "should store the checksum as the desired content" do @content = content.new(:resource => @resource) digest = Digest::MD5.hexdigest("this is some content") @content.stubs(:checksum_type).returns "md5" @content.should = "this is some content" @content.should.must == "{md5}#{digest}" end it "should not checksum 'absent'" do @content = content.new(:resource => @resource) @content.should = :absent @content.should.must == :absent end it "should accept a checksum as the desired content" do @content = content.new(:resource => @resource) digest = Digest::MD5.hexdigest("this is some content") string = "{md5}#{digest}" @content.should = string @content.should.must == string end end describe "when retrieving the current content" do it "should return :absent if the file does not exist" do @content = content.new(:resource => @resource) @resource.expects(:stat).returns nil @content.retrieve.should == :absent end it "should not manage content on directories" do @content = content.new(:resource => @resource) stat = mock 'stat', :ftype => "directory" @resource.expects(:stat).returns stat @content.retrieve.should be_nil end it "should not manage content on links" do @content = content.new(:resource => @resource) stat = mock 'stat', :ftype => "link" @resource.expects(:stat).returns stat @content.retrieve.should be_nil end it "should always return the checksum as a string" do @content = content.new(:resource => @resource) @resource[:checksum] = :mtime stat = mock 'stat', :ftype => "file" @resource.expects(:stat).returns stat time = Time.now @resource.parameter(:checksum).expects(:mtime_file).with(@resource[:path]).returns time @content.retrieve.should == "{mtime}#{time}" end it "should return the checksum of the file if it exists and is a normal file" do @content = content.new(:resource => @resource) stat = mock 'stat', :ftype => "file" @resource.expects(:stat).returns stat @resource.parameter(:checksum).expects(:md5_file).with(@resource[:path]).returns "mysum" @content.retrieve.should == "{md5}mysum" end end describe "when testing whether the content is in sync" do before do @resource[:ensure] = :file @content = content.new(:resource => @resource) end it "should return true if the resource shouldn't be a regular file" do @resource.expects(:should_be_file?).returns false @content.should = "foo" @content.must be_safe_insync("whatever") end it "should return false if the current content is :absent" do @content.should = "foo" @content.should_not be_safe_insync(:absent) end it "should return false if the file should be a file but is not present" do @resource.expects(:should_be_file?).returns true @content.should = "foo" @content.should_not be_safe_insync(:absent) end describe "and the file exists" do before do @resource.stubs(:stat).returns mock("stat") end it "should return false if the current contents are different from the desired content" do @content.should = "some content" @content.should_not be_safe_insync("other content") end it "should return true if the sum for the current contents is the same as the sum for the desired content" do @content.should = "some content" @content.must be_safe_insync("{md5}" + Digest::MD5.hexdigest("some content")) end describe "and Puppet[:show_diff] is set" do before do Puppet[:show_diff] = true end it "should display a diff if the current contents are different from the desired content" do @content.should = "some content" @content.expects(:diff).returns("my diff").once @content.expects(:print).with("my diff").once @content.safe_insync?("other content") end it "should not display a diff if the sum for the current contents is the same as the sum for the desired content" do @content.should = "some content" @content.expects(:diff).never @content.safe_insync?("{md5}" + Digest::MD5.hexdigest("some content")) end end end describe "and :replace is false" do before do @resource.stubs(:replace?).returns false end it "should be insync if the file exists and the content is different" do @resource.stubs(:stat).returns mock('stat') @content.must be_safe_insync("whatever") end it "should be insync if the file exists and the content is right" do @resource.stubs(:stat).returns mock('stat') @content.must be_safe_insync("something") end it "should not be insync if the file does not exist" do @content.should = "foo" @content.should_not be_safe_insync(:absent) end end end describe "when changing the content" do before do @content = content.new(:resource => @resource) @content.should = "some content" @resource.stubs(:[]).with(:path).returns "/boo" @resource.stubs(:stat).returns "eh" end it "should use the file's :write method to write the content" do @resource.expects(:write).with(:content) @content.sync end it "should return :file_changed if the file already existed" do @resource.expects(:stat).returns "something" @resource.stubs(:write) @content.sync.should == :file_changed end it "should return :file_created if the file did not exist" do @resource.expects(:stat).returns nil @resource.stubs(:write) @content.sync.should == :file_created end end describe "when writing" do before do @content = content.new(:resource => @resource) end it "should attempt to read from the filebucket if no actual content nor source exists" do @fh = File.open(@filename, 'w') @content.should = "{md5}foo" @content.resource.bucket.class.any_instance.stubs(:getfile).returns "foo" @content.write(@fh) end describe "from actual content" do before(:each) do @content.stubs(:actual_content).returns("this is content") end it "should write to the given file handle" do @fh.expects(:print).with("this is content") @content.write(@fh) end it "should return the current checksum value" do @resource.parameter(:checksum).expects(:sum_stream).returns "checksum" @content.write(@fh).should == "checksum" end end describe "from a file bucket" do it "should fail if a file bucket cannot be retrieved" do @content.should = "{md5}foo" @content.resource.expects(:bucket).returns nil lambda { @content.write(@fh) }.should raise_error(Puppet::Error) end it "should fail if the file bucket cannot find any content" do @content.should = "{md5}foo" bucket = stub 'bucket' @content.resource.expects(:bucket).returns bucket bucket.expects(:getfile).with("foo").raises "foobar" lambda { @content.write(@fh) }.should raise_error(Puppet::Error) end it "should write the returned content to the file" do @content.should = "{md5}foo" bucket = stub 'bucket' @content.resource.expects(:bucket).returns bucket bucket.expects(:getfile).with("foo").returns "mycontent" @fh.expects(:print).with("mycontent") @content.write(@fh) end end describe "from local source" do before(:each) do @resource = Puppet::Type.type(:file).new :path => @filename, :backup => false @sourcename = tmpfile('source') @source_content = "source file content"*10000 @sourcefile = File.open(@sourcename, 'w') {|f| f.write @source_content} @content = @resource.newattr(:content) @source = @resource.newattr(:source) @source.stubs(:metadata).returns stub_everything('metadata', :source => @sourcename, :ftype => 'file') end it "should copy content from the source to the file" do @resource.write(@source) File.read(@filename).should == @source_content end it "should return the checksum computed" do File.open(@filename, 'w') do |file| @content.write(file).should == "{md5}#{Digest::MD5.hexdigest(@source_content)}" end end end describe "from remote source" do before(:each) do @resource = Puppet::Type.type(:file).new :path => @filename, :backup => false @response = stub_everything 'response', :code => "200" @source_content = "source file content"*10000 @response.stubs(:read_body).multiple_yields(*(["source file content"]*10000)) @conn = stub_everything 'connection' @conn.stubs(:request_get).yields(@response) Puppet::Network::HttpPool.stubs(:http_instance).returns @conn @content = @resource.newattr(:content) @sourcename = "puppet:///test/foo" @source = @resource.newattr(:source) @source.stubs(:metadata).returns stub_everything('metadata', :source => @sourcename, :ftype => 'file') end it "should write the contents to the file" do @resource.write(@source) File.read(@filename).should == @source_content end it "should not write anything if source is not found" do @response.stubs(:code).returns("404") lambda {@resource.write(@source)}.should raise_error(Net::HTTPError) { |e| e.message =~ /404/ } File.read(@filename).should == "initial file content" end it "should raise an HTTP error in case of server error" do @response.stubs(:code).returns("500") lambda { @content.write(@fh) }.should raise_error { |e| e.message.include? @source_content } end it "should return the checksum computed" do File.open(@filename, 'w') do |file| @content.write(file).should == "{md5}#{Digest::MD5.hexdigest(@source_content)}" end end end # These are testing the implementation rather than the desired behaviour; while that bites, there are a whole # pile of other methods in the File type that depend on intimate details of this implementation and vice-versa. # If these blow up, you are gonna have to review the callers to make sure they don't explode! --daniel 2011-02-01 describe "each_chunk_from should work" do before do @content = content.new(:resource => @resource) end it "when content is a string" do @content.each_chunk_from('i_am_a_string') { |chunk| chunk.should == 'i_am_a_string' } end # The following manifest is a case where source and content.should are both set # file { "/tmp/mydir" : # source => '/tmp/sourcedir', # recurse => true, # } it "when content checksum comes from source" do source_param = Puppet::Type.type(:file).attrclass(:source) source = source_param.new(:resource => @resource) @content.should = "{md5}123abcd" @content.expects(:chunk_file_from_source).returns('from_source') @content.each_chunk_from(source) { |chunk| chunk.should == 'from_source' } end it "when no content, source, but ensure present" do @resource[:ensure] = :present @content.each_chunk_from(nil) { |chunk| chunk.should == '' } end # you might do this if you were just auditing it "when no content, source, but ensure file" do @resource[:ensure] = :file @content.each_chunk_from(nil) { |chunk| chunk.should == '' } end it "when source_or_content is nil and content not a checksum" do @content.each_chunk_from(nil) { |chunk| chunk.should == '' } end # the content is munged so that if it's a checksum nil gets passed in it "when content is a checksum it should try to read from filebucket" do @content.should = "{md5}123abcd" @content.expects(:read_file_from_filebucket).once.returns('im_a_filebucket') @content.each_chunk_from(nil) { |chunk| chunk.should == 'im_a_filebucket' } end it "when running as puppet apply" do @content.class.expects(:standalone?).returns true source_or_content = stubs('source_or_content') source_or_content.expects(:content).once.returns :whoo @content.each_chunk_from(source_or_content) { |chunk| chunk.should == :whoo } end it "when running from source with a local file" do source_or_content = stubs('source_or_content') source_or_content.expects(:local?).returns true @content.expects(:chunk_file_from_disk).with(source_or_content).once.yields 'woot' @content.each_chunk_from(source_or_content) { |chunk| chunk.should == 'woot' } end it "when running from source with a remote file" do source_or_content = stubs('source_or_content') source_or_content.expects(:local?).returns false @content.expects(:chunk_file_from_source).with(source_or_content).once.yields 'woot' @content.each_chunk_from(source_or_content) { |chunk| chunk.should == 'woot' } end end end end diff --git a/spec/unit/type/file/ctime.rb b/spec/unit/type/file/ctime.rb index 6145cbfdc..9fb892aed 100644 --- a/spec/unit/type/file/ctime.rb +++ b/spec/unit/type/file/ctime.rb @@ -1,35 +1,35 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe Puppet::Type.type(:file).attrclass(:ctime) do require 'puppet_spec/files' include PuppetSpec::Files before do @filename = tmpfile('ctime') @resource = Puppet::Type.type(:file).new({:name => @filename}) end it "should be able to audit the file's ctime" do File.open(@filename, "w"){ } @resource[:audit] = [:ctime] # this .to_resource audit behavior is magical :-( @resource.to_resource[:ctime].should == File.stat(@filename).ctime end it "should return absent if auditing an absent file" do @resource[:audit] = [:ctime] @resource.to_resource[:ctime].should == :absent end it "should prevent the user from trying to set the ctime" do lambda { @resource[:ctime] = Time.now.to_s }.should raise_error(Puppet::Error, /ctime is read-only/) end end diff --git a/spec/unit/type/file/ensure_spec.rb b/spec/unit/type/file/ensure_spec.rb index dbb3a1053..c5351309e 100755 --- a/spec/unit/type/file/ensure_spec.rb +++ b/spec/unit/type/file/ensure_spec.rb @@ -1,85 +1,85 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') property = Puppet::Type.type(:file).attrclass(:ensure) describe property do before do # Wow that's a messy interface to the resource. @resource = stub 'resource', :[] => nil, :[]= => nil, :property => nil, :newattr => nil, :parameter => nil, :replace? => true @resource.stubs(:[]).returns "foo" @resource.stubs(:[]).with(:path).returns "/my/file" @ensure = property.new :resource => @resource end it "should be a subclass of Ensure" do property.superclass.must == Puppet::Property::Ensure end describe "when retrieving the current state" do it "should return :absent if the file does not exist" do @ensure = property.new(:resource => @resource) @resource.expects(:stat).returns nil @ensure.retrieve.should == :absent end it "should return the current file type if the file exists" do @ensure = property.new(:resource => @resource) stat = mock 'stat', :ftype => "directory" @resource.expects(:stat).returns stat @ensure.retrieve.should == :directory end end describe "when testing whether :ensure is in sync" do before do @ensure = property.new(:resource => @resource) @stat = stub 'stat', :ftype => "file" end it "should always be in sync if replace is 'false' unless the file is missing" do @ensure.should = :file @resource.expects(:replace?).returns false @ensure.safe_insync?(:link).should be_true end it "should be in sync if :ensure is set to :absent and the file does not exist" do @ensure.should = :absent @ensure.must be_safe_insync(:absent) end it "should not be in sync if :ensure is set to :absent and the file exists" do @ensure.should = :absent @ensure.should_not be_safe_insync(:file) end it "should be in sync if a normal file exists and :ensure is set to :present" do @ensure.should = :present @ensure.must be_safe_insync(:file) end it "should be in sync if a directory exists and :ensure is set to :present" do @ensure.should = :present @ensure.must be_safe_insync(:directory) end it "should be in sync if a symlink exists and :ensure is set to :present" do @ensure.should = :present @ensure.must be_safe_insync(:link) end it "should not be in sync if :ensure is set to :file and a directory exists" do @ensure.should = :file @ensure.should_not be_safe_insync(:directory) end end end diff --git a/spec/unit/type/file/group_spec.rb b/spec/unit/type/file/group_spec.rb index 956cd57e7..37a6872bd 100755 --- a/spec/unit/type/file/group_spec.rb +++ b/spec/unit/type/file/group_spec.rb @@ -1,123 +1,123 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') property = Puppet::Type.type(:file).attrclass(:group) describe property do before do @resource = stub 'resource', :line => "foo", :file => "bar" @resource.stubs(:[]).returns "foo" @resource.stubs(:[]).with(:path).returns "/my/file" @group = property.new :resource => @resource end it "should have a method for testing whether a group is valid" do @group.must respond_to(:validgroup?) end it "should return the found gid if a group is valid" do @group.expects(:gid).with("foo").returns 500 @group.validgroup?("foo").should == 500 end it "should return false if a group is not valid" do @group.expects(:gid).with("foo").returns nil @group.validgroup?("foo").should be_false end describe "when retrieving the current value" do it "should return :absent if the file cannot stat" do @resource.expects(:stat).returns nil @group.retrieve.should == :absent end it "should get the gid from the stat instance from the file" do stat = stub 'stat', :ftype => "foo" @resource.expects(:stat).returns stat stat.expects(:gid).returns 500 @group.retrieve.should == 500 end it "should warn and return :silly if the found value is higher than the maximum uid value" do Puppet.settings.expects(:value).with(:maximum_uid).returns 500 stat = stub 'stat', :ftype => "foo" @resource.expects(:stat).returns stat stat.expects(:gid).returns 1000 @group.expects(:warning) @group.retrieve.should == :silly end end describe "when determining if the file is in sync" do it "should directly compare the group values if the desired group is an integer" do @group.should = [10] @group.must be_safe_insync(10) end it "should treat numeric strings as integers" do @group.should = ["10"] @group.must be_safe_insync(10) end it "should convert the group name to an integer if the desired group is a string" do @group.expects(:gid).with("foo").returns 10 @group.should = %w{foo} @group.must be_safe_insync(10) end it "should not validate that groups exist when a group is specified as an integer" do @group.expects(:gid).never @group.validgroup?(10) end it "should fail if it cannot convert a group name to an integer" do @group.expects(:gid).with("foo").returns nil @group.should = %w{foo} lambda { @group.safe_insync?(10) }.should raise_error(Puppet::Error) end it "should return false if the groups are not equal" do @group.should = [10] @group.should_not be_safe_insync(20) end end describe "when changing the group" do before do @group.should = %w{one} @group.stubs(:gid).returns 500 end it "should chown the file if :links is set to :follow" do @resource.expects(:[]).with(:links).returns :follow File.expects(:chown) @group.sync end it "should lchown the file if :links is set to :manage" do @resource.expects(:[]).with(:links).returns :manage File.expects(:lchown) @group.sync end it "should use the first valid group in its 'should' list" do @group.should = %w{one two three} @group.expects(:validgroup?).with("one").returns nil @group.expects(:validgroup?).with("two").returns 500 @group.expects(:validgroup?).with("three").never File.expects(:chown).with(nil, 500, "/my/file") @group.sync end end end diff --git a/spec/unit/type/file/mtime.rb b/spec/unit/type/file/mtime.rb index 043156ceb..fa61bc343 100644 --- a/spec/unit/type/file/mtime.rb +++ b/spec/unit/type/file/mtime.rb @@ -1,35 +1,35 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe Puppet::Type.type(:file).attrclass(:mtime) do require 'puppet_spec/files' include PuppetSpec::Files before do @filename = tmpfile('mtime') @resource = Puppet::Type.type(:file).new({:name => @filename}) end it "should be able to audit the file's mtime" do File.open(@filename, "w"){ } @resource[:audit] = [:mtime] # this .to_resource audit behavior is magical :-( @resource.to_resource[:mtime].should == File.stat(@filename).mtime end it "should return absent if auditing an absent file" do @resource[:audit] = [:mtime] @resource.to_resource[:mtime].should == :absent end it "should prevent the user from trying to set the mtime" do lambda { @resource[:mtime] = Time.now.to_s }.should raise_error(Puppet::Error, /mtime is read-only/) end end diff --git a/spec/unit/type/file/owner_spec.rb b/spec/unit/type/file/owner_spec.rb index bcb8e07d6..375faa237 100755 --- a/spec/unit/type/file/owner_spec.rb +++ b/spec/unit/type/file/owner_spec.rb @@ -1,150 +1,150 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') property = Puppet::Type.type(:file).attrclass(:owner) describe property do before do # FIXME: many of these tests exercise the provider rather than `owner` # and should be moved into provider tests. ~JW @provider = Puppet::Type.type(:file).provider(:posix).new @provider.stubs(:uid).with("one").returns(1) @resource = stub 'resource', :line => "foo", :file => "bar" @resource.stubs(:[]).returns "foo" @resource.stubs(:[]).with(:path).returns "/my/file" @resource.stubs(:provider).returns @provider @owner = property.new :resource => @resource end it "should have a method for testing whether an owner is valid" do @provider.must respond_to(:validuser?) end it "should return the found uid if an owner is valid" do @provider.expects(:uid).with("foo").returns 500 @provider.validuser?("foo").should == 500 end it "should return false if an owner is not valid" do @provider.expects(:uid).with("foo").returns nil @provider.validuser?("foo").should be_false end describe "when retrieving the current value" do it "should return :absent if the file cannot stat" do @resource.expects(:stat).returns nil @owner.retrieve.should == :absent end it "should get the uid from the stat instance from the file" do stat = stub 'stat', :ftype => "foo" @resource.expects(:stat).returns stat stat.expects(:uid).returns 500 @owner.retrieve.should == 500 end it "should warn and return :silly if the found value is higher than the maximum uid value" do Puppet.settings.expects(:value).with(:maximum_uid).returns 500 stat = stub 'stat', :ftype => "foo" @resource.expects(:stat).returns stat stat.expects(:uid).returns 1000 @provider.expects(:warning) @owner.retrieve.should == :silly end end describe "when determining if the file is in sync" do describe "and not running as root" do it "should warn once and return true" do Puppet.features.expects(:root?).returns false @provider.expects(:warnonce) @owner.should = [10] @owner.must be_safe_insync(20) end end before do Puppet.features.stubs(:root?).returns true end it "should be in sync if 'should' is not provided" do @owner.must be_safe_insync(10) end it "should directly compare the owner values if the desired owner is an integer" do @owner.should = [10] @owner.must be_safe_insync(10) end it "should treat numeric strings as integers" do @owner.should = ["10"] @owner.must be_safe_insync(10) end it "should convert the owner name to an integer if the desired owner is a string" do @provider.expects(:uid).with("foo").returns 10 @owner.should = %w{foo} @owner.must be_safe_insync(10) end it "should not validate that users exist when a user is specified as an integer" do @provider.expects(:uid).never @provider.validuser?(10) end it "should fail if it cannot convert an owner name to an integer" do @provider.expects(:uid).with("foo").returns nil @owner.should = %w{foo} lambda { @owner.safe_insync?(10) }.should raise_error(Puppet::Error) end it "should return false if the owners are not equal" do @owner.should = [10] @owner.should_not be_safe_insync(20) end end describe "when changing the owner" do before do @owner.should = %w{one} @owner.stubs(:path).returns "path" @owner.stubs(:uid).returns 500 end it "should chown the file if :links is set to :follow" do @resource.expects(:[]).with(:links).returns :follow File.expects(:chown) @owner.sync end it "should lchown the file if :links is set to :manage" do @resource.expects(:[]).with(:links).returns :manage File.expects(:lchown) @owner.sync end it "should use the first valid owner in its 'should' list" do @owner.should = %w{one two three} @provider.expects(:validuser?).with("one").returns nil @provider.expects(:validuser?).with("two").returns 500 @provider.expects(:validuser?).with("three").never File.expects(:chown).with(500, nil, "/my/file") @owner.sync end end end diff --git a/spec/unit/type/file/selinux_spec.rb b/spec/unit/type/file/selinux_spec.rb index a2444acd9..45e8b3b14 100644 --- a/spec/unit/type/file/selinux_spec.rb +++ b/spec/unit/type/file/selinux_spec.rb @@ -1,88 +1,88 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') [:seluser, :selrole, :seltype, :selrange].each do |param| property = Puppet::Type.type(:file).attrclass(param) describe property do before do @resource = Puppet::Type.type(:file).new :path => "/my/file" @sel = property.new :resource => @resource end it "retrieve on #{param} should return :absent if the file isn't statable" do @resource.expects(:stat).returns nil @sel.retrieve.should == :absent end it "should retrieve nil for #{param} if there is no SELinux support" do stat = stub 'stat', :ftype => "foo" @resource.expects(:stat).returns stat @sel.expects(:get_selinux_current_context).with("/my/file").returns nil @sel.retrieve.should be_nil end it "should retrieve #{param} if a SELinux context is found with a range" do stat = stub 'stat', :ftype => "foo" @resource.expects(:stat).returns stat @sel.expects(:get_selinux_current_context).with("/my/file").returns "user_u:role_r:type_t:s0" expectedresult = case param when :seluser; "user_u" when :selrole; "role_r" when :seltype; "type_t" when :selrange; "s0" end @sel.retrieve.should == expectedresult end it "should retrieve #{param} if a SELinux context is found without a range" do stat = stub 'stat', :ftype => "foo" @resource.expects(:stat).returns stat @sel.expects(:get_selinux_current_context).with("/my/file").returns "user_u:role_r:type_t" expectedresult = case param when :seluser; "user_u" when :selrole; "role_r" when :seltype; "type_t" when :selrange; nil end @sel.retrieve.should == expectedresult end it "should handle no default gracefully" do @sel.expects(:get_selinux_default_context).with("/my/file").returns nil @sel.default.must be_nil end it "should be able to detect matchpathcon defaults" do @sel.stubs(:debug) @sel.expects(:get_selinux_default_context).with("/my/file").returns "user_u:role_r:type_t:s0" expectedresult = case param when :seluser; "user_u" when :selrole; "role_r" when :seltype; "type_t" when :selrange; "s0" end @sel.default.must == expectedresult end it "should return nil for defaults if selinux_ignore_defaults is true" do @resource[:selinux_ignore_defaults] = :true @sel.default.must be_nil end it "should be able to set a new context" do stat = stub 'stat', :ftype => "foo" @sel.should = %w{newone} @sel.expects(:set_selinux_context).with("/my/file", ["newone"], param) @sel.sync end it "should do nothing for safe_insync? if no SELinux support" do @sel.should = %{newcontext} @sel.expects(:selinux_support?).returns false @sel.safe_insync?("oldcontext").should == true end end end diff --git a/spec/unit/type/file/source_spec.rb b/spec/unit/type/file/source_spec.rb index c07963a50..bb83e7531 100755 --- a/spec/unit/type/file/source_spec.rb +++ b/spec/unit/type/file/source_spec.rb @@ -1,272 +1,272 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') source = Puppet::Type.type(:file).attrclass(:source) describe Puppet::Type.type(:file).attrclass(:source) do before do # Wow that's a messy interface to the resource. @resource = stub 'resource', :[]= => nil, :property => nil, :catalog => stub("catalog", :dependent_data_expired? => false), :line => 0, :file => '' end it "should be a subclass of Parameter" do source.superclass.must == Puppet::Parameter end describe "when initializing" do it "should fail if the set values are not URLs" do s = source.new(:resource => @resource) URI.expects(:parse).with('foo').raises RuntimeError lambda { s.value = %w{foo} }.must raise_error(Puppet::Error) end it "should fail if the URI is not a local file, file URI, or puppet URI" do s = source.new(:resource => @resource) lambda { s.value = %w{http://foo/bar} }.must raise_error(Puppet::Error) end end it "should have a method for retrieving its metadata" do source.new(:resource => @resource).must respond_to(:metadata) end it "should have a method for setting its metadata" do source.new(:resource => @resource).must respond_to(:metadata=) end describe "when returning the metadata" do before do @metadata = stub 'metadata', :source= => nil end it "should return already-available metadata" do @source = source.new(:resource => @resource) @source.metadata = "foo" @source.metadata.should == "foo" end it "should return nil if no @should value is set and no metadata is available" do @source = source.new(:resource => @resource) @source.metadata.should be_nil end it "should collect its metadata using the Metadata class if it is not already set" do @source = source.new(:resource => @resource, :value => "/foo/bar") Puppet::FileServing::Metadata.indirection.expects(:find).with("/foo/bar").returns @metadata @source.metadata end it "should use the metadata from the first found source" do metadata = stub 'metadata', :source= => nil @source = source.new(:resource => @resource, :value => ["/foo/bar", "/fee/booz"]) Puppet::FileServing::Metadata.indirection.expects(:find).with("/foo/bar").returns nil Puppet::FileServing::Metadata.indirection.expects(:find).with("/fee/booz").returns metadata @source.metadata.should equal(metadata) end it "should store the found source as the metadata's source" do metadata = mock 'metadata' @source = source.new(:resource => @resource, :value => "/foo/bar") Puppet::FileServing::Metadata.indirection.expects(:find).with("/foo/bar").returns metadata metadata.expects(:source=).with("/foo/bar") @source.metadata end it "should fail intelligently if an exception is encountered while querying for metadata" do @source = source.new(:resource => @resource, :value => "/foo/bar") Puppet::FileServing::Metadata.indirection.expects(:find).with("/foo/bar").raises RuntimeError @source.expects(:fail).raises ArgumentError lambda { @source.metadata }.should raise_error(ArgumentError) end it "should fail if no specified sources can be found" do @source = source.new(:resource => @resource, :value => "/foo/bar") Puppet::FileServing::Metadata.indirection.expects(:find).with("/foo/bar").returns nil @source.expects(:fail).raises RuntimeError lambda { @source.metadata }.should raise_error(RuntimeError) end it "should expire the metadata appropriately" do expirer = stub 'expired', :dependent_data_expired? => true metadata = stub 'metadata', :source= => nil Puppet::FileServing::Metadata.indirection.expects(:find).with("/fee/booz").returns metadata @source = source.new(:resource => @resource, :value => ["/fee/booz"]) @source.metadata = "foo" @source.stubs(:expirer).returns expirer @source.metadata.should_not == "foo" end end it "should have a method for setting the desired values on the resource" do source.new(:resource => @resource).must respond_to(:copy_source_values) end describe "when copying the source values" do before do @resource = Puppet::Type.type(:file).new :path => "/foo/bar" @source = source.new(:resource => @resource) @metadata = stub 'metadata', :owner => 100, :group => 200, :mode => 123, :checksum => "{md5}asdfasdf", :ftype => "file" @source.stubs(:metadata).returns @metadata end it "should fail if there is no metadata" do @source.stubs(:metadata).returns nil @source.expects(:devfail).raises ArgumentError lambda { @source.copy_source_values }.should raise_error(ArgumentError) end it "should set :ensure to the file type" do @metadata.stubs(:ftype).returns "file" @source.copy_source_values @resource[:ensure].must == :file end it "should not set 'ensure' if it is already set to 'absent'" do @metadata.stubs(:ftype).returns "file" @resource[:ensure] = :absent @source.copy_source_values @resource[:ensure].must == :absent end describe "and the source is a file" do before do @metadata.stubs(:ftype).returns "file" end it "should copy the metadata's owner, group, checksum, and mode to the resource if they are not set on the resource" do Puppet.features.expects(:root?).returns true @source.copy_source_values @resource[:owner].must == 100 @resource[:group].must == 200 @resource[:mode].must == "173" # Metadata calls it checksum, we call it content. @resource[:content].must == @metadata.checksum end it "should not copy the metadata's owner to the resource if it is already set" do @resource[:owner] = 1 @resource[:group] = 2 @resource[:mode] = 3 @resource[:content] = "foobar" @source.copy_source_values @resource[:owner].must == 1 @resource[:group].must == 2 @resource[:mode].must == "3" @resource[:content].should_not == @metadata.checksum end describe "and puppet is not running as root" do it "should not try to set the owner" do Puppet.features.expects(:root?).returns false @source.copy_source_values @resource[:owner].should be_nil end end end describe "and the source is a link" do it "should set the target to the link destination" do @metadata.stubs(:ftype).returns "link" @resource.stubs(:[]) @resource.stubs(:[]=) @metadata.expects(:destination).returns "/path/to/symlink" @resource.expects(:[]=).with(:target, "/path/to/symlink") @source.copy_source_values end end end it "should have a local? method" do source.new(:resource => @resource).must be_respond_to(:local?) end context "when accessing source properties" do before(:each) do @source = source.new(:resource => @resource) @metadata = stub_everything @source.stubs(:metadata).returns(@metadata) end describe "for local sources" do before(:each) do @metadata.stubs(:ftype).returns "file" @metadata.stubs(:source).returns("file:///path/to/source") end it "should be local" do @source.must be_local end it "should be local if there is no scheme" do @metadata.stubs(:source).returns("/path/to/source") @source.must be_local end it "should be able to return the metadata source full path" do @source.full_path.should == "/path/to/source" end end describe "for remote sources" do before(:each) do @metadata.stubs(:ftype).returns "file" @metadata.stubs(:source).returns("puppet://server:8192/path/to/source") end it "should not be local" do @source.should_not be_local end it "should be able to return the metadata source full path" do @source.full_path.should == "/path/to/source" end it "should be able to return the source server" do @source.server.should == "server" end it "should be able to return the source port" do @source.port.should == 8192 end describe "which don't specify server or port" do before(:each) do @metadata.stubs(:source).returns("puppet:///path/to/source") end it "should return the default source server" do Puppet.settings.expects(:[]).with(:server).returns("myserver") @source.server.should == "myserver" end it "should return the default source port" do Puppet.settings.expects(:[]).with(:masterport).returns(1234) @source.port.should == 1234 end end end end end diff --git a/spec/unit/type/file/type.rb b/spec/unit/type/file/type.rb index e46f0e0b0..0d38b64cd 100644 --- a/spec/unit/type/file/type.rb +++ b/spec/unit/type/file/type.rb @@ -1,20 +1,20 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe Puppet::Type.type(:file).attrclass(:type) do require 'puppet_spec/files' include PuppetSpec::Files before do @filename = tmpfile('type') @resource = Puppet::Type.type(:file).new({:name => @filename}) end it "should prevent the user from trying to set the type" do lambda { @resource[:type] = "fifo" }.should raise_error(Puppet::Error, /type is read-only/) end end diff --git a/spec/unit/type/maillist_spec.rb b/spec/unit/type/maillist_spec.rb index 04acea7dd..7e96b4760 100755 --- a/spec/unit/type/maillist_spec.rb +++ b/spec/unit/type/maillist_spec.rb @@ -1,42 +1,42 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') maillist = Puppet::Type.type(:maillist) describe maillist do before do @provider_class = Puppet::Type.type(:maillist).provider(:mailman) @provider = stub 'provider', :class => @provider_class, :clear => nil @provider.stubs(:respond_to).with(:aliases).returns(true) @provider_class.stubs(:new).returns(@provider) Puppet::Type.type(:maillist).stubs(:defaultprovider).returns(@provider_class) @maillist = Puppet::Type.type(:maillist).new( :name => 'test' ) @catalog = Puppet::Resource::Catalog.new @maillist.catalog = @catalog end it "should generate aliases unless they already exist" do # Mail List aliases are careful not to stomp on managed Mail Alias aliases # test1 is an unmanaged alias from /etc/aliases Puppet::Type.type(:mailalias).provider(:aliases).stubs(:target_object).returns( StringIO.new("test1: root\n") ) # test2 is a managed alias from the manifest dupe = Puppet::Type.type(:mailalias).new( :name => 'test2' ) @catalog.add_resource dupe @provider.stubs(:aliases).returns({"test1" => 'this will get included', "test2" => 'this will dropped', "test3" => 'this will get included'}) generated = @maillist.generate generated.map{ |x| x.name }.sort.should == ['test1', 'test3'] generated.map{ |x| x.class }.should == [Puppet::Type::Mailalias, Puppet::Type::Mailalias] end end diff --git a/spec/unit/type/selboolean_spec.rb b/spec/unit/type/selboolean_spec.rb index 3b31f4306..41b254f25 100755 --- a/spec/unit/type/selboolean_spec.rb +++ b/spec/unit/type/selboolean_spec.rb @@ -1,45 +1,45 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Puppet::Type.type(:selboolean), "when validating attributes" do [:name, :persistent].each do |param| it "should have a #{param} parameter" do Puppet::Type.type(:selboolean).attrtype(param).should == :param end end it "should have a value property" do Puppet::Type.type(:selboolean).attrtype(:value).should == :property end end describe Puppet::Type.type(:selboolean), "when validating values" do before do @class = Puppet::Type.type(:selboolean) @provider_class = stub 'provider_class', :name => "fake", :suitable? => true, :supports_parameter? => true @class.stubs(:defaultprovider).returns(@provider_class) @class.stubs(:provider).returns(@provider_class) @provider = stub 'provider', :class => @provider_class, :clear => nil @provider_class.stubs(:new).returns(@provider) end it "should support :on as a value to :value" do Puppet::Type.type(:selboolean).new(:name => "yay", :value => :on) end it "should support :off as a value to :value" do Puppet::Type.type(:selboolean).new(:name => "yay", :value => :off) end it "should support :true as a value to :persistent" do Puppet::Type.type(:selboolean).new(:name => "yay", :value => :on, :persistent => :true) end it "should support :false as a value to :persistent" do Puppet::Type.type(:selboolean).new(:name => "yay", :value => :on, :persistent => :false) end end diff --git a/spec/unit/type/selmodule_spec.rb b/spec/unit/type/selmodule_spec.rb index 3d126256c..37453d8ed 100755 --- a/spec/unit/type/selmodule_spec.rb +++ b/spec/unit/type/selmodule_spec.rb @@ -1,18 +1,18 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Puppet::Type.type(:selmodule), "when validating attributes" do [:name, :selmoduledir, :selmodulepath].each do |param| it "should have a #{param} parameter" do Puppet::Type.type(:selmodule).attrtype(param).should == :param end end [:ensure, :syncversion].each do |param| it "should have a #{param} property" do Puppet::Type.type(:selmodule).attrtype(param).should == :property end end end diff --git a/spec/unit/type/zfs_spec.rb b/spec/unit/type/zfs_spec.rb index 6b0b17f3a..88193fca3 100755 --- a/spec/unit/type/zfs_spec.rb +++ b/spec/unit/type/zfs_spec.rb @@ -1,45 +1,45 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') zfs = Puppet::Type.type(:zfs) describe zfs do properties = [:ensure, :mountpoint, :compression, :copies, :quota, :reservation, :sharenfs, :snapdir] properties.each do |property| it "should have a #{property} property" do zfs.attrclass(property).ancestors.should be_include(Puppet::Property) end end parameters = [:name] parameters.each do |parameter| it "should have a #{parameter} parameter" do zfs.attrclass(parameter).ancestors.should be_include(Puppet::Parameter) end end it "should autorequire the containing zfss and the zpool" do provider = mock "provider" provider.stubs(:name).returns(:solaris) zfs.stubs(:defaultprovider).returns(provider) Puppet::Type.type(:zpool).stubs(:defaultprovider).returns(provider) foo_pool = Puppet::Type.type(:zpool).new(:name => "foo") foo_bar_zfs = Puppet::Type.type(:zfs).new(:name => "foo/bar") foo_bar_baz_zfs = Puppet::Type.type(:zfs).new(:name => "foo/bar/baz") foo_bar_baz_buz_zfs = Puppet::Type.type(:zfs).new(:name => "foo/bar/baz/buz") config = Puppet::Resource::Catalog.new :testing do |conf| [foo_pool, foo_bar_zfs, foo_bar_baz_zfs, foo_bar_baz_buz_zfs].each { |resource| conf.add_resource resource } end req = foo_bar_baz_buz_zfs.autorequire.collect { |edge| edge.source.ref } [foo_pool.ref, foo_bar_zfs.ref, foo_bar_baz_zfs.ref].each { |ref| req.include?(ref).should == true } end end diff --git a/spec/unit/type/zone_spec.rb b/spec/unit/type/zone_spec.rb index a3e748bde..e479fb1e9 100755 --- a/spec/unit/type/zone_spec.rb +++ b/spec/unit/type/zone_spec.rb @@ -1,80 +1,80 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') zone = Puppet::Type.type(:zone) describe zone do before do zone = Puppet::Type.type(:zone) provider = stub 'provider' provider.stubs(:name).returns(:solaris) zone.stubs(:defaultprovider).returns(provider) resource = stub 'resource', :resource => nil, :provider => provider, :line => nil, :file => nil end parameters = [:create_args, :install_args, :sysidcfg, :path, :realhostname] parameters.each do |parameter| it "should have a #{parameter} parameter" do zone.attrclass(parameter).ancestors.should be_include(Puppet::Parameter) end end properties = [:ip, :iptype, :autoboot, :pool, :shares, :inherit] properties.each do |property| it "should have a #{property} property" do zone.attrclass(property).ancestors.should be_include(Puppet::Property) end end it "should be invalid when :path is missing" do lambda { zone.new(:name => "dummy") }.should raise_error end it "should be invalid when :ip is missing a \":\" and iptype is :shared" do lambda { zone.new(:name => "dummy", :ip => "if") }.should raise_error end it "should be invalid when :ip has a \":\" and iptype is :exclusive" do lambda { zone.new(:name => "dummy", :ip => "if:1.2.3.4", :iptype => :exclusive) }.should raise_error end it "should be invalid when :ip has two \":\" and iptype is :exclusive" do lambda { zone.new(:name => "dummy", :ip => "if:1.2.3.4:2.3.4.5", :iptype => :exclusive) }.should raise_error end it "should be valid when :iptype is :shared and using interface and ip" do zone.new(:name => "dummy", :path => "/dummy", :ip => "if:1.2.3.4") end it "should be valid when :iptype is :shared and using interface, ip and default route" do zone.new(:name => "dummy", :path => "/dummy", :ip => "if:1.2.3.4:2.3.4.5") end it "should be valid when :iptype is :exclusive and using interface" do zone.new(:name => "dummy", :path => "/dummy", :ip => "if", :iptype => :exclusive) end it "should auto-require :dataset entries" do fs = 'random-pool/some-zfs' # ick provider = stub 'zfs::provider' provider.stubs(:name).returns(:solaris) Puppet::Type.type(:zfs).stubs(:defaultprovider).returns(provider) catalog = Puppet::Resource::Catalog.new zfs_instance = Puppet::Type.type(:zfs).new(:name => fs) catalog.add_resource zfs_instance zone_instance = zone.new(:name => "dummy", :path => "/foo", :ip => 'en1:1.0.0.0', :dataset => fs) catalog.add_resource zone_instance catalog.relationship_graph.dependencies(zone_instance).should == [zfs_instance] end end diff --git a/spec/unit/type/zpool_spec.rb b/spec/unit/type/zpool_spec.rb index be8cb12ba..96e7d548c 100755 --- a/spec/unit/type/zpool_spec.rb +++ b/spec/unit/type/zpool_spec.rb @@ -1,110 +1,110 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') zpool = Puppet::Type.type(:zpool) describe zpool do before do @provider = stub 'provider' @resource = stub 'resource', :resource => nil, :provider => @provider, :line => nil, :file => nil end properties = [:ensure, :disk, :mirror, :raidz, :spare, :log] properties.each do |property| it "should have a #{property} property" do zpool.attrclass(property).ancestors.should be_include(Puppet::Property) end end parameters = [:pool, :raid_parity] parameters.each do |parameter| it "should have a #{parameter} parameter" do zpool.attrclass(parameter).ancestors.should be_include(Puppet::Parameter) end end end vdev_property = Puppet::Property::VDev describe vdev_property do before do vdev_property.initvars @resource = stub 'resource', :[]= => nil, :property => nil @property = vdev_property.new(:resource => @resource) end it "should be insync if the devices are the same" do @property.should = ["dev1 dev2"] @property.safe_insync?(["dev2 dev1"]).must be_true end it "should be out of sync if the devices are not the same" do @property.should = ["dev1 dev3"] @property.safe_insync?(["dev2 dev1"]).must be_false end it "should be insync if the devices are the same and the should values are comma seperated" do @property.should = ["dev1", "dev2"] @property.safe_insync?(["dev2 dev1"]).must be_true end it "should be out of sync if the device is absent and should has a value" do @property.should = ["dev1", "dev2"] @property.safe_insync?(:absent).must be_false end it "should be insync if the device is absent and should is absent" do @property.should = [:absent] @property.safe_insync?(:absent).must be_true end end multi_vdev_property = Puppet::Property::MultiVDev describe multi_vdev_property do before do multi_vdev_property.initvars @resource = stub 'resource', :[]= => nil, :property => nil @property = multi_vdev_property.new(:resource => @resource) end it "should be insync if the devices are the same" do @property.should = ["dev1 dev2"] @property.safe_insync?(["dev2 dev1"]).must be_true end it "should be out of sync if the devices are not the same" do @property.should = ["dev1 dev3"] @property.safe_insync?(["dev2 dev1"]).must be_false end it "should be out of sync if the device is absent and should has a value" do @property.should = ["dev1", "dev2"] @property.safe_insync?(:absent).must be_false end it "should be insync if the device is absent and should is absent" do @property.should = [:absent] @property.safe_insync?(:absent).must be_true end describe "when there are multiple lists of devices" do it "should be in sync if each group has the same devices" do @property.should = ["dev1 dev2", "dev3 dev4"] @property.safe_insync?(["dev2 dev1", "dev3 dev4"]).must be_true end it "should be out of sync if any group has the different devices" do @property.should = ["dev1 devX", "dev3 dev4"] @property.safe_insync?(["dev2 dev1", "dev3 dev4"]).must be_false end it "should be out of sync if devices are in the wrong group" do @property.should = ["dev1 dev2", "dev3 dev4"] @property.safe_insync?(["dev2 dev3", "dev1 dev4"]).must be_false end end end diff --git a/spec/unit/util/autoload_spec.rb b/spec/unit/util/autoload_spec.rb index eb0b705f4..808885dd7 100755 --- a/spec/unit/util/autoload_spec.rb +++ b/spec/unit/util/autoload_spec.rb @@ -1,120 +1,120 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/autoload' describe Puppet::Util::Autoload do before do @autoload = Puppet::Util::Autoload.new("foo", "tmp") @autoload.stubs(:eachdir).yields "/my/dir" end it "should use the Cacher module" do Puppet::Util::Autoload.ancestors.should be_include(Puppet::Util::Cacher) end describe "when building the search path" do it "should collect all of the plugins and lib directories that exist in the current environment's module path" do Puppet.settings.expects(:value).with(:environment).returns "foo" Puppet.settings.expects(:value).with(:modulepath, :foo).returns "/a:/b:/c" Dir.expects(:entries).with("/a").returns %w{one two} Dir.expects(:entries).with("/b").returns %w{one two} FileTest.stubs(:directory?).returns false FileTest.expects(:directory?).with("/a").returns true FileTest.expects(:directory?).with("/b").returns true %w{/a/one/plugins /a/two/lib /b/one/plugins /b/two/lib}.each do |d| FileTest.expects(:directory?).with(d).returns true end @autoload.module_directories.should == %w{/a/one/plugins /a/two/lib /b/one/plugins /b/two/lib} end it "should not look for lib directories in directories starting with '.'" do Puppet.settings.expects(:value).with(:environment).returns "foo" Puppet.settings.expects(:value).with(:modulepath, :foo).returns "/a" Dir.expects(:entries).with("/a").returns %w{. ..} FileTest.expects(:directory?).with("/a").returns true FileTest.expects(:directory?).with("/a/./lib").never FileTest.expects(:directory?).with("/a/./plugins").never FileTest.expects(:directory?).with("/a/../lib").never FileTest.expects(:directory?).with("/a/../plugins").never @autoload.module_directories end it "should include the module directories, the Puppet libdir, and all of the Ruby load directories" do Puppet.stubs(:[]).with(:libdir).returns(%w{/libdir1 /lib/dir/two /third/lib/dir}.join(File::PATH_SEPARATOR)) @autoload.expects(:module_directories).returns %w{/one /two} @autoload.search_directories.should == %w{/one /two /libdir1 /lib/dir/two /third/lib/dir} + $LOAD_PATH end it "should include in its search path all of the search directories that have a subdirectory matching the autoload path" do @autoload = Puppet::Util::Autoload.new("foo", "loaddir") @autoload.expects(:search_directories).returns %w{/one /two /three} FileTest.expects(:directory?).with("/one/loaddir").returns true FileTest.expects(:directory?).with("/two/loaddir").returns false FileTest.expects(:directory?).with("/three/loaddir").returns true @autoload.searchpath.should == ["/one/loaddir", "/three/loaddir"] end end it "should include its FileCache module" do Puppet::Util::Autoload.ancestors.should be_include(Puppet::Util::Autoload::FileCache) end describe "when loading a file" do before do @autoload.stubs(:searchpath).returns %w{/a} end [RuntimeError, LoadError, SyntaxError].each do |error| it "should die with Puppet::Error if a #{error.to_s} exception is thrown" do @autoload.stubs(:file_exist?).returns true Kernel.expects(:load).raises error lambda { @autoload.load("foo") }.should raise_error(Puppet::Error) end end it "should not raise an error if the file is missing" do @autoload.load("foo").should == false end it "should register loaded files with the main loaded file list so they are not reloaded by ruby" do @autoload.stubs(:file_exist?).returns true Kernel.stubs(:load) @autoload.load("myfile") $LOADED_FEATURES.should be_include("tmp/myfile.rb") end end describe "when loading all files" do before do @autoload.stubs(:searchpath).returns %w{/a} Dir.stubs(:glob).returns "/path/to/file.rb" @autoload.class.stubs(:loaded?).returns(false) end [RuntimeError, LoadError, SyntaxError].each do |error| it "should die an if a #{error.to_s} exception is thrown" do Kernel.expects(:require).raises error lambda { @autoload.loadall }.should raise_error(Puppet::Error) end end it "should require the full path to the file" do Kernel.expects(:require).with("/path/to/file.rb") @autoload.loadall end end end diff --git a/spec/unit/util/command_line_spec.rb b/spec/unit/util/command_line_spec.rb index 98ddb92f6..a7d261dcf 100755 --- a/spec/unit/util/command_line_spec.rb +++ b/spec/unit/util/command_line_spec.rb @@ -1,137 +1,137 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/command_line' describe Puppet::Util::CommandLine do include PuppetSpec::Files before do @tty = stub("tty", :tty? => true ) @pipe = stub("pipe", :tty? => false) end it "should pull off the first argument if it looks like a subcommand" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ client --help whatever.pp }, @tty ) command_line.subcommand_name.should == "client" command_line.args.should == %w{ --help whatever.pp } end it "should use 'apply' if the first argument looks like a .pp file" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ whatever.pp }, @tty ) command_line.subcommand_name.should == "apply" command_line.args.should == %w{ whatever.pp } end it "should use 'apply' if the first argument looks like a .rb file" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ whatever.rb }, @tty ) command_line.subcommand_name.should == "apply" command_line.args.should == %w{ whatever.rb } end it "should use 'apply' if the first argument looks like a flag" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ --debug }, @tty ) command_line.subcommand_name.should == "apply" command_line.args.should == %w{ --debug } end it "should use 'apply' if the first argument is -" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ - }, @tty ) command_line.subcommand_name.should == "apply" command_line.args.should == %w{ - } end it "should return nil if the first argument is --help" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ --help }, @tty ) command_line.subcommand_name.should == nil end it "should return nil if there are no arguments on a tty" do command_line = Puppet::Util::CommandLine.new("puppet", [], @tty ) command_line.subcommand_name.should == nil command_line.args.should == [] end it "should use 'apply' if there are no arguments on a pipe" do command_line = Puppet::Util::CommandLine.new("puppet", [], @pipe ) command_line.subcommand_name.should == "apply" command_line.args.should == [] end it "should return the executable name if it is not puppet" do command_line = Puppet::Util::CommandLine.new("puppetmasterd", [], @tty ) command_line.subcommand_name.should == "puppetmasterd" end it "should translate subcommand names into their legacy equivalent" do command_line = Puppet::Util::CommandLine.new("puppet", ["master"], @tty) command_line.legacy_executable_name.should == "puppetmasterd" end it "should leave legacy command names alone" do command_line = Puppet::Util::CommandLine.new("puppetmasterd", [], @tty) command_line.legacy_executable_name.should == "puppetmasterd" end describe "when the subcommand is not implemented" do it "should find and invoke an executable with a hyphenated name" do commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'], @tty) Puppet::Util.expects(:which).with('puppet-whatever').returns('/dev/null/puppet-whatever') commandline.expects(:system).with('/dev/null/puppet-whatever', 'argument') commandline.execute end describe "and an external implementation cannot be found" do it "should abort and show the usage message" do commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'], @tty) Puppet::Util.expects(:which).with('puppet-whatever').returns(nil) commandline.expects(:system).never commandline.expects(:usage_message).returns("the usage message") commandline.expects(:abort).with{|x| x =~ /the usage message/}.raises("stubbed abort") lambda{ commandline.execute }.should raise_error('stubbed abort') end end end describe 'when loading commands' do before do @core_apps = %w{describe filebucket kick queue resource agent cert apply doc master} @command_line = Puppet::Util::CommandLine.new("foo", %w{ client --help whatever.pp }, @tty ) end it 'should be able to find all existing commands' do @core_apps.each do |command| @command_line.available_subcommands.should include command end end describe 'when multiple paths have applications' do before do @dir=tmpdir('command_line_plugin_test') @appdir="#{@dir}/puppet/application" FileUtils.mkdir_p(@appdir) FileUtils.touch("#{@appdir}/foo.rb") $LOAD_PATH.unshift(@dir) # WARNING: MUST MATCH THE AFTER ACTIONS! end it 'should be able to find commands from both paths' do found = @command_line.available_subcommands found.should include 'foo' @core_apps.each { |cmd| found.should include cmd } end after do $LOAD_PATH.shift # WARNING: MUST MATCH THE BEFORE ACTIONS! end end end end diff --git a/spec/unit/util/errors_spec.rb b/spec/unit/util/errors_spec.rb index 2500403d0..da1b8b0bd 100755 --- a/spec/unit/util/errors_spec.rb +++ b/spec/unit/util/errors_spec.rb @@ -1,38 +1,38 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/errors' class ErrorTester include Puppet::Util::Errors attr_accessor :line, :file end describe Puppet::Util::Errors do before do @tester = ErrorTester.new end it "should provide a 'fail' method" do @tester.should respond_to(:fail) end it "should provide a 'devfail' method" do @tester.should respond_to(:devfail) end it "should raise any provided error when failing" do lambda { @tester.fail(Puppet::ParseError, "stuff") }.should raise_error(Puppet::ParseError) end it "should default to Puppet::Error when failing" do lambda { @tester.fail("stuff") }.should raise_error(Puppet::Error) end it "should have a method for converting error context into a string" do @tester.file = "/my/file" @tester.line = 50 @tester.error_context.should == " at /my/file:50" end end diff --git a/spec/unit/util/feature_spec.rb b/spec/unit/util/feature_spec.rb index 8cedade7d..365428752 100755 --- a/spec/unit/util/feature_spec.rb +++ b/spec/unit/util/feature_spec.rb @@ -1,72 +1,72 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/feature' describe Puppet::Util::Feature do before do @features = Puppet::Util::Feature.new("features") @features.stubs(:warn) end it "should consider undefined features to be absent" do @features.should_not be_defined_feature end it "should be able to add new features" do @features.add(:myfeature) {} @features.should respond_to(:myfeature?) end it "should call associated code when loading a feature" do $loaded_feature = false @features.add(:myfeature) { $loaded_feature = true} $loaded_feature.should be_true end it "should consider a feature absent when the feature load fails" do @features.add(:failer) { raise "foo" } @features.should_not be_failer end it "should consider a feature to be absent when the feature load returns false" do @features.add(:failer) { false } @features.should_not be_failer end it "should consider a feature to be present when the feature load returns true" do @features.add(:available) { true } @features.should be_available end it "should cache the results of a feature load" do $loaded_feature = 0 @features.add(:myfeature) { $loaded_feature += 1 } @features.myfeature? @features.myfeature? $loaded_feature.should == 1 end it "should support features with libraries" do lambda { @features.add(:puppet, :libs => %w{puppet}) }.should_not raise_error end it "should consider a feature to be present if all of its libraries are present" do @features.add(:myfeature, :libs => %w{foo bar}) @features.expects(:require).with("foo") @features.expects(:require).with("bar") @features.should be_myfeature end it "should log and consider a feature to be absent if any of its libraries are absent" do @features.add(:myfeature, :libs => %w{foo bar}) @features.expects(:require).with("foo").raises(LoadError) @features.stubs(:require).with("bar") Puppet.expects(:debug) @features.should_not be_myfeature end end diff --git a/spec/unit/util/file_locking_spec.rb b/spec/unit/util/file_locking_spec.rb index 8fafb1d52..e9dbe9d7b 100755 --- a/spec/unit/util/file_locking_spec.rb +++ b/spec/unit/util/file_locking_spec.rb @@ -1,160 +1,160 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/file_locking' class FileLocker include Puppet::Util::FileLocking end describe Puppet::Util::FileLocking do it "should have a module method for getting a read lock on files" do Puppet::Util::FileLocking.should respond_to(:readlock) end it "should have a module method for getting a write lock on files" do Puppet::Util::FileLocking.should respond_to(:writelock) end it "should have an instance method for getting a read lock on files" do FileLocker.new.private_methods.should be_include("readlock") end it "should have an instance method for getting a write lock on files" do FileLocker.new.private_methods.should be_include("writelock") end describe "when acquiring a read lock" do before do File.stubs(:exists?).with('/file').returns true File.stubs(:file?).with('/file').returns true end it "should use a global shared mutex" do Puppet::Util.expects(:synchronize_on).with('/file',Sync::SH).once Puppet::Util::FileLocking.readlock '/file' end it "should use a shared lock on the file" do Puppet::Util.expects(:synchronize_on).with('/file',Sync::SH).yields fh = mock 'filehandle' File.expects(:open).with("/file").yields fh fh.expects(:lock_shared).yields "locked_fh" result = nil Puppet::Util::FileLocking.readlock('/file') { |l| result = l } result.should == "locked_fh" end it "should only work on regular files" do File.expects(:file?).with('/file').returns false proc { Puppet::Util::FileLocking.readlock('/file') }.should raise_error(ArgumentError) end it "should create missing files" do Puppet::Util.expects(:synchronize_on).with('/file',Sync::SH).yields File.expects(:exists?).with('/file').returns false File.expects(:open).with('/file').once Puppet::Util::FileLocking.readlock('/file') end end describe "when acquiring a write lock" do before do Puppet::Util.stubs(:synchronize_on).yields File.stubs(:file?).with('/file').returns true File.stubs(:exists?).with('/file').returns true end it "should fail if the parent directory does not exist" do FileTest.expects(:directory?).with("/my/dir").returns false File.stubs(:file?).with('/my/dir/file').returns true File.stubs(:exists?).with('/my/dir/file').returns true lambda { Puppet::Util::FileLocking.writelock('/my/dir/file') }.should raise_error(Puppet::DevError) end it "should use a global exclusive mutex" do Puppet::Util.expects(:synchronize_on).with("/file",Sync::EX) Puppet::Util::FileLocking.writelock '/file' end it "should use any specified mode when opening the file" do File.expects(:open).with("/file", File::Constants::CREAT | File::Constants::WRONLY , :mymode) Puppet::Util::FileLocking.writelock('/file', :mymode) end it "should use the mode of the existing file if no mode is specified" do File.expects(:stat).with("/file").returns(mock("stat", :mode => 0755)) File.expects(:open).with("/file", File::Constants::CREAT | File::Constants::WRONLY, 0755) Puppet::Util::FileLocking.writelock('/file') end it "should use 0600 as the mode if no mode is specified and the file does not exist" do File.expects(:stat).raises(Errno::ENOENT) File.expects(:open).with("/file", File::Constants::CREAT | File::Constants::WRONLY, 0600) Puppet::Util::FileLocking.writelock('/file') end it "should create an exclusive file lock" do fh = mock 'fh' File.expects(:open).yields fh fh.expects(:lock_exclusive) Puppet::Util::FileLocking.writelock('/file') end it "should allow the caller to write to the locked file" do fh = mock 'fh' File.expects(:open).yields fh lfh = mock 'locked_filehandle' fh.expects(:lock_exclusive).yields(lfh) lfh.stubs(:seek) lfh.stubs(:truncate) lfh.expects(:print).with "foo" Puppet::Util::FileLocking.writelock('/file') do |f| f.print "foo" end end it "should truncate the file under an exclusive lock" do fh = mock 'fh' File.expects(:open).yields fh lfh = mock 'locked_filehandle' fh.expects(:lock_exclusive).yields(lfh) lfh.expects(:seek).with(0, IO::SEEK_SET) lfh.expects(:truncate).with(0) lfh.stubs(:print) Puppet::Util::FileLocking.writelock('/file') do |f| f.print "foo" end end it "should only work on regular files" do File.expects(:file?).with('/file').returns false proc { Puppet::Util::FileLocking.writelock('/file') }.should raise_error(ArgumentError) end it "should create missing files" do Puppet::Util.expects(:synchronize_on).with('/file',Sync::EX).yields File.expects(:exists?).with('/file').returns false File.expects(:open).with('/file', File::Constants::CREAT | File::Constants::WRONLY, 0600).once Puppet::Util::FileLocking.writelock('/file') end end end diff --git a/spec/unit/util/filetype_spec.rb b/spec/unit/util/filetype_spec.rb index 68ef9d6eb..012631b91 100644 --- a/spec/unit/util/filetype_spec.rb +++ b/spec/unit/util/filetype_spec.rb @@ -1,100 +1,100 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/filetype' # XXX Import all of the tests into this file. describe Puppet::Util::FileType do describe "when backing up a file" do before do @file = Puppet::Util::FileType.filetype(:flat).new("/my/file") end it "should do nothing if the file does not exist" do File.expects(:exists?).with("/my/file").returns false @file.expects(:bucket).never @file.backup end it "should use its filebucket to backup the file if it exists" do File.expects(:exists?).with("/my/file").returns true bucket = mock 'bucket' bucket.expects(:backup).with("/my/file") @file.expects(:bucket).returns bucket @file.backup end it "should use the default filebucket" do bucket = mock 'bucket' bucket.expects(:bucket).returns "mybucket" Puppet::Type.type(:filebucket).expects(:mkdefaultbucket).returns bucket @file.bucket.should == "mybucket" end end describe "the flat filetype" do before do @type = Puppet::Util::FileType.filetype(:flat) end it "should exist" do @type.should_not be_nil end describe "when the file already exists" do it "should return the file's contents when asked to read it" do file = @type.new("/my/file") File.expects(:exist?).with("/my/file").returns true File.expects(:read).with("/my/file").returns "my text" file.read.should == "my text" end it "should unlink the file when asked to remove it" do file = @type.new("/my/file") File.expects(:exist?).with("/my/file").returns true File.expects(:unlink).with("/my/file") file.remove end end describe "when the file does not exist" do it "should return an empty string when asked to read the file" do file = @type.new("/my/file") File.expects(:exist?).with("/my/file").returns false file.read.should == "" end end describe "when writing the file" do before do @file = @type.new("/my/file") FileUtils.stubs(:cp) @tempfile = stub 'tempfile', :print => nil, :close => nil, :flush => nil, :path => "/other/file" Tempfile.stubs(:new).returns @tempfile end it "should first create a temp file and copy its contents over to the file location" do Tempfile.expects(:new).with("puppet").returns @tempfile @tempfile.expects(:print).with("my text") @tempfile.expects(:flush) @tempfile.expects(:close) FileUtils.expects(:cp).with(@tempfile.path, "/my/file") @file.write "my text" end it "should set the selinux default context on the file" do @file.expects(:set_selinux_default_context).with("/my/file") @file.write "eh" end end end end diff --git a/spec/unit/util/inline_docs_spec.rb b/spec/unit/util/inline_docs_spec.rb index edfa405a1..75afb57cb 100755 --- a/spec/unit/util/inline_docs_spec.rb +++ b/spec/unit/util/inline_docs_spec.rb @@ -1,32 +1,32 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/inline_docs' class InlineDoccer include Puppet::Util::InlineDocs end describe Puppet::Util::InlineDocs do describe "when included" do it "should create a class method for specifying that docs should be associated" do InlineDoccer.expects(:use_docs=).with true InlineDoccer.associates_doc end it "should default to not associating docs" do (!! InlineDoccer.use_docs).should be_false end it "should create an instance method for setting documentation" do instance = InlineDoccer.new instance.doc = "foo" instance.doc.should == "foo" end it "should default to an empty string for docs" do InlineDoccer.new.doc.should == "" end end end diff --git a/spec/unit/util/log_spec.rb b/spec/unit/util/log_spec.rb index 29df0787a..3c8577493 100755 --- a/spec/unit/util/log_spec.rb +++ b/spec/unit/util/log_spec.rb @@ -1,227 +1,227 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/log' describe Puppet::Util::Log do it "should write a given message to the specified destination" do arraydest = [] Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(arraydest)) Puppet::Util::Log.new(:level => :notice, :message => "foo") message = arraydest.last.message message.should == "foo" end describe Puppet::Util::Log::DestConsole do before do @console = Puppet::Util::Log::DestConsole.new end it "should colorize if Puppet[:color] is :ansi" do Puppet[:color] = :ansi @console.colorize(:alert, "abc").should == "\e[0;31mabc\e[0m" end it "should colorize if Puppet[:color] is 'yes'" do Puppet[:color] = "yes" @console.colorize(:alert, "abc").should == "\e[0;31mabc\e[0m" end it "should htmlize if Puppet[:color] is :html" do Puppet[:color] = :html @console.colorize(:alert, "abc").should == "abc" end it "should do nothing if Puppet[:color] is false" do Puppet[:color] = false @console.colorize(:alert, "abc").should == "abc" end it "should do nothing if Puppet[:color] is invalid" do Puppet[:color] = "invalid option" @console.colorize(:alert, "abc").should == "abc" end end describe "instances" do before do Puppet::Util::Log.stubs(:newmessage) end [:level, :message, :time, :remote].each do |attr| it "should have a #{attr} attribute" do log = Puppet::Util::Log.new :level => :notice, :message => "A test message" log.should respond_to(attr) log.should respond_to(attr.to_s + "=") end end it "should fail if created without a level" do lambda { Puppet::Util::Log.new(:message => "A test message") }.should raise_error(ArgumentError) end it "should fail if created without a message" do lambda { Puppet::Util::Log.new(:level => :notice) }.should raise_error(ArgumentError) end it "should make available the level passed in at initialization" do Puppet::Util::Log.new(:level => :notice, :message => "A test message").level.should == :notice end it "should make available the message passed in at initialization" do Puppet::Util::Log.new(:level => :notice, :message => "A test message").message.should == "A test message" end # LAK:NOTE I don't know why this behavior is here, I'm just testing what's in the code, # at least at first. it "should always convert messages to strings" do Puppet::Util::Log.new(:level => :notice, :message => :foo).message.should == "foo" end it "should flush the log queue when the first destination is specified" do Puppet::Util::Log.close_all Puppet::Util::Log.expects(:flushqueue) Puppet::Util::Log.newdestination(:console) end it "should convert the level to a symbol if it's passed in as a string" do Puppet::Util::Log.new(:level => "notice", :message => :foo).level.should == :notice end it "should fail if the level is not a symbol or string" do lambda { Puppet::Util::Log.new(:level => 50, :message => :foo) }.should raise_error(ArgumentError) end it "should fail if the provided level is not valid" do Puppet::Util::Log.expects(:validlevel?).with(:notice).returns false lambda { Puppet::Util::Log.new(:level => :notice, :message => :foo) }.should raise_error(ArgumentError) end it "should set its time to the initialization time" do time = mock 'time' Time.expects(:now).returns time Puppet::Util::Log.new(:level => "notice", :message => :foo).time.should equal(time) end it "should make available any passed-in tags" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{foo bar}) log.tags.should be_include("foo") log.tags.should be_include("bar") end it "should use an passed-in source" do Puppet::Util::Log.any_instance.expects(:source=).with "foo" Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => "foo") end [:file, :line].each do |attr| it "should use #{attr} if provided" do Puppet::Util::Log.any_instance.expects(attr.to_s + "=").with "foo" Puppet::Util::Log.new(:level => "notice", :message => :foo, attr => "foo") end end it "should default to 'Puppet' as its source" do Puppet::Util::Log.new(:level => "notice", :message => :foo).source.should == "Puppet" end it "should register itself with Log" do Puppet::Util::Log.expects(:newmessage) Puppet::Util::Log.new(:level => "notice", :message => :foo) end it "should update Log autoflush when Puppet[:autoflush] is set" do Puppet::Util::Log.expects(:autoflush=).once.with(true) Puppet[:autoflush] = true end it "should have a method for determining if a tag is present" do Puppet::Util::Log.new(:level => "notice", :message => :foo).should respond_to(:tagged?) end it "should match a tag if any of the tags are equivalent to the passed tag as a string" do Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{one two}).should be_tagged(:one) end it "should tag itself with its log level" do Puppet::Util::Log.new(:level => "notice", :message => :foo).should be_tagged(:notice) end it "should return its message when converted to a string" do Puppet::Util::Log.new(:level => "notice", :message => :foo).to_s.should == "foo" end it "should include its time, source, level, and message when prepared for reporting" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo) report = log.to_report report.should be_include("notice") report.should be_include("foo") report.should be_include(log.source) report.should be_include(log.time.to_s) end describe "when setting the source as a RAL object" do it "should tag itself with any tags the source has" do source = Puppet::Type.type(:file).new :path => "/foo/bar" log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source) source.tags.each do |tag| log.tags.should be_include(tag) end end it "should use the source_descriptors" do source = stub "source" source.stubs(:source_descriptors).returns(:tags => ["tag","tag2"], :path => "path", :version => 100) log = Puppet::Util::Log.new(:level => "notice", :message => :foo) log.expects(:tag).with("tag") log.expects(:tag).with("tag2") log.source = source log.source.should == "path" end it "should copy over any file and line information" do source = Puppet::Type.type(:file).new :path => "/foo/bar" source.file = "/my/file" source.line = 50 log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source) log.file.should == "/my/file" log.line.should == 50 end end describe "when setting the source as a non-RAL object" do it "should not try to copy over file, version, line, or tag information" do source = Puppet::Module.new("foo") source.expects(:file).never log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source) end end end describe "to_yaml" do it "should not include the @version attribute" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100) log.to_yaml_properties.should_not include('@version') end it "should include attributes @level, @message, @source, @tags, and @time" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100) log.to_yaml_properties.should == %w{@level @message @source @tags @time} end it "should include attributes @file and @line if specified" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :file => "foo", :line => 35) log.to_yaml_properties.should include('@file') log.to_yaml_properties.should include('@line') end end end diff --git a/spec/unit/util/logging_spec.rb b/spec/unit/util/logging_spec.rb index 411cd17a9..97ffc0b25 100755 --- a/spec/unit/util/logging_spec.rb +++ b/spec/unit/util/logging_spec.rb @@ -1,95 +1,95 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/logging' class LoggingTester include Puppet::Util::Logging end describe Puppet::Util::Logging do before do @logger = LoggingTester.new end Puppet::Util::Log.eachlevel do |level| it "should have a method for sending '#{level}' logs" do @logger.should respond_to(level) end end it "should have a method for sending a log with a specified log level" do @logger.expects(:to_s).returns "I'm a string!" Puppet::Util::Log.expects(:create).with { |args| args[:source] == "I'm a string!" and args[:level] == "loglevel" and args[:message] == "mymessage" } @logger.send_log "loglevel", "mymessage" end describe "when sending a log" do it "should use the Log's 'create' entrance method" do Puppet::Util::Log.expects(:create) @logger.notice "foo" end it "should send itself converted to a string as the log source" do @logger.expects(:to_s).returns "I'm a string!" Puppet::Util::Log.expects(:create).with { |args| args[:source] == "I'm a string!" } @logger.notice "foo" end it "should queue logs sent without a specified destination" do Puppet::Util::Log.close_all Puppet::Util::Log.expects(:queuemessage) @logger.notice "foo" end it "should use the path of any provided resource type" do resource = Puppet::Type.type(:mount).new :name => "foo" resource.expects(:path).returns "/path/to/mount".to_sym Puppet::Util::Log.expects(:create).with { |args| args[:source] == "/path/to/mount" } resource.notice "foo" end it "should use the path of any provided resource parameter" do resource = Puppet::Type.type(:mount).new :name => "foo" param = resource.parameter(:name) param.expects(:path).returns "/path/to/param".to_sym Puppet::Util::Log.expects(:create).with { |args| args[:source] == "/path/to/param" } param.notice "foo" end it "should send the provided argument as the log message" do Puppet::Util::Log.expects(:create).with { |args| args[:message] == "foo" } @logger.notice "foo" end it "should join any provided arguments into a single string for the message" do Puppet::Util::Log.expects(:create).with { |args| args[:message] == "foo bar baz" } @logger.notice ["foo", "bar", "baz"] end [:file, :line, :tags].each do |attr| it "should include #{attr} if available" do @logger.singleton_class.send(:attr_accessor, attr) @logger.send(attr.to_s + "=", "myval") Puppet::Util::Log.expects(:create).with { |args| args[attr] == "myval" } @logger.notice "foo" end end end end diff --git a/spec/unit/util/metric_spec.rb b/spec/unit/util/metric_spec.rb index 600b88f85..425812297 100755 --- a/spec/unit/util/metric_spec.rb +++ b/spec/unit/util/metric_spec.rb @@ -1,95 +1,95 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/metric' describe Puppet::Util::Metric do before do @metric = Puppet::Util::Metric.new("foo") end it "should be aliased to Puppet::Metric" do Puppet::Util::Metric.should equal(Puppet::Metric) end [:type, :name, :value, :label, :basedir].each do |name| it "should have a #{name} attribute" do @metric.should respond_to(name) @metric.should respond_to(name.to_s + "=") end end it "should default to the :rrdir as the basedir "do Puppet.settings.expects(:value).with(:rrddir).returns "myrrd" @metric.basedir.should == "myrrd" end it "should use any provided basedir" do @metric.basedir = "foo" @metric.basedir.should == "foo" end it "should require a name at initialization" do lambda { Puppet::Util::Metric.new }.should raise_error(ArgumentError) end it "should always convert its name to a string" do Puppet::Util::Metric.new(:foo).name.should == "foo" end it "should support a label" do Puppet::Util::Metric.new("foo", "mylabel").label.should == "mylabel" end it "should autogenerate a label if none is provided" do Puppet::Util::Metric.new("foo_bar").label.should == "Foo bar" end it "should have a method for adding values" do @metric.should respond_to(:newvalue) end it "should have a method for returning values" do @metric.should respond_to(:values) end it "should require a name and value for its values" do lambda { @metric.newvalue }.should raise_error(ArgumentError) end it "should support a label for values" do @metric.newvalue("foo", 10, "label") @metric.values[0][1].should == "label" end it "should autogenerate value labels if none is provided" do @metric.newvalue("foo_bar", 10) @metric.values[0][1].should == "Foo bar" end it "should return its values sorted by label" do @metric.newvalue("foo", 10, "b") @metric.newvalue("bar", 10, "a") @metric.values.should == [["bar", "a", 10], ["foo", "b", 10]] end it "should use an array indexer method to retrieve individual values" do @metric.newvalue("foo", 10) @metric["foo"].should == 10 end it "should return nil if the named value cannot be found" do @metric["foo"].should == 0 end # LAK: I'm not taking the time to develop these tests right now. # I expect they should actually be extracted into a separate class # anyway. it "should be able to graph metrics using RRDTool" it "should be able to create a new RRDTool database" it "should be able to store metrics into an RRDTool database" end diff --git a/spec/unit/util/monkey_patches_spec.rb b/spec/unit/util/monkey_patches_spec.rb index 049ed1044..8bfcd900e 100644 --- a/spec/unit/util/monkey_patches_spec.rb +++ b/spec/unit/util/monkey_patches_spec.rb @@ -1,33 +1,33 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/monkey_patches' describe "yaml deserialization" do it "should call yaml_initialize when deserializing objects that have that method defined" do class Puppet::TestYamlInitializeClass attr_reader :foo def yaml_initialize(tag, var) var.should == {'foo' => 100} instance_variables.should == [] @foo = 200 end end obj = YAML.load("--- !ruby/object:Puppet::TestYamlInitializeClass\n foo: 100") obj.foo.should == 200 end it "should not call yaml_initialize if not defined" do class Puppet::TestYamlNonInitializeClass attr_reader :foo end obj = YAML.load("--- !ruby/object:Puppet::TestYamlNonInitializeClass\n foo: 100") obj.foo.should == 100 end end diff --git a/spec/unit/util/posix_spec.rb b/spec/unit/util/posix_spec.rb index dbc90d9d0..6d7351220 100755 --- a/spec/unit/util/posix_spec.rb +++ b/spec/unit/util/posix_spec.rb @@ -1,256 +1,256 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/posix' class PosixTest include Puppet::Util::POSIX end describe Puppet::Util::POSIX do before do @posix = PosixTest.new end [:group, :gr].each do |name| it "should return :gid as the field for #{name}" do @posix.idfield(name).should == :gid end it "should return :getgrgid as the id method for #{name}" do @posix.methodbyid(name).should == :getgrgid end it "should return :getgrnam as the name method for #{name}" do @posix.methodbyname(name).should == :getgrnam end end [:user, :pw, :passwd].each do |name| it "should return :uid as the field for #{name}" do @posix.idfield(name).should == :uid end it "should return :getpwuid as the id method for #{name}" do @posix.methodbyid(name).should == :getpwuid end it "should return :getpwnam as the name method for #{name}" do @posix.methodbyname(name).should == :getpwnam end end describe "when retrieving a posix field" do before do @thing = stub 'thing', :field => "asdf" end it "should fail if no id was passed" do lambda { @posix.get_posix_field("asdf", "bar", nil) }.should raise_error(Puppet::DevError) end describe "and the id is an integer" do it "should log an error and return nil if the specified id is greater than the maximum allowed ID" do Puppet.settings.expects(:value).with(:maximum_uid).returns 100 Puppet.expects(:err) @posix.get_posix_field("asdf", "bar", 200).should be_nil end it "should use the method return by :methodbyid and return the specified field" do Etc.expects(:getgrgid).returns @thing @thing.expects(:field).returns "myval" @posix.get_posix_field(:gr, :field, 200).should == "myval" end it "should return nil if the method throws an exception" do Etc.expects(:getgrgid).raises ArgumentError @thing.expects(:field).never @posix.get_posix_field(:gr, :field, 200).should be_nil end end describe "and the id is not an integer" do it "should use the method return by :methodbyid and return the specified field" do Etc.expects(:getgrnam).returns @thing @thing.expects(:field).returns "myval" @posix.get_posix_field(:gr, :field, "asdf").should == "myval" end it "should return nil if the method throws an exception" do Etc.expects(:getgrnam).raises ArgumentError @thing.expects(:field).never @posix.get_posix_field(:gr, :field, "asdf").should be_nil end end end describe "when returning the gid" do before do @posix.stubs(:get_posix_field) end describe "and the group is an integer" do it "should convert integers specified as a string into an integer" do @posix.expects(:get_posix_field).with(:group, :name, 100) @posix.gid("100") end it "should look up the name for the group" do @posix.expects(:get_posix_field).with(:group, :name, 100) @posix.gid(100) end it "should return nil if the group cannot be found" do @posix.expects(:get_posix_field).once.returns nil @posix.expects(:search_posix_field).never @posix.gid(100).should be_nil end it "should use the found name to look up the id" do @posix.expects(:get_posix_field).with(:group, :name, 100).returns "asdf" @posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 100 @posix.gid(100).should == 100 end # LAK: This is because some platforms have a broken Etc module that always return # the same group. it "should use :search_posix_field if the discovered id does not match the passed-in id" do @posix.expects(:get_posix_field).with(:group, :name, 100).returns "asdf" @posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 50 @posix.expects(:search_posix_field).with(:group, :gid, 100).returns "asdf" @posix.gid(100).should == "asdf" end end describe "and the group is a string" do it "should look up the gid for the group" do @posix.expects(:get_posix_field).with(:group, :gid, "asdf") @posix.gid("asdf") end it "should return nil if the group cannot be found" do @posix.expects(:get_posix_field).once.returns nil @posix.expects(:search_posix_field).never @posix.gid("asdf").should be_nil end it "should use the found gid to look up the nam" do @posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 100 @posix.expects(:get_posix_field).with(:group, :name, 100).returns "asdf" @posix.gid("asdf").should == 100 end it "should use :search_posix_field if the discovered name does not match the passed-in name" do @posix.expects(:get_posix_field).with(:group, :gid, "asdf").returns 100 @posix.expects(:get_posix_field).with(:group, :name, 100).returns "boo" @posix.expects(:search_posix_field).with(:group, :gid, "asdf").returns "asdf" @posix.gid("asdf").should == "asdf" end end end describe "when returning the uid" do before do @posix.stubs(:get_posix_field) end describe "and the group is an integer" do it "should convert integers specified as a string into an integer" do @posix.expects(:get_posix_field).with(:passwd, :name, 100) @posix.uid("100") end it "should look up the name for the group" do @posix.expects(:get_posix_field).with(:passwd, :name, 100) @posix.uid(100) end it "should return nil if the group cannot be found" do @posix.expects(:get_posix_field).once.returns nil @posix.expects(:search_posix_field).never @posix.uid(100).should be_nil end it "should use the found name to look up the id" do @posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "asdf" @posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 100 @posix.uid(100).should == 100 end # LAK: This is because some platforms have a broken Etc module that always return # the same group. it "should use :search_posix_field if the discovered id does not match the passed-in id" do @posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "asdf" @posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 50 @posix.expects(:search_posix_field).with(:passwd, :uid, 100).returns "asdf" @posix.uid(100).should == "asdf" end end describe "and the group is a string" do it "should look up the uid for the group" do @posix.expects(:get_posix_field).with(:passwd, :uid, "asdf") @posix.uid("asdf") end it "should return nil if the group cannot be found" do @posix.expects(:get_posix_field).once.returns nil @posix.expects(:search_posix_field).never @posix.uid("asdf").should be_nil end it "should use the found uid to look up the nam" do @posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 100 @posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "asdf" @posix.uid("asdf").should == 100 end it "should use :search_posix_field if the discovered name does not match the passed-in name" do @posix.expects(:get_posix_field).with(:passwd, :uid, "asdf").returns 100 @posix.expects(:get_posix_field).with(:passwd, :name, 100).returns "boo" @posix.expects(:search_posix_field).with(:passwd, :uid, "asdf").returns "asdf" @posix.uid("asdf").should == "asdf" end end end it "should be able to iteratively search for posix values" do @posix.should respond_to(:search_posix_field) end describe "when searching for posix values iteratively" do it "should iterate across all of the structs returned by Etc and return the appropriate field from the first matching value" end end diff --git a/spec/unit/util/pson_spec.rb b/spec/unit/util/pson_spec.rb index 474ddafa4..08758ee38 100755 --- a/spec/unit/util/pson_spec.rb +++ b/spec/unit/util/pson_spec.rb @@ -1,53 +1,53 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/pson' class PsonUtil include Puppet::Util::Pson end describe Puppet::Util::Pson do it "should fail if no data is provided" do lambda { PsonUtil.new.pson_create("type" => "foo") }.should raise_error(ArgumentError) end it "should call 'from_pson' with the provided data" do pson = PsonUtil.new pson.expects(:from_pson).with("mydata") pson.pson_create("type" => "foo", "data" => "mydata") end { 'foo' => '"foo"', 1 => '1', "\x80" => "\"\x80\"", [] => '[]' }.each { |str,pson| it "should be able to encode #{str.inspect}" do str.to_pson.should == pson end } it "should be able to handle arbitrary binary data" do bin_string = (1..20000).collect { |i| ((17*i+13*i*i) % 255).chr }.join PSON.parse(%Q{{ "type": "foo", "data": #{bin_string.to_pson} }})["data"].should == bin_string end it "should be able to handle UTF8 that isn't a real unicode character" do s = ["\355\274\267"] PSON.parse( [s].to_pson ).should == [s] end it "should be able to handle UTF8 for \\xFF" do s = ["\xc3\xbf"] PSON.parse( [s].to_pson ).should == [s] end it "should be able to handle invalid UTF8 bytes" do s = ["\xc3\xc3"] PSON.parse( [s].to_pson ).should == [s] end end diff --git a/spec/unit/util/rdoc/parser_spec.rb b/spec/unit/util/rdoc/parser_spec.rb index 8545def54..ab54c8cd3 100755 --- a/spec/unit/util/rdoc/parser_spec.rb +++ b/spec/unit/util/rdoc/parser_spec.rb @@ -1,562 +1,562 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require 'puppet/resource/type_collection' require 'puppet/util/rdoc/parser' require 'puppet/util/rdoc/code_objects' require 'rdoc/options' require 'rdoc/rdoc' describe RDoc::Parser do before :each do File.stubs(:stat).with("init.pp") @top_level = stub_everything 'toplevel', :file_relative_name => "init.pp" @parser = RDoc::Parser.new(@top_level, "module/manifests/init.pp", nil, Options.instance, RDoc::Stats.new) end describe "when scanning files" do it "should parse puppet files with the puppet parser" do @parser.stubs(:scan_top_level) parser = stub 'parser' Puppet::Parser::Parser.stubs(:new).returns(parser) parser.expects(:parse).returns(Puppet::Parser::AST::Hostclass.new('')) parser.expects(:file=).with("module/manifests/init.pp") @parser.scan end it "should scan the ast for Puppet files" do parser = stub_everything 'parser' Puppet::Parser::Parser.stubs(:new).returns(parser) parser.expects(:parse).returns(Puppet::Parser::AST::Hostclass.new('')) @parser.expects(:scan_top_level) @parser.scan end it "should return a PuppetTopLevel to RDoc" do parser = stub_everything 'parser' Puppet::Parser::Parser.stubs(:new).returns(parser) parser.expects(:parse).returns(Puppet::Parser::AST::Hostclass.new('')) @parser.expects(:scan_top_level) @parser.scan.should be_a(RDoc::PuppetTopLevel) end it "should scan the top level even if the file has already parsed" do known_type = stub 'known_types' env = stub 'env' Puppet::Node::Environment.stubs(:new).returns(env) env.stubs(:known_resource_types).returns(known_type) known_type.expects(:watching_file?).with("module/manifests/init.pp").returns(true) @parser.expects(:scan_top_level) @parser.scan end end describe "when scanning top level entities" do before :each do @resource_type_collection = resource_type_collection = stub_everything('resource_type_collection') @parser.instance_eval { @known_resource_types = resource_type_collection } @parser.stubs(:split_module).returns("module") @topcontainer = stub_everything 'topcontainer' @container = stub_everything 'container' @module = stub_everything 'module' @container.stubs(:add_module).returns(@module) @parser.stubs(:get_class_or_module).returns([@container, "module"]) end it "should read any present README as module documentation" do FileTest.stubs(:readable?).returns(true) File.stubs(:open).returns("readme") @parser.stubs(:parse_elements) @module.expects(:comment=).with("readme") @parser.scan_top_level(@topcontainer) end it "should tell the container its module name" do @parser.stubs(:parse_elements) @topcontainer.expects(:module_name=).with("module") @parser.scan_top_level(@topcontainer) end it "should not document our toplevel if it isn't a valid module" do @parser.stubs(:split_module).returns(nil) @topcontainer.expects(:document_self=).with(false) @parser.expects(:parse_elements).never @parser.scan_top_level(@topcontainer) end it "should set the module as global if we parse the global manifests (ie __site__ module)" do @parser.stubs(:split_module).returns(RDoc::Parser::SITE) @parser.stubs(:parse_elements) @topcontainer.expects(:global=).with(true) @parser.scan_top_level(@topcontainer) end it "should attach this module container to the toplevel container" do @parser.stubs(:parse_elements) @container.expects(:add_module).with(RDoc::PuppetModule, "module").returns(@module) @parser.scan_top_level(@topcontainer) end it "should defer ast parsing to parse_elements for this module" do @parser.expects(:parse_elements).with(@module) @parser.scan_top_level(@topcontainer) end it "should defer plugins parsing to parse_plugins for this module" do @parser.input_file_name = "module/lib/puppet/parser/function.rb" @parser.expects(:parse_plugins).with(@module) @parser.scan_top_level(@topcontainer) end end describe "when finding modules from filepath" do before :each do Puppet::Module.stubs(:modulepath).returns("/path/to/modules") end it "should return the module name for modulized puppet manifests" do File.stubs(:expand_path).returns("/path/to/module/manifests/init.pp") File.stubs(:identical?).with("/path/to", "/path/to/modules").returns(true) @parser.split_module("/path/to/modules/mymodule/manifests/init.pp").should == "module" end it "should return for manifests not under module path" do File.stubs(:expand_path).returns("/path/to/manifests/init.pp") File.stubs(:identical?).returns(false) @parser.split_module("/path/to/manifests/init.pp").should == RDoc::Parser::SITE end end describe "when parsing AST elements" do before :each do @klass = stub_everything 'klass', :file => "module/manifests/init.pp", :name => "myclass", :type => :hostclass @definition = stub_everything 'definition', :file => "module/manifests/init.pp", :type => :definition, :name => "mydef" @node = stub_everything 'node', :file => "module/manifests/init.pp", :type => :node, :name => "mynode" @resource_type_collection = resource_type_collection = Puppet::Resource::TypeCollection.new("env") @parser.instance_eval { @known_resource_types = resource_type_collection } @container = stub_everything 'container' end it "should document classes in the parsed file" do @resource_type_collection.add_hostclass(@klass) @parser.expects(:document_class).with("myclass", @klass, @container) @parser.parse_elements(@container) end it "should not document class parsed in an other file" do @klass.stubs(:file).returns("/not/same/path/file.pp") @resource_type_collection.add_hostclass(@klass) @parser.expects(:document_class).with("myclass", @klass, @container).never @parser.parse_elements(@container) end it "should document vardefs for the main class" do @klass.stubs(:name).returns :main @resource_type_collection.add_hostclass(@klass) code = stub 'code', :is_a? => false @klass.stubs(:name).returns("") @klass.stubs(:code).returns(code) @parser.expects(:scan_for_vardef).with(@container, code) @parser.parse_elements(@container) end it "should document definitions in the parsed file" do @resource_type_collection.add_definition(@definition) @parser.expects(:document_define).with("mydef", @definition, @container) @parser.parse_elements(@container) end it "should not document definitions parsed in an other file" do @definition.stubs(:file).returns("/not/same/path/file.pp") @resource_type_collection.add_definition(@definition) @parser.expects(:document_define).with("mydef", @definition, @container).never @parser.parse_elements(@container) end it "should document nodes in the parsed file" do @resource_type_collection.add_node(@node) @parser.expects(:document_node).with("mynode", @node, @container) @parser.parse_elements(@container) end it "should not document node parsed in an other file" do @node.stubs(:file).returns("/not/same/path/file.pp") @resource_type_collection.add_node(@node) @parser.expects(:document_node).with("mynode", @node, @container).never @parser.parse_elements(@container) end end describe "when documenting definition" do before(:each) do @define = stub_everything 'define', :arguments => [], :doc => "mydoc", :file => "file", :line => 42 @class = stub_everything 'class' @parser.stubs(:get_class_or_module).returns([@class, "mydef"]) end it "should register a RDoc method to the current container" do @class.expects(:add_method).with { |m| m.name == "mydef"} @parser.document_define("mydef", @define, @class) end it "should attach the documentation to this method" do @class.expects(:add_method).with { |m| m.comment = "mydoc" } @parser.document_define("mydef", @define, @class) end it "should produce a better error message on unhandled exception" do @class.expects(:add_method).raises(ArgumentError) lambda { @parser.document_define("mydef", @define, @class) }.should raise_error(Puppet::ParseError, /in file at line 42/) end it "should convert all definition parameter to string" do arg = stub 'arg' val = stub 'val' @define.stubs(:arguments).returns({arg => val}) arg.expects(:to_s).returns("arg") val.expects(:to_s).returns("val") @parser.document_define("mydef", @define, @class) end end describe "when documenting nodes" do before :each do @code = stub_everything 'code' @node = stub_everything 'node', :doc => "mydoc", :parent => "parent", :code => @code, :file => "file", :line => 42 @rdoc_node = stub_everything 'rdocnode' @class = stub_everything 'class' @class.stubs(:add_node).returns(@rdoc_node) end it "should add a node to the current container" do @class.expects(:add_node).with("mynode", "parent").returns(@rdoc_node) @parser.document_node("mynode", @node, @class) end it "should associate the node documentation to the rdoc node" do @rdoc_node.expects(:comment=).with("mydoc") @parser.document_node("mynode", @node, @class) end it "should scan for include and require" do @parser.expects(:scan_for_include_or_require).with(@rdoc_node, @code) @parser.document_node("mynode", @node, @class) end it "should scan for variable definition" do @parser.expects(:scan_for_vardef).with(@rdoc_node, @code) @parser.document_node("mynode", @node, @class) end it "should scan for resources if needed" do Puppet.settings.stubs(:[]).with(:document_all).returns(true) @parser.expects(:scan_for_resource).with(@rdoc_node, @code) @parser.document_node("mynode", @node, @class) end it "should produce a better error message on unhandled exception" do @class.stubs(:add_node).raises(ArgumentError) lambda { @parser.document_node("mynode", @node, @class) }.should raise_error(Puppet::ParseError, /in file at line 42/) end end describe "when documenting classes" do before :each do @code = stub_everything 'code' @class = stub_everything 'class', :doc => "mydoc", :parent => "parent", :code => @code, :file => "file", :line => 42 @rdoc_class = stub_everything 'rdoc-class' @module = stub_everything 'class' @module.stubs(:add_class).returns(@rdoc_class) @parser.stubs(:get_class_or_module).returns([@module, "myclass"]) end it "should add a class to the current container" do @module.expects(:add_class).with(RDoc::PuppetClass, "myclass", "parent").returns(@rdoc_class) @parser.document_class("mynode", @class, @module) end it "should set the superclass" do @rdoc_class.expects(:superclass=).with("parent") @parser.document_class("mynode", @class, @module) end it "should associate the node documentation to the rdoc class" do @rdoc_class.expects(:comment=).with("mydoc") @parser.document_class("mynode", @class, @module) end it "should scan for include and require" do @parser.expects(:scan_for_include_or_require).with(@rdoc_class, @code) @parser.document_class("mynode", @class, @module) end it "should scan for resources if needed" do Puppet.settings.stubs(:[]).with(:document_all).returns(true) @parser.expects(:scan_for_resource).with(@rdoc_class, @code) @parser.document_class("mynode", @class, @module) end it "should produce a better error message on unhandled exception" do @module.stubs(:add_class).raises(ArgumentError) lambda { @parser.document_class("mynode", @class, @module) }.should raise_error(Puppet::ParseError, /in file at line 42/) end end describe "when scanning for includes and requires" do def create_stmt(name) stmt_value = stub "#{name}_value", :to_s => "myclass" Puppet::Parser::AST::Function.new( :name => name, :arguments => [stmt_value], :doc => 'mydoc' ) end before(:each) do @class = stub_everything 'class' @code = stub_everything 'code' @code.stubs(:is_a?).with(Puppet::Parser::AST::ASTArray).returns(true) end it "should also scan mono-instruction code" do @class.expects(:add_include).with { |i| i.is_a?(RDoc::Include) and i.name == "myclass" and i.comment == "mydoc" } @parser.scan_for_include_or_require(@class, create_stmt("include")) end it "should register recursively includes to the current container" do @code.stubs(:children).returns([ create_stmt("include") ]) @class.expects(:add_include)#.with { |i| i.is_a?(RDoc::Include) and i.name == "myclass" and i.comment == "mydoc" } @parser.scan_for_include_or_require(@class, [@code]) end it "should register requires to the current container" do @code.stubs(:children).returns([ create_stmt("require") ]) @class.expects(:add_require).with { |i| i.is_a?(RDoc::Include) and i.name == "myclass" and i.comment == "mydoc" } @parser.scan_for_include_or_require(@class, [@code]) end end describe "when scanning for realized virtual resources" do def create_stmt stmt_value = stub "resource_ref", :to_s => "File[\"/tmp/a\"]" Puppet::Parser::AST::Function.new( :name => 'realize', :arguments => [stmt_value], :doc => 'mydoc' ) end before(:each) do @class = stub_everything 'class' @code = stub_everything 'code' @code.stubs(:is_a?).with(Puppet::Parser::AST::ASTArray).returns(true) end it "should also scan mono-instruction code" do @class.expects(:add_realize).with { |i| i.is_a?(RDoc::Include) and i.name == "File[\"/tmp/a\"]" and i.comment == "mydoc" } @parser.scan_for_realize(@class,create_stmt) end it "should register recursively includes to the current container" do @code.stubs(:children).returns([ create_stmt ]) @class.expects(:add_realize).with { |i| i.is_a?(RDoc::Include) and i.name == "File[\"/tmp/a\"]" and i.comment == "mydoc" } @parser.scan_for_realize(@class, [@code]) end end describe "when scanning for variable definition" do before :each do @class = stub_everything 'class' @stmt = stub_everything 'stmt', :name => "myvar", :value => "myvalue", :doc => "mydoc" @stmt.stubs(:is_a?).with(Puppet::Parser::AST::ASTArray).returns(false) @stmt.stubs(:is_a?).with(Puppet::Parser::AST::VarDef).returns(true) @code = stub_everything 'code' @code.stubs(:is_a?).with(Puppet::Parser::AST::ASTArray).returns(true) end it "should recursively register variables to the current container" do @code.stubs(:children).returns([ @stmt ]) @class.expects(:add_constant).with { |i| i.is_a?(RDoc::Constant) and i.name == "myvar" and i.comment == "mydoc" } @parser.scan_for_vardef(@class, [ @code ]) end it "should also scan mono-instruction code" do @class.expects(:add_constant).with { |i| i.is_a?(RDoc::Constant) and i.name == "myvar" and i.comment == "mydoc" } @parser.scan_for_vardef(@class, @stmt) end end describe "when scanning for resources" do before :each do @class = stub_everything 'class' @stmt = Puppet::Parser::AST::Resource.new( :type => "File", :instances => Puppet::Parser::AST::ASTArray.new(:children => [ Puppet::Parser::AST::ResourceInstance.new( :title => Puppet::Parser::AST::Name.new(:value => "myfile"), :parameters => Puppet::Parser::AST::ASTArray.new(:children => []) ) ]), :doc => 'mydoc' ) @code = stub_everything 'code' @code.stubs(:is_a?).with(Puppet::Parser::AST::ASTArray).returns(true) end it "should register a PuppetResource to the current container" do @code.stubs(:children).returns([ @stmt ]) @class.expects(:add_resource).with { |i| i.is_a?(RDoc::PuppetResource) and i.title == "myfile" and i.comment == "mydoc" } @parser.scan_for_resource(@class, [ @code ]) end it "should also scan mono-instruction code" do @class.expects(:add_resource).with { |i| i.is_a?(RDoc::PuppetResource) and i.title == "myfile" and i.comment == "mydoc" } @parser.scan_for_resource(@class, @stmt) end end describe "when parsing plugins" do before :each do @container = stub 'container' end it "should delegate parsing custom facts to parse_facts" do @parser = RDoc::Parser.new(@top_level, "module/manifests/lib/puppet/facter/test.rb", nil, Options.instance, RDoc::Stats.new) @parser.expects(:parse_fact).with(@container) @parser.parse_plugins(@container) end it "should delegate parsing plugins to parse_plugins" do @parser = RDoc::Parser.new(@top_level, "module/manifests/lib/puppet/functions/test.rb", nil, Options.instance, RDoc::Stats.new) @parser.expects(:parse_puppet_plugin).with(@container) @parser.parse_plugins(@container) end end describe "when parsing plugins" do before :each do @container = stub_everything 'container' end it "should add custom functions to the container" do File.stubs(:open).yields("# documentation module Puppet::Parser::Functions newfunction(:myfunc, :type => :rvalue) do |args| File.dirname(args[0]) end end".split("\n")) @container.expects(:add_plugin).with do |plugin| plugin.comment == "documentation\n" #and plugin.name == "myfunc" end @parser.parse_puppet_plugin(@container) end it "should add custom types to the container" do File.stubs(:open).yields("# documentation Puppet::Type.newtype(:mytype) do end".split("\n")) @container.expects(:add_plugin).with do |plugin| plugin.comment == "documentation\n" #and plugin.name == "mytype" end @parser.parse_puppet_plugin(@container) end end describe "when parsing facts" do before :each do @container = stub_everything 'container' File.stubs(:open).yields(["# documentation", "Facter.add('myfact') do", "confine :kernel => :linux", "end"]) end it "should add facts to the container" do @container.expects(:add_fact).with do |fact| fact.comment == "documentation\n" and fact.name == "myfact" end @parser.parse_fact(@container) end it "should add confine to the parsed facts" do ourfact = nil @container.expects(:add_fact).with do |fact| ourfact = fact true end @parser.parse_fact(@container) ourfact.confine.should == { :type => "kernel", :value => ":linux" } end end end diff --git a/spec/unit/util/rdoc_spec.rb b/spec/unit/util/rdoc_spec.rb index 93c4f9bfa..3b5248528 100755 --- a/spec/unit/util/rdoc_spec.rb +++ b/spec/unit/util/rdoc_spec.rb @@ -1,148 +1,148 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/rdoc' require 'rdoc/rdoc' describe Puppet::Util::RDoc do describe "when generating RDoc HTML documentation" do before :each do @rdoc = stub_everything 'rdoc' RDoc::RDoc.stubs(:new).returns(@rdoc) end it "should tell the parser to ignore import" do Puppet.expects(:[]=).with(:ignoreimport, true) Puppet::Util::RDoc.rdoc("output", []) end it "should install the Puppet HTML Generator into RDoc generators" do Puppet::Util::RDoc.rdoc("output", []) RDoc::RDoc::GENERATORS["puppet"].file_name.should == "puppet/util/rdoc/generators/puppet_generator.rb" end it "should tell RDoc to generate documentation using the Puppet generator" do @rdoc.expects(:document).with { |args| args.include?("--fmt") and args.include?("puppet") } Puppet::Util::RDoc.rdoc("output", []) end it "should tell RDoc to be quiet" do @rdoc.expects(:document).with { |args| args.include?("--quiet") } Puppet::Util::RDoc.rdoc("output", []) end it "should pass charset to RDoc" do @rdoc.expects(:document).with { |args| args.include?("--charset") and args.include?("utf-8") } Puppet::Util::RDoc.rdoc("output", [], "utf-8") end it "should tell RDoc to force updates of indices when RDoc supports it" do Options::OptionList.stubs(:options).returns([["--force-update", "-U", 0 ]]) @rdoc.expects(:document).with { |args| args.include?("--force-update") } Puppet::Util::RDoc.rdoc("output", []) end it "should not tell RDoc to force updates of indices when RDoc doesn't support it" do Options::OptionList.stubs(:options).returns([]) @rdoc.expects(:document).never.with { |args| args.include?("--force-update") } Puppet::Util::RDoc.rdoc("output", []) end it "should tell RDoc to use the given outputdir" do @rdoc.expects(:document).with { |args| args.include?("--op") and args.include?("myoutputdir") } Puppet::Util::RDoc.rdoc("myoutputdir", []) end it "should tell RDoc to exclude .pp files under any modules//files section" do @rdoc.expects(:document).with { |args| args.include?("--exclude") and args.include?("/modules/[^/]*/files/.*\.pp$") } Puppet::Util::RDoc.rdoc("myoutputdir", []) end it "should give all the source directories to RDoc" do @rdoc.expects(:document).with { |args| args.include?("sourcedir") } Puppet::Util::RDoc.rdoc("output", ["sourcedir"]) end end describe "when running a manifest documentation" do it "should tell the parser to ignore import" do Puppet.expects(:[]=).with(:ignoreimport, true) Puppet::Util::RDoc.manifestdoc([]) end it "should use a parser with the correct environment" do FileTest.stubs(:file?).returns(true) Puppet::Util::RDoc.stubs(:output) parser = stub_everything Puppet::Parser::Parser.stubs(:new).with{ |env| env.is_a?(Puppet::Node::Environment) }.returns(parser) parser.expects(:file=).with("file") parser.expects(:parse) Puppet::Util::RDoc.manifestdoc(["file"]) end it "should puppet parse all given files" do FileTest.stubs(:file?).returns(true) Puppet::Util::RDoc.stubs(:output) parser = stub_everything Puppet::Parser::Parser.stubs(:new).returns(parser) parser.expects(:file=).with("file") parser.expects(:parse) Puppet::Util::RDoc.manifestdoc(["file"]) end it "should call output for each parsed file" do FileTest.stubs(:file?).returns(true) ast = stub_everything parser = stub_everything Puppet::Parser::Parser.stubs(:new).returns(parser) parser.stubs(:parse).returns(ast) Puppet::Util::RDoc.expects(:output).with("file", ast) Puppet::Util::RDoc.manifestdoc(["file"]) end describe "when outputing documentation" do it "should output doc for ast classes, nodes and definitions in order of increasing line number" do byline = sequence('documentation outputs in line order') Puppet::Util::RDoc.expects(:puts).with("im a class\n").in_sequence(byline) Puppet::Util::RDoc.expects(:puts).with("im a node\n").in_sequence(byline) Puppet::Util::RDoc.expects(:puts).with("im a define\n").in_sequence(byline) # any other output must fail Puppet::Util::RDoc.manifestdoc([my_fixture('basic.pp')]) end it "should output resource documentation if needed" do pending "#6634 being fixed" Puppet.settings[:document_all] = true byline = sequence('documentation outputs in line order') Puppet::Util::RDoc.expects(:puts).with("im a class\n").in_sequence(byline) Puppet::Util::RDoc.expects(:puts).with("im a node\n").in_sequence(byline) Puppet::Util::RDoc.expects(:puts).with("im a define\n").in_sequence(byline) Puppet::Util::RDoc.expects(:puts).with("im a resource\n").in_sequence(byline) # any other output must fail Puppet::Util::RDoc.manifestdoc([my_fixture('basic.pp')]) end end end end diff --git a/spec/unit/util/user_attr_spec.rb b/spec/unit/util/user_attr_spec.rb index 61312ef19..5acdaee58 100644 --- a/spec/unit/util/user_attr_spec.rb +++ b/spec/unit/util/user_attr_spec.rb @@ -1,47 +1,47 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/user_attr' describe UserAttr do before do user_attr = ["foo::::type=role", "bar::::type=normal;profile=foobar"] File.stubs(:readlines).returns(user_attr) end describe "when getting attributes by name" do it "should return nil if there is no entry for that name" do UserAttr.get_attributes_by_name('baz').should == nil end it "should return a hash if there is an entry in /etc/user_attr" do UserAttr.get_attributes_by_name('foo').class.should == Hash end it "should return a hash with the name value from /etc/user_attr" do UserAttr.get_attributes_by_name('foo')[:name].should == 'foo' end #this test is contrived #there are a bunch of possible parameters that could be in the hash #the role/normal is just a the convention of the file describe "when the name is a role" do it "should contain :type = role" do UserAttr.get_attributes_by_name('foo')[:type].should == 'role' end end describe "when the name is not a role" do it "should contain :type = normal" do UserAttr.get_attributes_by_name('bar')[:type].should == 'normal' end end describe "when the name has more attributes" do it "should contain all the attributes" do UserAttr.get_attributes_by_name('bar')[:profile].should == 'foobar' end end end end diff --git a/spec/unit/util/zaml_spec.rb b/spec/unit/util/zaml_spec.rb index 358c6aa11..804aa8e58 100755 --- a/spec/unit/util/zaml_spec.rb +++ b/spec/unit/util/zaml_spec.rb @@ -1,63 +1,63 @@ #!/usr/bin/env ruby -Dir.chdir(File.dirname(__FILE__)) { (s = lambda { |f| File.exist?(f) ? require(f) : Dir.chdir("..") { s.call(f) } }).call("spec/spec_helper.rb") } +require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') require 'puppet/util/monkey_patches' describe "Pure ruby yaml implementation" do { 7 => "--- 7", 3.14159 => "--- 3.14159", 'test' => "--- test", [] => "--- []", :symbol => "--- !ruby/sym symbol", {:a => "A"} => "--- \n !ruby/sym a: A", {:a => "x\ny"} => "--- \n !ruby/sym a: |-\n x\n y" }.each { |o,y| it "should convert the #{o.class} #{o.inspect} to yaml" do o.to_yaml.should == y end it "should produce yaml for the #{o.class} #{o.inspect} that can be reconstituted" do YAML.load(o.to_yaml).should == o end } # # Can't test for equality on raw objects { Object.new => "--- !ruby/object {}", [Object.new] => "--- \n - !ruby/object {}", {Object.new => Object.new} => "--- \n ? !ruby/object {}\n : !ruby/object {}" }.each { |o,y| it "should convert the #{o.class} #{o.inspect} to yaml" do o.to_yaml.should == y end it "should produce yaml for the #{o.class} #{o.inspect} that can be reconstituted" do lambda { YAML.load(o.to_yaml) }.should_not raise_error end } it "should emit proper labels and backreferences for common objects" do # Note: this test makes assumptions about the names ZAML chooses # for labels. x = [1, 2] y = [3, 4] z = [x, y, x, y] z.to_yaml.should == "--- \n - &id001\n - 1\n - 2\n - &id002\n - 3\n - 4\n - *id001\n - *id002" z2 = YAML.load(z.to_yaml) z2.should == z z2[0].should equal(z2[2]) z2[1].should equal(z2[3]) end it "should emit proper labels and backreferences for recursive objects" do x = [1, 2] x << x x.to_yaml.should == "--- &id001\n \n - 1\n - 2\n - *id001" x2 = YAML.load(x.to_yaml) x2.should be_a(Array) x2.length.should == 3 x2[0].should == 1 x2[1].should == 2 x2[2].should equal(x2) end end diff --git a/tasks/rake/gem.rake b/tasks/rake/gem.rake index d654886ae..efea73882 100644 --- a/tasks/rake/gem.rake +++ b/tasks/rake/gem.rake @@ -1,59 +1,60 @@ -require 'ftools' +require 'fileutils' GEM_FILES = FileList[ '[A-Z]*', 'install.rb', 'bin/**/*', 'lib/**/*', 'conf/**/*', 'man/**/*', 'examples/**/*', 'ext/**/*', 'tasks/**/*', 'test/**/*', 'spec/**/*' ] EXECUTABLES = FileList[ 'bin/**/*', 'sbin/**/*' ] SBIN = Dir.glob("sbin/*") spec = Gem::Specification.new do |spec| spec.platform = Gem::Platform::RUBY spec.name = 'puppet' spec.files = GEM_FILES.to_a spec.executables = EXECUTABLES.gsub(/sbin\/|bin\//, '').to_a spec.version = Puppet::PUPPETVERSION spec.add_dependency('facter', '>= 1.5.1') spec.summary = 'Puppet, an automated configuration management tool' spec.description = 'Puppet, an automated configuration management tool' spec.author = 'Puppet Labs' spec.email = 'puppet@puppetlabs.com' spec.homepage = 'http://puppetlabs.com' spec.rubyforge_project = 'puppet' spec.has_rdoc = true spec.rdoc_options << '--title' << 'Puppet - Configuration Management' << '--main' << 'README' << '--line-numbers' end desc "Prepare binaries for gem creation" task :prepare_gem do SBIN.each do |f| - File.copy(f,"bin") + FileUtils.copy(f,"bin") end end desc "Create the gem" task :create_gem => :prepare_gem do Dir.mkdir("pkg") rescue nil Gem::Builder.new(spec).build - File.move("puppet-#{Puppet::PUPPETVERSION}.gem", "pkg") + FileUtils.move("puppet-#{Puppet::PUPPETVERSION}.gem", "pkg") SBIN.each do |f| - File.unlink("bin/" + f.gsub(/sbin\//, '')) + fn = f.gsub(/sbin\/(.*)/, '\1') + FileUtils.rm_r "bin/" + fn end end diff --git a/tasks/rake/git_workflow.rake b/tasks/rake/git_workflow.rake index 1ba57c1aa..75dc8833a 100644 --- a/tasks/rake/git_workflow.rake +++ b/tasks/rake/git_workflow.rake @@ -1,132 +1,132 @@ # This set of tasks helps automate the workflow as described on # http://projects.puppetlabs.com/projects/puppet/wiki/Development_Lifecycle def find_start(start) # This is a case statement, as we might want to map certain # git tags to starting points that are not currently in git. - case start - when nil?: - when @next_release: return "master" - else return start - end + case start + when nil?; + when @next_release; return "master" + else return start + end end desc "Set up git for working with Puppet" task :git_setup do - # This should be changed as new versions get released - @next_release = '0.26.x' - @remote = {} - default_remote = {} - default_remote[:url] = 'git://github.com/reductivelabs/puppet' - default_remote[:name] = 'origin' - @remote[:name] = %x{git config puppet.defaultremote}.chomp - @remote[:name] = @remote[:name].empty? ? default_remote[:name] : @remote[:name] - @remote[:url] = default_remote[:url] if @remote[:name] == default_remote[:name] - default_fetch = '+refs/heads/*:refs/remotes/puppet/*' - @remote[:fetch] = %x{git config puppet.#{@remote[:name]}.fetch}.chomp - @remote[:fetch] = @remote[:fetch].empty? ? default_fetch : @remote[:fetch] + # This should be changed as new versions get released + @next_release = '0.26.x' + @remote = {} + default_remote = {} + default_remote[:url] = 'git://github.com/reductivelabs/puppet' + default_remote[:name] = 'origin' + @remote[:name] = %x{git config puppet.defaultremote}.chomp + @remote[:name] = @remote[:name].empty? ? default_remote[:name] : @remote[:name] + @remote[:url] = default_remote[:url] if @remote[:name] == default_remote[:name] + default_fetch = '+refs/heads/*:refs/remotes/puppet/*' + @remote[:fetch] = %x{git config puppet.#{@remote[:name]}.fetch}.chomp + @remote[:fetch] = @remote[:fetch].empty? ? default_fetch : @remote[:fetch] end desc "Start work on a feature" task :start_feature, [:feature,:remote,:branch] => :git_setup do |t, args| - args.with_defaults(:remote => @remote[:name]) - args.with_defaults(:branch => @next_release) - start_at = find_start(args.branch) - branch = "feature/#{start_at}/#{args.feature}" - sh "git checkout -b #{branch} #{start_at}" do |ok, res| - if ! ok - raise < @remote[:name]) + args.with_defaults(:branch => @next_release) + start_at = find_start(args.branch) + branch = "feature/#{start_at}/#{args.feature}" + sh "git checkout -b #{branch} #{start_at}" do |ok, res| + if ! ok + raise < :git_setup do |t, args| - args.with_defaults(:remote => @remote[:name]) - args.with_defaults(:branch => @next_release) - start_at = find_start(args.branch) - branch = "tickets/#{start_at}/#{args.ticket}" - sh "git checkout -b #{branch} #{start_at}" do |ok, res| - unless ok - raise < @remote[:name]) + args.with_defaults(:branch => @next_release) + start_at = find_start(args.branch) + branch = "tickets/#{start_at}/#{args.ticket}" + sh "git checkout -b #{branch} #{start_at}" do |ok, res| + unless ok + raise < 0 raise "Patches already exist matching '00*.patch'; clean up first" end unless %x{git status} =~ /On branch (.+)/ raise "Could not get branch from 'git status'" end branch = $1 unless branch =~ %r{^([^\/]+)/([^\/]+)/([^\/]+)$} raise "Branch name does not follow // model; cannot autodetect parent branch" end type, parent, name = $1, $2, $3 # Create all of the patches sh "git format-patch -C -M -s -n --subject-prefix='PATCH/puppet' #{parent}..HEAD" # Add info to the patches additional_info = "Local-branch: #{branch}\n" files = Dir.glob("00*.patch") files.each do |file| contents = File.read(file) contents.sub!(/^---\n/, "---\n#{additional_info}") File.open(file, 'w') do |file_handle| file_handle.print contents end end # And then mail them out. # If we've got more than one patch, add --compose if files.length > 1 compose = "--compose" else compose = "" end # Now send the mail. sh "git send-email #{compose} --no-signed-off-by-cc --suppress-from --to puppet-dev@googlegroups.com 00*.patch" # Finally, clean up the patches sh "rm 00*.patch" end diff --git a/test/ral/type/exec.rb b/test/ral/type/exec.rb index 829b1a068..0831d466d 100755 --- a/test/ral/type/exec.rb +++ b/test/ral/type/exec.rb @@ -1,804 +1,717 @@ #!/usr/bin/env ruby require File.expand_path(File.dirname(__FILE__) + '/../../lib/puppettest') require 'puppettest' class TestExec < Test::Unit::TestCase include PuppetTest def test_numvsstring [0, "0"].each { |val| command = nil output = nil assert_nothing_raised { command = Puppet::Type.type(:exec).new( :command => "/bin/echo", :returns => val ) } assert_events([:executed_command], command) } end def test_path_or_qualified command = nil output = nil assert_raise(Puppet::Error) { command = Puppet::Type.type(:exec).new( :command => "echo" ) } assert_nothing_raised { command = Puppet::Type.type(:exec).new( - :command => "echo", - - :path => "/usr/bin:/bin:/usr/sbin:/sbin" + :path => "/usr/bin:/bin:/usr/sbin:/sbin" ) } assert_nothing_raised { command = Puppet::Type.type(:exec).new( :command => "/bin/echo" ) } assert_nothing_raised { command = Puppet::Type.type(:exec).new( - :command => "/bin/echo", - - :path => "/usr/bin:/bin:/usr/sbin:/sbin" + :path => "/usr/bin:/bin:/usr/sbin:/sbin" ) } end def test_nonzero_returns assert_nothing_raised { command = Puppet::Type.type(:exec).new( - :command => "mkdir /this/directory/does/not/exist", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - + :path => "/usr/bin:/bin:/usr/sbin:/sbin", :returns => 1 ) } assert_nothing_raised { command = Puppet::Type.type(:exec).new( - :command => "touch /etc", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - + :path => "/usr/bin:/bin:/usr/sbin:/sbin", :returns => 1 ) } assert_nothing_raised { command = Puppet::Type.type(:exec).new( - :command => "thiscommanddoesnotexist", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - + :path => "/usr/bin:/bin:/usr/sbin:/sbin", :returns => 127 ) } end def test_cwdsettings command = nil dir = "/tmp" wd = Dir.chdir(dir) { Dir.getwd } assert_nothing_raised { command = Puppet::Type.type(:exec).new( - :command => "pwd", - :cwd => dir, - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - + :cwd => dir, + :path => "/usr/bin:/bin:/usr/sbin:/sbin", :returns => 0 ) } assert_events([:executed_command], command) assert_equal(wd,command.output.chomp) end def test_refreshonly_functional file = nil cmd = nil tmpfile = tempfile @@tmpfiles.push tmpfile trans = nil - file = Puppet::Type.type(:file).new( - - :path => tmpfile, - - :content => "yay" + file = Puppet::Type.type(:file).new( + :path => tmpfile, + :content => "yay" ) # Get the file in sync assert_apply(file) # Now make an exec maker = tempfile assert_nothing_raised { - cmd = Puppet::Type.type(:exec).new( - - :command => "touch #{maker}", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :subscribe => file, - + :command => "touch #{maker}", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :subscribe => file, :refreshonly => true ) } assert(cmd, "did not make exec") assert_nothing_raised do - assert(! cmd.check, "Check passed when refreshonly is set") + assert(! cmd.check_all_attributes, "Check passed when refreshonly is set") end assert_events([], file, cmd) assert(! FileTest.exists?(maker), "made file without refreshing") # Now change our content, so we throw a refresh file[:content] = "yayness" assert_events([:content_changed, :restarted], file, cmd) assert(FileTest.exists?(maker), "file was not made in refresh") end def test_refreshonly cmd = true assert_nothing_raised { - cmd = Puppet::Type.type(:exec).new( - - :command => "pwd", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - + :command => "pwd", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", :refreshonly => true ) } # Checks should always fail when refreshonly is enabled - assert(!cmd.check, "Check passed with refreshonly true") + assert(!cmd.check_all_attributes, "Check passed with refreshonly true") # Now make sure it passes if we pass in "true" - assert(cmd.check(true), "Check failed with refreshonly true while refreshing") + assert(cmd.check_all_attributes(true), "Check failed with refreshonly true while refreshing") # Now set it to false cmd[:refreshonly] = false - assert(cmd.check, "Check failed with refreshonly false") + assert(cmd.check_all_attributes, "Check failed with refreshonly false") end def test_creates file = tempfile exec = nil assert(! FileTest.exists?(file), "File already exists") assert_nothing_raised { exec = Puppet::Type.type(:exec).new( - :command => "touch #{file}", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - + :path => "/usr/bin:/bin:/usr/sbin:/sbin", :creates => file ) } comp = mk_catalog("createstest", exec) assert_events([:executed_command], comp, "creates") assert_events([], comp, "creates") end # Verify that we can download the file that we're going to execute. def test_retrievethenmkexe exe = tempfile oexe = tempfile sh = %x{which sh} File.open(exe, "w") { |f| f.puts "#!#{sh}\necho yup" } - - file = Puppet::Type.type(:file).new( - - :path => oexe, - :source => exe, - - :mode => 0755 + file = Puppet::Type.type(:file).new( + :path => oexe, + :source => exe, + :mode => 0755 ) - - exec = Puppet::Type.type(:exec).new( - - :command => oexe, - - :require => Puppet::Resource.new(:file, oexe) + exec = Puppet::Type.type(:exec).new( + :command => oexe, + :require => Puppet::Resource.new(:file, oexe) ) comp = mk_catalog("Testing", file, exec) assert_events([:file_created, :executed_command], comp) end # Verify that we auto-require any managed scripts. def test_autorequire_files exe = tempfile oexe = tempfile sh = %x{which sh} File.open(exe, "w") { |f| f.puts "#!#{sh}\necho yup" } - file = Puppet::Type.type(:file).new( - - :path => oexe, - :source => exe, - - :mode => 755 + file = Puppet::Type.type(:file).new( + :path => oexe, + :source => exe, + :mode => 755 ) basedir = File.dirname(oexe) - baseobj = Puppet::Type.type(:file).new( - - :path => basedir, - :source => exe, - - :mode => 755 + baseobj = Puppet::Type.type(:file).new( + :path => basedir, + :source => exe, + :mode => 755 ) - ofile = Puppet::Type.type(:file).new( - - :path => exe, - - :mode => 755 + ofile = Puppet::Type.type(:file).new( + :path => exe, + :mode => 755 ) - exec = Puppet::Type.type(:exec).new( - - :command => oexe, - :path => ENV["PATH"], - - :cwd => basedir + exec = Puppet::Type.type(:exec).new( + :command => oexe, + :path => ENV["PATH"], + :cwd => basedir ) - - cat = Puppet::Type.type(:exec).new( - - :command => "cat #{exe} #{oexe}", - - :path => ENV["PATH"] + cat = Puppet::Type.type(:exec).new( + :command => "cat #{exe} #{oexe}", + :path => ENV["PATH"] ) catalog = mk_catalog(file, baseobj, ofile, exec, cat) rels = nil assert_nothing_raised do rels = exec.autorequire end # Verify we get the script itself assert(rels.detect { |r| r.source == file }, "Exec did not autorequire its command") # Verify we catch the cwd assert(rels.detect { |r| r.source == baseobj }, "Exec did not autorequire its cwd") # Verify we don't require ourselves assert(! rels.detect { |r| r.source == ofile }, "Exec incorrectly required mentioned file") # We not longer autorequire inline files assert_nothing_raised do rels = cat.autorequire end assert(! rels.detect { |r| r.source == ofile }, "Exec required second inline file") assert(! rels.detect { |r| r.source == file }, "Exec required inline file") end def test_ifonly afile = tempfile bfile = tempfile exec = nil assert_nothing_raised { exec = Puppet::Type.type(:exec).new( - :command => "touch #{bfile}", - :onlyif => "test -f #{afile}", - - :path => ENV['PATH'] + :onlyif => "test -f #{afile}", + :path => ENV['PATH'] ) } assert_events([], exec) system("touch #{afile}") assert_events([:executed_command], exec) assert_events([:executed_command], exec) system("rm #{afile}") assert_events([], exec) end def test_unless afile = tempfile bfile = tempfile exec = nil assert_nothing_raised { - exec = Puppet::Type.type(:exec).new( - :command => "touch #{bfile}", :unless => "test -f #{afile}", - :path => ENV['PATH'] ) } comp = mk_catalog(exec) assert_events([:executed_command], comp) assert_events([:executed_command], comp) system("touch #{afile}") assert_events([], comp) assert_events([], comp) system("rm #{afile}") assert_events([:executed_command], comp) assert_events([:executed_command], comp) end if Puppet.features.root? # Verify that we can execute commands as a special user def mknverify(file, user, group = nil, id = true) File.umask(0022) args = { :command => "touch #{file}", :path => "/usr/bin:/bin:/usr/sbin:/sbin", } if user #Puppet.warning "Using user #{user.name}" if id # convert to a string, because that's what the object expects args[:user] = user.uid.to_s else args[:user] = user.name end end if group #Puppet.warning "Using group #{group.name}" if id args[:group] = group.gid.to_s else args[:group] = group.name end end exec = nil assert_nothing_raised { exec = Puppet::Type.type(:exec).new(args) } comp = mk_catalog("usertest", exec) assert_events([:executed_command], comp, "usertest") assert(FileTest.exists?(file), "File does not exist") assert_equal(user.uid, File.stat(file).uid, "File UIDs do not match") if user # We can't actually test group ownership, unfortunately, because # behaviour changes wildlly based on platform. Puppet::Type.allclear end def test_userngroup file = tempfile [ [nonrootuser], # just user, by name [nonrootuser, nil, true], # user, by uid [nil, nonrootgroup], # just group [nil, nonrootgroup, true], # just group, by id [nonrootuser, nonrootgroup], # user and group, by name [nonrootuser, nonrootgroup, true], # user and group, by id ].each { |ary| mknverify(file, *ary) { } } end end def test_logoutput exec = nil assert_nothing_raised { - exec = Puppet::Type.type(:exec).new( - - :title => "logoutputesting", - :path => "/usr/bin:/bin", - :command => "echo logoutput is false", - + :title => "logoutputesting", + :path => "/usr/bin:/bin", + :command => "echo logoutput is false", :logoutput => false ) } assert_apply(exec) assert_nothing_raised { exec[:command] = "echo logoutput is true" exec[:logoutput] = true } assert_apply(exec) assert_nothing_raised { exec[:command] = "echo logoutput is on_failure" exec[:logoutput] = "on_failure" } assert_apply(exec) end def test_execthenfile exec = nil file = nil basedir = tempfile path = File.join(basedir, "subfile") assert_nothing_raised { exec = Puppet::Type.type(:exec).new( - - :title => "mkdir", - :path => "/usr/bin:/bin", + :title => "mkdir", + :path => "/usr/bin:/bin", :creates => basedir, - :command => "mkdir #{basedir}; touch #{path}" - ) } assert_nothing_raised { file = Puppet::Type.type(:file).new( - - :path => basedir, + :path => basedir, :recurse => true, - :mode => "755", - + :mode => "755", :require => Puppet::Resource.new("exec", "mkdir") ) } comp = mk_catalog(file, exec) comp.finalize assert_events([:executed_command, :mode_changed], comp) assert(FileTest.exists?(path), "Exec ran first") assert(File.stat(path).mode & 007777 == 0755) end # Make sure all checks need to be fully qualified. def test_falsevals exec = nil assert_nothing_raised do exec = Puppet::Type.type(:exec).new( :command => "/bin/touch yayness" ) end Puppet::Type.type(:exec).checks.each do |check| klass = Puppet::Type.type(:exec).paramclass(check) next if klass.value_collection.values.include? :false assert_raise(Puppet::Error, "Check '#{check}' did not fail on false") do exec[check] = false end end end def test_createcwdandexe exec1 = exec2 = nil dir = tempfile file = tempfile assert_nothing_raised { - exec1 = Puppet::Type.type(:exec).new( - - :title => "one", - :path => ENV["PATH"], - + :title => "one", + :path => ENV["PATH"], :command => "mkdir #{dir}" ) } assert_nothing_raised("Could not create exec w/out existing cwd") { exec2 = Puppet::Type.type(:exec).new( - - :title => "two", - :path => ENV["PATH"], + :title => "two", + :path => ENV["PATH"], :command => "touch #{file}", - - :cwd => dir + :cwd => dir ) } # Throw a check in there with our cwd and make sure it works assert_nothing_raised("Could not check with a missing cwd") do exec2[:unless] = "test -f /this/file/does/not/exist" exec2.retrieve end assert_raise(Puppet::Error) do exec2.property(:returns).sync end assert_nothing_raised do exec2[:require] = exec1 end assert_apply(exec1, exec2) assert(FileTest.exists?(file)) end def test_checkarrays exec = nil file = tempfile test = "test -f #{file}" assert_nothing_raised { - exec = Puppet::Type.type(:exec).new( - - :path => ENV["PATH"], - + :path => ENV["PATH"], :command => "touch #{file}" ) } assert_nothing_raised { exec[:unless] = test } assert_nothing_raised { - assert(exec.check, "Check did not pass") + assert(exec.check_all_attributes, "Check did not pass") } assert_nothing_raised { exec[:unless] = [test, test] } assert_nothing_raised { exec.finish } assert_nothing_raised { - assert(exec.check, "Check did not pass") + assert(exec.check_all_attributes, "Check did not pass") } assert_apply(exec) assert_nothing_raised { - assert(! exec.check, "Check passed") + assert(! exec.check_all_attributes, "Check passed") } end def test_missing_checks_cause_failures # Solaris's sh exits with 1 here instead of 127 return if Facter.value(:operatingsystem) == "Solaris" exec = Puppet::Type.type(:exec).new( - :command => "echo true", - :path => ENV["PATH"], - - :onlyif => "/bin/nosuchthingexists" - ) + :path => ENV["PATH"], + :onlyif => "/bin/nosuchthingexists" + ) assert_raise(ArgumentError, "Missing command did not raise error") { - exec.run("/bin/nosuchthingexists") + exec.provider.run("/bin/nosuchthingexists") } end def test_environmentparam exec = Puppet::Type.newexec( - - :command => "echo $environmenttest", - :path => ENV["PATH"], - + :command => "echo $environmenttest", + :path => ENV["PATH"], :environment => "environmenttest=yayness" ) assert(exec, "Could not make exec") output = status = nil assert_nothing_raised { - output, status = exec.run("echo $environmenttest") + output, status = exec.provider.run("echo $environmenttest") } assert_equal("yayness\n", output) # Now check whether we can do multiline settings assert_nothing_raised do exec[:environment] = "environmenttest=a list of things and stuff" end output = status = nil assert_nothing_raised { - output, status = exec.run('echo "$environmenttest"') + output, status = exec.provider.run('echo "$environmenttest"') } assert_equal("a list of things\nand stuff\n", output) # Now test arrays assert_nothing_raised do exec[:environment] = ["funtest=A", "yaytest=B"] end output = status = nil assert_nothing_raised { - output, status = exec.run('echo "$funtest" "$yaytest"') + output, status = exec.provider.run('echo "$funtest" "$yaytest"') } assert_equal("A B\n", output) end - def test_timeout - exec = Puppet::Type.type(:exec).new(:command => "sleep 1", :path => ENV["PATH"], :timeout => "0.2") - time = Time.now - - assert_raise(Timeout::Error) { - exec.run("sleep 1") - } - Puppet.info "#{Time.now.to_f - time.to_f} seconds, vs a timeout of #{exec[:timeout]}" - - - assert_apply(exec) - end - # Testing #470 def test_run_as_created_user exec = nil if Process.uid == 0 user = "nosuchuser" assert_nothing_raised("Could not create exec with non-existent user") do - exec = Puppet::Type.type(:exec).new( - :command => "/bin/echo yay", - - :user => user + :user => user ) end end # Now try the group group = "nosuchgroup" assert_nothing_raised("Could not create exec with non-existent user") do exec = Puppet::Type.type(:exec).new( - :command => "/bin/echo yay", - - :group => group + :group => group ) end end # make sure paths work both as arrays and strings def test_paths_as_arrays path = %w{/usr/bin /usr/sbin /sbin} exec = nil assert_nothing_raised("Could not use an array for the path") do exec = Puppet::Type.type(:exec).new(:command => "echo yay", :path => path) end assert_equal(path, exec[:path], "array-based path did not match") assert_nothing_raised("Could not use a string for the path") do exec = Puppet::Type.type(:exec).new(:command => "echo yay", :path => path.join(":")) end assert_equal(path, exec[:path], "string-based path did not match") assert_nothing_raised("Could not use a colon-separated strings in an array for the path") do exec = Puppet::Type.type(:exec).new(:command => "echo yay", :path => ["/usr/bin", "/usr/sbin:/sbin"]) end assert_equal(path, exec[:path], "colon-separated array path did not match") end def test_checks_apply_to_refresh file = tempfile maker = tempfile - exec = Puppet::Type.type(:exec).new( - - :title => "maker", - :command => "touch #{maker}", - - :path => ENV["PATH"] + exec = Puppet::Type.type(:exec).new( + :title => "maker", + :command => "touch #{maker}", + :path => ENV["PATH"] ) # Make sure it runs normally assert_apply(exec) assert(FileTest.exists?(maker), "exec did not run") File.unlink(maker) # Now make sure it refreshes assert_nothing_raised("Failed to refresh exec") do exec.refresh end assert(FileTest.exists?(maker), "exec did not run refresh") File.unlink(maker) # Now add the checks exec[:creates] = file # Make sure it runs when the file doesn't exist assert_nothing_raised("Failed to refresh exec") do exec.refresh end assert(FileTest.exists?(maker), "exec did not refresh when checks passed") File.unlink(maker) # Now create the file and make sure it doesn't refresh File.open(file, "w") { |f| f.puts "" } assert_nothing_raised("Failed to refresh exec") do exec.refresh end assert(! FileTest.exists?(maker), "exec refreshed with failing checks") end def test_explicit_refresh refresher = tempfile maker = tempfile - exec = Puppet::Type.type(:exec).new( - - :title => "maker", - :command => "touch #{maker}", - - :path => ENV["PATH"] + exec = Puppet::Type.type(:exec).new( + :title => "maker", + :command => "touch #{maker}", + :path => ENV["PATH"] ) # Call refresh normally assert_nothing_raised do exec.refresh end # Make sure it created the normal file assert(FileTest.exists?(maker), "normal refresh did not work") File.unlink(maker) # Now reset refresh, and make sure it wins assert_nothing_raised("Could not set refresh parameter") do exec[:refresh] = "touch #{refresher}" end assert_nothing_raised do exec.refresh end # Make sure it created the normal file assert(FileTest.exists?(refresher), "refresh param was ignored") assert(! FileTest.exists?(maker), "refresh param also ran command") end if Puppet.features.root? def test_autorequire_user user = Puppet::Type.type(:user).new(:name => "yay") exec = Puppet::Type.type(:exec).new(:command => "/bin/echo fun", :user => "yay") rels = nil assert_nothing_raised("Could not evaluate autorequire") do rels = exec.autorequire end assert(rels.find { |r| r.source == user and r.target == exec }, "Exec did not autorequire user") end end end -