From 1756bec99b9136463e5d35f1de4119b813ce40cc Mon Sep 17 00:00:00 2001 From: luke Date: Thu, 8 Feb 2007 05:11:49 +0000 Subject: Fixing #484. Moving unit tests at the same time. git-svn-id: https://reductivelabs.com/svn/puppet/trunk@2181 980ebf18-57e1-0310-9a29-db15c13687c0 --- lib/puppet/util/config.rb | 9 +- test/lib/puppettest.rb | 5 + test/other/autoload.rb | 130 ------- test/other/config.rb | 937 --------------------------------------------- test/other/features.rb | 94 ----- test/other/filetype.rb | 92 ----- test/other/inifile.rb | 126 ------ test/other/loadedfile.rb | 106 ----- test/other/log.rb | 286 -------------- test/other/metrics.rb | 81 ---- test/other/storage.rb | 123 ------ test/util/autoload.rb | 130 +++++++ test/util/config.rb | 958 ++++++++++++++++++++++++++++++++++++++++++++++ test/util/features.rb | 94 +++++ test/util/filetype.rb | 92 +++++ test/util/inifile.rb | 126 ++++++ test/util/loadedfile.rb | 106 +++++ test/util/log.rb | 286 ++++++++++++++ test/util/metrics.rb | 81 ++++ test/util/storage.rb | 123 ++++++ 20 files changed, 2009 insertions(+), 1976 deletions(-) delete mode 100755 test/other/autoload.rb delete mode 100755 test/other/config.rb delete mode 100755 test/other/features.rb delete mode 100755 test/other/filetype.rb delete mode 100755 test/other/inifile.rb delete mode 100755 test/other/loadedfile.rb delete mode 100755 test/other/log.rb delete mode 100755 test/other/metrics.rb delete mode 100755 test/other/storage.rb create mode 100755 test/util/autoload.rb create mode 100755 test/util/config.rb create mode 100755 test/util/features.rb create mode 100755 test/util/filetype.rb create mode 100755 test/util/inifile.rb create mode 100755 test/util/loadedfile.rb create mode 100755 test/util/log.rb create mode 100755 test/util/metrics.rb create mode 100755 test/util/storage.rb diff --git a/lib/puppet/util/config.rb b/lib/puppet/util/config.rb index 097d59b9f..b94b84051 100644 --- a/lib/puppet/util/config.rb +++ b/lib/puppet/util/config.rb @@ -39,7 +39,7 @@ class Puppet::Util::Config param = symbolize(param) unless @config.include?(param) raise Puppet::Error, - "Unknown configuration parameter %s" % param.inspect + "Attempt to assign a value to unknown configuration parameter %s" % param.inspect end unless @order.include?(param) @order << param @@ -283,6 +283,13 @@ class Puppet::Util::Config var = $1.intern value = mungearg($2) + # Only warn if we don't know what this config var is. This + # prevents exceptions later on. + unless @config.include?(var) or metas.include?(var.to_s) + Puppet.warning "Discarded unknown configuration parameter %s" % var.inspect + next # Skip this line. + end + # Mmm, "special" attributes if metas.include?(var.to_s) unless values.include?(section) diff --git a/test/lib/puppettest.rb b/test/lib/puppettest.rb index 6d19ba983..99794bc3b 100755 --- a/test/lib/puppettest.rb +++ b/test/lib/puppettest.rb @@ -269,6 +269,11 @@ module PuppetTest exit(74) end end + + def logstore + @logs = [] + Puppet::Util::Log.newdestination(@logs) + end end require 'puppettest/support' diff --git a/test/other/autoload.rb b/test/other/autoload.rb deleted file mode 100755 index 34f40df24..000000000 --- a/test/other/autoload.rb +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppet/util/autoload' -require 'puppettest' - -class TestAutoload < Test::Unit::TestCase - include PuppetTest - @things = [] - def self.newthing(name) - @things << name - end - - def self.thing?(name) - @things.include? name - end - - def self.clear - @things.clear - end - - def mkfile(name, path) - # Now create a file to load - File.open(path, "w") do |f| - f.puts %{ -TestAutoload.newthing(:#{name.to_s}) - } - end - end - - def teardown - super - self.class.clear - end - - def test_load - dir = tempfile() - $: << dir - cleanup do - $:.delete(dir) - end - - Dir.mkdir(dir) - - rbdir = File.join(dir, "yayness") - - Dir.mkdir(rbdir) - - # An object for specifying autoload - klass = self.class - - loader = nil - assert_nothing_raised { - loader = Puppet::Util::Autoload.new(klass, :yayness) - } - - assert_equal(loader.object_id, Puppet::Util::Autoload[klass].object_id, - "Did not retrieve loader object by class") - - # Make sure we don't fail on missing files - assert_nothing_raised { - assert_equal(false, loader.load(:mything), - "got incorrect return on failed load") - } - - # Now create a couple of files for testing - path = File.join(rbdir, "mything.rb") - mkfile(:mything, path) - opath = File.join(rbdir, "othing.rb") - mkfile(:othing, opath) - - # Now try to actually load it. - assert_nothing_raised { - assert_equal(true, loader.load(:mything), - "got incorrect return on failed load") - } - - assert(loader.loaded?(:mything), "Not considered loaded") - - assert(klass.thing?(:mything), - "Did not get loaded thing") - - # Now clear everything, and test loadall - assert_nothing_raised { - loader.clear - } - - self.class.clear - - assert_nothing_raised { - loader.loadall - } - - [:mything, :othing].each do |thing| - assert(loader.loaded?(thing), "#{thing.to_s} not considered loaded") - - assert(klass.thing?(thing), - "Did not get loaded #{thing.to_s}") - end - end - - # Make sure that autoload dynamically modifies $: with the libdir as - # appropriate. - def test_autoload_uses_libdir - dir = Puppet[:libdir] - unless FileTest.directory?(dir) - Dir.mkdir(dir) - end - - loader = File.join(dir, "test") - Dir.mkdir(loader) - name = "funtest" - file = File.join(loader, "funtest.rb") - File.open(file, "w") do |f| - f.puts "$loaded = true" - end - - auto = Puppet::Util::Autoload.new(self, "test") - - # Now make sure autoloading modifies $: as necessary - assert(! $:.include?(dir), "search path already includes libdir") - - assert_nothing_raised do - assert(auto.load("funtest"), "did not successfully load funtest") - end - assert($:.include?(dir), "libdir did not get added to search path") - end -end diff --git a/test/other/config.rb b/test/other/config.rb deleted file mode 100755 index fad3e9763..000000000 --- a/test/other/config.rb +++ /dev/null @@ -1,937 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppet/util/config' -require 'puppettest' -require 'puppettest/parsertesting' - -class TestConfig < Test::Unit::TestCase - include PuppetTest - include PuppetTest::ParserTesting - - def check_for_users - count = Puppet::Type.type(:user).inject(0) { |c,o| - c + 1 - } - assert(count > 0, "Found no users") - end - - def check_to_transportable(config) - trans = nil - assert_nothing_raised("Could not convert to a transportable") { - trans = config.to_transportable - } - - comp = nil - assert_nothing_raised("Could not convert transportable to component") { - comp = trans.to_type - } - - check_for_users() - - assert_nothing_raised("Could not retrieve transported config") { - comp.retrieve - } - end - - def check_to_manifest(config) - manifest = nil - assert_nothing_raised("Could not convert to a manifest") { - manifest = config.to_manifest - } - - Puppet[:parseonly] = true - - interp = nil - assert_nothing_raised do - interp = mkinterp :Code => manifest, :UseNodes => false - end - - trans = nil - assert_nothing_raised do - trans = interp.evaluate(nil, {}) - end - assert_nothing_raised("Could not instantiate objects") { - trans.to_type - } - check_for_users() - end - - def check_to_comp(config) - comp = nil - assert_nothing_raised("Could not convert to a component") { - comp = config.to_component - } - - assert_nothing_raised("Could not retrieve component") { - comp.retrieve - } - - check_for_users() - end - - def check_to_config(config) - newc = config.dup - - newfile = tempfile() - File.open(newfile, "w") { |f| f.print config.to_config } - assert_nothing_raised("Could not parse generated configuration") { - newc.parse(newfile) - } - - assert_equal(config, newc, "Configurations are not equal") - end - - def mkconfig - c = nil - assert_nothing_raised { - c = Puppet::Util::Config.new - } - return c - end - - def test_addbools - c = mkconfig - - assert_nothing_raised { - c.setdefaults(:testing, :booltest => [true, "testing"]) - } - - assert(c[:booltest]) - c = mkconfig - - assert_nothing_raised { - c.setdefaults(:testing, :booltest => ["true", "testing"]) - } - - assert(c[:booltest]) - - assert_nothing_raised { - c[:booltest] = false - } - - assert(! c[:booltest], "Booltest is not false") - - assert_nothing_raised { - c[:booltest] = "false" - } - - assert(! c[:booltest], "Booltest is not false") - - assert_raise(Puppet::Error) { - c[:booltest] = "yayness" - } - - assert_raise(Puppet::Error) { - c[:booltest] = "/some/file" - } - end - - def test_strings - c = mkconfig - val = "this is a string" - assert_nothing_raised { - c.setdefaults(:testing, :strtest => [val, "testing"]) - } - - assert_equal(val, c[:strtest]) - - # Verify that variables are interpolated - assert_nothing_raised { - c.setdefaults(:testing, :another => ["another $strtest", "testing"]) - } - - assert_equal("another #{val}", c[:another]) - end - - def test_files - c = mkconfig - - parent = "/puppet" - assert_nothing_raised { - c.setdefaults(:testing, :parentdir => [parent, "booh"]) - } - - assert_nothing_raised { - c.setdefaults(:testing, :child => ["$parent/child", "rah"]) - } - - assert_equal(parent, c[:parentdir]) - assert_equal("/puppet/child", File.join(c[:parentdir], "child")) - end - - def test_getset - c = mkconfig - initial = "an initial value" - assert_raise(Puppet::Error) { - c[:yayness] = initial - } - - default = "this is a default" - assert_nothing_raised { - c.setdefaults(:testing, :yayness => [default, "rah"]) - } - - assert_equal(default, c[:yayness]) - - assert_nothing_raised { - c[:yayness] = initial - } - - assert_equal(initial, c[:yayness]) - - assert_nothing_raised { - c.clear - } - - assert_equal(default, c[:yayness]) - - assert_nothing_raised { - c[:yayness] = "not default" - } - assert_equal("not default", c[:yayness]) - end - - def test_parse - text = %{ -one = this is a test -two = another test -owner = root -group = root -yay = /a/path - -[section1] - attr = value - owner = puppet - group = puppet - attrdir = /some/dir - attr3 = $attrdir/other - } - - file = tempfile() - File.open(file, "w") { |f| f.puts text } - - c = mkconfig - assert_nothing_raised { - c.setdefaults("puppet", - :one => ["a", "one"], - :two => ["a", "two"], - :yay => ["/default/path", "boo"], - :mkusers => [true, "uh, yeah"] - ) - } - - assert_nothing_raised { - c.setdefaults("section1", - :attr => ["a", "one"], - :attrdir => ["/another/dir", "two"], - :attr3 => ["$attrdir/maybe", "boo"] - ) - } - - assert_nothing_raised { - c.parse(file) - } - - assert_equal("value", c[:attr]) - assert_equal("/some/dir", c[:attrdir]) - assert_equal(:directory, c.element(:attrdir).type) - assert_equal("/some/dir/other", c[:attr3]) - - elem = nil - assert_nothing_raised { - elem = c.element(:attr3) - } - - assert(elem) - assert_equal("puppet", elem.owner) - - config = nil - assert_nothing_raised { - config = c.to_config - } - - assert_nothing_raised("Could not create transportable config") { - c.to_transportable - } - - check_to_comp(c) - Puppet::Type.allclear - check_to_manifest(c) - Puppet::Type.allclear - check_to_config(c) - Puppet::Type.allclear - check_to_transportable(c) - end - - def test_arghandling - c = mkconfig - - assert_nothing_raised { - c.setdefaults("testing", - :onboolean => [true, "An on bool"], - :offboolean => [false, "An off bool"], - :string => ["a string", "A string arg"], - :file => ["/path/to/file", "A file arg"] - ) - } - - data = { - :onboolean => [true, false], - :offboolean => [true, false], - :string => ["one string", "another string"], - :file => %w{/a/file /another/file} - } - data.each { |param, values| - values.each { |val| - opt = nil - arg = nil - if c.boolean?(param) - if val - opt = "--%s" % param - else - opt = "--no-%s" % param - end - else - opt = "--%s" % param - arg = val - end - - assert_nothing_raised("Could not handle arg %s with value %s" % - [opt, val]) { - - c.handlearg(opt, arg) - } - } - } - end - - def test_argadding - c = mkconfig - - assert_nothing_raised { - c.setdefaults("testing", - :onboolean => [true, "An on bool"], - :offboolean => [false, "An off bool"], - :string => ["a string", "A string arg"], - :file => ["/path/to/file", "A file arg"] - ) - } - options = [] - - c.addargs(options) - - c.each { |param, obj| - opt = "--%s" % param - assert(options.find { |ary| - ary[0] == opt - }, "Argument %s was not added" % opt) - - if c.boolean?(param) - o = "--no-%s" % param - assert(options.find { |ary| - ary[0] == o - }, "Boolean off %s was not added" % o) - end - } - end - - def test_usesection - # We want to make sure that config processes do not result in graphing. - Puppet[:graphdir] = tempfile() - Puppet[:graph] = true - Dir.mkdir(Puppet[:graphdir]) - c = mkconfig - - dir = tempfile() - file = "$mydir/myfile" - realfile = File.join(dir, "myfile") - otherfile = File.join(dir, "otherfile") - section = "testing" - assert_nothing_raised { - c.setdefaults(section, - :mydir => [dir, "A dir arg"], - :otherfile => { - :default => "$mydir/otherfile", - :create => true, - :desc => "A file arg" - }, - :myfile => [file, "A file arg"] - ) - } - - assert_nothing_raised("Could not use a section") { - c.use(section) - } - - assert_nothing_raised("Could not reuse a section") { - c.use(section) - } - - # Make sure it didn't graph anything, which is the only real way - # to test that the transaction was marked as a configurator. - assert(Dir.entries(Puppet[:graphdir]).reject { |f| f =~ /^\.\.?$/ }.empty?, "Graphed config process") - - assert(FileTest.directory?(dir), "Did not create directory") - assert(FileTest.exists?(otherfile), "Did not create file") - assert(!FileTest.exists?(realfile), "Created file") - end - - def test_setdefaultsarray - c = mkconfig - - assert_nothing_raised { - c.setdefaults("yay", - :a => [false, "some value"], - :b => ["/my/file", "a file"] - ) - } - - assert_equal(false, c[:a], "Values are not equal") - assert_equal("/my/file", c[:b], "Values are not equal") - end - - def test_setdefaultshash - c = mkconfig - - assert_nothing_raised { - c.setdefaults("yay", - :a => {:default => false, :desc => "some value"}, - :b => {:default => "/my/file", :desc => "a file"} - ) - } - - assert_equal(false, c[:a], "Values are not equal") - assert_equal("/my/file", c[:b], "Values are not equal") - end - - def test_reuse - c = mkconfig - - file = tempfile() - section = "testing" - assert_nothing_raised { - c.setdefaults(section, - :myfile => {:default => file, :create => true, :desc => "yay"} - ) - } - - assert_nothing_raised("Could not use a section") { - c.use(section) - } - - assert(FileTest.exists?(file), "Did not create file") - - assert(! Puppet::Type.type(:file)[file], "File obj still exists") - - File.unlink(file) - - c.reuse - assert(FileTest.exists?(file), "Did not create file") - end - - def test_mkusers - c = mkconfig - - file = tempfile() - section = "testing" - assert_nothing_raised { - c.setdefaults(section, - :mkusers => [false, "yay"], - :myfile => { - :default => file, - :owner => "pptest", - :group => "pptest", - :desc => "yay", - :create => true - } - ) - } - - comp = nil - assert_nothing_raised { - comp = c.to_component - } - - [:user, :group].each do |type| - # The objects might get created internally by Puppet::Util; just - # make sure they're not being managed - if obj = Puppet.type(type)["pptest"] - assert(! obj.managed?, "%s objectis managed" % type) - end - end - comp.each { |o| o.remove } - - c[:mkusers] = true - - assert_nothing_raised { - c.to_component - } - - user = Puppet.type(:user)["pptest"] - assert(user, "User object did not get created") - assert(user.managed?, "User object is not managed.") - assert(user.should(:comment), "user does not have a comment set") - - group = Puppet.type(:group)["pptest"] - assert(group, "Group object did not get created") - assert(group.managed?, - "Group object is not managed." - ) - - if Process.uid == 0 - cleanup do - user[:ensure] = :absent - group[:ensure] = :absent - assert_apply(user, group) - end - - assert_apply(user, group) - end - end - - def test_notmanagingdev - c = mkconfig - path = "/dev/testing" - c.setdefaults(:test, - :file => { - :default => path, - :mode => 0640, - :desc => 'yay' - } - ) - - assert_nothing_raised { - c.to_component - } - - assert(! Puppet.type(:file)["/dev/testing"], "Created dev file") - end - - def test_groupsetting - cfile = tempfile() - - group = "yayness" - - File.open(cfile, "w") do |f| - f.puts "[#{Puppet.name}] - group = #{group} - " - end - - config = mkconfig - config.setdefaults(Puppet.name, :group => ["puppet", "a group"]) - - assert_nothing_raised { - config.parse(cfile) - } - - assert_equal(group, config[:group], "Group did not take") - end - - # provide a method to modify and create files w/out specifying the info - # already stored in a config - def test_writingfiles - File.umask(0022) - - path = tempfile() - mode = 0644 - - config = mkconfig - - args = { :default => path, :mode => mode, :desc => "yay" } - - user = nonrootuser() - group = nonrootgroup() - - if Puppet::Util::SUIDManager.uid == 0 - args[:owner] = user.name - args[:group] = group.name - end - - config.setdefaults(:testing, :myfile => args) - - assert_nothing_raised { - config.write(:myfile) do |file| - file.puts "yay" - end - } - - assert_equal(mode, filemode(path), "Modes are not equal") - - # OS X is broken in how it chgrps files - if Puppet::Util::SUIDManager.uid == 0 - assert_equal(user.uid, File.stat(path).uid, "UIDS are not equal") - - case Facter["operatingsystem"].value - when /BSD/, "Darwin": # nothing - else - assert_equal(group.gid, File.stat(path).gid, "GIDS are not equal") - end - end - end - - def test_mkdir - File.umask(0022) - - path = tempfile() - mode = 0755 - - config = mkconfig - - args = { :default => path, :mode => mode, :desc => "a file" } - - user = nonrootuser() - group = nonrootgroup() - - if Puppet::Util::SUIDManager.uid == 0 - args[:owner] = user.name - args[:group] = group.name - end - - config.setdefaults(:testing, :mydir => args) - - assert_nothing_raised { - config.mkdir(:mydir) - } - - assert_equal(mode, filemode(path), "Modes are not equal") - - - # OS X and *BSD is broken in how it chgrps files - if Puppet::Util::SUIDManager.uid == 0 - assert_equal(user.uid, File.stat(path).uid, "UIDS are not equal") - - case Facter["operatingsystem"].value - when /BSD/, "Darwin": # nothing - else - assert_equal(group.gid, File.stat(path).gid, "GIDS are not equal") - end - end - end - - def test_booleans_and_integers - config = mkconfig - config.setdefaults(:mysection, - :booltest => [false, "yay"], - :inttest => [14, "yay"] - ) - - file = tempfile() - - File.open(file, "w") do |f| - f.puts %{ -[mysection] -booltest = true -inttest = 27 -} - end - - assert_nothing_raised { - config.parse(file) - } - - assert_equal(true, config[:booltest], "Boolean was not converted") - assert_equal(27, config[:inttest], "Integer was not converted") - - # Now make sure that they get converted through handlearg - config.handlearg("--inttest", "true") - assert_equal(true, config[:inttest], "Boolean was not converted") - config.handlearg("--no-booltest", "false") - assert_equal(false, config[:booltest], "Boolean was not converted") - end - - # Make sure that tags are ignored when configuring - def test_configs_ignore_tags - config = mkconfig - file = tempfile() - - config.setdefaults(:mysection, - :mydir => [file, "a file"] - ) - - Puppet[:tags] = "yayness" - - assert_nothing_raised { - config.use(:mysection) - } - - assert(FileTest.directory?(file), "Directory did not get created") - - assert_equal("yayness", Puppet[:tags], - "Tags got changed during config") - end - - def test_configs_replace_in_url - config = mkconfig - - config.setdefaults(:mysection, :name => ["yayness", "yay"]) - config.setdefaults(:mysection, :url => ["http://$name/rahness", "yay"]) - - val = nil - assert_nothing_raised { - val = config[:url] - } - - assert_equal("http://yayness/rahness", val, - "Config got messed up") - end - - def test_correct_type_assumptions - config = mkconfig - - file = Puppet::Util::Config::CFile - element = Puppet::Util::Config::CElement - bool = Puppet::Util::Config::CBoolean - - # We have to keep these ordered, unfortunately. - [ - ["/this/is/a/file", file], - ["true", bool], - [true, bool], - ["false", bool], - ["server", element], - ["http://$server/yay", element], - ["$server/yayness", file], - ["$server/yayness.conf", file] - ].each do |ary| - value, type = ary - elem = nil - assert_nothing_raised { - elem = config.newelement( - :name => value, - :default => value, - :desc => name.to_s, - :section => :yayness - ) - } - - assert_instance_of(type, elem, - "%s got created as wrong type" % value.inspect) - end - end - - # Make sure we correctly reparse our config files but don't lose CLI values. - def test_reparse - Puppet[:filetimeout] = 0 - - config = mkconfig() - config.setdefaults(:mysection, :default => ["default", "yay"]) - config.setdefaults(:mysection, :clichange => ["clichange", "yay"]) - config.setdefaults(:mysection, :filechange => ["filechange", "yay"]) - - file = tempfile() - # Set one parameter in the file - File.open(file, "w") { |f| - f.puts %{[mysection]\nfilechange = filevalue} - } - assert_nothing_raised { - config.parse(file) - } - - # Set another "from the cli" - assert_nothing_raised { - config.handlearg("clichange", "clivalue") - } - - # And leave the other unset - assert_equal("default", config[:default]) - assert_equal("filevalue", config[:filechange]) - assert_equal("clivalue", config[:clichange]) - - # Now rewrite the file - File.open(file, "w") { |f| - f.puts %{[mysection]\nfilechange = newvalue} - } - - cfile = config.file - cfile.send("tstamp=".intern, Time.now - 50) - - # And check all of the values - assert_equal("default", config[:default]) - assert_equal("clivalue", config[:clichange]) - assert_equal("newvalue", config[:filechange]) - end - - def test_parse_removes_quotes - config = mkconfig() - config.setdefaults(:mysection, :singleq => ["single", "yay"]) - config.setdefaults(:mysection, :doubleq => ["double", "yay"]) - config.setdefaults(:mysection, :none => ["noquote", "yay"]) - config.setdefaults(:mysection, :middle => ["midquote", "yay"]) - - file = tempfile() - # Set one parameter in the file - File.open(file, "w") { |f| - f.puts %{[mysection]\n - singleq = 'one' - doubleq = "one" - none = one - middle = mid"quote -} - } - - assert_nothing_raised { - config.parse(file) - } - - %w{singleq doubleq none}.each do |p| - assert_equal("one", config[p], "%s did not match" % p) - end - assert_equal('mid"quote', config["middle"], "middle did not match") - end - - def test_timer - Puppet[:filetimeout] = 0.1 - origpath = tempfile() - config = mkconfig() - config.setdefaults(:mysection, :paramdir => [tempfile(), "yay"]) - - file = tempfile() - # Set one parameter in the file - File.open(file, "w") { |f| - f.puts %{[mysection]\n - paramdir = #{origpath} -} - } - - assert_nothing_raised { - config.parse(file) - config.use(:mysection) - } - - assert(FileTest.directory?(origpath), "dir did not get created") - - # Now start the timer - assert_nothing_raised { - EventLoop.current.monitor_timer config.timer - } - - newpath = tempfile() - - File.open(file, "w") { |f| - f.puts %{[mysection]\n - paramdir = #{newpath} -} - } - config.file.send("tstamp=".intern, Time.now - 50) - sleep 1 - - assert_equal(newpath, config["paramdir"], - "File did not get reparsed from timer") - assert(FileTest.directory?(newpath), "new dir did not get created") - - - end - - # Test that config parameters correctly call passed-in blocks when the value - # is set. - def test_paramblocks - config = mkconfig() - - testing = nil - elem = nil - assert_nothing_raised do - elem = config.newelement :default => "yay", - :name => :blocktest, - :desc => "boo", - :section => :test, - :hook => proc { |value| testing = value } - end - - assert_nothing_raised do - assert_equal("yay", elem.value) - end - - assert_nothing_raised do - elem.value = "yaytest" - end - - assert_nothing_raised do - assert_equal("yaytest", elem.value) - end - assert_equal("yaytest", testing) - - assert_nothing_raised do - elem.value = "another" - end - - assert_nothing_raised do - assert_equal("another", elem.value) - end - assert_equal("another", testing) - - # Now verify it works from setdefault - assert_nothing_raised do - config.setdefaults :test, - :blocktest2 => { - :default => "yay", - :desc => "yay", - :hook => proc { |v| testing = v } - } - end - - assert_equal("yay", config[:blocktest2]) - - assert_nothing_raised do - config[:blocktest2] = "footest" - end - assert_equal("footest", config[:blocktest2]) - assert_equal("footest", testing) - end - - def test_no_modify_root - config = mkconfig - config.setdefaults(:yay, - :mydir => {:default => tempfile(), - :mode => 0644, - :owner => "root", - :group => "root", - :desc => "yay" - }, - :mkusers => [false, "yay"] - ) - - assert_nothing_raised do - config.use(:yay) - end - - # Now enable it so they'll be added - config[:mkusers] = true - - comp = config.to_component - - Puppet::Type.type(:user).each do |u| - assert(u.name != "root", "Tried to manage root user") - end - Puppet::Type.type(:group).each do |u| - assert(u.name != "root", "Tried to manage root group") - assert(u.name != "wheel", "Tried to manage wheel group") - end - -# assert(yay, "Did not find yay component") -# yay.each do |c| -# puts c.ref -# end -# assert(! yay.find { |o| o.class.name == :user and o.name == "root" }, -# "Found root user") -# assert(! yay.find { |o| o.class.name == :group and o.name == "root" }, -# "Found root group") - end - - # #415 - def test_remove_trailing_spaces - config = mkconfig() - config.setdefaults(:yay, :rah => ["testing", "a desc"]) - - file = tempfile() - File.open(file, "w") { |f| f.puts "rah = something " } - - assert_nothing_raised { config.parse(file) } - assert_equal("something", config[:rah], "did not remove trailing whitespace in parsing") - end -end - -# $Id$ diff --git a/test/other/features.rb b/test/other/features.rb deleted file mode 100755 index 129c14769..000000000 --- a/test/other/features.rb +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env ruby -# -# Created by Luke Kanies on 2006-11-07. -# Copyright (c) 2006. All rights reserved. - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppettest' -require 'puppet/util/feature' - -class TestFeatures < Test::Unit::TestCase - include PuppetTest - - def setup - super - libdir = tempfile() - @features = Puppet::Util::Feature.new(libdir) - end - - def test_new - assert_nothing_raised do - @features.add(:failer) do - raise ArgumentError, "nopes" - end - end - - assert(@features.respond_to?(:failer?), "Feature method did not get added") - assert_nothing_raised("failure propagated outside of feature") do - assert(! @features.failer?, "failure was considered true") - end - - # Now make one that succeeds - $succeeds = nil - assert_nothing_raised("Failed to add normal feature") do - @features.add(:succeeds) do - $succeeds = true - end - end - assert($succeeds, "Block was not called on initialization") - - assert(@features.respond_to?(:succeeds?), "Did not add succeeding feature") - assert_nothing_raised("Failed to call succeeds") { assert(@features.succeeds?, "Feature was not true") } - end - - def test_libs - assert_nothing_raised do - @features.add(:puppet, :libs => %w{puppet}) - end - - assert(@features.puppet?) - - assert_nothing_raised do - @features.add(:missing, :libs => %w{puppet no/such/library/okay}) - end - - assert(! @features.missing?, "Missing lib was considered true") - end - - def test_dynamic_loading - # Make sure it defaults to false - assert_nothing_raised("Undefined features throw an exception") do - assert(! @features.nosuchfeature?, "missing feature returned true") - end - - $features = @features - cleanup { $features = nil } - # Now create a feature and make sure it loads. - Dir.mkdir(@features.path) - nope = File.join(@features.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.yep?, "'yep' returned true before definition") - end - - yep = File.join(@features.path, "yep.rb") - File.open(yep, "w") { |f| - f.puts "$features.add(:yep, :libs => %w{puppet})" - } - - # Now make sure the value is not cached or anything. - assert_nothing_raised("Failed to autoload features") do - assert(@features.yep?, "'yep' returned false") - end - end -end - -# $Id$ diff --git a/test/other/filetype.rb b/test/other/filetype.rb deleted file mode 100755 index 81a2af2c8..000000000 --- a/test/other/filetype.rb +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppet/util/filetype' -require 'puppettest' - -class TestFileType < Test::Unit::TestCase - include PuppetTest - - def test_flat - obj = nil - path = tempfile() - type = nil - - assert_nothing_raised { - type = Puppet::Util::FileType.filetype(:flat) - } - - assert(type, "Could not retrieve flat filetype") - - assert_nothing_raised { - obj = type.new(path) - } - - text = "This is some text\n" - - newtext = nil - assert_nothing_raised { - newtext = obj.read - } - - # The base class doesn't allow a return of nil - assert_equal("", newtext, "Somehow got some text") - - assert_nothing_raised { - obj.write(text) - } - assert_nothing_raised { - newtext = obj.read - } - - assert_equal(text, newtext, "Text was changed somehow") - - File.open(path, "w") { |f| f.puts "someyayness" } - - text = File.read(path) - assert_nothing_raised { - newtext = obj.read - } - - assert_equal(text, newtext, "Text was changed somehow") - end - - if Facter["operatingsystem"].value == "Darwin" - def test_ninfotoarray - obj = nil - type = nil - - assert_nothing_raised { - type = Puppet::Util::FileType.filetype(:netinfo) - } - - assert(type, "Could not retrieve netinfo filetype") - %w{users groups aliases}.each do |map| - assert_nothing_raised { - obj = type.new(map) - } - - assert_nothing_raised("could not read map %s" % map) { - obj.read - } - - array = nil - - assert_nothing_raised { - array = obj.to_array - } - - assert_instance_of(Array, array) - - array.each do |record| - assert_instance_of(Hash, record) - assert(record.length != 0) - end - end - end - end -end - -# $Id$ diff --git a/test/other/inifile.rb b/test/other/inifile.rb deleted file mode 100755 index bdac23f7d..000000000 --- a/test/other/inifile.rb +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppet/util/inifile' -require 'puppettest' - -class TestFileType < Test::Unit::TestCase - include PuppetTest - - def setup - super - @file = Puppet::Util::IniConfig::File.new - end - - def teardown - @file = nil - super - end - - def test_simple - fname = mkfile("[main]\nkey1=value1\n# Comment\nkey2=value=2") - assert_nothing_raised { - @file.read(fname) - } - s = get_section('main') - assert_entries(s, { 'key1' => 'value1', 'key2' => 'value=2' }) - @file['main']['key2'] = 'newvalue2' - @file['main']['key3'] = 'newvalue3' - text = s.format - assert_equal("[main]\nkey1=value1\n# Comment\nkey2=newvalue2\nkey3=newvalue3\n", - s.format) - end - - def test_multi - fmain = mkfile("[main]\nkey1=main.value1\n# Comment\nkey2=main.value2") - fsub = mkfile("[sub1]\nkey1=sub1 value1\n\n" + - "[sub2]\nkey1=sub2.value1") - main_mtime = File::stat(fmain).mtime - assert_nothing_raised { - @file.read(fmain) - @file.read(fsub) - } - main = get_section('main') - assert_entries(main, - { 'key1' => 'main.value1', 'key2' => 'main.value2' }) - sub1 = get_section('sub1') - assert_entries(sub1, { 'key1' => 'sub1 value1' }) - sub2 = get_section('sub2') - assert_entries(sub2, { 'key1' => 'sub2.value1' }) - [main, sub1, sub2].each { |s| assert( !s.dirty? ) } - sub1['key1'] = 'sub1 newvalue1' - sub2['key2'] = 'sub2 newvalue2' - assert(! main.dirty?) - [sub1, sub2].each { |s| assert( s.dirty? ) } - @file.store - [main, sub1, sub2].each { |s| assert( !s.dirty? ) } - assert( File.exists?(fmain) ) - assert( File.exists?(fsub) ) - assert_equal(main_mtime, File::stat(fmain).mtime) - subtext = File.read(fsub) - assert_equal("[sub1]\nkey1=sub1 newvalue1\n\n" + - "[sub2]\nkey1=sub2.value1\nkey2=sub2 newvalue2\n", - subtext) - end - - def test_format_nil - fname = mkfile("[main]\nkey1=value1\n# Comment\nkey2=value2\n" + - "# Comment2\n") - assert_nothing_raised { - @file.read(fname) - } - s = get_section('main') - s['key2'] = nil - s['key3'] = nil - text = s.format - assert_equal("[main]\nkey1=value1\n# Comment\n# Comment2\n", - s.format) - end - - def test_whitespace - # FIXME: Should we really accept keys preceded by whitespace ? - fname = mkfile("[main]\n key1=v1\nkey2 =v2\n") - assert_nothing_raised { - @file.read(fname) - } - s = get_section('main') - assert_equal('v1', s['key1']) - assert_equal('v2', s['key2']) - # FIXME: We are losing whitespace around keys - assert_equal("[main]\nkey1=v1\nkey2=v2\n", s.format) - end - - def test_continuation - cont = "[main]\nkey1=v1\nkey2=v2a\n v2b\n" - fname = mkfile(cont) - assert_nothing_raised { - @file.read(fname) - } - s = get_section('main') - assert_equal('v1', s['key1']) - assert_equal("v2a\n v2b", s['key2']) - assert_equal(cont, s.format) - end - - def assert_entries(section, hash) - hash.each do |k, v| - assert_equal(v, section[k], - "Expected <#{v}> for #{section.name}[#{k}] " + - "but got <#{section[k]}>") - end - end - - def get_section(name) - result = @file[name] - assert_not_nil(result) - return result - end - - def mkfile(content) - file = tempfile() - File.open(file, "w") { |f| f.print(content) } - return file - end -end diff --git a/test/other/loadedfile.rb b/test/other/loadedfile.rb deleted file mode 100755 index 2c6b241fb..000000000 --- a/test/other/loadedfile.rb +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppet/util/loadedfile' -require 'puppettest' - -class TestLoadedFile < Test::Unit::TestCase - include PuppetTest - def test_file - Puppet[:filetimeout] = 0 - file = nil - path = tempfile() - File.open(path, "w") { |f| f.puts "yayness" } - assert_nothing_raised { - file = Puppet::Util::LoadedFile.new(path) - } - - assert(!file.changed?, "File incorrectly returned changed") - - File.open(path, "w") { |f| f.puts "booness" } - #file.tstamp = File.stat(path).ctime - 5 - new = File.stat(path).ctime - 5 - file.tstamp = new - - assert(file.changed?, "File did not catch change") - end - - def test_timeout - Puppet[:filetimeout] = 50 - path = tempfile() - - File.open(path, "w") { |f| f.puts "yay" } - file = nil - assert_nothing_raised { - file = Puppet::Util::LoadedFile.new(path) - } - - assert_nothing_raised { - assert(!file.changed?, - "File thought it changed immediately") - } - - sleep 1 - File.open(path, "w") { |f| f.puts "yay" } - #file.tstamp = File.stat(path).ctime - 5 - - assert(!file.changed?, - "File was marked as changed too soon") - - Puppet[:filetimeout] = 0 - assert(file.changed?, - "File was not marked as changed soon enough") - end - - def test_stamp - file = tempfile() - File.open(file, "w") { |f| f.puts "" } - obj = nil - assert_nothing_raised { - obj = Puppet::Util::LoadedFile.new(file) - } - - # Make sure we don't refresh - Puppet[:filetimeout] = 50 - - stamp = File.stat(file).ctime - - assert_equal(stamp, obj.stamp) - - sleep 1 - # Now change the file, and make sure the stamp doesn't update yet - File.open(file, "w") { |f| f.puts "" } - assert_equal(stamp, obj.stamp, - "File prematurely refreshed") - - Puppet[:filetimeout] = 0 - assert_equal(File.stat(file).ctime, obj.stamp, - "File did not refresh") - end - - # Testing #394. - def test_changed_missing_file - file = tempfile() - File.open(file, "w") { |f| f.puts "" } - obj = nil - assert_nothing_raised { - obj = Puppet::Util::LoadedFile.new(file) - } - Puppet[:filetimeout] = -10 - - assert_nothing_raised { - obj.changed? - } - - # Now remove the file - File.unlink(file) - - assert_nothing_raised("removed file threw an error") { - assert(obj.changed?, "File was not considered changed when missing") - } - end -end - -# $Id$ diff --git a/test/other/log.rb b/test/other/log.rb deleted file mode 100755 index e1af9897a..000000000 --- a/test/other/log.rb +++ /dev/null @@ -1,286 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppet/util/log' -require 'puppettest' - -class TestLog < Test::Unit::TestCase - include PuppetTest - - def setup - super - @oldloglevel = Puppet::Util::Log.level - Puppet::Util::Log.close - end - - def teardown - super - Puppet::Util::Log.close - Puppet::Util::Log.level = @oldloglevel - Puppet::Util::Log.newdestination(:console) - end - - def getlevels - levels = nil - assert_nothing_raised() { - levels = [] - Puppet::Util::Log.eachlevel { |level| levels << level } - } - # Don't test the top levels; too annoying - return levels.reject { |level| level == :emerg or level == :crit } - end - - def mkmsgs(levels) - levels.collect { |level| - next if level == :alert - assert_nothing_raised() { - Puppet::Util::Log.new( - :level => level, - :source => "Test", - :message => "Unit test for %s" % level - ) - } - } - end - - def test_logfile - fact = nil - levels = nil - Puppet::Util::Log.level = :debug - levels = getlevels - logfile = tempfile() - fact = nil - assert_nothing_raised() { - Puppet::Util::Log.newdestination(logfile) - } - msgs = mkmsgs(levels) - assert(msgs.length == levels.length) - Puppet::Util::Log.close - count = 0 - - assert(FileTest.exists?(logfile), "Did not create logfile") - - assert_nothing_raised() { - File.open(logfile) { |of| - count = of.readlines.length - } - } - assert(count == levels.length - 1) # skip alert - end - - def test_syslog - levels = nil - assert_nothing_raised() { - levels = getlevels.reject { |level| - level == :emerg || level == :crit - } - } - assert_nothing_raised() { - Puppet::Util::Log.newdestination("syslog") - } - # there's really no way to verify that we got syslog messages... - msgs = mkmsgs(levels) - assert(msgs.length == levels.length) - end - - def test_consolelog - fact = nil - levels = getlevels - assert_nothing_raised() { - Puppet::Util::Log.newdestination(:console) - } - msgs = mkmsgs(levels) - assert(msgs.length == levels.length) - Puppet::Util::Log.close - end - - def test_levelmethods - assert_nothing_raised() { - Puppet::Util::Log.newdestination("/dev/null") - } - getlevels.each { |level| - assert_nothing_raised() { - Puppet.send(level,"Testing for %s" % level) - } - } - end - - def test_output - Puppet::Util::Log.level = :notice - assert(Puppet.err("This is an error").is_a?(Puppet::Util::Log)) - assert(Puppet.debug("This is debugging").nil?) - Puppet::Util::Log.level = :debug - assert(Puppet.err("This is an error").is_a?(Puppet::Util::Log)) - assert(Puppet.debug("This is debugging").is_a?(Puppet::Util::Log)) - end - - def test_creatingdirs - dir = tempfile() - file = File.join(dir, "logfile") - Puppet::Util::Log.newdestination file - Puppet.info "testing logs" - assert(FileTest.directory?(dir)) - assert(FileTest.file?(file)) - end - - def test_logtags - path = tempfile - File.open(path, "w") { |f| f.puts "yayness" } - - file = Puppet.type(:file).create( - :path => path, - :check => [:owner, :group, :mode, :checksum], - :ensure => :file - ) - file.tags = %w{this is a test} - - property = file.property(:ensure) - assert(property, "Did not get property") - log = nil - assert_nothing_raised { - log = Puppet::Util::Log.new( - :level => :info, - :source => property, - :message => "A test message" - ) - } - - # Now yaml and de-yaml it, and test again - yamllog = YAML.load(YAML.dump(log)) - - {:log => log, :yaml => yamllog}.each do |type, msg| - assert(msg.tags, "Got no tags") - - msg.tags.each do |tag| - assert(msg.tagged?(tag), "Was not tagged with %s" % tag) - end - - assert_equal(msg.tags, property.tags, "Tags were not equal") - assert_equal(msg.source, property.path, "Source was not set correctly") - end - - end - - # Verify that we can pass strings that match printf args - def test_percentlogs - Puppet::Util::Log.newdestination :syslog - - assert_nothing_raised { - Puppet::Util::Log.new( - :level => :info, - :message => "A message with %s in it" - ) - } - end - - # Verify that the error and source are always strings - def test_argsAreStrings - msg = nil - file = Puppet.type(:file).create( - :path => tempfile(), - :check => %w{owner group} - ) - assert_nothing_raised { - msg = Puppet::Util::Log.new(:level => :info, :message => "This is a message") - } - assert_nothing_raised { - msg.source = file - } - - assert_instance_of(String, msg.to_s) - assert_instance_of(String, msg.source) - end - - # Verify that loglevel behaves as one expects - def test_loglevel - path = tempfile() - file = Puppet.type(:file).create( - :path => path, - :ensure => "file" - ) - - assert_nothing_raised { - assert_equal(:notice, file[:loglevel]) - } - - assert_nothing_raised { - file[:loglevel] = "warning" - } - - assert_nothing_raised { - assert_equal(:warning, file[:loglevel]) - } - end - - def test_destination_matching - dest = nil - assert_nothing_raised { - dest = Puppet::Util::Log.newdesttype("Destine") do - def handle(msg) - puts msg - end - end - } - - [:destine, "Destine", "destine"].each do |name| - assert(dest.match?(name), "Did not match %s" % name.inspect) - end - - assert_nothing_raised { - dest.match(:yayness) - } - assert(dest.match("Yayness"), "Did not match yayness") - Puppet::Util::Log.close(dest) - end - - def test_autoflush - file = tempfile - Puppet::Util::Log.close(:console) - Puppet::Util::Log.newdestination(file) - Puppet.warning "A test" - assert(File.read(file) !~ /A test/, - "File defualted to autoflush") - Puppet::Util::Log.flush - assert(File.read(file) =~ /A test/, - "File did not flush") - Puppet::Util::Log.close(file) - - # Now try one with autoflush enabled - Puppet[:autoflush] = true - file = tempfile - Puppet::Util::Log.newdestination(file) - Puppet.warning "A test" - assert(File.read(file) =~ /A test/, - "File did not autoflush") - Puppet::Util::Log.close(file) - end - - def test_reopen - Puppet[:autoflush] = true - file = tempfile - Puppet::Util::Log.close(:console) - Puppet::Util::Log.newdestination(file) - Puppet.warning "A test" - assert(File.read(file) =~ /A test/, - "File did not flush") - # Rename the file - newfile = file + ".old" - File.rename(file, newfile) - - # Send another log - Puppet.warning "Another test" - assert(File.read(newfile) =~ /Another test/, - "File did not rename") - - # Now reopen the log - Puppet::Util::Log.reopen - Puppet.warning "Reopen test" - assert(File.read(file) =~ /Reopen test/, - "File did not reopen") - Puppet::Util::Log.close(file) - end -end - -# $Id$ diff --git a/test/other/metrics.rb b/test/other/metrics.rb deleted file mode 100755 index c4e375e7b..000000000 --- a/test/other/metrics.rb +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppet/util/metric' -require 'puppettest' -require 'puppet/type' - -if Puppet.features.rrd? - class TestMetric < Test::Unit::TestCase - include PuppetTest - - def gendata - totalmax = 1000 - changemax = 1000 - eventmax = 10 - maxdiff = 10 - - types = [Puppet.type(:file), Puppet.type(:package), Puppet.type(:package)] - data = [:total, :managed, :outofsync, :changed, :totalchanges] - events = [:file_changed, :package_installed, :service_started] - - # if this is the first set of data points... - typedata = Hash.new { |typehash,type| - typehash[type] = Hash.new(0) - } - eventdata = Hash.new(0) - typedata = {} - typedata[:total] = rand(totalmax) - typedata[:managed] = rand(typedata[:total]) - typedata[:outofsync] = rand(typedata[:managed]) - typedata[:changed] = rand(typedata[:outofsync]) - typedata[:totalchanges] = rand(changemax) - - events.each { |event| - eventdata[event] = rand(eventmax) - } - - return {:typedata => typedata, :eventdata => eventdata} - end - - def rundata(report, time) - assert_nothing_raised { - gendata.each do |name, data| - report.newmetric(name, data) - end - report.metrics.each { |n, m| m.store(time) } - } - end - - def setup - super - Puppet[:rrdgraph] = true - end - - def test_fakedata - report = Puppet::Transaction::Report.new - time = Time.now.to_i - start = time - 10.times { - rundata(report, time) - time += 300 - } - rundata(report, time) - - report.metrics.each do |n, m| m.graph end - - File.open(File.join(Puppet[:rrddir],"index.html"),"w") { |of| - of.puts "" - report.metrics.each { |name, metric| - of.puts "
" % metric.name - } - } - end - end -else - $stderr.puts "Missing RRD library -- skipping metric tests" -end - -# $Id$ diff --git a/test/other/storage.rb b/test/other/storage.rb deleted file mode 100755 index dd68af5bf..000000000 --- a/test/other/storage.rb +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ - -require 'puppet' -require 'puppettest' - -class TestStorage < Test::Unit::TestCase - include PuppetTest - - def mkfile - path = tempfile() - File.open(path, "w") { |f| f.puts :yayness } - - f = Puppet.type(:file).create( - :name => path, - :check => %w{checksum type} - ) - - return f - end - - def test_storeandretrieve - path = tempfile() - - f = mkfile() - - # Load first, since that's what we do in the code base; this creates - # all of the necessary directories. - assert_nothing_raised { - Puppet::Util::Storage.load - } - - hash = {:a => :b, :c => :d} - - state = nil - assert_nothing_raised { - state = Puppet::Util::Storage.cache(f) - } - - assert(!state.include?("name")) - - assert_nothing_raised { - state["name"] = hash - } - - assert_nothing_raised { - Puppet::Util::Storage.store - } - assert_nothing_raised { - Puppet::Util::Storage.clear - } - assert_nothing_raised { - Puppet::Util::Storage.load - } - - # Reset it - state = nil - assert_nothing_raised { - state = Puppet::Util::Storage.cache(f) - } - - assert_equal(state["name"], hash) - end - - # we're getting corrupt files, probably because multiple processes - # are reading or writing the file at once - # so we need to test that - def test_multiwrite - f = mkfile() - - value = {:a => :b} - threads = [] - 9.times { |a| - threads << Thread.new { - 9.times { |b| - assert_nothing_raised { - Puppet::Util::Storage.load - state = Puppet::Util::Storage.cache(f) - value.each { |k,v| state[k] = v } - state[:e] = rand(100) - Puppet::Util::Storage.store - } - } - } - } - threads.each { |th| th.join } - end - - def test_emptyrestore - Puppet::Util::Storage.load - Puppet::Util::Storage.store - Puppet::Util::Storage.clear - Puppet::Util::Storage.load - - f = mkfile() - state = Puppet::Util::Storage.cache(f) - assert_same Hash, state.class - assert_equal 0, state.size - end - - def test_caching - hash = nil - one = Puppet::Type.type(:exec).create :title => "/bin/echo one" - [one, :yayness].each do |object| - assert_nothing_raised do - hash = Puppet::Util::Storage.cache(object) - end - assert_equal({}, hash, "Did not get empty hash back for %s" % object) - - hash[:testing] = true - assert_nothing_raised do - hash = Puppet::Util::Storage.cache(object) - end - assert_equal({:testing => true}, hash, "Did not get hash back for %s" % object) - end - assert_raise(ArgumentError, "was able to cache from string") do - Puppet::Util::Storage.cache("somethingelse") - end - end -end - -# $Id$ diff --git a/test/util/autoload.rb b/test/util/autoload.rb new file mode 100755 index 000000000..34f40df24 --- /dev/null +++ b/test/util/autoload.rb @@ -0,0 +1,130 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppet/util/autoload' +require 'puppettest' + +class TestAutoload < Test::Unit::TestCase + include PuppetTest + @things = [] + def self.newthing(name) + @things << name + end + + def self.thing?(name) + @things.include? name + end + + def self.clear + @things.clear + end + + def mkfile(name, path) + # Now create a file to load + File.open(path, "w") do |f| + f.puts %{ +TestAutoload.newthing(:#{name.to_s}) + } + end + end + + def teardown + super + self.class.clear + end + + def test_load + dir = tempfile() + $: << dir + cleanup do + $:.delete(dir) + end + + Dir.mkdir(dir) + + rbdir = File.join(dir, "yayness") + + Dir.mkdir(rbdir) + + # An object for specifying autoload + klass = self.class + + loader = nil + assert_nothing_raised { + loader = Puppet::Util::Autoload.new(klass, :yayness) + } + + assert_equal(loader.object_id, Puppet::Util::Autoload[klass].object_id, + "Did not retrieve loader object by class") + + # Make sure we don't fail on missing files + assert_nothing_raised { + assert_equal(false, loader.load(:mything), + "got incorrect return on failed load") + } + + # Now create a couple of files for testing + path = File.join(rbdir, "mything.rb") + mkfile(:mything, path) + opath = File.join(rbdir, "othing.rb") + mkfile(:othing, opath) + + # Now try to actually load it. + assert_nothing_raised { + assert_equal(true, loader.load(:mything), + "got incorrect return on failed load") + } + + assert(loader.loaded?(:mything), "Not considered loaded") + + assert(klass.thing?(:mything), + "Did not get loaded thing") + + # Now clear everything, and test loadall + assert_nothing_raised { + loader.clear + } + + self.class.clear + + assert_nothing_raised { + loader.loadall + } + + [:mything, :othing].each do |thing| + assert(loader.loaded?(thing), "#{thing.to_s} not considered loaded") + + assert(klass.thing?(thing), + "Did not get loaded #{thing.to_s}") + end + end + + # Make sure that autoload dynamically modifies $: with the libdir as + # appropriate. + def test_autoload_uses_libdir + dir = Puppet[:libdir] + unless FileTest.directory?(dir) + Dir.mkdir(dir) + end + + loader = File.join(dir, "test") + Dir.mkdir(loader) + name = "funtest" + file = File.join(loader, "funtest.rb") + File.open(file, "w") do |f| + f.puts "$loaded = true" + end + + auto = Puppet::Util::Autoload.new(self, "test") + + # Now make sure autoloading modifies $: as necessary + assert(! $:.include?(dir), "search path already includes libdir") + + assert_nothing_raised do + assert(auto.load("funtest"), "did not successfully load funtest") + end + assert($:.include?(dir), "libdir did not get added to search path") + end +end diff --git a/test/util/config.rb b/test/util/config.rb new file mode 100755 index 000000000..a18eddd0c --- /dev/null +++ b/test/util/config.rb @@ -0,0 +1,958 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppet/util/config' +require 'puppettest' +require 'puppettest/parsertesting' + +class TestConfig < Test::Unit::TestCase + include PuppetTest + include PuppetTest::ParserTesting + + def check_for_users + count = Puppet::Type.type(:user).inject(0) { |c,o| + c + 1 + } + assert(count > 0, "Found no users") + end + + def check_to_transportable(config) + trans = nil + assert_nothing_raised("Could not convert to a transportable") { + trans = config.to_transportable + } + + comp = nil + assert_nothing_raised("Could not convert transportable to component") { + comp = trans.to_type + } + + check_for_users() + + assert_nothing_raised("Could not retrieve transported config") { + comp.retrieve + } + end + + def check_to_manifest(config) + manifest = nil + assert_nothing_raised("Could not convert to a manifest") { + manifest = config.to_manifest + } + + Puppet[:parseonly] = true + + interp = nil + assert_nothing_raised do + interp = mkinterp :Code => manifest, :UseNodes => false + end + + trans = nil + assert_nothing_raised do + trans = interp.evaluate(nil, {}) + end + assert_nothing_raised("Could not instantiate objects") { + trans.to_type + } + check_for_users() + end + + def check_to_comp(config) + comp = nil + assert_nothing_raised("Could not convert to a component") { + comp = config.to_component + } + + assert_nothing_raised("Could not retrieve component") { + comp.retrieve + } + + check_for_users() + end + + def check_to_config(config) + newc = config.dup + + newfile = tempfile() + File.open(newfile, "w") { |f| f.print config.to_config } + assert_nothing_raised("Could not parse generated configuration") { + newc.parse(newfile) + } + + assert_equal(config, newc, "Configurations are not equal") + end + + def mkconfig + c = nil + assert_nothing_raised { + c = Puppet::Util::Config.new + } + return c + end + + def test_addbools + c = mkconfig + + assert_nothing_raised { + c.setdefaults(:testing, :booltest => [true, "testing"]) + } + + assert(c[:booltest]) + c = mkconfig + + assert_nothing_raised { + c.setdefaults(:testing, :booltest => ["true", "testing"]) + } + + assert(c[:booltest]) + + assert_nothing_raised { + c[:booltest] = false + } + + assert(! c[:booltest], "Booltest is not false") + + assert_nothing_raised { + c[:booltest] = "false" + } + + assert(! c[:booltest], "Booltest is not false") + + assert_raise(Puppet::Error) { + c[:booltest] = "yayness" + } + + assert_raise(Puppet::Error) { + c[:booltest] = "/some/file" + } + end + + def test_strings + c = mkconfig + val = "this is a string" + assert_nothing_raised { + c.setdefaults(:testing, :strtest => [val, "testing"]) + } + + assert_equal(val, c[:strtest]) + + # Verify that variables are interpolated + assert_nothing_raised { + c.setdefaults(:testing, :another => ["another $strtest", "testing"]) + } + + assert_equal("another #{val}", c[:another]) + end + + def test_files + c = mkconfig + + parent = "/puppet" + assert_nothing_raised { + c.setdefaults(:testing, :parentdir => [parent, "booh"]) + } + + assert_nothing_raised { + c.setdefaults(:testing, :child => ["$parent/child", "rah"]) + } + + assert_equal(parent, c[:parentdir]) + assert_equal("/puppet/child", File.join(c[:parentdir], "child")) + end + + def test_getset + c = mkconfig + initial = "an initial value" + assert_raise(Puppet::Error) { + c[:yayness] = initial + } + + default = "this is a default" + assert_nothing_raised { + c.setdefaults(:testing, :yayness => [default, "rah"]) + } + + assert_equal(default, c[:yayness]) + + assert_nothing_raised { + c[:yayness] = initial + } + + assert_equal(initial, c[:yayness]) + + assert_nothing_raised { + c.clear + } + + assert_equal(default, c[:yayness]) + + assert_nothing_raised { + c[:yayness] = "not default" + } + assert_equal("not default", c[:yayness]) + end + + def test_parse + text = %{ +one = this is a test +two = another test +owner = root +group = root +yay = /a/path + +[section1] + attr = value + owner = puppet + group = puppet + attrdir = /some/dir + attr3 = $attrdir/other + } + + file = tempfile() + File.open(file, "w") { |f| f.puts text } + + c = mkconfig + assert_nothing_raised { + c.setdefaults("puppet", + :one => ["a", "one"], + :two => ["a", "two"], + :yay => ["/default/path", "boo"], + :mkusers => [true, "uh, yeah"] + ) + } + + assert_nothing_raised { + c.setdefaults("section1", + :attr => ["a", "one"], + :attrdir => ["/another/dir", "two"], + :attr3 => ["$attrdir/maybe", "boo"] + ) + } + + assert_nothing_raised { + c.parse(file) + } + + assert_equal("value", c[:attr]) + assert_equal("/some/dir", c[:attrdir]) + assert_equal(:directory, c.element(:attrdir).type) + assert_equal("/some/dir/other", c[:attr3]) + + elem = nil + assert_nothing_raised { + elem = c.element(:attr3) + } + + assert(elem) + assert_equal("puppet", elem.owner) + + config = nil + assert_nothing_raised { + config = c.to_config + } + + assert_nothing_raised("Could not create transportable config") { + c.to_transportable + } + + check_to_comp(c) + Puppet::Type.allclear + check_to_manifest(c) + Puppet::Type.allclear + check_to_config(c) + Puppet::Type.allclear + check_to_transportable(c) + end + + def test_arghandling + c = mkconfig + + assert_nothing_raised { + c.setdefaults("testing", + :onboolean => [true, "An on bool"], + :offboolean => [false, "An off bool"], + :string => ["a string", "A string arg"], + :file => ["/path/to/file", "A file arg"] + ) + } + + data = { + :onboolean => [true, false], + :offboolean => [true, false], + :string => ["one string", "another string"], + :file => %w{/a/file /another/file} + } + data.each { |param, values| + values.each { |val| + opt = nil + arg = nil + if c.boolean?(param) + if val + opt = "--%s" % param + else + opt = "--no-%s" % param + end + else + opt = "--%s" % param + arg = val + end + + assert_nothing_raised("Could not handle arg %s with value %s" % + [opt, val]) { + + c.handlearg(opt, arg) + } + } + } + end + + def test_argadding + c = mkconfig + + assert_nothing_raised { + c.setdefaults("testing", + :onboolean => [true, "An on bool"], + :offboolean => [false, "An off bool"], + :string => ["a string", "A string arg"], + :file => ["/path/to/file", "A file arg"] + ) + } + options = [] + + c.addargs(options) + + c.each { |param, obj| + opt = "--%s" % param + assert(options.find { |ary| + ary[0] == opt + }, "Argument %s was not added" % opt) + + if c.boolean?(param) + o = "--no-%s" % param + assert(options.find { |ary| + ary[0] == o + }, "Boolean off %s was not added" % o) + end + } + end + + def test_usesection + # We want to make sure that config processes do not result in graphing. + Puppet[:graphdir] = tempfile() + Puppet[:graph] = true + Dir.mkdir(Puppet[:graphdir]) + c = mkconfig + + dir = tempfile() + file = "$mydir/myfile" + realfile = File.join(dir, "myfile") + otherfile = File.join(dir, "otherfile") + section = "testing" + assert_nothing_raised { + c.setdefaults(section, + :mydir => [dir, "A dir arg"], + :otherfile => { + :default => "$mydir/otherfile", + :create => true, + :desc => "A file arg" + }, + :myfile => [file, "A file arg"] + ) + } + + assert_nothing_raised("Could not use a section") { + c.use(section) + } + + assert_nothing_raised("Could not reuse a section") { + c.use(section) + } + + # Make sure it didn't graph anything, which is the only real way + # to test that the transaction was marked as a configurator. + assert(Dir.entries(Puppet[:graphdir]).reject { |f| f =~ /^\.\.?$/ }.empty?, "Graphed config process") + + assert(FileTest.directory?(dir), "Did not create directory") + assert(FileTest.exists?(otherfile), "Did not create file") + assert(!FileTest.exists?(realfile), "Created file") + end + + def test_setdefaultsarray + c = mkconfig + + assert_nothing_raised { + c.setdefaults("yay", + :a => [false, "some value"], + :b => ["/my/file", "a file"] + ) + } + + assert_equal(false, c[:a], "Values are not equal") + assert_equal("/my/file", c[:b], "Values are not equal") + end + + def test_setdefaultshash + c = mkconfig + + assert_nothing_raised { + c.setdefaults("yay", + :a => {:default => false, :desc => "some value"}, + :b => {:default => "/my/file", :desc => "a file"} + ) + } + + assert_equal(false, c[:a], "Values are not equal") + assert_equal("/my/file", c[:b], "Values are not equal") + end + + def test_reuse + c = mkconfig + + file = tempfile() + section = "testing" + assert_nothing_raised { + c.setdefaults(section, + :myfile => {:default => file, :create => true, :desc => "yay"} + ) + } + + assert_nothing_raised("Could not use a section") { + c.use(section) + } + + assert(FileTest.exists?(file), "Did not create file") + + assert(! Puppet::Type.type(:file)[file], "File obj still exists") + + File.unlink(file) + + c.reuse + assert(FileTest.exists?(file), "Did not create file") + end + + def test_mkusers + c = mkconfig + + file = tempfile() + section = "testing" + assert_nothing_raised { + c.setdefaults(section, + :mkusers => [false, "yay"], + :myfile => { + :default => file, + :owner => "pptest", + :group => "pptest", + :desc => "yay", + :create => true + } + ) + } + + comp = nil + assert_nothing_raised { + comp = c.to_component + } + + [:user, :group].each do |type| + # The objects might get created internally by Puppet::Util; just + # make sure they're not being managed + if obj = Puppet.type(type)["pptest"] + assert(! obj.managed?, "%s objectis managed" % type) + end + end + comp.each { |o| o.remove } + + c[:mkusers] = true + + assert_nothing_raised { + c.to_component + } + + user = Puppet.type(:user)["pptest"] + assert(user, "User object did not get created") + assert(user.managed?, "User object is not managed.") + assert(user.should(:comment), "user does not have a comment set") + + group = Puppet.type(:group)["pptest"] + assert(group, "Group object did not get created") + assert(group.managed?, + "Group object is not managed." + ) + + if Process.uid == 0 + cleanup do + user[:ensure] = :absent + group[:ensure] = :absent + assert_apply(user, group) + end + + assert_apply(user, group) + end + end + + def test_notmanagingdev + c = mkconfig + path = "/dev/testing" + c.setdefaults(:test, + :file => { + :default => path, + :mode => 0640, + :desc => 'yay' + } + ) + + assert_nothing_raised { + c.to_component + } + + assert(! Puppet.type(:file)["/dev/testing"], "Created dev file") + end + + def test_groupsetting + cfile = tempfile() + + group = "yayness" + + File.open(cfile, "w") do |f| + f.puts "[#{Puppet.name}] + group = #{group} + " + end + + config = mkconfig + config.setdefaults(Puppet.name, :group => ["puppet", "a group"]) + + assert_nothing_raised { + config.parse(cfile) + } + + assert_equal(group, config[:group], "Group did not take") + end + + # provide a method to modify and create files w/out specifying the info + # already stored in a config + def test_writingfiles + File.umask(0022) + + path = tempfile() + mode = 0644 + + config = mkconfig + + args = { :default => path, :mode => mode, :desc => "yay" } + + user = nonrootuser() + group = nonrootgroup() + + if Puppet::Util::SUIDManager.uid == 0 + args[:owner] = user.name + args[:group] = group.name + end + + config.setdefaults(:testing, :myfile => args) + + assert_nothing_raised { + config.write(:myfile) do |file| + file.puts "yay" + end + } + + assert_equal(mode, filemode(path), "Modes are not equal") + + # OS X is broken in how it chgrps files + if Puppet::Util::SUIDManager.uid == 0 + assert_equal(user.uid, File.stat(path).uid, "UIDS are not equal") + + case Facter["operatingsystem"].value + when /BSD/, "Darwin": # nothing + else + assert_equal(group.gid, File.stat(path).gid, "GIDS are not equal") + end + end + end + + def test_mkdir + File.umask(0022) + + path = tempfile() + mode = 0755 + + config = mkconfig + + args = { :default => path, :mode => mode, :desc => "a file" } + + user = nonrootuser() + group = nonrootgroup() + + if Puppet::Util::SUIDManager.uid == 0 + args[:owner] = user.name + args[:group] = group.name + end + + config.setdefaults(:testing, :mydir => args) + + assert_nothing_raised { + config.mkdir(:mydir) + } + + assert_equal(mode, filemode(path), "Modes are not equal") + + + # OS X and *BSD is broken in how it chgrps files + if Puppet::Util::SUIDManager.uid == 0 + assert_equal(user.uid, File.stat(path).uid, "UIDS are not equal") + + case Facter["operatingsystem"].value + when /BSD/, "Darwin": # nothing + else + assert_equal(group.gid, File.stat(path).gid, "GIDS are not equal") + end + end + end + + def test_booleans_and_integers + config = mkconfig + config.setdefaults(:mysection, + :booltest => [false, "yay"], + :inttest => [14, "yay"] + ) + + file = tempfile() + + File.open(file, "w") do |f| + f.puts %{ +[mysection] +booltest = true +inttest = 27 +} + end + + assert_nothing_raised { + config.parse(file) + } + + assert_equal(true, config[:booltest], "Boolean was not converted") + assert_equal(27, config[:inttest], "Integer was not converted") + + # Now make sure that they get converted through handlearg + config.handlearg("--inttest", "true") + assert_equal(true, config[:inttest], "Boolean was not converted") + config.handlearg("--no-booltest", "false") + assert_equal(false, config[:booltest], "Boolean was not converted") + end + + # Make sure that tags are ignored when configuring + def test_configs_ignore_tags + config = mkconfig + file = tempfile() + + config.setdefaults(:mysection, + :mydir => [file, "a file"] + ) + + Puppet[:tags] = "yayness" + + assert_nothing_raised { + config.use(:mysection) + } + + assert(FileTest.directory?(file), "Directory did not get created") + + assert_equal("yayness", Puppet[:tags], + "Tags got changed during config") + end + + def test_configs_replace_in_url + config = mkconfig + + config.setdefaults(:mysection, :name => ["yayness", "yay"]) + config.setdefaults(:mysection, :url => ["http://$name/rahness", "yay"]) + + val = nil + assert_nothing_raised { + val = config[:url] + } + + assert_equal("http://yayness/rahness", val, + "Config got messed up") + end + + def test_correct_type_assumptions + config = mkconfig + + file = Puppet::Util::Config::CFile + element = Puppet::Util::Config::CElement + bool = Puppet::Util::Config::CBoolean + + # We have to keep these ordered, unfortunately. + [ + ["/this/is/a/file", file], + ["true", bool], + [true, bool], + ["false", bool], + ["server", element], + ["http://$server/yay", element], + ["$server/yayness", file], + ["$server/yayness.conf", file] + ].each do |ary| + value, type = ary + elem = nil + assert_nothing_raised { + elem = config.newelement( + :name => value, + :default => value, + :desc => name.to_s, + :section => :yayness + ) + } + + assert_instance_of(type, elem, + "%s got created as wrong type" % value.inspect) + end + end + + # Make sure we correctly reparse our config files but don't lose CLI values. + def test_reparse + Puppet[:filetimeout] = 0 + + config = mkconfig() + config.setdefaults(:mysection, :default => ["default", "yay"]) + config.setdefaults(:mysection, :clichange => ["clichange", "yay"]) + config.setdefaults(:mysection, :filechange => ["filechange", "yay"]) + + file = tempfile() + # Set one parameter in the file + File.open(file, "w") { |f| + f.puts %{[mysection]\nfilechange = filevalue} + } + assert_nothing_raised { + config.parse(file) + } + + # Set another "from the cli" + assert_nothing_raised { + config.handlearg("clichange", "clivalue") + } + + # And leave the other unset + assert_equal("default", config[:default]) + assert_equal("filevalue", config[:filechange]) + assert_equal("clivalue", config[:clichange]) + + # Now rewrite the file + File.open(file, "w") { |f| + f.puts %{[mysection]\nfilechange = newvalue} + } + + cfile = config.file + cfile.send("tstamp=".intern, Time.now - 50) + + # And check all of the values + assert_equal("default", config[:default]) + assert_equal("clivalue", config[:clichange]) + assert_equal("newvalue", config[:filechange]) + end + + def test_parse_removes_quotes + config = mkconfig() + config.setdefaults(:mysection, :singleq => ["single", "yay"]) + config.setdefaults(:mysection, :doubleq => ["double", "yay"]) + config.setdefaults(:mysection, :none => ["noquote", "yay"]) + config.setdefaults(:mysection, :middle => ["midquote", "yay"]) + + file = tempfile() + # Set one parameter in the file + File.open(file, "w") { |f| + f.puts %{[mysection]\n + singleq = 'one' + doubleq = "one" + none = one + middle = mid"quote +} + } + + assert_nothing_raised { + config.parse(file) + } + + %w{singleq doubleq none}.each do |p| + assert_equal("one", config[p], "%s did not match" % p) + end + assert_equal('mid"quote', config["middle"], "middle did not match") + end + + def test_timer + Puppet[:filetimeout] = 0.1 + origpath = tempfile() + config = mkconfig() + config.setdefaults(:mysection, :paramdir => [tempfile(), "yay"]) + + file = tempfile() + # Set one parameter in the file + File.open(file, "w") { |f| + f.puts %{[mysection]\n + paramdir = #{origpath} +} + } + + assert_nothing_raised { + config.parse(file) + config.use(:mysection) + } + + assert(FileTest.directory?(origpath), "dir did not get created") + + # Now start the timer + assert_nothing_raised { + EventLoop.current.monitor_timer config.timer + } + + newpath = tempfile() + + File.open(file, "w") { |f| + f.puts %{[mysection]\n + paramdir = #{newpath} +} + } + config.file.send("tstamp=".intern, Time.now - 50) + sleep 1 + + assert_equal(newpath, config["paramdir"], + "File did not get reparsed from timer") + assert(FileTest.directory?(newpath), "new dir did not get created") + + + end + + # Test that config parameters correctly call passed-in blocks when the value + # is set. + def test_paramblocks + config = mkconfig() + + testing = nil + elem = nil + assert_nothing_raised do + elem = config.newelement :default => "yay", + :name => :blocktest, + :desc => "boo", + :section => :test, + :hook => proc { |value| testing = value } + end + + assert_nothing_raised do + assert_equal("yay", elem.value) + end + + assert_nothing_raised do + elem.value = "yaytest" + end + + assert_nothing_raised do + assert_equal("yaytest", elem.value) + end + assert_equal("yaytest", testing) + + assert_nothing_raised do + elem.value = "another" + end + + assert_nothing_raised do + assert_equal("another", elem.value) + end + assert_equal("another", testing) + + # Now verify it works from setdefault + assert_nothing_raised do + config.setdefaults :test, + :blocktest2 => { + :default => "yay", + :desc => "yay", + :hook => proc { |v| testing = v } + } + end + + assert_equal("yay", config[:blocktest2]) + + assert_nothing_raised do + config[:blocktest2] = "footest" + end + assert_equal("footest", config[:blocktest2]) + assert_equal("footest", testing) + end + + def test_no_modify_root + config = mkconfig + config.setdefaults(:yay, + :mydir => {:default => tempfile(), + :mode => 0644, + :owner => "root", + :group => "root", + :desc => "yay" + }, + :mkusers => [false, "yay"] + ) + + assert_nothing_raised do + config.use(:yay) + end + + # Now enable it so they'll be added + config[:mkusers] = true + + comp = config.to_component + + Puppet::Type.type(:user).each do |u| + assert(u.name != "root", "Tried to manage root user") + end + Puppet::Type.type(:group).each do |u| + assert(u.name != "root", "Tried to manage root group") + assert(u.name != "wheel", "Tried to manage wheel group") + end + +# assert(yay, "Did not find yay component") +# yay.each do |c| +# puts c.ref +# end +# assert(! yay.find { |o| o.class.name == :user and o.name == "root" }, +# "Found root user") +# assert(! yay.find { |o| o.class.name == :group and o.name == "root" }, +# "Found root group") + end + + # #415 + def test_remove_trailing_spaces + config = mkconfig() + config.setdefaults(:yay, :rah => ["testing", "a desc"]) + + file = tempfile() + File.open(file, "w") { |f| f.puts "rah = something " } + + assert_nothing_raised { config.parse(file) } + assert_equal("something", config[:rah], "did not remove trailing whitespace in parsing") + end + + # #484 + def test_parsing_unknown_variables + logstore() + config = mkconfig() + config.setdefaults(:mysection, :one => ["yay", "yay"]) + file = tempfile() + File.open(file, "w") { |f| + f.puts %{[mysection]\n + one = one + two = yay + } + } + + assert_nothing_raised("Unknown parameter threw an exception") do + config.parse(file) + end + + assert(@logs.detect { |l| l.message =~ /unknown configuration/ and l.level == :warning }, + "Did not generate warning message") + end +end + +# $Id$ diff --git a/test/util/features.rb b/test/util/features.rb new file mode 100755 index 000000000..129c14769 --- /dev/null +++ b/test/util/features.rb @@ -0,0 +1,94 @@ +#!/usr/bin/env ruby +# +# Created by Luke Kanies on 2006-11-07. +# Copyright (c) 2006. All rights reserved. + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppettest' +require 'puppet/util/feature' + +class TestFeatures < Test::Unit::TestCase + include PuppetTest + + def setup + super + libdir = tempfile() + @features = Puppet::Util::Feature.new(libdir) + end + + def test_new + assert_nothing_raised do + @features.add(:failer) do + raise ArgumentError, "nopes" + end + end + + assert(@features.respond_to?(:failer?), "Feature method did not get added") + assert_nothing_raised("failure propagated outside of feature") do + assert(! @features.failer?, "failure was considered true") + end + + # Now make one that succeeds + $succeeds = nil + assert_nothing_raised("Failed to add normal feature") do + @features.add(:succeeds) do + $succeeds = true + end + end + assert($succeeds, "Block was not called on initialization") + + assert(@features.respond_to?(:succeeds?), "Did not add succeeding feature") + assert_nothing_raised("Failed to call succeeds") { assert(@features.succeeds?, "Feature was not true") } + end + + def test_libs + assert_nothing_raised do + @features.add(:puppet, :libs => %w{puppet}) + end + + assert(@features.puppet?) + + assert_nothing_raised do + @features.add(:missing, :libs => %w{puppet no/such/library/okay}) + end + + assert(! @features.missing?, "Missing lib was considered true") + end + + def test_dynamic_loading + # Make sure it defaults to false + assert_nothing_raised("Undefined features throw an exception") do + assert(! @features.nosuchfeature?, "missing feature returned true") + end + + $features = @features + cleanup { $features = nil } + # Now create a feature and make sure it loads. + Dir.mkdir(@features.path) + nope = File.join(@features.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.yep?, "'yep' returned true before definition") + end + + yep = File.join(@features.path, "yep.rb") + File.open(yep, "w") { |f| + f.puts "$features.add(:yep, :libs => %w{puppet})" + } + + # Now make sure the value is not cached or anything. + assert_nothing_raised("Failed to autoload features") do + assert(@features.yep?, "'yep' returned false") + end + end +end + +# $Id$ diff --git a/test/util/filetype.rb b/test/util/filetype.rb new file mode 100755 index 000000000..81a2af2c8 --- /dev/null +++ b/test/util/filetype.rb @@ -0,0 +1,92 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppet/util/filetype' +require 'puppettest' + +class TestFileType < Test::Unit::TestCase + include PuppetTest + + def test_flat + obj = nil + path = tempfile() + type = nil + + assert_nothing_raised { + type = Puppet::Util::FileType.filetype(:flat) + } + + assert(type, "Could not retrieve flat filetype") + + assert_nothing_raised { + obj = type.new(path) + } + + text = "This is some text\n" + + newtext = nil + assert_nothing_raised { + newtext = obj.read + } + + # The base class doesn't allow a return of nil + assert_equal("", newtext, "Somehow got some text") + + assert_nothing_raised { + obj.write(text) + } + assert_nothing_raised { + newtext = obj.read + } + + assert_equal(text, newtext, "Text was changed somehow") + + File.open(path, "w") { |f| f.puts "someyayness" } + + text = File.read(path) + assert_nothing_raised { + newtext = obj.read + } + + assert_equal(text, newtext, "Text was changed somehow") + end + + if Facter["operatingsystem"].value == "Darwin" + def test_ninfotoarray + obj = nil + type = nil + + assert_nothing_raised { + type = Puppet::Util::FileType.filetype(:netinfo) + } + + assert(type, "Could not retrieve netinfo filetype") + %w{users groups aliases}.each do |map| + assert_nothing_raised { + obj = type.new(map) + } + + assert_nothing_raised("could not read map %s" % map) { + obj.read + } + + array = nil + + assert_nothing_raised { + array = obj.to_array + } + + assert_instance_of(Array, array) + + array.each do |record| + assert_instance_of(Hash, record) + assert(record.length != 0) + end + end + end + end +end + +# $Id$ diff --git a/test/util/inifile.rb b/test/util/inifile.rb new file mode 100755 index 000000000..bdac23f7d --- /dev/null +++ b/test/util/inifile.rb @@ -0,0 +1,126 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppet/util/inifile' +require 'puppettest' + +class TestFileType < Test::Unit::TestCase + include PuppetTest + + def setup + super + @file = Puppet::Util::IniConfig::File.new + end + + def teardown + @file = nil + super + end + + def test_simple + fname = mkfile("[main]\nkey1=value1\n# Comment\nkey2=value=2") + assert_nothing_raised { + @file.read(fname) + } + s = get_section('main') + assert_entries(s, { 'key1' => 'value1', 'key2' => 'value=2' }) + @file['main']['key2'] = 'newvalue2' + @file['main']['key3'] = 'newvalue3' + text = s.format + assert_equal("[main]\nkey1=value1\n# Comment\nkey2=newvalue2\nkey3=newvalue3\n", + s.format) + end + + def test_multi + fmain = mkfile("[main]\nkey1=main.value1\n# Comment\nkey2=main.value2") + fsub = mkfile("[sub1]\nkey1=sub1 value1\n\n" + + "[sub2]\nkey1=sub2.value1") + main_mtime = File::stat(fmain).mtime + assert_nothing_raised { + @file.read(fmain) + @file.read(fsub) + } + main = get_section('main') + assert_entries(main, + { 'key1' => 'main.value1', 'key2' => 'main.value2' }) + sub1 = get_section('sub1') + assert_entries(sub1, { 'key1' => 'sub1 value1' }) + sub2 = get_section('sub2') + assert_entries(sub2, { 'key1' => 'sub2.value1' }) + [main, sub1, sub2].each { |s| assert( !s.dirty? ) } + sub1['key1'] = 'sub1 newvalue1' + sub2['key2'] = 'sub2 newvalue2' + assert(! main.dirty?) + [sub1, sub2].each { |s| assert( s.dirty? ) } + @file.store + [main, sub1, sub2].each { |s| assert( !s.dirty? ) } + assert( File.exists?(fmain) ) + assert( File.exists?(fsub) ) + assert_equal(main_mtime, File::stat(fmain).mtime) + subtext = File.read(fsub) + assert_equal("[sub1]\nkey1=sub1 newvalue1\n\n" + + "[sub2]\nkey1=sub2.value1\nkey2=sub2 newvalue2\n", + subtext) + end + + def test_format_nil + fname = mkfile("[main]\nkey1=value1\n# Comment\nkey2=value2\n" + + "# Comment2\n") + assert_nothing_raised { + @file.read(fname) + } + s = get_section('main') + s['key2'] = nil + s['key3'] = nil + text = s.format + assert_equal("[main]\nkey1=value1\n# Comment\n# Comment2\n", + s.format) + end + + def test_whitespace + # FIXME: Should we really accept keys preceded by whitespace ? + fname = mkfile("[main]\n key1=v1\nkey2 =v2\n") + assert_nothing_raised { + @file.read(fname) + } + s = get_section('main') + assert_equal('v1', s['key1']) + assert_equal('v2', s['key2']) + # FIXME: We are losing whitespace around keys + assert_equal("[main]\nkey1=v1\nkey2=v2\n", s.format) + end + + def test_continuation + cont = "[main]\nkey1=v1\nkey2=v2a\n v2b\n" + fname = mkfile(cont) + assert_nothing_raised { + @file.read(fname) + } + s = get_section('main') + assert_equal('v1', s['key1']) + assert_equal("v2a\n v2b", s['key2']) + assert_equal(cont, s.format) + end + + def assert_entries(section, hash) + hash.each do |k, v| + assert_equal(v, section[k], + "Expected <#{v}> for #{section.name}[#{k}] " + + "but got <#{section[k]}>") + end + end + + def get_section(name) + result = @file[name] + assert_not_nil(result) + return result + end + + def mkfile(content) + file = tempfile() + File.open(file, "w") { |f| f.print(content) } + return file + end +end diff --git a/test/util/loadedfile.rb b/test/util/loadedfile.rb new file mode 100755 index 000000000..2c6b241fb --- /dev/null +++ b/test/util/loadedfile.rb @@ -0,0 +1,106 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppet/util/loadedfile' +require 'puppettest' + +class TestLoadedFile < Test::Unit::TestCase + include PuppetTest + def test_file + Puppet[:filetimeout] = 0 + file = nil + path = tempfile() + File.open(path, "w") { |f| f.puts "yayness" } + assert_nothing_raised { + file = Puppet::Util::LoadedFile.new(path) + } + + assert(!file.changed?, "File incorrectly returned changed") + + File.open(path, "w") { |f| f.puts "booness" } + #file.tstamp = File.stat(path).ctime - 5 + new = File.stat(path).ctime - 5 + file.tstamp = new + + assert(file.changed?, "File did not catch change") + end + + def test_timeout + Puppet[:filetimeout] = 50 + path = tempfile() + + File.open(path, "w") { |f| f.puts "yay" } + file = nil + assert_nothing_raised { + file = Puppet::Util::LoadedFile.new(path) + } + + assert_nothing_raised { + assert(!file.changed?, + "File thought it changed immediately") + } + + sleep 1 + File.open(path, "w") { |f| f.puts "yay" } + #file.tstamp = File.stat(path).ctime - 5 + + assert(!file.changed?, + "File was marked as changed too soon") + + Puppet[:filetimeout] = 0 + assert(file.changed?, + "File was not marked as changed soon enough") + end + + def test_stamp + file = tempfile() + File.open(file, "w") { |f| f.puts "" } + obj = nil + assert_nothing_raised { + obj = Puppet::Util::LoadedFile.new(file) + } + + # Make sure we don't refresh + Puppet[:filetimeout] = 50 + + stamp = File.stat(file).ctime + + assert_equal(stamp, obj.stamp) + + sleep 1 + # Now change the file, and make sure the stamp doesn't update yet + File.open(file, "w") { |f| f.puts "" } + assert_equal(stamp, obj.stamp, + "File prematurely refreshed") + + Puppet[:filetimeout] = 0 + assert_equal(File.stat(file).ctime, obj.stamp, + "File did not refresh") + end + + # Testing #394. + def test_changed_missing_file + file = tempfile() + File.open(file, "w") { |f| f.puts "" } + obj = nil + assert_nothing_raised { + obj = Puppet::Util::LoadedFile.new(file) + } + Puppet[:filetimeout] = -10 + + assert_nothing_raised { + obj.changed? + } + + # Now remove the file + File.unlink(file) + + assert_nothing_raised("removed file threw an error") { + assert(obj.changed?, "File was not considered changed when missing") + } + end +end + +# $Id$ diff --git a/test/util/log.rb b/test/util/log.rb new file mode 100755 index 000000000..e1af9897a --- /dev/null +++ b/test/util/log.rb @@ -0,0 +1,286 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppet/util/log' +require 'puppettest' + +class TestLog < Test::Unit::TestCase + include PuppetTest + + def setup + super + @oldloglevel = Puppet::Util::Log.level + Puppet::Util::Log.close + end + + def teardown + super + Puppet::Util::Log.close + Puppet::Util::Log.level = @oldloglevel + Puppet::Util::Log.newdestination(:console) + end + + def getlevels + levels = nil + assert_nothing_raised() { + levels = [] + Puppet::Util::Log.eachlevel { |level| levels << level } + } + # Don't test the top levels; too annoying + return levels.reject { |level| level == :emerg or level == :crit } + end + + def mkmsgs(levels) + levels.collect { |level| + next if level == :alert + assert_nothing_raised() { + Puppet::Util::Log.new( + :level => level, + :source => "Test", + :message => "Unit test for %s" % level + ) + } + } + end + + def test_logfile + fact = nil + levels = nil + Puppet::Util::Log.level = :debug + levels = getlevels + logfile = tempfile() + fact = nil + assert_nothing_raised() { + Puppet::Util::Log.newdestination(logfile) + } + msgs = mkmsgs(levels) + assert(msgs.length == levels.length) + Puppet::Util::Log.close + count = 0 + + assert(FileTest.exists?(logfile), "Did not create logfile") + + assert_nothing_raised() { + File.open(logfile) { |of| + count = of.readlines.length + } + } + assert(count == levels.length - 1) # skip alert + end + + def test_syslog + levels = nil + assert_nothing_raised() { + levels = getlevels.reject { |level| + level == :emerg || level == :crit + } + } + assert_nothing_raised() { + Puppet::Util::Log.newdestination("syslog") + } + # there's really no way to verify that we got syslog messages... + msgs = mkmsgs(levels) + assert(msgs.length == levels.length) + end + + def test_consolelog + fact = nil + levels = getlevels + assert_nothing_raised() { + Puppet::Util::Log.newdestination(:console) + } + msgs = mkmsgs(levels) + assert(msgs.length == levels.length) + Puppet::Util::Log.close + end + + def test_levelmethods + assert_nothing_raised() { + Puppet::Util::Log.newdestination("/dev/null") + } + getlevels.each { |level| + assert_nothing_raised() { + Puppet.send(level,"Testing for %s" % level) + } + } + end + + def test_output + Puppet::Util::Log.level = :notice + assert(Puppet.err("This is an error").is_a?(Puppet::Util::Log)) + assert(Puppet.debug("This is debugging").nil?) + Puppet::Util::Log.level = :debug + assert(Puppet.err("This is an error").is_a?(Puppet::Util::Log)) + assert(Puppet.debug("This is debugging").is_a?(Puppet::Util::Log)) + end + + def test_creatingdirs + dir = tempfile() + file = File.join(dir, "logfile") + Puppet::Util::Log.newdestination file + Puppet.info "testing logs" + assert(FileTest.directory?(dir)) + assert(FileTest.file?(file)) + end + + def test_logtags + path = tempfile + File.open(path, "w") { |f| f.puts "yayness" } + + file = Puppet.type(:file).create( + :path => path, + :check => [:owner, :group, :mode, :checksum], + :ensure => :file + ) + file.tags = %w{this is a test} + + property = file.property(:ensure) + assert(property, "Did not get property") + log = nil + assert_nothing_raised { + log = Puppet::Util::Log.new( + :level => :info, + :source => property, + :message => "A test message" + ) + } + + # Now yaml and de-yaml it, and test again + yamllog = YAML.load(YAML.dump(log)) + + {:log => log, :yaml => yamllog}.each do |type, msg| + assert(msg.tags, "Got no tags") + + msg.tags.each do |tag| + assert(msg.tagged?(tag), "Was not tagged with %s" % tag) + end + + assert_equal(msg.tags, property.tags, "Tags were not equal") + assert_equal(msg.source, property.path, "Source was not set correctly") + end + + end + + # Verify that we can pass strings that match printf args + def test_percentlogs + Puppet::Util::Log.newdestination :syslog + + assert_nothing_raised { + Puppet::Util::Log.new( + :level => :info, + :message => "A message with %s in it" + ) + } + end + + # Verify that the error and source are always strings + def test_argsAreStrings + msg = nil + file = Puppet.type(:file).create( + :path => tempfile(), + :check => %w{owner group} + ) + assert_nothing_raised { + msg = Puppet::Util::Log.new(:level => :info, :message => "This is a message") + } + assert_nothing_raised { + msg.source = file + } + + assert_instance_of(String, msg.to_s) + assert_instance_of(String, msg.source) + end + + # Verify that loglevel behaves as one expects + def test_loglevel + path = tempfile() + file = Puppet.type(:file).create( + :path => path, + :ensure => "file" + ) + + assert_nothing_raised { + assert_equal(:notice, file[:loglevel]) + } + + assert_nothing_raised { + file[:loglevel] = "warning" + } + + assert_nothing_raised { + assert_equal(:warning, file[:loglevel]) + } + end + + def test_destination_matching + dest = nil + assert_nothing_raised { + dest = Puppet::Util::Log.newdesttype("Destine") do + def handle(msg) + puts msg + end + end + } + + [:destine, "Destine", "destine"].each do |name| + assert(dest.match?(name), "Did not match %s" % name.inspect) + end + + assert_nothing_raised { + dest.match(:yayness) + } + assert(dest.match("Yayness"), "Did not match yayness") + Puppet::Util::Log.close(dest) + end + + def test_autoflush + file = tempfile + Puppet::Util::Log.close(:console) + Puppet::Util::Log.newdestination(file) + Puppet.warning "A test" + assert(File.read(file) !~ /A test/, + "File defualted to autoflush") + Puppet::Util::Log.flush + assert(File.read(file) =~ /A test/, + "File did not flush") + Puppet::Util::Log.close(file) + + # Now try one with autoflush enabled + Puppet[:autoflush] = true + file = tempfile + Puppet::Util::Log.newdestination(file) + Puppet.warning "A test" + assert(File.read(file) =~ /A test/, + "File did not autoflush") + Puppet::Util::Log.close(file) + end + + def test_reopen + Puppet[:autoflush] = true + file = tempfile + Puppet::Util::Log.close(:console) + Puppet::Util::Log.newdestination(file) + Puppet.warning "A test" + assert(File.read(file) =~ /A test/, + "File did not flush") + # Rename the file + newfile = file + ".old" + File.rename(file, newfile) + + # Send another log + Puppet.warning "Another test" + assert(File.read(newfile) =~ /Another test/, + "File did not rename") + + # Now reopen the log + Puppet::Util::Log.reopen + Puppet.warning "Reopen test" + assert(File.read(file) =~ /Reopen test/, + "File did not reopen") + Puppet::Util::Log.close(file) + end +end + +# $Id$ diff --git a/test/util/metrics.rb b/test/util/metrics.rb new file mode 100755 index 000000000..c4e375e7b --- /dev/null +++ b/test/util/metrics.rb @@ -0,0 +1,81 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppet/util/metric' +require 'puppettest' +require 'puppet/type' + +if Puppet.features.rrd? + class TestMetric < Test::Unit::TestCase + include PuppetTest + + def gendata + totalmax = 1000 + changemax = 1000 + eventmax = 10 + maxdiff = 10 + + types = [Puppet.type(:file), Puppet.type(:package), Puppet.type(:package)] + data = [:total, :managed, :outofsync, :changed, :totalchanges] + events = [:file_changed, :package_installed, :service_started] + + # if this is the first set of data points... + typedata = Hash.new { |typehash,type| + typehash[type] = Hash.new(0) + } + eventdata = Hash.new(0) + typedata = {} + typedata[:total] = rand(totalmax) + typedata[:managed] = rand(typedata[:total]) + typedata[:outofsync] = rand(typedata[:managed]) + typedata[:changed] = rand(typedata[:outofsync]) + typedata[:totalchanges] = rand(changemax) + + events.each { |event| + eventdata[event] = rand(eventmax) + } + + return {:typedata => typedata, :eventdata => eventdata} + end + + def rundata(report, time) + assert_nothing_raised { + gendata.each do |name, data| + report.newmetric(name, data) + end + report.metrics.each { |n, m| m.store(time) } + } + end + + def setup + super + Puppet[:rrdgraph] = true + end + + def test_fakedata + report = Puppet::Transaction::Report.new + time = Time.now.to_i + start = time + 10.times { + rundata(report, time) + time += 300 + } + rundata(report, time) + + report.metrics.each do |n, m| m.graph end + + File.open(File.join(Puppet[:rrddir],"index.html"),"w") { |of| + of.puts "" + report.metrics.each { |name, metric| + of.puts "
" % metric.name + } + } + end + end +else + $stderr.puts "Missing RRD library -- skipping metric tests" +end + +# $Id$ diff --git a/test/util/storage.rb b/test/util/storage.rb new file mode 100755 index 000000000..dd68af5bf --- /dev/null +++ b/test/util/storage.rb @@ -0,0 +1,123 @@ +#!/usr/bin/env ruby + +$:.unshift("../lib").unshift("../../lib") if __FILE__ =~ /\.rb$/ + +require 'puppet' +require 'puppettest' + +class TestStorage < Test::Unit::TestCase + include PuppetTest + + def mkfile + path = tempfile() + File.open(path, "w") { |f| f.puts :yayness } + + f = Puppet.type(:file).create( + :name => path, + :check => %w{checksum type} + ) + + return f + end + + def test_storeandretrieve + path = tempfile() + + f = mkfile() + + # Load first, since that's what we do in the code base; this creates + # all of the necessary directories. + assert_nothing_raised { + Puppet::Util::Storage.load + } + + hash = {:a => :b, :c => :d} + + state = nil + assert_nothing_raised { + state = Puppet::Util::Storage.cache(f) + } + + assert(!state.include?("name")) + + assert_nothing_raised { + state["name"] = hash + } + + assert_nothing_raised { + Puppet::Util::Storage.store + } + assert_nothing_raised { + Puppet::Util::Storage.clear + } + assert_nothing_raised { + Puppet::Util::Storage.load + } + + # Reset it + state = nil + assert_nothing_raised { + state = Puppet::Util::Storage.cache(f) + } + + assert_equal(state["name"], hash) + end + + # we're getting corrupt files, probably because multiple processes + # are reading or writing the file at once + # so we need to test that + def test_multiwrite + f = mkfile() + + value = {:a => :b} + threads = [] + 9.times { |a| + threads << Thread.new { + 9.times { |b| + assert_nothing_raised { + Puppet::Util::Storage.load + state = Puppet::Util::Storage.cache(f) + value.each { |k,v| state[k] = v } + state[:e] = rand(100) + Puppet::Util::Storage.store + } + } + } + } + threads.each { |th| th.join } + end + + def test_emptyrestore + Puppet::Util::Storage.load + Puppet::Util::Storage.store + Puppet::Util::Storage.clear + Puppet::Util::Storage.load + + f = mkfile() + state = Puppet::Util::Storage.cache(f) + assert_same Hash, state.class + assert_equal 0, state.size + end + + def test_caching + hash = nil + one = Puppet::Type.type(:exec).create :title => "/bin/echo one" + [one, :yayness].each do |object| + assert_nothing_raised do + hash = Puppet::Util::Storage.cache(object) + end + assert_equal({}, hash, "Did not get empty hash back for %s" % object) + + hash[:testing] = true + assert_nothing_raised do + hash = Puppet::Util::Storage.cache(object) + end + assert_equal({:testing => true}, hash, "Did not get hash back for %s" % object) + end + assert_raise(ArgumentError, "was able to cache from string") do + Puppet::Util::Storage.cache("somethingelse") + end + end +end + +# $Id$ -- cgit