diff options
| author | Markus Roberts <Markus@reality.com> | 2010-07-09 18:12:17 -0700 |
|---|---|---|
| committer | Markus Roberts <Markus@reality.com> | 2010-07-09 18:12:17 -0700 |
| commit | 3180b9d9b2c844dade1d361326600f7001ec66dd (patch) | |
| tree | 98fe7c5ac7eb942aac9c39f019a17b0b3f5a57f4 /test/util | |
| parent | 543225970225de5697734bfaf0a6eee996802c04 (diff) | |
| download | puppet-3180b9d9b2c844dade1d361326600f7001ec66dd.tar.gz puppet-3180b9d9b2c844dade1d361326600f7001ec66dd.tar.xz puppet-3180b9d9b2c844dade1d361326600f7001ec66dd.zip | |
Code smell: Two space indentation
Replaced 106806 occurances of ^( +)(.*$) with
The ruby community almost universally (i.e. everyone but Luke, Markus, and the other eleven people
who learned ruby in the 1900s) uses two-space indentation.
3 Examples:
The code:
end
# Tell getopt which arguments are valid
def test_get_getopt_args
element = Setting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new
assert_equal([["--foo", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args")
becomes:
end
# Tell getopt which arguments are valid
def test_get_getopt_args
element = Setting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new
assert_equal([["--foo", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args")
The code:
assert_equal(str, val)
assert_instance_of(Float, result)
end
# Now test it with a passed object
becomes:
assert_equal(str, val)
assert_instance_of(Float, result)
end
# Now test it with a passed object
The code:
end
assert_nothing_raised do
klass[:Yay] = "boo"
klass["Cool"] = :yayness
end
becomes:
end
assert_nothing_raised do
klass[:Yay] = "boo"
klass["Cool"] = :yayness
end
Diffstat (limited to 'test/util')
| -rwxr-xr-x | test/util/classgen.rb | 340 | ||||
| -rwxr-xr-x | test/util/execution.rb | 36 | ||||
| -rwxr-xr-x | test/util/fileparsing.rb | 1094 | ||||
| -rwxr-xr-x | test/util/inifile.rb | 254 | ||||
| -rwxr-xr-x | test/util/instance_loader.rb | 58 | ||||
| -rwxr-xr-x | test/util/log.rb | 392 | ||||
| -rwxr-xr-x | test/util/metrics.rb | 102 | ||||
| -rwxr-xr-x | test/util/package.rb | 22 | ||||
| -rwxr-xr-x | test/util/pidlock.rb | 230 | ||||
| -rwxr-xr-x | test/util/settings.rb | 1178 | ||||
| -rwxr-xr-x | test/util/storage.rb | 132 | ||||
| -rwxr-xr-x | test/util/subclass_loader.rb | 138 | ||||
| -rwxr-xr-x | test/util/utiltest.rb | 422 |
13 files changed, 2199 insertions, 2199 deletions
diff --git a/test/util/classgen.rb b/test/util/classgen.rb index 83b64813c..5560764d5 100755 --- a/test/util/classgen.rb +++ b/test/util/classgen.rb @@ -6,236 +6,236 @@ require 'puppet' require 'puppettest' class TestPuppetUtilClassGen < Test::Unit::TestCase - include PuppetTest + include PuppetTest - class FakeBase - class << self - attr_accessor :name - end + class FakeBase + class << self + attr_accessor :name end + end - class GenTest - class << self - include Puppet::Util::ClassGen - end + class GenTest + class << self + include Puppet::Util::ClassGen end + end - def testclasses(name) - sub = Class.new(GenTest) do @name = "base#{name.to_s}" end - self.class.const_set("Base#{name.to_s}", sub) + def testclasses(name) + sub = Class.new(GenTest) do @name = "base#{name.to_s}" end + self.class.const_set("Base#{name.to_s}", sub) - klass = Class.new(FakeBase) do @name = "gen#{name.to_s}"end + klass = Class.new(FakeBase) do @name = "gen#{name.to_s}"end - return sub, klass - end + return sub, klass + end - def test_handleclassconst - sub, klass = testclasses("const") - const = nil - assert_nothing_raised do - const = sub.send(:handleclassconst, klass, klass.name, {}) - end + def test_handleclassconst + sub, klass = testclasses("const") + const = nil + assert_nothing_raised do + const = sub.send(:handleclassconst, klass, klass.name, {}) + end - # make sure the constant is set - assert(defined?(Baseconst::Genconst), "const was not defined") - assert_equal(Baseconst::Genconst.object_id, klass.object_id) + # make sure the constant is set + assert(defined?(Baseconst::Genconst), "const was not defined") + assert_equal(Baseconst::Genconst.object_id, klass.object_id) - # Now make sure don't replace by default - newklass = Class.new(FakeBase) do @name = klass.name end - assert_raise(Puppet::ConstantAlreadyDefined) do - const = sub.send(:handleclassconst, newklass, klass.name, {}) - end - assert_equal(Baseconst::Genconst.object_id, klass.object_id) + # Now make sure don't replace by default + newklass = Class.new(FakeBase) do @name = klass.name end + assert_raise(Puppet::ConstantAlreadyDefined) do + const = sub.send(:handleclassconst, newklass, klass.name, {}) + end + assert_equal(Baseconst::Genconst.object_id, klass.object_id) - # Now make sure we can replace it - assert_nothing_raised do - const = sub.send(:handleclassconst, newklass, klass.name, :overwrite => true) - end - assert_equal(Baseconst::Genconst.object_id, newklass.object_id) + # Now make sure we can replace it + assert_nothing_raised do + const = sub.send(:handleclassconst, newklass, klass.name, :overwrite => true) + end + assert_equal(Baseconst::Genconst.object_id, newklass.object_id) - # Now make sure we can choose our own constant - assert_nothing_raised do + # Now make sure we can choose our own constant + assert_nothing_raised do - const = sub.send( - :handleclassconst, newklass, klass.name, + const = sub.send( + :handleclassconst, newklass, klass.name, - :constant => "Fooness") - end - assert(defined?(Baseconst::Fooness), "Specified constant was not defined") + :constant => "Fooness") + end + assert(defined?(Baseconst::Fooness), "Specified constant was not defined") - # And make sure prefixes work - assert_nothing_raised do + # And make sure prefixes work + assert_nothing_raised do - const = sub.send( - :handleclassconst, newklass, klass.name, + const = sub.send( + :handleclassconst, newklass, klass.name, - :prefix => "Test") - end - assert(defined?(Baseconst::TestGenconst), "prefix was not used") + :prefix => "Test") end + assert(defined?(Baseconst::TestGenconst), "prefix was not used") + end - def test_initclass_preinit - sub, klass = testclasses("preinit") + def test_initclass_preinit + sub, klass = testclasses("preinit") - class << klass - attr_accessor :set - def preinit - @set = true - end - end + class << klass + attr_accessor :set + def preinit + @set = true + end + end - assert(!klass.set, "Class was already initialized") + assert(!klass.set, "Class was already initialized") - assert_nothing_raised do sub.send(:initclass, klass, {}) end + assert_nothing_raised do sub.send(:initclass, klass, {}) end - assert(klass.set, "Class was not initialized") - end + assert(klass.set, "Class was not initialized") + end - def test_initclass_initvars - sub, klass = testclasses("initvars") + def test_initclass_initvars + sub, klass = testclasses("initvars") - class << klass - attr_accessor :set - def initvars - @set = true - end - end + class << klass + attr_accessor :set + def initvars + @set = true + end + end - assert(!klass.set, "Class was already initialized") + assert(!klass.set, "Class was already initialized") - assert_nothing_raised do sub.send(:initclass, klass, {}) end + assert_nothing_raised do sub.send(:initclass, klass, {}) end - assert(klass.set, "Class was not initialized") - end + assert(klass.set, "Class was not initialized") + end - def test_initclass_attributes - sub, klass = testclasses("attributes") + def test_initclass_attributes + sub, klass = testclasses("attributes") - class << klass - attr_accessor :one, :two, :three - end + class << klass + attr_accessor :one, :two, :three + end - assert(!klass.one, "'one' was already set") + assert(!klass.one, "'one' was already set") - assert_nothing_raised do sub.send( - :initclass, klass, + assert_nothing_raised do sub.send( + :initclass, klass, - :attributes => {:one => :a, :two => :b}) end + :attributes => {:one => :a, :two => :b}) end - assert_equal(:a, klass.one, "Class was initialized incorrectly") - assert_equal(:b, klass.two, "Class was initialized incorrectly") - assert_nil(klass.three, "Class was initialized incorrectly") - end + assert_equal(:a, klass.one, "Class was initialized incorrectly") + assert_equal(:b, klass.two, "Class was initialized incorrectly") + assert_nil(klass.three, "Class was initialized incorrectly") + end - def test_initclass_include_and_extend - sub, klass = testclasses("include_and_extend") + def test_initclass_include_and_extend + sub, klass = testclasses("include_and_extend") - incl = Module.new do - attr_accessor :included - end - self.class.const_set("Incl", incl) + incl = Module.new do + attr_accessor :included + end + self.class.const_set("Incl", incl) - ext = Module.new do - attr_accessor :extended - end - self.class.const_set("Ext", ext) + ext = Module.new do + attr_accessor :extended + end + self.class.const_set("Ext", ext) - assert(! klass.respond_to?(:extended), "Class already responds to extended") - assert(! klass.new.respond_to?(:included), "Class already responds to included") + assert(! klass.respond_to?(:extended), "Class already responds to extended") + assert(! klass.new.respond_to?(:included), "Class already responds to included") - assert_nothing_raised do sub.send( - :initclass, klass, + assert_nothing_raised do sub.send( + :initclass, klass, - :include => incl, :extend => ext) - end - - assert(klass.respond_to?(:extended), "Class did not get extended") - assert(klass.new.respond_to?(:included), "Class did not include") + :include => incl, :extend => ext) end - def test_genclass - hash = {} - array = [] + assert(klass.respond_to?(:extended), "Class did not get extended") + assert(klass.new.respond_to?(:included), "Class did not include") + end - name = "yayness" - klass = nil - assert_nothing_raised { - klass = GenTest.genclass(name, :array => array, :hash => hash, :parent => FakeBase) do - class << self - attr_accessor :name - end - end - } + def test_genclass + hash = {} + array = [] - assert(klass.respond_to?(:name=), "Class did not execute block") + name = "yayness" + klass = nil + assert_nothing_raised { + klass = GenTest.genclass(name, :array => array, :hash => hash, :parent => FakeBase) do + class << self + attr_accessor :name + end + end + } + + assert(klass.respond_to?(:name=), "Class did not execute block") - assert( - hash.include?(klass.name), + assert( + hash.include?(klass.name), - "Class did not get added to hash") + "Class did not get added to hash") - assert( - array.include?(klass), + assert( + array.include?(klass), - "Class did not get added to array") - assert_equal(klass.superclass, FakeBase, "Parent class was wrong") + "Class did not get added to array") + assert_equal(klass.superclass, FakeBase, "Parent class was wrong") + end + + # Make sure we call a preinithook, if there is one. + def test_inithooks + newclass = Class.new(FakeBase) do + class << self + attr_accessor :preinited, :postinited + end + def self.preinit + self.preinited = true + end + def self.postinit + self.postinited = true + end end - # Make sure we call a preinithook, if there is one. - def test_inithooks - newclass = Class.new(FakeBase) do - class << self - attr_accessor :preinited, :postinited - end - def self.preinit - self.preinited = true - end - def self.postinit - self.postinited = true - end - end + klass = nil + assert_nothing_raised { + klass = GenTest.genclass(:funtest, :parent => newclass) + } - klass = nil - assert_nothing_raised { - klass = GenTest.genclass(:funtest, :parent => newclass) - } - - assert(klass.preinited, "prehook did not get called") - assert(klass.postinited, "posthook did not get called") - end + assert(klass.preinited, "prehook did not get called") + assert(klass.postinited, "posthook did not get called") + end - def test_modulegen - hash = {} - array = [] + def test_modulegen + hash = {} + array = [] - name = "modness" - mod = nil - assert_nothing_raised { - mod = GenTest.genmodule(name, :array => array, :hash => hash) do - class << self - attr_accessor :yaytest - end + name = "modness" + mod = nil + assert_nothing_raised { + mod = GenTest.genmodule(name, :array => array, :hash => hash) do + class << self + attr_accessor :yaytest + end - @yaytest = true - end - } + @yaytest = true + end + } - assert(mod.respond_to?(:yaytest), "Class did not execute block") + assert(mod.respond_to?(:yaytest), "Class did not execute block") - assert_instance_of(Module, mod) - assert(hash.include?(mod.name), "Class did not get added to hash") - assert(array.include?(mod), "Class did not get added to array") - end + assert_instance_of(Module, mod) + assert(hash.include?(mod.name), "Class did not get added to hash") + assert(array.include?(mod), "Class did not get added to array") + end - def test_genconst_string - const = nil - assert_nothing_raised do - const = GenTest.send(:genconst_string, :testing, :prefix => "Yayness") - end - assert_equal("YaynessTesting", const) + def test_genconst_string + const = nil + assert_nothing_raised do + const = GenTest.send(:genconst_string, :testing, :prefix => "Yayness") end + assert_equal("YaynessTesting", const) + end end diff --git a/test/util/execution.rb b/test/util/execution.rb index be85d6502..e6509582e 100755 --- a/test/util/execution.rb +++ b/test/util/execution.rb @@ -6,28 +6,28 @@ require 'puppet' require 'puppettest' class TestPuppetUtilExecution < Test::Unit::TestCase - include PuppetTest + include PuppetTest - def test_withenv - ENV["testing"] = "yay" + def test_withenv + ENV["testing"] = "yay" - assert_nothing_raised do - Puppet::Util::Execution.withenv :testing => "foo" do - $ran = ENV["testing"] - end - end - - assert_equal("yay", ENV["testing"]) - assert_equal("foo", $ran) + assert_nothing_raised do + Puppet::Util::Execution.withenv :testing => "foo" do + $ran = ENV["testing"] + end + end - ENV["rah"] = "yay" - assert_raise(ArgumentError) do - Puppet::Util::Execution.withenv :testing => "foo" do - raise ArgumentError, "yay" - end - end + assert_equal("yay", ENV["testing"]) + assert_equal("foo", $ran) - assert_equal("yay", ENV["rah"]) + ENV["rah"] = "yay" + assert_raise(ArgumentError) do + Puppet::Util::Execution.withenv :testing => "foo" do + raise ArgumentError, "yay" + end end + + assert_equal("yay", ENV["rah"]) + end end diff --git a/test/util/fileparsing.rb b/test/util/fileparsing.rb index eaf57cef6..05ed80a79 100755 --- a/test/util/fileparsing.rb +++ b/test/util/fileparsing.rb @@ -8,718 +8,718 @@ require 'puppet' require 'puppet/util/fileparsing' class TestUtilFileParsing < Test::Unit::TestCase - include PuppetTest - include PuppetTest::FileParsing + include PuppetTest + include PuppetTest::FileParsing - class FParser - include Puppet::Util::FileParsing - end + class FParser + include Puppet::Util::FileParsing + end - def setup - super - @parser = FParser.new - end + def setup + super + @parser = FParser.new + end - def test_lines - assert_equal("\n", @parser.line_separator, "Default separator was incorrect") + def test_lines + assert_equal("\n", @parser.line_separator, "Default separator was incorrect") - {"\n" => ["one two\nthree four", "one two\nthree four\n"], - "\t" => ["one two\tthree four", "one two\tthree four\t"], - }.each do |sep, tests| - assert_nothing_raised do - @parser.line_separator = sep - end + {"\n" => ["one two\nthree four", "one two\nthree four\n"], + "\t" => ["one two\tthree four", "one two\tthree four\t"], + }.each do |sep, tests| + assert_nothing_raised do + @parser.line_separator = sep + end - assert_equal( - sep, @parser.line_separator, + assert_equal( + sep, @parser.line_separator, - "Did not set separator") + "Did not set separator") - tests.each do |test| - assert_equal(["one two", "three four"], @parser.lines(test), "Incorrectly parsed #{test.inspect}") - end - end + tests.each do |test| + assert_equal(["one two", "three four"], @parser.lines(test), "Incorrectly parsed #{test.inspect}") + end end + end - # Make sure parse calls the appropriate methods or errors out - def test_parse - @parser.meta_def(:parse_line) do |line| - line.split(/\s+/) - end - - text = "one line\ntwo line" - should = [%w{one line}, %w{two line}] - ret = nil - assert_nothing_raised do - ret = @parser.parse(text) - end + # Make sure parse calls the appropriate methods or errors out + def test_parse + @parser.meta_def(:parse_line) do |line| + line.split(/\s+/) + end - assert_equal(should, ret) + text = "one line\ntwo line" + should = [%w{one line}, %w{two line}] + ret = nil + assert_nothing_raised do + ret = @parser.parse(text) end - # Make sure we correctly handle different kinds of text lines. - def test_text_line - comment = "# this is a comment" + assert_equal(should, ret) + end - # Make sure it fails if no regex is passed - assert_raise(ArgumentError) do - @parser.text_line :comment - end + # Make sure we correctly handle different kinds of text lines. + def test_text_line + comment = "# this is a comment" - # define a text matching comment record - assert_nothing_raised do - @parser.text_line :comment, :match => /^#/ - end + # Make sure it fails if no regex is passed + assert_raise(ArgumentError) do + @parser.text_line :comment + end - # Make sure it matches - assert_nothing_raised do + # define a text matching comment record + assert_nothing_raised do + @parser.text_line :comment, :match => /^#/ + end - assert_equal( - {:record_type => :comment, :line => comment}, + # Make sure it matches + assert_nothing_raised do - @parser.parse_line(comment)) - end + assert_equal( + {:record_type => :comment, :line => comment}, - # But not something else - assert_nothing_raised do - assert_nil(@parser.parse_line("some other text")) - end + @parser.parse_line(comment)) + end - # Now define another type and make sure we get the right one back - assert_nothing_raised do - @parser.text_line :blank, :match => /^\s*$/ - end + # But not something else + assert_nothing_raised do + assert_nil(@parser.parse_line("some other text")) + end - # The comment should still match - assert_nothing_raised do + # Now define another type and make sure we get the right one back + assert_nothing_raised do + @parser.text_line :blank, :match => /^\s*$/ + end - assert_equal( - {:record_type => :comment, :line => comment}, + # The comment should still match + assert_nothing_raised do - @parser.parse_line(comment)) - end + assert_equal( + {:record_type => :comment, :line => comment}, - # As should our new line type - assert_nothing_raised do + @parser.parse_line(comment)) + end - assert_equal( - {:record_type => :blank, :line => ""}, + # As should our new line type + assert_nothing_raised do - @parser.parse_line("")) - end + assert_equal( + {:record_type => :blank, :line => ""}, + @parser.parse_line("")) end - def test_parse_line - Puppet[:trace] = false - - comment = "# this is a comment" + end - # Make sure it fails if we don't have any record types defined - assert_raise(Puppet::DevError) do - @parser.parse_line(comment) - end + def test_parse_line + Puppet[:trace] = false - # Now define a text matching comment record - assert_nothing_raised do - @parser.text_line :comment, :match => /^#/ - end + comment = "# this is a comment" - # And make sure we can't define another one with the same name - assert_raise(ArgumentError) do - @parser.text_line :comment, :match => /^"/ - end - - result = nil - assert_nothing_raised("Did not parse text line") do - result = @parser.parse_line comment - end + # Make sure it fails if we don't have any record types defined + assert_raise(Puppet::DevError) do + @parser.parse_line(comment) + end - assert_equal({:record_type => :comment, :line => comment}, result) + # Now define a text matching comment record + assert_nothing_raised do + @parser.text_line :comment, :match => /^#/ + end - # Make sure we just return nil on unmatched lines. - assert_nothing_raised("Did not parse text line") do - result = @parser.parse_line "No match for this" - end + # And make sure we can't define another one with the same name + assert_raise(ArgumentError) do + @parser.text_line :comment, :match => /^"/ + end - assert_nil(result, "Somehow matched an empty line") + result = nil + assert_nothing_raised("Did not parse text line") do + result = @parser.parse_line comment + end - # Now define another type of comment, and make sure both types get - # correctly returned as comments - assert_nothing_raised do - @parser.text_line :comment2, :match => /^"/ - end + assert_equal({:record_type => :comment, :line => comment}, result) - assert_nothing_raised("Did not parse old comment") do - assert_equal({:record_type => :comment, :line => comment}, @parser.parse_line(comment)) - end - comment = '" another type of comment' - assert_nothing_raised("Did not parse new comment") do - assert_equal({:record_type => :comment2, :line => comment}, @parser.parse_line(comment)) - end + # Make sure we just return nil on unmatched lines. + assert_nothing_raised("Did not parse text line") do + result = @parser.parse_line "No match for this" + end - # Now define two overlapping record types and make sure we keep the - # correct order. We do first match, not longest match. - assert_nothing_raised do - @parser.text_line :one, :match => /^y/ - @parser.text_line :two, :match => /^yay/ - end + assert_nil(result, "Somehow matched an empty line") - assert_nothing_raised do - assert_equal({:record_type => :one, :line => "yayness"}, @parser.parse_line("yayness")) - end + # Now define another type of comment, and make sure both types get + # correctly returned as comments + assert_nothing_raised do + @parser.text_line :comment2, :match => /^"/ + end + assert_nothing_raised("Did not parse old comment") do + assert_equal({:record_type => :comment, :line => comment}, @parser.parse_line(comment)) + end + comment = '" another type of comment' + assert_nothing_raised("Did not parse new comment") do + assert_equal({:record_type => :comment2, :line => comment}, @parser.parse_line(comment)) end - def test_record_line - tabrecord = "tab separated content" - spacerecord = "space separated content" + # Now define two overlapping record types and make sure we keep the + # correct order. We do first match, not longest match. + assert_nothing_raised do + @parser.text_line :one, :match => /^y/ + @parser.text_line :two, :match => /^yay/ + end - # Make sure we always require an appropriate set of options - [{:separator => "\t"}, {}, {:fields => %w{record_type}}].each do |opts| - assert_raise(ArgumentError, "Accepted #{opts.inspect}") do - @parser.record_line :record, opts - end - end + assert_nothing_raised do + assert_equal({:record_type => :one, :line => "yayness"}, @parser.parse_line("yayness")) + end - # Verify that our default separator is tabs - tabs = nil - assert_nothing_raised do - tabs = @parser.record_line :tabs, :fields => [:name, :first, :second] - end + end - # Make sure out tab line gets matched - tabshould = {:record_type => :tabs, :name => "tab", :first => "separated", :second => "content"} - assert_nothing_raised do - assert_equal(tabshould, @parser.handle_record_line(tabrecord, tabs)) - end + def test_record_line + tabrecord = "tab separated content" + spacerecord = "space separated content" - # Now add our space-separated record type - spaces = nil - assert_nothing_raised do - spaces = @parser.record_line :spaces, :fields => [:name, :first, :second] - end + # Make sure we always require an appropriate set of options + [{:separator => "\t"}, {}, {:fields => %w{record_type}}].each do |opts| + assert_raise(ArgumentError, "Accepted #{opts.inspect}") do + @parser.record_line :record, opts + end + end - # Now make sure both lines parse correctly - spaceshould = {:record_type => :spaces, :name => "space", :first => "separated", :second => "content"} + # Verify that our default separator is tabs + tabs = nil + assert_nothing_raised do + tabs = @parser.record_line :tabs, :fields => [:name, :first, :second] + end - assert_nothing_raised do - assert_equal(tabshould, @parser.handle_record_line(tabrecord, tabs)) - assert_equal(spaceshould, @parser.handle_record_line(spacerecord, spaces)) - end + # Make sure out tab line gets matched + tabshould = {:record_type => :tabs, :name => "tab", :first => "separated", :second => "content"} + assert_nothing_raised do + assert_equal(tabshould, @parser.handle_record_line(tabrecord, tabs)) end - def test_to_line - @parser.text_line :comment, :match => /^#/ - @parser.text_line :blank, :match => /^\s*$/ - @parser.record_line :record, :fields => %w{name one two}, :joiner => "\t" - - johnny = {:record_type => :record, :name => "johnny", :one => "home", - :two => "yay"} - bill = {:record_type => :record, :name => "bill", :one => "work", - :two => "boo"} - - records = { - :comment => {:record_type => :comment, :line => "# This is a file"}, - :blank => {:record_type => :blank, :line => ""}, - :johnny => johnny, - :bill => bill - } - - lines = { - :comment => "# This is a file", - :blank => "", - :johnny => "johnny home yay", - :bill => "bill work boo" - } - - records.each do |name, details| - result = nil - assert_nothing_raised do - result = @parser.to_line(details) - end - - assert_equal(lines[name], result) - end - order = [:comment, :blank, :johnny, :bill] + # Now add our space-separated record type + spaces = nil + assert_nothing_raised do + spaces = @parser.record_line :spaces, :fields => [:name, :first, :second] + end - file = order.collect { |name| lines[name] }.join("\n") + # Now make sure both lines parse correctly + spaceshould = {:record_type => :spaces, :name => "space", :first => "separated", :second => "content"} - ordered_records = order.collect { |name| records[name] } + assert_nothing_raised do + assert_equal(tabshould, @parser.handle_record_line(tabrecord, tabs)) + assert_equal(spaceshould, @parser.handle_record_line(spacerecord, spaces)) + end + end + + def test_to_line + @parser.text_line :comment, :match => /^#/ + @parser.text_line :blank, :match => /^\s*$/ + @parser.record_line :record, :fields => %w{name one two}, :joiner => "\t" + + johnny = {:record_type => :record, :name => "johnny", :one => "home", + :two => "yay"} + bill = {:record_type => :record, :name => "bill", :one => "work", + :two => "boo"} + + records = { + :comment => {:record_type => :comment, :line => "# This is a file"}, + :blank => {:record_type => :blank, :line => ""}, + :johnny => johnny, + :bill => bill + } + + lines = { + :comment => "# This is a file", + :blank => "", + :johnny => "johnny home yay", + :bill => "bill work boo" + } + + records.each do |name, details| + result = nil + assert_nothing_raised do + result = @parser.to_line(details) + end + + assert_equal(lines[name], result) + end + order = [:comment, :blank, :johnny, :bill] - # Make sure we default to a trailing separator - assert_equal(true, @parser.trailing_separator, "Did not default to a trailing separtor") + file = order.collect { |name| lines[name] }.join("\n") - # Start without a trailing separator - @parser.trailing_separator = false - assert_nothing_raised do - assert_equal(file, @parser.to_file(ordered_records)) - end + ordered_records = order.collect { |name| records[name] } - # Now with a trailing separator - file += "\n" - @parser.trailing_separator = true - assert_nothing_raised do - assert_equal(file, @parser.to_file(ordered_records)) - end + # Make sure we default to a trailing separator + assert_equal(true, @parser.trailing_separator, "Did not default to a trailing separtor") - # Now try it with a different separator, so we're not just catching - # defaults - file.gsub!("\n", "\t") - @parser.line_separator = "\t" - assert_nothing_raised do - assert_equal(file, @parser.to_file(ordered_records)) - end + # Start without a trailing separator + @parser.trailing_separator = false + assert_nothing_raised do + assert_equal(file, @parser.to_file(ordered_records)) end - # Make sure fields that are marked absent get replaced with the appropriate - # string. - def test_absent_fields - record = nil - assert_nothing_raised do - record = @parser.record_line :record, :fields => %w{one two three}, - :optional => %w{two three} - end - assert_equal("", record.absent, "Did not set a default absent string") + # Now with a trailing separator + file += "\n" + @parser.trailing_separator = true + assert_nothing_raised do + assert_equal(file, @parser.to_file(ordered_records)) + end - result = nil - assert_nothing_raised do + # Now try it with a different separator, so we're not just catching + # defaults + file.gsub!("\n", "\t") + @parser.line_separator = "\t" + assert_nothing_raised do + assert_equal(file, @parser.to_file(ordered_records)) + end + end + + # Make sure fields that are marked absent get replaced with the appropriate + # string. + def test_absent_fields + record = nil + assert_nothing_raised do + record = @parser.record_line :record, :fields => %w{one two three}, + :optional => %w{two three} + end + assert_equal("", record.absent, "Did not set a default absent string") - result = @parser.to_line( - :record_type => :record, + result = nil + assert_nothing_raised do - :one => "a", :two => :absent, :three => "b") - end + result = @parser.to_line( + :record_type => :record, - assert_equal("a b", result, "Absent was not correctly replaced") + :one => "a", :two => :absent, :three => "b") + end - # Now try using a different replacement character - record.absent = "*" # Because cron is a pain in my ass - assert_nothing_raised do - result = @parser.to_line(:record_type => :record, :one => "a", :two => :absent, :three => "b") - end + assert_equal("a b", result, "Absent was not correctly replaced") - assert_equal("a * b", result, "Absent was not correctly replaced") + # Now try using a different replacement character + record.absent = "*" # Because cron is a pain in my ass + assert_nothing_raised do + result = @parser.to_line(:record_type => :record, :one => "a", :two => :absent, :three => "b") + end - # Make sure we deal correctly with the string 'absent' - assert_nothing_raised do + assert_equal("a * b", result, "Absent was not correctly replaced") - result = @parser.to_line( - :record_type => :record, + # Make sure we deal correctly with the string 'absent' + assert_nothing_raised do - :one => "a", :two => "b", :three => 'absent') - end + result = @parser.to_line( + :record_type => :record, - assert_equal("a b absent", result, "Replaced string 'absent'") + :one => "a", :two => "b", :three => 'absent') + end - # And, of course, make sure we can swap things around. - assert_nothing_raised do + assert_equal("a b absent", result, "Replaced string 'absent'") - result = @parser.to_line( - :record_type => :record, + # And, of course, make sure we can swap things around. + assert_nothing_raised do - :one => "a", :two => "b", :three => :absent) - end + result = @parser.to_line( + :record_type => :record, - assert_equal("a b *", result, "Absent was not correctly replaced") + :one => "a", :two => "b", :three => :absent) end - # Make sure we can specify a different join character than split character - def test_split_join_record_line - check = proc do |start, record, final| - # Check parsing first - result = @parser.parse_line(start) - [:one, :two].each do |param| + assert_equal("a b *", result, "Absent was not correctly replaced") + end - assert_equal( - record[param], result[param], + # Make sure we can specify a different join character than split character + def test_split_join_record_line + check = proc do |start, record, final| + # Check parsing first + result = @parser.parse_line(start) + [:one, :two].each do |param| - "Did not correctly parse #{start.inspect}") - end + assert_equal( + record[param], result[param], - # And generating - assert_equal(final, @parser.to_line(result), "Did not correctly generate #{final.inspect} from #{record.inspect}") - end + "Did not correctly parse #{start.inspect}") + end - # First try it with symmetric characters - @parser.record_line :symmetric, :fields => %w{one two}, - :separator => " " + # And generating + assert_equal(final, @parser.to_line(result), "Did not correctly generate #{final.inspect} from #{record.inspect}") + end - check.call "a b", {:one => "a", :two => "b"}, "a b" - @parser.clear_records + # First try it with symmetric characters + @parser.record_line :symmetric, :fields => %w{one two}, + :separator => " " - # Now assymetric but both strings - @parser.record_line :asymmetric, :fields => %w{one two}, - :separator => "\t", :joiner => " " + check.call "a b", {:one => "a", :two => "b"}, "a b" + @parser.clear_records - check.call "a\tb", {:one => "a", :two => "b"}, "a b" - @parser.clear_records + # Now assymetric but both strings + @parser.record_line :asymmetric, :fields => %w{one two}, + :separator => "\t", :joiner => " " - # And assymmetric with a regex - @parser.record_line :asymmetric2, :fields => %w{one two}, - :separator => /\s+/, :joiner => " " + check.call "a\tb", {:one => "a", :two => "b"}, "a b" + @parser.clear_records - check.call "a\tb", {:one => "a", :two => "b"}, "a b" - check.call "a b", {:one => "a", :two => "b"}, "a b" - end + # And assymmetric with a regex + @parser.record_line :asymmetric2, :fields => %w{one two}, + :separator => /\s+/, :joiner => " " - # Make sure we correctly regenerate files. - def test_to_file - @parser.text_line :comment, :match => /^#/ - @parser.text_line :blank, :match => /^\s*$/ - @parser.record_line :record, :fields => %w{name one two} + check.call "a\tb", {:one => "a", :two => "b"}, "a b" + check.call "a b", {:one => "a", :two => "b"}, "a b" + end - text = "# This is a comment + # Make sure we correctly regenerate files. + def test_to_file + @parser.text_line :comment, :match => /^#/ + @parser.text_line :blank, :match => /^\s*$/ + @parser.record_line :record, :fields => %w{name one two} + + text = "# This is a comment johnny one two billy three four\n" # Just parse and generate, to make sure it's isomorphic. assert_nothing_raised do - assert_equal(text, @parser.to_file(@parser.parse(text)), - "parsing was not isomorphic") - end + assert_equal(text, @parser.to_file(@parser.parse(text)), + "parsing was not isomorphic") end + end - def test_valid_attrs - @parser.record_line :record, :fields => %w{one two three} - - - assert( - @parser.valid_attr?(:record, :one), - - "one was considered invalid") + def test_valid_attrs + @parser.record_line :record, :fields => %w{one two three} - assert( - @parser.valid_attr?(:record, :ensure), + assert( + @parser.valid_attr?(:record, :one), - "ensure was considered invalid") + "one was considered invalid") - assert( - ! @parser.valid_attr?(:record, :four), + assert( + @parser.valid_attr?(:record, :ensure), - "four was considered valid") - end + "ensure was considered invalid") - def test_record_blocks - options = nil - assert_nothing_raised do - # Just do a simple test - options = @parser.record_line :record, - :fields => %w{name alias info} do |line| - line = line.dup - ret = {} - if line.sub!(/(\w+)\s*/, '') - ret[:name] = $1 - else - return nil - end - if line.sub!(/(#.+)/, '') - desc = $1.sub(/^#\s*/, '') - ret[:description] = desc unless desc == "" - end + assert( + ! @parser.valid_attr?(:record, :four), - ret[:alias] = line.split(/\s+/) if line != "" + "four was considered valid") + end - return ret - end + def test_record_blocks + options = nil + assert_nothing_raised do + # Just do a simple test + options = @parser.record_line :record, + :fields => %w{name alias info} do |line| + line = line.dup + ret = {} + if line.sub!(/(\w+)\s*/, '') + ret[:name] = $1 + else + return nil end - values = { - :name => "tcpmux", - :description => "TCP port service multiplexer", - :alias => ["sink"] - } - - { - - "tcpmux " => [:name], - "tcpmux" => [:name], - "tcpmux sink" => [:name, :port, :protocols, :alias], - "tcpmux # TCP port service multiplexer" => - [:name, :description, :port, :protocols], - "tcpmux sink # TCP port service multiplexer" => - [:name, :description, :port, :alias, :protocols], - "tcpmux sink null # TCP port service multiplexer" => - [:name, :description, :port, :alias, :protocols], - }.each do |line, should| - result = nil - assert_nothing_raised do - result = @parser.handle_record_line(line, options) - end - assert(result, "Did not get a result back for '#{line}'") - should.each do |field| - if field == :alias and line =~ /null/ - assert_equal(%w{sink null}, result[field], "Field #{field} was not right in '#{line}'") - else - assert_equal(values[field], result[field], "Field #{field} was not right in '#{line}'") - end - end + if line.sub!(/(#.+)/, '') + desc = $1.sub(/^#\s*/, '') + ret[:description] = desc unless desc == "" end + ret[:alias] = line.split(/\s+/) if line != "" + return ret + end end - # Make sure we correctly handle optional fields. We'll skip this - # functionality until we really know we need it. - def test_optional_fields - assert_nothing_raised do - @parser.record_line :record, - :fields => %w{one two three four}, - :optional => %w{three four}, - :absent => "*", - :separator => " " # A single space - end + values = { + :name => "tcpmux", + :description => "TCP port service multiplexer", + :alias => ["sink"] + } + + { + + "tcpmux " => [:name], + "tcpmux" => [:name], + "tcpmux sink" => [:name, :port, :protocols, :alias], + "tcpmux # TCP port service multiplexer" => + [:name, :description, :port, :protocols], + "tcpmux sink # TCP port service multiplexer" => + [:name, :description, :port, :alias, :protocols], + "tcpmux sink null # TCP port service multiplexer" => + [:name, :description, :port, :alias, :protocols], + }.each do |line, should| + result = nil + assert_nothing_raised do + result = @parser.handle_record_line(line, options) + end + assert(result, "Did not get a result back for '#{line}'") + should.each do |field| + if field == :alias and line =~ /null/ + assert_equal(%w{sink null}, result[field], "Field #{field} was not right in '#{line}'") + else + assert_equal(values[field], result[field], "Field #{field} was not right in '#{line}'") + end + end + end - { "a b c d" => [], - "a b * d" => [:three], - "a b * *" => [:three, :four], - "a b c *" => [:four] - }.each do |line, absentees| - record = nil - assert_nothing_raised do - record = @parser.parse_line(line) - end - - # Absent field is :absent, not "*" inside the record - absentees.each do |absentee| - assert_equal(:absent, record[absentee]) - end - - # Now regenerate the line - newline = nil - assert_nothing_raised do - newline = @parser.to_line(record) - end - - # And make sure they're equal - assert_equal(line, newline) - end - # Now make sure it pukes if we don't provide the required fields - assert_raise(ArgumentError) do - @parser.to_line(:record_type => :record, :one => "yay") - end + end + + # Make sure we correctly handle optional fields. We'll skip this + # functionality until we really know we need it. + def test_optional_fields + assert_nothing_raised do + @parser.record_line :record, + :fields => %w{one two three four}, + :optional => %w{three four}, + :absent => "*", + :separator => " " # A single space end - def test_record_rts - # Start with the default - assert_nothing_raised do - @parser.record_line :record, - :fields => %w{one two three four}, - :optional => %w{three four} - end + { "a b c d" => [], + "a b * d" => [:three], + "a b * *" => [:three, :four], + "a b c *" => [:four] + }.each do |line, absentees| + record = nil + assert_nothing_raised do + record = @parser.parse_line(line) + end + + # Absent field is :absent, not "*" inside the record + absentees.each do |absentee| + assert_equal(:absent, record[absentee]) + end + + # Now regenerate the line + newline = nil + assert_nothing_raised do + newline = @parser.to_line(record) + end + + # And make sure they're equal + assert_equal(line, newline) + end + # Now make sure it pukes if we don't provide the required fields + assert_raise(ArgumentError) do + @parser.to_line(:record_type => :record, :one => "yay") + end + end + + def test_record_rts + # Start with the default + assert_nothing_raised do + @parser.record_line :record, + :fields => %w{one two three four}, + :optional => %w{three four} + end - assert_equal( - "a b ", - @parser.to_line(:record_type => :record, :one => "a", :two => "b") - ) + assert_equal( + "a b ", - # Now say yes to removing - @parser.clear_records - assert_nothing_raised do - @parser.record_line :record, - :fields => %w{one two three four}, - :optional => %w{three four}, - :rts => true - end + @parser.to_line(:record_type => :record, :one => "a", :two => "b") + ) + # Now say yes to removing + @parser.clear_records + assert_nothing_raised do + @parser.record_line :record, + :fields => %w{one two three four}, + :optional => %w{three four}, + :rts => true + end - assert_equal( - "a b", - @parser.to_line(:record_type => :record, :one => "a", :two => "b") - ) + assert_equal( + "a b", - # Lastly, try a regex - @parser.clear_records - assert_nothing_raised do - @parser.record_line :record, - :fields => %w{one two three four}, - :optional => %w{three four}, - :absent => "*", - :rts => /[ *]+$/ - end + @parser.to_line(:record_type => :record, :one => "a", :two => "b") + ) + # Lastly, try a regex + @parser.clear_records + assert_nothing_raised do + @parser.record_line :record, + :fields => %w{one two three four}, + :optional => %w{three four}, + :absent => "*", + :rts => /[ *]+$/ + end - assert_equal( - "a b", - @parser.to_line(:record_type => :record, :one => "a", :two => "b") - ) - end + assert_equal( + "a b", - # Make sure the last field can contain the separator, as crontabs do, and - # that we roll them all up by default. - def test_field_rollups - @parser.record_line :yes, :fields => %w{name one two} + @parser.to_line(:record_type => :record, :one => "a", :two => "b") + ) + end - result = nil - assert_nothing_raised do - result = @parser.send(:parse_line, "Name One Two Three") - end + # Make sure the last field can contain the separator, as crontabs do, and + # that we roll them all up by default. + def test_field_rollups + @parser.record_line :yes, :fields => %w{name one two} - assert_equal( - "Two Three", result[:two], + result = nil + assert_nothing_raised do + result = @parser.send(:parse_line, "Name One Two Three") + end - "Did not roll up last fields by default") + assert_equal( + "Two Three", result[:two], - @parser = FParser.new - assert_nothing_raised("Could not create record that rolls up fields") do - @parser.record_line :no, :fields => %w{name one two}, :rollup => false - end + "Did not roll up last fields by default") - result = nil - assert_nothing_raised do - result = @parser.send(:parse_line, "Name One Two Three") - end + @parser = FParser.new + assert_nothing_raised("Could not create record that rolls up fields") do + @parser.record_line :no, :fields => %w{name one two}, :rollup => false + end + + result = nil + assert_nothing_raised do + result = @parser.send(:parse_line, "Name One Two Three") + end + + assert_equal( + "Two", result[:two], - assert_equal( - "Two", result[:two], + "Rolled up last fields when rollup => false") + end - "Rolled up last fields when rollup => false") + def test_text_blocks + record = nil + assert_nothing_raised do + record = @parser.text_line :name, :match => %r{^#} do |line| + {:line => line.upcase} + end end - def test_text_blocks - record = nil - assert_nothing_raised do - record = @parser.text_line :name, :match => %r{^#} do |line| - {:line => line.upcase} - end - end + assert( + record.respond_to?(:process), - assert( - record.respond_to?(:process), + "Block was not used with text line") - "Block was not used with text line") + assert_equal("YAYNESS", record.process("yayness")[:line], + "Did not call process method") + end - assert_equal("YAYNESS", record.process("yayness")[:line], - "Did not call process method") + def test_hooks + record = nil + # First try it with a normal record + assert_nothing_raised("Could not set hooks") do + record = @parser.record_line :yay, :fields => %w{one two}, + :post_parse => proc { |hash| hash[:posted] = true }, + :pre_gen => proc { |hash| hash[:one] = hash[:one].upcase }, + :to_line => proc { |hash| "# Line\n" + join(hash) } end - def test_hooks - record = nil - # First try it with a normal record - assert_nothing_raised("Could not set hooks") do - record = @parser.record_line :yay, :fields => %w{one two}, - :post_parse => proc { |hash| hash[:posted] = true }, - :pre_gen => proc { |hash| hash[:one] = hash[:one].upcase }, - :to_line => proc { |hash| "# Line\n" + join(hash) } - end - - assert(record.respond_to?(:post_parse), "did not create method for post-hook") - assert(record.respond_to?(:pre_gen), "did not create method for pre-hook") + assert(record.respond_to?(:post_parse), "did not create method for post-hook") + assert(record.respond_to?(:pre_gen), "did not create method for pre-hook") - result = nil - assert_nothing_raised("Could not process line with hooks") do - result = @parser.parse_line("one two") - end + result = nil + assert_nothing_raised("Could not process line with hooks") do + result = @parser.parse_line("one two") + end - assert(result[:posted], "Did not run post-hook") - old_result = result + assert(result[:posted], "Did not run post-hook") + old_result = result - # Now make sure our pre-gen hook is called - assert_nothing_raised("Could not generate line with hooks") do - result = @parser.to_line(result) - end - assert_equal("# Line\nONE two", result, "did not call pre-gen hook") - assert_equal("one", old_result[:one], "passed original hash to pre hook") + # Now make sure our pre-gen hook is called + assert_nothing_raised("Could not generate line with hooks") do + result = @parser.to_line(result) end + assert_equal("# Line\nONE two", result, "did not call pre-gen hook") + assert_equal("one", old_result[:one], "passed original hash to pre hook") + end end class TestUtilFileRecord < Test::Unit::TestCase - include PuppetTest - include PuppetTest::FileParsing - - Record = Puppet::Util::FileParsing::FileRecord - def test_new_filerecord - [ [:fake, {}], - [nil, ] - ].each do |args| - assert_raise(ArgumentError, "Did not fail on #{args.inspect}") do - Record.new(*args) - end - end - - # Make sure the fields get turned into symbols - record = nil - assert_nothing_raised do - record = Record.new(:record, :fields => %w{one two}) - end - assert_equal([:one, :two], record.fields, "Did not symbolize fields") + include PuppetTest + include PuppetTest::FileParsing + + Record = Puppet::Util::FileParsing::FileRecord + def test_new_filerecord + [ [:fake, {}], + [nil, ] + ].each do |args| + assert_raise(ArgumentError, "Did not fail on #{args.inspect}") do + Record.new(*args) + end + end - # Make sure we fail on invalid fields - [:record_type, :target, :on_disk].each do |field| - assert_raise(ArgumentError, "Did not fail on invalid field #{field}") { - Record.new(:record, :fields => [field]) - } - end + # Make sure the fields get turned into symbols + record = nil + assert_nothing_raised do + record = Record.new(:record, :fields => %w{one two}) end + assert_equal([:one, :two], record.fields, "Did not symbolize fields") - def test_defaults - record = Record.new(:text, :match => %r{^#}) - [:absent, :separator, :joiner, :optional].each do |field| - assert_nil(record.send(field), "#{field} was not nil") - end + # Make sure we fail on invalid fields + [:record_type, :target, :on_disk].each do |field| + assert_raise(ArgumentError, "Did not fail on invalid field #{field}") { + Record.new(:record, :fields => [field]) + } + end + end - record = Record.new(:record, :fields => %w{fields}) - {:absent => "", :separator => /\s+/, :joiner => " ", :optional => []}.each do |field, default| - assert_equal(default, record.send(field), "#{field} was not default") - end + def test_defaults + record = Record.new(:text, :match => %r{^#}) + [:absent, :separator, :joiner, :optional].each do |field| + assert_nil(record.send(field), "#{field} was not nil") end - def test_block - record = nil - assert_nothing_raised("Could not pass a block when creating record") do - record = Record.new(:record, :fields => %w{one}) do |line| - return line.upcase - end - end + record = Record.new(:record, :fields => %w{fields}) + {:absent => "", :separator => /\s+/, :joiner => " ", :optional => []}.each do |field, default| + assert_equal(default, record.send(field), "#{field} was not default") + end + end + + def test_block + record = nil + assert_nothing_raised("Could not pass a block when creating record") do + record = Record.new(:record, :fields => %w{one}) do |line| + return line.upcase + end + end - line = "This is a line" + line = "This is a line" - assert( - record.respond_to?(:process), + assert( + record.respond_to?(:process), - "Record did not define :process method") + "Record did not define :process method") - assert_equal( - line.upcase, record.process(line), + assert_equal( + line.upcase, record.process(line), - "Record did not process line correctly") - end + "Record did not process line correctly") + end - # Make sure we can declare that we want the block to be instance-eval'ed instead of - # defining the 'process' method. - def test_instance_block - record = nil - assert_nothing_raised("Could not pass a block when creating record") do - record = Record.new(:record, :block_eval => :instance, :fields => %w{one}) do - def process(line) - line.upcase - end + # Make sure we can declare that we want the block to be instance-eval'ed instead of + # defining the 'process' method. + def test_instance_block + record = nil + assert_nothing_raised("Could not pass a block when creating record") do + record = Record.new(:record, :block_eval => :instance, :fields => %w{one}) do + def process(line) + line.upcase + end - def to_line(details) - details.upcase - end - end + def to_line(details) + details.upcase end + end + end - assert(record.respond_to?(:process), "Block was not instance-eval'ed and process was not defined") - assert(record.respond_to?(:to_line), "Block was not instance-eval'ed and to_line was not defined") + assert(record.respond_to?(:process), "Block was not instance-eval'ed and process was not defined") + assert(record.respond_to?(:to_line), "Block was not instance-eval'ed and to_line was not defined") - line = "some text" - assert_equal(line.upcase, record.process(line), "Instance-eval'ed record did not call :process correctly") - assert_equal(line.upcase, record.to_line(line), "Instance-eval'ed record did not call :to_line correctly") - end + line = "some text" + assert_equal(line.upcase, record.process(line), "Instance-eval'ed record did not call :process correctly") + assert_equal(line.upcase, record.to_line(line), "Instance-eval'ed record did not call :to_line correctly") + end end diff --git a/test/util/inifile.rb b/test/util/inifile.rb index f465dfd58..78831ca2f 100755 --- a/test/util/inifile.rb +++ b/test/util/inifile.rb @@ -7,132 +7,132 @@ 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\nkey3=\n\tv3a\n v3b\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("\n\tv3a\n v3b", s['key3']) - 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) - result - end - - def mkfile(content) - file = tempfile - File.open(file, "w") { |f| f.print(content) } - file + 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\nkey3=\n\tv3a\n v3b\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("\n\tv3a\n v3b", s['key3']) + 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) + result + end + + def mkfile(content) + file = tempfile + File.open(file, "w") { |f| f.print(content) } + file + end end diff --git a/test/util/instance_loader.rb b/test/util/instance_loader.rb index a7ea41532..2e3dcb3d6 100755 --- a/test/util/instance_loader.rb +++ b/test/util/instance_loader.rb @@ -7,46 +7,46 @@ require 'puppet/util/instance_loader' require 'puppettest' class TestInstanceloader < Test::Unit::TestCase - include PuppetTest + include PuppetTest - def setup - super - @loader = Class.new do - extend Puppet::Util::InstanceLoader + def setup + super + @loader = Class.new do + extend Puppet::Util::InstanceLoader - def self.newstuff(name, value) - instance_hash(:stuff)[name] = value - end - end + def self.newstuff(name, value) + instance_hash(:stuff)[name] = value + end + end - assert_nothing_raised("Could not create instance loader") do - @loader.instance_load(:stuff, "puppet/stuff") - end + assert_nothing_raised("Could not create instance loader") do + @loader.instance_load(:stuff, "puppet/stuff") end + end - # Make sure we correctly create our autoload instance. This covers the basics. - def test_autoload - # Make sure we can retrieve the loader - assert_instance_of(Puppet::Util::Autoload, @loader.instance_loader(:stuff), "Could not get instance loader") + # Make sure we correctly create our autoload instance. This covers the basics. + def test_autoload + # Make sure we can retrieve the loader + assert_instance_of(Puppet::Util::Autoload, @loader.instance_loader(:stuff), "Could not get instance loader") - # Make sure we can get the instance hash - assert(@loader.instance_hash(:stuff), "Could not get instance hash") + # Make sure we can get the instance hash + assert(@loader.instance_hash(:stuff), "Could not get instance hash") - # Make sure it defines the instance retrieval method - assert(@loader.respond_to?(:stuff), "Did not define instance retrieval method") - end + # Make sure it defines the instance retrieval method + assert(@loader.respond_to?(:stuff), "Did not define instance retrieval method") + end - def test_loaded_instances - assert_equal([], @loader.loaded_instances(:stuff), "Incorrect loaded instances") + def test_loaded_instances + assert_equal([], @loader.loaded_instances(:stuff), "Incorrect loaded instances") - @loader.newstuff(:testing, "a value") + @loader.newstuff(:testing, "a value") - assert_equal([:testing], @loader.loaded_instances(:stuff), "Incorrect loaded instances") + assert_equal([:testing], @loader.loaded_instances(:stuff), "Incorrect loaded instances") - assert_equal("a value", @loader.loaded_instance(:stuff, :testing), "Got incorrect loaded instance") - end + assert_equal("a value", @loader.loaded_instance(:stuff, :testing), "Got incorrect loaded instance") + end - def test_instance_loading - end + def test_instance_loading + end end diff --git a/test/util/log.rb b/test/util/log.rb index 8d5c8c558..4dbd3c6d1 100755 --- a/test/util/log.rb +++ b/test/util/log.rb @@ -7,213 +7,213 @@ 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_all - end - - def teardown - super - Puppet::Util::Log.close_all - Puppet::Util::Log.level = @oldloglevel - end - - def getlevels - levels = nil - assert_nothing_raised { - levels = [] - Puppet::Util::Log.eachlevel { |level| levels << level } - } - # Don't test the top levels; too annoying - 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( + include PuppetTest + + def setup + super + @oldloglevel = Puppet::Util::Log.level + Puppet::Util::Log.close_all + end + + def teardown + super + Puppet::Util::Log.close_all + Puppet::Util::Log.level = @oldloglevel + end + + def getlevels + levels = nil + assert_nothing_raised { + levels = [] + Puppet::Util::Log.eachlevel { |level| levels << level } + } + # Don't test the top levels; too annoying + 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", + :level => level, + :source => "Test", - :message => "Unit test for #{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_all - 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_levelmethods - assert_nothing_raised { - Puppet::Util::Log.newdestination("/dev/null") - } - getlevels.each { |level| - assert_nothing_raised { - Puppet.send(level,"Testing for #{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 - - # 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( + :message => "Unit test for #{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_all + 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_levelmethods + assert_nothing_raised { + Puppet::Util::Log.newdestination("/dev/null") + } + getlevels.each { |level| + assert_nothing_raised { + Puppet.send(level,"Testing for #{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 + + # 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, + :level => :info, - :message => "A message with %s in it" - ) - } - end + :message => "A message with %s in it" + ) + } + end - # Verify that the error and source are always strings - def test_argsAreStrings - msg = nil + # Verify that the error and source are always strings + def test_argsAreStrings + msg = nil - file = Puppet::Type.type(:file).new( + file = Puppet::Type.type(:file).new( - :path => tempfile, + :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 - - 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 #{name.inspect}") + :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 + + def test_destination_matching + dest = nil + assert_nothing_raised { + dest = Puppet::Util::Log.newdesttype("Destine") do + def handle(msg) + puts msg end + end + } - assert_nothing_raised { - dest.match(:yayness) - } - assert(dest.match("Yayness"), "Did not match yayness") - Puppet::Util::Log.close(dest) + [:destine, "Destine", "destine"].each do |name| + assert(dest.match?(name), "Did not match #{name.inspect}") 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 + 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 diff --git a/test/util/metrics.rb b/test/util/metrics.rb index 2575330b5..1fd57f2f1 100755 --- a/test/util/metrics.rb +++ b/test/util/metrics.rb @@ -8,65 +8,65 @@ require 'puppettest' require 'puppet/type' class TestMetric < PuppetTest::TestCase - confine "Missing RRDtool library" => Puppet.features.rrd? - include PuppetTest + confine "Missing RRDtool library" => Puppet.features.rrd? + include PuppetTest - def gendata - totalmax = 1000 - changemax = 1000 - eventmax = 10 - maxdiff = 10 + def gendata + totalmax = 1000 + changemax = 1000 + eventmax = 10 + maxdiff = 10 - types = [Puppet::Type.type(:file), Puppet::Type.type(:package), Puppet::Type.type(:package)] - data = [:total, :managed, :outofsync, :changed, :totalchanges] - events = [:file_changed, :package_installed, :service_started] + types = [Puppet::Type.type(:file), Puppet::Type.type(:package), Puppet::Type.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) + # 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) - } + events.each { |event| + eventdata[event] = rand(eventmax) + } - {:typedata => typedata, :eventdata => eventdata} - end + {: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 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 test_fakedata - report = Puppet::Transaction::Report.new - time = Time.now.to_i - start = time - 10.times { - rundata(report, time) - time += 300 - } - rundata(report, time) + 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 + report.metrics.each do |n, m| m.graph end - File.open(File.join(Puppet[:rrddir],"index.html"),"w") { |of| - of.puts "<html><body>" - report.metrics.each { |name, metric| - of.puts "<img src=#{metric.name}.png><br>" - } - } - end + File.open(File.join(Puppet[:rrddir],"index.html"),"w") { |of| + of.puts "<html><body>" + report.metrics.each { |name, metric| + of.puts "<img src=#{metric.name}.png><br>" + } + } + end end diff --git a/test/util/package.rb b/test/util/package.rb index c252db1d8..b2bb6dfcc 100755 --- a/test/util/package.rb +++ b/test/util/package.rb @@ -7,19 +7,19 @@ require 'puppet/util/package' require 'puppettest' class TestPuppetUtilPackage < Test::Unit::TestCase - include PuppetTest - include Puppet::Util::Package + include PuppetTest + include Puppet::Util::Package - def test_versioncmp - ary = %w{ 1.1.6 2.3 1.1a 3.0 1.5 1 2.4 1.1-4 2.3.1 1.2 2.3.0 1.1-3 2.4b 2.4 2.40.2 2.3a.1 3.1 0002 1.1-5 1.1.a 1.06} + def test_versioncmp + ary = %w{ 1.1.6 2.3 1.1a 3.0 1.5 1 2.4 1.1-4 2.3.1 1.2 2.3.0 1.1-3 2.4b 2.4 2.40.2 2.3a.1 3.1 0002 1.1-5 1.1.a 1.06} - newary = nil - assert_nothing_raised do - newary = ary.sort { |a, b| - versioncmp(a,b) - } - end - assert_equal(["0002", "1", "1.06", "1.1-3", "1.1-4", "1.1-5", "1.1.6", "1.1.a", "1.1a", "1.2", "1.5", "2.3", "2.3.0", "2.3.1", "2.3a.1", "2.4", "2.4", "2.4b", "2.40.2", "3.0", "3.1"], newary) + newary = nil + assert_nothing_raised do + newary = ary.sort { |a, b| + versioncmp(a,b) + } end + assert_equal(["0002", "1", "1.06", "1.1-3", "1.1-4", "1.1-5", "1.1.6", "1.1.a", "1.1a", "1.2", "1.5", "2.3", "2.3.0", "2.3.1", "2.3a.1", "2.4", "2.4", "2.4b", "2.40.2", "3.0", "3.1"], newary) + end end diff --git a/test/util/pidlock.rb b/test/util/pidlock.rb index 8d22ead81..764c7436d 100755 --- a/test/util/pidlock.rb +++ b/test/util/pidlock.rb @@ -7,120 +7,120 @@ require 'fileutils' Puppet.debug = false class TestPuppetUtilPidlock < Test::Unit::TestCase - include PuppetTest - - def setup - super - @workdir = tstdir - end - - def teardown - super - FileUtils.rm_rf(@workdir) - end - - def test_00_basic_create - l = nil - assert_nothing_raised { l = Puppet::Util::Pidlock.new(@workdir + '/nothingmuch') } - - assert_equal Puppet::Util::Pidlock, l.class - - assert_equal @workdir + '/nothingmuch', l.lockfile - end - - def test_10_uncontended_lock - l = Puppet::Util::Pidlock.new(@workdir + '/test_lock') - - assert !l.locked? - assert !l.mine? - assert l.lock - assert l.locked? - assert l.mine? - assert !l.anonymous? - # It's OK to call lock multiple times - assert l.lock - assert l.unlock - assert !l.locked? - assert !l.mine? - end - - def test_20_someone_elses_lock - childpid = nil - l = Puppet::Util::Pidlock.new(@workdir + '/someone_elses_lock') - - # First, we need a PID that's guaranteed to be (a) used, (b) someone - # else's, and (c) around for the life of this test. - childpid = fork { loop do; sleep 10; end } - - File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } - - assert l.locked? - assert !l.mine? - assert !l.lock - assert l.locked? - assert !l.mine? - assert !l.unlock - assert l.locked? - assert !l.mine? - ensure - Process.kill("KILL", childpid) unless childpid.nil? - end - - def test_30_stale_lock - # This is a bit hard to guarantee, but we need a PID that is definitely - # unused, and will stay so for the the life of this test. Our best - # bet is to create a process, get it's PID, let it die, and *then* - # lock on it. - childpid = fork { exit } - - # Now we can't continue until we're sure that the PID is dead - Process.wait(childpid) - - l = Puppet::Util::Pidlock.new(@workdir + '/stale_lock') - - # locked? should clear the lockfile - File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } - assert File.exists?(l.lockfile) - assert !l.locked? - assert !File.exists?(l.lockfile) - - # lock should replace the lockfile with our own - File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } - assert File.exists?(l.lockfile) - assert l.lock - assert l.locked? - assert l.mine? - - # unlock should fail, and should *not* molest the existing lockfile, - # despite it being stale - File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } - assert File.exists?(l.lockfile) - assert !l.unlock - assert File.exists?(l.lockfile) - end - - def test_40_not_locked_at_all - l = Puppet::Util::Pidlock.new(@workdir + '/not_locked') - - assert !l.locked? - # We can't unlock if we don't hold the lock - assert !l.unlock - end - - def test_50_anonymous_lock - l = Puppet::Util::Pidlock.new(@workdir + '/anonymous_lock') - - assert !l.locked? - assert l.lock(:anonymous => true) - assert l.locked? - assert l.anonymous? - assert !l.mine? - assert "", File.read(l.lockfile) - assert !l.unlock - assert l.locked? - assert l.anonymous? - assert l.unlock(:anonymous => true) - assert !File.exists?(l.lockfile) - end + include PuppetTest + + def setup + super + @workdir = tstdir + end + + def teardown + super + FileUtils.rm_rf(@workdir) + end + + def test_00_basic_create + l = nil + assert_nothing_raised { l = Puppet::Util::Pidlock.new(@workdir + '/nothingmuch') } + + assert_equal Puppet::Util::Pidlock, l.class + + assert_equal @workdir + '/nothingmuch', l.lockfile + end + + def test_10_uncontended_lock + l = Puppet::Util::Pidlock.new(@workdir + '/test_lock') + + assert !l.locked? + assert !l.mine? + assert l.lock + assert l.locked? + assert l.mine? + assert !l.anonymous? + # It's OK to call lock multiple times + assert l.lock + assert l.unlock + assert !l.locked? + assert !l.mine? + end + + def test_20_someone_elses_lock + childpid = nil + l = Puppet::Util::Pidlock.new(@workdir + '/someone_elses_lock') + + # First, we need a PID that's guaranteed to be (a) used, (b) someone + # else's, and (c) around for the life of this test. + childpid = fork { loop do; sleep 10; end } + + File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } + + assert l.locked? + assert !l.mine? + assert !l.lock + assert l.locked? + assert !l.mine? + assert !l.unlock + assert l.locked? + assert !l.mine? + ensure + Process.kill("KILL", childpid) unless childpid.nil? + end + + def test_30_stale_lock + # This is a bit hard to guarantee, but we need a PID that is definitely + # unused, and will stay so for the the life of this test. Our best + # bet is to create a process, get it's PID, let it die, and *then* + # lock on it. + childpid = fork { exit } + + # Now we can't continue until we're sure that the PID is dead + Process.wait(childpid) + + l = Puppet::Util::Pidlock.new(@workdir + '/stale_lock') + + # locked? should clear the lockfile + File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } + assert File.exists?(l.lockfile) + assert !l.locked? + assert !File.exists?(l.lockfile) + + # lock should replace the lockfile with our own + File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } + assert File.exists?(l.lockfile) + assert l.lock + assert l.locked? + assert l.mine? + + # unlock should fail, and should *not* molest the existing lockfile, + # despite it being stale + File.open(l.lockfile, 'w') { |fd| fd.write(childpid) } + assert File.exists?(l.lockfile) + assert !l.unlock + assert File.exists?(l.lockfile) + end + + def test_40_not_locked_at_all + l = Puppet::Util::Pidlock.new(@workdir + '/not_locked') + + assert !l.locked? + # We can't unlock if we don't hold the lock + assert !l.unlock + end + + def test_50_anonymous_lock + l = Puppet::Util::Pidlock.new(@workdir + '/anonymous_lock') + + assert !l.locked? + assert l.lock(:anonymous => true) + assert l.locked? + assert l.anonymous? + assert !l.mine? + assert "", File.read(l.lockfile) + assert !l.unlock + assert l.locked? + assert l.anonymous? + assert l.unlock(:anonymous => true) + assert !File.exists?(l.lockfile) + end end diff --git a/test/util/settings.rb b/test/util/settings.rb index d05f555ec..ffcfbbfc2 100755 --- a/test/util/settings.rb +++ b/test/util/settings.rb @@ -8,627 +8,627 @@ require 'puppet/util/settings' require 'puppettest/parsertesting' class TestSettings < Test::Unit::TestCase - include PuppetTest - include PuppetTest::ParserTesting - Setting = Puppet::Util::Settings::Setting - BooleanSetting = Puppet::Util::Settings::BooleanSetting - - def setup - super - @config = mkconfig - end + include PuppetTest + include PuppetTest::ParserTesting + Setting = Puppet::Util::Settings::Setting + BooleanSetting = Puppet::Util::Settings::BooleanSetting + + def setup + super + @config = mkconfig + end + + def set_configs(config = nil) + config ||= @config + + config.setdefaults( + "main", + :one => ["a", "one"], + :two => ["a", "two"], + :yay => ["/default/path", "boo"], + :mkusers => [true, "uh, yeah"], + + :name => ["testing", "a"] + ) + + + config.setdefaults( + "section1", + :attr => ["a", "one"], + :attrdir => ["/another/dir", "two"], + + :attr3 => ["$attrdir/maybe", "boo"] + ) + end + + def check_for_users + count = Puppet::Type.type(:user).inject(0) { |c,o| + c + 1 + } + assert(count > 0, "Found no users") + end - def set_configs(config = nil) - config ||= @config + def test_to_config + set_configs - config.setdefaults( - "main", - :one => ["a", "one"], - :two => ["a", "two"], - :yay => ["/default/path", "boo"], - :mkusers => [true, "uh, yeah"], + newc = mkconfig + set_configs(newc) - :name => ["testing", "a"] - ) + # Reset all of the values, so we know they're changing. + newc.each do |name, obj| + next if name == :name + newc[name] = true + end + newfile = tempfile + File.open(newfile, "w") { |f| + @config.to_config.split("\n").each do |line| + # Uncomment the settings, so they actually take. + if line =~ / = / + f.puts line.sub(/^\s*#/, '') + else + f.puts line + end + end + } - config.setdefaults( - "section1", - :attr => ["a", "one"], - :attrdir => ["/another/dir", "two"], + newc.setdefaults :section, :config => [newfile, "eh"] - :attr3 => ["$attrdir/maybe", "boo"] - ) - end + assert_nothing_raised("Could not parse generated configuration") { + newc.parse + } - def check_for_users - count = Puppet::Type.type(:user).inject(0) { |c,o| - c + 1 - } - assert(count > 0, "Found no users") + @config.each do |name, object| + assert_equal(@config[name], newc[name], "Parameter #{name} is not the same") end + end - def test_to_config - set_configs - - newc = mkconfig - set_configs(newc) + def mkconfig + c = Puppet::Util::Settings.new + c.setdefaults :main, :noop => [false, "foo"] + c + end - # Reset all of the values, so we know they're changing. - newc.each do |name, obj| - next if name == :name - newc[name] = true - end + def test_addbools + assert_nothing_raised { + @config.setdefaults(:testing, :booltest => [true, "testing"]) + } - newfile = tempfile - File.open(newfile, "w") { |f| - @config.to_config.split("\n").each do |line| - # Uncomment the settings, so they actually take. - if line =~ / = / - f.puts line.sub(/^\s*#/, '') - else - f.puts line - end - end - } + assert(@config[:booltest]) + @config = mkconfig - newc.setdefaults :section, :config => [newfile, "eh"] + assert_nothing_raised { + @config.setdefaults(:testing, :booltest => ["true", "testing"]) + } - assert_nothing_raised("Could not parse generated configuration") { - newc.parse - } + assert(@config[:booltest]) - @config.each do |name, object| - assert_equal(@config[name], newc[name], "Parameter #{name} is not the same") - end - end + assert_nothing_raised { + @config[:booltest] = false + } - def mkconfig - c = Puppet::Util::Settings.new - c.setdefaults :main, :noop => [false, "foo"] - c - end + assert(! @config[:booltest], "Booltest is not false") - def test_addbools - assert_nothing_raised { - @config.setdefaults(:testing, :booltest => [true, "testing"]) - } + assert_nothing_raised { + @config[:booltest] = "false" + } - assert(@config[:booltest]) - @config = mkconfig + assert(! @config[:booltest], "Booltest is not false") - assert_nothing_raised { - @config.setdefaults(:testing, :booltest => ["true", "testing"]) - } + assert_raise(ArgumentError) { + @config[:booltest] = "yayness" + } - assert(@config[:booltest]) + assert_raise(ArgumentError) { + @config[:booltest] = "/some/file" + } + end - assert_nothing_raised { - @config[:booltest] = false - } + def test_strings + val = "this is a string" + assert_nothing_raised { + @config.setdefaults(:testing, :strtest => [val, "testing"]) + } - assert(! @config[:booltest], "Booltest is not false") + assert_equal(val, @config[:strtest]) - assert_nothing_raised { - @config[:booltest] = "false" - } + # Verify that variables are interpolated + assert_nothing_raised { + @config.setdefaults(:testing, :another => ["another $strtest", "testing"]) + } - assert(! @config[:booltest], "Booltest is not false") + assert_equal("another #{val}", @config[:another]) + end - assert_raise(ArgumentError) { - @config[:booltest] = "yayness" - } + def test_files + c = mkconfig - assert_raise(ArgumentError) { - @config[:booltest] = "/some/file" - } - end + parent = "/puppet" + assert_nothing_raised { + @config.setdefaults(:testing, :parentdir => [parent, "booh"]) + } - def test_strings - val = "this is a string" - assert_nothing_raised { - @config.setdefaults(:testing, :strtest => [val, "testing"]) - } + assert_nothing_raised { + @config.setdefaults(:testing, :child => ["$parent/child", "rah"]) + } - assert_equal(val, @config[:strtest]) + assert_equal(parent, @config[:parentdir]) + assert_equal("/puppet/child", File.join(@config[:parentdir], "child")) + end - # Verify that variables are interpolated - assert_nothing_raised { - @config.setdefaults(:testing, :another => ["another $strtest", "testing"]) - } + def test_getset + initial = "an initial value" + assert_raise(ArgumentError) { + @config[:yayness] = initial + } - assert_equal("another #{val}", @config[:another]) - end + default = "this is a default" + assert_nothing_raised { + @config.setdefaults(:testing, :yayness => [default, "rah"]) + } - def test_files - c = mkconfig + assert_equal(default, @config[:yayness]) - parent = "/puppet" - assert_nothing_raised { - @config.setdefaults(:testing, :parentdir => [parent, "booh"]) - } + assert_nothing_raised { + @config[:yayness] = initial + } - assert_nothing_raised { - @config.setdefaults(:testing, :child => ["$parent/child", "rah"]) - } + assert_equal(initial, @config[:yayness]) - assert_equal(parent, @config[:parentdir]) - assert_equal("/puppet/child", File.join(@config[:parentdir], "child")) - end + assert_nothing_raised { + @config.clear + } - def test_getset - initial = "an initial value" - assert_raise(ArgumentError) { - @config[:yayness] = initial - } + assert_equal(default, @config[:yayness], "'clear' did not remove old values") - default = "this is a default" - assert_nothing_raised { - @config.setdefaults(:testing, :yayness => [default, "rah"]) - } + assert_nothing_raised { + @config[:yayness] = "not default" + } + assert_equal("not default", @config[:yayness]) + end - assert_equal(default, @config[:yayness]) + def test_parse_file + text = %{ + one = this is a test + two = another test + owner = root + group = root + yay = /a/path - assert_nothing_raised { - @config[:yayness] = initial - } + [main] + four = five + six = seven - assert_equal(initial, @config[:yayness]) +[section1] + attr = value + owner = puppet + group = puppet + attrdir = /some/dir + attr3 = $attrdir/other + } - assert_nothing_raised { - @config.clear - } + file = tempfile + File.open(file, "w") { |f| f.puts text } - assert_equal(default, @config[:yayness], "'clear' did not remove old values") + result = nil + assert_nothing_raised { + result = @config.send(:parse_file, file) + } - assert_nothing_raised { - @config[:yayness] = "not default" - } - assert_equal("not default", @config[:yayness]) + main = result[:main] + assert(main, "Did not get section for main") + { + :one => "this is a test", + :two => "another test", + :owner => "root", + :group => "root", + :yay => "/a/path", + :four => "five", + :six => "seven" + }.each do |param, value| + assert_equal(value, main[param], "Param #{param} was not set correctly in main") end - def test_parse_file - text = %{ - one = this is a test - two = another test - owner = root - group = root - yay = /a/path + section1 = result[:section1] + assert(section1, "Did not get section1") + + { + :attr => "value", + :owner => "puppet", + :group => "puppet", + :attrdir => "/some/dir", + :attr3 => "$attrdir/other" + }.each do |param, value| + assert_equal(value, section1[param], "Param #{param} was not set correctly in section1") + end + end - [main] - four = five - six = seven + def test_arghandling + c = mkconfig -[section1] - attr = value - owner = puppet - group = puppet - attrdir = /some/dir - attr3 = $attrdir/other - } + assert_nothing_raised { - file = tempfile - File.open(file, "w") { |f| f.puts text } + @config.setdefaults( + "testing", + :onboolean => [true, "An on bool"], + :offboolean => [false, "An off bool"], + :string => ["a string", "A string arg"], - result = nil - assert_nothing_raised { - result = @config.send(:parse_file, file) - } + :file => ["/path/to/file", "A file arg"] + ) + } - main = result[:main] - assert(main, "Did not get section for main") - { - :one => "this is a test", - :two => "another test", - :owner => "root", - :group => "root", - :yay => "/a/path", - :four => "five", - :six => "seven" - }.each do |param, value| - assert_equal(value, main[param], "Param #{param} was not set correctly in main") + 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 @config.boolean?(param) + if val + opt = "--#{param}" + else + opt = "--no-#{param}" + end + else + opt = "--#{param}" + arg = val end - section1 = result[:section1] - assert(section1, "Did not get section1") - - { - :attr => "value", - :owner => "puppet", - :group => "puppet", - :attrdir => "/some/dir", - :attr3 => "$attrdir/other" - }.each do |param, value| - assert_equal(value, section1[param], "Param #{param} was not set correctly in section1") - end - end + assert_nothing_raised("Could not handle arg #{opt} with value #{val}") { - def test_arghandling - c = mkconfig + @config.handlearg(opt, arg) + } + } + } + end - assert_nothing_raised { + def test_addargs - @config.setdefaults( - "testing", - :onboolean => [true, "An on bool"], - :offboolean => [false, "An off bool"], - :string => ["a string", "A string arg"], + @config.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"] - ) - } + :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 @config.boolean?(param) - if val - opt = "--#{param}" - else - opt = "--no-#{param}" - end - else - opt = "--#{param}" - arg = val - end - - assert_nothing_raised("Could not handle arg #{opt} with value #{val}") { - - @config.handlearg(opt, arg) - } - } - } + should = [] + @config.each { |name, element| + element.expects(:getopt_args).returns([name]) + should << name + } + result = [] + assert_nothing_raised("Add args failed") do + @config.addargs(result) end + assert_equal(should, result, "Did not call addargs correctly.") - def test_addargs + end - @config.setdefaults( - "testing", - :onboolean => [true, "An on bool"], - :offboolean => [false, "An off bool"], - :string => ["a string", "A string arg"], + def test_addargs_functional + @config = Puppet::Util::Settings.new - :file => ["/path/to/file", "A file arg"] - ) - should = [] - @config.each { |name, element| - element.expects(:getopt_args).returns([name]) - should << name - } - result = [] - assert_nothing_raised("Add args failed") do - @config.addargs(result) - end - assert_equal(should, result, "Did not call addargs correctly.") + @config.setdefaults( + "testing", + :onboolean => [true, "An on bool"], + :string => ["a string", "A string arg"] + ) + result = [] + should = [] + assert_nothing_raised("Add args failed") do + @config.addargs(result) end - - def test_addargs_functional - @config = Puppet::Util::Settings.new - - - @config.setdefaults( - "testing", - :onboolean => [true, "An on bool"], - - :string => ["a string", "A string arg"] - ) - result = [] - should = [] - assert_nothing_raised("Add args failed") do - @config.addargs(result) - end - @config.each do |name, element| - if name == :onboolean - should << ["--onboolean", GetoptLong::NO_ARGUMENT] - should << ["--no-onboolean", GetoptLong::NO_ARGUMENT] - elsif name == :string - should << ["--string", GetoptLong::REQUIRED_ARGUMENT] - end - end - assert_equal(should, result, "Add args functional test failed") + @config.each do |name, element| + if name == :onboolean + should << ["--onboolean", GetoptLong::NO_ARGUMENT] + should << ["--no-onboolean", GetoptLong::NO_ARGUMENT] + elsif name == :string + should << ["--string", GetoptLong::REQUIRED_ARGUMENT] + end end + assert_equal(should, result, "Add args functional test failed") + end - def test_groupsetting - cfile = tempfile + def test_groupsetting + cfile = tempfile - group = "yayness" + group = "yayness" - File.open(cfile, "w") do |f| - f.puts "[main] - group = #{group} - " - end + File.open(cfile, "w") do |f| + f.puts "[main] + group = #{group} + " + end - config = mkconfig - config.setdefaults(Puppet[:name], :group => ["puppet", "a group"], :config => [cfile, "eh"]) + config = mkconfig + config.setdefaults(Puppet[:name], :group => ["puppet", "a group"], :config => [cfile, "eh"]) - assert_nothing_raised { - config.parse - } + assert_nothing_raised { + config.parse + } - assert_equal(group, config[:group], "Group did not take") - end + 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) + # 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 + path = tempfile + mode = 0644 - config = mkconfig + config = mkconfig - args = { :default => path, :mode => mode, :desc => "yay" } + args = { :default => path, :mode => mode, :desc => "yay" } - user = nonrootuser - group = nonrootgroup + user = nonrootuser + group = nonrootgroup - if Puppet.features.root? - args[:owner] = user.name - args[:group] = group.name - end + if Puppet.features.root? + args[:owner] = user.name + args[:group] = group.name + end - config.setdefaults(:testing, :myfile => args) + config.setdefaults(:testing, :myfile => args) - assert_nothing_raised { - config.write(:myfile) do |file| - file.puts "yay" - end - } + assert_nothing_raised { + config.write(:myfile) do |file| + file.puts "yay" + end + } - assert_equal(mode, filemode(path), "Modes are not equal") + assert_equal(mode, filemode(path), "Modes are not equal") - # OS X is broken in how it chgrps files - if Puppet.features.root? - assert_equal(user.uid, File.stat(path).uid, "UIDS are not equal") + # OS X is broken in how it chgrps files + if Puppet.features.root? + 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 + 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) + def test_mkdir + File.umask(0022) - path = tempfile - mode = 0755 + path = tempfile + mode = 0755 - config = mkconfig + config = mkconfig - args = { :default => path, :mode => mode, :desc => "a file" } + args = { :default => path, :mode => mode, :desc => "a file" } - user = nonrootuser - group = nonrootgroup + user = nonrootuser + group = nonrootgroup - if Puppet.features.root? - args[:owner] = user.name - args[:group] = group.name - end + if Puppet.features.root? + args[:owner] = user.name + args[:group] = group.name + end - config.setdefaults(:testing, :mydir => args) + config.setdefaults(:testing, :mydir => args) - assert_nothing_raised { - config.mkdir(:mydir) - } + assert_nothing_raised { + config.mkdir(:mydir) + } - assert_equal(mode, filemode(path), "Modes are not equal") + assert_equal(mode, filemode(path), "Modes are not equal") - # OS X and *BSD is broken in how it chgrps files - if Puppet.features.root? - assert_equal(user.uid, File.stat(path).uid, "UIDS are not equal") + # OS X and *BSD is broken in how it chgrps files + if Puppet.features.root? + 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 + case Facter["operatingsystem"].value + when /BSD/, "Darwin" # nothing + else + assert_equal(group.gid, File.stat(path).gid, "GIDS are not equal") + end end + end - # Make sure that tags are ignored when configuring - def test_configs_ignore_tags - config = mkconfig - file = tempfile + # Make sure that tags are ignored when configuring + def test_configs_ignore_tags + config = mkconfig + file = tempfile - config.setdefaults( - :mysection, + config.setdefaults( + :mysection, - :mydir => [file, "a file"] - ) + :mydir => [file, "a file"] + ) - Puppet[:tags] = "yayness" + Puppet[:tags] = "yayness" - assert_nothing_raised { - config.use(:mysection) - } - - assert(FileTest.directory?(file), "Directory did not get created") + 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 + assert_equal( + "yayness", Puppet[:tags], - def test_configs_replace_in_url - config = mkconfig + "Tags got changed during config") + end - config.setdefaults(:mysection, :host => ["yayness", "yay"]) - config.setdefaults(:mysection, :url => ["http://$host/rahness", "yay"]) + def test_configs_replace_in_url + config = mkconfig - val = nil - assert_nothing_raised { - val = config[:url] - } + config.setdefaults(:mysection, :host => ["yayness", "yay"]) + config.setdefaults(:mysection, :url => ["http://$host/rahness", "yay"]) + val = nil + assert_nothing_raised { + val = config[:url] + } - assert_equal( - "http://yayness/rahness", val, - "Settings got messed up") - end - - def test_correct_type_assumptions - file = Puppet::Util::Settings::FileSetting - setting = Puppet::Util::Settings::Setting - bool = Puppet::Util::Settings::BooleanSetting - - # We have to keep these ordered, unfortunately. - [ - ["/this/is/a/file", file], - ["true", bool], - [true, bool], - ["false", bool], - ["server", setting], - ["http://$server/yay", setting], - ["$server/yayness", file], - ["$server/yayness.conf", file] - ].each do |ary| - config = mkconfig - value, type = ary - name = value.to_s + "_setting" - assert_nothing_raised { - config.setdefaults(:yayness, name => { :default => value, :desc => name.to_s}) - } - elem = config.setting(name) - - - assert_instance_of( - type, elem, - - "#{value.inspect} got created as wrong type") - end + assert_equal( + "http://yayness/rahness", val, + + "Settings got messed up") + end + + def test_correct_type_assumptions + file = Puppet::Util::Settings::FileSetting + setting = Puppet::Util::Settings::Setting + bool = Puppet::Util::Settings::BooleanSetting + + # We have to keep these ordered, unfortunately. + [ + ["/this/is/a/file", file], + ["true", bool], + [true, bool], + ["false", bool], + ["server", setting], + ["http://$server/yay", setting], + ["$server/yayness", file], + ["$server/yayness.conf", file] + ].each do |ary| + config = mkconfig + value, type = ary + name = value.to_s + "_setting" + assert_nothing_raised { + config.setdefaults(:yayness, name => { :default => value, :desc => name.to_s}) + } + elem = config.setting(name) + + + assert_instance_of( + type, elem, + + "#{value.inspect} got created as wrong type") 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 %{[main]\n - singleq = 'one' - doubleq = "one" - none = one - middle = mid"quote + 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 %{[main]\n + singleq = 'one' + doubleq = "one" + none = one + middle = mid"quote } - } + } - config.setdefaults(:mysection, :config => [file, "eh"]) + config.setdefaults(:mysection, :config => [file, "eh"]) - assert_nothing_raised { - config.parse - } + assert_nothing_raised { + config.parse + } - %w{singleq doubleq none}.each do |p| - assert_equal("one", config[p], "#{p} did not match") - end - assert_equal('mid"quote', config["middle"], "middle did not match") + %w{singleq doubleq none}.each do |p| + assert_equal("one", config[p], "#{p} did not match") end + assert_equal('mid"quote', config["middle"], "middle did not match") + end - # Test that config parameters correctly call passed-in blocks when the value - # is set. - def test_paramblocks - config = mkconfig - - testing = nil - assert_nothing_raised do - config.setdefaults :test, :blocktest => {:default => "yay", :desc => "boo", :hook => proc { |value| testing = value }} - end - elem = config.setting(:blocktest) - - assert_nothing_raised do - assert_equal("yay", elem.value) - end - - assert_nothing_raised do - config[:blocktest] = "yaytest" - end - - assert_nothing_raised do - assert_equal("yaytest", elem.value) - end - assert_equal("yaytest", testing) + # Test that config parameters correctly call passed-in blocks when the value + # is set. + def test_paramblocks + config = mkconfig - assert_nothing_raised do - config[:blocktest] = "another" - end + testing = nil + assert_nothing_raised do + config.setdefaults :test, :blocktest => {:default => "yay", :desc => "boo", :hook => proc { |value| testing = value }} + end + elem = config.setting(:blocktest) - 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_nothing_raised do + assert_equal("yay", elem.value) + end - assert_equal("yay", config[:blocktest2]) + assert_nothing_raised do + config[:blocktest] = "yaytest" + end - assert_nothing_raised do - config[:blocktest2] = "footest" - end - assert_equal("footest", config[:blocktest2]) - assert_equal("footest", testing) + assert_nothing_raised do + assert_equal("yaytest", elem.value) end + assert_equal("yaytest", testing) - def test_no_modify_root - config = mkconfig + assert_nothing_raised do + config[:blocktest] = "another" + end - config.setdefaults( - :yay, - :mydir => {:default => tempfile, + 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 - :mode => 0644, - :owner => "root", - :group => "service", - :desc => "yay" - }, - :mkusers => [false, "yay"] - ) + assert_equal("yay", config[:blocktest2]) - assert_nothing_raised do - config.use(:yay) - end + 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 => "service", + :desc => "yay" + }, + :mkusers => [false, "yay"] + ) + + assert_nothing_raised do + config.use(:yay) + end - # Now enable it so they'll be added - config[:mkusers] = true + # Now enable it so they'll be added + config[:mkusers] = true - comp = config.to_catalog + comp = config.to_catalog - comp.vertices.find_all { |r| r.class.name == :user }.each do |u| - assert(u.name != "root", "Tried to manage root user") - end - comp.vertices.find_all { |r| r.class.name == :group }.each do |u| - assert(u.name != "root", "Tried to manage root group") - assert(u.name != "wheel", "Tried to manage wheel group") - end + comp.vertices.find_all { |r| r.class.name == :user }.each do |u| + assert(u.name != "root", "Tried to manage root user") + end + comp.vertices.find_all { |r| r.class.name == :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| @@ -638,136 +638,136 @@ class TestSettings < Test::Unit::TestCase # "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 - file = tempfile - File.open(file, "w") { |f| f.puts "rah = something " } + end + + # #415 + def test_remove_trailing_spaces + config = mkconfig + file = tempfile + File.open(file, "w") { |f| f.puts "rah = something " } + + config.setdefaults(:yay, :config => [file, "eh"], :rah => ["testing", "a desc"]) + + assert_nothing_raised { config.parse } + assert_equal("something", config[:rah], "did not remove trailing whitespace in parsing") + end + + # #484 + def test_parsing_unknown_variables + logstore + config = mkconfig + file = tempfile + File.open(file, "w") { |f| + f.puts %{[main]\n + one = one + two = yay + } + } - config.setdefaults(:yay, :config => [file, "eh"], :rah => ["testing", "a desc"]) + config.setdefaults(:mysection, :config => [file, "eh"], :one => ["yay", "yay"]) - assert_nothing_raised { config.parse } - assert_equal("something", config[:rah], "did not remove trailing whitespace in parsing") + assert_nothing_raised("Unknown parameter threw an exception") do + config.parse end + end - # #484 - def test_parsing_unknown_variables - logstore - config = mkconfig - file = tempfile - File.open(file, "w") { |f| - f.puts %{[main]\n - one = one - two = yay - } - } + def test_multiple_interpolations - config.setdefaults(:mysection, :config => [file, "eh"], :one => ["yay", "yay"]) + @config.setdefaults( + :section, + :one => ["oneval", "yay"], + :two => ["twoval", "yay"], - assert_nothing_raised("Unknown parameter threw an exception") do - config.parse - end - end + :three => ["$one/$two", "yay"] + ) - def test_multiple_interpolations - @config.setdefaults( - :section, - :one => ["oneval", "yay"], - :two => ["twoval", "yay"], + assert_equal( + "oneval/twoval", @config[:three], - :three => ["$one/$two", "yay"] - ) + "Did not interpolate multiple variables") + end + # Make sure we can replace ${style} var names + def test_curly_replacements - assert_equal( - "oneval/twoval", @config[:three], + @config.setdefaults( + :section, + :one => ["oneval", "yay"], + :two => ["twoval", "yay"], - "Did not interpolate multiple variables") - end + :three => ["$one/${two}/${one}/$two", "yay"] + ) - # Make sure we can replace ${style} var names - def test_curly_replacements - @config.setdefaults( - :section, - :one => ["oneval", "yay"], - :two => ["twoval", "yay"], - - :three => ["$one/${two}/${one}/$two", "yay"] - ) + assert_equal( + "oneval/twoval/oneval/twoval", @config[:three], + "Did not interpolate curlied variables") + end - assert_equal( - "oneval/twoval/oneval/twoval", @config[:three], - - "Did not interpolate curlied variables") + # Test to make sure that we can set and get a short name + def test_setting_short_name + setting= nil + assert_nothing_raised("Could not create setting") do + setting= Setting.new :short => "n", :desc => "anything", :settings => Puppet::Util::Settings.new end + assert_equal("n", setting.short, "Short value is not retained") - # Test to make sure that we can set and get a short name - def test_setting_short_name - setting= nil - assert_nothing_raised("Could not create setting") do - setting= Setting.new :short => "n", :desc => "anything", :settings => Puppet::Util::Settings.new - end - assert_equal("n", setting.short, "Short value is not retained") - - assert_raise(ArgumentError,"Allowed multicharactered short names.") do - setting= Setting.new :short => "no", :desc => "anything", :settings => Puppet::Util::Settings.new - end + assert_raise(ArgumentError,"Allowed multicharactered short names.") do + setting= Setting.new :short => "no", :desc => "anything", :settings => Puppet::Util::Settings.new end + end - # Test to make sure that no two celements have the same short name - def test_celement_short_name_not_duplicated - config = mkconfig - assert_nothing_raised("Could not create celement with short name.") do + # Test to make sure that no two celements have the same short name + def test_celement_short_name_not_duplicated + config = mkconfig + assert_nothing_raised("Could not create celement with short name.") do - config.setdefaults( - :main, + config.setdefaults( + :main, - :one => { :default => "blah", :desc => "anything", :short => "o" }) - end - assert_nothing_raised("Could not create second celement with short name.") do + :one => { :default => "blah", :desc => "anything", :short => "o" }) + end + assert_nothing_raised("Could not create second celement with short name.") do - config.setdefaults( - :main, + config.setdefaults( + :main, - :two => { :default => "blah", :desc => "anything", :short => "i" }) - end - assert_raise(ArgumentError, "Could create second celement with duplicate short name.") do + :two => { :default => "blah", :desc => "anything", :short => "i" }) + end + assert_raise(ArgumentError, "Could create second celement with duplicate short name.") do - config.setdefaults( - :main, + config.setdefaults( + :main, - :three => { :default => "blah", :desc => "anything", :short => "i" }) - end - # make sure that when the above raises an expection that the config is not included - assert(!config.include?(:three), "Invalid configuration item was retained") + :three => { :default => "blah", :desc => "anything", :short => "i" }) end + # make sure that when the above raises an expection that the config is not included + assert(!config.include?(:three), "Invalid configuration item was retained") + end - # Tell getopt which arguments are valid - def test_get_getopt_args - element = Setting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new - assert_equal([["--foo", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args") + # Tell getopt which arguments are valid + def test_get_getopt_args + element = Setting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new + assert_equal([["--foo", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args") - element.short = "n" - assert_equal([["--foo", "-n", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args") + element.short = "n" + assert_equal([["--foo", "-n", GetoptLong::REQUIRED_ARGUMENT]], element.getopt_args, "Did not produce appropriate getopt args") - element = BooleanSetting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new + element = BooleanSetting.new :name => "foo", :desc => "anything", :settings => Puppet::Util::Settings.new - assert_equal( - [["--foo", GetoptLong::NO_ARGUMENT], ["--no-foo", GetoptLong::NO_ARGUMENT]], + assert_equal( + [["--foo", GetoptLong::NO_ARGUMENT], ["--no-foo", GetoptLong::NO_ARGUMENT]], - element.getopt_args, "Did not produce appropriate getopt args") + element.getopt_args, "Did not produce appropriate getopt args") - element.short = "n" + element.short = "n" - assert_equal( - [["--foo", "-n", GetoptLong::NO_ARGUMENT],["--no-foo", GetoptLong::NO_ARGUMENT]], + assert_equal( + [["--foo", "-n", GetoptLong::NO_ARGUMENT],["--no-foo", GetoptLong::NO_ARGUMENT]], - element.getopt_args, "Did not produce appropriate getopt args") - end + element.getopt_args, "Did not produce appropriate getopt args") + end end diff --git a/test/util/storage.rb b/test/util/storage.rb index cde5d6414..f4836ce78 100755 --- a/test/util/storage.rb +++ b/test/util/storage.rb @@ -6,76 +6,76 @@ require 'puppet' require 'puppettest' class TestStorage < Test::Unit::TestCase - include PuppetTest + include PuppetTest - def mkfile - path = tempfile - File.open(path, "w") { |f| f.puts :yayness } + def mkfile + path = tempfile + File.open(path, "w") { |f| f.puts :yayness } - f = Puppet::Type.type(:file).new( + f = Puppet::Type.type(:file).new( - :name => path, + :name => path, - :check => %w{checksum type} - ) - - 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 - - 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 + :check => %w{checksum type} + ) + + 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 + + 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 end diff --git a/test/util/subclass_loader.rb b/test/util/subclass_loader.rb index 946bc2b34..957b6cc6c 100755 --- a/test/util/subclass_loader.rb +++ b/test/util/subclass_loader.rb @@ -6,84 +6,84 @@ require 'puppettest' require 'puppet/util/subclass_loader' class TestPuppetUtilSubclassLoader < Test::Unit::TestCase - include PuppetTest - - class LoadTest - extend Puppet::Util::SubclassLoader - handle_subclasses :faker, "puppet/fakeloaders" + include PuppetTest + + class LoadTest + extend Puppet::Util::SubclassLoader + handle_subclasses :faker, "puppet/fakeloaders" + end + + def mk_subclass(name, path, parent) + # Make a fake client + unless defined?(@basedir) + @basedir ||= tempfile + $LOAD_PATH << @basedir + cleanup { $LOAD_PATH.delete(@basedir) if $LOAD_PATH.include?(@basedir) } end - def mk_subclass(name, path, parent) - # Make a fake client - unless defined?(@basedir) - @basedir ||= tempfile - $LOAD_PATH << @basedir - cleanup { $LOAD_PATH.delete(@basedir) if $LOAD_PATH.include?(@basedir) } - end - - libdir = File.join([@basedir, path.split(File::SEPARATOR)].flatten) - FileUtils.mkdir_p(libdir) - - file = File.join(libdir, "#{name}.rb") - File.open(file, "w") do |f| - f.puts %{class #{parent}::#{name.to_s.capitalize} < #{parent}; end} - end - end + libdir = File.join([@basedir, path.split(File::SEPARATOR)].flatten) + FileUtils.mkdir_p(libdir) - def test_subclass_loading - # Make a fake client - mk_subclass("fake", "puppet/fakeloaders", "TestPuppetUtilSubclassLoader::LoadTest") + file = File.join(libdir, "#{name}.rb") + File.open(file, "w") do |f| + f.puts %{class #{parent}::#{name.to_s.capitalize} < #{parent}; end} + end + end + def test_subclass_loading + # Make a fake client + mk_subclass("fake", "puppet/fakeloaders", "TestPuppetUtilSubclassLoader::LoadTest") - fake = nil - assert_nothing_raised do - fake = LoadTest.faker(:fake) - end - assert_nothing_raised do - assert_equal(fake, LoadTest.fake, "Did not get subclass back from main method") - end - assert(fake, "did not load subclass") - # Now make sure the subclass behaves correctly - assert_equal(:Fake, fake.name, "name was not calculated correctly") + fake = nil + assert_nothing_raised do + fake = LoadTest.faker(:fake) end - - def test_multiple_subclasses - sub1 = Class.new(LoadTest) - Object.const_set("Sub1", sub1) - sub2 = Class.new(sub1) - Object.const_set("Sub2", sub2) - assert_equal(sub2, LoadTest.sub2, "did not get subclass of subclass") + assert_nothing_raised do + assert_equal(fake, LoadTest.fake, "Did not get subclass back from main method") end + assert(fake, "did not load subclass") + + # Now make sure the subclass behaves correctly + assert_equal(:Fake, fake.name, "name was not calculated correctly") + end + + def test_multiple_subclasses + sub1 = Class.new(LoadTest) + Object.const_set("Sub1", sub1) + sub2 = Class.new(sub1) + Object.const_set("Sub2", sub2) + assert_equal(sub2, LoadTest.sub2, "did not get subclass of subclass") + end + + # I started out using a class variable to mark the loader, + # but it's shared among all classes that include this module, + # so it didn't work. This is testing whether I get the behaviour + # that I want. + def test_multiple_classes_using_module + other = Class.new do + extend Puppet::Util::SubclassLoader + handle_subclasses :other, "puppet/other" + end + Object.const_set("OtherLoader", other) + + mk_subclass("multipletest", "puppet/other", "OtherLoader") + mk_subclass("multipletest", "puppet/fakeloaders", "TestPuppetUtilSubclassLoader::LoadTest") + #system("find #{@basedir}") + #puts File.read(File.join(@basedir, "puppet/fakeloaders/multipletest.rb")) + #puts File.read(File.join(@basedir, "puppet/other/multipletest.rb")) - # I started out using a class variable to mark the loader, - # but it's shared among all classes that include this module, - # so it didn't work. This is testing whether I get the behaviour - # that I want. - def test_multiple_classes_using_module - other = Class.new do - extend Puppet::Util::SubclassLoader - handle_subclasses :other, "puppet/other" - end - Object.const_set("OtherLoader", other) - - mk_subclass("multipletest", "puppet/other", "OtherLoader") - mk_subclass("multipletest", "puppet/fakeloaders", "TestPuppetUtilSubclassLoader::LoadTest") - #system("find #{@basedir}") - #puts File.read(File.join(@basedir, "puppet/fakeloaders/multipletest.rb")) - #puts File.read(File.join(@basedir, "puppet/other/multipletest.rb")) - - othersub = mainsub = nil - assert_nothing_raised("Could not look up other sub") do - othersub = OtherLoader.other(:multipletest) - end - assert_nothing_raised("Could not look up main sub") do - mainsub = LoadTest.faker(:multipletest) - end - assert(othersub, "did not get other sub") - assert(mainsub, "did not get main sub") - assert(othersub.ancestors.include?(OtherLoader), "othersub is not a subclass of otherloader") - assert(mainsub.ancestors.include?(LoadTest), "mainsub is not a subclass of loadtest") + othersub = mainsub = nil + assert_nothing_raised("Could not look up other sub") do + othersub = OtherLoader.other(:multipletest) + end + assert_nothing_raised("Could not look up main sub") do + mainsub = LoadTest.faker(:multipletest) end + assert(othersub, "did not get other sub") + assert(mainsub, "did not get main sub") + assert(othersub.ancestors.include?(OtherLoader), "othersub is not a subclass of otherloader") + assert(mainsub.ancestors.include?(LoadTest), "mainsub is not a subclass of loadtest") + end end diff --git a/test/util/utiltest.rb b/test/util/utiltest.rb index 45c48727d..0e55e1dde 100755 --- a/test/util/utiltest.rb +++ b/test/util/utiltest.rb @@ -6,231 +6,231 @@ require 'puppettest' require 'mocha' class TestPuppetUtil < Test::Unit::TestCase - include PuppetTest + include PuppetTest - def test_withumask - oldmask = File.umask + def test_withumask + oldmask = File.umask - path = tempfile + path = tempfile - # FIXME this fails on FreeBSD with a mode of 01777 - Puppet::Util.withumask(000) do - Dir.mkdir(path, 0777) - end + # FIXME this fails on FreeBSD with a mode of 01777 + Puppet::Util.withumask(000) do + Dir.mkdir(path, 0777) + end + + assert(File.stat(path).mode & 007777 == 0777, "File has the incorrect mode") + assert_equal(oldmask, File.umask, "Umask was not reset") + end + + def test_benchmark + path = tempfile + str = "yayness" + File.open(path, "w") do |f| f.print "yayness" end + + # First test it with the normal args + assert_nothing_raised do + val = nil + result = Puppet::Util.benchmark(:notice, "Read file") do + val = File.read(path) + end + + assert_equal(str, val) + + assert_instance_of(Float, result) - assert(File.stat(path).mode & 007777 == 0777, "File has the incorrect mode") - assert_equal(oldmask, File.umask, "Umask was not reset") end - def test_benchmark - path = tempfile - str = "yayness" - File.open(path, "w") do |f| f.print "yayness" end + # Now test it with a passed object + assert_nothing_raised do + val = nil + Puppet::Util.benchmark(Puppet, :notice, "Read file") do + val = File.read(path) + end - # First test it with the normal args - assert_nothing_raised do - val = nil - result = Puppet::Util.benchmark(:notice, "Read file") do - val = File.read(path) - end + assert_equal(str, val) + end + end + + def test_proxy + klass = Class.new do + attr_accessor :hash + class << self + attr_accessor :ohash + end + end + klass.send(:include, Puppet::Util) - assert_equal(str, val) + klass.ohash = {} - assert_instance_of(Float, result) + inst = klass.new + inst.hash = {} + assert_nothing_raised do + Puppet::Util.proxy klass, :hash, "[]", "[]=", :clear, :delete + end - end + assert_nothing_raised do + Puppet::Util.classproxy klass, :ohash, "[]", "[]=", :clear, :delete + end - # Now test it with a passed object - assert_nothing_raised do - val = nil - Puppet::Util.benchmark(Puppet, :notice, "Read file") do - val = File.read(path) - end + assert_nothing_raised do + inst[:yay] = "boo" + inst["cool"] = :yayness + end - assert_equal(str, val) - end + [:yay, "cool"].each do |var| + assert_equal(inst.hash[var], inst[var], "Var #{var} did not take") end - def test_proxy - klass = Class.new do - attr_accessor :hash - class << self - attr_accessor :ohash - end - end - klass.send(:include, Puppet::Util) - - klass.ohash = {} - - inst = klass.new - inst.hash = {} - assert_nothing_raised do - Puppet::Util.proxy klass, :hash, "[]", "[]=", :clear, :delete - end - - assert_nothing_raised do - Puppet::Util.classproxy klass, :ohash, "[]", "[]=", :clear, :delete - end - - assert_nothing_raised do - inst[:yay] = "boo" - inst["cool"] = :yayness - end - - [:yay, "cool"].each do |var| - assert_equal(inst.hash[var], inst[var], "Var #{var} did not take") - end - - assert_nothing_raised do - klass[:Yay] = "boo" - klass["Cool"] = :yayness - end - - [:Yay, "Cool"].each do |var| - assert_equal(inst.hash[var], inst[var], "Var #{var} did not take") - end - end - - def test_symbolize - ret = nil - assert_nothing_raised { - ret = Puppet::Util.symbolize("yayness") - } - - assert_equal(:yayness, ret) - - assert_nothing_raised { - ret = Puppet::Util.symbolize(:yayness) - } - - assert_equal(:yayness, ret) - - assert_nothing_raised { - ret = Puppet::Util.symbolize(43) - } - - assert_equal(43, ret) - - assert_nothing_raised { - ret = Puppet::Util.symbolize(nil) - } - - assert_equal(nil, ret) - end - - def test_execute - command = tempfile - File.open(command, "w") { |f| - f.puts %{#!/bin/sh\n/bin/echo "$1">&1; echo "$2">&2} - } - File.chmod(0755, command) - output = nil - assert_nothing_raised do - output = Puppet::Util.execute([command, "yaytest", "funtest"]) - end - assert_equal("yaytest\nfuntest\n", output) - - # Now try it with a single quote - assert_nothing_raised do - output = Puppet::Util.execute([command, "yay'test", "funtest"]) - end - assert_equal("yay'test\nfuntest\n", output) - - # Now make sure we can squelch output (#565) - assert_nothing_raised do - output = Puppet::Util.execute([command, "yay'test", "funtest"], :squelch => true) - end - assert_equal(nil, output) - - # Now test that we correctly fail if the command returns non-zero - assert_raise(Puppet::ExecutionFailure) do - out = Puppet::Util.execute(["touch", "/no/such/file/could/exist"]) - end - - # And that we can tell it not to fail - assert_nothing_raised do - out = Puppet::Util.execute(["touch", "/no/such/file/could/exist"], :failonfail => false) - end - - if Process.uid == 0 - # Make sure we correctly set our uid and gid - user = nonrootuser - group = nonrootgroup - file = tempfile - assert_nothing_raised do - Puppet::Util.execute(["touch", file], :uid => user.name, :gid => group.name) - end - assert(FileTest.exists?(file), "file was not created") - assert_equal(user.uid, File.stat(file).uid, "uid was not set correctly") - - # We can't really check the gid, because it just behaves too - # inconsistently everywhere. - # assert_equal(group.gid, File.stat(file).gid, - # "gid was not set correctly") - end - - # (#565) Test the case of patricide. - patricidecommand = tempfile - File.open(patricidecommand, "w") { |f| - f.puts %{#!/bin/bash\n/bin/bash -c 'kill -TERM \$PPID' &;\n while [ 1 ]; do echo -n ''; done;\n} - } - File.chmod(0755, patricidecommand) - assert_nothing_raised do - output = Puppet::Util.execute([patricidecommand], :squelch => true) - end - assert_equal(nil, output) - # See what happens if we try and read the pipe to the command... - assert_raise(Puppet::ExecutionFailure) do - output = Puppet::Util.execute([patricidecommand]) - end - assert_nothing_raised do - output = Puppet::Util.execute([patricidecommand], :failonfail => false) - end - end - - def test_lang_environ_in_execute - orig_lang = ENV["LANG"] - orig_lc_all = ENV["LC_ALL"] - orig_lc_messages = ENV["LC_MESSAGES"] - orig_language = ENV["LANGUAGE"] - - cleanup do - ENV["LANG"] = orig_lang - ENV["LC_ALL"] = orig_lc_all - ENV["LC_MESSAGES"] = orig_lc_messages - ENV["LANGUAGE"] = orig_lc_messages - end - - # Mmm, we love gettext(3) - ENV["LANG"] = "en_US" - ENV["LC_ALL"] = "en_US" - ENV["LC_MESSAGES"] = "en_US" - ENV["LANGUAGE"] = "en_US" - - %w{LANG LC_ALL LC_MESSAGES LANGUAGE}.each do |env| - - assert_equal( - 'C', - Puppet::Util.execute(['ruby', '-e', "print ENV['#{env}']"]), - - "Environment var #{env} wasn't set to 'C'") - - assert_equal 'en_US', ENV[env], "Environment var #{env} not set back correctly" - end - - end - - # Check whether execute accepts strings in addition to arrays. - def test_string_exec - cmd = "/bin/echo howdy" - output = nil - assert_raise(ArgumentError) { - output = Puppet::Util.execute(cmd) - } - #assert_equal("howdy\n", output) - #assert_raise(RuntimeError) { - # Puppet::Util.execute(cmd, 0, 0) - #} + assert_nothing_raised do + klass[:Yay] = "boo" + klass["Cool"] = :yayness + end + + [:Yay, "Cool"].each do |var| + assert_equal(inst.hash[var], inst[var], "Var #{var} did not take") + end + end + + def test_symbolize + ret = nil + assert_nothing_raised { + ret = Puppet::Util.symbolize("yayness") + } + + assert_equal(:yayness, ret) + + assert_nothing_raised { + ret = Puppet::Util.symbolize(:yayness) + } + + assert_equal(:yayness, ret) + + assert_nothing_raised { + ret = Puppet::Util.symbolize(43) + } + + assert_equal(43, ret) + + assert_nothing_raised { + ret = Puppet::Util.symbolize(nil) + } + + assert_equal(nil, ret) + end + + def test_execute + command = tempfile + File.open(command, "w") { |f| + f.puts %{#!/bin/sh\n/bin/echo "$1">&1; echo "$2">&2} + } + File.chmod(0755, command) + output = nil + assert_nothing_raised do + output = Puppet::Util.execute([command, "yaytest", "funtest"]) end + assert_equal("yaytest\nfuntest\n", output) + + # Now try it with a single quote + assert_nothing_raised do + output = Puppet::Util.execute([command, "yay'test", "funtest"]) + end + assert_equal("yay'test\nfuntest\n", output) + + # Now make sure we can squelch output (#565) + assert_nothing_raised do + output = Puppet::Util.execute([command, "yay'test", "funtest"], :squelch => true) + end + assert_equal(nil, output) + + # Now test that we correctly fail if the command returns non-zero + assert_raise(Puppet::ExecutionFailure) do + out = Puppet::Util.execute(["touch", "/no/such/file/could/exist"]) + end + + # And that we can tell it not to fail + assert_nothing_raised do + out = Puppet::Util.execute(["touch", "/no/such/file/could/exist"], :failonfail => false) + end + + if Process.uid == 0 + # Make sure we correctly set our uid and gid + user = nonrootuser + group = nonrootgroup + file = tempfile + assert_nothing_raised do + Puppet::Util.execute(["touch", file], :uid => user.name, :gid => group.name) + end + assert(FileTest.exists?(file), "file was not created") + assert_equal(user.uid, File.stat(file).uid, "uid was not set correctly") + + # We can't really check the gid, because it just behaves too + # inconsistently everywhere. + # assert_equal(group.gid, File.stat(file).gid, + # "gid was not set correctly") + end + + # (#565) Test the case of patricide. + patricidecommand = tempfile + File.open(patricidecommand, "w") { |f| + f.puts %{#!/bin/bash\n/bin/bash -c 'kill -TERM \$PPID' &;\n while [ 1 ]; do echo -n ''; done;\n} + } + File.chmod(0755, patricidecommand) + assert_nothing_raised do + output = Puppet::Util.execute([patricidecommand], :squelch => true) + end + assert_equal(nil, output) + # See what happens if we try and read the pipe to the command... + assert_raise(Puppet::ExecutionFailure) do + output = Puppet::Util.execute([patricidecommand]) + end + assert_nothing_raised do + output = Puppet::Util.execute([patricidecommand], :failonfail => false) + end + end + + def test_lang_environ_in_execute + orig_lang = ENV["LANG"] + orig_lc_all = ENV["LC_ALL"] + orig_lc_messages = ENV["LC_MESSAGES"] + orig_language = ENV["LANGUAGE"] + + cleanup do + ENV["LANG"] = orig_lang + ENV["LC_ALL"] = orig_lc_all + ENV["LC_MESSAGES"] = orig_lc_messages + ENV["LANGUAGE"] = orig_lc_messages + end + + # Mmm, we love gettext(3) + ENV["LANG"] = "en_US" + ENV["LC_ALL"] = "en_US" + ENV["LC_MESSAGES"] = "en_US" + ENV["LANGUAGE"] = "en_US" + + %w{LANG LC_ALL LC_MESSAGES LANGUAGE}.each do |env| + + assert_equal( + 'C', + Puppet::Util.execute(['ruby', '-e', "print ENV['#{env}']"]), + + "Environment var #{env} wasn't set to 'C'") + + assert_equal 'en_US', ENV[env], "Environment var #{env} not set back correctly" + end + + end + + # Check whether execute accepts strings in addition to arrays. + def test_string_exec + cmd = "/bin/echo howdy" + output = nil + assert_raise(ArgumentError) { + output = Puppet::Util.execute(cmd) + } + #assert_equal("howdy\n", output) + #assert_raise(RuntimeError) { + # Puppet::Util.execute(cmd, 0, 0) + #} + end end |
