From f7328804d00d8a82d7ab3a955ff579ff956ef3d0 Mon Sep 17 00:00:00 2001 From: luke Date: Sat, 22 Oct 2005 22:27:20 +0000 Subject: Getting rid of the tc_ prefix to test cases git-svn-id: https://reductivelabs.com/svn/puppet/trunk@724 980ebf18-57e1-0310-9a29-db15c13687c0 --- test/certmgr/certmgr.rb | 273 ++++++++++++++ test/certmgr/tc_certmgr.rb | 273 -------------- test/client/client.rb | 203 ++++++++++ test/client/tc_client.rb | 203 ---------- test/executables/puppetbin.rb | 46 +++ test/executables/puppetca.rb | 79 ++++ test/executables/puppetd.rb | 70 ++++ test/executables/puppetmasterd.rb | 148 ++++++++ test/executables/tc_puppetbin.rb | 46 --- test/executables/tc_puppetca.rb | 79 ---- test/executables/tc_puppetd.rb | 70 ---- test/executables/tc_puppetmasterd.rb | 148 -------- test/language/ast.rb | 500 +++++++++++++++++++++++++ test/language/interpreter.rb | 29 ++ test/language/scope.rb | 305 +++++++++++++++ test/language/snippets.rb | 445 ++++++++++++++++++++++ test/language/tc_ast.rb | 500 ------------------------- test/language/tc_interpreter.rb | 29 -- test/language/tc_scope.rb | 305 --------------- test/language/tc_snippets.rb | 445 ---------------------- test/other/events.rb | 111 ++++++ test/other/log.rb | 123 +++++++ test/other/metrics.rb | 92 +++++ test/other/overrides.rb | 115 ++++++ test/other/parsedfile.rb | 31 ++ test/other/relationships.rb | 113 ++++++ test/other/state.rb | 106 ++++++ test/other/tc_events.rb | 111 ------ test/other/tc_log.rb | 123 ------- test/other/tc_metrics.rb | 92 ----- test/other/tc_overrides.rb | 115 ------ test/other/tc_parsedfile.rb | 31 -- test/other/tc_relationships.rb | 113 ------ test/other/tc_state.rb | 106 ------ test/other/tc_transactions.rb | 227 ------------ test/other/transactions.rb | 227 ++++++++++++ test/parser/lexer.rb | 120 ++++++ test/parser/parser.rb | 180 +++++++++ test/parser/tc_lexer.rb | 120 ------ test/parser/tc_parser.rb | 180 --------- test/puppet/defaults.rb | 100 +++++ test/puppet/tc_defaults.rb | 100 ----- test/puppettest.rb | 2 +- test/server/authstore.rb | 217 +++++++++++ test/server/bucket.rb | 225 ++++++++++++ test/server/ca.rb | 201 ++++++++++ test/server/fileserver.rb | 694 +++++++++++++++++++++++++++++++++++ test/server/master.rb | 151 ++++++++ test/server/server.rb | 130 +++++++ test/server/tc_authstore.rb | 217 ----------- test/server/tc_bucket.rb | 225 ------------ test/server/tc_ca.rb | 201 ---------- test/server/tc_fileserver.rb | 694 ----------------------------------- test/server/tc_master.rb | 151 -------- test/server/tc_server.rb | 130 ------- test/tagging/tagging.rb | 80 ++++ test/tagging/tc_tagging.rb | 80 ---- test/test | 12 +- test/types/basic.rb | 119 ++++++ test/types/component.rb | 279 ++++++++++++++ test/types/cron.rb | 262 +++++++++++++ test/types/exec.rb | 213 +++++++++++ test/types/file.rb | 502 +++++++++++++++++++++++++ test/types/filebucket.rb | 167 +++++++++ test/types/fileignoresource.rb | 287 +++++++++++++++ test/types/filesources.rb | 532 +++++++++++++++++++++++++++ test/types/filetype.rb | 162 ++++++++ test/types/group.rb | 247 +++++++++++++ test/types/package.rb | 205 +++++++++++ test/types/query.rb | 109 ++++++ test/types/service.rb | 101 +++++ test/types/symlink.rb | 93 +++++ test/types/tc_basic.rb | 119 ------ test/types/tc_component.rb | 279 -------------- test/types/tc_cron.rb | 262 ------------- test/types/tc_exec.rb | 213 ----------- test/types/tc_file.rb | 502 ------------------------- test/types/tc_filebucket.rb | 167 --------- test/types/tc_fileignoresource.rb | 287 --------------- test/types/tc_filesources.rb | 532 --------------------------- test/types/tc_filetype.rb | 162 -------- test/types/tc_group.rb | 247 ------------- test/types/tc_package.rb | 205 ----------- test/types/tc_query.rb | 109 ------ test/types/tc_service.rb | 101 ----- test/types/tc_symlink.rb | 93 ----- test/types/tc_tidy.rb | 124 ------- test/types/tc_type.rb | 114 ------ test/types/tc_user.rb | 350 ------------------ test/types/tidy.rb | 124 +++++++ test/types/type.rb | 114 ++++++ test/types/user.rb | 350 ++++++++++++++++++ 92 files changed, 8983 insertions(+), 8991 deletions(-) create mode 100755 test/certmgr/certmgr.rb delete mode 100755 test/certmgr/tc_certmgr.rb create mode 100644 test/client/client.rb delete mode 100644 test/client/tc_client.rb create mode 100755 test/executables/puppetbin.rb create mode 100755 test/executables/puppetca.rb create mode 100755 test/executables/puppetd.rb create mode 100755 test/executables/puppetmasterd.rb delete mode 100755 test/executables/tc_puppetbin.rb delete mode 100755 test/executables/tc_puppetca.rb delete mode 100755 test/executables/tc_puppetd.rb delete mode 100755 test/executables/tc_puppetmasterd.rb create mode 100755 test/language/ast.rb create mode 100755 test/language/interpreter.rb create mode 100755 test/language/scope.rb create mode 100755 test/language/snippets.rb delete mode 100755 test/language/tc_ast.rb delete mode 100755 test/language/tc_interpreter.rb delete mode 100755 test/language/tc_scope.rb delete mode 100755 test/language/tc_snippets.rb create mode 100755 test/other/events.rb create mode 100644 test/other/log.rb create mode 100644 test/other/metrics.rb create mode 100755 test/other/overrides.rb create mode 100755 test/other/parsedfile.rb create mode 100755 test/other/relationships.rb create mode 100644 test/other/state.rb delete mode 100755 test/other/tc_events.rb delete mode 100644 test/other/tc_log.rb delete mode 100644 test/other/tc_metrics.rb delete mode 100755 test/other/tc_overrides.rb delete mode 100755 test/other/tc_parsedfile.rb delete mode 100755 test/other/tc_relationships.rb delete mode 100644 test/other/tc_state.rb delete mode 100644 test/other/tc_transactions.rb create mode 100644 test/other/transactions.rb create mode 100644 test/parser/lexer.rb create mode 100644 test/parser/parser.rb delete mode 100644 test/parser/tc_lexer.rb delete mode 100644 test/parser/tc_parser.rb create mode 100755 test/puppet/defaults.rb delete mode 100755 test/puppet/tc_defaults.rb create mode 100755 test/server/authstore.rb create mode 100644 test/server/bucket.rb create mode 100644 test/server/ca.rb create mode 100755 test/server/fileserver.rb create mode 100644 test/server/master.rb create mode 100644 test/server/server.rb delete mode 100755 test/server/tc_authstore.rb delete mode 100644 test/server/tc_bucket.rb delete mode 100644 test/server/tc_ca.rb delete mode 100755 test/server/tc_fileserver.rb delete mode 100644 test/server/tc_master.rb delete mode 100644 test/server/tc_server.rb create mode 100644 test/tagging/tagging.rb delete mode 100644 test/tagging/tc_tagging.rb create mode 100644 test/types/basic.rb create mode 100755 test/types/component.rb create mode 100755 test/types/cron.rb create mode 100755 test/types/exec.rb create mode 100644 test/types/file.rb create mode 100755 test/types/filebucket.rb create mode 100644 test/types/fileignoresource.rb create mode 100755 test/types/filesources.rb create mode 100644 test/types/filetype.rb create mode 100755 test/types/group.rb create mode 100644 test/types/package.rb create mode 100644 test/types/query.rb create mode 100644 test/types/service.rb create mode 100755 test/types/symlink.rb delete mode 100644 test/types/tc_basic.rb delete mode 100755 test/types/tc_component.rb delete mode 100755 test/types/tc_cron.rb delete mode 100755 test/types/tc_exec.rb delete mode 100644 test/types/tc_file.rb delete mode 100755 test/types/tc_filebucket.rb delete mode 100644 test/types/tc_fileignoresource.rb delete mode 100755 test/types/tc_filesources.rb delete mode 100644 test/types/tc_filetype.rb delete mode 100755 test/types/tc_group.rb delete mode 100644 test/types/tc_package.rb delete mode 100644 test/types/tc_query.rb delete mode 100644 test/types/tc_service.rb delete mode 100755 test/types/tc_symlink.rb delete mode 100755 test/types/tc_tidy.rb delete mode 100644 test/types/tc_type.rb delete mode 100755 test/types/tc_user.rb create mode 100755 test/types/tidy.rb create mode 100644 test/types/type.rb create mode 100755 test/types/user.rb diff --git a/test/certmgr/certmgr.rb b/test/certmgr/certmgr.rb new file mode 100755 index 000000000..c0ec7c934 --- /dev/null +++ b/test/certmgr/certmgr.rb @@ -0,0 +1,273 @@ +#!/usr/bin/ruby + +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/sslcertificates.rb' +require 'test/unit' +require 'puppettest' + +# so, what kind of things do we want to test? + +# we don't need to test function, since we're confident in the +# library tests. We do, however, need to test how things are actually +# working in the language. + +# so really, we want to do things like test that our ast is correct +# and test whether we've got things in the right scopes + +class TestCertMgr < Test::Unit::TestCase + include TestPuppet + def setup + Puppet[:loglevel] = :debug if __FILE__ == $0 + #@dir = File.join(Puppet[:certdir], "testing") + system("mkdir -p %s" % @dir) + @@tmpfiles = [@dir] + end + + def mkPassFile() + keyfile = File.join(@dir, "tmpkeyfile") + @@tmpfiles << keyfile + unless FileTest.exists?(@dir) + system("mkdir -p %s" % @dir) + end + File.open(keyfile, "w", 0600) { |f| + f.print "as;dklj23rlkjzdflij23wr" + } + + return keyfile + end + + def mkCA + ca = nil + Puppet[:ssldir] = @dir + assert_nothing_raised { + ca = Puppet::SSLCertificates::CA.new() + } + + return ca + end + + def teardown + @@tmpfiles.each { |f| + if FileTest.exists?(f) + system("rm -rf %s" % f) + end + } + end + + def testCreateSelfSignedCertificate + cert = nil + name = "testing" + newcert = proc { + Puppet::SSLCertificates::Certificate.new( + :name => name, + :selfsign => true + ) + } + assert_nothing_raised { + cert = newcert.call() + } + assert_nothing_raised { + cert.mkselfsigned + } + + assert_raise(Puppet::Error) { + cert.mkselfsigned + } + + assert_nothing_raised { + cert.write + } + + assert(FileTest.exists?(cert.certfile)) + + assert_nothing_raised { + cert.delete + } + + assert_nothing_raised { + cert = newcert.call() + } + assert_nothing_raised { + cert.mkselfsigned + } + + assert_nothing_raised { + cert.delete + } + + end + + def disabled_testCreateEncryptedSelfSignedCertificate + cert = nil + name = "testing" + keyfile = mkPassFile + assert_nothing_raised { + cert = Puppet::SSLCertificates::Certificate.new( + :name => name, + :selfsign => true, + :capass => keyfile + ) + } + assert_nothing_raised { + cert.mkselfsigned + } + assert_nothing_raised { + cert.mkhash + } + + assert_raise(Puppet::Error) { + cert.mkselfsigned + } + + assert(FileTest.exists?(cert.certfile)) + assert(FileTest.exists?(cert.hash)) + + assert_nothing_raised { + cert.delete + } + + assert_nothing_raised { + cert.mkselfsigned + } + + assert_nothing_raised { + cert.delete + } + + end + + def testCreateCA + ca = nil + assert_nothing_raised { + ca = Puppet::SSLCertificates::CA.new() + } + + # make the CA again and verify it doesn't fail because everything + # still exists + assert_nothing_raised { + ca = Puppet::SSLCertificates::CA.new() + } + + end + + def testSignCert + ca = mkCA() + + cert = nil + assert_nothing_raised { + cert = Puppet::SSLCertificates::Certificate.new( + :name => "signedcertest", + :state => "TN", + :city => "Nashville", + :country => "US", + :email => "luke@madstop.com", + :org => "Reductive", + :ou => "Development", + :encrypt => mkPassFile() + ) + + } + + assert_nothing_raised { + cert.mkcsr + } + + signedcert = nil + cacert = nil + + assert_nothing_raised { + signedcert, cacert = ca.sign(cert.csr) + } + + assert_instance_of(OpenSSL::X509::Certificate, signedcert) + assert_instance_of(OpenSSL::X509::Certificate, cacert) + + assert_nothing_raised { + cert.cert = signedcert + cert.cacert = cacert + cert.write + } + #system("find %s" % Puppet[:ssldir]) + #system("cp -R %s /tmp/ssltesting" % Puppet[:ssldir]) + + output = nil + assert_nothing_raised { + output = %x{openssl verify -CAfile #{Puppet[:cacert]} -purpose sslserver #{cert.certfile}} + #output = %x{openssl verify -CApath #{Puppet[:certdir]} -purpose sslserver #{cert.certfile}} + } + + assert_equal($?,0) + assert_equal("/tmp/puppetcertestingdir/certs/signedcertest.pem: OK\n", output) + end + + def mkcert(hostname) + cert = nil + assert_nothing_raised { + cert = Puppet::SSLCertificates::Certificate.new(:name => hostname) + cert.mkcsr + } + + return cert + end + + + def test_interactiveca + ca = nil + + assert_nothing_raised { + ca = Puppet::SSLCertificates::CA.new + } + + # basic initialization + hostname = "test.hostname.com" + cert = mkcert(hostname) + + # create the csr + csr = nil + assert_nothing_raised { + csr = cert.mkcsr + } + + assert_nothing_raised { + ca.storeclientcsr(csr) + } + + # store it + pulledcsr = nil + assert_nothing_raised { + pulledcsr = ca.getclientcsr(hostname) + } + + assert_equal(csr.to_pem, pulledcsr.to_pem) + + signedcert = nil + assert_nothing_raised { + signedcert, cacert = ca.sign(csr) + } + + assert_instance_of(OpenSSL::X509::Certificate, signedcert) + newsignedcert = nil + assert_nothing_raised { + newsignedcert, cacert = ca.getclientcert(hostname) + } + + assert(newsignedcert) + + assert_equal(signedcert.to_pem, newsignedcert.to_pem) + end + + def test_cafailures + ca = mkCA() + cert = cacert = nil + assert_nothing_raised { + cert, cacert = ca.getclientcert("nohost") + } + assert_nil(cert) + end +end diff --git a/test/certmgr/tc_certmgr.rb b/test/certmgr/tc_certmgr.rb deleted file mode 100755 index c0ec7c934..000000000 --- a/test/certmgr/tc_certmgr.rb +++ /dev/null @@ -1,273 +0,0 @@ -#!/usr/bin/ruby - -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/sslcertificates.rb' -require 'test/unit' -require 'puppettest' - -# so, what kind of things do we want to test? - -# we don't need to test function, since we're confident in the -# library tests. We do, however, need to test how things are actually -# working in the language. - -# so really, we want to do things like test that our ast is correct -# and test whether we've got things in the right scopes - -class TestCertMgr < Test::Unit::TestCase - include TestPuppet - def setup - Puppet[:loglevel] = :debug if __FILE__ == $0 - #@dir = File.join(Puppet[:certdir], "testing") - system("mkdir -p %s" % @dir) - @@tmpfiles = [@dir] - end - - def mkPassFile() - keyfile = File.join(@dir, "tmpkeyfile") - @@tmpfiles << keyfile - unless FileTest.exists?(@dir) - system("mkdir -p %s" % @dir) - end - File.open(keyfile, "w", 0600) { |f| - f.print "as;dklj23rlkjzdflij23wr" - } - - return keyfile - end - - def mkCA - ca = nil - Puppet[:ssldir] = @dir - assert_nothing_raised { - ca = Puppet::SSLCertificates::CA.new() - } - - return ca - end - - def teardown - @@tmpfiles.each { |f| - if FileTest.exists?(f) - system("rm -rf %s" % f) - end - } - end - - def testCreateSelfSignedCertificate - cert = nil - name = "testing" - newcert = proc { - Puppet::SSLCertificates::Certificate.new( - :name => name, - :selfsign => true - ) - } - assert_nothing_raised { - cert = newcert.call() - } - assert_nothing_raised { - cert.mkselfsigned - } - - assert_raise(Puppet::Error) { - cert.mkselfsigned - } - - assert_nothing_raised { - cert.write - } - - assert(FileTest.exists?(cert.certfile)) - - assert_nothing_raised { - cert.delete - } - - assert_nothing_raised { - cert = newcert.call() - } - assert_nothing_raised { - cert.mkselfsigned - } - - assert_nothing_raised { - cert.delete - } - - end - - def disabled_testCreateEncryptedSelfSignedCertificate - cert = nil - name = "testing" - keyfile = mkPassFile - assert_nothing_raised { - cert = Puppet::SSLCertificates::Certificate.new( - :name => name, - :selfsign => true, - :capass => keyfile - ) - } - assert_nothing_raised { - cert.mkselfsigned - } - assert_nothing_raised { - cert.mkhash - } - - assert_raise(Puppet::Error) { - cert.mkselfsigned - } - - assert(FileTest.exists?(cert.certfile)) - assert(FileTest.exists?(cert.hash)) - - assert_nothing_raised { - cert.delete - } - - assert_nothing_raised { - cert.mkselfsigned - } - - assert_nothing_raised { - cert.delete - } - - end - - def testCreateCA - ca = nil - assert_nothing_raised { - ca = Puppet::SSLCertificates::CA.new() - } - - # make the CA again and verify it doesn't fail because everything - # still exists - assert_nothing_raised { - ca = Puppet::SSLCertificates::CA.new() - } - - end - - def testSignCert - ca = mkCA() - - cert = nil - assert_nothing_raised { - cert = Puppet::SSLCertificates::Certificate.new( - :name => "signedcertest", - :state => "TN", - :city => "Nashville", - :country => "US", - :email => "luke@madstop.com", - :org => "Reductive", - :ou => "Development", - :encrypt => mkPassFile() - ) - - } - - assert_nothing_raised { - cert.mkcsr - } - - signedcert = nil - cacert = nil - - assert_nothing_raised { - signedcert, cacert = ca.sign(cert.csr) - } - - assert_instance_of(OpenSSL::X509::Certificate, signedcert) - assert_instance_of(OpenSSL::X509::Certificate, cacert) - - assert_nothing_raised { - cert.cert = signedcert - cert.cacert = cacert - cert.write - } - #system("find %s" % Puppet[:ssldir]) - #system("cp -R %s /tmp/ssltesting" % Puppet[:ssldir]) - - output = nil - assert_nothing_raised { - output = %x{openssl verify -CAfile #{Puppet[:cacert]} -purpose sslserver #{cert.certfile}} - #output = %x{openssl verify -CApath #{Puppet[:certdir]} -purpose sslserver #{cert.certfile}} - } - - assert_equal($?,0) - assert_equal("/tmp/puppetcertestingdir/certs/signedcertest.pem: OK\n", output) - end - - def mkcert(hostname) - cert = nil - assert_nothing_raised { - cert = Puppet::SSLCertificates::Certificate.new(:name => hostname) - cert.mkcsr - } - - return cert - end - - - def test_interactiveca - ca = nil - - assert_nothing_raised { - ca = Puppet::SSLCertificates::CA.new - } - - # basic initialization - hostname = "test.hostname.com" - cert = mkcert(hostname) - - # create the csr - csr = nil - assert_nothing_raised { - csr = cert.mkcsr - } - - assert_nothing_raised { - ca.storeclientcsr(csr) - } - - # store it - pulledcsr = nil - assert_nothing_raised { - pulledcsr = ca.getclientcsr(hostname) - } - - assert_equal(csr.to_pem, pulledcsr.to_pem) - - signedcert = nil - assert_nothing_raised { - signedcert, cacert = ca.sign(csr) - } - - assert_instance_of(OpenSSL::X509::Certificate, signedcert) - newsignedcert = nil - assert_nothing_raised { - newsignedcert, cacert = ca.getclientcert(hostname) - } - - assert(newsignedcert) - - assert_equal(signedcert.to_pem, newsignedcert.to_pem) - end - - def test_cafailures - ca = mkCA() - cert = cacert = nil - assert_nothing_raised { - cert, cacert = ca.getclientcert("nohost") - } - assert_nil(cert) - end -end diff --git a/test/client/client.rb b/test/client/client.rb new file mode 100644 index 000000000..39c19bb16 --- /dev/null +++ b/test/client/client.rb @@ -0,0 +1,203 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/client' +require 'puppet/server' +require 'test/unit' +require 'puppettest.rb' + +# $Id$ + +class TestClient < Test::Unit::TestCase + include ServerTest + # a single run through of connect, auth, etc. + def test_sslInitWithAutosigningLocalServer + # autosign everything, for simplicity + Puppet[:autosign] = true + + # create a server to which to connect + mkserver() + + # create our client + client = nil + assert_nothing_raised { + client = Puppet::Client::MasterClient.new( + :Server => "localhost", + :Port => @@port + ) + } + + # get our certs + assert_nothing_raised { + client.initcerts + } + + # make sure all of our cert files exist + certfile = File.join(Puppet[:certdir], [client.fqdn, "pem"].join(".")) + keyfile = File.join(Puppet[:privatekeydir], [client.fqdn, "pem"].join(".")) + publickeyfile = File.join(Puppet[:publickeydir], [client.fqdn, "pem"].join(".")) + + assert(File.exists?(keyfile)) + assert(File.exists?(certfile)) + assert(File.exists?(publickeyfile)) + + # verify we can retrieve the configuration + assert_nothing_raised("Client could not retrieve configuration") { + client.getconfig + } + + # and apply it + assert_nothing_raised("Client could not apply configuration") { + client.apply + } + + # and verify that it did what it was supposed to + assert(FileTest.exists?(@createdfile), + "Applied file does not exist") + end + + + # here we create two servers; we + def test_failureWithUntrustedCerts + Puppet[:autosign] = true + + # create a pair of clients with no certs + nonemaster = nil + assert_nothing_raised { + nonemaster = Puppet::Client::MasterClient.new( + :Server => "localhost", + :Port => @@port + ) + } + + nonebucket = nil + assert_nothing_raised { + nonebucket = Puppet::Client::Dipper.new( + :Server => "localhost", + :Port => @@port + ) + } + + # create a ca so we can create a set of certs + ca = nil + assert_nothing_raised { + ca = Puppet::Client::CAClient.new(:CA => true, :Local => true) + ca.requestcert + } + + # initialize our clients with this set of certs + certmaster = nil + assert_nothing_raised { + certmaster = Puppet::Client::MasterClient.new( + :Server => "localhost", + :Port => @@port + ) + } + + certbucket = nil + assert_nothing_raised { + certbucket = Puppet::Client::Dipper.new( + :Server => "localhost", + :Port => @@port + ) + } + + # clean up the existing certs, so the server creates a new CA + system("rm -rf %s" % Puppet[:ssldir]) + + # start our server + mkserver + + # now verify that our client cannot do non-cert operations + # because its certs are signed by a different CA + assert_raise(Puppet::NetworkClientError, + "Client was allowed to call getconfig with no certs") { + nonemaster.getconfig + } + assert_raise(Puppet::NetworkClientError, + "Client was allowed to call getconfig with untrusted certs") { + certmaster.getconfig + } + + assert_raise(Puppet::NetworkClientError, + "Client was allowed to call backup with no certs") { + nonebucket.backup("/etc/passwd") + } + assert_raise(Puppet::NetworkClientError, + "Client was allowed to call backup with untrusted certs") { + certbucket.backup("/etc/passwd") + } + end + + # disabled because the server needs to have its certs in place + # in order to start at all + # i don't think this test makes much sense anyway + def disabled_test_sslInitWithNonsigningLocalServer + Puppet[:autosign] = false + Puppet[:ssldir] = "/tmp/puppetclientcertests" + @@tmpfiles.push Puppet[:ssldir] + + file = File.join($puppetbase, "examples", "code", "head") + + server = nil + port = 8086 + assert_nothing_raised { + server = Puppet::Server.new( + :Port => port, + :Handlers => { + :CA => {}, # so that certs autogenerate + :Master => { + :File => file, + }, + } + ) + } + + spid = fork { + trap(:INT) { server.shutdown } + server.start + } + + @@tmppids << spid + client = nil + assert_nothing_raised { + client = Puppet::Client.new(:Server => "localhost", :Port => port) + } + certfile = File.join(Puppet[:certdir], [client.fqdn, "pem"].join(".")) + cafile = File.join(Puppet[:certdir], ["ca", "pem"].join(".")) + assert_nil(client.initcerts) + assert(! File.exists?(certfile)) + + ca = nil + assert_nothing_raised { + ca = Puppet::SSLCertificates::CA.new() + } + + + csr = nil + assert_nothing_raised { + csr = ca.getclientcsr(client.fqdn) + } + + assert(csr) + + cert = nil + assert_nothing_raised { + cert, cacert = ca.sign(csr) + File.open(certfile, "w") { |f| f.print cert.to_pem } + File.open(cafile, "w") { |f| f.print cacert.to_pem } + } + + # this time it should get the cert correctly + assert_nothing_raised { + client.initcerts + } + + # this isn't a very good test, since i just wrote the file out + assert(File.exists?(certfile)) + end +end diff --git a/test/client/tc_client.rb b/test/client/tc_client.rb deleted file mode 100644 index 39c19bb16..000000000 --- a/test/client/tc_client.rb +++ /dev/null @@ -1,203 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/client' -require 'puppet/server' -require 'test/unit' -require 'puppettest.rb' - -# $Id$ - -class TestClient < Test::Unit::TestCase - include ServerTest - # a single run through of connect, auth, etc. - def test_sslInitWithAutosigningLocalServer - # autosign everything, for simplicity - Puppet[:autosign] = true - - # create a server to which to connect - mkserver() - - # create our client - client = nil - assert_nothing_raised { - client = Puppet::Client::MasterClient.new( - :Server => "localhost", - :Port => @@port - ) - } - - # get our certs - assert_nothing_raised { - client.initcerts - } - - # make sure all of our cert files exist - certfile = File.join(Puppet[:certdir], [client.fqdn, "pem"].join(".")) - keyfile = File.join(Puppet[:privatekeydir], [client.fqdn, "pem"].join(".")) - publickeyfile = File.join(Puppet[:publickeydir], [client.fqdn, "pem"].join(".")) - - assert(File.exists?(keyfile)) - assert(File.exists?(certfile)) - assert(File.exists?(publickeyfile)) - - # verify we can retrieve the configuration - assert_nothing_raised("Client could not retrieve configuration") { - client.getconfig - } - - # and apply it - assert_nothing_raised("Client could not apply configuration") { - client.apply - } - - # and verify that it did what it was supposed to - assert(FileTest.exists?(@createdfile), - "Applied file does not exist") - end - - - # here we create two servers; we - def test_failureWithUntrustedCerts - Puppet[:autosign] = true - - # create a pair of clients with no certs - nonemaster = nil - assert_nothing_raised { - nonemaster = Puppet::Client::MasterClient.new( - :Server => "localhost", - :Port => @@port - ) - } - - nonebucket = nil - assert_nothing_raised { - nonebucket = Puppet::Client::Dipper.new( - :Server => "localhost", - :Port => @@port - ) - } - - # create a ca so we can create a set of certs - ca = nil - assert_nothing_raised { - ca = Puppet::Client::CAClient.new(:CA => true, :Local => true) - ca.requestcert - } - - # initialize our clients with this set of certs - certmaster = nil - assert_nothing_raised { - certmaster = Puppet::Client::MasterClient.new( - :Server => "localhost", - :Port => @@port - ) - } - - certbucket = nil - assert_nothing_raised { - certbucket = Puppet::Client::Dipper.new( - :Server => "localhost", - :Port => @@port - ) - } - - # clean up the existing certs, so the server creates a new CA - system("rm -rf %s" % Puppet[:ssldir]) - - # start our server - mkserver - - # now verify that our client cannot do non-cert operations - # because its certs are signed by a different CA - assert_raise(Puppet::NetworkClientError, - "Client was allowed to call getconfig with no certs") { - nonemaster.getconfig - } - assert_raise(Puppet::NetworkClientError, - "Client was allowed to call getconfig with untrusted certs") { - certmaster.getconfig - } - - assert_raise(Puppet::NetworkClientError, - "Client was allowed to call backup with no certs") { - nonebucket.backup("/etc/passwd") - } - assert_raise(Puppet::NetworkClientError, - "Client was allowed to call backup with untrusted certs") { - certbucket.backup("/etc/passwd") - } - end - - # disabled because the server needs to have its certs in place - # in order to start at all - # i don't think this test makes much sense anyway - def disabled_test_sslInitWithNonsigningLocalServer - Puppet[:autosign] = false - Puppet[:ssldir] = "/tmp/puppetclientcertests" - @@tmpfiles.push Puppet[:ssldir] - - file = File.join($puppetbase, "examples", "code", "head") - - server = nil - port = 8086 - assert_nothing_raised { - server = Puppet::Server.new( - :Port => port, - :Handlers => { - :CA => {}, # so that certs autogenerate - :Master => { - :File => file, - }, - } - ) - } - - spid = fork { - trap(:INT) { server.shutdown } - server.start - } - - @@tmppids << spid - client = nil - assert_nothing_raised { - client = Puppet::Client.new(:Server => "localhost", :Port => port) - } - certfile = File.join(Puppet[:certdir], [client.fqdn, "pem"].join(".")) - cafile = File.join(Puppet[:certdir], ["ca", "pem"].join(".")) - assert_nil(client.initcerts) - assert(! File.exists?(certfile)) - - ca = nil - assert_nothing_raised { - ca = Puppet::SSLCertificates::CA.new() - } - - - csr = nil - assert_nothing_raised { - csr = ca.getclientcsr(client.fqdn) - } - - assert(csr) - - cert = nil - assert_nothing_raised { - cert, cacert = ca.sign(csr) - File.open(certfile, "w") { |f| f.print cert.to_pem } - File.open(cafile, "w") { |f| f.print cacert.to_pem } - } - - # this time it should get the cert correctly - assert_nothing_raised { - client.initcerts - } - - # this isn't a very good test, since i just wrote the file out - assert(File.exists?(certfile)) - end -end diff --git a/test/executables/puppetbin.rb b/test/executables/puppetbin.rb new file mode 100755 index 000000000..4a3eb7946 --- /dev/null +++ b/test/executables/puppetbin.rb @@ -0,0 +1,46 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +# $ID: $ + +require 'puppet' +require 'puppet/server' +require 'puppet/sslcertificates' +require 'test/unit' +require 'puppettest.rb' + +# add the bin directory to our search path +ENV["PATH"] += ":" + File.join($puppetbase, "bin") + +# and then the library directories +libdirs = $:.find_all { |dir| + dir =~ /puppet/ or dir =~ /\.\./ +} +ENV["RUBYLIB"] = libdirs.join(":") + +class TestPuppetBin < Test::Unit::TestCase + include ServerTest + def test_version + output = nil + assert_nothing_raised { + output = %x{puppet --version}.chomp + } + assert(output == Puppet.version) + end + + def test_execution + file = mktestmanifest() + @@tmpfiles << "/tmp/puppetbintesting" + + output = nil + assert_nothing_raised { + system("puppet --logdest /dev/null %s" % file) + } + assert($? == 0, "Puppet exited with code %s" % $?.to_i) + + assert(FileTest.exists?(@createdfile), "Failed to create config'ed file") + end +end diff --git a/test/executables/puppetca.rb b/test/executables/puppetca.rb new file mode 100755 index 000000000..2fed58557 --- /dev/null +++ b/test/executables/puppetca.rb @@ -0,0 +1,79 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/server' +require 'puppet/sslcertificates' +require 'test/unit' +require 'puppettest.rb' + +# $Id$ + +# ok, we have to add the bin directory to our search path +ENV["PATH"] += ":" + File.join($puppetbase, "bin") + +# and then the library directories +libdirs = $:.find_all { |dir| + dir =~ /puppet/ or dir =~ /\.\./ +} +ENV["RUBYLIB"] = libdirs.join(":") + +class TestPuppetCA < Test::Unit::TestCase + include ServerTest + def mkcert(hostname) + cert = nil + assert_nothing_raised { + cert = Puppet::SSLCertificates::Certificate.new( + :name => hostname + ) + cert.mkcsr + } + + return cert + end + + def test_signing + ca = nil + Puppet[:ssldir] = "/tmp/puppetcatest" + @@tmpfiles << Puppet[:ssldir] + Puppet[:autosign] = false + assert_nothing_raised { + ca = Puppet::Server::CA.new() + } + #Puppet.warning "SSLDir is %s" % Puppet[:ssldir] + #system("find %s" % Puppet[:ssldir]) + + cert = mkcert("host.test.com") + resp = nil + assert_nothing_raised { + # We need to use a fake name so it doesn't think the cert is from + # itself. + resp = ca.getcert(cert.csr.to_pem, "fakename", "127.0.0.1") + } + assert_equal(["",""], resp) + #Puppet.warning "SSLDir is %s" % Puppet[:ssldir] + #system("find %s" % Puppet[:ssldir]) + + output = nil + assert_nothing_raised { + output = %x{puppetca --list --ssldir=#{Puppet[:ssldir]} 2>&1}.chomp.split("\n").reject { |line| line =~ /warning:/ } # stupid ssl.rb + } + #Puppet.warning "SSLDir is %s" % Puppet[:ssldir] + #system("find %s" % Puppet[:ssldir]) + assert_equal($?,0) + assert_equal(%w{host.test.com}, output) + assert_nothing_raised { + output = %x{puppetca --sign -a --ssldir=#{Puppet[:ssldir]}}.chomp.split("\n") + } + assert_equal($?,0) + assert_equal([], output) + assert_nothing_raised { + output = %x{puppetca --list --ssldir=#{Puppet[:ssldir]}}.chomp.split("\n") + } + assert_equal($?,0) + assert_equal([], output) + end +end diff --git a/test/executables/puppetd.rb b/test/executables/puppetd.rb new file mode 100755 index 000000000..72cf1f031 --- /dev/null +++ b/test/executables/puppetd.rb @@ -0,0 +1,70 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/server' +require 'test/unit' +require 'puppettest.rb' +require 'socket' +require 'facter' + +# $Id$ + +# ok, we have to add the bin directory to our search path +ENV["PATH"] += ":" + File.join($puppetbase, "bin") + +# and then the library directories +libdirs = $:.find_all { |dir| + dir =~ /puppet/ or dir =~ /\.\./ +} +ENV["RUBYLIB"] = libdirs.join(":") + +class TestPuppetDExe < Test::Unit::TestCase + include ExeTest + def test_normalstart + # start the master + file = startmasterd + + # create the client + client = Puppet::Client.new(:Server => "localhost", :Port => @@port) + + # make a new fqdn + fqdn = client.fqdn.sub(/^\w+\./, "testing.") + + cmd = "puppetd" + cmd += " --verbose" + #cmd += " --fqdn %s" % fqdn + cmd += " --port %s" % @@port + cmd += " --ssldir %s" % Puppet[:ssldir] + cmd += " --server localhost" + + # and verify our daemon runs + assert_nothing_raised { + output = %x{#{cmd}}.chomp + puts output + } + sleep 1 + assert($? == 0, "Puppetd exited with code %s" % $?) + + assert(FileTest.exists?(@createdfile), + "Failed to create config'ed file") + + # now verify that --noop works + File.unlink(@createdfile) + + cmd += " --noop" + assert_nothing_raised { + output = %x{#{cmd}}.chomp + } + sleep 1 + assert($? == 0, "Puppetd exited with code %s" % $?) + + assert(! FileTest.exists?(@createdfile), + "Noop created config'ed file") + + stopmasterd + end +end diff --git a/test/executables/puppetmasterd.rb b/test/executables/puppetmasterd.rb new file mode 100755 index 000000000..7051f02a7 --- /dev/null +++ b/test/executables/puppetmasterd.rb @@ -0,0 +1,148 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/server' +require 'puppet/daemon' +require 'test/unit' +require 'puppettest.rb' +require 'socket' +require 'facter' + +# $Id$ + +class TestPuppetMasterD < Test::Unit::TestCase + include ExeTest + def getcerts + include Puppet::Daemon + if self.readcerts + return [@cert, @key, @cacert, @cacertfile] + else + raise "Couldn't read certs" + end + end + + # start the daemon and verify it responds and such + def test_normalstart + startmasterd + + assert_nothing_raised { + socket = TCPSocket.new("127.0.0.1", @@port) + socket.close + } + + client = nil + assert_nothing_raised() { + client = Puppet::Client::StatusClient.new( + :Server => "localhost", + :Port => @@port + ) + } + + # set our client up to auto-sign + assert(Puppet[:autosign] =~ /^#{File::SEPARATOR}/, + "Autosign is set to %s, not a file" % Puppet[:autosign]) + + FileUtils.mkdir_p(File.dirname(Puppet[:autosign])) + File.open(Puppet[:autosign], "w") { |f| + f.puts client.fqdn + } + + retval = nil + + # init the client certs + assert_nothing_raised() { + client.initcerts + } + + # call status + assert_nothing_raised() { + retval = client.status + } + assert_equal(1, retval, "Status.status return value was %s" % retval) + + # this client shoulduse the same certs + assert_nothing_raised() { + client = Puppet::Client::MasterClient.new( + :Server => "localhost", + :Port => @@port + ) + } + assert_nothing_raised() { + #Puppet.notice "calling status" + #retval = client.call("status.status", "") + retval = client.getconfig + } + + objects = nil + assert_instance_of(Puppet::TransBucket, retval, + "Retrieved non-transportable object") + stopmasterd + end + + # verify that we can run puppetmasterd in parse-only mode + def test_parseonly + startmasterd("--parseonly") + sleep(1) + + pid = nil + ps = Facter["ps"].value || "ps -ef" + %x{#{ps}}.chomp.split(/\n/).each { |line| + if line =~ /puppetmasterd --manifest/ + ary = line.split(" ") + pid = ary[1].to_i + end + } + + assert($? == 0, "Puppetmasterd ended with non-zero exit status") + + assert_nil(pid, "Puppetmasterd is still running after parseonly") + end + + def disabled_test_sslconnection + #file = File.join($puppetbase, "examples", "code", "head") + #startmasterd("--manifest #{file}") + + #assert_nothing_raised { + # socket = TCPSocket.new("127.0.0.1", Puppet[:masterport]) + # socket.close + #} + + client = nil + cert, key, cacert, cacertfile = getcerts() + + assert_nothing_raised() { + client = Net::HTTP.new("localhost", Puppet[:masterport]) + client.cert = cert + client.key = key + client.ca_file = cacertfile + client.use_ssl = true + client.start_immediately = true + } + retval = nil + + assert_nothing_raised() { + retval = client.nothing + } + assert_equal(1, retval, "return value was %s" % retval) + facts = {} + Facter.each { |p,v| + facts[p] = v + } + textfacts = CGI.escape(Marshal::dump(facts)) + assert_nothing_raised() { + #Puppet.notice "calling status" + #retval = client.call("status.status", "") + retval = client.call("puppetmaster.getconfig", textfacts) + } + + objects = nil + assert_nothing_raised { + Marshal::load(CGI.unescape(retval)) + } + #stopmasterd + end +end diff --git a/test/executables/tc_puppetbin.rb b/test/executables/tc_puppetbin.rb deleted file mode 100755 index 4a3eb7946..000000000 --- a/test/executables/tc_puppetbin.rb +++ /dev/null @@ -1,46 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -# $ID: $ - -require 'puppet' -require 'puppet/server' -require 'puppet/sslcertificates' -require 'test/unit' -require 'puppettest.rb' - -# add the bin directory to our search path -ENV["PATH"] += ":" + File.join($puppetbase, "bin") - -# and then the library directories -libdirs = $:.find_all { |dir| - dir =~ /puppet/ or dir =~ /\.\./ -} -ENV["RUBYLIB"] = libdirs.join(":") - -class TestPuppetBin < Test::Unit::TestCase - include ServerTest - def test_version - output = nil - assert_nothing_raised { - output = %x{puppet --version}.chomp - } - assert(output == Puppet.version) - end - - def test_execution - file = mktestmanifest() - @@tmpfiles << "/tmp/puppetbintesting" - - output = nil - assert_nothing_raised { - system("puppet --logdest /dev/null %s" % file) - } - assert($? == 0, "Puppet exited with code %s" % $?.to_i) - - assert(FileTest.exists?(@createdfile), "Failed to create config'ed file") - end -end diff --git a/test/executables/tc_puppetca.rb b/test/executables/tc_puppetca.rb deleted file mode 100755 index 2fed58557..000000000 --- a/test/executables/tc_puppetca.rb +++ /dev/null @@ -1,79 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/server' -require 'puppet/sslcertificates' -require 'test/unit' -require 'puppettest.rb' - -# $Id$ - -# ok, we have to add the bin directory to our search path -ENV["PATH"] += ":" + File.join($puppetbase, "bin") - -# and then the library directories -libdirs = $:.find_all { |dir| - dir =~ /puppet/ or dir =~ /\.\./ -} -ENV["RUBYLIB"] = libdirs.join(":") - -class TestPuppetCA < Test::Unit::TestCase - include ServerTest - def mkcert(hostname) - cert = nil - assert_nothing_raised { - cert = Puppet::SSLCertificates::Certificate.new( - :name => hostname - ) - cert.mkcsr - } - - return cert - end - - def test_signing - ca = nil - Puppet[:ssldir] = "/tmp/puppetcatest" - @@tmpfiles << Puppet[:ssldir] - Puppet[:autosign] = false - assert_nothing_raised { - ca = Puppet::Server::CA.new() - } - #Puppet.warning "SSLDir is %s" % Puppet[:ssldir] - #system("find %s" % Puppet[:ssldir]) - - cert = mkcert("host.test.com") - resp = nil - assert_nothing_raised { - # We need to use a fake name so it doesn't think the cert is from - # itself. - resp = ca.getcert(cert.csr.to_pem, "fakename", "127.0.0.1") - } - assert_equal(["",""], resp) - #Puppet.warning "SSLDir is %s" % Puppet[:ssldir] - #system("find %s" % Puppet[:ssldir]) - - output = nil - assert_nothing_raised { - output = %x{puppetca --list --ssldir=#{Puppet[:ssldir]} 2>&1}.chomp.split("\n").reject { |line| line =~ /warning:/ } # stupid ssl.rb - } - #Puppet.warning "SSLDir is %s" % Puppet[:ssldir] - #system("find %s" % Puppet[:ssldir]) - assert_equal($?,0) - assert_equal(%w{host.test.com}, output) - assert_nothing_raised { - output = %x{puppetca --sign -a --ssldir=#{Puppet[:ssldir]}}.chomp.split("\n") - } - assert_equal($?,0) - assert_equal([], output) - assert_nothing_raised { - output = %x{puppetca --list --ssldir=#{Puppet[:ssldir]}}.chomp.split("\n") - } - assert_equal($?,0) - assert_equal([], output) - end -end diff --git a/test/executables/tc_puppetd.rb b/test/executables/tc_puppetd.rb deleted file mode 100755 index 72cf1f031..000000000 --- a/test/executables/tc_puppetd.rb +++ /dev/null @@ -1,70 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/server' -require 'test/unit' -require 'puppettest.rb' -require 'socket' -require 'facter' - -# $Id$ - -# ok, we have to add the bin directory to our search path -ENV["PATH"] += ":" + File.join($puppetbase, "bin") - -# and then the library directories -libdirs = $:.find_all { |dir| - dir =~ /puppet/ or dir =~ /\.\./ -} -ENV["RUBYLIB"] = libdirs.join(":") - -class TestPuppetDExe < Test::Unit::TestCase - include ExeTest - def test_normalstart - # start the master - file = startmasterd - - # create the client - client = Puppet::Client.new(:Server => "localhost", :Port => @@port) - - # make a new fqdn - fqdn = client.fqdn.sub(/^\w+\./, "testing.") - - cmd = "puppetd" - cmd += " --verbose" - #cmd += " --fqdn %s" % fqdn - cmd += " --port %s" % @@port - cmd += " --ssldir %s" % Puppet[:ssldir] - cmd += " --server localhost" - - # and verify our daemon runs - assert_nothing_raised { - output = %x{#{cmd}}.chomp - puts output - } - sleep 1 - assert($? == 0, "Puppetd exited with code %s" % $?) - - assert(FileTest.exists?(@createdfile), - "Failed to create config'ed file") - - # now verify that --noop works - File.unlink(@createdfile) - - cmd += " --noop" - assert_nothing_raised { - output = %x{#{cmd}}.chomp - } - sleep 1 - assert($? == 0, "Puppetd exited with code %s" % $?) - - assert(! FileTest.exists?(@createdfile), - "Noop created config'ed file") - - stopmasterd - end -end diff --git a/test/executables/tc_puppetmasterd.rb b/test/executables/tc_puppetmasterd.rb deleted file mode 100755 index 7051f02a7..000000000 --- a/test/executables/tc_puppetmasterd.rb +++ /dev/null @@ -1,148 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/server' -require 'puppet/daemon' -require 'test/unit' -require 'puppettest.rb' -require 'socket' -require 'facter' - -# $Id$ - -class TestPuppetMasterD < Test::Unit::TestCase - include ExeTest - def getcerts - include Puppet::Daemon - if self.readcerts - return [@cert, @key, @cacert, @cacertfile] - else - raise "Couldn't read certs" - end - end - - # start the daemon and verify it responds and such - def test_normalstart - startmasterd - - assert_nothing_raised { - socket = TCPSocket.new("127.0.0.1", @@port) - socket.close - } - - client = nil - assert_nothing_raised() { - client = Puppet::Client::StatusClient.new( - :Server => "localhost", - :Port => @@port - ) - } - - # set our client up to auto-sign - assert(Puppet[:autosign] =~ /^#{File::SEPARATOR}/, - "Autosign is set to %s, not a file" % Puppet[:autosign]) - - FileUtils.mkdir_p(File.dirname(Puppet[:autosign])) - File.open(Puppet[:autosign], "w") { |f| - f.puts client.fqdn - } - - retval = nil - - # init the client certs - assert_nothing_raised() { - client.initcerts - } - - # call status - assert_nothing_raised() { - retval = client.status - } - assert_equal(1, retval, "Status.status return value was %s" % retval) - - # this client shoulduse the same certs - assert_nothing_raised() { - client = Puppet::Client::MasterClient.new( - :Server => "localhost", - :Port => @@port - ) - } - assert_nothing_raised() { - #Puppet.notice "calling status" - #retval = client.call("status.status", "") - retval = client.getconfig - } - - objects = nil - assert_instance_of(Puppet::TransBucket, retval, - "Retrieved non-transportable object") - stopmasterd - end - - # verify that we can run puppetmasterd in parse-only mode - def test_parseonly - startmasterd("--parseonly") - sleep(1) - - pid = nil - ps = Facter["ps"].value || "ps -ef" - %x{#{ps}}.chomp.split(/\n/).each { |line| - if line =~ /puppetmasterd --manifest/ - ary = line.split(" ") - pid = ary[1].to_i - end - } - - assert($? == 0, "Puppetmasterd ended with non-zero exit status") - - assert_nil(pid, "Puppetmasterd is still running after parseonly") - end - - def disabled_test_sslconnection - #file = File.join($puppetbase, "examples", "code", "head") - #startmasterd("--manifest #{file}") - - #assert_nothing_raised { - # socket = TCPSocket.new("127.0.0.1", Puppet[:masterport]) - # socket.close - #} - - client = nil - cert, key, cacert, cacertfile = getcerts() - - assert_nothing_raised() { - client = Net::HTTP.new("localhost", Puppet[:masterport]) - client.cert = cert - client.key = key - client.ca_file = cacertfile - client.use_ssl = true - client.start_immediately = true - } - retval = nil - - assert_nothing_raised() { - retval = client.nothing - } - assert_equal(1, retval, "return value was %s" % retval) - facts = {} - Facter.each { |p,v| - facts[p] = v - } - textfacts = CGI.escape(Marshal::dump(facts)) - assert_nothing_raised() { - #Puppet.notice "calling status" - #retval = client.call("status.status", "") - retval = client.call("puppetmaster.getconfig", textfacts) - } - - objects = nil - assert_nothing_raised { - Marshal::load(CGI.unescape(retval)) - } - #stopmasterd - end -end diff --git a/test/language/ast.rb b/test/language/ast.rb new file mode 100755 index 000000000..d78ce382c --- /dev/null +++ b/test/language/ast.rb @@ -0,0 +1,500 @@ +#!/usr/bin/ruby + +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/parser/interpreter' +require 'puppet/parser/parser' +require 'puppet/client' +require 'test/unit' +require 'puppettest' + +class TestAST < Test::Unit::TestCase + include TestPuppet + AST = Puppet::Parser::AST + + def astarray + AST::ASTArray.new( + :children => [] + ) + end + + def classobj(name, args = {}) + unless args.include?(:name) + args[:name] = nameobj(name) + end + unless args.include?(:code) + args[:code] = AST::ASTArray.new( + :children => [ + varobj("%svar" % name, "%svalue" % name), + fileobj("/%s" % name) + ] + ) + end + assert_nothing_raised("Could not create class %s" % name) { + return AST::ClassDef.new(args) + } + end + + def compobj(name, args = {}) + args[:name] = nameobj(name) + args[:code] = AST::ASTArray.new( + :children => [ + varobj("%svar" % name, "%svalue" % name), + fileobj("/%s" % name) + ] + ) + assert_nothing_raised("Could not create compdef %s" % name) { + return AST::CompDef.new(args) + } + end + + def fileobj(path, hash = {"owner" => "root"}) + assert_nothing_raised("Could not create file %s" % path) { + return AST::ObjectDef.new( + :name => stringobj(path), + :type => nameobj("file"), + :params => objectinst(hash) + ) + } + end + + def nameobj(name) + assert_nothing_raised("Could not create name %s" % name) { + return AST::Name.new( + :value => name + ) + } + end + + def nodeobj(name) + assert_nothing_raised("Could not create node %s" % name) { + return AST::NodeDef.new( + :names => nameobj(name), + :code => AST::ASTArray.new( + :children => [ + varobj("%svar" % name, "%svalue" % name), + fileobj("/%s" % name) + ] + ) + ) + } + end + + def objectinst(hash) + assert_nothing_raised("Could not create object instance") { + params = hash.collect { |param, value| + objectparam(param, value) + } + return AST::ObjectInst.new( + :children => params + ) + } + end + + def objectparam(param, value) + assert_nothing_raised("Could not create param %s" % param) { + return AST::ObjectParam.new( + :param => nameobj(param), + :value => stringobj(value) + ) + } + end + + def stringobj(value) + AST::String.new(:value => value) + end + + def varobj(name, value) + assert_nothing_raised("Could not create %s code" % name) { + return AST::VarDef.new( + :name => nameobj(name), + :value => stringobj(value) + ) + } + end + + # Test that classes behave like singletons + def test_classsingleton + parent = child1 = child2 = nil + children = [] + + # create the parent class + children << classobj("parent") + + # Create child class one + children << classobj("child1", :parentclass => nameobj("parent")) + + # Create child class two + children << classobj("child2", :parentclass => nameobj("parent")) + + # Now call the two classes + assert_nothing_raised("Could not add AST nodes for calling") { + children << AST::ObjectDef.new( + :type => nameobj("child1"), + :name => nameobj("yayness"), + :params => astarray() + ) + children << AST::ObjectDef.new( + :type => nameobj("child2"), + :name => nameobj("booness"), + :params => astarray() + ) + } + + top = nil + assert_nothing_raised("Could not create top object") { + top = AST::ASTArray.new( + :children => children + ) + } + + scope = nil + assert_nothing_raised("Could not evaluate") { + scope = Puppet::Parser::Scope.new() + objects = top.evaluate(scope) + } + + assert_equal(1, scope.find_all { |child| + child.lookupobject("/parent", "file") + }.length, "Found incorrect number of '/parent' objects") + end + + # Test that 'setobject' collects all of an object's parameters and stores + # them in one TransObject, rather than many. This is probably a bad idea. + def test_setobject + top = nil + children = [ + fileobj("/etc", "owner" => "root"), + fileobj("/etc", "group" => "root") + ] + assert_nothing_raised("Could not create top object") { + top = AST::ASTArray.new( + :children => children + ) + } + + scope = Puppet::Parser::Scope.new() + assert_nothing_raised("Could not evaluate") { + top.evaluate(scope) + } + + obj = nil + assert_nothing_raised("Could not retrieve file object") { + obj = scope.lookupobject("/etc", "file") + } + + assert(obj, "could not retrieve file object") + + %w{owner group}.each { |param| + assert(obj.include?(param), "Object did not include %s" % param) + } + + end + + # Verify that objects can only have parents of the same type. + def test_validparent + parent = child1 = nil + children = [] + + # create the parent class + children << compobj("parent", :args => AST::ASTArray.new(:children => [])) + + # Create child class one + children << classobj("child1", :parentclass => nameobj("parent")) + + # Now call the two classes + assert_nothing_raised("Could not add AST nodes for calling") { + children << AST::ObjectDef.new( + :type => nameobj("child1"), + :name => nameobj("yayness"), + :params => astarray() + ) + } + + top = nil + assert_nothing_raised("Could not create top object") { + top = AST::ASTArray.new( + :children => children + ) + } + + scope = nil + assert_raise(Puppet::ParseError, "Invalid parent type was allowed") { + scope = Puppet::Parser::Scope.new() + objects = top.evaluate(scope) + } + end + + # Verify that classes are correctly defined in node scopes. + def test_nodeclasslookup + parent = child1 = nil + children = [] + + # create the parent class + children << classobj("parent") + + # Create child class one + children << classobj("child1", :parentclass => nameobj("parent")) + + # Now call the two classes + assert_nothing_raised("Could not add AST nodes for calling") { + children << AST::ObjectDef.new( + :type => nameobj("child1"), + :name => nameobj("yayness"), + :params => astarray() + ) + } + + # create the node + nodename = "mynodename" + node = nil + assert_nothing_raised("Could not create parent object") { + node = AST::NodeDef.new( + :names => nameobj(nodename), + :code => AST::ASTArray.new( + :children => children + ) + ) + } + + # Create the wrapper object + top = nil + assert_nothing_raised("Could not create top object") { + top = AST::ASTArray.new( + :children => [node] + ) + } + + # Evaluate the parse tree + scope = nil + assert_nothing_raised("Could not evaluate node") { + scope = Puppet::Parser::Scope.new() + top.evaluate(scope) + } + + # Verify that, well, nothing really happened, and especially verify + # that the top scope is not a node scope + assert(scope.topscope?, "Scope is not top scope") + assert(! scope.nodescope?, "Scope is mistakenly node scope") + assert(! scope.lookupclass("parent"), "Found parent class in top scope") + + # verify we can find our node + assert(scope.node(nodename), "Could not find node") + + # And verify that we can evaluate it okay + objects = nil + assert_nothing_raised("Could not retrieve node definition") { + objects = scope.evalnode([nodename], {}) + } + assert(objects, "Could not retrieve node definition") + + # Because node scopes are temporary (i.e., they get destroyed after the node's + # config is returned) we should not be able to find the node scope. + nodescope = nil + assert_nothing_raised { + nodescope = scope.find { |child| + child.nodescope? + } + } + + assert_nil(nodescope, "Found nodescope") + + # And now verify again that the top scope cannot find the node's definition + # of the parent class + assert(! scope.lookupclass("parent"), "Found parent class in top scope") + + # Verify that we can evaluate the node twice + assert_nothing_raised("Could not retrieve node definition") { + scope.evalnode([nodename], {}) + } + end + + # Test that you can look a host up using multiple names, e.g., an FQDN and + # a short name + def test_multiplenodenames + children = [] + + # create a short-name node + shortname = "mynodename" + children << nodeobj(shortname) + + # And a long-name node + longname = "node.domain.com" + children << nodeobj(longname) + + # Create the wrapper object + top = nil + assert_nothing_raised("Could not create top object") { + top = AST::ASTArray.new( + :children => children + ) + } + + # Evaluate the parse tree + scope = nil + assert_nothing_raised("Could not evaluate node") { + scope = Puppet::Parser::Scope.new() + top.evaluate(scope) + } + + # Verify we can find the node via a search list + objects = nil + assert_nothing_raised("Could not retrieve short node definition") { + objects = scope.evalnode(["%s.domain.com" % shortname, shortname], {}) + } + assert(objects, "Could not retrieve short node definition") + + # and then look for the long name + assert_nothing_raised("Could not retrieve long node definition") { + objects = scope.evalnode([longname.sub(/\..+/, ''), longname], {}) + } + assert(objects, "Could not retrieve long node definition") + end + + # Test that a node gets the entire configuration except for work meant for + # another node + def test_fullconfigwithnodes + children = [] + + children << fileobj("/testing") + + # create a short-name node + name = "mynodename" + children << nodeobj(name) + + # Create the wrapper object + top = nil + assert_nothing_raised("Could not create top object") { + top = AST::ASTArray.new( + :children => children + ) + } + + # Evaluate the parse tree + scope = nil + assert_nothing_raised("Could not evaluate node") { + scope = Puppet::Parser::Scope.new() + top.evaluate(scope) + } + + # Verify we can find the node via a search list + objects = nil + assert_nothing_raised("Could not retrieve short node definition") { + objects = scope.evalnode([name], {}) + } + assert(objects, "Could not retrieve short node definition") + + # And now verify that we got both the top and node objects + assert_nothing_raised("Could not find top-declared object") { + assert_equal("/testing", objects[0][:name]) + } + + assert_nothing_raised("Could not find node-declared object") { + assert_equal("/%s" % name, objects[1][0][:name]) + } + end + + # Test that we can 'include' variables, not just normal strings. + def test_includevars + children = [] + + # Create our class for testin + klassname = "include" + children << classobj(klassname) + + # Then add our variable assignment + children << varobj("klassvar", klassname) + + # And finally add our calling of the variable + children << AST::ObjectDef.new( + :type => AST::Variable.new(:value => "klassvar"), + :params => astarray + ) + + # And then create our top object + top = AST::ASTArray.new( + :children => children + ) + + # Evaluate the parse tree + scope = nil + assert_nothing_raised("Could not evaluate node") { + scope = Puppet::Parser::Scope.new() + top.evaluate(scope) + } + + # Verify we can find the node via a search list + objects = nil + assert_nothing_raised("Could not retrieve objects") { + objects = scope.to_trans + } + assert(objects, "Could not retrieve objects") + + assert_nothing_raised("Could not find top-declared object") { + assert_equal("/%s" % klassname, objects[0][0][:name]) + } + end + + # Test that node inheritance works correctly + def test_nodeinheritance + children = [] + + # create the base node + name = "basenode" + children << nodeobj(name) + + # and the sub node + name = "subnode" + children << AST::NodeDef.new( + :names => nameobj(name), + :parentclass => nameobj("basenode"), + :code => AST::ASTArray.new( + :children => [ + varobj("%svar" % name, "%svalue" % name), + fileobj("/%s" % name) + ] + ) + ) + #subnode = nodeobj(name) + #subnode.parentclass = "basenode" + + #children << subnode + + # and the top object + top = nil + assert_nothing_raised("Could not create top object") { + top = AST::ASTArray.new( + :children => children + ) + } + + # Evaluate the parse tree + scope = nil + assert_nothing_raised("Could not evaluate node") { + scope = Puppet::Parser::Scope.new() + top.evaluate(scope) + } + + # Verify we can find the node via a search list + objects = nil + assert_nothing_raised("Could not retrieve node definition") { + objects = scope.evalnode([name], {}) + } + assert(objects, "Could not retrieve node definition") + + # And now verify that we got the subnode file + assert_nothing_raised("Could not find basenode file") { + assert_equal("/basenode", objects[0][0][:name]) + } + + # and the parent node file + assert_nothing_raised("Could not find subnode file") { + assert_equal("/subnode", objects[0][1][:name]) + } + end +end diff --git a/test/language/interpreter.rb b/test/language/interpreter.rb new file mode 100755 index 000000000..a37d0d95a --- /dev/null +++ b/test/language/interpreter.rb @@ -0,0 +1,29 @@ +#!/usr/bin/ruby + +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/parser/interpreter' +require 'puppet/parser/parser' +require 'puppet/client' +require 'test/unit' +require 'puppettest' + +class TestInterpreter < Test::Unit::TestCase + include TestPuppet + AST = Puppet::Parser::AST + + def test_simple + file = tempfile() + File.open(file, "w") { |f| + f.puts "file { \"/etc\": owner => root }" + } + assert_nothing_raised { + Puppet::Parser::Interpreter.new(:Manifest => file) + } + end +end diff --git a/test/language/scope.rb b/test/language/scope.rb new file mode 100755 index 000000000..38bcdce5a --- /dev/null +++ b/test/language/scope.rb @@ -0,0 +1,305 @@ +#!/usr/bin/ruby + +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/parser/interpreter' +require 'puppet/parser/parser' +require 'puppet/client' +require 'test/unit' +require 'puppettest' + +# so, what kind of things do we want to test? + +# we don't need to test function, since we're confident in the +# library tests. We do, however, need to test how things are actually +# working in the language. + +# so really, we want to do things like test that our ast is correct +# and test whether we've got things in the right scopes + +class TestScope < Test::Unit::TestCase + include TestPuppet + AST = Puppet::Parser::AST + def to_ary(hash) + hash.collect { |key,value| + [key,value] + } + end + + def test_variables + scope = nil + over = "over" + + scopes = [] + vars = [] + values = {} + ovalues = [] + + 10.times { |index| + # slap some recursion in there + scope = Puppet::Parser::Scope.new(scope) + scopes.push scope + + var = "var%s" % index + value = rand(1000) + ovalue = rand(1000) + + ovalues.push ovalue + + vars.push var + values[var] = value + + # set the variable in the current scope + assert_nothing_raised { + scope.setvar(var,value) + } + + # this should override previous values + assert_nothing_raised { + scope.setvar(over,ovalue) + } + + assert_equal(value,scope.lookupvar(var)) + + #puts "%s vars, %s scopes" % [vars.length,scopes.length] + i = 0 + vars.zip(scopes) { |v,s| + # this recurses all the way up the tree as necessary + val = nil + oval = nil + + # look up the values using the bottom scope + assert_nothing_raised { + val = scope.lookupvar(v) + oval = scope.lookupvar(over) + } + + # verify they're correct + assert_equal(values[v],val) + assert_equal(ovalue,oval) + + # verify that we get the most recent value + assert_equal(ovalue,scope.lookupvar(over)) + + # verify that they aren't available in upper scopes + if parent = s.parent + assert_raise(Puppet::ParseError) { + parent.lookupvar(v) + } + + # and verify that the parent sees its correct value + assert_equal(ovalues[i - 1],parent.lookupvar(over)) + end + i += 1 + } + } + end + + def test_declarative + # set to declarative + top = Puppet::Parser::Scope.new(nil,true) + sub = Puppet::Parser::Scope.new(top) + + assert_nothing_raised { + top.setvar("test","value") + } + assert_raise(Puppet::ParseError) { + top.setvar("test","other") + } + assert_nothing_raised { + sub.setvar("test","later") + } + assert_raise(Puppet::ParseError) { + top.setvar("test","yeehaw") + } + end + + def test_notdeclarative + # set to not declarative + top = Puppet::Parser::Scope.new(nil,false) + sub = Puppet::Parser::Scope.new(top) + + assert_nothing_raised { + top.setvar("test","value") + } + assert_nothing_raised { + top.setvar("test","other") + } + assert_nothing_raised { + sub.setvar("test","later") + } + assert_nothing_raised { + sub.setvar("test","yayness") + } + end + + def test_defaults + scope = nil + over = "over" + + scopes = [] + vars = [] + values = {} + ovalues = [] + + defs = Hash.new { |hash,key| + hash[key] = Hash.new(nil) + } + + prevdefs = Hash.new { |hash,key| + hash[key] = Hash.new(nil) + } + + params = %w{a list of parameters that could be used for defaults} + + types = %w{a set of types that could be used to set defaults} + + 10.times { |index| + scope = Puppet::Parser::Scope.new(scope) + scopes.push scope + + tmptypes = [] + + # randomly create defaults for a random set of types + tnum = rand(5) + tnum.times { |t| + # pick a type + #Puppet.debug "Type length is %s" % types.length + #s = rand(types.length) + #Puppet.debug "Type num is %s" % s + #type = types[s] + #Puppet.debug "Type is %s" % s + type = types[rand(types.length)] + if tmptypes.include?(type) + Puppet.debug "Duplicate type %s" % type + redo + else + tmptypes.push type + end + + Puppet.debug "type is %s" % type + + d = {} + + # randomly assign some parameters + num = rand(4) + num.times { |n| + param = params[rand(params.length)] + if d.include?(param) + Puppet.debug "Duplicate param %s" % param + redo + else + d[param] = rand(1000) + end + } + + # and then add a consistent type + d["always"] = rand(1000) + + d.each { |var,val| + defs[type][var] = val + } + + assert_nothing_raised { + scope.setdefaults(type,to_ary(d)) + } + fdefs = nil + assert_nothing_raised { + fdefs = scope.lookupdefaults(type) + } + + # now, make sure that reassignment fails if we're + # in declarative mode + assert_raise(Puppet::ParseError) { + scope.setdefaults(type,[%w{always funtest}]) + } + + # assert that we have collected the same values + assert_equal(defs[type],fdefs) + + # now assert that our parent still finds the same defaults + # it got last time + if parent = scope.parent + unless prevdefs[type].nil? + assert_equal(prevdefs[type],parent.lookupdefaults(type)) + end + end + d.each { |var,val| + prevdefs[type][var] = val + } + } + } + end + + def test_strinterp + scope = Puppet::Parser::Scope.new(nil) + + assert_nothing_raised { + scope.setvar("test","value") + } + val = nil + assert_nothing_raised { + val = scope.strinterp("string ${test}") + } + assert_equal("string value", val) + + assert_nothing_raised { + val = scope.strinterp("string ${test} ${test} ${test}") + } + assert_equal("string value value value", val) + + assert_nothing_raised { + val = scope.strinterp("string $test ${test} $test") + } + assert_equal("string value value value", val) + end + + # Test some of the host manipulations + def test_zhostlookup + top = Puppet::Parser::Scope.new(nil) + + # Create a deep scope tree, so that we know we're doing a deeply recursive + # search. + mid1 = Puppet::Parser::Scope.new(top) + mid2 = Puppet::Parser::Scope.new(mid1) + mid3 = Puppet::Parser::Scope.new(mid2) + child1 = Puppet::Parser::Scope.new(mid3) + mida = Puppet::Parser::Scope.new(top) + midb = Puppet::Parser::Scope.new(mida) + midc = Puppet::Parser::Scope.new(midb) + child2 = Puppet::Parser::Scope.new(midc) + + # verify we can set a host + assert_nothing_raised("Could not create host") { + child1.setnode("testing", AST::Node.new( + :name => "testing", + :code => :notused + ) + ) + } + + # Verify we cannot redefine it + assert_raise(Puppet::ParseError, "Duplicate host creation succeeded") { + child2.setnode("testing", AST::Node.new( + :name => "testing", + :code => :notused + ) + ) + } + + # Now verify we can find the host again + host = nil + assert_nothing_raised("Host lookup failed") { + hash = top.node("testing") + host = hash[:node] + } + + assert(host, "Could not find host") + assert(host.code == :notused, "Host is not what we stored") + end +end diff --git a/test/language/snippets.rb b/test/language/snippets.rb new file mode 100755 index 000000000..450c656b7 --- /dev/null +++ b/test/language/snippets.rb @@ -0,0 +1,445 @@ +#!/usr/bin/ruby -w + +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/parser/interpreter' +require 'puppet/parser/parser' +require 'puppet/client' +require 'puppet/server' +require 'test/unit' +require 'puppettest' + +# so, what kind of things do we want to test? + +# we don't need to test function, since we're confident in the +# library tests. We do, however, need to test how things are actually +# working in the language. + +# so really, we want to do things like test that our ast is correct +# and test whether we've got things in the right scopes + +class TestSnippets < Test::Unit::TestCase + include TestPuppet + $snippetbase = File.join($puppetbase, "examples", "code", "snippets") + + def file2ast(file) + parser = Puppet::Parser::Parser.new() + parser.file = file + ast = parser.parse + + return ast + end + + def snippet2ast(text) + parser = Puppet::Parser::Parser.new() + parser.string = text + ast = parser.parse + + return ast + end + + def client + args = { + :Listen => false + } + Puppet::Client.new(args) + end + + def ast2scope(ast) + interp = Puppet::Parser::Interpreter.new( + :ast => ast, + :client => client() + ) + scope = Puppet::Parser::Scope.new() + ast.evaluate(scope) + + return scope + end + + def scope2objs(scope) + objs = scope.to_trans + end + + def snippet2scope(snippet) + ast = snippet2ast(snippet) + scope = ast2scope(ast) + end + + def snippet2objs(snippet) + ast = snippet2ast(snippet) + scope = ast2scope(ast) + objs = scope2objs(scope) + end + + def states(type) + states = [] + + type.buildstatehash + type.validstates.each { |name,state| + states.push name + } + + #if states.length == 0 + # raise "%s has no states" % type + #end + + states + end + + def metaparams(type) + mparams = [] + Puppet::Type.eachmetaparam { |param| + mparams.push param + } + + mparams + end + + def params(type) + params = [] + type.parameters.each { |name,state| + params.push name + } + + params + end + + def randthing(thing,type) + list = self.send(thing,type) + list[rand(list.length)] + end + + def randeach(type) + [:states, :metaparams, :params].collect { |thing| + randthing(thing,type) + } + end + + @@snippets = { + true => [ + %{File { mode => 755 }} + ], + } + + def disabled_test_defaults + Puppet::Type.eachtype { |type| + next if type.name == :puppet or type.name == :component + + rands = randeach(type) + + name = type.name.to_s.capitalize + + [0..1, 0..2].each { |range| + params = rands[range] + paramstr = params.collect { |param| + "%s => fake" % param + }.join(", ") + + str = "%s { %s }" % [name, paramstr] + + scope = nil + assert_nothing_raised { + scope = snippet2scope(str) + } + + defaults = nil + assert_nothing_raised { + defaults = scope.lookupdefaults(name) + } + + p defaults + + params.each { |param| + puts "%s => '%s'" % [name,param] + assert(defaults.include?(param)) + } + } + } + end + + # this is here in case no tests get defined; otherwise we get a warning + def test_nothing + end + + def snippet_filecreate(trans) + %w{a b c d}.each { |letter| + file = "/tmp/create%stest" % letter + Puppet.info "testing %s" % file + assert(Puppet::Type::PFile[file], "File %s does not exist" % file) + assert(FileTest.exists?(file)) + @@tmpfiles << file + } + %w{a b}.each { |letter| + file = "/tmp/create%stest" % letter + assert(File.stat(file).mode & 007777 == 0755) + } + + assert_nothing_raised { + trans.rollback + } + %w{a b c d}.each { |letter| + file = "/tmp/create%stest" % letter + assert(! FileTest.exists?(file), "File %s still exists" % file) + } + end + + def snippet_simpledefaults(trans) + file = "/tmp/defaulttest" + @@tmpfiles << file + assert(FileTest.exists?(file), "File %s does not exist" % file) + assert(File.stat(file).mode & 007777 == 0755) + + assert_nothing_raised { + trans.rollback + } + assert(! FileTest.exists?(file)) + end + + def snippet_simpleselector(trans) + files = %w{a b c d}.collect { |letter| + "/tmp/snippetselect%stest" % letter + } + @@tmpfiles += files + + files.each { |file| + assert(FileTest.exists?(file)) + assert(File.stat(file).mode & 007777 == 0755) + @@tmpfiles << file + } + + assert_nothing_raised { + trans.rollback + } + files.each { |file| + assert(! FileTest.exists?(file)) + } + end + + def snippet_classpathtest(trans) + file = "/tmp/classtest" + @@tmpfiles << file + + assert(FileTest.exists?(file)) + + obj = nil + assert_nothing_raised { + obj = Puppet::Type::PFile[file] + } + + assert_nothing_raised { + assert_equal(%w{puppet[top] testing[testing] component[componentname] /tmp/classtest}, obj.path) + #Puppet.err obj.path + } + + assert_nothing_raised { + trans.rollback + } + assert(! FileTest.exists?(file)) + end + + def snippet_argumentdefaults(trans) + file1 = "/tmp/argumenttest1" + file2 = "/tmp/argumenttest2" + @@tmpfiles << file1 + @@tmpfiles << file2 + + assert(FileTest.exists?(file1)) + assert(File.stat(file1).mode & 007777 == 0755) + + assert(FileTest.exists?(file2)) + assert(File.stat(file2).mode & 007777 == 0644) + end + + def snippet_casestatement(trans) + files = %w{ + /tmp/existsfile + /tmp/existsfile2 + /tmp/existsfile3 + } + + files.each { |file| + assert(FileTest.exists?(file), "File %s is missing" % file) + assert(File.stat(file).mode & 007777 == 0755, "File %s is not 755" % file) + } + + assert_nothing_raised { + trans.rollback + } + end + + def snippet_implicititeration(trans) + files = %w{a b c d e f g h}.collect { |l| "/tmp/iteration%stest" % l } + + files.each { |file| + @@tmpfiles << file + assert(FileTest.exists?(file), "File %s does not exist" % file) + assert(File.stat(file).mode & 007777 == 0755, + "File %s is not 755" % file) + + } + + assert_nothing_raised { + trans.rollback + } + + files.each { |file| + assert(! FileTest.exists?(file), "file %s still exists" % file) + } + end + + def snippet_multipleinstances(trans) + files = %w{a b c}.collect { |l| "/tmp/multipleinstances%s" % l } + + files.each { |file| + @@tmpfiles << file + assert(FileTest.exists?(file), "File %s does not exist" % file) + assert(File.stat(file).mode & 007777 == 0755, + "File %s is not 755" % file) + + } + + assert_nothing_raised { + trans.rollback + } + + files.each { |file| + assert(! FileTest.exists?(file), "file %s still exists" % file) + } + end + + def snippet_namevartest(trans) + file = "/tmp/testfiletest" + dir = "/tmp/testdirtest" + @@tmpfiles << file + @@tmpfiles << dir + assert(FileTest.file?(file), "File %s does not exist" % file) + assert(FileTest.directory?(dir), "Directory %s does not exist" % dir) + end + + def snippet_scopetest(trans) + file = "/tmp/scopetest" + @@tmpfiles << file + assert(FileTest.file?(file), "File %s does not exist" % file) + assert(File.stat(file).mode & 007777 == 0755, + "File %s is not 755" % file) + end + + def snippet_failmissingexecpath(trans) + file = "/tmp/exectesting1" + execfile = "/tmp/execdisttesting" + @@tmpfiles << file + @@tmpfiles << execfile + assert(!FileTest.exists?(execfile), "File %s exists" % execfile) + end + + def snippet_selectorvalues(trans) + nums = %w{1 2 3} + files = nums.collect { |n| + "/tmp/selectorvalues%s" % n + } + + files.each { |f| + @@tmpfiles << f + assert(FileTest.exists?(f), "File %s does not exist" % f) + assert(File.stat(f).mode & 007777 == 0755, + "File %s is not 755" % f) + } + end + + def snippet_falsevalues(trans) + file = "/tmp/falsevaluesfalse" + @@tmpfiles << file + assert(FileTest.exists?(file), "File %s does not exist" % file) + end + + def disabled_snippet_classargtest(trans) + [1,2].each { |num| + file = "/tmp/classargtest%s" % num + @@tmpfiles << file + assert(FileTest.file?(file), "File %s does not exist" % file) + assert(File.stat(file).mode & 007777 == 0755, + "File %s is not 755" % file) + } + end + + def snippet_classheirarchy(trans) + [1,2,3].each { |num| + file = "/tmp/classheir%s" % num + @@tmpfiles << file + assert(FileTest.file?(file), "File %s does not exist" % file) + assert(File.stat(file).mode & 007777 == 0755, + "File %s is not 755" % file) + } + end + + def snippet_classincludes(trans) + [1,2,3].each { |num| + file = "/tmp/classincludes%s" % num + @@tmpfiles << file + assert(FileTest.file?(file), "File %s does not exist" % file) + assert(File.stat(file).mode & 007777 == 0755, + "File %s is not 755" % file) + } + end + + def disabled_snippet_dirchmod(trans) + dirs = %w{a b}.collect { |letter| + "/tmp/dirchmodtest%s" % letter + } + + @@tmpfiles << dirs + + dirs.each { |dir| + assert(FileTest.directory?(dir)) + } + + assert(File.stat("/tmp/dirchmodtesta").mode & 007777 == 0755) + assert(File.stat("/tmp/dirchmodtestb").mode & 007777 == 0700) + + assert_nothing_raised { + trans.rollback + } + end + + # XXX this is the answer + Dir.entries($snippetbase).sort.each { |file| + next if file =~ /^\./ + + + mname = "snippet_" + file.sub(/\.pp$/, '') + if self.method_defined?(mname) + #eval("alias %s %s" % [testname, mname]) + testname = ("test_" + mname).intern + self.send(:define_method, testname) { + # first parse the file + server = Puppet::Server::Master.new( + :File => File.join($snippetbase, file), + :Local => true + ) + client = Puppet::Client::MasterClient.new( + :Master => server, + :Cache => false + ) + + assert(client.local) + assert_nothing_raised { + client.getconfig() + } + trans = nil + assert_nothing_raised { + trans = client.apply() + } + assert_nothing_raised { + self.send(mname, trans) + } + } + mname = mname.intern + #eval("alias %s %s" % [testname, mname]) + end + } +end diff --git a/test/language/tc_ast.rb b/test/language/tc_ast.rb deleted file mode 100755 index d78ce382c..000000000 --- a/test/language/tc_ast.rb +++ /dev/null @@ -1,500 +0,0 @@ -#!/usr/bin/ruby - -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/parser/interpreter' -require 'puppet/parser/parser' -require 'puppet/client' -require 'test/unit' -require 'puppettest' - -class TestAST < Test::Unit::TestCase - include TestPuppet - AST = Puppet::Parser::AST - - def astarray - AST::ASTArray.new( - :children => [] - ) - end - - def classobj(name, args = {}) - unless args.include?(:name) - args[:name] = nameobj(name) - end - unless args.include?(:code) - args[:code] = AST::ASTArray.new( - :children => [ - varobj("%svar" % name, "%svalue" % name), - fileobj("/%s" % name) - ] - ) - end - assert_nothing_raised("Could not create class %s" % name) { - return AST::ClassDef.new(args) - } - end - - def compobj(name, args = {}) - args[:name] = nameobj(name) - args[:code] = AST::ASTArray.new( - :children => [ - varobj("%svar" % name, "%svalue" % name), - fileobj("/%s" % name) - ] - ) - assert_nothing_raised("Could not create compdef %s" % name) { - return AST::CompDef.new(args) - } - end - - def fileobj(path, hash = {"owner" => "root"}) - assert_nothing_raised("Could not create file %s" % path) { - return AST::ObjectDef.new( - :name => stringobj(path), - :type => nameobj("file"), - :params => objectinst(hash) - ) - } - end - - def nameobj(name) - assert_nothing_raised("Could not create name %s" % name) { - return AST::Name.new( - :value => name - ) - } - end - - def nodeobj(name) - assert_nothing_raised("Could not create node %s" % name) { - return AST::NodeDef.new( - :names => nameobj(name), - :code => AST::ASTArray.new( - :children => [ - varobj("%svar" % name, "%svalue" % name), - fileobj("/%s" % name) - ] - ) - ) - } - end - - def objectinst(hash) - assert_nothing_raised("Could not create object instance") { - params = hash.collect { |param, value| - objectparam(param, value) - } - return AST::ObjectInst.new( - :children => params - ) - } - end - - def objectparam(param, value) - assert_nothing_raised("Could not create param %s" % param) { - return AST::ObjectParam.new( - :param => nameobj(param), - :value => stringobj(value) - ) - } - end - - def stringobj(value) - AST::String.new(:value => value) - end - - def varobj(name, value) - assert_nothing_raised("Could not create %s code" % name) { - return AST::VarDef.new( - :name => nameobj(name), - :value => stringobj(value) - ) - } - end - - # Test that classes behave like singletons - def test_classsingleton - parent = child1 = child2 = nil - children = [] - - # create the parent class - children << classobj("parent") - - # Create child class one - children << classobj("child1", :parentclass => nameobj("parent")) - - # Create child class two - children << classobj("child2", :parentclass => nameobj("parent")) - - # Now call the two classes - assert_nothing_raised("Could not add AST nodes for calling") { - children << AST::ObjectDef.new( - :type => nameobj("child1"), - :name => nameobj("yayness"), - :params => astarray() - ) - children << AST::ObjectDef.new( - :type => nameobj("child2"), - :name => nameobj("booness"), - :params => astarray() - ) - } - - top = nil - assert_nothing_raised("Could not create top object") { - top = AST::ASTArray.new( - :children => children - ) - } - - scope = nil - assert_nothing_raised("Could not evaluate") { - scope = Puppet::Parser::Scope.new() - objects = top.evaluate(scope) - } - - assert_equal(1, scope.find_all { |child| - child.lookupobject("/parent", "file") - }.length, "Found incorrect number of '/parent' objects") - end - - # Test that 'setobject' collects all of an object's parameters and stores - # them in one TransObject, rather than many. This is probably a bad idea. - def test_setobject - top = nil - children = [ - fileobj("/etc", "owner" => "root"), - fileobj("/etc", "group" => "root") - ] - assert_nothing_raised("Could not create top object") { - top = AST::ASTArray.new( - :children => children - ) - } - - scope = Puppet::Parser::Scope.new() - assert_nothing_raised("Could not evaluate") { - top.evaluate(scope) - } - - obj = nil - assert_nothing_raised("Could not retrieve file object") { - obj = scope.lookupobject("/etc", "file") - } - - assert(obj, "could not retrieve file object") - - %w{owner group}.each { |param| - assert(obj.include?(param), "Object did not include %s" % param) - } - - end - - # Verify that objects can only have parents of the same type. - def test_validparent - parent = child1 = nil - children = [] - - # create the parent class - children << compobj("parent", :args => AST::ASTArray.new(:children => [])) - - # Create child class one - children << classobj("child1", :parentclass => nameobj("parent")) - - # Now call the two classes - assert_nothing_raised("Could not add AST nodes for calling") { - children << AST::ObjectDef.new( - :type => nameobj("child1"), - :name => nameobj("yayness"), - :params => astarray() - ) - } - - top = nil - assert_nothing_raised("Could not create top object") { - top = AST::ASTArray.new( - :children => children - ) - } - - scope = nil - assert_raise(Puppet::ParseError, "Invalid parent type was allowed") { - scope = Puppet::Parser::Scope.new() - objects = top.evaluate(scope) - } - end - - # Verify that classes are correctly defined in node scopes. - def test_nodeclasslookup - parent = child1 = nil - children = [] - - # create the parent class - children << classobj("parent") - - # Create child class one - children << classobj("child1", :parentclass => nameobj("parent")) - - # Now call the two classes - assert_nothing_raised("Could not add AST nodes for calling") { - children << AST::ObjectDef.new( - :type => nameobj("child1"), - :name => nameobj("yayness"), - :params => astarray() - ) - } - - # create the node - nodename = "mynodename" - node = nil - assert_nothing_raised("Could not create parent object") { - node = AST::NodeDef.new( - :names => nameobj(nodename), - :code => AST::ASTArray.new( - :children => children - ) - ) - } - - # Create the wrapper object - top = nil - assert_nothing_raised("Could not create top object") { - top = AST::ASTArray.new( - :children => [node] - ) - } - - # Evaluate the parse tree - scope = nil - assert_nothing_raised("Could not evaluate node") { - scope = Puppet::Parser::Scope.new() - top.evaluate(scope) - } - - # Verify that, well, nothing really happened, and especially verify - # that the top scope is not a node scope - assert(scope.topscope?, "Scope is not top scope") - assert(! scope.nodescope?, "Scope is mistakenly node scope") - assert(! scope.lookupclass("parent"), "Found parent class in top scope") - - # verify we can find our node - assert(scope.node(nodename), "Could not find node") - - # And verify that we can evaluate it okay - objects = nil - assert_nothing_raised("Could not retrieve node definition") { - objects = scope.evalnode([nodename], {}) - } - assert(objects, "Could not retrieve node definition") - - # Because node scopes are temporary (i.e., they get destroyed after the node's - # config is returned) we should not be able to find the node scope. - nodescope = nil - assert_nothing_raised { - nodescope = scope.find { |child| - child.nodescope? - } - } - - assert_nil(nodescope, "Found nodescope") - - # And now verify again that the top scope cannot find the node's definition - # of the parent class - assert(! scope.lookupclass("parent"), "Found parent class in top scope") - - # Verify that we can evaluate the node twice - assert_nothing_raised("Could not retrieve node definition") { - scope.evalnode([nodename], {}) - } - end - - # Test that you can look a host up using multiple names, e.g., an FQDN and - # a short name - def test_multiplenodenames - children = [] - - # create a short-name node - shortname = "mynodename" - children << nodeobj(shortname) - - # And a long-name node - longname = "node.domain.com" - children << nodeobj(longname) - - # Create the wrapper object - top = nil - assert_nothing_raised("Could not create top object") { - top = AST::ASTArray.new( - :children => children - ) - } - - # Evaluate the parse tree - scope = nil - assert_nothing_raised("Could not evaluate node") { - scope = Puppet::Parser::Scope.new() - top.evaluate(scope) - } - - # Verify we can find the node via a search list - objects = nil - assert_nothing_raised("Could not retrieve short node definition") { - objects = scope.evalnode(["%s.domain.com" % shortname, shortname], {}) - } - assert(objects, "Could not retrieve short node definition") - - # and then look for the long name - assert_nothing_raised("Could not retrieve long node definition") { - objects = scope.evalnode([longname.sub(/\..+/, ''), longname], {}) - } - assert(objects, "Could not retrieve long node definition") - end - - # Test that a node gets the entire configuration except for work meant for - # another node - def test_fullconfigwithnodes - children = [] - - children << fileobj("/testing") - - # create a short-name node - name = "mynodename" - children << nodeobj(name) - - # Create the wrapper object - top = nil - assert_nothing_raised("Could not create top object") { - top = AST::ASTArray.new( - :children => children - ) - } - - # Evaluate the parse tree - scope = nil - assert_nothing_raised("Could not evaluate node") { - scope = Puppet::Parser::Scope.new() - top.evaluate(scope) - } - - # Verify we can find the node via a search list - objects = nil - assert_nothing_raised("Could not retrieve short node definition") { - objects = scope.evalnode([name], {}) - } - assert(objects, "Could not retrieve short node definition") - - # And now verify that we got both the top and node objects - assert_nothing_raised("Could not find top-declared object") { - assert_equal("/testing", objects[0][:name]) - } - - assert_nothing_raised("Could not find node-declared object") { - assert_equal("/%s" % name, objects[1][0][:name]) - } - end - - # Test that we can 'include' variables, not just normal strings. - def test_includevars - children = [] - - # Create our class for testin - klassname = "include" - children << classobj(klassname) - - # Then add our variable assignment - children << varobj("klassvar", klassname) - - # And finally add our calling of the variable - children << AST::ObjectDef.new( - :type => AST::Variable.new(:value => "klassvar"), - :params => astarray - ) - - # And then create our top object - top = AST::ASTArray.new( - :children => children - ) - - # Evaluate the parse tree - scope = nil - assert_nothing_raised("Could not evaluate node") { - scope = Puppet::Parser::Scope.new() - top.evaluate(scope) - } - - # Verify we can find the node via a search list - objects = nil - assert_nothing_raised("Could not retrieve objects") { - objects = scope.to_trans - } - assert(objects, "Could not retrieve objects") - - assert_nothing_raised("Could not find top-declared object") { - assert_equal("/%s" % klassname, objects[0][0][:name]) - } - end - - # Test that node inheritance works correctly - def test_nodeinheritance - children = [] - - # create the base node - name = "basenode" - children << nodeobj(name) - - # and the sub node - name = "subnode" - children << AST::NodeDef.new( - :names => nameobj(name), - :parentclass => nameobj("basenode"), - :code => AST::ASTArray.new( - :children => [ - varobj("%svar" % name, "%svalue" % name), - fileobj("/%s" % name) - ] - ) - ) - #subnode = nodeobj(name) - #subnode.parentclass = "basenode" - - #children << subnode - - # and the top object - top = nil - assert_nothing_raised("Could not create top object") { - top = AST::ASTArray.new( - :children => children - ) - } - - # Evaluate the parse tree - scope = nil - assert_nothing_raised("Could not evaluate node") { - scope = Puppet::Parser::Scope.new() - top.evaluate(scope) - } - - # Verify we can find the node via a search list - objects = nil - assert_nothing_raised("Could not retrieve node definition") { - objects = scope.evalnode([name], {}) - } - assert(objects, "Could not retrieve node definition") - - # And now verify that we got the subnode file - assert_nothing_raised("Could not find basenode file") { - assert_equal("/basenode", objects[0][0][:name]) - } - - # and the parent node file - assert_nothing_raised("Could not find subnode file") { - assert_equal("/subnode", objects[0][1][:name]) - } - end -end diff --git a/test/language/tc_interpreter.rb b/test/language/tc_interpreter.rb deleted file mode 100755 index a37d0d95a..000000000 --- a/test/language/tc_interpreter.rb +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/ruby - -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/parser/interpreter' -require 'puppet/parser/parser' -require 'puppet/client' -require 'test/unit' -require 'puppettest' - -class TestInterpreter < Test::Unit::TestCase - include TestPuppet - AST = Puppet::Parser::AST - - def test_simple - file = tempfile() - File.open(file, "w") { |f| - f.puts "file { \"/etc\": owner => root }" - } - assert_nothing_raised { - Puppet::Parser::Interpreter.new(:Manifest => file) - } - end -end diff --git a/test/language/tc_scope.rb b/test/language/tc_scope.rb deleted file mode 100755 index 38bcdce5a..000000000 --- a/test/language/tc_scope.rb +++ /dev/null @@ -1,305 +0,0 @@ -#!/usr/bin/ruby - -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/parser/interpreter' -require 'puppet/parser/parser' -require 'puppet/client' -require 'test/unit' -require 'puppettest' - -# so, what kind of things do we want to test? - -# we don't need to test function, since we're confident in the -# library tests. We do, however, need to test how things are actually -# working in the language. - -# so really, we want to do things like test that our ast is correct -# and test whether we've got things in the right scopes - -class TestScope < Test::Unit::TestCase - include TestPuppet - AST = Puppet::Parser::AST - def to_ary(hash) - hash.collect { |key,value| - [key,value] - } - end - - def test_variables - scope = nil - over = "over" - - scopes = [] - vars = [] - values = {} - ovalues = [] - - 10.times { |index| - # slap some recursion in there - scope = Puppet::Parser::Scope.new(scope) - scopes.push scope - - var = "var%s" % index - value = rand(1000) - ovalue = rand(1000) - - ovalues.push ovalue - - vars.push var - values[var] = value - - # set the variable in the current scope - assert_nothing_raised { - scope.setvar(var,value) - } - - # this should override previous values - assert_nothing_raised { - scope.setvar(over,ovalue) - } - - assert_equal(value,scope.lookupvar(var)) - - #puts "%s vars, %s scopes" % [vars.length,scopes.length] - i = 0 - vars.zip(scopes) { |v,s| - # this recurses all the way up the tree as necessary - val = nil - oval = nil - - # look up the values using the bottom scope - assert_nothing_raised { - val = scope.lookupvar(v) - oval = scope.lookupvar(over) - } - - # verify they're correct - assert_equal(values[v],val) - assert_equal(ovalue,oval) - - # verify that we get the most recent value - assert_equal(ovalue,scope.lookupvar(over)) - - # verify that they aren't available in upper scopes - if parent = s.parent - assert_raise(Puppet::ParseError) { - parent.lookupvar(v) - } - - # and verify that the parent sees its correct value - assert_equal(ovalues[i - 1],parent.lookupvar(over)) - end - i += 1 - } - } - end - - def test_declarative - # set to declarative - top = Puppet::Parser::Scope.new(nil,true) - sub = Puppet::Parser::Scope.new(top) - - assert_nothing_raised { - top.setvar("test","value") - } - assert_raise(Puppet::ParseError) { - top.setvar("test","other") - } - assert_nothing_raised { - sub.setvar("test","later") - } - assert_raise(Puppet::ParseError) { - top.setvar("test","yeehaw") - } - end - - def test_notdeclarative - # set to not declarative - top = Puppet::Parser::Scope.new(nil,false) - sub = Puppet::Parser::Scope.new(top) - - assert_nothing_raised { - top.setvar("test","value") - } - assert_nothing_raised { - top.setvar("test","other") - } - assert_nothing_raised { - sub.setvar("test","later") - } - assert_nothing_raised { - sub.setvar("test","yayness") - } - end - - def test_defaults - scope = nil - over = "over" - - scopes = [] - vars = [] - values = {} - ovalues = [] - - defs = Hash.new { |hash,key| - hash[key] = Hash.new(nil) - } - - prevdefs = Hash.new { |hash,key| - hash[key] = Hash.new(nil) - } - - params = %w{a list of parameters that could be used for defaults} - - types = %w{a set of types that could be used to set defaults} - - 10.times { |index| - scope = Puppet::Parser::Scope.new(scope) - scopes.push scope - - tmptypes = [] - - # randomly create defaults for a random set of types - tnum = rand(5) - tnum.times { |t| - # pick a type - #Puppet.debug "Type length is %s" % types.length - #s = rand(types.length) - #Puppet.debug "Type num is %s" % s - #type = types[s] - #Puppet.debug "Type is %s" % s - type = types[rand(types.length)] - if tmptypes.include?(type) - Puppet.debug "Duplicate type %s" % type - redo - else - tmptypes.push type - end - - Puppet.debug "type is %s" % type - - d = {} - - # randomly assign some parameters - num = rand(4) - num.times { |n| - param = params[rand(params.length)] - if d.include?(param) - Puppet.debug "Duplicate param %s" % param - redo - else - d[param] = rand(1000) - end - } - - # and then add a consistent type - d["always"] = rand(1000) - - d.each { |var,val| - defs[type][var] = val - } - - assert_nothing_raised { - scope.setdefaults(type,to_ary(d)) - } - fdefs = nil - assert_nothing_raised { - fdefs = scope.lookupdefaults(type) - } - - # now, make sure that reassignment fails if we're - # in declarative mode - assert_raise(Puppet::ParseError) { - scope.setdefaults(type,[%w{always funtest}]) - } - - # assert that we have collected the same values - assert_equal(defs[type],fdefs) - - # now assert that our parent still finds the same defaults - # it got last time - if parent = scope.parent - unless prevdefs[type].nil? - assert_equal(prevdefs[type],parent.lookupdefaults(type)) - end - end - d.each { |var,val| - prevdefs[type][var] = val - } - } - } - end - - def test_strinterp - scope = Puppet::Parser::Scope.new(nil) - - assert_nothing_raised { - scope.setvar("test","value") - } - val = nil - assert_nothing_raised { - val = scope.strinterp("string ${test}") - } - assert_equal("string value", val) - - assert_nothing_raised { - val = scope.strinterp("string ${test} ${test} ${test}") - } - assert_equal("string value value value", val) - - assert_nothing_raised { - val = scope.strinterp("string $test ${test} $test") - } - assert_equal("string value value value", val) - end - - # Test some of the host manipulations - def test_zhostlookup - top = Puppet::Parser::Scope.new(nil) - - # Create a deep scope tree, so that we know we're doing a deeply recursive - # search. - mid1 = Puppet::Parser::Scope.new(top) - mid2 = Puppet::Parser::Scope.new(mid1) - mid3 = Puppet::Parser::Scope.new(mid2) - child1 = Puppet::Parser::Scope.new(mid3) - mida = Puppet::Parser::Scope.new(top) - midb = Puppet::Parser::Scope.new(mida) - midc = Puppet::Parser::Scope.new(midb) - child2 = Puppet::Parser::Scope.new(midc) - - # verify we can set a host - assert_nothing_raised("Could not create host") { - child1.setnode("testing", AST::Node.new( - :name => "testing", - :code => :notused - ) - ) - } - - # Verify we cannot redefine it - assert_raise(Puppet::ParseError, "Duplicate host creation succeeded") { - child2.setnode("testing", AST::Node.new( - :name => "testing", - :code => :notused - ) - ) - } - - # Now verify we can find the host again - host = nil - assert_nothing_raised("Host lookup failed") { - hash = top.node("testing") - host = hash[:node] - } - - assert(host, "Could not find host") - assert(host.code == :notused, "Host is not what we stored") - end -end diff --git a/test/language/tc_snippets.rb b/test/language/tc_snippets.rb deleted file mode 100755 index 450c656b7..000000000 --- a/test/language/tc_snippets.rb +++ /dev/null @@ -1,445 +0,0 @@ -#!/usr/bin/ruby -w - -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/parser/interpreter' -require 'puppet/parser/parser' -require 'puppet/client' -require 'puppet/server' -require 'test/unit' -require 'puppettest' - -# so, what kind of things do we want to test? - -# we don't need to test function, since we're confident in the -# library tests. We do, however, need to test how things are actually -# working in the language. - -# so really, we want to do things like test that our ast is correct -# and test whether we've got things in the right scopes - -class TestSnippets < Test::Unit::TestCase - include TestPuppet - $snippetbase = File.join($puppetbase, "examples", "code", "snippets") - - def file2ast(file) - parser = Puppet::Parser::Parser.new() - parser.file = file - ast = parser.parse - - return ast - end - - def snippet2ast(text) - parser = Puppet::Parser::Parser.new() - parser.string = text - ast = parser.parse - - return ast - end - - def client - args = { - :Listen => false - } - Puppet::Client.new(args) - end - - def ast2scope(ast) - interp = Puppet::Parser::Interpreter.new( - :ast => ast, - :client => client() - ) - scope = Puppet::Parser::Scope.new() - ast.evaluate(scope) - - return scope - end - - def scope2objs(scope) - objs = scope.to_trans - end - - def snippet2scope(snippet) - ast = snippet2ast(snippet) - scope = ast2scope(ast) - end - - def snippet2objs(snippet) - ast = snippet2ast(snippet) - scope = ast2scope(ast) - objs = scope2objs(scope) - end - - def states(type) - states = [] - - type.buildstatehash - type.validstates.each { |name,state| - states.push name - } - - #if states.length == 0 - # raise "%s has no states" % type - #end - - states - end - - def metaparams(type) - mparams = [] - Puppet::Type.eachmetaparam { |param| - mparams.push param - } - - mparams - end - - def params(type) - params = [] - type.parameters.each { |name,state| - params.push name - } - - params - end - - def randthing(thing,type) - list = self.send(thing,type) - list[rand(list.length)] - end - - def randeach(type) - [:states, :metaparams, :params].collect { |thing| - randthing(thing,type) - } - end - - @@snippets = { - true => [ - %{File { mode => 755 }} - ], - } - - def disabled_test_defaults - Puppet::Type.eachtype { |type| - next if type.name == :puppet or type.name == :component - - rands = randeach(type) - - name = type.name.to_s.capitalize - - [0..1, 0..2].each { |range| - params = rands[range] - paramstr = params.collect { |param| - "%s => fake" % param - }.join(", ") - - str = "%s { %s }" % [name, paramstr] - - scope = nil - assert_nothing_raised { - scope = snippet2scope(str) - } - - defaults = nil - assert_nothing_raised { - defaults = scope.lookupdefaults(name) - } - - p defaults - - params.each { |param| - puts "%s => '%s'" % [name,param] - assert(defaults.include?(param)) - } - } - } - end - - # this is here in case no tests get defined; otherwise we get a warning - def test_nothing - end - - def snippet_filecreate(trans) - %w{a b c d}.each { |letter| - file = "/tmp/create%stest" % letter - Puppet.info "testing %s" % file - assert(Puppet::Type::PFile[file], "File %s does not exist" % file) - assert(FileTest.exists?(file)) - @@tmpfiles << file - } - %w{a b}.each { |letter| - file = "/tmp/create%stest" % letter - assert(File.stat(file).mode & 007777 == 0755) - } - - assert_nothing_raised { - trans.rollback - } - %w{a b c d}.each { |letter| - file = "/tmp/create%stest" % letter - assert(! FileTest.exists?(file), "File %s still exists" % file) - } - end - - def snippet_simpledefaults(trans) - file = "/tmp/defaulttest" - @@tmpfiles << file - assert(FileTest.exists?(file), "File %s does not exist" % file) - assert(File.stat(file).mode & 007777 == 0755) - - assert_nothing_raised { - trans.rollback - } - assert(! FileTest.exists?(file)) - end - - def snippet_simpleselector(trans) - files = %w{a b c d}.collect { |letter| - "/tmp/snippetselect%stest" % letter - } - @@tmpfiles += files - - files.each { |file| - assert(FileTest.exists?(file)) - assert(File.stat(file).mode & 007777 == 0755) - @@tmpfiles << file - } - - assert_nothing_raised { - trans.rollback - } - files.each { |file| - assert(! FileTest.exists?(file)) - } - end - - def snippet_classpathtest(trans) - file = "/tmp/classtest" - @@tmpfiles << file - - assert(FileTest.exists?(file)) - - obj = nil - assert_nothing_raised { - obj = Puppet::Type::PFile[file] - } - - assert_nothing_raised { - assert_equal(%w{puppet[top] testing[testing] component[componentname] /tmp/classtest}, obj.path) - #Puppet.err obj.path - } - - assert_nothing_raised { - trans.rollback - } - assert(! FileTest.exists?(file)) - end - - def snippet_argumentdefaults(trans) - file1 = "/tmp/argumenttest1" - file2 = "/tmp/argumenttest2" - @@tmpfiles << file1 - @@tmpfiles << file2 - - assert(FileTest.exists?(file1)) - assert(File.stat(file1).mode & 007777 == 0755) - - assert(FileTest.exists?(file2)) - assert(File.stat(file2).mode & 007777 == 0644) - end - - def snippet_casestatement(trans) - files = %w{ - /tmp/existsfile - /tmp/existsfile2 - /tmp/existsfile3 - } - - files.each { |file| - assert(FileTest.exists?(file), "File %s is missing" % file) - assert(File.stat(file).mode & 007777 == 0755, "File %s is not 755" % file) - } - - assert_nothing_raised { - trans.rollback - } - end - - def snippet_implicititeration(trans) - files = %w{a b c d e f g h}.collect { |l| "/tmp/iteration%stest" % l } - - files.each { |file| - @@tmpfiles << file - assert(FileTest.exists?(file), "File %s does not exist" % file) - assert(File.stat(file).mode & 007777 == 0755, - "File %s is not 755" % file) - - } - - assert_nothing_raised { - trans.rollback - } - - files.each { |file| - assert(! FileTest.exists?(file), "file %s still exists" % file) - } - end - - def snippet_multipleinstances(trans) - files = %w{a b c}.collect { |l| "/tmp/multipleinstances%s" % l } - - files.each { |file| - @@tmpfiles << file - assert(FileTest.exists?(file), "File %s does not exist" % file) - assert(File.stat(file).mode & 007777 == 0755, - "File %s is not 755" % file) - - } - - assert_nothing_raised { - trans.rollback - } - - files.each { |file| - assert(! FileTest.exists?(file), "file %s still exists" % file) - } - end - - def snippet_namevartest(trans) - file = "/tmp/testfiletest" - dir = "/tmp/testdirtest" - @@tmpfiles << file - @@tmpfiles << dir - assert(FileTest.file?(file), "File %s does not exist" % file) - assert(FileTest.directory?(dir), "Directory %s does not exist" % dir) - end - - def snippet_scopetest(trans) - file = "/tmp/scopetest" - @@tmpfiles << file - assert(FileTest.file?(file), "File %s does not exist" % file) - assert(File.stat(file).mode & 007777 == 0755, - "File %s is not 755" % file) - end - - def snippet_failmissingexecpath(trans) - file = "/tmp/exectesting1" - execfile = "/tmp/execdisttesting" - @@tmpfiles << file - @@tmpfiles << execfile - assert(!FileTest.exists?(execfile), "File %s exists" % execfile) - end - - def snippet_selectorvalues(trans) - nums = %w{1 2 3} - files = nums.collect { |n| - "/tmp/selectorvalues%s" % n - } - - files.each { |f| - @@tmpfiles << f - assert(FileTest.exists?(f), "File %s does not exist" % f) - assert(File.stat(f).mode & 007777 == 0755, - "File %s is not 755" % f) - } - end - - def snippet_falsevalues(trans) - file = "/tmp/falsevaluesfalse" - @@tmpfiles << file - assert(FileTest.exists?(file), "File %s does not exist" % file) - end - - def disabled_snippet_classargtest(trans) - [1,2].each { |num| - file = "/tmp/classargtest%s" % num - @@tmpfiles << file - assert(FileTest.file?(file), "File %s does not exist" % file) - assert(File.stat(file).mode & 007777 == 0755, - "File %s is not 755" % file) - } - end - - def snippet_classheirarchy(trans) - [1,2,3].each { |num| - file = "/tmp/classheir%s" % num - @@tmpfiles << file - assert(FileTest.file?(file), "File %s does not exist" % file) - assert(File.stat(file).mode & 007777 == 0755, - "File %s is not 755" % file) - } - end - - def snippet_classincludes(trans) - [1,2,3].each { |num| - file = "/tmp/classincludes%s" % num - @@tmpfiles << file - assert(FileTest.file?(file), "File %s does not exist" % file) - assert(File.stat(file).mode & 007777 == 0755, - "File %s is not 755" % file) - } - end - - def disabled_snippet_dirchmod(trans) - dirs = %w{a b}.collect { |letter| - "/tmp/dirchmodtest%s" % letter - } - - @@tmpfiles << dirs - - dirs.each { |dir| - assert(FileTest.directory?(dir)) - } - - assert(File.stat("/tmp/dirchmodtesta").mode & 007777 == 0755) - assert(File.stat("/tmp/dirchmodtestb").mode & 007777 == 0700) - - assert_nothing_raised { - trans.rollback - } - end - - # XXX this is the answer - Dir.entries($snippetbase).sort.each { |file| - next if file =~ /^\./ - - - mname = "snippet_" + file.sub(/\.pp$/, '') - if self.method_defined?(mname) - #eval("alias %s %s" % [testname, mname]) - testname = ("test_" + mname).intern - self.send(:define_method, testname) { - # first parse the file - server = Puppet::Server::Master.new( - :File => File.join($snippetbase, file), - :Local => true - ) - client = Puppet::Client::MasterClient.new( - :Master => server, - :Cache => false - ) - - assert(client.local) - assert_nothing_raised { - client.getconfig() - } - trans = nil - assert_nothing_raised { - trans = client.apply() - } - assert_nothing_raised { - self.send(mname, trans) - } - } - mname = mname.intern - #eval("alias %s %s" % [testname, mname]) - end - } -end diff --git a/test/other/events.rb b/test/other/events.rb new file mode 100755 index 000000000..61551983e --- /dev/null +++ b/test/other/events.rb @@ -0,0 +1,111 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +# $Id$ + +class TestEvents < Test::Unit::TestCase + include TestPuppet + def teardown + super + Puppet::Event::Subscription.clear + end + + def test_simplesubscribe + file = Puppet::Type::PFile.create( + :name => "/tmp/eventtestingA", + :create => true + ) + exec = Puppet::Type::Exec.create( + :name => "echo true", + :path => "/usr/bin:/bin", + :refreshonly => true, + :subscribe => [[file.class.name, file.name]] + ) + + @@tmpfiles << "/tmp/eventtestingA" + + comp = newcomp("eventtesting", file, exec) + + trans = assert_events(comp, [:file_created], "events") + + assert_equal(1, trans.triggered?(exec, :refresh)) + end + + def test_simplerequire + file = Puppet::Type::PFile.create( + :name => "/tmp/eventtestingA", + :create => true + ) + exec = Puppet::Type::Exec.create( + :name => "echo true", + :path => "/usr/bin:/bin", + :refreshonly => true, + :require => [[file.class.name, file.name]] + ) + + @@tmpfiles << "/tmp/eventtestingA" + + comp = Puppet::Type::Component.create( + :name => "eventtesting" + ) + comp.push exec + trans = comp.evaluate + events = nil + assert_nothing_raised { + events = trans.evaluate + } + + assert_equal(1, events.length) + + assert_equal(0, trans.triggered?(exec, :refresh)) + end + + def test_zladderrequire + comps = {} + objects = {} + fname = "/tmp/eventtestfuntest" + [:a, :b].each { |l| + case l + when :a + name = "/tmp/eventtesting%s" % l + objects[l] = Puppet::Type::PFile.create( + :name => name, + :create => true + ) + @@tmpfiles << name + when :b + objects[l] = Puppet::Type::Exec.create( + :name => "touch %s" % fname, + :path => "/usr/bin:/bin", + :refreshonly => true + ) + @@tmpfiles << fname + end + + + comps[l] = Puppet::Type::Component.create( + :name => "eventtesting%s" % l + ) + + comps[l].push objects[l] + } + + comps[:b][:subscribe] = [[comps[:a].class.name, comps[:a].name]] + + trans = comps[:a].evaluate + events = nil + assert_nothing_raised { + events = trans.evaluate + } + + assert(FileTest.exists?(fname)) + #assert_equal(events.length, trans.triggered?(objects[:b], :refresh)) + end +end diff --git a/test/other/log.rb b/test/other/log.rb new file mode 100644 index 000000000..f4a39d467 --- /dev/null +++ b/test/other/log.rb @@ -0,0 +1,123 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk/" +end + +require 'puppet/log' +require 'puppet' +require 'test/unit' + +# $Id$ + +class TestLog < Test::Unit::TestCase + @@logfile = File.join(Puppet[:logdir], "puppettest.log") + + def teardown + system("rm -f %s" % @@logfile) + Puppet::Log.destination=(:console) + Puppet[:loglevel] = :notice + end + + def getlevels + levels = nil + assert_nothing_raised() { + levels = Puppet::Log.levels + } + return levels + end + + def mkmsgs(levels) + levels.collect { |level| + assert_nothing_raised() { + Puppet::Log.new( + :level => level, + :source => "Test", + :message => "Unit test for %s" % level + ) + } + } + end + + def test_logfile + Puppet[:debug] = true if __FILE__ == $0 + fact = nil + levels = nil + levels = getlevels + assert_nothing_raised() { + Puppet::Log.destination=(@@logfile) + } + msgs = mkmsgs(levels) + assert(msgs.length == levels.length) + Puppet::Log.flush + count = 0 + assert_nothing_raised() { + File.open(@@logfile) { |of| + count = of.readlines.length + } + } + assert(count == levels.length) + end + + def test_syslog + levels = nil + assert_nothing_raised() { + levels = getlevels.reject { |level| + level == :emerg || level == :crit + } + } + assert_nothing_raised() { + Puppet::Log.destination=("syslog") + } + # there's really no way to verify that we got syslog messages... + msgs = mkmsgs(levels) + assert(msgs.length == levels.length) + end + + def test_consolelog + Puppet[:debug] = true if __FILE__ == $0 + fact = nil + levels = nil + assert_nothing_raised() { + levels = Puppet::Log.levels + } + assert_nothing_raised() { + Puppet::Log.destination=(:console) + } + msgs = mkmsgs(levels) + assert(msgs.length == levels.length) + Puppet::Log.close + end + + def test_levelmethods + assert_nothing_raised() { + Puppet::Log.destination=("/dev/null") + } + getlevels.each { |level| + assert_nothing_raised() { + Puppet.send(level,"Testing for %s" % level) + } + } + end + + def test_output + Puppet[:debug] = false + assert(Puppet.err("This is an error").is_a?(Puppet::Log)) + assert(Puppet.debug("This is debugging").nil?) + Puppet[:debug] = true + assert(Puppet.err("This is an error").is_a?(Puppet::Log)) + assert(Puppet.debug("This is debugging").is_a?(Puppet::Log)) + end + + def test_creatingdirs + curdest = Puppet[:logdest] + + Puppet[:logdest] = "/tmp/logtesting/logfile" + Puppet.info "testing logs" + assert(FileTest.directory?("/tmp/logtesting")) + assert(FileTest.file?("/tmp/logtesting/logfile")) + + system("rm -rf /tmp/logtesting") + Puppet[:logdest] = curdest + end +end diff --git a/test/other/metrics.rb b/test/other/metrics.rb new file mode 100644 index 000000000..dbae3cf54 --- /dev/null +++ b/test/other/metrics.rb @@ -0,0 +1,92 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet/metric' +require 'puppet' +require 'puppet/type' +require 'test/unit' + +$haverrd = true +begin + require 'RRD' +rescue LoadError + $haverrd = false +end + +if $haverrd + class TestMetric < Test::Unit::TestCase + + def gendata + totalmax = 1000 + changemax = 1000 + eventmax = 10 + maxdiff = 10 + + types = [Puppet::Type::PFile, Puppet::Type::Package, Puppet::Type::Service] + 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) + types.each { |type| + name = type.name + typedata[type] = {} + typedata[type][:total] = rand(totalmax) + typedata[type][:managed] = rand(typedata[type][:total]) + typedata[type][:outofsync] = rand(typedata[type][:managed]) + typedata[type][:changed] = rand(typedata[type][:outofsync]) + typedata[type][:totalchanges] = rand(changemax) + } + + events.each { |event| + eventdata[event] = rand(eventmax) + } + + return [typedata,eventdata] + end + + def setup + Puppet[:rrddir] = File.join(Puppet[:puppetvar], "rrdtesting") + Puppet[:rrdgraph] = true + Puppet[:loglevel] = :debug if __FILE__ == $0 + end + + def teardown + system("rm -rf %s" % Puppet[:rrddir]) + end + + def test_fakedata + assert_nothing_raised { Puppet::Metric.init } + time = Time.now.to_i + start = time + 10.times { + assert_nothing_raised { Puppet::Metric.load(gendata) } + assert_nothing_raised { Puppet::Metric.tally } + assert_nothing_raised { Puppet::Metric.store(time) } + assert_nothing_raised { Puppet::Metric.clear } + time += 300 + } + assert_nothing_raised { Puppet::Metric.load(gendata) } + assert_nothing_raised { Puppet::Metric.tally } + assert_nothing_raised { Puppet::Metric.store(time) } + assert_nothing_raised { Puppet::Metric.graph([start,time]) } + + File.open(File.join(Puppet[:rrddir],"index.html"),"w") { |of| + of.puts "" + Puppet::Metric.each { |metric| + of.puts "
" % metric.name + } + } + end + end +else + $stderr.puts "Missing RRD library -- skipping metric tests" +end + +# $Id$ diff --git a/test/other/overrides.rb b/test/other/overrides.rb new file mode 100755 index 000000000..be9ccd2ce --- /dev/null +++ b/test/other/overrides.rb @@ -0,0 +1,115 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +class TestOverrides < Test::Unit::TestCase + include TestPuppet + def mksubdirs(basedir, level) + @@tmpfiles << basedir + dir = basedir.dup + + (level + 1).times { |index| + Dir.mkdir(dir) + path = File.join(dir, "file") + File.open(path, "w") { |f| f.puts "yayness" } + dir = File.join(dir, index.to_s) + } + end + + def test_simpleoverride + basedir = File.join(tmpdir(), "overridetesting") + mksubdirs(basedir, 1) + + baseobj = nil + basefile = File.join(basedir, "file") + assert_nothing_raised("Could not create base obj") { + baseobj = Puppet::Type::PFile.create( + :path => basedir, + :recurse => true, + :mode => "755" + ) + } + + subobj = nil + subdir = File.join(basedir, "0") + subfile = File.join(subdir, "file") + assert_nothing_raised("Could not create sub obj") { + subobj = Puppet::Type::PFile.create( + :path => subdir, + :recurse => true, + :mode => "644" + ) + } + + comp = newcomp("overrides", baseobj, subobj) + assert_nothing_raised("Could not eval component") { + trans = comp.evaluate + trans.evaluate + } + + assert(File.stat(basefile).mode & 007777 == 0755) + assert(File.stat(subfile).mode & 007777 == 0644) + end + + def test_zdeepoverride + basedir = File.join(tmpdir(), "deepoverridetesting") + mksubdirs(basedir, 10) + + baseobj = nil + assert_nothing_raised("Could not create base obj") { + baseobj = Puppet::Type::PFile.create( + :path => basedir, + :recurse => true, + :mode => "755" + ) + } + + children = [] + files = {} + subdir = basedir.dup + mode = nil + 10.times { |index| + next unless index % 3 + subdir = File.join(subdir, index.to_s) + path = File.join(subdir, "file") + if index % 2 + mode = "644" + files[path] = 0644 + else + mode = "750" + files[path] = 0750 + end + + assert_nothing_raised("Could not create sub obj") { + children << Puppet::Type::PFile.create( + :path => subdir, + :recurse => true, + :mode => mode + ) + } + } + + comp = newcomp("overrides", baseobj) + children.each { |child| comp.push child } + + assert_nothing_raised("Could not eval component") { + trans = comp.evaluate + trans.evaluate + } + + files.each { |path, mode| + assert(FileTest.exists?(path), "File %s does not exist" % path) + curmode = File.stat(path).mode & 007777 + assert(curmode == mode, + "File %s was incorrect mode %o instead of %o" % [path, curmode, mode]) + } + end +end + +# $Id$ diff --git a/test/other/parsedfile.rb b/test/other/parsedfile.rb new file mode 100755 index 000000000..e343e5478 --- /dev/null +++ b/test/other/parsedfile.rb @@ -0,0 +1,31 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/parsedfile' +require 'puppettest' +require 'test/unit' + +class TestParsedFile < Test::Unit::TestCase + include TestPuppet + def test_file + file = nil + path = tempfile() + File.open(path, "w") { |f| f.puts "yayness" } + assert_nothing_raised { + file = Puppet::ParsedFile.new(path) + } + + assert(!file.changed?, "File incorrectly returned changed") + + sleep(1) + File.open(path, "w") { |f| f.puts "booness" } + + assert(file.changed?, "File did not catch change") + end +end + +# $Id$ diff --git a/test/other/relationships.rb b/test/other/relationships.rb new file mode 100755 index 000000000..04cbd73dc --- /dev/null +++ b/test/other/relationships.rb @@ -0,0 +1,113 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +class TestRelationships < Test::Unit::TestCase + include TestPuppet + def newfile + assert_nothing_raised() { + return Puppet::Type::PFile.create( + :path => tempfile, + :check => [:mode, :owner, :group] + ) + } + end + + def test_simplerel + file1 = newfile() + file2 = newfile() + assert_nothing_raised { + file1[:require] = [file2.class.name, file2.name] + } + + deps = [] + assert_nothing_raised { + file1.eachdependency { |obj| + deps << obj + } + } + + assert_equal(1, deps.length, "Did not get dependency") + + assert_nothing_raised { + file1.unsubscribe(file2) + } + + deps = [] + assert_nothing_raised { + file1.eachdependency { |obj| + deps << obj + } + } + + assert_equal(0, deps.length, "Still have dependency") + end + + def test_newsub + file1 = newfile() + file2 = newfile() + + sub = nil + assert_nothing_raised("Could not create subscription") { + sub = Puppet::Event::Subscription.new( + :source => file1, + :target => file2, + :event => :ALL_EVENTS, + :callback => :refresh + ) + } + + subs = nil + + assert_nothing_raised { + subs = Puppet::Event::Subscription.subscribers(file1) + } + assert_equal(1, subs.length, "Got incorrect number of subs") + assert_equal(sub.target, subs[0], "Got incorrect sub") + + deps = nil + assert_nothing_raised { + deps = Puppet::Event::Subscription.dependencies(file2) + } + assert_equal(1, deps.length, "Got incorrect number of deps") + assert_equal(sub, deps[0], "Got incorrect dep") + end + + def test_eventmatch + file1 = newfile() + file2 = newfile() + + sub = nil + assert_nothing_raised("Could not create subscription") { + sub = Puppet::Event::Subscription.new( + :source => file1, + :target => file2, + :event => :ALL_EVENTS, + :callback => :refresh + ) + } + + assert(sub.match?(:anything), "ALL_EVENTS did not match") + assert(! sub.match?(:NONE), "ALL_EVENTS matched :NONE") + + sub.event = :file_created + + assert(sub.match?(:file_created), "event did not match") + assert(sub.match?(:ALL_EVENTS), "ALL_EVENTS did not match") + assert(! sub.match?(:NONE), "ALL_EVENTS matched :NONE") + + sub.event = :NONE + + assert(! sub.match?(:file_created), "Invalid match") + assert(! sub.match?(:ALL_EVENTS), "ALL_EVENTS matched") + assert(! sub.match?(:NONE), "matched :NONE") + end +end + +# $Id$ diff --git a/test/other/state.rb b/test/other/state.rb new file mode 100644 index 000000000..bd17d86c3 --- /dev/null +++ b/test/other/state.rb @@ -0,0 +1,106 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'puppettest' +require 'puppet/storage' +require 'test/unit' + +# $Id$ + +class StorageTestingClass +end + +class TestStorage < Test::Unit::TestCase + include TestPuppet + def disabled_setup + Puppet[:loglevel] = :debug if __FILE__ == $0 + Puppet[:checksumfile] = "/var/tmp/puppetteststate" + + @oldconf = Puppet[:puppetconf] + Puppet[:puppetconf] = "/tmp/storagetesting" + @oldvar = Puppet[:puppetvar] + Puppet[:puppetvar] = "/tmp/storagetesting" + + @@tmpfiles << "/tmp/storagetesting" + end + + def teardown + #system("rm -f %s" % Puppet[:checksumfile]) + Puppet::Storage.clear + + #Puppet[:puppetconf] = @oldconf + #Puppet[:puppetvar] = @oldvar + super + end + + def test_simple + state = nil + assert_nothing_raised { + Puppet::Storage.load + } + assert_nothing_raised { + state = Puppet::Storage.state(Puppet::Type) + } + assert(state) + state["/etc/passwd"] = ["md5","9ebebe0c02445c40b9dc6871b64ee416"] + assert_nothing_raised { + Puppet::Storage.store + } + + # clear the memory, so we're sure we're hitting the state file + assert_nothing_raised { + Puppet::Storage.clear + Puppet::Storage.init + } + assert_nothing_raised { + Puppet::Storage.load + } + assert_equal( + ["md5","9ebebe0c02445c40b9dc6871b64ee416"], + Puppet::Storage.state(Puppet::Type)["/etc/passwd"] + ) + end + + def test_instance + file = nil + state = nil + assert_nothing_raised { + file = Puppet::Type::PFile.create( + :path => "/etc/passwd" + ) + } + assert_nothing_raised { + Puppet::Storage.load + } + assert_nothing_raised { + state = Puppet::Storage.state(file) + } + assert(state) + end + + def test_update + state = Puppet::Storage.state(StorageTestingClass) + state["testing"] = "yayness" + Puppet::Storage.store + assert(FileTest.exists?(Puppet[:checksumfile])) + end + + def test_hashstorage + state = Puppet::Storage.state(StorageTestingClass) + hash = { + :yay => "boo", + :rah => "foo" + } + state["testing"] = hash + Puppet::Storage.store + Puppet::Storage.clear + Puppet::Storage.init + Puppet::Storage.load + state = Puppet::Storage.state(StorageTestingClass) + assert_equal(hash, state["testing"]) + end +end diff --git a/test/other/tc_events.rb b/test/other/tc_events.rb deleted file mode 100755 index 61551983e..000000000 --- a/test/other/tc_events.rb +++ /dev/null @@ -1,111 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -# $Id$ - -class TestEvents < Test::Unit::TestCase - include TestPuppet - def teardown - super - Puppet::Event::Subscription.clear - end - - def test_simplesubscribe - file = Puppet::Type::PFile.create( - :name => "/tmp/eventtestingA", - :create => true - ) - exec = Puppet::Type::Exec.create( - :name => "echo true", - :path => "/usr/bin:/bin", - :refreshonly => true, - :subscribe => [[file.class.name, file.name]] - ) - - @@tmpfiles << "/tmp/eventtestingA" - - comp = newcomp("eventtesting", file, exec) - - trans = assert_events(comp, [:file_created], "events") - - assert_equal(1, trans.triggered?(exec, :refresh)) - end - - def test_simplerequire - file = Puppet::Type::PFile.create( - :name => "/tmp/eventtestingA", - :create => true - ) - exec = Puppet::Type::Exec.create( - :name => "echo true", - :path => "/usr/bin:/bin", - :refreshonly => true, - :require => [[file.class.name, file.name]] - ) - - @@tmpfiles << "/tmp/eventtestingA" - - comp = Puppet::Type::Component.create( - :name => "eventtesting" - ) - comp.push exec - trans = comp.evaluate - events = nil - assert_nothing_raised { - events = trans.evaluate - } - - assert_equal(1, events.length) - - assert_equal(0, trans.triggered?(exec, :refresh)) - end - - def test_zladderrequire - comps = {} - objects = {} - fname = "/tmp/eventtestfuntest" - [:a, :b].each { |l| - case l - when :a - name = "/tmp/eventtesting%s" % l - objects[l] = Puppet::Type::PFile.create( - :name => name, - :create => true - ) - @@tmpfiles << name - when :b - objects[l] = Puppet::Type::Exec.create( - :name => "touch %s" % fname, - :path => "/usr/bin:/bin", - :refreshonly => true - ) - @@tmpfiles << fname - end - - - comps[l] = Puppet::Type::Component.create( - :name => "eventtesting%s" % l - ) - - comps[l].push objects[l] - } - - comps[:b][:subscribe] = [[comps[:a].class.name, comps[:a].name]] - - trans = comps[:a].evaluate - events = nil - assert_nothing_raised { - events = trans.evaluate - } - - assert(FileTest.exists?(fname)) - #assert_equal(events.length, trans.triggered?(objects[:b], :refresh)) - end -end diff --git a/test/other/tc_log.rb b/test/other/tc_log.rb deleted file mode 100644 index f4a39d467..000000000 --- a/test/other/tc_log.rb +++ /dev/null @@ -1,123 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk/" -end - -require 'puppet/log' -require 'puppet' -require 'test/unit' - -# $Id$ - -class TestLog < Test::Unit::TestCase - @@logfile = File.join(Puppet[:logdir], "puppettest.log") - - def teardown - system("rm -f %s" % @@logfile) - Puppet::Log.destination=(:console) - Puppet[:loglevel] = :notice - end - - def getlevels - levels = nil - assert_nothing_raised() { - levels = Puppet::Log.levels - } - return levels - end - - def mkmsgs(levels) - levels.collect { |level| - assert_nothing_raised() { - Puppet::Log.new( - :level => level, - :source => "Test", - :message => "Unit test for %s" % level - ) - } - } - end - - def test_logfile - Puppet[:debug] = true if __FILE__ == $0 - fact = nil - levels = nil - levels = getlevels - assert_nothing_raised() { - Puppet::Log.destination=(@@logfile) - } - msgs = mkmsgs(levels) - assert(msgs.length == levels.length) - Puppet::Log.flush - count = 0 - assert_nothing_raised() { - File.open(@@logfile) { |of| - count = of.readlines.length - } - } - assert(count == levels.length) - end - - def test_syslog - levels = nil - assert_nothing_raised() { - levels = getlevels.reject { |level| - level == :emerg || level == :crit - } - } - assert_nothing_raised() { - Puppet::Log.destination=("syslog") - } - # there's really no way to verify that we got syslog messages... - msgs = mkmsgs(levels) - assert(msgs.length == levels.length) - end - - def test_consolelog - Puppet[:debug] = true if __FILE__ == $0 - fact = nil - levels = nil - assert_nothing_raised() { - levels = Puppet::Log.levels - } - assert_nothing_raised() { - Puppet::Log.destination=(:console) - } - msgs = mkmsgs(levels) - assert(msgs.length == levels.length) - Puppet::Log.close - end - - def test_levelmethods - assert_nothing_raised() { - Puppet::Log.destination=("/dev/null") - } - getlevels.each { |level| - assert_nothing_raised() { - Puppet.send(level,"Testing for %s" % level) - } - } - end - - def test_output - Puppet[:debug] = false - assert(Puppet.err("This is an error").is_a?(Puppet::Log)) - assert(Puppet.debug("This is debugging").nil?) - Puppet[:debug] = true - assert(Puppet.err("This is an error").is_a?(Puppet::Log)) - assert(Puppet.debug("This is debugging").is_a?(Puppet::Log)) - end - - def test_creatingdirs - curdest = Puppet[:logdest] - - Puppet[:logdest] = "/tmp/logtesting/logfile" - Puppet.info "testing logs" - assert(FileTest.directory?("/tmp/logtesting")) - assert(FileTest.file?("/tmp/logtesting/logfile")) - - system("rm -rf /tmp/logtesting") - Puppet[:logdest] = curdest - end -end diff --git a/test/other/tc_metrics.rb b/test/other/tc_metrics.rb deleted file mode 100644 index dbae3cf54..000000000 --- a/test/other/tc_metrics.rb +++ /dev/null @@ -1,92 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet/metric' -require 'puppet' -require 'puppet/type' -require 'test/unit' - -$haverrd = true -begin - require 'RRD' -rescue LoadError - $haverrd = false -end - -if $haverrd - class TestMetric < Test::Unit::TestCase - - def gendata - totalmax = 1000 - changemax = 1000 - eventmax = 10 - maxdiff = 10 - - types = [Puppet::Type::PFile, Puppet::Type::Package, Puppet::Type::Service] - 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) - types.each { |type| - name = type.name - typedata[type] = {} - typedata[type][:total] = rand(totalmax) - typedata[type][:managed] = rand(typedata[type][:total]) - typedata[type][:outofsync] = rand(typedata[type][:managed]) - typedata[type][:changed] = rand(typedata[type][:outofsync]) - typedata[type][:totalchanges] = rand(changemax) - } - - events.each { |event| - eventdata[event] = rand(eventmax) - } - - return [typedata,eventdata] - end - - def setup - Puppet[:rrddir] = File.join(Puppet[:puppetvar], "rrdtesting") - Puppet[:rrdgraph] = true - Puppet[:loglevel] = :debug if __FILE__ == $0 - end - - def teardown - system("rm -rf %s" % Puppet[:rrddir]) - end - - def test_fakedata - assert_nothing_raised { Puppet::Metric.init } - time = Time.now.to_i - start = time - 10.times { - assert_nothing_raised { Puppet::Metric.load(gendata) } - assert_nothing_raised { Puppet::Metric.tally } - assert_nothing_raised { Puppet::Metric.store(time) } - assert_nothing_raised { Puppet::Metric.clear } - time += 300 - } - assert_nothing_raised { Puppet::Metric.load(gendata) } - assert_nothing_raised { Puppet::Metric.tally } - assert_nothing_raised { Puppet::Metric.store(time) } - assert_nothing_raised { Puppet::Metric.graph([start,time]) } - - File.open(File.join(Puppet[:rrddir],"index.html"),"w") { |of| - of.puts "" - Puppet::Metric.each { |metric| - of.puts "
" % metric.name - } - } - end - end -else - $stderr.puts "Missing RRD library -- skipping metric tests" -end - -# $Id$ diff --git a/test/other/tc_overrides.rb b/test/other/tc_overrides.rb deleted file mode 100755 index be9ccd2ce..000000000 --- a/test/other/tc_overrides.rb +++ /dev/null @@ -1,115 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -class TestOverrides < Test::Unit::TestCase - include TestPuppet - def mksubdirs(basedir, level) - @@tmpfiles << basedir - dir = basedir.dup - - (level + 1).times { |index| - Dir.mkdir(dir) - path = File.join(dir, "file") - File.open(path, "w") { |f| f.puts "yayness" } - dir = File.join(dir, index.to_s) - } - end - - def test_simpleoverride - basedir = File.join(tmpdir(), "overridetesting") - mksubdirs(basedir, 1) - - baseobj = nil - basefile = File.join(basedir, "file") - assert_nothing_raised("Could not create base obj") { - baseobj = Puppet::Type::PFile.create( - :path => basedir, - :recurse => true, - :mode => "755" - ) - } - - subobj = nil - subdir = File.join(basedir, "0") - subfile = File.join(subdir, "file") - assert_nothing_raised("Could not create sub obj") { - subobj = Puppet::Type::PFile.create( - :path => subdir, - :recurse => true, - :mode => "644" - ) - } - - comp = newcomp("overrides", baseobj, subobj) - assert_nothing_raised("Could not eval component") { - trans = comp.evaluate - trans.evaluate - } - - assert(File.stat(basefile).mode & 007777 == 0755) - assert(File.stat(subfile).mode & 007777 == 0644) - end - - def test_zdeepoverride - basedir = File.join(tmpdir(), "deepoverridetesting") - mksubdirs(basedir, 10) - - baseobj = nil - assert_nothing_raised("Could not create base obj") { - baseobj = Puppet::Type::PFile.create( - :path => basedir, - :recurse => true, - :mode => "755" - ) - } - - children = [] - files = {} - subdir = basedir.dup - mode = nil - 10.times { |index| - next unless index % 3 - subdir = File.join(subdir, index.to_s) - path = File.join(subdir, "file") - if index % 2 - mode = "644" - files[path] = 0644 - else - mode = "750" - files[path] = 0750 - end - - assert_nothing_raised("Could not create sub obj") { - children << Puppet::Type::PFile.create( - :path => subdir, - :recurse => true, - :mode => mode - ) - } - } - - comp = newcomp("overrides", baseobj) - children.each { |child| comp.push child } - - assert_nothing_raised("Could not eval component") { - trans = comp.evaluate - trans.evaluate - } - - files.each { |path, mode| - assert(FileTest.exists?(path), "File %s does not exist" % path) - curmode = File.stat(path).mode & 007777 - assert(curmode == mode, - "File %s was incorrect mode %o instead of %o" % [path, curmode, mode]) - } - end -end - -# $Id$ diff --git a/test/other/tc_parsedfile.rb b/test/other/tc_parsedfile.rb deleted file mode 100755 index e343e5478..000000000 --- a/test/other/tc_parsedfile.rb +++ /dev/null @@ -1,31 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/parsedfile' -require 'puppettest' -require 'test/unit' - -class TestParsedFile < Test::Unit::TestCase - include TestPuppet - def test_file - file = nil - path = tempfile() - File.open(path, "w") { |f| f.puts "yayness" } - assert_nothing_raised { - file = Puppet::ParsedFile.new(path) - } - - assert(!file.changed?, "File incorrectly returned changed") - - sleep(1) - File.open(path, "w") { |f| f.puts "booness" } - - assert(file.changed?, "File did not catch change") - end -end - -# $Id$ diff --git a/test/other/tc_relationships.rb b/test/other/tc_relationships.rb deleted file mode 100755 index 04cbd73dc..000000000 --- a/test/other/tc_relationships.rb +++ /dev/null @@ -1,113 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -class TestRelationships < Test::Unit::TestCase - include TestPuppet - def newfile - assert_nothing_raised() { - return Puppet::Type::PFile.create( - :path => tempfile, - :check => [:mode, :owner, :group] - ) - } - end - - def test_simplerel - file1 = newfile() - file2 = newfile() - assert_nothing_raised { - file1[:require] = [file2.class.name, file2.name] - } - - deps = [] - assert_nothing_raised { - file1.eachdependency { |obj| - deps << obj - } - } - - assert_equal(1, deps.length, "Did not get dependency") - - assert_nothing_raised { - file1.unsubscribe(file2) - } - - deps = [] - assert_nothing_raised { - file1.eachdependency { |obj| - deps << obj - } - } - - assert_equal(0, deps.length, "Still have dependency") - end - - def test_newsub - file1 = newfile() - file2 = newfile() - - sub = nil - assert_nothing_raised("Could not create subscription") { - sub = Puppet::Event::Subscription.new( - :source => file1, - :target => file2, - :event => :ALL_EVENTS, - :callback => :refresh - ) - } - - subs = nil - - assert_nothing_raised { - subs = Puppet::Event::Subscription.subscribers(file1) - } - assert_equal(1, subs.length, "Got incorrect number of subs") - assert_equal(sub.target, subs[0], "Got incorrect sub") - - deps = nil - assert_nothing_raised { - deps = Puppet::Event::Subscription.dependencies(file2) - } - assert_equal(1, deps.length, "Got incorrect number of deps") - assert_equal(sub, deps[0], "Got incorrect dep") - end - - def test_eventmatch - file1 = newfile() - file2 = newfile() - - sub = nil - assert_nothing_raised("Could not create subscription") { - sub = Puppet::Event::Subscription.new( - :source => file1, - :target => file2, - :event => :ALL_EVENTS, - :callback => :refresh - ) - } - - assert(sub.match?(:anything), "ALL_EVENTS did not match") - assert(! sub.match?(:NONE), "ALL_EVENTS matched :NONE") - - sub.event = :file_created - - assert(sub.match?(:file_created), "event did not match") - assert(sub.match?(:ALL_EVENTS), "ALL_EVENTS did not match") - assert(! sub.match?(:NONE), "ALL_EVENTS matched :NONE") - - sub.event = :NONE - - assert(! sub.match?(:file_created), "Invalid match") - assert(! sub.match?(:ALL_EVENTS), "ALL_EVENTS matched") - assert(! sub.match?(:NONE), "matched :NONE") - end -end - -# $Id$ diff --git a/test/other/tc_state.rb b/test/other/tc_state.rb deleted file mode 100644 index bd17d86c3..000000000 --- a/test/other/tc_state.rb +++ /dev/null @@ -1,106 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'puppettest' -require 'puppet/storage' -require 'test/unit' - -# $Id$ - -class StorageTestingClass -end - -class TestStorage < Test::Unit::TestCase - include TestPuppet - def disabled_setup - Puppet[:loglevel] = :debug if __FILE__ == $0 - Puppet[:checksumfile] = "/var/tmp/puppetteststate" - - @oldconf = Puppet[:puppetconf] - Puppet[:puppetconf] = "/tmp/storagetesting" - @oldvar = Puppet[:puppetvar] - Puppet[:puppetvar] = "/tmp/storagetesting" - - @@tmpfiles << "/tmp/storagetesting" - end - - def teardown - #system("rm -f %s" % Puppet[:checksumfile]) - Puppet::Storage.clear - - #Puppet[:puppetconf] = @oldconf - #Puppet[:puppetvar] = @oldvar - super - end - - def test_simple - state = nil - assert_nothing_raised { - Puppet::Storage.load - } - assert_nothing_raised { - state = Puppet::Storage.state(Puppet::Type) - } - assert(state) - state["/etc/passwd"] = ["md5","9ebebe0c02445c40b9dc6871b64ee416"] - assert_nothing_raised { - Puppet::Storage.store - } - - # clear the memory, so we're sure we're hitting the state file - assert_nothing_raised { - Puppet::Storage.clear - Puppet::Storage.init - } - assert_nothing_raised { - Puppet::Storage.load - } - assert_equal( - ["md5","9ebebe0c02445c40b9dc6871b64ee416"], - Puppet::Storage.state(Puppet::Type)["/etc/passwd"] - ) - end - - def test_instance - file = nil - state = nil - assert_nothing_raised { - file = Puppet::Type::PFile.create( - :path => "/etc/passwd" - ) - } - assert_nothing_raised { - Puppet::Storage.load - } - assert_nothing_raised { - state = Puppet::Storage.state(file) - } - assert(state) - end - - def test_update - state = Puppet::Storage.state(StorageTestingClass) - state["testing"] = "yayness" - Puppet::Storage.store - assert(FileTest.exists?(Puppet[:checksumfile])) - end - - def test_hashstorage - state = Puppet::Storage.state(StorageTestingClass) - hash = { - :yay => "boo", - :rah => "foo" - } - state["testing"] = hash - Puppet::Storage.store - Puppet::Storage.clear - Puppet::Storage.init - Puppet::Storage.load - state = Puppet::Storage.state(StorageTestingClass) - assert_equal(hash, state["testing"]) - end -end diff --git a/test/other/tc_transactions.rb b/test/other/tc_transactions.rb deleted file mode 100644 index 338bb6844..000000000 --- a/test/other/tc_transactions.rb +++ /dev/null @@ -1,227 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -# $Id$ - -class TestTransactions < Test::Unit::TestCase - include FileTesting - def ingroup(gid) - require 'etc' - begin - group = Etc.getgrgid(gid) - rescue => detail - puts "Could not retrieve info for group %s: %s" % [gid, detail] - return nil - end - - return @groups.include?(group.name) - end - - def setup - @groups = %x{groups}.chomp.split(/ /) - unless @groups.length > 1 - p @groups - raise "You must be a member of more than one group to test this" - end - super - end - - def teardown - Puppet::Type::Service.each { |serv| - serv[:running] = false - serv.sync - } - print "\n\n" if Puppet[:debug] - super - end - - def newfile(hash = {}) - tmpfile = tempfile() - File.open(tmpfile, "w") { |f| f.puts rand(100) } - - # XXX now, because os x apparently somehow allows me to make a file - # owned by a group i'm not a member of, i have to verify that - # the file i just created is owned by one of my groups - # grrr - unless ingroup(File.stat(tmpfile).gid) - Puppet.info "Somehow created file in non-member group %s; fixing" % - File.stat(tmpfile).gid - - require 'etc' - firstgr = @groups[0] - unless firstgr.is_a?(Integer) - str = Etc.getgrnam(firstgr) - firstgr = str.gid - end - File.chown(nil, firstgr, tmpfile) - end - - @@tmpfiles.push tmpfile - hash[:name] = tmpfile - assert_nothing_raised() { - return Puppet::Type::PFile.create(hash) - } - end - - def newservice - assert_nothing_raised() { - return Puppet::Type::Service.create( - :name => "sleeper", - :type => "init", - :path => File.join($puppetbase,"examples/root/etc/init.d"), - :hasstatus => true, - :check => [:running] - ) - } - end - - def newexec(file) - assert_nothing_raised() { - return Puppet::Type::Exec.create( - :name => "touch %s" % file, - :path => "/bin:/usr/bin:/sbin:/usr/sbin", - :returns => 0 - ) - } - end - - # modify a file and then roll the modifications back - def test_filerollback - transaction = nil - file = newfile() - - states = {} - check = [:group,:mode] - file[:check] = check - - assert_nothing_raised() { - file.retrieve - } - - assert_nothing_raised() { - check.each { |state| - assert(file[state]) - states[state] = file[state] - } - } - - - component = newcomp("file",file) - assert_nothing_raised() { - file[:group] = @groups[1] - file[:mode] = "755" - } - trans = assert_events(component, [:inode_changed, :inode_changed], "file") - - assert_rollback_events(trans, [:inode_changed, :inode_changed], "file") - - assert_nothing_raised() { - file.retrieve - } - states.each { |state,value| - assert_equal( - value,file.is(state), "File %s remained %s" % [state, file.is(state)] - ) - } - end - - # start a service, and then roll the modification back - def test_servicetrans - transaction = nil - service = newservice() - - component = newcomp("service",service) - - assert_nothing_raised() { - service[:running] = 1 - } - trans = assert_events(component, [:service_started], "file") - - assert_rollback_events(trans, [:service_stopped], "file") - end - - # test that services are correctly restarted and that work is done - # in the right order - def test_refreshing - transaction = nil - file = newfile() - execfile = File.join(tmpdir(), "exectestingness") - exec = newexec(execfile) - states = {} - check = [:group,:mode] - file[:check] = check - - @@tmpfiles << execfile - - component = newcomp("both",file,exec) - - # 'subscribe' expects an array of arrays - exec[:subscribe] = [[file.class.name,file.name]] - exec[:refreshonly] = true - - assert_nothing_raised() { - file.retrieve - exec.retrieve - } - - check.each { |state| - states[state] = file[state] - } - assert_nothing_raised() { - file[:mode] = "755" - } - - trans = assert_events(component, - [:inode_changed], "testboth") - - assert(FileTest.exists?(execfile), "Execfile does not exist") - File.unlink(execfile) - assert_nothing_raised() { - file[:group] = @groups[1] - } - - trans = assert_events(component, - [:inode_changed], "testboth") - assert(FileTest.exists?(execfile), "Execfile does not exist") - end - - def test_zrefreshAcrossTwoComponents - transaction = nil - file = newfile() - execfile = File.join(tmpdir(), "exectestingness2") - @@tmpfiles << execfile - exec = newexec(execfile) - states = {} - check = [:group,:mode] - file[:check] = check - - fcomp = newcomp("file",file) - ecomp = newcomp("exec",exec) - - component = newcomp("both",fcomp,ecomp) - - # 'subscribe' expects an array of arrays - #component[:require] = [[file.class.name,file.name]] - ecomp[:subscribe] = [[fcomp.class.name,fcomp.name]] - exec[:refreshonly] = true - - trans = assert_events(component, [], "subscribe1") - - assert_nothing_raised() { - file[:group] = @groups[1] - file[:mode] = "755" - } - - trans = assert_events(component, [:inode_changed, :inode_changed], - "subscribe2") - - end - -end diff --git a/test/other/transactions.rb b/test/other/transactions.rb new file mode 100644 index 000000000..338bb6844 --- /dev/null +++ b/test/other/transactions.rb @@ -0,0 +1,227 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +# $Id$ + +class TestTransactions < Test::Unit::TestCase + include FileTesting + def ingroup(gid) + require 'etc' + begin + group = Etc.getgrgid(gid) + rescue => detail + puts "Could not retrieve info for group %s: %s" % [gid, detail] + return nil + end + + return @groups.include?(group.name) + end + + def setup + @groups = %x{groups}.chomp.split(/ /) + unless @groups.length > 1 + p @groups + raise "You must be a member of more than one group to test this" + end + super + end + + def teardown + Puppet::Type::Service.each { |serv| + serv[:running] = false + serv.sync + } + print "\n\n" if Puppet[:debug] + super + end + + def newfile(hash = {}) + tmpfile = tempfile() + File.open(tmpfile, "w") { |f| f.puts rand(100) } + + # XXX now, because os x apparently somehow allows me to make a file + # owned by a group i'm not a member of, i have to verify that + # the file i just created is owned by one of my groups + # grrr + unless ingroup(File.stat(tmpfile).gid) + Puppet.info "Somehow created file in non-member group %s; fixing" % + File.stat(tmpfile).gid + + require 'etc' + firstgr = @groups[0] + unless firstgr.is_a?(Integer) + str = Etc.getgrnam(firstgr) + firstgr = str.gid + end + File.chown(nil, firstgr, tmpfile) + end + + @@tmpfiles.push tmpfile + hash[:name] = tmpfile + assert_nothing_raised() { + return Puppet::Type::PFile.create(hash) + } + end + + def newservice + assert_nothing_raised() { + return Puppet::Type::Service.create( + :name => "sleeper", + :type => "init", + :path => File.join($puppetbase,"examples/root/etc/init.d"), + :hasstatus => true, + :check => [:running] + ) + } + end + + def newexec(file) + assert_nothing_raised() { + return Puppet::Type::Exec.create( + :name => "touch %s" % file, + :path => "/bin:/usr/bin:/sbin:/usr/sbin", + :returns => 0 + ) + } + end + + # modify a file and then roll the modifications back + def test_filerollback + transaction = nil + file = newfile() + + states = {} + check = [:group,:mode] + file[:check] = check + + assert_nothing_raised() { + file.retrieve + } + + assert_nothing_raised() { + check.each { |state| + assert(file[state]) + states[state] = file[state] + } + } + + + component = newcomp("file",file) + assert_nothing_raised() { + file[:group] = @groups[1] + file[:mode] = "755" + } + trans = assert_events(component, [:inode_changed, :inode_changed], "file") + + assert_rollback_events(trans, [:inode_changed, :inode_changed], "file") + + assert_nothing_raised() { + file.retrieve + } + states.each { |state,value| + assert_equal( + value,file.is(state), "File %s remained %s" % [state, file.is(state)] + ) + } + end + + # start a service, and then roll the modification back + def test_servicetrans + transaction = nil + service = newservice() + + component = newcomp("service",service) + + assert_nothing_raised() { + service[:running] = 1 + } + trans = assert_events(component, [:service_started], "file") + + assert_rollback_events(trans, [:service_stopped], "file") + end + + # test that services are correctly restarted and that work is done + # in the right order + def test_refreshing + transaction = nil + file = newfile() + execfile = File.join(tmpdir(), "exectestingness") + exec = newexec(execfile) + states = {} + check = [:group,:mode] + file[:check] = check + + @@tmpfiles << execfile + + component = newcomp("both",file,exec) + + # 'subscribe' expects an array of arrays + exec[:subscribe] = [[file.class.name,file.name]] + exec[:refreshonly] = true + + assert_nothing_raised() { + file.retrieve + exec.retrieve + } + + check.each { |state| + states[state] = file[state] + } + assert_nothing_raised() { + file[:mode] = "755" + } + + trans = assert_events(component, + [:inode_changed], "testboth") + + assert(FileTest.exists?(execfile), "Execfile does not exist") + File.unlink(execfile) + assert_nothing_raised() { + file[:group] = @groups[1] + } + + trans = assert_events(component, + [:inode_changed], "testboth") + assert(FileTest.exists?(execfile), "Execfile does not exist") + end + + def test_zrefreshAcrossTwoComponents + transaction = nil + file = newfile() + execfile = File.join(tmpdir(), "exectestingness2") + @@tmpfiles << execfile + exec = newexec(execfile) + states = {} + check = [:group,:mode] + file[:check] = check + + fcomp = newcomp("file",file) + ecomp = newcomp("exec",exec) + + component = newcomp("both",fcomp,ecomp) + + # 'subscribe' expects an array of arrays + #component[:require] = [[file.class.name,file.name]] + ecomp[:subscribe] = [[fcomp.class.name,fcomp.name]] + exec[:refreshonly] = true + + trans = assert_events(component, [], "subscribe1") + + assert_nothing_raised() { + file[:group] = @groups[1] + file[:mode] = "755" + } + + trans = assert_events(component, [:inode_changed, :inode_changed], + "subscribe2") + + end + +end diff --git a/test/parser/lexer.rb b/test/parser/lexer.rb new file mode 100644 index 000000000..d37004ef3 --- /dev/null +++ b/test/parser/lexer.rb @@ -0,0 +1,120 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/parser/lexer' +require 'test/unit' +require 'puppettest.rb' + +#%q{service("telnet") = \{ +# port => "23", +# protocol => "tcp", +# name => "telnet", +#\} +#} => [[:NAME, "service"], [:LPAREN, "("], [:DQUOTE, "\""], [:NAME, "telnet"], [:DQUOTE, "\""], [:RPAREN, ")"], [:EQUALS, "="], [:lbrace, "{"], [:NAME, "port"], [:FARROW, "=>"], [:DQUOTE, "\""], [:NAME, "23"], [:DQUOTE, "\""], [:COMMA, ","], [:NAME, "protocol"], [:FARROW, "=>"], [:DQUOTE, "\""], [:NAME, "tcp"], [:DQUOTE, "\""], [:COMMA, ","], [:NAME, "name"], [:FARROW, "=>"], [:DQUOTE, "\""], [:NAME, "telnet"], [:DQUOTE, "\""], [:COMMA, ","], [:RBRACE, "}"]] + +class TestLexer < Test::Unit::TestCase + include TestPuppet + def setup + super + @lexer = Puppet::Parser::Lexer.new() + end + + def test_simple_lex + strings = { +%q{\\} => [[:BACKSLASH,"\\"],[false,false]], +%q{simplest scanner test} => [[:NAME,"simplest"],[:NAME,"scanner"],[:NAME,"test"],[false,false]], +%q{returned scanner test +} => [[:NAME,"returned"],[:NAME,"scanner"],[:NAME,"test"],[false,false]] + } + strings.each { |str,ary| + @lexer.string = str + assert_equal( + ary, + @lexer.fullscan() + ) + } + end + + def test_quoted_strings + strings = { +%q{a simple "scanner" test +} => [[:NAME,"a"],[:NAME,"simple"],[:QTEXT,"scanner"],[:NAME,"test"],[false,false]], +%q{a harder "scanner test" +} => [[:NAME,"a"],[:NAME,"harder"],[:QTEXT,"scanner test"],[false,false]], +%q{a hardest "scanner \"test\"" +} => [[:NAME,"a"],[:NAME,"hardest"],[:QTEXT,'scanner "test"'],[false,false]], +%q{function("call")} => [[:NAME,"function"],[:LPAREN,"("],[:QTEXT,'call'],[:RPAREN,")"],[false,false]] +} + strings.each { |str,array| + @lexer.string = str + assert_equal( + array, + @lexer.fullscan() + ) + } + end + + def test_errors + strings = %w{ + ^ + @ + } + strings.each { |str| + @lexer.string = str + assert_raise(RuntimeError) { + @lexer.fullscan() + } + } + end + + def test_more_error + assert_raise(TypeError) { + @lexer.fullscan() + } + end + + def test_files + textfiles() { |file| + @lexer.file = file + assert_nothing_raised() { + @lexer.fullscan() + } + Puppet::Type.allclear + } + end + + def test_strings + names = %w{this is a bunch of names} + types = %w{Many Different Words A Word} + words = %w{differently Cased words A a} + + names.each { |t| + @lexer.string = t + assert_equal( + [[:NAME,t],[false,false]], + @lexer.fullscan + ) + } + types.each { |t| + @lexer.string = t + assert_equal( + [[:TYPE,t],[false,false]], + @lexer.fullscan + ) + } + end + + def test_emptystring + bit = '$var = ""' + + assert_nothing_raised { + @lexer.string = bit + } + end +end + +# $Id$ diff --git a/test/parser/parser.rb b/test/parser/parser.rb new file mode 100644 index 000000000..16ac0048b --- /dev/null +++ b/test/parser/parser.rb @@ -0,0 +1,180 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/parser/parser' +require 'test/unit' +require 'puppettest' + +class TestParser < Test::Unit::TestCase + include TestPuppet + def setup + super + Puppet[:parseonly] = true + #@lexer = Puppet::Parser::Lexer.new() + @parser = Puppet::Parser::Parser.new() + end + + def test_each_file + textfiles { |file| + Puppet.debug("parsing %s" % file) if __FILE__ == $0 + assert_nothing_raised() { + @parser.file = file + @parser.parse + } + + Puppet::Type.eachtype { |type| + type.each { |obj| + assert(obj.file) + assert(obj.name) + assert(obj.line) + } + } + Puppet::Type.allclear + } + end + + def test_failers + failers { |file| + Puppet.debug("parsing failer %s" % file) if __FILE__ == $0 + assert_raise(Puppet::ParseError) { + @parser.file = file + @parser.parse + } + Puppet::Type.allclear + } + end + + def test_arrayrvalues + parser = Puppet::Parser::Parser.new() + ret = nil + assert_nothing_raised { + parser.string = 'file { "/tmp/testing": mode => [755, 640] }' + } + + assert_nothing_raised { + ret = parser.parse + } + end + + def mkmanifest(file) + name = File.join(tmpdir, "file%s" % rand(100)) + @@tmpfiles << name + + File.open(file, "w") { |f| + f.puts "file { \"%s\": create => true, mode => 755 }\n" % + name + } + end + + def test_importglobbing + basedir = File.join(tmpdir(), "importesting") + @@tmpfiles << basedir + Dir.mkdir(basedir) + + subdir = "subdir" + Dir.mkdir(File.join(basedir, subdir)) + manifest = File.join(basedir, "manifest") + File.open(manifest, "w") { |f| + f.puts "import \"%s/*\"" % subdir + } + + 4.times { |i| + path = File.join(basedir, subdir, "subfile%s" % i) + mkmanifest(path) + } + + assert_nothing_raised("Could not parse multiple files") { + parser = Puppet::Parser::Parser.new() + parser.file = manifest + parser.parse + } + end + + def test_zdefaults + basedir = File.join(tmpdir(), "defaulttesting") + @@tmpfiles << basedir + Dir.mkdir(basedir) + + defs1 = { + "testing" => "value" + } + + defs2 = { + "one" => "two", + "three" => "four", + "five" => false, + "seven" => "eight", + "nine" => true, + "eleven" => "twelve" + } + + mkdef = proc { |hash| + hash.collect { |arg, value| + "%s = %s" % [arg, value] + }.join(", ") + } + manifest = File.join(basedir, "manifest") + File.open(manifest, "w") { |f| + f.puts " + define method(#{mkdef.call(defs1)}, other) { + $variable = $testing + } + + define othermethod(#{mkdef.call(defs2)}, goodness) { + $more = less + } + + method { + other => yayness + } + + othermethod { + goodness => rahness + } +" + } + + ast = nil + assert_nothing_raised("Could not parse multiple files") { + parser = Puppet::Parser::Parser.new() + parser.file = manifest + ast = parser.parse + } + + assert(ast, "Did not receive AST while parsing defaults") + + scope = nil + assert_nothing_raised("Could not evaluate defaults parse tree") { + scope = Puppet::Parser::Scope.new() + objects = scope.evaluate(ast) + } + + method = nil + othermethod = nil + assert_nothing_raised { + method = scope.find { |child| + child.is_a?(Puppet::Parser::Scope) and child.type == "method" + } + defs1.each { |var, value| + curval = method.lookupvar(var) + assert_equal(value, curval, "Did not get default") + } + } + + assert_nothing_raised { + method = scope.find { |child| + child.is_a?(Puppet::Parser::Scope) and child.type == "othermethod" + } + defs2.each { |var, value| + curval = method.lookupvar(var) + assert_equal(value, curval, "Did not get default") + } + } + end +end + +# $Id$ diff --git a/test/parser/tc_lexer.rb b/test/parser/tc_lexer.rb deleted file mode 100644 index d37004ef3..000000000 --- a/test/parser/tc_lexer.rb +++ /dev/null @@ -1,120 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/parser/lexer' -require 'test/unit' -require 'puppettest.rb' - -#%q{service("telnet") = \{ -# port => "23", -# protocol => "tcp", -# name => "telnet", -#\} -#} => [[:NAME, "service"], [:LPAREN, "("], [:DQUOTE, "\""], [:NAME, "telnet"], [:DQUOTE, "\""], [:RPAREN, ")"], [:EQUALS, "="], [:lbrace, "{"], [:NAME, "port"], [:FARROW, "=>"], [:DQUOTE, "\""], [:NAME, "23"], [:DQUOTE, "\""], [:COMMA, ","], [:NAME, "protocol"], [:FARROW, "=>"], [:DQUOTE, "\""], [:NAME, "tcp"], [:DQUOTE, "\""], [:COMMA, ","], [:NAME, "name"], [:FARROW, "=>"], [:DQUOTE, "\""], [:NAME, "telnet"], [:DQUOTE, "\""], [:COMMA, ","], [:RBRACE, "}"]] - -class TestLexer < Test::Unit::TestCase - include TestPuppet - def setup - super - @lexer = Puppet::Parser::Lexer.new() - end - - def test_simple_lex - strings = { -%q{\\} => [[:BACKSLASH,"\\"],[false,false]], -%q{simplest scanner test} => [[:NAME,"simplest"],[:NAME,"scanner"],[:NAME,"test"],[false,false]], -%q{returned scanner test -} => [[:NAME,"returned"],[:NAME,"scanner"],[:NAME,"test"],[false,false]] - } - strings.each { |str,ary| - @lexer.string = str - assert_equal( - ary, - @lexer.fullscan() - ) - } - end - - def test_quoted_strings - strings = { -%q{a simple "scanner" test -} => [[:NAME,"a"],[:NAME,"simple"],[:QTEXT,"scanner"],[:NAME,"test"],[false,false]], -%q{a harder "scanner test" -} => [[:NAME,"a"],[:NAME,"harder"],[:QTEXT,"scanner test"],[false,false]], -%q{a hardest "scanner \"test\"" -} => [[:NAME,"a"],[:NAME,"hardest"],[:QTEXT,'scanner "test"'],[false,false]], -%q{function("call")} => [[:NAME,"function"],[:LPAREN,"("],[:QTEXT,'call'],[:RPAREN,")"],[false,false]] -} - strings.each { |str,array| - @lexer.string = str - assert_equal( - array, - @lexer.fullscan() - ) - } - end - - def test_errors - strings = %w{ - ^ - @ - } - strings.each { |str| - @lexer.string = str - assert_raise(RuntimeError) { - @lexer.fullscan() - } - } - end - - def test_more_error - assert_raise(TypeError) { - @lexer.fullscan() - } - end - - def test_files - textfiles() { |file| - @lexer.file = file - assert_nothing_raised() { - @lexer.fullscan() - } - Puppet::Type.allclear - } - end - - def test_strings - names = %w{this is a bunch of names} - types = %w{Many Different Words A Word} - words = %w{differently Cased words A a} - - names.each { |t| - @lexer.string = t - assert_equal( - [[:NAME,t],[false,false]], - @lexer.fullscan - ) - } - types.each { |t| - @lexer.string = t - assert_equal( - [[:TYPE,t],[false,false]], - @lexer.fullscan - ) - } - end - - def test_emptystring - bit = '$var = ""' - - assert_nothing_raised { - @lexer.string = bit - } - end -end - -# $Id$ diff --git a/test/parser/tc_parser.rb b/test/parser/tc_parser.rb deleted file mode 100644 index 16ac0048b..000000000 --- a/test/parser/tc_parser.rb +++ /dev/null @@ -1,180 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/parser/parser' -require 'test/unit' -require 'puppettest' - -class TestParser < Test::Unit::TestCase - include TestPuppet - def setup - super - Puppet[:parseonly] = true - #@lexer = Puppet::Parser::Lexer.new() - @parser = Puppet::Parser::Parser.new() - end - - def test_each_file - textfiles { |file| - Puppet.debug("parsing %s" % file) if __FILE__ == $0 - assert_nothing_raised() { - @parser.file = file - @parser.parse - } - - Puppet::Type.eachtype { |type| - type.each { |obj| - assert(obj.file) - assert(obj.name) - assert(obj.line) - } - } - Puppet::Type.allclear - } - end - - def test_failers - failers { |file| - Puppet.debug("parsing failer %s" % file) if __FILE__ == $0 - assert_raise(Puppet::ParseError) { - @parser.file = file - @parser.parse - } - Puppet::Type.allclear - } - end - - def test_arrayrvalues - parser = Puppet::Parser::Parser.new() - ret = nil - assert_nothing_raised { - parser.string = 'file { "/tmp/testing": mode => [755, 640] }' - } - - assert_nothing_raised { - ret = parser.parse - } - end - - def mkmanifest(file) - name = File.join(tmpdir, "file%s" % rand(100)) - @@tmpfiles << name - - File.open(file, "w") { |f| - f.puts "file { \"%s\": create => true, mode => 755 }\n" % - name - } - end - - def test_importglobbing - basedir = File.join(tmpdir(), "importesting") - @@tmpfiles << basedir - Dir.mkdir(basedir) - - subdir = "subdir" - Dir.mkdir(File.join(basedir, subdir)) - manifest = File.join(basedir, "manifest") - File.open(manifest, "w") { |f| - f.puts "import \"%s/*\"" % subdir - } - - 4.times { |i| - path = File.join(basedir, subdir, "subfile%s" % i) - mkmanifest(path) - } - - assert_nothing_raised("Could not parse multiple files") { - parser = Puppet::Parser::Parser.new() - parser.file = manifest - parser.parse - } - end - - def test_zdefaults - basedir = File.join(tmpdir(), "defaulttesting") - @@tmpfiles << basedir - Dir.mkdir(basedir) - - defs1 = { - "testing" => "value" - } - - defs2 = { - "one" => "two", - "three" => "four", - "five" => false, - "seven" => "eight", - "nine" => true, - "eleven" => "twelve" - } - - mkdef = proc { |hash| - hash.collect { |arg, value| - "%s = %s" % [arg, value] - }.join(", ") - } - manifest = File.join(basedir, "manifest") - File.open(manifest, "w") { |f| - f.puts " - define method(#{mkdef.call(defs1)}, other) { - $variable = $testing - } - - define othermethod(#{mkdef.call(defs2)}, goodness) { - $more = less - } - - method { - other => yayness - } - - othermethod { - goodness => rahness - } -" - } - - ast = nil - assert_nothing_raised("Could not parse multiple files") { - parser = Puppet::Parser::Parser.new() - parser.file = manifest - ast = parser.parse - } - - assert(ast, "Did not receive AST while parsing defaults") - - scope = nil - assert_nothing_raised("Could not evaluate defaults parse tree") { - scope = Puppet::Parser::Scope.new() - objects = scope.evaluate(ast) - } - - method = nil - othermethod = nil - assert_nothing_raised { - method = scope.find { |child| - child.is_a?(Puppet::Parser::Scope) and child.type == "method" - } - defs1.each { |var, value| - curval = method.lookupvar(var) - assert_equal(value, curval, "Did not get default") - } - } - - assert_nothing_raised { - method = scope.find { |child| - child.is_a?(Puppet::Parser::Scope) and child.type == "othermethod" - } - defs2.each { |var, value| - curval = method.lookupvar(var) - assert_equal(value, curval, "Did not get default") - } - } - end -end - -# $Id$ diff --git a/test/puppet/defaults.rb b/test/puppet/defaults.rb new file mode 100755 index 000000000..e1d0124d2 --- /dev/null +++ b/test/puppet/defaults.rb @@ -0,0 +1,100 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = ".." +end + +require 'puppet' +require 'test/unit' + +# $Id$ + +class TestPuppetDefaults < Test::Unit::TestCase + @@dirs = %w{rrddir puppetconf puppetvar logdir statedir} + @@files = %w{logfile checksumfile manifest masterlog} + @@normals = %w{puppetport masterport server} + @@booleans = %w{rrdgraph noop} + + def testVersion + assert( Puppet.version =~ /^[0-9]+(\.[0-9]+)*$/ ) + end + + def testStringOrParam + [@@dirs,@@files,@@booleans].flatten.each { |param| + assert_nothing_raised { Puppet[param] } + assert_nothing_raised { Puppet[param.intern] } + } + end + + def test_valuesForEach + [@@dirs,@@files,@@booleans].flatten.each { |param| + param = param.intern + assert_nothing_raised { Puppet[param] } + } + end + + def testValuesForEach + [@@dirs,@@files,@@booleans].flatten.each { |param| + assert_nothing_raised { Puppet[param] } + } + end + + if __FILE__ == $0 + def disabled_testContained + confdir = Regexp.new(Puppet[:puppetconf]) + vardir = Regexp.new(Puppet[:puppetvar]) + [@@dirs,@@files].flatten.each { |param| + value = Puppet[param] + + unless value =~ confdir or value =~ vardir + assert_nothing_raised { raise "%s is in wrong dir: %s" % + [param,value] } + end + } + end + end + + def testArgumentTypes + assert_raise(ArgumentError) { Puppet[["string"]] } + assert_raise(ArgumentError) { Puppet[[:symbol]] } + end + + def testFailOnBogusArgs + [0, "ashoweklj", ";", :thisisafakesymbol].each { |param| + assert_raise(ArgumentError) { Puppet[param] } + } + end + + # we don't want user defaults in /, or root defaults in ~ + def testDefaultsInCorrectRoots + notval = nil + if Process.uid == 0 + notval = Regexp.new(File.expand_path("~")) + else + notval = /^\/var|^\/etc/ + end + [@@dirs,@@files].flatten.each { |param| + value = Puppet[param] + + unless value !~ notval + assert_nothing_raised { raise "%s is in wrong dir: %s" % + [param,value] } + end + } + end + + def test_settingdefaults + testvals = { + :fakeparam => [:puppetconf, "yaytest"], + :anotherparam => proc { File.join(Puppet[:puppetvar], "goodtest") }, + :string => "a yay string", + :boolean => true + } + + testvals.each { |param, default| + assert_nothing_raised { + Puppet.setdefault(param,default) + } + } + end +end diff --git a/test/puppet/tc_defaults.rb b/test/puppet/tc_defaults.rb deleted file mode 100755 index e1d0124d2..000000000 --- a/test/puppet/tc_defaults.rb +++ /dev/null @@ -1,100 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = ".." -end - -require 'puppet' -require 'test/unit' - -# $Id$ - -class TestPuppetDefaults < Test::Unit::TestCase - @@dirs = %w{rrddir puppetconf puppetvar logdir statedir} - @@files = %w{logfile checksumfile manifest masterlog} - @@normals = %w{puppetport masterport server} - @@booleans = %w{rrdgraph noop} - - def testVersion - assert( Puppet.version =~ /^[0-9]+(\.[0-9]+)*$/ ) - end - - def testStringOrParam - [@@dirs,@@files,@@booleans].flatten.each { |param| - assert_nothing_raised { Puppet[param] } - assert_nothing_raised { Puppet[param.intern] } - } - end - - def test_valuesForEach - [@@dirs,@@files,@@booleans].flatten.each { |param| - param = param.intern - assert_nothing_raised { Puppet[param] } - } - end - - def testValuesForEach - [@@dirs,@@files,@@booleans].flatten.each { |param| - assert_nothing_raised { Puppet[param] } - } - end - - if __FILE__ == $0 - def disabled_testContained - confdir = Regexp.new(Puppet[:puppetconf]) - vardir = Regexp.new(Puppet[:puppetvar]) - [@@dirs,@@files].flatten.each { |param| - value = Puppet[param] - - unless value =~ confdir or value =~ vardir - assert_nothing_raised { raise "%s is in wrong dir: %s" % - [param,value] } - end - } - end - end - - def testArgumentTypes - assert_raise(ArgumentError) { Puppet[["string"]] } - assert_raise(ArgumentError) { Puppet[[:symbol]] } - end - - def testFailOnBogusArgs - [0, "ashoweklj", ";", :thisisafakesymbol].each { |param| - assert_raise(ArgumentError) { Puppet[param] } - } - end - - # we don't want user defaults in /, or root defaults in ~ - def testDefaultsInCorrectRoots - notval = nil - if Process.uid == 0 - notval = Regexp.new(File.expand_path("~")) - else - notval = /^\/var|^\/etc/ - end - [@@dirs,@@files].flatten.each { |param| - value = Puppet[param] - - unless value !~ notval - assert_nothing_raised { raise "%s is in wrong dir: %s" % - [param,value] } - end - } - end - - def test_settingdefaults - testvals = { - :fakeparam => [:puppetconf, "yaytest"], - :anotherparam => proc { File.join(Puppet[:puppetvar], "goodtest") }, - :string => "a yay string", - :boolean => true - } - - testvals.each { |param, default| - assert_nothing_raised { - Puppet.setdefault(param,default) - } - } - end -end diff --git a/test/puppettest.rb b/test/puppettest.rb index daa13e3d9..30b596983 100644 --- a/test/puppettest.rb +++ b/test/puppettest.rb @@ -528,7 +528,7 @@ class PuppetTestSuite Dir.entries(name).collect { |file| File.join(name,file) }.find_all { |file| - FileTest.file?(file) and file =~ /tc_.+\.rb$/ + FileTest.file?(file) and file =~ /\.rb$/ }.sort { |a,b| # in the order they were modified, so the last modified files # are loaded and thus displayed last diff --git a/test/server/authstore.rb b/test/server/authstore.rb new file mode 100755 index 000000000..c7dfd0978 --- /dev/null +++ b/test/server/authstore.rb @@ -0,0 +1,217 @@ +if __FILE__ == $0 + if Dir.getwd =~ /test\/server$/ + Dir.chdir("..") + end + + $:.unshift '../lib' + $puppetbase = ".." + +end + +require 'puppet' +require 'puppet/server/authstore' +require 'test/unit' +require 'puppettest.rb' + +class TestAuthStore < Test::Unit::TestCase + include TestPuppet + def setup + if __FILE__ == $0 + Puppet[:loglevel] = :debug + end + + super + end + + def mkstore + store = nil + assert_nothing_raised { + store = Puppet::Server::AuthStore.new + } + + return store + end + + def test_localallow + store = mkstore + + assert_nothing_raised { + assert(store.allowed?(nil, nil), "Store disallowed local access") + } + + assert_raise(Puppet::DevError) { + store.allowed?("kirby.madstop.com", nil) + } + + assert_raise(Puppet::DevError) { + store.allowed?(nil, "192.168.0.1") + } + end + + def test_hostnames + store = mkstore + + %w{ + kirby.madstop.com + luke.madstop.net + name-other.madstop.net + }.each { |name| + assert_nothing_raised("Failed to store simple name %s" % name) { + store.allow(name) + } + assert(store.allowed?(name, "192.168.0.1"), "Name %s not allowed" % name) + } + + %w{ + invalid + ^invalid! + inval$id + + }.each { |pat| + assert_raise(Puppet::Server::AuthStoreError, + "name '%s' was allowed" % pat) { + store.allow(pat) + } + } + end + + def test_domains + store = mkstore + + assert_nothing_raised("Failed to store domains") { + store.allow("*.a.very.long.domain.name.com") + store.allow("*.madstop.com") + store.allow("*.some-other.net") + store.allow("*.much.longer.more-other.net") + } + + %w{ + madstop.com + culain.madstop.com + kirby.madstop.com + funtest.some-other.net + ya-test.madstop.com + some.much.much.longer.more-other.net + }.each { |name| + assert(store.allowed?(name, "192.168.0.1"), "Host %s not allowed" % name) + } + + assert_raise(Puppet::Server::AuthStoreError) { + store.allow("domain.*.com") + } + + assert(!store.allowed?("very.long.domain.name.com", "1.2.3.4"), + "Long hostname allowed") + + assert_raise(Puppet::Server::AuthStoreError) { + store.allow("domain.*.other.com") + } + end + + def test_simpleips + store = mkstore + + %w{ + 192.168.0.5 + 7.0.48.7 + }.each { |ip| + assert_nothing_raised("Failed to store IP address %s" % ip) { + store.allow(ip) + } + + assert(store.allowed?("hosttest.com", ip), "IP %s not allowed" % ip) + } + + assert_raise(Puppet::Server::AuthStoreError) { + store.allow("192.168.674.0") + } + + assert_raise(Puppet::Server::AuthStoreError) { + store.allow("192.168.0") + } + end + + def test_ipranges + store = mkstore + + %w{ + 192.168.0.* + 192.168.1.0/24 + 192.178.* + 193.179.0.0/8 + }.each { |range| + assert_nothing_raised("Failed to store IP range %s" % range) { + store.allow(range) + } + } + + %w{ + 192.168.0.1 + 192.168.1.5 + 192.178.0.5 + 193.0.0.1 + }.each { |ip| + assert(store.allowed?("fakename.com", ip), "IP %s is not allowed" % ip) + } + end + + def test_iprangedenials + store = mkstore + + assert_nothing_raised("Failed to store overlapping IP ranges") { + store.allow("192.168.0.0/16") + store.deny("192.168.0.0/24") + } + + assert(store.allowed?("fake.name", "192.168.1.50"), "/16 ip not allowed") + assert(! store.allowed?("fake.name", "192.168.0.50"), "/24 ip allowed") + end + + def test_subdomaindenails + store = mkstore + + assert_nothing_raised("Failed to store overlapping IP ranges") { + store.allow("*.madstop.com") + store.deny("*.sub.madstop.com") + } + + assert(store.allowed?("hostname.madstop.com", "192.168.1.50"), + "hostname not allowed") + assert(! store.allowed?("name.sub.madstop.com", "192.168.0.50"), + "subname name allowed") + end + + def test_orderingstuff + store = mkstore + + assert_nothing_raised("Failed to store overlapping IP ranges") { + store.allow("*.madstop.com") + store.deny("192.168.0.0/24") + } + + assert(store.allowed?("hostname.madstop.com", "192.168.1.50"), + "hostname not allowed") + assert(! store.allowed?("hostname.madstop.com", "192.168.0.50"), + "Host allowed over IP") + end + + def test_globalallow + store = mkstore + + assert_nothing_raised("Failed to add global allow") { + store.allow("*") + } + + [ + %w{hostname.com 192.168.0.4}, + %w{localhost 192.168.0.1}, + %w{localhost 127.0.0.1} + + ].each { |ary| + assert(store.allowed?(*ary), "Failed to allow %s" % [ary.join(",")]) + } + end +end + +# $Id$ + diff --git a/test/server/bucket.rb b/test/server/bucket.rb new file mode 100644 index 000000000..5d45eedb2 --- /dev/null +++ b/test/server/bucket.rb @@ -0,0 +1,225 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." + $debug = true +else + $debug = false +end + +require 'puppet' +require 'test/unit' +require 'puppettest.rb' +require 'base64' + +class TestBucket < Test::Unit::TestCase + include ServerTest + # run through all of the files and exercise the filebucket methods + def checkfiles(client) + files = filelist() + + # iterate across all of the files + files.each { |file| + spin + name = File.basename(file) + tmppath = File.join(tmpdir,name) + @@tmpfiles << tmppath + + # copy the files to our tmp directory so we can modify them... + File.open(tmppath,File::WRONLY|File::TRUNC|File::CREAT) { |wf| + File.open(file) { |rf| + wf.print(rf.read) + } + } + + # make sure the copy worked + assert(FileTest.exists?(tmppath)) + + # backup both the orig file and the tmp file + osum = nil + tsum = nil + nsum = nil + spin + assert_nothing_raised { + osum = client.backup(file) + } + spin + assert_nothing_raised { + tsum = client.backup(tmppath) + } + + # verify you got the same sum back for both + assert(tsum == osum) + + # modify our tmp file + File.open(tmppath,File::WRONLY|File::TRUNC) { |wf| + wf.print "This is some test text\n" + } + + # back it up + spin + assert_nothing_raised { + #STDERR.puts("backing up %s" % tmppath) if $debug + nsum = client.backup(tmppath) + } + + # and verify the sum changed + assert(tsum != nsum) + + # restore the orig + spin + assert_nothing_raised { + nsum = client.restore(tmppath,tsum) + } + + # and verify it actually got restored + spin + contents = File.open(tmppath) { |rf| + #STDERR.puts("reading %s" % tmppath) if $debug + rf.read + } + csum = Digest::MD5.hexdigest(contents) + assert(tsum == csum) + } + end + + # a list of files that should be on the system + # just something to test moving files around + def filelist + if defined? @files + return @files + else + @files = [] + end + + %w{ + who bash vim sh uname /etc/passwd /etc/syslog.conf /etc/hosts + }.each { |file| + # if it's fully qualified, just add it + if file =~ /^\// + if FileTest.exists?(file) + @files.push file + end + else + # else if it's unqualified, look for it in our path + begin + path = %x{which #{file}} + rescue => detail + #STDERR.puts "Could not search for binaries: %s" % detail + next + end + + if path != "" + @files.push path.chomp + end + end + } + + return @files + end + + def setup + super + @bucket = File.join(Puppet[:puppetconf], "buckettesting") + + @@tmpfiles << @bucket + end + + # test operating against the local filebucket object + # this calls the direct server methods, which are different than the + # Dipper methods + def test_localserver + files = filelist() + server = nil + assert_nothing_raised { + server = Puppet::Server::FileBucket.new( + :Bucket => @bucket + ) + } + + # iterate across them... + files.each { |file| + spin + contents = File.open(file) { |of| of.read } + + md5 = nil + + # add a file to the repository + assert_nothing_raised { + #STDERR.puts("adding %s" % file) if $debug + md5 = server.addfile(Base64.encode64(contents),file) + } + + # and get it back again + newcontents = nil + assert_nothing_raised { + #STDERR.puts("getting %s" % file) if $debug + newcontents = Base64.decode64(server.getfile(md5)) + } + + # and then make sure they're still the same + assert( + contents == newcontents + ) + } + end + + # test with a server and a Dipper + def test_localboth + files = filelist() + + tmpdir = File.join(tmpdir(),"tmpfiledir") + @@tmpfiles << tmpdir + FileUtils.mkdir_p(tmpdir) + + bucket = nil + client = nil + threads = [] + assert_nothing_raised { + bucket = Puppet::Server::FileBucket.new( + :Bucket => @bucket + ) + } + + #sleep(30) + assert_nothing_raised { + client = Puppet::Client::Dipper.new( + :Bucket => bucket + ) + } + + checkfiles(client) + + end + + # test that things work over the wire + def test_webxmlmix + files = filelist() + + tmpdir = File.join(tmpdir(),"tmpfiledir") + @@tmpfiles << tmpdir + FileUtils.mkdir_p(tmpdir) + + Puppet[:autosign] = true + client = nil + port = Puppet[:masterport] + + pid = mkserver(:CA => {}, :FileBucket => { :Bucket => @bucket}) + + assert_nothing_raised { + client = Puppet::Client::Dipper.new( + :Server => "localhost", + :Port => @@port + ) + } + + checkfiles(client) + + unless pid + raise "Uh, we don't have a child pid" + end + system("kill %s" % pid) + end +end + +# $Id$ diff --git a/test/server/ca.rb b/test/server/ca.rb new file mode 100644 index 000000000..b48cb42c7 --- /dev/null +++ b/test/server/ca.rb @@ -0,0 +1,201 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppet/server/ca' +require 'puppet/sslcertificates' +require 'openssl' +require 'test/unit' +require 'puppettest.rb' + +# $Id$ + +if ARGV.length > 0 and ARGV[0] == "short" + $short = true +else + $short = false +end + +class TestCA < Test::Unit::TestCase + include ServerTest + def teardown + super + print "\n\n" if Puppet[:debug] + end + + # Verify that we're autosigning. We have to autosign a "different" machine, + # since we always autosign the CA server's certificate. + def test_autocertgeneration + ca = nil + + # create our ca + assert_nothing_raised { + ca = Puppet::Server::CA.new(:autosign => true) + } + + # create a cert with a fake name + key = nil + csr = nil + cert = nil + hostname = "test.domain.com" + assert_nothing_raised { + cert = Puppet::SSLCertificates::Certificate.new( + :name => "test.domain.com" + ) + } + + # make the request + assert_nothing_raised { + cert.mkcsr + } + + # and get it signed + certtext = nil + cacerttext = nil + assert_nothing_raised { + certtext, cacerttext = ca.getcert(cert.csr.to_s) + } + + # they should both be strings + assert_instance_of(String, certtext) + assert_instance_of(String, cacerttext) + + # and they should both be valid certs + assert_nothing_raised { + OpenSSL::X509::Certificate.new(certtext) + } + assert_nothing_raised { + OpenSSL::X509::Certificate.new(cacerttext) + } + + # and pull it again, just to make sure we're getting the same thing + newtext = nil + assert_nothing_raised { + newtext, cacerttext = ca.getcert( + cert.csr.to_s, "test.reductivelabs.com", "127.0.0.1" + ) + } + + assert_equal(certtext,newtext) + end + + # this time don't use autosign + def test_storeAndSign + ca = nil + caserv = nil + + # make our CA server + assert_nothing_raised { + caserv = Puppet::Server::CA.new(:autosign => false) + } + + # retrieve the actual ca object + assert_nothing_raised { + ca = caserv.ca + } + + # make our test cert again + key = nil + csr = nil + cert = nil + hostname = "test.domain.com" + assert_nothing_raised { + cert = Puppet::SSLCertificates::Certificate.new( + :name => "anothertest.domain.com" + ) + } + # and the CSR + assert_nothing_raised { + cert.mkcsr + } + + # retrieve them + certtext = nil + assert_nothing_raised { + certtext, cacerttext = caserv.getcert( + cert.csr.to_s, "test.reductivelabs.com", "127.0.0.1" + ) + } + + # verify we got nothing back, since autosign is off + assert_equal("", certtext) + + # now sign it manually, with the CA object + x509 = nil + assert_nothing_raised { + x509, cacert = ca.sign(cert.csr) + } + + # and write it out + cert.cert = x509 + assert_nothing_raised { + cert.write + } + + assert(File.exists?(cert.certfile)) + + # now get them again, and verify that we actually get them + newtext = nil + assert_nothing_raised { + newtext, cacerttext = caserv.getcert(cert.csr.to_s) + } + + assert(newtext) + assert_nothing_raised { + OpenSSL::X509::Certificate.new(newtext) + } + end + + # and now test the autosign file + def test_autosign + autosign = File.join(tmpdir, "autosigntesting") + @@tmpfiles << autosign + File.open(autosign, "w") { |f| + f.puts "hostmatch.domain.com" + f.puts "*.other.com" + } + + caserv = nil + assert_nothing_raised { + caserv = Puppet::Server::CA.new(:autosign => autosign) + } + + # make sure we know what's going on + assert(caserv.autosign?("hostmatch.domain.com")) + assert(caserv.autosign?("fakehost.other.com")) + assert(!caserv.autosign?("kirby.reductivelabs.com")) + assert(!caserv.autosign?("culain.domain.com")) + end + + # verify that things aren't autosigned by default + def test_nodefaultautosign + caserv = nil + assert_nothing_raised { + caserv = Puppet::Server::CA.new() + } + + # make sure we know what's going on + assert(!caserv.autosign?("hostmatch.domain.com")) + assert(!caserv.autosign?("fakehost.other.com")) + assert(!caserv.autosign?("kirby.reductivelabs.com")) + assert(!caserv.autosign?("culain.domain.com")) + end + + # We want the CA to autosign its own certificate, because otherwise + # the puppetmasterd CA does not autostart. + def test_caautosign + server = nil + assert_nothing_raised { + server = Puppet::Server.new( + :Port => @@port, + :Handlers => { + :CA => {}, # so that certs autogenerate + :Status => nil + } + ) + } + end +end diff --git a/test/server/fileserver.rb b/test/server/fileserver.rb new file mode 100755 index 000000000..6712c30b7 --- /dev/null +++ b/test/server/fileserver.rb @@ -0,0 +1,694 @@ +if __FILE__ == $0 + if Dir.getwd =~ /test\/server$/ + Dir.chdir("..") + end + + $:.unshift '../lib' + $puppetbase = ".." + +end + +require 'puppet' +require 'puppet/server/fileserver' +require 'test/unit' +require 'puppettest.rb' + +class TestFileServer < Test::Unit::TestCase + include TestPuppet + # make a simple file source + def mktestdir + testdir = File.join(tmpdir(), "remotefilecopytesting") + @@tmpfiles << testdir + + # create a tmpfile + pattern = "tmpfile" + tmpfile = File.join(testdir, pattern) + assert_nothing_raised { + Dir.mkdir(testdir) + File.open(tmpfile, "w") { |f| + 3.times { f.puts rand(100) } + } + } + + return [testdir, %r{#{pattern}}, tmpfile] + end + + # make a bunch of random test files + def mktestfiles(testdir) + @@tmpfiles << testdir + assert_nothing_raised { + Dir.mkdir(testdir) + @@tmpfiles << testdir + files = %w{a b c d e}.collect { |l| + name = File.join(testdir, "file%s" % l) + File.open(name, "w") { |f| + f.puts rand(100) + } + + name + } + + return files + } + end + + def assert_describe(base, file, server) + file = File.basename(file) + assert_nothing_raised { + desc = server.describe(base + file) + assert(desc, "Got no description for %s" % file) + assert(desc != "", "Got no description for %s" % file) + assert_match(/^\d+/, desc, "Got invalid description %s" % desc) + } + end + + # test for invalid names + def test_namefailures + server = nil + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + assert_raise(Puppet::Server::FileServerError) { + server.mount("/tmp", "invalid+name") + } + + assert_raise(Puppet::Server::FileServerError) { + server.mount("/tmp", "invalid-name") + } + + assert_raise(Puppet::Server::FileServerError) { + server.mount("/tmp", "invalid name") + } + + assert_raise(Puppet::Server::FileServerError) { + server.mount("/tmp", "") + } + end + + # verify that listing the root behaves as expected + def test_listroot + server = nil + testdir, pattern, tmpfile = mktestdir() + + file = nil + checks = Puppet::Server::FileServer::CHECKPARAMS + + # and make our fileserver + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + # mount the testdir + assert_nothing_raised { + server.mount(testdir, "test") + } + + # and verify different iterations of 'root' return the same value + list = nil + assert_nothing_raised { + list = server.list("/test/", true, false) + } + + assert(list =~ pattern) + + assert_nothing_raised { + list = server.list("/test", true, false) + } + assert(list =~ pattern) + + end + + # test listing individual files + def test_getfilelist + server = nil + testdir, pattern, tmpfile = mktestdir() + + file = nil + + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + assert_nothing_raised { + server.mount(testdir, "test") + } + + # get our listing + list = nil + sfile = "/test/tmpfile" + assert_nothing_raised { + list = server.list(sfile, true, false) + } + + assert_nothing_raised { + file = Puppet::Type::PFile[tmpfile] + } + + output = "/\tfile" + + # verify it got listed as a file + assert_equal(output, list) + + # verify we got all fields + assert(list !~ /\t\t/) + + # verify that we didn't get the directory itself + list.split("\n").each { |line| + assert(line !~ %r{remotefile}) + } + + # and then verify that the contents match + contents = File.read(tmpfile) + + ret = nil + assert_nothing_raised { + ret = server.retrieve(sfile) + } + + assert_equal(contents, ret) + end + + # check that the fileserver is seeing newly created files + def test_seenewfiles + server = nil + testdir, pattern, tmpfile = mktestdir() + + + newfile = File.join(testdir, "newfile") + + # go through the whole schtick again... + file = nil + checks = Puppet::Server::FileServer::CHECKPARAMS + + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + assert_nothing_raised { + server.mount(testdir, "test") + } + + list = nil + sfile = "/test/" + assert_nothing_raised { + list = server.list(sfile, true, false) + } + + # create the new file + File.open(newfile, "w") { |f| + 3.times { f.puts rand(100) } + } + + newlist = nil + assert_nothing_raised { + newlist = server.list(sfile, true, false) + } + + # verify the list has changed + assert(list != newlist) + + # and verify that we are specifically seeing the new file + assert(newlist =~ /newfile/) + end + + # verify we can mount /, which is what local file servers will + # normally do + def test_mountroot + server = nil + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + assert_nothing_raised { + server.mount("/", "root") + } + + testdir, pattern, tmpfile = mktestdir() + + list = nil + assert_nothing_raised { + list = server.list("/root/" + testdir, true, false) + } + + assert(list =~ pattern) + end + + # verify that we're correctly recursing the right number of levels + def test_recursionlevels + server = nil + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + # make our deep recursion + basedir = File.join(tmpdir(), "recurseremotetesting") + testdir = "%s/with/some/sub/directories/for/the/purposes/of/testing" % basedir + oldfile = File.join(testdir, "oldfile") + assert_nothing_raised { + system("mkdir -p %s" % testdir) + File.open(oldfile, "w") { |f| + 3.times { f.puts rand(100) } + } + @@tmpfiles << basedir + } + + assert_nothing_raised { + server.mount(basedir, "test") + } + + # get our list + list = nil + assert_nothing_raised { + list = server.list("/test/with", false, false) + } + + # make sure we only got one line, since we're not recursing + assert(list !~ /\n/) + + # for each level of recursion, make sure we get the right list + [0, 1, 2].each { |num| + assert_nothing_raised { + list = server.list("/test/with", num, false) + } + + count = 0 + while list =~ /\n/ + list.sub!(/\n/, '') + count += 1 + end + assert_equal(num, count) + } + end + + # verify that we're not seeing the dir we ask for; i.e., that our + # list is relative to that dir, not it's parent dir + def test_listedpath + server = nil + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + + # create a deep dir + basedir = "/tmp/remotefilecopying" + testdir = "%s/with/some/sub/directories/for/testing" % basedir + oldfile = File.join(testdir, "oldfile") + assert_nothing_raised { + system("mkdir -p %s" % testdir) + File.open(oldfile, "w") { |f| + 3.times { f.puts rand(100) } + } + @@tmpfiles << basedir + } + + # mounty mounty + assert_nothing_raised { + server.mount(basedir, "localhost") + } + + list = nil + # and then check a few dirs + assert_nothing_raised { + list = server.list("/localhost/with", false, false) + } + + assert(list !~ /with/) + + assert_nothing_raised { + list = server.list("/localhost/with/some/sub", true, false) + } + + assert(list !~ /sub/) + end + + # test many dirs, not necessarily very deep + def test_widelists + server = nil + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + basedir = "/tmp/remotefilecopying" + dirs = %w{a set of directories} + assert_nothing_raised { + Dir.mkdir(basedir) + dirs.each { |dir| + Dir.mkdir(File.join(basedir, dir)) + } + @@tmpfiles << basedir + } + + assert_nothing_raised { + server.mount(basedir, "localhost") + } + + list = nil + assert_nothing_raised { + list = server.list("/localhost/", 1, false) + } + assert_instance_of(String, list, "Server returned %s instead of string") + list = list.split("\n") + + assert_equal(dirs.length + 1, list.length) + end + + # verify that 'describe' works as advertised + def test_describe + server = nil + testdir = "/tmp/remotefilecopying" + files = mktestfiles(testdir) + + file = nil + checks = Puppet::Server::FileServer::CHECKPARAMS + + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => false + ) + } + + assert_nothing_raised { + server.mount(testdir, "test") + } + + # get our list + list = nil + sfile = "/test/" + assert_nothing_raised { + list = server.list(sfile, true, false) + } + + # and describe each file in the list + assert_nothing_raised { + list.split("\n").each { |line| + file, type = line.split("\t") + + desc = server.describe(sfile + file) + } + } + + # and then make sure we can describe everything that we know is there + files.each { |file| + assert_describe(sfile, file, server) + } + + # And then describe some files that we know aren't there + retval = nil + assert_nothing_raised("Describing non-existent files raised an error") { + retval = server.describe(sfile + "noexisties") + } + + assert_equal("", retval, "Description of non-existent files returned a value") + + # Now try to describe some sources that don't even exist + retval = nil + assert_raise(Puppet::Server::FileServerError, + "Describing non-existent mount did not raise an error") { + retval = server.describe("/notmounted/" + "noexisties") + } + + assert_nil(retval, "Description of non-existent mounts returned a value") + end + + # test that our config file is parsing and working as planned + def test_configfile + server = nil + basedir = File.join(tmpdir, "fileserverconfigfiletesting") + @@tmpfiles << basedir + + # make some dirs for mounting + Dir.mkdir(basedir) + mounts = {} + %w{thing thus these those}.each { |dir| + path = File.join(basedir, dir) + mounts[dir] = mktestfiles(path) + + } + + # create an example file with each of them + conffile = tempfile + @@tmpfiles << conffile + + File.open(conffile, "w") { |f| + f.print "# a test config file + +[thing] + path #{basedir}/thing + allow 192.168.0.* + +[thus] + path #{basedir}/thus + allow *.madstop.com, *.kanies.com + deny *.sub.madstop.com + +[these] + path #{basedir}/these + +[those] + path #{basedir}/those + +" + } + + + # create a server with the file + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => conffile + ) + } + + list = nil + # run through once with no host/ip info, to verify everything is working + mounts.each { |mount, files| + mount = "/#{mount}/" + assert_nothing_raised { + list = server.list(mount, true, false) + } + + assert_nothing_raised { + list.split("\n").each { |line| + file, type = line.split("\t") + + desc = server.describe(mount + file) + } + } + + files.each { |f| + assert_describe(mount, f, server) + } + } + + # now let's check that things are being correctly forbidden + # this is just a map of names and expected results + { + "thing" => { + :deny => [ + ["hostname.com", "192.168.1.0"], + ["hostname.com", "192.158.0.0"] + ], + :allow => [ + ["hostname.com", "192.168.0.0"], + ["hostname.com", "192.168.0.245"], + ] + }, + "thus" => { + :deny => [ + ["hostname.com", "192.168.1.0"], + ["name.sub.madstop.com", "192.158.0.0"] + ], + :allow => [ + ["luke.kanies.com", "192.168.0.0"], + ["luke.madstop.com", "192.168.0.245"], + ] + } + }.each { |mount, hash| + mount = "/#{mount}/" + + # run through the map + hash.each { |type, ary| + ary.each { |sub| + host, ip = sub + + case type + when :deny: + assert_raise(Puppet::Server::AuthorizationError, + "Host %s, ip %s, allowed %s" % + [host, ip, mount]) { + list = server.list(mount, true, false, host, ip) + } + when :allow: + assert_nothing_raised("Host %s, ip %s, denied %s" % + [host, ip, mount]) { + list = server.list(mount, true, false, host, ip) + } + end + } + } + } + + end + + # Test that we smoothly handle invalid config files + def test_configfailures + # create an example file with each of them + conffile = tempfile() + + invalidmounts = { + "noexist" => "[noexist] + path /this/path/does/not/exist + allow 192.168.0.* +" +} + + invalidconfigs = [ +"[not valid] + path /this/path/does/not/exist + allow 192.168.0.* +", +"[valid] + invalidstatement + path /etc + allow 192.168.0.* +", +"[valid] + allow 192.168.0.* +" +] + + invalidmounts.each { |mount, text| + File.open(conffile, "w") { |f| + f.print text + } + + + # create a server with the file + server = nil + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => conffile + ) + } + + assert_raise(Puppet::Server::FileServerError, + "Invalid mount was mounted") { + server.list(mount) + } + } + + invalidconfigs.each_with_index { |text, i| + File.open(conffile, "w") { |f| + f.print text + } + + + # create a server with the file + server = nil + assert_raise(Puppet::Server::FileServerError, + "Invalid config %s did not raise error" % i) { + server = Puppet::Server::FileServer.new( + :Local => true, + :Config => conffile + ) + } + } + end + + # verify we reread the config file when it changes + def test_filereread + server = nil + + dir = testdir() + + files = mktestfiles(dir) + + conffile = tempfile() + + File.open(conffile, "w") { |f| + f.print "# a test config file + +[thing] + path #{dir} + allow test1.domain.com +" + } + + + # start our server with a fast timeout + assert_nothing_raised { + server = Puppet::Server::FileServer.new( + :Local => true, + :ConfigTimeout => 0.5, + :Config => conffile + ) + } + + list = nil + assert_nothing_raised { + list = server.list("/thing/", false, false, + "test1.domain.com", "127.0.0.1") + } + assert(list != "", "List returned nothing in rereard test") + + assert_raise(Puppet::Server::AuthorizationError, "List allowed invalid host") { + list = server.list("/thing/", false, false, + "test2.domain.com", "127.0.0.1") + } + + sleep 1 + File.open(conffile, "w") { |f| + f.print "# a test config file + +[thing] + path #{dir} + allow test2.domain.com +" + } + + assert_raise(Puppet::Server::AuthorizationError, "List allowed invalid host") { + list = server.list("/thing/", false, false, + "test1.domain.com", "127.0.0.1") + } + + assert_nothing_raised { + list = server.list("/thing/", false, false, + "test2.domain.com", "127.0.0.1") + } + + assert(list != "", "List returned nothing in rereard test") + + list = nil + end + +end + +# $Id$ + diff --git a/test/server/master.rb b/test/server/master.rb new file mode 100644 index 000000000..df5d092d7 --- /dev/null +++ b/test/server/master.rb @@ -0,0 +1,151 @@ +if __FILE__ == $0 + if Dir.getwd =~ /test\/server$/ + Dir.chdir("..") + end + + $:.unshift '../lib' + $puppetbase = ".." + +end + +require 'puppet' +require 'puppet/server' +require 'puppet/client' +require 'test/unit' +require 'puppettest.rb' + +class TestMaster < Test::Unit::TestCase + include ServerTest + def teardown + super + print "\n\n\n\n" if Puppet[:debug] + end + + # run through all of the existing test files and make sure everything + # works + def test_files + count = 0 + textfiles { |file| + Puppet.err :mark + Puppet.debug("parsing %s" % file) + client = nil + master = nil + + # create our master + assert_nothing_raised() { + # this is the default server setup + master = Puppet::Server::Master.new( + :File => file, + :UseNodes => false, + :Local => true + ) + } + + # and our client + assert_nothing_raised() { + client = Puppet::Client::MasterClient.new( + :Master => master + ) + } + + # pull our configuration a few times + assert_nothing_raised() { + client.getconfig + stopservices + Puppet::Type.allclear + } + assert_nothing_raised() { + client.getconfig + stopservices + Puppet::Type.allclear + } + assert_nothing_raised() { + client.getconfig + stopservices + Puppet::Type.allclear + } + # only test three files; that's plenty + if count > 3 + break + end + count += 1 + } + end + + def test_defaultmanifest + textfiles { |file| + Puppet[:manifest] = file + client = nil + master = nil + assert_nothing_raised() { + # this is the default server setup + master = Puppet::Server::Master.new( + :File => file, + :UseNodes => false, + :Local => true + ) + } + assert_nothing_raised() { + client = Puppet::Client::MasterClient.new( + :Master => master + ) + } + + # pull our configuration + assert_nothing_raised() { + client.getconfig + stopservices + Puppet::Type.allclear + } + + break + } + end + + def test_filereread + manifest = mktestmanifest() + + file2 = @createdfile + "2" + @@tmpfiles << file2 + + client = master = nil + assert_nothing_raised() { + # this is the default server setup + master = Puppet::Server::Master.new( + :File => manifest, + :UseNodes => false, + :Local => true, + :FileTimeout => 0.5 + ) + } + assert_nothing_raised() { + client = Puppet::Client::MasterClient.new( + :Master => master + ) + } + + assert_nothing_raised { + client.getconfig + client.apply + } + + assert(FileTest.exists?(@createdfile), + "Created file %s does not exist" % @createdfile) + sleep 1 + Puppet::Type.allclear + + File.open(manifest, "w") { |f| + f.puts "file { \"%s\": create => true }\n" % file2 + } + assert_nothing_raised { + client.getconfig + client.apply + } + + assert(FileTest.exists?(file2), "Second file %s does not exist" % file2) + end + +end + +# $Id$ + diff --git a/test/server/server.rb b/test/server/server.rb new file mode 100644 index 000000000..aa75b1422 --- /dev/null +++ b/test/server/server.rb @@ -0,0 +1,130 @@ +if __FILE__ == $0 + $:.unshift '../../lib' + $:.unshift '..' + $puppetbase = "../.." +end + +require 'puppet' +require 'cgi' +#require 'puppet/server' +require 'facter' +require 'puppet/client' +require 'xmlrpc/client' +require 'test/unit' +require 'puppettest.rb' + +# $Id$ + +if ARGV.length > 0 and ARGV[0] == "short" + $short = true +else + $short = false +end + +class TestServer < Test::Unit::TestCase + include ServerTest + def teardown + super + print "\n\n\n\n" if Puppet[:debug] + end + + # test that we can connect to the server + # we have to use fork here, because we apparently can't use threads + # to talk to other threads + def test_connect_with_fork + server = nil + Puppet[:autosign] = true + + # create a server just serving status + assert_nothing_raised() { + server = Puppet::Server.new( + :Port => @@port, + :Handlers => { + :CA => {}, # so that certs autogenerate + :Status => nil + } + ) + + } + + # and fork + serverpid = fork { + assert_nothing_raised() { + trap(:INT) { server.shutdown } + server.start + } + } + @@tmppids << serverpid + + # create a status client, and verify it can talk + client = nil + assert_nothing_raised() { + client = Puppet::Client::StatusClient.new( + :Server => "localhost", + :Port => @@port + ) + } + retval = nil + + assert_nothing_raised() { + retval = client.status + } + + assert_equal(1, retval) + end + + # similar to the last test, but this time actually run getconfig + def test_getconfig_with_fork + Puppet[:autosign] = true + serverpid = nil + + file = mktestmanifest() + + server = nil + # make our server again + assert_nothing_raised() { + server = Puppet::Server.new( + :Port => @@port, + :Handlers => { + :CA => {}, # so that certs autogenerate + :Master => { + :UseNodes => false, + :File => file + }, + :Status => nil + } + ) + + } + serverpid = fork { + assert_nothing_raised() { + #trap(:INT) { server.shutdown; Kernel.exit! } + trap(:INT) { server.shutdown } + server.start + } + } + @@tmppids << serverpid + + client = nil + + # and then start a masterclient + assert_nothing_raised() { + client = Puppet::Client::MasterClient.new( + :Server => "localhost", + :Port => @@port + ) + } + retval = nil + + # and run getconfig a couple of times + assert_nothing_raised() { + retval = client.getconfig + } + assert_instance_of(Puppet::TransBucket, retval, + "Server returned something other than a TransBucket") + + assert_nothing_raised() { + retval = client.getconfig + } + end +end diff --git a/test/server/tc_authstore.rb b/test/server/tc_authstore.rb deleted file mode 100755 index c7dfd0978..000000000 --- a/test/server/tc_authstore.rb +++ /dev/null @@ -1,217 +0,0 @@ -if __FILE__ == $0 - if Dir.getwd =~ /test\/server$/ - Dir.chdir("..") - end - - $:.unshift '../lib' - $puppetbase = ".." - -end - -require 'puppet' -require 'puppet/server/authstore' -require 'test/unit' -require 'puppettest.rb' - -class TestAuthStore < Test::Unit::TestCase - include TestPuppet - def setup - if __FILE__ == $0 - Puppet[:loglevel] = :debug - end - - super - end - - def mkstore - store = nil - assert_nothing_raised { - store = Puppet::Server::AuthStore.new - } - - return store - end - - def test_localallow - store = mkstore - - assert_nothing_raised { - assert(store.allowed?(nil, nil), "Store disallowed local access") - } - - assert_raise(Puppet::DevError) { - store.allowed?("kirby.madstop.com", nil) - } - - assert_raise(Puppet::DevError) { - store.allowed?(nil, "192.168.0.1") - } - end - - def test_hostnames - store = mkstore - - %w{ - kirby.madstop.com - luke.madstop.net - name-other.madstop.net - }.each { |name| - assert_nothing_raised("Failed to store simple name %s" % name) { - store.allow(name) - } - assert(store.allowed?(name, "192.168.0.1"), "Name %s not allowed" % name) - } - - %w{ - invalid - ^invalid! - inval$id - - }.each { |pat| - assert_raise(Puppet::Server::AuthStoreError, - "name '%s' was allowed" % pat) { - store.allow(pat) - } - } - end - - def test_domains - store = mkstore - - assert_nothing_raised("Failed to store domains") { - store.allow("*.a.very.long.domain.name.com") - store.allow("*.madstop.com") - store.allow("*.some-other.net") - store.allow("*.much.longer.more-other.net") - } - - %w{ - madstop.com - culain.madstop.com - kirby.madstop.com - funtest.some-other.net - ya-test.madstop.com - some.much.much.longer.more-other.net - }.each { |name| - assert(store.allowed?(name, "192.168.0.1"), "Host %s not allowed" % name) - } - - assert_raise(Puppet::Server::AuthStoreError) { - store.allow("domain.*.com") - } - - assert(!store.allowed?("very.long.domain.name.com", "1.2.3.4"), - "Long hostname allowed") - - assert_raise(Puppet::Server::AuthStoreError) { - store.allow("domain.*.other.com") - } - end - - def test_simpleips - store = mkstore - - %w{ - 192.168.0.5 - 7.0.48.7 - }.each { |ip| - assert_nothing_raised("Failed to store IP address %s" % ip) { - store.allow(ip) - } - - assert(store.allowed?("hosttest.com", ip), "IP %s not allowed" % ip) - } - - assert_raise(Puppet::Server::AuthStoreError) { - store.allow("192.168.674.0") - } - - assert_raise(Puppet::Server::AuthStoreError) { - store.allow("192.168.0") - } - end - - def test_ipranges - store = mkstore - - %w{ - 192.168.0.* - 192.168.1.0/24 - 192.178.* - 193.179.0.0/8 - }.each { |range| - assert_nothing_raised("Failed to store IP range %s" % range) { - store.allow(range) - } - } - - %w{ - 192.168.0.1 - 192.168.1.5 - 192.178.0.5 - 193.0.0.1 - }.each { |ip| - assert(store.allowed?("fakename.com", ip), "IP %s is not allowed" % ip) - } - end - - def test_iprangedenials - store = mkstore - - assert_nothing_raised("Failed to store overlapping IP ranges") { - store.allow("192.168.0.0/16") - store.deny("192.168.0.0/24") - } - - assert(store.allowed?("fake.name", "192.168.1.50"), "/16 ip not allowed") - assert(! store.allowed?("fake.name", "192.168.0.50"), "/24 ip allowed") - end - - def test_subdomaindenails - store = mkstore - - assert_nothing_raised("Failed to store overlapping IP ranges") { - store.allow("*.madstop.com") - store.deny("*.sub.madstop.com") - } - - assert(store.allowed?("hostname.madstop.com", "192.168.1.50"), - "hostname not allowed") - assert(! store.allowed?("name.sub.madstop.com", "192.168.0.50"), - "subname name allowed") - end - - def test_orderingstuff - store = mkstore - - assert_nothing_raised("Failed to store overlapping IP ranges") { - store.allow("*.madstop.com") - store.deny("192.168.0.0/24") - } - - assert(store.allowed?("hostname.madstop.com", "192.168.1.50"), - "hostname not allowed") - assert(! store.allowed?("hostname.madstop.com", "192.168.0.50"), - "Host allowed over IP") - end - - def test_globalallow - store = mkstore - - assert_nothing_raised("Failed to add global allow") { - store.allow("*") - } - - [ - %w{hostname.com 192.168.0.4}, - %w{localhost 192.168.0.1}, - %w{localhost 127.0.0.1} - - ].each { |ary| - assert(store.allowed?(*ary), "Failed to allow %s" % [ary.join(",")]) - } - end -end - -# $Id$ - diff --git a/test/server/tc_bucket.rb b/test/server/tc_bucket.rb deleted file mode 100644 index 5d45eedb2..000000000 --- a/test/server/tc_bucket.rb +++ /dev/null @@ -1,225 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." - $debug = true -else - $debug = false -end - -require 'puppet' -require 'test/unit' -require 'puppettest.rb' -require 'base64' - -class TestBucket < Test::Unit::TestCase - include ServerTest - # run through all of the files and exercise the filebucket methods - def checkfiles(client) - files = filelist() - - # iterate across all of the files - files.each { |file| - spin - name = File.basename(file) - tmppath = File.join(tmpdir,name) - @@tmpfiles << tmppath - - # copy the files to our tmp directory so we can modify them... - File.open(tmppath,File::WRONLY|File::TRUNC|File::CREAT) { |wf| - File.open(file) { |rf| - wf.print(rf.read) - } - } - - # make sure the copy worked - assert(FileTest.exists?(tmppath)) - - # backup both the orig file and the tmp file - osum = nil - tsum = nil - nsum = nil - spin - assert_nothing_raised { - osum = client.backup(file) - } - spin - assert_nothing_raised { - tsum = client.backup(tmppath) - } - - # verify you got the same sum back for both - assert(tsum == osum) - - # modify our tmp file - File.open(tmppath,File::WRONLY|File::TRUNC) { |wf| - wf.print "This is some test text\n" - } - - # back it up - spin - assert_nothing_raised { - #STDERR.puts("backing up %s" % tmppath) if $debug - nsum = client.backup(tmppath) - } - - # and verify the sum changed - assert(tsum != nsum) - - # restore the orig - spin - assert_nothing_raised { - nsum = client.restore(tmppath,tsum) - } - - # and verify it actually got restored - spin - contents = File.open(tmppath) { |rf| - #STDERR.puts("reading %s" % tmppath) if $debug - rf.read - } - csum = Digest::MD5.hexdigest(contents) - assert(tsum == csum) - } - end - - # a list of files that should be on the system - # just something to test moving files around - def filelist - if defined? @files - return @files - else - @files = [] - end - - %w{ - who bash vim sh uname /etc/passwd /etc/syslog.conf /etc/hosts - }.each { |file| - # if it's fully qualified, just add it - if file =~ /^\// - if FileTest.exists?(file) - @files.push file - end - else - # else if it's unqualified, look for it in our path - begin - path = %x{which #{file}} - rescue => detail - #STDERR.puts "Could not search for binaries: %s" % detail - next - end - - if path != "" - @files.push path.chomp - end - end - } - - return @files - end - - def setup - super - @bucket = File.join(Puppet[:puppetconf], "buckettesting") - - @@tmpfiles << @bucket - end - - # test operating against the local filebucket object - # this calls the direct server methods, which are different than the - # Dipper methods - def test_localserver - files = filelist() - server = nil - assert_nothing_raised { - server = Puppet::Server::FileBucket.new( - :Bucket => @bucket - ) - } - - # iterate across them... - files.each { |file| - spin - contents = File.open(file) { |of| of.read } - - md5 = nil - - # add a file to the repository - assert_nothing_raised { - #STDERR.puts("adding %s" % file) if $debug - md5 = server.addfile(Base64.encode64(contents),file) - } - - # and get it back again - newcontents = nil - assert_nothing_raised { - #STDERR.puts("getting %s" % file) if $debug - newcontents = Base64.decode64(server.getfile(md5)) - } - - # and then make sure they're still the same - assert( - contents == newcontents - ) - } - end - - # test with a server and a Dipper - def test_localboth - files = filelist() - - tmpdir = File.join(tmpdir(),"tmpfiledir") - @@tmpfiles << tmpdir - FileUtils.mkdir_p(tmpdir) - - bucket = nil - client = nil - threads = [] - assert_nothing_raised { - bucket = Puppet::Server::FileBucket.new( - :Bucket => @bucket - ) - } - - #sleep(30) - assert_nothing_raised { - client = Puppet::Client::Dipper.new( - :Bucket => bucket - ) - } - - checkfiles(client) - - end - - # test that things work over the wire - def test_webxmlmix - files = filelist() - - tmpdir = File.join(tmpdir(),"tmpfiledir") - @@tmpfiles << tmpdir - FileUtils.mkdir_p(tmpdir) - - Puppet[:autosign] = true - client = nil - port = Puppet[:masterport] - - pid = mkserver(:CA => {}, :FileBucket => { :Bucket => @bucket}) - - assert_nothing_raised { - client = Puppet::Client::Dipper.new( - :Server => "localhost", - :Port => @@port - ) - } - - checkfiles(client) - - unless pid - raise "Uh, we don't have a child pid" - end - system("kill %s" % pid) - end -end - -# $Id$ diff --git a/test/server/tc_ca.rb b/test/server/tc_ca.rb deleted file mode 100644 index b48cb42c7..000000000 --- a/test/server/tc_ca.rb +++ /dev/null @@ -1,201 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppet/server/ca' -require 'puppet/sslcertificates' -require 'openssl' -require 'test/unit' -require 'puppettest.rb' - -# $Id$ - -if ARGV.length > 0 and ARGV[0] == "short" - $short = true -else - $short = false -end - -class TestCA < Test::Unit::TestCase - include ServerTest - def teardown - super - print "\n\n" if Puppet[:debug] - end - - # Verify that we're autosigning. We have to autosign a "different" machine, - # since we always autosign the CA server's certificate. - def test_autocertgeneration - ca = nil - - # create our ca - assert_nothing_raised { - ca = Puppet::Server::CA.new(:autosign => true) - } - - # create a cert with a fake name - key = nil - csr = nil - cert = nil - hostname = "test.domain.com" - assert_nothing_raised { - cert = Puppet::SSLCertificates::Certificate.new( - :name => "test.domain.com" - ) - } - - # make the request - assert_nothing_raised { - cert.mkcsr - } - - # and get it signed - certtext = nil - cacerttext = nil - assert_nothing_raised { - certtext, cacerttext = ca.getcert(cert.csr.to_s) - } - - # they should both be strings - assert_instance_of(String, certtext) - assert_instance_of(String, cacerttext) - - # and they should both be valid certs - assert_nothing_raised { - OpenSSL::X509::Certificate.new(certtext) - } - assert_nothing_raised { - OpenSSL::X509::Certificate.new(cacerttext) - } - - # and pull it again, just to make sure we're getting the same thing - newtext = nil - assert_nothing_raised { - newtext, cacerttext = ca.getcert( - cert.csr.to_s, "test.reductivelabs.com", "127.0.0.1" - ) - } - - assert_equal(certtext,newtext) - end - - # this time don't use autosign - def test_storeAndSign - ca = nil - caserv = nil - - # make our CA server - assert_nothing_raised { - caserv = Puppet::Server::CA.new(:autosign => false) - } - - # retrieve the actual ca object - assert_nothing_raised { - ca = caserv.ca - } - - # make our test cert again - key = nil - csr = nil - cert = nil - hostname = "test.domain.com" - assert_nothing_raised { - cert = Puppet::SSLCertificates::Certificate.new( - :name => "anothertest.domain.com" - ) - } - # and the CSR - assert_nothing_raised { - cert.mkcsr - } - - # retrieve them - certtext = nil - assert_nothing_raised { - certtext, cacerttext = caserv.getcert( - cert.csr.to_s, "test.reductivelabs.com", "127.0.0.1" - ) - } - - # verify we got nothing back, since autosign is off - assert_equal("", certtext) - - # now sign it manually, with the CA object - x509 = nil - assert_nothing_raised { - x509, cacert = ca.sign(cert.csr) - } - - # and write it out - cert.cert = x509 - assert_nothing_raised { - cert.write - } - - assert(File.exists?(cert.certfile)) - - # now get them again, and verify that we actually get them - newtext = nil - assert_nothing_raised { - newtext, cacerttext = caserv.getcert(cert.csr.to_s) - } - - assert(newtext) - assert_nothing_raised { - OpenSSL::X509::Certificate.new(newtext) - } - end - - # and now test the autosign file - def test_autosign - autosign = File.join(tmpdir, "autosigntesting") - @@tmpfiles << autosign - File.open(autosign, "w") { |f| - f.puts "hostmatch.domain.com" - f.puts "*.other.com" - } - - caserv = nil - assert_nothing_raised { - caserv = Puppet::Server::CA.new(:autosign => autosign) - } - - # make sure we know what's going on - assert(caserv.autosign?("hostmatch.domain.com")) - assert(caserv.autosign?("fakehost.other.com")) - assert(!caserv.autosign?("kirby.reductivelabs.com")) - assert(!caserv.autosign?("culain.domain.com")) - end - - # verify that things aren't autosigned by default - def test_nodefaultautosign - caserv = nil - assert_nothing_raised { - caserv = Puppet::Server::CA.new() - } - - # make sure we know what's going on - assert(!caserv.autosign?("hostmatch.domain.com")) - assert(!caserv.autosign?("fakehost.other.com")) - assert(!caserv.autosign?("kirby.reductivelabs.com")) - assert(!caserv.autosign?("culain.domain.com")) - end - - # We want the CA to autosign its own certificate, because otherwise - # the puppetmasterd CA does not autostart. - def test_caautosign - server = nil - assert_nothing_raised { - server = Puppet::Server.new( - :Port => @@port, - :Handlers => { - :CA => {}, # so that certs autogenerate - :Status => nil - } - ) - } - end -end diff --git a/test/server/tc_fileserver.rb b/test/server/tc_fileserver.rb deleted file mode 100755 index 6712c30b7..000000000 --- a/test/server/tc_fileserver.rb +++ /dev/null @@ -1,694 +0,0 @@ -if __FILE__ == $0 - if Dir.getwd =~ /test\/server$/ - Dir.chdir("..") - end - - $:.unshift '../lib' - $puppetbase = ".." - -end - -require 'puppet' -require 'puppet/server/fileserver' -require 'test/unit' -require 'puppettest.rb' - -class TestFileServer < Test::Unit::TestCase - include TestPuppet - # make a simple file source - def mktestdir - testdir = File.join(tmpdir(), "remotefilecopytesting") - @@tmpfiles << testdir - - # create a tmpfile - pattern = "tmpfile" - tmpfile = File.join(testdir, pattern) - assert_nothing_raised { - Dir.mkdir(testdir) - File.open(tmpfile, "w") { |f| - 3.times { f.puts rand(100) } - } - } - - return [testdir, %r{#{pattern}}, tmpfile] - end - - # make a bunch of random test files - def mktestfiles(testdir) - @@tmpfiles << testdir - assert_nothing_raised { - Dir.mkdir(testdir) - @@tmpfiles << testdir - files = %w{a b c d e}.collect { |l| - name = File.join(testdir, "file%s" % l) - File.open(name, "w") { |f| - f.puts rand(100) - } - - name - } - - return files - } - end - - def assert_describe(base, file, server) - file = File.basename(file) - assert_nothing_raised { - desc = server.describe(base + file) - assert(desc, "Got no description for %s" % file) - assert(desc != "", "Got no description for %s" % file) - assert_match(/^\d+/, desc, "Got invalid description %s" % desc) - } - end - - # test for invalid names - def test_namefailures - server = nil - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - assert_raise(Puppet::Server::FileServerError) { - server.mount("/tmp", "invalid+name") - } - - assert_raise(Puppet::Server::FileServerError) { - server.mount("/tmp", "invalid-name") - } - - assert_raise(Puppet::Server::FileServerError) { - server.mount("/tmp", "invalid name") - } - - assert_raise(Puppet::Server::FileServerError) { - server.mount("/tmp", "") - } - end - - # verify that listing the root behaves as expected - def test_listroot - server = nil - testdir, pattern, tmpfile = mktestdir() - - file = nil - checks = Puppet::Server::FileServer::CHECKPARAMS - - # and make our fileserver - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - # mount the testdir - assert_nothing_raised { - server.mount(testdir, "test") - } - - # and verify different iterations of 'root' return the same value - list = nil - assert_nothing_raised { - list = server.list("/test/", true, false) - } - - assert(list =~ pattern) - - assert_nothing_raised { - list = server.list("/test", true, false) - } - assert(list =~ pattern) - - end - - # test listing individual files - def test_getfilelist - server = nil - testdir, pattern, tmpfile = mktestdir() - - file = nil - - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - assert_nothing_raised { - server.mount(testdir, "test") - } - - # get our listing - list = nil - sfile = "/test/tmpfile" - assert_nothing_raised { - list = server.list(sfile, true, false) - } - - assert_nothing_raised { - file = Puppet::Type::PFile[tmpfile] - } - - output = "/\tfile" - - # verify it got listed as a file - assert_equal(output, list) - - # verify we got all fields - assert(list !~ /\t\t/) - - # verify that we didn't get the directory itself - list.split("\n").each { |line| - assert(line !~ %r{remotefile}) - } - - # and then verify that the contents match - contents = File.read(tmpfile) - - ret = nil - assert_nothing_raised { - ret = server.retrieve(sfile) - } - - assert_equal(contents, ret) - end - - # check that the fileserver is seeing newly created files - def test_seenewfiles - server = nil - testdir, pattern, tmpfile = mktestdir() - - - newfile = File.join(testdir, "newfile") - - # go through the whole schtick again... - file = nil - checks = Puppet::Server::FileServer::CHECKPARAMS - - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - assert_nothing_raised { - server.mount(testdir, "test") - } - - list = nil - sfile = "/test/" - assert_nothing_raised { - list = server.list(sfile, true, false) - } - - # create the new file - File.open(newfile, "w") { |f| - 3.times { f.puts rand(100) } - } - - newlist = nil - assert_nothing_raised { - newlist = server.list(sfile, true, false) - } - - # verify the list has changed - assert(list != newlist) - - # and verify that we are specifically seeing the new file - assert(newlist =~ /newfile/) - end - - # verify we can mount /, which is what local file servers will - # normally do - def test_mountroot - server = nil - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - assert_nothing_raised { - server.mount("/", "root") - } - - testdir, pattern, tmpfile = mktestdir() - - list = nil - assert_nothing_raised { - list = server.list("/root/" + testdir, true, false) - } - - assert(list =~ pattern) - end - - # verify that we're correctly recursing the right number of levels - def test_recursionlevels - server = nil - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - # make our deep recursion - basedir = File.join(tmpdir(), "recurseremotetesting") - testdir = "%s/with/some/sub/directories/for/the/purposes/of/testing" % basedir - oldfile = File.join(testdir, "oldfile") - assert_nothing_raised { - system("mkdir -p %s" % testdir) - File.open(oldfile, "w") { |f| - 3.times { f.puts rand(100) } - } - @@tmpfiles << basedir - } - - assert_nothing_raised { - server.mount(basedir, "test") - } - - # get our list - list = nil - assert_nothing_raised { - list = server.list("/test/with", false, false) - } - - # make sure we only got one line, since we're not recursing - assert(list !~ /\n/) - - # for each level of recursion, make sure we get the right list - [0, 1, 2].each { |num| - assert_nothing_raised { - list = server.list("/test/with", num, false) - } - - count = 0 - while list =~ /\n/ - list.sub!(/\n/, '') - count += 1 - end - assert_equal(num, count) - } - end - - # verify that we're not seeing the dir we ask for; i.e., that our - # list is relative to that dir, not it's parent dir - def test_listedpath - server = nil - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - - # create a deep dir - basedir = "/tmp/remotefilecopying" - testdir = "%s/with/some/sub/directories/for/testing" % basedir - oldfile = File.join(testdir, "oldfile") - assert_nothing_raised { - system("mkdir -p %s" % testdir) - File.open(oldfile, "w") { |f| - 3.times { f.puts rand(100) } - } - @@tmpfiles << basedir - } - - # mounty mounty - assert_nothing_raised { - server.mount(basedir, "localhost") - } - - list = nil - # and then check a few dirs - assert_nothing_raised { - list = server.list("/localhost/with", false, false) - } - - assert(list !~ /with/) - - assert_nothing_raised { - list = server.list("/localhost/with/some/sub", true, false) - } - - assert(list !~ /sub/) - end - - # test many dirs, not necessarily very deep - def test_widelists - server = nil - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - basedir = "/tmp/remotefilecopying" - dirs = %w{a set of directories} - assert_nothing_raised { - Dir.mkdir(basedir) - dirs.each { |dir| - Dir.mkdir(File.join(basedir, dir)) - } - @@tmpfiles << basedir - } - - assert_nothing_raised { - server.mount(basedir, "localhost") - } - - list = nil - assert_nothing_raised { - list = server.list("/localhost/", 1, false) - } - assert_instance_of(String, list, "Server returned %s instead of string") - list = list.split("\n") - - assert_equal(dirs.length + 1, list.length) - end - - # verify that 'describe' works as advertised - def test_describe - server = nil - testdir = "/tmp/remotefilecopying" - files = mktestfiles(testdir) - - file = nil - checks = Puppet::Server::FileServer::CHECKPARAMS - - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => false - ) - } - - assert_nothing_raised { - server.mount(testdir, "test") - } - - # get our list - list = nil - sfile = "/test/" - assert_nothing_raised { - list = server.list(sfile, true, false) - } - - # and describe each file in the list - assert_nothing_raised { - list.split("\n").each { |line| - file, type = line.split("\t") - - desc = server.describe(sfile + file) - } - } - - # and then make sure we can describe everything that we know is there - files.each { |file| - assert_describe(sfile, file, server) - } - - # And then describe some files that we know aren't there - retval = nil - assert_nothing_raised("Describing non-existent files raised an error") { - retval = server.describe(sfile + "noexisties") - } - - assert_equal("", retval, "Description of non-existent files returned a value") - - # Now try to describe some sources that don't even exist - retval = nil - assert_raise(Puppet::Server::FileServerError, - "Describing non-existent mount did not raise an error") { - retval = server.describe("/notmounted/" + "noexisties") - } - - assert_nil(retval, "Description of non-existent mounts returned a value") - end - - # test that our config file is parsing and working as planned - def test_configfile - server = nil - basedir = File.join(tmpdir, "fileserverconfigfiletesting") - @@tmpfiles << basedir - - # make some dirs for mounting - Dir.mkdir(basedir) - mounts = {} - %w{thing thus these those}.each { |dir| - path = File.join(basedir, dir) - mounts[dir] = mktestfiles(path) - - } - - # create an example file with each of them - conffile = tempfile - @@tmpfiles << conffile - - File.open(conffile, "w") { |f| - f.print "# a test config file - -[thing] - path #{basedir}/thing - allow 192.168.0.* - -[thus] - path #{basedir}/thus - allow *.madstop.com, *.kanies.com - deny *.sub.madstop.com - -[these] - path #{basedir}/these - -[those] - path #{basedir}/those - -" - } - - - # create a server with the file - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => conffile - ) - } - - list = nil - # run through once with no host/ip info, to verify everything is working - mounts.each { |mount, files| - mount = "/#{mount}/" - assert_nothing_raised { - list = server.list(mount, true, false) - } - - assert_nothing_raised { - list.split("\n").each { |line| - file, type = line.split("\t") - - desc = server.describe(mount + file) - } - } - - files.each { |f| - assert_describe(mount, f, server) - } - } - - # now let's check that things are being correctly forbidden - # this is just a map of names and expected results - { - "thing" => { - :deny => [ - ["hostname.com", "192.168.1.0"], - ["hostname.com", "192.158.0.0"] - ], - :allow => [ - ["hostname.com", "192.168.0.0"], - ["hostname.com", "192.168.0.245"], - ] - }, - "thus" => { - :deny => [ - ["hostname.com", "192.168.1.0"], - ["name.sub.madstop.com", "192.158.0.0"] - ], - :allow => [ - ["luke.kanies.com", "192.168.0.0"], - ["luke.madstop.com", "192.168.0.245"], - ] - } - }.each { |mount, hash| - mount = "/#{mount}/" - - # run through the map - hash.each { |type, ary| - ary.each { |sub| - host, ip = sub - - case type - when :deny: - assert_raise(Puppet::Server::AuthorizationError, - "Host %s, ip %s, allowed %s" % - [host, ip, mount]) { - list = server.list(mount, true, false, host, ip) - } - when :allow: - assert_nothing_raised("Host %s, ip %s, denied %s" % - [host, ip, mount]) { - list = server.list(mount, true, false, host, ip) - } - end - } - } - } - - end - - # Test that we smoothly handle invalid config files - def test_configfailures - # create an example file with each of them - conffile = tempfile() - - invalidmounts = { - "noexist" => "[noexist] - path /this/path/does/not/exist - allow 192.168.0.* -" -} - - invalidconfigs = [ -"[not valid] - path /this/path/does/not/exist - allow 192.168.0.* -", -"[valid] - invalidstatement - path /etc - allow 192.168.0.* -", -"[valid] - allow 192.168.0.* -" -] - - invalidmounts.each { |mount, text| - File.open(conffile, "w") { |f| - f.print text - } - - - # create a server with the file - server = nil - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => conffile - ) - } - - assert_raise(Puppet::Server::FileServerError, - "Invalid mount was mounted") { - server.list(mount) - } - } - - invalidconfigs.each_with_index { |text, i| - File.open(conffile, "w") { |f| - f.print text - } - - - # create a server with the file - server = nil - assert_raise(Puppet::Server::FileServerError, - "Invalid config %s did not raise error" % i) { - server = Puppet::Server::FileServer.new( - :Local => true, - :Config => conffile - ) - } - } - end - - # verify we reread the config file when it changes - def test_filereread - server = nil - - dir = testdir() - - files = mktestfiles(dir) - - conffile = tempfile() - - File.open(conffile, "w") { |f| - f.print "# a test config file - -[thing] - path #{dir} - allow test1.domain.com -" - } - - - # start our server with a fast timeout - assert_nothing_raised { - server = Puppet::Server::FileServer.new( - :Local => true, - :ConfigTimeout => 0.5, - :Config => conffile - ) - } - - list = nil - assert_nothing_raised { - list = server.list("/thing/", false, false, - "test1.domain.com", "127.0.0.1") - } - assert(list != "", "List returned nothing in rereard test") - - assert_raise(Puppet::Server::AuthorizationError, "List allowed invalid host") { - list = server.list("/thing/", false, false, - "test2.domain.com", "127.0.0.1") - } - - sleep 1 - File.open(conffile, "w") { |f| - f.print "# a test config file - -[thing] - path #{dir} - allow test2.domain.com -" - } - - assert_raise(Puppet::Server::AuthorizationError, "List allowed invalid host") { - list = server.list("/thing/", false, false, - "test1.domain.com", "127.0.0.1") - } - - assert_nothing_raised { - list = server.list("/thing/", false, false, - "test2.domain.com", "127.0.0.1") - } - - assert(list != "", "List returned nothing in rereard test") - - list = nil - end - -end - -# $Id$ - diff --git a/test/server/tc_master.rb b/test/server/tc_master.rb deleted file mode 100644 index df5d092d7..000000000 --- a/test/server/tc_master.rb +++ /dev/null @@ -1,151 +0,0 @@ -if __FILE__ == $0 - if Dir.getwd =~ /test\/server$/ - Dir.chdir("..") - end - - $:.unshift '../lib' - $puppetbase = ".." - -end - -require 'puppet' -require 'puppet/server' -require 'puppet/client' -require 'test/unit' -require 'puppettest.rb' - -class TestMaster < Test::Unit::TestCase - include ServerTest - def teardown - super - print "\n\n\n\n" if Puppet[:debug] - end - - # run through all of the existing test files and make sure everything - # works - def test_files - count = 0 - textfiles { |file| - Puppet.err :mark - Puppet.debug("parsing %s" % file) - client = nil - master = nil - - # create our master - assert_nothing_raised() { - # this is the default server setup - master = Puppet::Server::Master.new( - :File => file, - :UseNodes => false, - :Local => true - ) - } - - # and our client - assert_nothing_raised() { - client = Puppet::Client::MasterClient.new( - :Master => master - ) - } - - # pull our configuration a few times - assert_nothing_raised() { - client.getconfig - stopservices - Puppet::Type.allclear - } - assert_nothing_raised() { - client.getconfig - stopservices - Puppet::Type.allclear - } - assert_nothing_raised() { - client.getconfig - stopservices - Puppet::Type.allclear - } - # only test three files; that's plenty - if count > 3 - break - end - count += 1 - } - end - - def test_defaultmanifest - textfiles { |file| - Puppet[:manifest] = file - client = nil - master = nil - assert_nothing_raised() { - # this is the default server setup - master = Puppet::Server::Master.new( - :File => file, - :UseNodes => false, - :Local => true - ) - } - assert_nothing_raised() { - client = Puppet::Client::MasterClient.new( - :Master => master - ) - } - - # pull our configuration - assert_nothing_raised() { - client.getconfig - stopservices - Puppet::Type.allclear - } - - break - } - end - - def test_filereread - manifest = mktestmanifest() - - file2 = @createdfile + "2" - @@tmpfiles << file2 - - client = master = nil - assert_nothing_raised() { - # this is the default server setup - master = Puppet::Server::Master.new( - :File => manifest, - :UseNodes => false, - :Local => true, - :FileTimeout => 0.5 - ) - } - assert_nothing_raised() { - client = Puppet::Client::MasterClient.new( - :Master => master - ) - } - - assert_nothing_raised { - client.getconfig - client.apply - } - - assert(FileTest.exists?(@createdfile), - "Created file %s does not exist" % @createdfile) - sleep 1 - Puppet::Type.allclear - - File.open(manifest, "w") { |f| - f.puts "file { \"%s\": create => true }\n" % file2 - } - assert_nothing_raised { - client.getconfig - client.apply - } - - assert(FileTest.exists?(file2), "Second file %s does not exist" % file2) - end - -end - -# $Id$ - diff --git a/test/server/tc_server.rb b/test/server/tc_server.rb deleted file mode 100644 index aa75b1422..000000000 --- a/test/server/tc_server.rb +++ /dev/null @@ -1,130 +0,0 @@ -if __FILE__ == $0 - $:.unshift '../../lib' - $:.unshift '..' - $puppetbase = "../.." -end - -require 'puppet' -require 'cgi' -#require 'puppet/server' -require 'facter' -require 'puppet/client' -require 'xmlrpc/client' -require 'test/unit' -require 'puppettest.rb' - -# $Id$ - -if ARGV.length > 0 and ARGV[0] == "short" - $short = true -else - $short = false -end - -class TestServer < Test::Unit::TestCase - include ServerTest - def teardown - super - print "\n\n\n\n" if Puppet[:debug] - end - - # test that we can connect to the server - # we have to use fork here, because we apparently can't use threads - # to talk to other threads - def test_connect_with_fork - server = nil - Puppet[:autosign] = true - - # create a server just serving status - assert_nothing_raised() { - server = Puppet::Server.new( - :Port => @@port, - :Handlers => { - :CA => {}, # so that certs autogenerate - :Status => nil - } - ) - - } - - # and fork - serverpid = fork { - assert_nothing_raised() { - trap(:INT) { server.shutdown } - server.start - } - } - @@tmppids << serverpid - - # create a status client, and verify it can talk - client = nil - assert_nothing_raised() { - client = Puppet::Client::StatusClient.new( - :Server => "localhost", - :Port => @@port - ) - } - retval = nil - - assert_nothing_raised() { - retval = client.status - } - - assert_equal(1, retval) - end - - # similar to the last test, but this time actually run getconfig - def test_getconfig_with_fork - Puppet[:autosign] = true - serverpid = nil - - file = mktestmanifest() - - server = nil - # make our server again - assert_nothing_raised() { - server = Puppet::Server.new( - :Port => @@port, - :Handlers => { - :CA => {}, # so that certs autogenerate - :Master => { - :UseNodes => false, - :File => file - }, - :Status => nil - } - ) - - } - serverpid = fork { - assert_nothing_raised() { - #trap(:INT) { server.shutdown; Kernel.exit! } - trap(:INT) { server.shutdown } - server.start - } - } - @@tmppids << serverpid - - client = nil - - # and then start a masterclient - assert_nothing_raised() { - client = Puppet::Client::MasterClient.new( - :Server => "localhost", - :Port => @@port - ) - } - retval = nil - - # and run getconfig a couple of times - assert_nothing_raised() { - retval = client.getconfig - } - assert_instance_of(Puppet::TransBucket, retval, - "Server returned something other than a TransBucket") - - assert_nothing_raised() { - retval = client.getconfig - } - end -end diff --git a/test/tagging/tagging.rb b/test/tagging/tagging.rb new file mode 100644 index 000000000..260e0e53a --- /dev/null +++ b/test/tagging/tagging.rb @@ -0,0 +1,80 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +class TestTagging < Test::Unit::TestCase + include TestPuppet + + # Make sure the scopes are getting the right tags + def test_scopetags + scope = nil + assert_nothing_raised { + scope = Puppet::Parser::Scope.new() + scope.name = "yayness" + scope.type = "solaris" + } + + assert_nothing_raised { + assert_equal(%w{solaris}, scope.tags, "Incorrect scope tags") + } + end + + # Test deeper tags, where a scope gets all of its parent scopes' tags + def test_deepscopetags + scope = nil + assert_nothing_raised { + scope = Puppet::Parser::Scope.new() + scope.name = "yayness" + scope.type = "solaris" + scope = scope.newscope + scope.name = "booness" + scope.type = "apache" + } + + assert_nothing_raised { + # Scopes put their own tags first + assert_equal(%w{apache solaris}, scope.tags, "Incorrect scope tags") + } + end + + # Verify that the tags make their way to the objects + def test_objecttags + scope = nil + assert_nothing_raised { + scope = Puppet::Parser::Scope.new() + scope.name = "yayness" + scope.type = "solaris" + } + + assert_nothing_raised { + scope.setobject( + "file", + "/etc/passwd", + {"owner" => "root"}, + "/yay", + 1 + ) + } + + objects = nil + assert_nothing_raised { + objects = scope.to_trans + } + + # There's only one object, so shift it out + object = objects.shift + + assert_nothing_raised { + assert_equal(%w{solaris file /etc/passwd}, object.tags, + "Incorrect tags") + } + end +end + +# $Id$ diff --git a/test/tagging/tc_tagging.rb b/test/tagging/tc_tagging.rb deleted file mode 100644 index 260e0e53a..000000000 --- a/test/tagging/tc_tagging.rb +++ /dev/null @@ -1,80 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -class TestTagging < Test::Unit::TestCase - include TestPuppet - - # Make sure the scopes are getting the right tags - def test_scopetags - scope = nil - assert_nothing_raised { - scope = Puppet::Parser::Scope.new() - scope.name = "yayness" - scope.type = "solaris" - } - - assert_nothing_raised { - assert_equal(%w{solaris}, scope.tags, "Incorrect scope tags") - } - end - - # Test deeper tags, where a scope gets all of its parent scopes' tags - def test_deepscopetags - scope = nil - assert_nothing_raised { - scope = Puppet::Parser::Scope.new() - scope.name = "yayness" - scope.type = "solaris" - scope = scope.newscope - scope.name = "booness" - scope.type = "apache" - } - - assert_nothing_raised { - # Scopes put their own tags first - assert_equal(%w{apache solaris}, scope.tags, "Incorrect scope tags") - } - end - - # Verify that the tags make their way to the objects - def test_objecttags - scope = nil - assert_nothing_raised { - scope = Puppet::Parser::Scope.new() - scope.name = "yayness" - scope.type = "solaris" - } - - assert_nothing_raised { - scope.setobject( - "file", - "/etc/passwd", - {"owner" => "root"}, - "/yay", - 1 - ) - } - - objects = nil - assert_nothing_raised { - objects = scope.to_trans - } - - # There's only one object, so shift it out - object = objects.shift - - assert_nothing_raised { - assert_equal(%w{solaris file /etc/passwd}, object.tags, - "Incorrect tags") - } - end -end - -# $Id$ diff --git a/test/test b/test/test index 863530494..15f9ad5f9 100755 --- a/test/test +++ b/test/test @@ -1,22 +1,12 @@ #!/usr/bin/env ruby #------------------------------------------------------------ -# $Id$ -# # run any or all test suites $:.unshift '.' $:.unshift '../lib' -# if we're not in the library trunk, then add that to the lib search path -#if Dir.getwd !~ %r{puppet/library} -# $:.unshift '../../../library/trunk/lib/' -# $:.unshift '../../../language/trunk/lib/' -# $:.unshift '../../../library/trunk/test/' -#end - require 'puppettest.rb' - require 'getoptlong' #[ "--size", "-s", GetoptLong::REQUIRED_ARGUMENT ], @@ -52,3 +42,5 @@ suites.each { |suite| # This damn problem just doesn't seem to want to go away system("%s/etc/init.d/sleeper stop 2>/dev/null 1>/dev/null" % $puppetbase) + +# $Id$ diff --git a/test/types/basic.rb b/test/types/basic.rb new file mode 100644 index 000000000..4ad6d559b --- /dev/null +++ b/test/types/basic.rb @@ -0,0 +1,119 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +class TestBasic < Test::Unit::TestCase + include TestPuppet + # hmmm + # this is complicated, because we store references to the created + # objects in a central store + def setup + super + @component = nil + @configfile = nil + @sleeper = nil + + Puppet[:loglevel] = :debug if __FILE__ == $0 + + assert_nothing_raised() { + @component = Puppet::Type::Component.create( + :name => "yaytest", + :type => "testing" + ) + } + + assert_nothing_raised() { + @filepath = tempfile() + @@tmpfiles << @filepath + @configfile = Puppet::Type::PFile.create( + :path => @filepath, + :create => true, + :checksum => "md5" + ) + } + assert_nothing_raised() { + @sleeper = Puppet::Type::Service.create( + :name => "sleeper", + :type => "init", + :path => File.join($puppetbase,"examples/root/etc/init.d"), + :hasstatus => true, + :running => 1 + ) + } + assert_nothing_raised() { + @component.push( + @configfile, + @sleeper + ) + } + + #puts "Component is %s, id %s" % [@component, @component.object_id] + #puts "ConfigFile is %s, id %s" % [@configfile, @configfile.object_id] + end + + def test_name_calls + [@sleeper,@configfile].each { |obj| + Puppet.debug "obj is %s" % obj + assert_nothing_raised(){ + obj.name + } + } + end + + def test_name_equality + #puts "Component is %s, id %s" % [@component, @component.object_id] + assert_equal( + @filepath, + @configfile.name + ) + + assert_equal( + "sleeper", + @sleeper.name + ) + end + + def test_object_retrieval + [@sleeper,@configfile].each { |obj| + assert_equal( + obj.class[obj.name].object_id, + obj.object_id + ) + } + end + + def test_transaction + transaction = nil + assert_nothing_raised() { + transaction = @component.evaluate + } + assert_nothing_raised() { + transaction.evaluate + } + assert_nothing_raised() { + @sleeper[:running] = 0 + } + assert_nothing_raised() { + transaction = @component.evaluate + } + assert_nothing_raised() { + transaction.evaluate + } + end + + def test_paths + [@configfile,@sleeper,@component].each { |obj| + assert_nothing_raised { + assert(obj.path.is_a?(Array)) + } + } + end +end + +# $Id$ diff --git a/test/types/component.rb b/test/types/component.rb new file mode 100755 index 000000000..d52123ae0 --- /dev/null +++ b/test/types/component.rb @@ -0,0 +1,279 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +# $Id$ + +class TestComponent < Test::Unit::TestCase + include TestPuppet + def setup + @@used = {} + super + end + + def teardown + assert_nothing_raised() { + Puppet::Type.allclear + } + super + end + + def randnum(limit) + num = nil + looped = 0 + loop do + looped += 1 + if looped > 1000 + raise "Reached limit of looping" + break + end + num = rand(limit) + unless @@used.include?(num) + @@used[num] = true + break + end + end + + num + end + + def mkfile(num = nil) + unless num + num = randnum(1000) + end + name = "/tmp/componentrandfile" + num.to_s + + file = Puppet::Type::PFile.create( + :path => name, + :checksum => "md5" + ) + @@tmpfiles << name + file + end + + def mkcomp + Puppet::Type::Component.create(:name => "component_" + randnum(1000).to_s) + end + + def mkrandcomp(numfiles, numdivs) + comp = mkcomp + hash = {} + found = 0 + + divs = {} + + numdivs.times { |i| + num = i + 2 + divs[num] = nil + } + while found < numfiles + num = randnum(numfiles) + found += 1 + f = mkfile(num) + hash[f.name] = f + reqd = [] + divs.each { |n,obj| + if rand(50) % n == 0 + if obj + unless reqd.include?(obj.object_id) + f[:require] = [[obj.class.name, obj.name]] + reqd << obj.object_id + end + end + end + + divs[n] = f + } + end + + hash.each { |name, obj| + comp.push obj + } + + comp + end + + def test_ordering + list = nil + comp = mkrandcomp(30,5) + assert_nothing_raised { + list = comp.flatten + } + + list.each_with_index { |obj, index| + obj.eachdependency { |dep| + assert(list.index(dep) < index) + } + } + end + + def test_correctsorting + tmpfile = "/tmp/comptesting" + @@tmpfiles.push tmpfile + trans = nil + cmd = nil + File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| + of.puts rand(100) + } + file = Puppet::Type::PFile.create( + :path => tmpfile, + :checksum => "md5" + ) + assert_nothing_raised { + cmd = Puppet::Type::Exec.create( + :command => "pwd", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :subscribe => [[file.class.name,file.name]], + :refreshonly => true + ) + } + + order = nil + assert_nothing_raised { + order = Puppet::Type::Component.sort([file, cmd]) + } + + [cmd, file].each { |obj| + assert_equal(1, order.find_all { |o| o.name == obj.name }.length) + } + end + + def test_correctflattening + tmpfile = "/tmp/comptesting" + @@tmpfiles.push tmpfile + trans = nil + cmd = nil + File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| + of.puts rand(100) + } + file = Puppet::Type::PFile.create( + :path => tmpfile, + :checksum => "md5" + ) + assert_nothing_raised { + cmd = Puppet::Type::Exec.create( + :command => "pwd", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :subscribe => [[file.class.name,file.name]], + :refreshonly => true + ) + } + + comp = Puppet::Type::Component.create(:name => "RefreshTest") + [cmd, file].each { |obj| + comp.push obj + } + objects = nil + assert_nothing_raised { + objects = comp.flatten + } + + [cmd, file].each { |obj| + assert_equal(1, objects.find_all { |o| o.name == obj.name }.length) + } + + assert(objects[0] == file, "File was not first object") + assert(objects[1] == cmd, "Exec was not second object") + end + + def test_deepflatten + tmpfile = tempfile() + @@tmpfiles.push tmpfile + trans = nil + cmd = nil + File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| + of.puts rand(100) + } + file = Puppet::Type::PFile.create( + :path => tmpfile, + :checksum => "md5" + ) + assert_nothing_raised { + cmd = Puppet::Type::Exec.create( + :command => "pwd", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :refreshonly => true + ) + } + + fcomp = newcomp("fflatten", file) + ecomp = newcomp("eflatten", cmd) + + # this subscription can screw up the sorting + ecomp[:subscribe] = [[fcomp.class.name,fcomp.name]] + + comp = newcomp("bflatten", ecomp, fcomp) + objects = nil + assert_nothing_raised { + objects = comp.flatten + } + + assert_equal(objects.length, 2, "Did not get two sorted objects") + objects.each { |o| + assert(o.is_a?(Puppet::Type), "Object %s is not a Type" % o.class) + } + + assert(objects[0] == file, "File was not first object") + assert(objects[1] == cmd, "Exec was not second object") + end + + def test_deepflatten2 + tmpfile = tempfile() + @@tmpfiles.push tmpfile + trans = nil + cmd = nil + File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| + of.puts rand(100) + } + file = Puppet::Type::PFile.create( + :path => tmpfile, + :checksum => "md5" + ) + assert_nothing_raised { + cmd = Puppet::Type::Exec.create( + :command => "pwd", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :refreshonly => true + ) + } + + ocmd = nil + assert_nothing_raised { + ocmd = Puppet::Type::Exec.create( + :command => "echo true", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :refreshonly => true + ) + } + + fcomp = newcomp("fflatten", file) + ecomp = newcomp("eflatten", cmd) + ocomp = newcomp("oflatten", ocmd) + + # this subscription can screw up the sorting + cmd[:subscribe] = [[fcomp.class.name,fcomp.name]] + ocmd[:subscribe] = [[cmd.class.name,cmd.name]] + + comp = newcomp("bflatten", ocomp, ecomp, fcomp) + objects = nil + assert_nothing_raised { + objects = comp.flatten + } + + assert_equal(objects.length, 3, "Did not get three sorted objects") + + objects.each { |o| + assert(o.is_a?(Puppet::Type), "Object %s is not a Type" % o.class) + } + + assert(objects[0] == file, "File was not first object") + assert(objects[1] == cmd, "Exec was not second object") + assert(objects[2] == ocmd, "Other exec was not second object") + end +end diff --git a/test/types/cron.rb b/test/types/cron.rb new file mode 100755 index 000000000..ffefba3c1 --- /dev/null +++ b/test/types/cron.rb @@ -0,0 +1,262 @@ +# Test cron job creation, modification, and destruction + +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppettest' +require 'puppet' +require 'puppet/type/cron' +require 'test/unit' +require 'facter' + +class TestExec < Test::Unit::TestCase + include TestPuppet + def setup + # retrieve the user name + id = %x{id}.chomp + if id =~ /uid=\d+\(([^\)]+)\)/ + @me = $1 + else + puts id + end + unless defined? @me + raise "Could not retrieve user name; 'id' did not work" + end + # god i'm lazy + @crontype = Puppet::Type::Cron + + super + end + + # Back up the user's existing cron tab if they have one. + def cronback + tab = nil + assert_nothing_raised { + tab = Puppet::Type::Cron.crontype.read(@me) + } + + if $? == 0 + @currenttab = tab + else + @currenttab = nil + end + end + + # Restore the cron tab to its original form. + def cronrestore + assert_nothing_raised { + if @currenttab + @crontype.crontype.write(@me, @currenttab) + else + @crontype.crontype.remove(@me) + end + } + end + + # Create a cron job with all fields filled in. + def mkcron(name) + cron = nil + assert_nothing_raised { + cron = @crontype.create( + :command => "date > %s/crontest%s" % [tmpdir(), name], + :name => name, + :user => @me, + :minute => rand(59), + :month => "1", + :monthday => "1", + :hour => "1" + ) + } + + return cron + end + + # Run the cron through its paces -- install it then remove it. + def cyclecron(cron) + name = cron.name + comp = newcomp(name, cron) + + trans = assert_events(comp, [:cron_created], name) + cron.retrieve + assert(cron.insync?) + trans = assert_events(comp, [], name) + cron[:command] = :notfound + trans = assert_events(comp, [:cron_deleted], name) + # the cron should no longer exist, not even in the comp + trans = assert_events(comp, [], name) + + assert(!comp.include?(cron), + "Cron is still a member of comp, after being deleted") + end + + # A simple test to see if we can load the cron from disk. + def test_load + assert_nothing_raised { + @crontype.retrieve(@me) + } + end + + # Test that a cron job turns out as expected, by creating one and generating + # it directly + def test_simple_to_cron + cron = nil + # make the cron + name = "yaytest" + assert_nothing_raised { + cron = @crontype.create( + :name => name, + :command => "date", + :user => @me + ) + } + str = nil + # generate the text + assert_nothing_raised { + str = cron.to_cron + } + assert_equal(str, "# Puppet Name: #{name}\n* * * * * date", + "Cron did not generate correctly") + end + + # Test that comments are correctly retained + def test_retain_comments + str = "# this is a comment\n#and another comment\n" + user = "fakeuser" + assert_nothing_raised { + @crontype.parse(user, str) + } + + assert_nothing_raised { + newstr = @crontype.tab(user) + assert_equal(str, newstr, "Cron comments were changed or lost") + } + end + + # Test that a specified cron job will be matched against an existing job + # with no name, as long as all fields match + def test_matchcron + str = "0,30 * * * * date\n" + + assert_nothing_raised { + @crontype.parse(@me, str) + } + + assert_nothing_raised { + cron = @crontype.create( + :name => "yaycron", + :minute => [0, 30], + :command => "date", + :user => @me + ) + } + + modstr = "# Puppet Name: yaycron\n%s" % str + + assert_nothing_raised { + newstr = @crontype.tab(@me) + assert_equal(modstr, newstr, "Cron was not correctly matched") + } + end + + # Test adding a cron when there is currently no file. + def test_mkcronwithnotab + cronback + Puppet::Type::Cron.crontype.remove(@me) + + cron = mkcron("crontest") + cyclecron(cron) + cronrestore + end + + def test_mkcronwithtab + cronback + Puppet::Type::Cron.crontype.remove(@me) + Puppet::Type::Cron.crontype.write(@me, +"1 1 1 1 * date > %s/crontesting\n" % testdir() + ) + + cron = mkcron("crontest") + cyclecron(cron) + cronrestore + end + + def test_makeandretrievecron + cronback + Puppet::Type::Cron.crontype.remove(@me) + + name = "storeandretrieve" + cron = mkcron(name) + comp = newcomp(name, cron) + trans = assert_events(comp, [:cron_created], name) + + cron = nil + + Puppet::Type::Cron.clear + Puppet::Type::Cron.retrieve(@me) + + assert(cron = Puppet::Type::Cron[name], "Could not retrieve named cron") + assert_instance_of(Puppet::Type::Cron, cron) + cronrestore + end + + # Do input validation testing on all of the parameters. + def test_arguments + values = { + :monthday => { + :valid => [ 1, 13, "1,30" ], + :invalid => [ -1, 0, 32 ] + }, + :weekday => { + :valid => [ 0, 3, 6, "1,2", "tue", "wed", + "Wed", "MOnday", "SaTurday" ], + :invalid => [ -1, 7, "1, 3", "tues", "teusday", "thurs" ] + }, + :hour => { + :valid => [ 0, 21, 23 ], + :invalid => [ -1, 24 ] + }, + :minute => { + :valid => [ 0, 34, 59 ], + :invalid => [ -1, 60 ] + }, + :month => { + :valid => [ 1, 11, 12, "mar", "March", "apr", "October", "DeCeMbEr" ], + :invalid => [ 0, 13, "marc", "sept" ] + } + } + + cron = mkcron("valtesting") + values.each { |param, hash| + hash.each { |type, values| + values.each { |value| + case type + when :valid: + assert_nothing_raised { + cron[param] = value + } + + if value.is_a?(Integer) + assert_equal([value], cron[param], + "Cron value was not set correctly") + end + when :invalid: + assert_raise(Puppet::Error, "%s is incorrectly a valid %s" % + [value, param]) { + cron[param] = value + } + end + + if value.is_a?(Integer) + value = value.to_s + redo + end + } + } + } + end +end + +# $Id$ diff --git a/test/types/exec.rb b/test/types/exec.rb new file mode 100755 index 000000000..99e120ea2 --- /dev/null +++ b/test/types/exec.rb @@ -0,0 +1,213 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppettest' +require 'test/unit' +require 'facter' + +# $Id$ + +class TestExec < Test::Unit::TestCase + include TestPuppet + def test_execution + command = nil + output = nil + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "/bin/echo" + ) + } + assert_nothing_raised { + command.evaluate + } + assert_nothing_raised { + output = command.sync + } + assert_equal([:executed_command],output) + end + + def test_numvsstring + command = nil + output = nil + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "/bin/echo", + :returns => 0 + ) + } + assert_nothing_raised { + command.evaluate + } + assert_nothing_raised { + output = command.sync + } + Puppet::Type::Exec.clear + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "/bin/echo", + :returns => "0" + ) + } + assert_nothing_raised { + command.evaluate + } + assert_nothing_raised { + output = command.sync + } + end + + def test_path_or_qualified + command = nil + output = nil + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "echo" + ) + assert_nil(command) + } + Puppet::Type::Exec.clear + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "echo", + :path => "/usr/bin:/bin:/usr/sbin:/sbin" + ) + } + Puppet::Type::Exec.clear + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "/bin/echo" + ) + } + Puppet::Type::Exec.clear + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "/bin/echo", + :path => "/usr/bin:/bin:/usr/sbin:/sbin" + ) + } + end + + def test_nonzero_returns + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "mkdir /this/directory/does/not/exist", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :returns => 1 + ) + } + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "touch /etc", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :returns => 1 + ) + } + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "thiscommanddoesnotexist", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :returns => 127 + ) + } + end + + def test_cwdsettings + command = nil + dir = "/tmp" + wd = Dir.chdir(dir) { + Dir.getwd + } + assert_nothing_raised { + command = Puppet::Type::Exec.create( + :command => "pwd", + :cwd => dir, + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :returns => 0 + ) + } + assert_nothing_raised { + command.evaluate + } + assert_nothing_raised { + command.sync + } + assert_equal(wd,command.output.chomp) + end + + def test_refreshonly + file = nil + cmd = nil + tmpfile = "/tmp/exectesting" + @@tmpfiles.push tmpfile + trans = nil + File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| + of.puts rand(100) + } + file = Puppet::Type::PFile.create( + :path => tmpfile, + :checksum => "md5" + ) + assert_nothing_raised { + cmd = Puppet::Type::Exec.create( + :command => "pwd", + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :subscribe => [[file.class.name,file.name]], + :refreshonly => true + ) + } + + comp = Puppet::Type::Component.create(:name => "RefreshTest") + [file,cmd].each { |obj| + comp.push obj + } + events = nil + assert_nothing_raised { + trans = comp.evaluate + + sum = file.state(:checksum) + assert_equal(sum.is, sum.should) + events = trans.evaluate.collect { |event| + event.event + } + } + # the first checksum shouldn't result in a changed file + assert_equal([],events) + File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| + of.puts rand(100) + of.puts rand(100) + of.puts rand(100) + } + assert_nothing_raised { + trans = comp.evaluate + sum = file.state(:checksum) + events = trans.evaluate.collect { |event| event.event } + } + + # verify that only the file_changed event was kicked off, not the + # command_executed + assert_equal( + [:file_modified], + events + ) + end + + def test_creates + file = tempfile() + exec = nil + assert_nothing_raised { + exec = Puppet::Type::Exec.create( + :command => "touch %s" % file, + :path => "/usr/bin:/bin:/usr/sbin:/sbin", + :creates => file + ) + } + + comp = newcomp("createstest", exec) + assert_events(comp, [:executed_command], "creates") + assert_events(comp, [], "creates") + end +end diff --git a/test/types/file.rb b/test/types/file.rb new file mode 100644 index 000000000..713dd96c1 --- /dev/null +++ b/test/types/file.rb @@ -0,0 +1,502 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'test/unit' +require 'fileutils' +require 'puppettest' + +class TestFile < Test::Unit::TestCase + include FileTesting + # hmmm + # this is complicated, because we store references to the created + # objects in a central store + def mkfile(hash) + file = nil + assert_nothing_raised { + file = Puppet::Type::PFile.create(hash) + } + return file + end + + def mktestfile + # because luke's home directory is on nfs, it can't be used for testing + # as root + tmpfile = tempfile() + File.open(tmpfile, "w") { |f| f.puts rand(100) } + @@tmpfiles.push tmpfile + mkfile(:name => tmpfile) + end + + def setup + begin + initstorage + rescue + system("rm -rf %s" % Puppet[:checksumfile]) + end + super + end + + def teardown + clearstorage + Puppet::Storage.clear + super + end + + def initstorage + Puppet::Storage.init + Puppet::Storage.load + end + + def clearstorage + Puppet::Storage.store + Puppet::Storage.clear + end + + def test_owner + file = mktestfile() + + users = {} + count = 0 + + # collect five users + Etc.passwd { |passwd| + if count > 5 + break + else + count += 1 + end + users[passwd.uid] = passwd.name + } + + fake = {} + # find a fake user + while true + a = rand(1000) + begin + Etc.getpwuid(a) + rescue + fake[a] = "fakeuser" + break + end + end + + uid, name = users.shift + us = {} + us[uid] = name + users.each { |uid, name| + # just make sure we don't try to manage users + assert_nothing_raised() { + file.sync + } + assert_nothing_raised() { + file[:owner] = name + } + assert_nothing_raised() { + file.retrieve + } + assert_nothing_raised() { + file.sync + } + } + end + + def test_zgroup + file = mktestfile() + [%x{groups}.chomp.split(/ /), Process.groups].flatten.each { |group| + assert_nothing_raised() { + file[:group] = group + } + assert(file.state(:group)) + assert(file.state(:group).should) + } + end + + if Process.uid == 0 + def test_ownerasroot + file = mktestfile() + + users = {} + count = 0 + + # collect five users + Etc.passwd { |passwd| + if count > 5 + break + else + count += 1 + end + users[passwd.uid] = passwd.name + } + + fake = {} + # find a fake user + while true + a = rand(1000) + begin + Etc.getpwuid(a) + rescue + fake[a] = "fakeuser" + break + end + end + + users.each { |uid, name| + assert_nothing_raised() { + file[:owner] = name + } + changes = [] + assert_nothing_raised() { + changes << file.evaluate + } + assert(changes.length > 0) + assert_nothing_raised() { + file.sync + } + assert_nothing_raised() { + file.evaluate + } + assert(file.insync?()) + assert_nothing_raised() { + file[:owner] = uid + } + assert_nothing_raised() { + file.evaluate + } + # make sure changing to number doesn't cause a sync + assert(file.insync?()) + } + + fake.each { |uid, name| + assert_raise(Puppet::Error) { + file[:owner] = name + } + assert_raise(Puppet::Error) { + file[:owner] = uid + } + } + end + + def test_groupasroot + file = mktestfile() + [%x{groups}.chomp.split(/ /), Process.groups].flatten.each { |group| + assert_nothing_raised() { + file[:group] = group + } + assert(file.state(:group)) + assert(file.state(:group).should) + assert_nothing_raised() { + file.evaluate + } + assert_nothing_raised() { + file.sync + } + assert_nothing_raised() { + file.evaluate + } + assert(file.insync?()) + assert_nothing_raised() { + file.delete(:group) + } + } + end + else + $stderr.puts "Run as root for complete owner and group testing" + end + + def test_create + %w{a b c d}.collect { |name| "/tmp/createst%s" % name }.each { |path| + file =nil + assert_nothing_raised() { + file = Puppet::Type::PFile.create( + :name => path, + :create => true + ) + } + assert_nothing_raised() { + file.evaluate + } + assert_nothing_raised() { + file.sync + } + assert_nothing_raised() { + file.evaluate + } + assert(file.insync?()) + assert(FileTest.file?(path)) + @@tmpfiles.push path + } + end + + def test_create_dir + %w{a b c d}.collect { |name| "/tmp/createst%s" % name }.each { |path| + file = nil + assert_nothing_raised() { + file = Puppet::Type::PFile.create( + :name => path, + :create => "directory" + ) + } + assert_nothing_raised() { + file.evaluate + } + assert_nothing_raised() { + file.sync + } + assert_nothing_raised() { + file.evaluate + } + assert(file.insync?()) + assert(FileTest.directory?(path)) + @@tmpfiles.push path + } + end + + def test_modes + file = mktestfile + [0644,0755,0777,0641].each { |mode| + assert_nothing_raised() { + file[:mode] = mode + } + assert_nothing_raised() { + file.evaluate + } + assert_nothing_raised() { + file.sync + } + assert_nothing_raised() { + file.evaluate + } + assert(file.insync?()) + assert_nothing_raised() { + file.delete(:mode) + } + } + end + + def test_checksums + types = %w{md5 md5lite timestamp time} + exists = "/tmp/sumtest-exists" + nonexists = "/tmp/sumtest-nonexists" + + @@tmpfiles << exists + @@tmpfiles << nonexists + + # try it both with files that exist and ones that don't + files = [exists, nonexists] + initstorage + File.open(exists,"w") { |of| + 10.times { + of.puts rand(100) + } + } + types.each { |type| + files.each { |path| + if Puppet[:debug] + Puppet.info "Testing %s on %s" % [type,path] + end + file = nil + events = nil + # okay, we now know that we have a file... + assert_nothing_raised() { + file = Puppet::Type::PFile.create( + :name => path, + :create => true, + :checksum => type + ) + } + comp = Puppet::Type::Component.create( + :name => "componentfile" + ) + comp.push file + trans = nil + assert_nothing_raised() { + trans = comp.evaluate + } + + if file.name !~ /nonexists/ + sum = file.state(:checksum) + assert_equal(sum.is, sum.should) + assert(sum.insync?) + end + + assert_nothing_raised() { + events = trans.evaluate.collect { |e| e.event } + } + # we don't want to kick off an event the first time we + # come across a file + assert( + ! events.include?(:file_modified) + ) + assert_nothing_raised() { + File.open(path,"w") { |of| + of.puts rand(100) + } + } + Puppet::Type::PFile.clear + Puppet::Type::Component.clear + sleep 1 + + # now recreate the file + assert_nothing_raised() { + file = Puppet::Type::PFile.create( + :name => path, + :checksum => type + ) + } + comp = Puppet::Type::Component.create( + :name => "componentfile" + ) + comp.push file + trans = nil + assert_nothing_raised() { + trans = comp.evaluate + } + assert_nothing_raised() { + events = trans.evaluate.collect { |e| e.event } + } + + sum = file.state(:checksum) + + # verify that we're actually getting notified when a file changes + assert( + events.include?(:file_modified) + ) + assert_nothing_raised() { + Puppet::Type::PFile.clear + Puppet::Type::Component.clear + } + } + } + end + + def cyclefile(path) + # i had problems with using :name instead of :path + [:name,:path].each { |param| + file = nil + changes = nil + comp = nil + trans = nil + + initstorage + assert_nothing_raised { + file = Puppet::Type::PFile.create( + param => path, + :recurse => true, + :checksum => "md5" + ) + } + comp = Puppet::Type::Component.create( + :name => "component" + ) + comp.push file + assert_nothing_raised { + trans = comp.evaluate + } + assert_nothing_raised { + trans.evaluate + } + #assert_nothing_raised { + # file.sync + #} + clearstorage + Puppet::Type.allclear + } + end + + def test_recursion + path = "/tmp/filerecursetest" + @@tmpfiles.push path + tmpfile = File.join(path,"testing") + system("mkdir -p #{path}") + cyclefile(path) + File.open(tmpfile, File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "yayness" + } + cyclefile(path) + File.open(tmpfile, File::WRONLY|File::APPEND) { |of| + of.puts "goodness" + } + cyclefile(path) + end + +=begin + def test_ignore + + end +=end + + # XXX disabled until i change how dependencies work + def disabled_test_recursionwithcreation + path = "/tmp/this/directory/structure/does/not/exist" + @@tmpfiles.push "/tmp/this" + + file = nil + assert_nothing_raised { + file = mkfile( + :name => path, + :recurse => true, + :create => true + ) + } + + trans = nil + comp = newcomp("recursewithfiles", file) + assert_nothing_raised { + trans = comp.evaluate + } + + events = nil + assert_nothing_raised { + events = trans.evaluate.collect { |e| e.event.to_s } + } + + puts "events are %s" % events.join(", ") + end + + def test_filetype_retrieval + file = nil + + Puppet.err tmpdir() + assert_nothing_raised { + file = Puppet::Type::PFile.create( + :name => tmpdir(), + :check => :type + ) + } + + assert_nothing_raised { + file.evaluate + } + + assert_equal("directory", file.state(:type).is) + + assert_nothing_raised { + file = Puppet::Type::PFile.create( + :name => "/etc/passwd", + :check => :type + ) + } + + assert_nothing_raised { + file.evaluate + } + + assert_equal("file", file.state(:type).is) + + assert_raise(Puppet::Error) { + file[:type] = "directory" + } + + assert(file.insync?) + + assert_raise(Puppet::Error) { + file.sync + } + end +end + +# $Id$ diff --git a/test/types/filebucket.rb b/test/types/filebucket.rb new file mode 100755 index 000000000..a5c8e0c78 --- /dev/null +++ b/test/types/filebucket.rb @@ -0,0 +1,167 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'test/unit' +require 'fileutils' +require 'puppettest' + +# $Id$ + +class TestFileBucket < Test::Unit::TestCase + include FileTesting + # hmmm + # this is complicated, because we store references to the created + # objects in a central store + def mkfile(hash) + file = nil + assert_nothing_raised { + file = Puppet::Type::PFile.create(hash) + } + return file + end + + def mkbucket(name,path) + bucket = nil + assert_nothing_raised { + bucket = Puppet::Type::PFileBucket.create( + :name => name, + :path => path + ) + } + + @@tmpfiles.push path + + return bucket + end + + def mktestfile + # because luke's home directory is on nfs, it can't be used for testing + # as root + tmpfile = tempfile() + File.open(tmpfile, "w") { |f| f.puts rand(100) } + @@tmpfiles.push tmpfile + mkfile(:name => tmpfile) + end + + def setup + super + begin + initstorage + rescue + system("rm -rf %s" % Puppet[:checksumfile]) + end + end + + def teardown + super + clearstorage + end + + def initstorage + Puppet::Storage.init + Puppet::Storage.load + end + + def clearstorage + Puppet::Storage.store + Puppet::Storage.clear + end + + def test_simplebucket + name = "yayness" + mkbucket("yayness", "/tmp/filebucket") + + bucket = nil + assert_nothing_raised { + bucket = Puppet::Type::PFileBucket.bucket(name) + } + + assert_instance_of(Puppet::Client::Dipper, bucket) + + md5 = nil + newpath = "/tmp/passwd" + @@tmpfiles << newpath + system("cp /etc/passwd %s" % newpath) + assert_nothing_raised { + md5 = bucket.backup(newpath) + } + + assert(md5) + + newmd5 = nil + + File.open(newpath, "w") { |f| f.puts ";lkjasdf;lkjasdflkjwerlkj134lkj" } + + assert_nothing_raised { + newmd5 = bucket.backup(newpath) + } + + assert(md5 != newmd5) + + assert_nothing_raised { + bucket.restore(newpath, md5) + } + + File.open(newpath) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } + + assert_equal(md5, newmd5) + end + + def test_fileswithbuckets + name = "yayness" + mkbucket("yayness", "/tmp/filebucket") + + bucket = nil + assert_nothing_raised { + bucket = Puppet::Type::PFileBucket.bucket(name) + } + + file = mktestfile() + assert_nothing_raised { + file[:backup] = ["filebucket", name] + } + + opath = "/tmp/anotherbuckettest" + @@tmpfiles << opath + system("cp /etc/passwd %s" % opath) + + origmd5 = File.open(file.name) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } + + file[:source] = opath + #assert_nothing_raised { + # file[:backup] = true + #} + + comp = newcomp("yaytest", file) + + trans = nil + assert_nothing_raised { + trans = comp.evaluate + } + events = nil + assert_nothing_raised { + events = trans.evaluate.collect { |e| e.event } + } + + # so, we've now replaced the file with the opath file + assert_equal( + File.open(opath) { |f| newmd5 = Digest::MD5.hexdigest(f.read) }, + File.open(file.name) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } + ) + + assert_nothing_raised { + bucket.restore(file.name, origmd5) + } + + assert_equal( + origmd5, + File.open(file.name) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } + ) + + + end +end diff --git a/test/types/fileignoresource.rb b/test/types/fileignoresource.rb new file mode 100644 index 000000000..f3d258381 --- /dev/null +++ b/test/types/fileignoresource.rb @@ -0,0 +1,287 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $:.unshift "../../../../language/trunk/lib" + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'cgi' +require 'test/unit' +require 'fileutils' +require 'puppettest' + +# $Id: $ + +class TestFileIgnoreSources < Test::Unit::TestCase + include FileTesting + + def setup + begin + initstorage + rescue + system("rm -rf %s" % Puppet[:checksumfile]) + end + super + end + + def teardown + clearstorage + super + end + +#This is not needed unless using md5 (correct me if I'm wrong) + def initstorage + Puppet::Storage.init + Puppet::Storage.load + end + + def clearstorage + Puppet::Storage.store + Puppet::Storage.clear + end + + def test_ignore_simple_source + + #Temp directory to run tests in + path = "/tmp/Fileignoresourcetest" + @@tmpfiles.push path + + #source directory + sourcedir = "sourcedir" + sourcefile1 = "sourcefile1" + sourcefile2 = "sourcefile2" + + frompath = File.join(path,sourcedir) + FileUtils.mkdir_p frompath + + topath = File.join(path,"destdir") + FileUtils.mkdir topath + + #initialize variables before block + tofile = nil + trans = nil + + #create source files + + File.open(File.join(frompath,sourcefile1), + File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "yayness" + } + + File.open(File.join(frompath,sourcefile2), + File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "even yayer" + } + + + #makes Puppet file Object + assert_nothing_raised { + tofile = Puppet::Type::PFile.create( + :name => topath, + :source => frompath, + :recurse => true, + :ignore => "sourcefile2" + ) + } + + #make a component and adds the file + comp = Puppet::Type::Component.create( + :name => "component" + ) + comp.push tofile + + #make, evaluate transaction and sync the component + assert_nothing_raised { + trans = comp.evaluate + } + assert_nothing_raised { + trans.evaluate + } + + + #topath should exist as a directory with sourcedir as a directory + + #This file should exist + assert(FileTest.exists?(File.join(topath,sourcefile1))) + + #This file should not + assert(!(FileTest.exists?(File.join(topath,sourcefile2)))) + + Puppet::Type.allclear + end + + def test_ignore_with_wildcard + #Temp directory to run tests in + path = "/tmp/Fileignoresourcetest" + @@tmpfiles.push path + + #source directory + sourcedir = "sourcedir" + subdir = "subdir" + subdir2 = "subdir2" + sourcefile1 = "sourcefile1" + sourcefile2 = "sourcefile2" + + frompath = File.join(path,sourcedir) + FileUtils.mkdir_p frompath + + FileUtils.mkdir_p(File.join(frompath, subdir)) + FileUtils.mkdir_p(File.join(frompath, subdir2)) + dir = Dir.glob(File.join(path,"**/*")) + + topath = File.join(path,"destdir") + FileUtils.mkdir topath + + #initialize variables before block + tofile = nil + trans = nil + + #create source files + + dir.each { |dir| + File.open(File.join(dir,sourcefile1), + File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "yayness" + } + + File.open(File.join(dir,sourcefile2), + File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "even yayer" + } + + } + + #makes Puppet file Object + assert_nothing_raised { + tofile = Puppet::Type::PFile.create( + :name => topath, + :source => frompath, + :recurse => true, + :ignore => "*2" + ) + } + + #make a component and adds the file + comp = Puppet::Type::Component.create( + :name => "component" + ) + comp.push tofile + + #make, evaluate transaction and sync the component + assert_nothing_raised { + trans = comp.evaluate + } + assert_nothing_raised { + trans.evaluate + } + + #topath should exist as a directory with sourcedir as a directory + + #This file should exist + assert(FileTest.exists?(File.join(topath,sourcefile1))) + assert(FileTest.exists?(File.join(topath,subdir))) + assert(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile1))) + #This file should not + assert(!(FileTest.exists?(File.join(topath,sourcefile2)))) + assert(!(FileTest.exists?(File.join(topath,subdir2)))) + assert(!(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile2)))) + Puppet::Type.allclear + + end + + def test_ignore_array + #Temp directory to run tests in + path = "/tmp/Fileignoresourcetest" + @@tmpfiles.push path + + #source directory + sourcedir = "sourcedir" + subdir = "subdir" + subdir2 = "subdir2" + subdir3 = "anotherdir" + sourcefile1 = "sourcefile1" + sourcefile2 = "sourcefile2" + + frompath = File.join(path,sourcedir) + FileUtils.mkdir_p frompath + + FileUtils.mkdir_p(File.join(frompath, subdir)) + FileUtils.mkdir_p(File.join(frompath, subdir2)) + FileUtils.mkdir_p(File.join(frompath, subdir3)) + sourcedir = Dir.glob(File.join(path,"**/*")) + + topath = File.join(path,"destdir") + FileUtils.mkdir topath + + #initialize variables before block + tofile = nil + trans = nil + + #create source files + + + + sourcedir.each { |dir| + File.open(File.join(dir,sourcefile1), + File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "yayness" + } + + File.open(File.join(dir,sourcefile2), + File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "even yayer" + } + + } + + + #makes Puppet file Object + assert_nothing_raised { + tofile = Puppet::Type::PFile.create( + :name => topath, + :source => frompath, + :recurse => true, + :ignore => ["*2", "an*"] + # :ignore => ["*2", "an*", "nomatch"] + ) + } + + #make a component and adds the file + comp = Puppet::Type::Component.create( + :name => "component" + ) + comp.push tofile + + #make, evaluate transaction and sync the component + assert_nothing_raised { + trans = comp.evaluate + } + assert_nothing_raised { + trans.evaluate + } + + #topath should exist as a directory with sourcedir as a directory + + # This file should exist + # proper files in destination + assert(FileTest.exists?(File.join(topath,sourcefile1)), "file1 not in destdir") + assert(FileTest.exists?(File.join(topath,subdir)), "subdir1 not in destdir") + assert(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile1)), "file1 not in subdir") + # proper files in source + assert(FileTest.exists?(File.join(frompath,subdir)), "subdir not in source") + assert(FileTest.exists?(File.join(frompath,subdir2)), "subdir2 not in source") + assert(FileTest.exists?(File.join(frompath,subdir3)), "subdir3 not in source") + + # This file should not + assert(!(FileTest.exists?(File.join(topath,sourcefile2))), "file2 in dest") + assert(!(FileTest.exists?(File.join(topath,subdir2))), "subdir2 in dest") + assert(!(FileTest.exists?(File.join(topath,subdir3))), "anotherdir in dest") + assert(!(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile2))), "file2 in dest/sub") + + + Puppet::Type.allclear + + end + +end diff --git a/test/types/filesources.rb b/test/types/filesources.rb new file mode 100755 index 000000000..46542d76c --- /dev/null +++ b/test/types/filesources.rb @@ -0,0 +1,532 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $:.unshift "../../../../language/trunk/lib" + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'cgi' +require 'test/unit' +require 'fileutils' +require 'puppettest' + +class TestFileSources < Test::Unit::TestCase + include FileTesting + def setup + begin + initstorage + rescue + system("rm -rf %s" % Puppet[:checksumfile]) + end + if defined? @port + @port += 1 + else + @port = 8800 + end + super + end + + def teardown + clearstorage + super + end + + def initstorage + Puppet::Storage.init + Puppet::Storage.load + end + + def clearstorage + Puppet::Storage.store + Puppet::Storage.clear + end + + def test_newchild + path = "/tmp/newchilddir" + @@tmpfiles.push path + + FileUtils.mkdir_p path + File.open(File.join(path,"childtest"), "w") { |of| + of.puts "yayness" + } + file = nil + comp = nil + trans = nil + assert_nothing_raised { + file = Puppet::Type::PFile.create( + :name => path + ) + } + child = nil + assert_nothing_raised { + child = file.newchild("childtest") + } + assert(child) + assert_raise(Puppet::DevError) { + file.newchild(File.join(path,"childtest")) + } + end + + def test_simplelocalsource + path = "/tmp/Filesourcetest" + @@tmpfiles.push path + FileUtils.mkdir_p path + frompath = File.join(path,"source") + topath = File.join(path,"dest") + fromfile = nil + tofile = nil + trans = nil + + File.open(frompath, File::WRONLY|File::CREAT|File::APPEND) { |of| + of.puts "yayness" + } + assert_nothing_raised { + tofile = Puppet::Type::PFile.create( + :name => topath, + :source => frompath + ) + } + comp = Puppet::Type::Component.create( + :name => "component" + ) + comp.push tofile + assert_nothing_raised { + trans = comp.evaluate + } + assert_nothing_raised { + trans.evaluate + } + # assert_nothing_raised { + # comp.sync + # } + + assert(FileTest.exists?(topath)) + from = File.open(frompath) { |o| o.read } + to = File.open(topath) { |o| o.read } + assert_equal(from,to) + @@tmpfiles.push path + end + + def recursive_source_test(fromdir, todir) + Puppet::Type.allclear + initstorage + tofile = nil + trans = nil + + assert_nothing_raised { + tofile = Puppet::Type::PFile.create( + :name => todir, + "recurse" => true, + "backup" => false, + "source" => fromdir + ) + } + comp = Puppet::Type::Component.create( + :name => "component" + ) + comp.push tofile + assert_nothing_raised { + trans = comp.evaluate + } + assert_nothing_raised { + trans.evaluate + } + + assert(FileTest.exists?(todir)) + Puppet::Type.allclear + end + + def run_complex_sources(networked = false) + path = "/tmp/ComplexSourcesTest" + @@tmpfiles.push path + + # first create the source directory + FileUtils.mkdir_p path + + + # okay, let's create a directory structure + fromdir = File.join(path,"fromdir") + Dir.mkdir(fromdir) + FileUtils.cd(fromdir) { + mkranddirsandfiles() + } + + todir = File.join(path, "todir") + source = fromdir + if networked + source = "puppet://localhost/%s%s" % [networked, fromdir] + end + recursive_source_test(source, todir) + + return [fromdir,todir] + end + + def test_complex_sources_twice + fromdir, todir = run_complex_sources + assert_trees_equal(fromdir,todir) + recursive_source_test(fromdir, todir) + assert_trees_equal(fromdir,todir) + end + + def test_sources_with_deleted_destfiles + fromdir, todir = run_complex_sources + # then delete some files + assert(FileTest.exists?(todir)) + missing_files = delete_random_files(todir) + + # and run + recursive_source_test(fromdir, todir) + + missing_files.each { |file| + assert(FileTest.exists?(file), "Deleted file %s is still missing" % file) + } + + # and make sure they're still equal + assert_trees_equal(fromdir,todir) + end + + def test_sources_with_readonly_destfiles + fromdir, todir = run_complex_sources + assert(FileTest.exists?(todir)) + readonly_random_files(todir) + recursive_source_test(fromdir, todir) + + # and make sure they're still equal + assert_trees_equal(fromdir,todir) + end + + def test_sources_with_modified_dest_files + fromdir, todir = run_complex_sources + + assert(FileTest.exists?(todir)) + # then modify some files + modify_random_files(todir) + + recursive_source_test(fromdir, todir) + + # and make sure they're still equal + assert_trees_equal(fromdir,todir) + end + + def test_sources_with_added_destfiles + fromdir, todir = run_complex_sources + assert(FileTest.exists?(todir)) + # and finally, add some new files + add_random_files(todir) + + recursive_source_test(fromdir, todir) + + fromtree = file_list(fromdir) + totree = file_list(todir) + + assert(fromtree != totree) + + # then remove our new files + FileUtils.cd(todir) { + %x{find . 2>/dev/null}.chomp.split(/\n/).each { |file| + if file =~ /file[0-9]+/ + File.unlink(file) + end + } + } + + # and make sure they're still equal + assert_trees_equal(fromdir,todir) + end + + def test_RecursionWithAddedFiles + basedir = "/tmp/recursionplussaddedfiles" + Dir.mkdir(basedir) + @@tmpfiles << basedir + file1 = File.join(basedir, "file1") + file2 = File.join(basedir, "file2") + subdir1 = File.join(basedir, "subdir1") + file3 = File.join(subdir1, "file") + File.open(file1, "w") { |f| 3.times { f.print rand(100) } } + rootobj = nil + assert_nothing_raised { + rootobj = Puppet::Type::PFile.create( + :name => basedir, + :recurse => true, + :check => %w{type owner} + ) + + rootobj.evaluate + } + + klass = Puppet::Type::PFile + assert(klass[basedir]) + assert(klass[file1]) + assert_nil(klass[file2]) + + File.open(file2, "w") { |f| 3.times { f.print rand(100) } } + + assert_nothing_raised { + rootobj.evaluate + } + assert(klass[file2]) + + Dir.mkdir(subdir1) + File.open(file3, "w") { |f| 3.times { f.print rand(100) } } + + assert_nothing_raised { + rootobj.evaluate + } + assert(klass[file3]) + end + + def mkfileserverconf(mounts) + file = "/tmp/fileserverconftestingfile%s" % rand(100) + File.open(file, "w") { |f| + mounts.each { |path, name| + f.puts "[#{name}]\n\tpath #{path}\n\tallow *\n" + } + } + + @@tmpfiles << file + return file + end + + # test raw xmlrpc calls + # this test is disabled because it requires way too much setup to get + # the certificates correct + def disabled_test_SimpleNetworkSources + server = nil + basedir = "/tmp/simplenetworksourcetesting" + @@tmpfiles << basedir + + mounts = { + "/" => "root" + } + + fileserverconf = mkfileserverconf(mounts) + + if File.exists?(basedir) + system("rm -rf %s" % basedir) + end + Dir.mkdir(basedir) + + Puppet[:puppetconf] = basedir + Puppet[:puppetvar] = basedir + Puppet[:autosign] = true + + tmpname = "yaytesting" + tmpfile = File.join(basedir, tmpname) + File.open(tmpfile, "w") { |f| f.print rand(100) } + + port = 8765 + serverpid = nil + assert_nothing_raised() { + server = Puppet::Server.new( + :Port => port, + :Handlers => { + :CA => {}, # so that certs autogenerate + :FileServer => { + :Config => fileserverconf + } + } + ) + + } + serverpid = fork { + assert_nothing_raised() { + #trap(:INT) { server.shutdown; Kernel.exit! } + trap(:INT) { server.shutdown } + server.start + } + } + @@tmppids << serverpid + + client = nil + assert_nothing_raised() { + client = XMLRPC::Client.new("localhost", "/RPC2", port, nil, nil, + nil, nil, true, 3) + } + retval = nil + + sleep(1) + + list = nil + rpath = "/root%s" % tmpfile + assert_nothing_raised { + list = client.call("fileserver.list", rpath, false, false) + } + + assert_equal("/\tfile", list) + + assert_nothing_raised { + list = client.call("fileserver.describe", rpath) + } + + assert_match(/^\d+\tfile\t\d+\t\d+\t.+$/, list) + + assert_nothing_raised { + list = client.call("fileserver.retrieve", rpath) + } + + contents = File.read(tmpfile) + assert_equal(contents, CGI.unescape(list)) + + assert_nothing_raised { + system("kill -INT %s" % serverpid) + } + end + + def test_NetworkSources + server = nil + basedir = "/tmp/networksourcetesting" + @@tmpfiles << basedir + if File.exists?(basedir) + system("rm -rf %s" % basedir) + end + Dir.mkdir(basedir) + + mounts = { + "/" => "root" + } + + fileserverconf = mkfileserverconf(mounts) + + Puppet[:puppetconf] = basedir + Puppet[:puppetvar] = basedir + Puppet[:autosign] = true + + Puppet[:masterport] = 8762 + + serverpid = nil + assert_nothing_raised() { + server = Puppet::Server.new( + :Handlers => { + :CA => {}, # so that certs autogenerate + :FileServer => { + :Config => fileserverconf + } + } + ) + + } + serverpid = fork { + assert_nothing_raised() { + #trap(:INT) { server.shutdown; Kernel.exit! } + trap(:INT) { server.shutdown } + server.start + } + } + @@tmppids << serverpid + + sleep(1) + + fromdir, todir = run_complex_sources("root") + assert_trees_equal(fromdir,todir) + recursive_source_test(fromdir, todir) + assert_trees_equal(fromdir,todir) + + assert_nothing_raised { + system("kill -INT %s" % serverpid) + } + end + + def test_networkSourcesWithoutService + server = nil + + Puppet[:autosign] = true + Puppet[:masterport] = 8765 + + serverpid = nil + assert_nothing_raised() { + server = Puppet::Server.new( + :Handlers => { + :CA => {}, # so that certs autogenerate + } + ) + + } + serverpid = fork { + assert_nothing_raised() { + #trap(:INT) { server.shutdown; Kernel.exit! } + trap(:INT) { server.shutdown } + server.start + } + } + @@tmppids << serverpid + + sleep(1) + + name = File.join(tmpdir(), "nosourcefile") + file = Puppet::Type::PFile.create( + :source => "puppet://localhost/dist/file", + :name => name + ) + + assert_nothing_raised { + file.retrieve + } + + comp = newcomp("nosource", file) + + assert_nothing_raised { + comp.evaluate + } + + assert(!FileTest.exists?(name), "File with no source exists anyway") + end + + def test_unmountedNetworkSources + server = nil + mounts = { + "/" => "root", + "/noexistokay" => "noexist" + } + + fileserverconf = mkfileserverconf(mounts) + + Puppet[:autosign] = true + Puppet[:masterport] = @port + + serverpid = nil + assert_nothing_raised() { + server = Puppet::Server.new( + :Port => @port, + :Handlers => { + :CA => {}, # so that certs autogenerate + :FileServer => { + :Config => fileserverconf + } + } + ) + + } + + serverpid = fork { + assert_nothing_raised() { + #trap(:INT) { server.shutdown; Kernel.exit! } + trap(:INT) { server.shutdown } + server.start + } + } + @@tmppids << serverpid + + sleep(1) + + name = File.join(tmpdir(), "nosourcefile") + file = Puppet::Type::PFile.create( + :source => "puppet://localhost/noexist/file", + :name => name + ) + + assert_nothing_raised { + file.retrieve + } + + comp = newcomp("nosource", file) + + assert_nothing_raised { + comp.evaluate + } + + assert(!FileTest.exists?(name), "File with no source exists anyway") + end +end + +# $Id$ diff --git a/test/types/filetype.rb b/test/types/filetype.rb new file mode 100644 index 000000000..c6749ba3d --- /dev/null +++ b/test/types/filetype.rb @@ -0,0 +1,162 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'puppet/type/typegen/filetype' +require 'puppet/type/typegen/filerecord' +require 'test/unit' + +# $Id$ + +#class TestFileType < Test::Unit::TestCase +class TestFileType + def disabled_setup + Puppet[:loglevel] = :debug if __FILE__ == $0 + + @passwdtype = Puppet::Type::FileType["passwd"] + if @passwdtype.nil? + assert_nothing_raised() { + @passwdtype = Puppet::Type::FileType.createtype( + :name => "passwd" + ) + @passwdtype.addrecord( + :name => "user", + :splitchar => ":", + :fields => %w{name password uid gid gcos home shell} + ) + } + end + + @syslogtype = Puppet::Type::FileType["syslog"] + if @syslogtype.nil? + assert_nothing_raised() { + @syslogtype = Puppet::Type::FileType.createtype( + :escapednewlines => true, + :name => "syslog" + ) + @syslogtype.addrecord( + :name => "data", + :regex => %r{^([^#\s]+)\s+(\S+)$}, + :joinchar => "\t", + :fields => %w{logs dest} + ) + @syslogtype.addrecord( + :name => "comment", + :regex => %r{^(#.*)$}, + :joinchar => "", # not really necessary... + :fields => %w{comment} + ) + @syslogtype.addrecord( + :name => "blank", + :regex => %r{^(\s*)$}, + :joinchar => "", # not really necessary... + :fields => %w{blank} + ) + } + end + + end + + def disabled_test_passwd1_nochange + file = nil + type = nil + assert_nothing_raised() { + file = @passwdtype.new("/etc/passwd") + } + assert_nothing_raised() { + file.retrieve + } + + assert(file.insync?) + + contents = "" + ::File.open("/etc/passwd") { |ofile| + ofile.each { |line| + contents += line + } + } + + assert_equal( + contents, + file.to_s + ) + + end + + def disabled_test_passwd2_change + file = nil + type = nil + Kernel.system("cp /etc/passwd /tmp/oparsepasswd") + assert_nothing_raised() { + file = @passwdtype.new("/tmp/oparsepasswd") + } + assert_nothing_raised() { + file.retrieve + } + + assert(file.insync?) + + assert_nothing_raised() { + file.add("user") { |obj| + obj["name"] = "yaytest" + obj["password"] = "x" + obj["uid"] = "10000" + obj["gid"] = "10000" + obj["home"] = "/home/yaytest" + obj["gcos"] = "The Yaytest" + obj["shell"] = "/bin/sh" + } + } + + assert(!file.insync?) + + assert_nothing_raised() { + file.sync + } + + assert(file.insync?) + + assert_nothing_raised() { + file.delete("bin") + } + + assert(!file.insync?) + + assert_nothing_raised() { + file.sync + } + + assert(file.insync?) + + Kernel.system("rm /tmp/oparsepasswd") + end + + def disabled_test_syslog_nochange + file = nil + type = nil + syslog = File.join($puppetbase, "examples/root/etc/debian-syslog.conf") + assert_nothing_raised() { + file = @syslogtype.new(syslog) + } + assert_nothing_raised() { + file.retrieve + } + + assert(file.insync?) + + contents = "" + ::File.open(syslog) { |ofile| + ofile.each { |line| + contents += line + } + } + #assert_equal( + # contents, + # file.to_s + #) + + end +end diff --git a/test/types/group.rb b/test/types/group.rb new file mode 100755 index 000000000..dd705b6e5 --- /dev/null +++ b/test/types/group.rb @@ -0,0 +1,247 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +# $Id$ + +require 'etc' +require 'puppet/type' +require 'puppettest' +require 'test/unit' + +class TestGroup < Test::Unit::TestCase + include TestPuppet + def setup + @@tmpgroups = [] + super + end + + def teardown + Puppet::Type::Group.clear + @@tmpgroups.each { |group| + unless missing?(group) + remove(group) + end + } + super + end + + case Facter["operatingsystem"].value + when "Darwin": + def missing?(group) + output = %x{nidump -r /groups/#{group} / 2>/dev/null}.chomp + + if output == "" + return true + else + return false + end + + assert_equal("", output, "Group %s is present:\n%s" % [group, output]) + end + + def gid(name) + %x{nireport / /groups name gid}.split("\n").each { |line| + group, id = line.chomp.split(/\s+/) + if group == name + return Integer(id) + end + } + + return nil + end + + def remove(group) + system("niutil -destroy / /groups/%s" % group) + end + else + def missing?(group) + begin + obj = Etc.getgrnam(group) + return false + rescue ArgumentError + return true + end + end + + def gid(name) + assert_nothing_raised { + obj = Etc.getgrnam(name) + return obj.gid + } + + return nil + end + + def remove(group) + system("groupdel %s" % group) + end + end + + def groupnames + %x{groups}.chomp.split(/ /) + end + + def groupids + Process.groups + end + + def attrtest_gid(group) + obj = nil + #assert_nothing_raised { + # obj = Etc.getgrnam(group[:name]) + #} + group.retrieve + old = gid(group[:name]) + comp = newcomp("gidtest", group) + + group[:gid] = old + + trans = assert_events(comp, [], "group") + + newgid = old + while true + newgid += 1 + + if newgid - old > 1000 + $stderr.puts "Could not find extra test UID" + return + end + begin + Etc.getgrgid(newgid) + rescue ArgumentError => detail + break + end + end + + assert_nothing_raised("Failed to change group id") { + group[:gid] = newgid + } + + trans = assert_events(comp, [:group_modified], "group") + + curgid = nil + assert_nothing_raised { + curgid = gid(group[:name]) + } + + assert_equal(newgid, curgid, "GID was not changed") + + assert_rollback_events(trans, [:group_modified], "group") + + assert_nothing_raised { + curgid = gid(group[:name]) + } + + assert_equal(old, curgid, "UID was not reverted") + end + + def test_eachmethod + obj = Etc.getgrnam(groupnames()[0]) + + assert(obj, "Could not retrieve test group object") + + Puppet::Type::Group.validstates.each { |name, state| + assert_nothing_raised { + method = state.infomethod + assert(method, "State %s has no infomethod" % name) + assert(obj.respond_to?(method), + "State %s has an invalid method %s" % + [name, method] + ) + } + + assert_nothing_raised { + method = state.infomethod + assert(method, "State %s has no infomethod" % name) + assert(obj.respond_to?(method), + "State %s has an invalid method %s" % + [name, method] + ) + } + } + end + + def test_owngroups + groupnames().each { |group| + gobj = nil + comp = nil + assert_nothing_raised { + gobj = Puppet::Type::Group.create( + :name => group, + :check => [:gid] + ) + + comp = newcomp("grouptest %s" % group, gobj) + } + + trans = nil + assert_nothing_raised { + trans = comp.evaluate + } + + assert(gobj.is(:gid), "Failed to retrieve gid") + } + end + + if Process.uid == 0 + def test_mkgroup + gobj = nil + comp = nil + name = "pptestgr" + + os = Facter["operatingsystem"].value + + #if os == "Darwin" + # obj = nil + # assert_nothing_raised { + # obj = Etc.getgrnam(name) + # } + # assert_equal(-2, obj.gid, "Darwin GID is not -2") + #else + #assert_raise(ArgumentError) { + # obj = Etc.getgrnam(name) + #} + #end + assert(missing?(name), "Group %s is still present" % name) + + assert_nothing_raised { + gobj = Puppet::Type::Group.create( + :name => name + ) + + comp = newcomp("groupmaker %s" % name, gobj) + } + + @@tmpgroups << name + trans = assert_events(comp, [:group_created], "group") + + obj = nil + assert_nothing_raised { + obj = Etc.getgrnam(name) + } + assert(!missing?(name), "Group %s is missing" % name) + + tests = Puppet::Type::Group.validstates.collect { |sname, state| + state.name + } + + gobj.retrieve + tests.each { |test| + if self.respond_to?("attrtest_%s" % test) + self.send("attrtest_%s" % test, gobj) + else + #$stderr.puts "Not testing attr %s of group" % test + end + } + + assert_rollback_events(trans, [:group_deleted], "group") + + assert(missing?(name), "Group %s is still present" % name) + end + else + $stderr.puts "Not running as root; skipping group creation tests." + end +end diff --git a/test/types/package.rb b/test/types/package.rb new file mode 100644 index 000000000..1936c8bbc --- /dev/null +++ b/test/types/package.rb @@ -0,0 +1,205 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppettest' +require 'puppet' +require 'test/unit' +require 'facter' + +$platform = Facter["operatingsystem"].value + +unless Puppet::Type::Package.default + puts "No default package type for %s; skipping package tests" % $platform +else + +class TestPackageSource < Test::Unit::TestCase + include TestPuppet + def test_filesource + system("touch /tmp/fakepackage") + assert_equal( + "/tmp/fakepackage", + Puppet::PackageSource.get("file:///tmp/fakepackage") + ) + system("rm -f /tmp/fakepackage") + end +end + +class TestPackages < Test::Unit::TestCase + include FileTesting + def setup + #@list = Puppet::Type::Package.getpkglist + Puppet::Type::Package.clear + super + end + + # These are packages that we're sure will be installed + def installedpkgs + pkgs = nil + case $platform + when "SunOS" + pkgs = %w{SMCossh} + when "Linux" + case Facter["distro"].value + when "Debian": pkgs = %w{ssh openssl} + when "Fedora": pkgs = %w{openssh} + #when "RedHat": type = :rpm + else + Puppet.notice "No test package for %s" % $platform + return [] + end + else + Puppet.notice "No test package for %s" % $platform + return [] + end + + return pkgs + end + + def tstpkg + case $platform + #when "SunOS" + # type = "sunpkg" + when "Linux" + case Facter["distro"].value + when "Debian": + return %w{zec} + #when "RedHat": type = :rpm + when "Fedora": + return %w{wv} + else + Puppet.notice "No test packags for %s" % $platform + return nil + end + else + Puppet.notice "No test packags for %s" % $platform + return nil + end + end + + def mkpkgcomp(pkg) + assert_nothing_raised { + pkg = Puppet::Type::Package.create(:name => pkg, :install => true) + } + assert_nothing_raised { + pkg.retrieve + } + + comp = newcomp("package", pkg) + + return comp + end + + def test_retrievepkg + installedpkgs().each { |pkg| + obj = nil + assert_nothing_raised { + obj = Puppet::Type::Package.create( + :name => pkg + ) + } + + assert(obj, "could not create package") + + assert_nothing_raised { + obj.retrieve + } + + assert(obj.is(:install), "Could not retrieve package version") + } + end + + def test_nosuchpkg + obj = nil + assert_nothing_raised { + obj = Puppet::Type::Package.create( + :name => "thispackagedoesnotexist" + ) + } + + assert_nothing_raised { + obj.retrieve + } + + assert_equal(:notinstalled, obj.is(:install), + "Somehow retrieved unknown pkg's version") + end + + def test_latestpkg + pkgs = tstpkg || return + + pkgs.each { |name| + pkg = Puppet::Type::Package.create(:name => name) + assert_nothing_raised { + assert(pkg.latest, "Package did not return value for 'latest'") + } + } + end + + unless Process.uid == 0 + $stderr.puts "Run as root to perform package installation tests" + else + def test_installpkg + pkgs = tstpkg || return + pkgs.each { |pkg| + # we first set install to 'true', and make sure something gets + # installed + assert_nothing_raised { + pkg = Puppet::Type::Package.create(:name => pkg, :install => true) + } + assert_nothing_raised { + pkg.retrieve + } + + if pkg.insync? + Puppet.notice "Test package %s is already installed; please choose a different package for testing" % pkg + next + end + + comp = newcomp("package", pkg) + + assert_events(comp, [:package_installed], "package") + + # then uninstall it + assert_nothing_raised { + pkg[:install] = false + } + + + pkg.retrieve + + assert(! pkg.insync?, "Package is insync") + + assert_events(comp, [:package_removed], "package") + + # and now set install to 'latest' and verify it installs + # FIXME this isn't really a very good test -- we should install + # a low version, and then upgrade using this. But, eh. + assert_nothing_raised { + pkg[:install] = "latest" + } + + assert_events(comp, [:package_installed], "package") + + pkg.retrieve + assert(pkg.insync?, "After install, package is not insync") + + assert_nothing_raised { + pkg[:install] = false + } + + + pkg.retrieve + + assert(! pkg.insync?, "Package is insync") + + assert_events(comp, [:package_removed], "package") + } + end + end +end +end + +# $Id$ diff --git a/test/types/query.rb b/test/types/query.rb new file mode 100644 index 000000000..1793e1e17 --- /dev/null +++ b/test/types/query.rb @@ -0,0 +1,109 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'test/unit' + +# $Id$ + +class TestQuery < Test::Unit::TestCase + def setup + Puppet[:loglevel] = :debug if __FILE__ == $0 + end + + def teardown + assert_nothing_raised() { + Puppet::Type.allclear + } + end + + # hmmm + # this is complicated, because we store references to the created + # objects in a central store + def file + assert_nothing_raised() { + cfile = File.join($puppetbase,"examples/root/etc/configfile") + unless Puppet::Type::PFile.has_key?(cfile) + Puppet::Type::PFile.create( + :path => cfile, + :check => [:mode, :owner, :checksum] + ) + end + @configfile = Puppet::Type::PFile[cfile] + } + return @configfile + end + + def service + assert_nothing_raised() { + unless Puppet::Type::Service.has_key?("sleeper") + Puppet::Type::Service.create( + :name => "sleeper", + :type => "init", + :path => File.join($puppetbase,"examples/root/etc/init.d"), + :hasstatus => true, + :check => [:running] + ) + end + @sleeper = Puppet::Type::Service["sleeper"] + } + + return @sleeper + end + + def component(name,*args) + assert_nothing_raised() { + @component = Puppet::Type::Component.create(:name => name) + } + + args.each { |arg| + assert_nothing_raised() { + @component.push arg + } + } + + return @component + end + + def test_file + yayfile = file() + #p yayfile + yayfile.eachstate { |state| + assert_nil(state.is) + } + + assert_nothing_raised() { + yayfile.retrieve + } + + assert_nothing_raised() { + yayfile[:check] = :group + } + + assert_nothing_raised() { + yayfile.retrieve + } + end + + def test_service + service = service() + service.eachstate { |state| + assert_nil(state.is) + } + + assert_nothing_raised() { + service.retrieve + } + end + + def test_component + component = component("a",file(),service()) + + assert_nothing_raised() { + component.retrieve + } + end +end diff --git a/test/types/service.rb b/test/types/service.rb new file mode 100644 index 000000000..5d99d662d --- /dev/null +++ b/test/types/service.rb @@ -0,0 +1,101 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../.." +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +class TestService < Test::Unit::TestCase + include TestPuppet + # hmmm + # this is complicated, because we store references to the created + # objects in a central store + def setup + sleeper = nil + script = File.join($puppetbase,"examples/root/etc/init.d/sleeper") + @status = script + " status" + + super + end + + def teardown + stopservices + super + end + + def mksleeper(hash = {}) + hash[:name] = "sleeper" + hash[:path] = File.join($puppetbase,"examples/root/etc/init.d") + hash[:running] = true + hash[:type] = "init" + assert_nothing_raised() { + return Puppet::Type::Service.create(hash) + } + end + + def cyclesleeper(sleeper) + assert_nothing_raised() { + sleeper.retrieve + } + assert(!sleeper.insync?()) + assert_nothing_raised() { + sleeper.sync + } + assert_nothing_raised() { + sleeper.retrieve + } + assert(sleeper.insync?) + + # test refreshing it + assert_nothing_raised() { + sleeper.refresh + } + + assert(sleeper.respond_to?(:refresh)) + + # now stop it + assert_nothing_raised() { + sleeper[:running] = 0 + } + assert_nothing_raised() { + sleeper.retrieve + } + assert(!sleeper.insync?()) + assert_nothing_raised() { + sleeper.sync + } + assert_nothing_raised() { + sleeper.retrieve + } + assert(sleeper.insync?) + end + + def test_processStartWithPattern + sleeper = mksleeper(:pattern => "bin/sleeper") + + cyclesleeper(sleeper) + end + + def test_processStartWithStatus + sleeper = mksleeper(:hasstatus => true) + cyclesleeper(sleeper) + end + + unless Process.uid == 0 + puts "run as root to test service enable/disable" + else + case Puppet::Type::Service.defaulttype + when Puppet::ServiceTypes::InitSvc + when Puppet::ServiceTypes::SMFSvc + # yay + else + Puppet.notice "Not testing service type %s" % + Puppet::Type::Service.defaulttype + end + end +end + +# $Id$ diff --git a/test/types/symlink.rb b/test/types/symlink.rb new file mode 100755 index 000000000..3d288bc0a --- /dev/null +++ b/test/types/symlink.rb @@ -0,0 +1,93 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +# $Id$ + +class TestSymlink < Test::Unit::TestCase + include FileTesting + def mktmpfile + # because luke's home directory is on nfs, it can't be used for testing + # as root + tmpfile = tempfile() + File.open(tmpfile, "w") { |f| f.puts rand(100) } + @@tmpfiles.push tmpfile + return tmpfile + end + + def mktmpdir + dir = File.join(tmpdir(), "puppetlinkdir") + unless FileTest.exists?(dir) + Dir.mkdir(dir) + end + @@tmpfiles.push dir + return dir + end + + def tmplink + link = File.join(tmpdir(), "puppetlinktest") + @@tmpfiles.push link + return link + end + + def newlink(hash = {}) + hash[:name] = tmplink() + unless hash.include?(:target) + hash[:target] = mktmpfile() + end + link = Puppet::Type::Symlink.create(hash) + return link + end + + def test_target + link = nil + file = mktmpfile() + assert_nothing_raised() { + link = newlink() + } + assert_nothing_raised() { + link.retrieve + } + # we might already be in sync + assert(!link.insync?()) + assert_nothing_raised() { + link.sync + } + assert_nothing_raised() { + link.retrieve + } + assert(link.insync?()) + end + + def test_recursion + source = mktmpdir() + FileUtils.cd(source) { + mkranddirsandfiles() + } + + link = nil + assert_nothing_raised { + link = newlink(:target => source, :recurse => true) + } + comp = newcomp("linktest",link) + cycle(comp) + + path = link.name + list = file_list(path) + FileUtils.cd(path) { + list.each { |file| + unless FileTest.directory?(file) + assert(FileTest.symlink?(file)) + target = File.readlink(file) + assert_equal(target,File.join(source,file.sub(/^\.\//,''))) + end + } + } + end +end diff --git a/test/types/tc_basic.rb b/test/types/tc_basic.rb deleted file mode 100644 index 4ad6d559b..000000000 --- a/test/types/tc_basic.rb +++ /dev/null @@ -1,119 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -class TestBasic < Test::Unit::TestCase - include TestPuppet - # hmmm - # this is complicated, because we store references to the created - # objects in a central store - def setup - super - @component = nil - @configfile = nil - @sleeper = nil - - Puppet[:loglevel] = :debug if __FILE__ == $0 - - assert_nothing_raised() { - @component = Puppet::Type::Component.create( - :name => "yaytest", - :type => "testing" - ) - } - - assert_nothing_raised() { - @filepath = tempfile() - @@tmpfiles << @filepath - @configfile = Puppet::Type::PFile.create( - :path => @filepath, - :create => true, - :checksum => "md5" - ) - } - assert_nothing_raised() { - @sleeper = Puppet::Type::Service.create( - :name => "sleeper", - :type => "init", - :path => File.join($puppetbase,"examples/root/etc/init.d"), - :hasstatus => true, - :running => 1 - ) - } - assert_nothing_raised() { - @component.push( - @configfile, - @sleeper - ) - } - - #puts "Component is %s, id %s" % [@component, @component.object_id] - #puts "ConfigFile is %s, id %s" % [@configfile, @configfile.object_id] - end - - def test_name_calls - [@sleeper,@configfile].each { |obj| - Puppet.debug "obj is %s" % obj - assert_nothing_raised(){ - obj.name - } - } - end - - def test_name_equality - #puts "Component is %s, id %s" % [@component, @component.object_id] - assert_equal( - @filepath, - @configfile.name - ) - - assert_equal( - "sleeper", - @sleeper.name - ) - end - - def test_object_retrieval - [@sleeper,@configfile].each { |obj| - assert_equal( - obj.class[obj.name].object_id, - obj.object_id - ) - } - end - - def test_transaction - transaction = nil - assert_nothing_raised() { - transaction = @component.evaluate - } - assert_nothing_raised() { - transaction.evaluate - } - assert_nothing_raised() { - @sleeper[:running] = 0 - } - assert_nothing_raised() { - transaction = @component.evaluate - } - assert_nothing_raised() { - transaction.evaluate - } - end - - def test_paths - [@configfile,@sleeper,@component].each { |obj| - assert_nothing_raised { - assert(obj.path.is_a?(Array)) - } - } - end -end - -# $Id$ diff --git a/test/types/tc_component.rb b/test/types/tc_component.rb deleted file mode 100755 index d52123ae0..000000000 --- a/test/types/tc_component.rb +++ /dev/null @@ -1,279 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -# $Id$ - -class TestComponent < Test::Unit::TestCase - include TestPuppet - def setup - @@used = {} - super - end - - def teardown - assert_nothing_raised() { - Puppet::Type.allclear - } - super - end - - def randnum(limit) - num = nil - looped = 0 - loop do - looped += 1 - if looped > 1000 - raise "Reached limit of looping" - break - end - num = rand(limit) - unless @@used.include?(num) - @@used[num] = true - break - end - end - - num - end - - def mkfile(num = nil) - unless num - num = randnum(1000) - end - name = "/tmp/componentrandfile" + num.to_s - - file = Puppet::Type::PFile.create( - :path => name, - :checksum => "md5" - ) - @@tmpfiles << name - file - end - - def mkcomp - Puppet::Type::Component.create(:name => "component_" + randnum(1000).to_s) - end - - def mkrandcomp(numfiles, numdivs) - comp = mkcomp - hash = {} - found = 0 - - divs = {} - - numdivs.times { |i| - num = i + 2 - divs[num] = nil - } - while found < numfiles - num = randnum(numfiles) - found += 1 - f = mkfile(num) - hash[f.name] = f - reqd = [] - divs.each { |n,obj| - if rand(50) % n == 0 - if obj - unless reqd.include?(obj.object_id) - f[:require] = [[obj.class.name, obj.name]] - reqd << obj.object_id - end - end - end - - divs[n] = f - } - end - - hash.each { |name, obj| - comp.push obj - } - - comp - end - - def test_ordering - list = nil - comp = mkrandcomp(30,5) - assert_nothing_raised { - list = comp.flatten - } - - list.each_with_index { |obj, index| - obj.eachdependency { |dep| - assert(list.index(dep) < index) - } - } - end - - def test_correctsorting - tmpfile = "/tmp/comptesting" - @@tmpfiles.push tmpfile - trans = nil - cmd = nil - File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| - of.puts rand(100) - } - file = Puppet::Type::PFile.create( - :path => tmpfile, - :checksum => "md5" - ) - assert_nothing_raised { - cmd = Puppet::Type::Exec.create( - :command => "pwd", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :subscribe => [[file.class.name,file.name]], - :refreshonly => true - ) - } - - order = nil - assert_nothing_raised { - order = Puppet::Type::Component.sort([file, cmd]) - } - - [cmd, file].each { |obj| - assert_equal(1, order.find_all { |o| o.name == obj.name }.length) - } - end - - def test_correctflattening - tmpfile = "/tmp/comptesting" - @@tmpfiles.push tmpfile - trans = nil - cmd = nil - File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| - of.puts rand(100) - } - file = Puppet::Type::PFile.create( - :path => tmpfile, - :checksum => "md5" - ) - assert_nothing_raised { - cmd = Puppet::Type::Exec.create( - :command => "pwd", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :subscribe => [[file.class.name,file.name]], - :refreshonly => true - ) - } - - comp = Puppet::Type::Component.create(:name => "RefreshTest") - [cmd, file].each { |obj| - comp.push obj - } - objects = nil - assert_nothing_raised { - objects = comp.flatten - } - - [cmd, file].each { |obj| - assert_equal(1, objects.find_all { |o| o.name == obj.name }.length) - } - - assert(objects[0] == file, "File was not first object") - assert(objects[1] == cmd, "Exec was not second object") - end - - def test_deepflatten - tmpfile = tempfile() - @@tmpfiles.push tmpfile - trans = nil - cmd = nil - File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| - of.puts rand(100) - } - file = Puppet::Type::PFile.create( - :path => tmpfile, - :checksum => "md5" - ) - assert_nothing_raised { - cmd = Puppet::Type::Exec.create( - :command => "pwd", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :refreshonly => true - ) - } - - fcomp = newcomp("fflatten", file) - ecomp = newcomp("eflatten", cmd) - - # this subscription can screw up the sorting - ecomp[:subscribe] = [[fcomp.class.name,fcomp.name]] - - comp = newcomp("bflatten", ecomp, fcomp) - objects = nil - assert_nothing_raised { - objects = comp.flatten - } - - assert_equal(objects.length, 2, "Did not get two sorted objects") - objects.each { |o| - assert(o.is_a?(Puppet::Type), "Object %s is not a Type" % o.class) - } - - assert(objects[0] == file, "File was not first object") - assert(objects[1] == cmd, "Exec was not second object") - end - - def test_deepflatten2 - tmpfile = tempfile() - @@tmpfiles.push tmpfile - trans = nil - cmd = nil - File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| - of.puts rand(100) - } - file = Puppet::Type::PFile.create( - :path => tmpfile, - :checksum => "md5" - ) - assert_nothing_raised { - cmd = Puppet::Type::Exec.create( - :command => "pwd", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :refreshonly => true - ) - } - - ocmd = nil - assert_nothing_raised { - ocmd = Puppet::Type::Exec.create( - :command => "echo true", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :refreshonly => true - ) - } - - fcomp = newcomp("fflatten", file) - ecomp = newcomp("eflatten", cmd) - ocomp = newcomp("oflatten", ocmd) - - # this subscription can screw up the sorting - cmd[:subscribe] = [[fcomp.class.name,fcomp.name]] - ocmd[:subscribe] = [[cmd.class.name,cmd.name]] - - comp = newcomp("bflatten", ocomp, ecomp, fcomp) - objects = nil - assert_nothing_raised { - objects = comp.flatten - } - - assert_equal(objects.length, 3, "Did not get three sorted objects") - - objects.each { |o| - assert(o.is_a?(Puppet::Type), "Object %s is not a Type" % o.class) - } - - assert(objects[0] == file, "File was not first object") - assert(objects[1] == cmd, "Exec was not second object") - assert(objects[2] == ocmd, "Other exec was not second object") - end -end diff --git a/test/types/tc_cron.rb b/test/types/tc_cron.rb deleted file mode 100755 index ffefba3c1..000000000 --- a/test/types/tc_cron.rb +++ /dev/null @@ -1,262 +0,0 @@ -# Test cron job creation, modification, and destruction - -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppettest' -require 'puppet' -require 'puppet/type/cron' -require 'test/unit' -require 'facter' - -class TestExec < Test::Unit::TestCase - include TestPuppet - def setup - # retrieve the user name - id = %x{id}.chomp - if id =~ /uid=\d+\(([^\)]+)\)/ - @me = $1 - else - puts id - end - unless defined? @me - raise "Could not retrieve user name; 'id' did not work" - end - # god i'm lazy - @crontype = Puppet::Type::Cron - - super - end - - # Back up the user's existing cron tab if they have one. - def cronback - tab = nil - assert_nothing_raised { - tab = Puppet::Type::Cron.crontype.read(@me) - } - - if $? == 0 - @currenttab = tab - else - @currenttab = nil - end - end - - # Restore the cron tab to its original form. - def cronrestore - assert_nothing_raised { - if @currenttab - @crontype.crontype.write(@me, @currenttab) - else - @crontype.crontype.remove(@me) - end - } - end - - # Create a cron job with all fields filled in. - def mkcron(name) - cron = nil - assert_nothing_raised { - cron = @crontype.create( - :command => "date > %s/crontest%s" % [tmpdir(), name], - :name => name, - :user => @me, - :minute => rand(59), - :month => "1", - :monthday => "1", - :hour => "1" - ) - } - - return cron - end - - # Run the cron through its paces -- install it then remove it. - def cyclecron(cron) - name = cron.name - comp = newcomp(name, cron) - - trans = assert_events(comp, [:cron_created], name) - cron.retrieve - assert(cron.insync?) - trans = assert_events(comp, [], name) - cron[:command] = :notfound - trans = assert_events(comp, [:cron_deleted], name) - # the cron should no longer exist, not even in the comp - trans = assert_events(comp, [], name) - - assert(!comp.include?(cron), - "Cron is still a member of comp, after being deleted") - end - - # A simple test to see if we can load the cron from disk. - def test_load - assert_nothing_raised { - @crontype.retrieve(@me) - } - end - - # Test that a cron job turns out as expected, by creating one and generating - # it directly - def test_simple_to_cron - cron = nil - # make the cron - name = "yaytest" - assert_nothing_raised { - cron = @crontype.create( - :name => name, - :command => "date", - :user => @me - ) - } - str = nil - # generate the text - assert_nothing_raised { - str = cron.to_cron - } - assert_equal(str, "# Puppet Name: #{name}\n* * * * * date", - "Cron did not generate correctly") - end - - # Test that comments are correctly retained - def test_retain_comments - str = "# this is a comment\n#and another comment\n" - user = "fakeuser" - assert_nothing_raised { - @crontype.parse(user, str) - } - - assert_nothing_raised { - newstr = @crontype.tab(user) - assert_equal(str, newstr, "Cron comments were changed or lost") - } - end - - # Test that a specified cron job will be matched against an existing job - # with no name, as long as all fields match - def test_matchcron - str = "0,30 * * * * date\n" - - assert_nothing_raised { - @crontype.parse(@me, str) - } - - assert_nothing_raised { - cron = @crontype.create( - :name => "yaycron", - :minute => [0, 30], - :command => "date", - :user => @me - ) - } - - modstr = "# Puppet Name: yaycron\n%s" % str - - assert_nothing_raised { - newstr = @crontype.tab(@me) - assert_equal(modstr, newstr, "Cron was not correctly matched") - } - end - - # Test adding a cron when there is currently no file. - def test_mkcronwithnotab - cronback - Puppet::Type::Cron.crontype.remove(@me) - - cron = mkcron("crontest") - cyclecron(cron) - cronrestore - end - - def test_mkcronwithtab - cronback - Puppet::Type::Cron.crontype.remove(@me) - Puppet::Type::Cron.crontype.write(@me, -"1 1 1 1 * date > %s/crontesting\n" % testdir() - ) - - cron = mkcron("crontest") - cyclecron(cron) - cronrestore - end - - def test_makeandretrievecron - cronback - Puppet::Type::Cron.crontype.remove(@me) - - name = "storeandretrieve" - cron = mkcron(name) - comp = newcomp(name, cron) - trans = assert_events(comp, [:cron_created], name) - - cron = nil - - Puppet::Type::Cron.clear - Puppet::Type::Cron.retrieve(@me) - - assert(cron = Puppet::Type::Cron[name], "Could not retrieve named cron") - assert_instance_of(Puppet::Type::Cron, cron) - cronrestore - end - - # Do input validation testing on all of the parameters. - def test_arguments - values = { - :monthday => { - :valid => [ 1, 13, "1,30" ], - :invalid => [ -1, 0, 32 ] - }, - :weekday => { - :valid => [ 0, 3, 6, "1,2", "tue", "wed", - "Wed", "MOnday", "SaTurday" ], - :invalid => [ -1, 7, "1, 3", "tues", "teusday", "thurs" ] - }, - :hour => { - :valid => [ 0, 21, 23 ], - :invalid => [ -1, 24 ] - }, - :minute => { - :valid => [ 0, 34, 59 ], - :invalid => [ -1, 60 ] - }, - :month => { - :valid => [ 1, 11, 12, "mar", "March", "apr", "October", "DeCeMbEr" ], - :invalid => [ 0, 13, "marc", "sept" ] - } - } - - cron = mkcron("valtesting") - values.each { |param, hash| - hash.each { |type, values| - values.each { |value| - case type - when :valid: - assert_nothing_raised { - cron[param] = value - } - - if value.is_a?(Integer) - assert_equal([value], cron[param], - "Cron value was not set correctly") - end - when :invalid: - assert_raise(Puppet::Error, "%s is incorrectly a valid %s" % - [value, param]) { - cron[param] = value - } - end - - if value.is_a?(Integer) - value = value.to_s - redo - end - } - } - } - end -end - -# $Id$ diff --git a/test/types/tc_exec.rb b/test/types/tc_exec.rb deleted file mode 100755 index 99e120ea2..000000000 --- a/test/types/tc_exec.rb +++ /dev/null @@ -1,213 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppettest' -require 'test/unit' -require 'facter' - -# $Id$ - -class TestExec < Test::Unit::TestCase - include TestPuppet - def test_execution - command = nil - output = nil - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "/bin/echo" - ) - } - assert_nothing_raised { - command.evaluate - } - assert_nothing_raised { - output = command.sync - } - assert_equal([:executed_command],output) - end - - def test_numvsstring - command = nil - output = nil - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "/bin/echo", - :returns => 0 - ) - } - assert_nothing_raised { - command.evaluate - } - assert_nothing_raised { - output = command.sync - } - Puppet::Type::Exec.clear - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "/bin/echo", - :returns => "0" - ) - } - assert_nothing_raised { - command.evaluate - } - assert_nothing_raised { - output = command.sync - } - end - - def test_path_or_qualified - command = nil - output = nil - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "echo" - ) - assert_nil(command) - } - Puppet::Type::Exec.clear - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "echo", - :path => "/usr/bin:/bin:/usr/sbin:/sbin" - ) - } - Puppet::Type::Exec.clear - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "/bin/echo" - ) - } - Puppet::Type::Exec.clear - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "/bin/echo", - :path => "/usr/bin:/bin:/usr/sbin:/sbin" - ) - } - end - - def test_nonzero_returns - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "mkdir /this/directory/does/not/exist", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :returns => 1 - ) - } - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "touch /etc", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :returns => 1 - ) - } - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "thiscommanddoesnotexist", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :returns => 127 - ) - } - end - - def test_cwdsettings - command = nil - dir = "/tmp" - wd = Dir.chdir(dir) { - Dir.getwd - } - assert_nothing_raised { - command = Puppet::Type::Exec.create( - :command => "pwd", - :cwd => dir, - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :returns => 0 - ) - } - assert_nothing_raised { - command.evaluate - } - assert_nothing_raised { - command.sync - } - assert_equal(wd,command.output.chomp) - end - - def test_refreshonly - file = nil - cmd = nil - tmpfile = "/tmp/exectesting" - @@tmpfiles.push tmpfile - trans = nil - File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| - of.puts rand(100) - } - file = Puppet::Type::PFile.create( - :path => tmpfile, - :checksum => "md5" - ) - assert_nothing_raised { - cmd = Puppet::Type::Exec.create( - :command => "pwd", - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :subscribe => [[file.class.name,file.name]], - :refreshonly => true - ) - } - - comp = Puppet::Type::Component.create(:name => "RefreshTest") - [file,cmd].each { |obj| - comp.push obj - } - events = nil - assert_nothing_raised { - trans = comp.evaluate - - sum = file.state(:checksum) - assert_equal(sum.is, sum.should) - events = trans.evaluate.collect { |event| - event.event - } - } - # the first checksum shouldn't result in a changed file - assert_equal([],events) - File.open(tmpfile, File::WRONLY|File::CREAT|File::TRUNC) { |of| - of.puts rand(100) - of.puts rand(100) - of.puts rand(100) - } - assert_nothing_raised { - trans = comp.evaluate - sum = file.state(:checksum) - events = trans.evaluate.collect { |event| event.event } - } - - # verify that only the file_changed event was kicked off, not the - # command_executed - assert_equal( - [:file_modified], - events - ) - end - - def test_creates - file = tempfile() - exec = nil - assert_nothing_raised { - exec = Puppet::Type::Exec.create( - :command => "touch %s" % file, - :path => "/usr/bin:/bin:/usr/sbin:/sbin", - :creates => file - ) - } - - comp = newcomp("createstest", exec) - assert_events(comp, [:executed_command], "creates") - assert_events(comp, [], "creates") - end -end diff --git a/test/types/tc_file.rb b/test/types/tc_file.rb deleted file mode 100644 index 713dd96c1..000000000 --- a/test/types/tc_file.rb +++ /dev/null @@ -1,502 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'test/unit' -require 'fileutils' -require 'puppettest' - -class TestFile < Test::Unit::TestCase - include FileTesting - # hmmm - # this is complicated, because we store references to the created - # objects in a central store - def mkfile(hash) - file = nil - assert_nothing_raised { - file = Puppet::Type::PFile.create(hash) - } - return file - end - - def mktestfile - # because luke's home directory is on nfs, it can't be used for testing - # as root - tmpfile = tempfile() - File.open(tmpfile, "w") { |f| f.puts rand(100) } - @@tmpfiles.push tmpfile - mkfile(:name => tmpfile) - end - - def setup - begin - initstorage - rescue - system("rm -rf %s" % Puppet[:checksumfile]) - end - super - end - - def teardown - clearstorage - Puppet::Storage.clear - super - end - - def initstorage - Puppet::Storage.init - Puppet::Storage.load - end - - def clearstorage - Puppet::Storage.store - Puppet::Storage.clear - end - - def test_owner - file = mktestfile() - - users = {} - count = 0 - - # collect five users - Etc.passwd { |passwd| - if count > 5 - break - else - count += 1 - end - users[passwd.uid] = passwd.name - } - - fake = {} - # find a fake user - while true - a = rand(1000) - begin - Etc.getpwuid(a) - rescue - fake[a] = "fakeuser" - break - end - end - - uid, name = users.shift - us = {} - us[uid] = name - users.each { |uid, name| - # just make sure we don't try to manage users - assert_nothing_raised() { - file.sync - } - assert_nothing_raised() { - file[:owner] = name - } - assert_nothing_raised() { - file.retrieve - } - assert_nothing_raised() { - file.sync - } - } - end - - def test_zgroup - file = mktestfile() - [%x{groups}.chomp.split(/ /), Process.groups].flatten.each { |group| - assert_nothing_raised() { - file[:group] = group - } - assert(file.state(:group)) - assert(file.state(:group).should) - } - end - - if Process.uid == 0 - def test_ownerasroot - file = mktestfile() - - users = {} - count = 0 - - # collect five users - Etc.passwd { |passwd| - if count > 5 - break - else - count += 1 - end - users[passwd.uid] = passwd.name - } - - fake = {} - # find a fake user - while true - a = rand(1000) - begin - Etc.getpwuid(a) - rescue - fake[a] = "fakeuser" - break - end - end - - users.each { |uid, name| - assert_nothing_raised() { - file[:owner] = name - } - changes = [] - assert_nothing_raised() { - changes << file.evaluate - } - assert(changes.length > 0) - assert_nothing_raised() { - file.sync - } - assert_nothing_raised() { - file.evaluate - } - assert(file.insync?()) - assert_nothing_raised() { - file[:owner] = uid - } - assert_nothing_raised() { - file.evaluate - } - # make sure changing to number doesn't cause a sync - assert(file.insync?()) - } - - fake.each { |uid, name| - assert_raise(Puppet::Error) { - file[:owner] = name - } - assert_raise(Puppet::Error) { - file[:owner] = uid - } - } - end - - def test_groupasroot - file = mktestfile() - [%x{groups}.chomp.split(/ /), Process.groups].flatten.each { |group| - assert_nothing_raised() { - file[:group] = group - } - assert(file.state(:group)) - assert(file.state(:group).should) - assert_nothing_raised() { - file.evaluate - } - assert_nothing_raised() { - file.sync - } - assert_nothing_raised() { - file.evaluate - } - assert(file.insync?()) - assert_nothing_raised() { - file.delete(:group) - } - } - end - else - $stderr.puts "Run as root for complete owner and group testing" - end - - def test_create - %w{a b c d}.collect { |name| "/tmp/createst%s" % name }.each { |path| - file =nil - assert_nothing_raised() { - file = Puppet::Type::PFile.create( - :name => path, - :create => true - ) - } - assert_nothing_raised() { - file.evaluate - } - assert_nothing_raised() { - file.sync - } - assert_nothing_raised() { - file.evaluate - } - assert(file.insync?()) - assert(FileTest.file?(path)) - @@tmpfiles.push path - } - end - - def test_create_dir - %w{a b c d}.collect { |name| "/tmp/createst%s" % name }.each { |path| - file = nil - assert_nothing_raised() { - file = Puppet::Type::PFile.create( - :name => path, - :create => "directory" - ) - } - assert_nothing_raised() { - file.evaluate - } - assert_nothing_raised() { - file.sync - } - assert_nothing_raised() { - file.evaluate - } - assert(file.insync?()) - assert(FileTest.directory?(path)) - @@tmpfiles.push path - } - end - - def test_modes - file = mktestfile - [0644,0755,0777,0641].each { |mode| - assert_nothing_raised() { - file[:mode] = mode - } - assert_nothing_raised() { - file.evaluate - } - assert_nothing_raised() { - file.sync - } - assert_nothing_raised() { - file.evaluate - } - assert(file.insync?()) - assert_nothing_raised() { - file.delete(:mode) - } - } - end - - def test_checksums - types = %w{md5 md5lite timestamp time} - exists = "/tmp/sumtest-exists" - nonexists = "/tmp/sumtest-nonexists" - - @@tmpfiles << exists - @@tmpfiles << nonexists - - # try it both with files that exist and ones that don't - files = [exists, nonexists] - initstorage - File.open(exists,"w") { |of| - 10.times { - of.puts rand(100) - } - } - types.each { |type| - files.each { |path| - if Puppet[:debug] - Puppet.info "Testing %s on %s" % [type,path] - end - file = nil - events = nil - # okay, we now know that we have a file... - assert_nothing_raised() { - file = Puppet::Type::PFile.create( - :name => path, - :create => true, - :checksum => type - ) - } - comp = Puppet::Type::Component.create( - :name => "componentfile" - ) - comp.push file - trans = nil - assert_nothing_raised() { - trans = comp.evaluate - } - - if file.name !~ /nonexists/ - sum = file.state(:checksum) - assert_equal(sum.is, sum.should) - assert(sum.insync?) - end - - assert_nothing_raised() { - events = trans.evaluate.collect { |e| e.event } - } - # we don't want to kick off an event the first time we - # come across a file - assert( - ! events.include?(:file_modified) - ) - assert_nothing_raised() { - File.open(path,"w") { |of| - of.puts rand(100) - } - } - Puppet::Type::PFile.clear - Puppet::Type::Component.clear - sleep 1 - - # now recreate the file - assert_nothing_raised() { - file = Puppet::Type::PFile.create( - :name => path, - :checksum => type - ) - } - comp = Puppet::Type::Component.create( - :name => "componentfile" - ) - comp.push file - trans = nil - assert_nothing_raised() { - trans = comp.evaluate - } - assert_nothing_raised() { - events = trans.evaluate.collect { |e| e.event } - } - - sum = file.state(:checksum) - - # verify that we're actually getting notified when a file changes - assert( - events.include?(:file_modified) - ) - assert_nothing_raised() { - Puppet::Type::PFile.clear - Puppet::Type::Component.clear - } - } - } - end - - def cyclefile(path) - # i had problems with using :name instead of :path - [:name,:path].each { |param| - file = nil - changes = nil - comp = nil - trans = nil - - initstorage - assert_nothing_raised { - file = Puppet::Type::PFile.create( - param => path, - :recurse => true, - :checksum => "md5" - ) - } - comp = Puppet::Type::Component.create( - :name => "component" - ) - comp.push file - assert_nothing_raised { - trans = comp.evaluate - } - assert_nothing_raised { - trans.evaluate - } - #assert_nothing_raised { - # file.sync - #} - clearstorage - Puppet::Type.allclear - } - end - - def test_recursion - path = "/tmp/filerecursetest" - @@tmpfiles.push path - tmpfile = File.join(path,"testing") - system("mkdir -p #{path}") - cyclefile(path) - File.open(tmpfile, File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "yayness" - } - cyclefile(path) - File.open(tmpfile, File::WRONLY|File::APPEND) { |of| - of.puts "goodness" - } - cyclefile(path) - end - -=begin - def test_ignore - - end -=end - - # XXX disabled until i change how dependencies work - def disabled_test_recursionwithcreation - path = "/tmp/this/directory/structure/does/not/exist" - @@tmpfiles.push "/tmp/this" - - file = nil - assert_nothing_raised { - file = mkfile( - :name => path, - :recurse => true, - :create => true - ) - } - - trans = nil - comp = newcomp("recursewithfiles", file) - assert_nothing_raised { - trans = comp.evaluate - } - - events = nil - assert_nothing_raised { - events = trans.evaluate.collect { |e| e.event.to_s } - } - - puts "events are %s" % events.join(", ") - end - - def test_filetype_retrieval - file = nil - - Puppet.err tmpdir() - assert_nothing_raised { - file = Puppet::Type::PFile.create( - :name => tmpdir(), - :check => :type - ) - } - - assert_nothing_raised { - file.evaluate - } - - assert_equal("directory", file.state(:type).is) - - assert_nothing_raised { - file = Puppet::Type::PFile.create( - :name => "/etc/passwd", - :check => :type - ) - } - - assert_nothing_raised { - file.evaluate - } - - assert_equal("file", file.state(:type).is) - - assert_raise(Puppet::Error) { - file[:type] = "directory" - } - - assert(file.insync?) - - assert_raise(Puppet::Error) { - file.sync - } - end -end - -# $Id$ diff --git a/test/types/tc_filebucket.rb b/test/types/tc_filebucket.rb deleted file mode 100755 index a5c8e0c78..000000000 --- a/test/types/tc_filebucket.rb +++ /dev/null @@ -1,167 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'test/unit' -require 'fileutils' -require 'puppettest' - -# $Id$ - -class TestFileBucket < Test::Unit::TestCase - include FileTesting - # hmmm - # this is complicated, because we store references to the created - # objects in a central store - def mkfile(hash) - file = nil - assert_nothing_raised { - file = Puppet::Type::PFile.create(hash) - } - return file - end - - def mkbucket(name,path) - bucket = nil - assert_nothing_raised { - bucket = Puppet::Type::PFileBucket.create( - :name => name, - :path => path - ) - } - - @@tmpfiles.push path - - return bucket - end - - def mktestfile - # because luke's home directory is on nfs, it can't be used for testing - # as root - tmpfile = tempfile() - File.open(tmpfile, "w") { |f| f.puts rand(100) } - @@tmpfiles.push tmpfile - mkfile(:name => tmpfile) - end - - def setup - super - begin - initstorage - rescue - system("rm -rf %s" % Puppet[:checksumfile]) - end - end - - def teardown - super - clearstorage - end - - def initstorage - Puppet::Storage.init - Puppet::Storage.load - end - - def clearstorage - Puppet::Storage.store - Puppet::Storage.clear - end - - def test_simplebucket - name = "yayness" - mkbucket("yayness", "/tmp/filebucket") - - bucket = nil - assert_nothing_raised { - bucket = Puppet::Type::PFileBucket.bucket(name) - } - - assert_instance_of(Puppet::Client::Dipper, bucket) - - md5 = nil - newpath = "/tmp/passwd" - @@tmpfiles << newpath - system("cp /etc/passwd %s" % newpath) - assert_nothing_raised { - md5 = bucket.backup(newpath) - } - - assert(md5) - - newmd5 = nil - - File.open(newpath, "w") { |f| f.puts ";lkjasdf;lkjasdflkjwerlkj134lkj" } - - assert_nothing_raised { - newmd5 = bucket.backup(newpath) - } - - assert(md5 != newmd5) - - assert_nothing_raised { - bucket.restore(newpath, md5) - } - - File.open(newpath) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } - - assert_equal(md5, newmd5) - end - - def test_fileswithbuckets - name = "yayness" - mkbucket("yayness", "/tmp/filebucket") - - bucket = nil - assert_nothing_raised { - bucket = Puppet::Type::PFileBucket.bucket(name) - } - - file = mktestfile() - assert_nothing_raised { - file[:backup] = ["filebucket", name] - } - - opath = "/tmp/anotherbuckettest" - @@tmpfiles << opath - system("cp /etc/passwd %s" % opath) - - origmd5 = File.open(file.name) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } - - file[:source] = opath - #assert_nothing_raised { - # file[:backup] = true - #} - - comp = newcomp("yaytest", file) - - trans = nil - assert_nothing_raised { - trans = comp.evaluate - } - events = nil - assert_nothing_raised { - events = trans.evaluate.collect { |e| e.event } - } - - # so, we've now replaced the file with the opath file - assert_equal( - File.open(opath) { |f| newmd5 = Digest::MD5.hexdigest(f.read) }, - File.open(file.name) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } - ) - - assert_nothing_raised { - bucket.restore(file.name, origmd5) - } - - assert_equal( - origmd5, - File.open(file.name) { |f| newmd5 = Digest::MD5.hexdigest(f.read) } - ) - - - end -end diff --git a/test/types/tc_fileignoresource.rb b/test/types/tc_fileignoresource.rb deleted file mode 100644 index f3d258381..000000000 --- a/test/types/tc_fileignoresource.rb +++ /dev/null @@ -1,287 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $:.unshift "../../../../language/trunk/lib" - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'cgi' -require 'test/unit' -require 'fileutils' -require 'puppettest' - -# $Id: $ - -class TestFileIgnoreSources < Test::Unit::TestCase - include FileTesting - - def setup - begin - initstorage - rescue - system("rm -rf %s" % Puppet[:checksumfile]) - end - super - end - - def teardown - clearstorage - super - end - -#This is not needed unless using md5 (correct me if I'm wrong) - def initstorage - Puppet::Storage.init - Puppet::Storage.load - end - - def clearstorage - Puppet::Storage.store - Puppet::Storage.clear - end - - def test_ignore_simple_source - - #Temp directory to run tests in - path = "/tmp/Fileignoresourcetest" - @@tmpfiles.push path - - #source directory - sourcedir = "sourcedir" - sourcefile1 = "sourcefile1" - sourcefile2 = "sourcefile2" - - frompath = File.join(path,sourcedir) - FileUtils.mkdir_p frompath - - topath = File.join(path,"destdir") - FileUtils.mkdir topath - - #initialize variables before block - tofile = nil - trans = nil - - #create source files - - File.open(File.join(frompath,sourcefile1), - File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "yayness" - } - - File.open(File.join(frompath,sourcefile2), - File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "even yayer" - } - - - #makes Puppet file Object - assert_nothing_raised { - tofile = Puppet::Type::PFile.create( - :name => topath, - :source => frompath, - :recurse => true, - :ignore => "sourcefile2" - ) - } - - #make a component and adds the file - comp = Puppet::Type::Component.create( - :name => "component" - ) - comp.push tofile - - #make, evaluate transaction and sync the component - assert_nothing_raised { - trans = comp.evaluate - } - assert_nothing_raised { - trans.evaluate - } - - - #topath should exist as a directory with sourcedir as a directory - - #This file should exist - assert(FileTest.exists?(File.join(topath,sourcefile1))) - - #This file should not - assert(!(FileTest.exists?(File.join(topath,sourcefile2)))) - - Puppet::Type.allclear - end - - def test_ignore_with_wildcard - #Temp directory to run tests in - path = "/tmp/Fileignoresourcetest" - @@tmpfiles.push path - - #source directory - sourcedir = "sourcedir" - subdir = "subdir" - subdir2 = "subdir2" - sourcefile1 = "sourcefile1" - sourcefile2 = "sourcefile2" - - frompath = File.join(path,sourcedir) - FileUtils.mkdir_p frompath - - FileUtils.mkdir_p(File.join(frompath, subdir)) - FileUtils.mkdir_p(File.join(frompath, subdir2)) - dir = Dir.glob(File.join(path,"**/*")) - - topath = File.join(path,"destdir") - FileUtils.mkdir topath - - #initialize variables before block - tofile = nil - trans = nil - - #create source files - - dir.each { |dir| - File.open(File.join(dir,sourcefile1), - File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "yayness" - } - - File.open(File.join(dir,sourcefile2), - File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "even yayer" - } - - } - - #makes Puppet file Object - assert_nothing_raised { - tofile = Puppet::Type::PFile.create( - :name => topath, - :source => frompath, - :recurse => true, - :ignore => "*2" - ) - } - - #make a component and adds the file - comp = Puppet::Type::Component.create( - :name => "component" - ) - comp.push tofile - - #make, evaluate transaction and sync the component - assert_nothing_raised { - trans = comp.evaluate - } - assert_nothing_raised { - trans.evaluate - } - - #topath should exist as a directory with sourcedir as a directory - - #This file should exist - assert(FileTest.exists?(File.join(topath,sourcefile1))) - assert(FileTest.exists?(File.join(topath,subdir))) - assert(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile1))) - #This file should not - assert(!(FileTest.exists?(File.join(topath,sourcefile2)))) - assert(!(FileTest.exists?(File.join(topath,subdir2)))) - assert(!(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile2)))) - Puppet::Type.allclear - - end - - def test_ignore_array - #Temp directory to run tests in - path = "/tmp/Fileignoresourcetest" - @@tmpfiles.push path - - #source directory - sourcedir = "sourcedir" - subdir = "subdir" - subdir2 = "subdir2" - subdir3 = "anotherdir" - sourcefile1 = "sourcefile1" - sourcefile2 = "sourcefile2" - - frompath = File.join(path,sourcedir) - FileUtils.mkdir_p frompath - - FileUtils.mkdir_p(File.join(frompath, subdir)) - FileUtils.mkdir_p(File.join(frompath, subdir2)) - FileUtils.mkdir_p(File.join(frompath, subdir3)) - sourcedir = Dir.glob(File.join(path,"**/*")) - - topath = File.join(path,"destdir") - FileUtils.mkdir topath - - #initialize variables before block - tofile = nil - trans = nil - - #create source files - - - - sourcedir.each { |dir| - File.open(File.join(dir,sourcefile1), - File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "yayness" - } - - File.open(File.join(dir,sourcefile2), - File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "even yayer" - } - - } - - - #makes Puppet file Object - assert_nothing_raised { - tofile = Puppet::Type::PFile.create( - :name => topath, - :source => frompath, - :recurse => true, - :ignore => ["*2", "an*"] - # :ignore => ["*2", "an*", "nomatch"] - ) - } - - #make a component and adds the file - comp = Puppet::Type::Component.create( - :name => "component" - ) - comp.push tofile - - #make, evaluate transaction and sync the component - assert_nothing_raised { - trans = comp.evaluate - } - assert_nothing_raised { - trans.evaluate - } - - #topath should exist as a directory with sourcedir as a directory - - # This file should exist - # proper files in destination - assert(FileTest.exists?(File.join(topath,sourcefile1)), "file1 not in destdir") - assert(FileTest.exists?(File.join(topath,subdir)), "subdir1 not in destdir") - assert(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile1)), "file1 not in subdir") - # proper files in source - assert(FileTest.exists?(File.join(frompath,subdir)), "subdir not in source") - assert(FileTest.exists?(File.join(frompath,subdir2)), "subdir2 not in source") - assert(FileTest.exists?(File.join(frompath,subdir3)), "subdir3 not in source") - - # This file should not - assert(!(FileTest.exists?(File.join(topath,sourcefile2))), "file2 in dest") - assert(!(FileTest.exists?(File.join(topath,subdir2))), "subdir2 in dest") - assert(!(FileTest.exists?(File.join(topath,subdir3))), "anotherdir in dest") - assert(!(FileTest.exists?(File.join(File.join(topath,subdir),sourcefile2))), "file2 in dest/sub") - - - Puppet::Type.allclear - - end - -end diff --git a/test/types/tc_filesources.rb b/test/types/tc_filesources.rb deleted file mode 100755 index 46542d76c..000000000 --- a/test/types/tc_filesources.rb +++ /dev/null @@ -1,532 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $:.unshift "../../../../language/trunk/lib" - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'cgi' -require 'test/unit' -require 'fileutils' -require 'puppettest' - -class TestFileSources < Test::Unit::TestCase - include FileTesting - def setup - begin - initstorage - rescue - system("rm -rf %s" % Puppet[:checksumfile]) - end - if defined? @port - @port += 1 - else - @port = 8800 - end - super - end - - def teardown - clearstorage - super - end - - def initstorage - Puppet::Storage.init - Puppet::Storage.load - end - - def clearstorage - Puppet::Storage.store - Puppet::Storage.clear - end - - def test_newchild - path = "/tmp/newchilddir" - @@tmpfiles.push path - - FileUtils.mkdir_p path - File.open(File.join(path,"childtest"), "w") { |of| - of.puts "yayness" - } - file = nil - comp = nil - trans = nil - assert_nothing_raised { - file = Puppet::Type::PFile.create( - :name => path - ) - } - child = nil - assert_nothing_raised { - child = file.newchild("childtest") - } - assert(child) - assert_raise(Puppet::DevError) { - file.newchild(File.join(path,"childtest")) - } - end - - def test_simplelocalsource - path = "/tmp/Filesourcetest" - @@tmpfiles.push path - FileUtils.mkdir_p path - frompath = File.join(path,"source") - topath = File.join(path,"dest") - fromfile = nil - tofile = nil - trans = nil - - File.open(frompath, File::WRONLY|File::CREAT|File::APPEND) { |of| - of.puts "yayness" - } - assert_nothing_raised { - tofile = Puppet::Type::PFile.create( - :name => topath, - :source => frompath - ) - } - comp = Puppet::Type::Component.create( - :name => "component" - ) - comp.push tofile - assert_nothing_raised { - trans = comp.evaluate - } - assert_nothing_raised { - trans.evaluate - } - # assert_nothing_raised { - # comp.sync - # } - - assert(FileTest.exists?(topath)) - from = File.open(frompath) { |o| o.read } - to = File.open(topath) { |o| o.read } - assert_equal(from,to) - @@tmpfiles.push path - end - - def recursive_source_test(fromdir, todir) - Puppet::Type.allclear - initstorage - tofile = nil - trans = nil - - assert_nothing_raised { - tofile = Puppet::Type::PFile.create( - :name => todir, - "recurse" => true, - "backup" => false, - "source" => fromdir - ) - } - comp = Puppet::Type::Component.create( - :name => "component" - ) - comp.push tofile - assert_nothing_raised { - trans = comp.evaluate - } - assert_nothing_raised { - trans.evaluate - } - - assert(FileTest.exists?(todir)) - Puppet::Type.allclear - end - - def run_complex_sources(networked = false) - path = "/tmp/ComplexSourcesTest" - @@tmpfiles.push path - - # first create the source directory - FileUtils.mkdir_p path - - - # okay, let's create a directory structure - fromdir = File.join(path,"fromdir") - Dir.mkdir(fromdir) - FileUtils.cd(fromdir) { - mkranddirsandfiles() - } - - todir = File.join(path, "todir") - source = fromdir - if networked - source = "puppet://localhost/%s%s" % [networked, fromdir] - end - recursive_source_test(source, todir) - - return [fromdir,todir] - end - - def test_complex_sources_twice - fromdir, todir = run_complex_sources - assert_trees_equal(fromdir,todir) - recursive_source_test(fromdir, todir) - assert_trees_equal(fromdir,todir) - end - - def test_sources_with_deleted_destfiles - fromdir, todir = run_complex_sources - # then delete some files - assert(FileTest.exists?(todir)) - missing_files = delete_random_files(todir) - - # and run - recursive_source_test(fromdir, todir) - - missing_files.each { |file| - assert(FileTest.exists?(file), "Deleted file %s is still missing" % file) - } - - # and make sure they're still equal - assert_trees_equal(fromdir,todir) - end - - def test_sources_with_readonly_destfiles - fromdir, todir = run_complex_sources - assert(FileTest.exists?(todir)) - readonly_random_files(todir) - recursive_source_test(fromdir, todir) - - # and make sure they're still equal - assert_trees_equal(fromdir,todir) - end - - def test_sources_with_modified_dest_files - fromdir, todir = run_complex_sources - - assert(FileTest.exists?(todir)) - # then modify some files - modify_random_files(todir) - - recursive_source_test(fromdir, todir) - - # and make sure they're still equal - assert_trees_equal(fromdir,todir) - end - - def test_sources_with_added_destfiles - fromdir, todir = run_complex_sources - assert(FileTest.exists?(todir)) - # and finally, add some new files - add_random_files(todir) - - recursive_source_test(fromdir, todir) - - fromtree = file_list(fromdir) - totree = file_list(todir) - - assert(fromtree != totree) - - # then remove our new files - FileUtils.cd(todir) { - %x{find . 2>/dev/null}.chomp.split(/\n/).each { |file| - if file =~ /file[0-9]+/ - File.unlink(file) - end - } - } - - # and make sure they're still equal - assert_trees_equal(fromdir,todir) - end - - def test_RecursionWithAddedFiles - basedir = "/tmp/recursionplussaddedfiles" - Dir.mkdir(basedir) - @@tmpfiles << basedir - file1 = File.join(basedir, "file1") - file2 = File.join(basedir, "file2") - subdir1 = File.join(basedir, "subdir1") - file3 = File.join(subdir1, "file") - File.open(file1, "w") { |f| 3.times { f.print rand(100) } } - rootobj = nil - assert_nothing_raised { - rootobj = Puppet::Type::PFile.create( - :name => basedir, - :recurse => true, - :check => %w{type owner} - ) - - rootobj.evaluate - } - - klass = Puppet::Type::PFile - assert(klass[basedir]) - assert(klass[file1]) - assert_nil(klass[file2]) - - File.open(file2, "w") { |f| 3.times { f.print rand(100) } } - - assert_nothing_raised { - rootobj.evaluate - } - assert(klass[file2]) - - Dir.mkdir(subdir1) - File.open(file3, "w") { |f| 3.times { f.print rand(100) } } - - assert_nothing_raised { - rootobj.evaluate - } - assert(klass[file3]) - end - - def mkfileserverconf(mounts) - file = "/tmp/fileserverconftestingfile%s" % rand(100) - File.open(file, "w") { |f| - mounts.each { |path, name| - f.puts "[#{name}]\n\tpath #{path}\n\tallow *\n" - } - } - - @@tmpfiles << file - return file - end - - # test raw xmlrpc calls - # this test is disabled because it requires way too much setup to get - # the certificates correct - def disabled_test_SimpleNetworkSources - server = nil - basedir = "/tmp/simplenetworksourcetesting" - @@tmpfiles << basedir - - mounts = { - "/" => "root" - } - - fileserverconf = mkfileserverconf(mounts) - - if File.exists?(basedir) - system("rm -rf %s" % basedir) - end - Dir.mkdir(basedir) - - Puppet[:puppetconf] = basedir - Puppet[:puppetvar] = basedir - Puppet[:autosign] = true - - tmpname = "yaytesting" - tmpfile = File.join(basedir, tmpname) - File.open(tmpfile, "w") { |f| f.print rand(100) } - - port = 8765 - serverpid = nil - assert_nothing_raised() { - server = Puppet::Server.new( - :Port => port, - :Handlers => { - :CA => {}, # so that certs autogenerate - :FileServer => { - :Config => fileserverconf - } - } - ) - - } - serverpid = fork { - assert_nothing_raised() { - #trap(:INT) { server.shutdown; Kernel.exit! } - trap(:INT) { server.shutdown } - server.start - } - } - @@tmppids << serverpid - - client = nil - assert_nothing_raised() { - client = XMLRPC::Client.new("localhost", "/RPC2", port, nil, nil, - nil, nil, true, 3) - } - retval = nil - - sleep(1) - - list = nil - rpath = "/root%s" % tmpfile - assert_nothing_raised { - list = client.call("fileserver.list", rpath, false, false) - } - - assert_equal("/\tfile", list) - - assert_nothing_raised { - list = client.call("fileserver.describe", rpath) - } - - assert_match(/^\d+\tfile\t\d+\t\d+\t.+$/, list) - - assert_nothing_raised { - list = client.call("fileserver.retrieve", rpath) - } - - contents = File.read(tmpfile) - assert_equal(contents, CGI.unescape(list)) - - assert_nothing_raised { - system("kill -INT %s" % serverpid) - } - end - - def test_NetworkSources - server = nil - basedir = "/tmp/networksourcetesting" - @@tmpfiles << basedir - if File.exists?(basedir) - system("rm -rf %s" % basedir) - end - Dir.mkdir(basedir) - - mounts = { - "/" => "root" - } - - fileserverconf = mkfileserverconf(mounts) - - Puppet[:puppetconf] = basedir - Puppet[:puppetvar] = basedir - Puppet[:autosign] = true - - Puppet[:masterport] = 8762 - - serverpid = nil - assert_nothing_raised() { - server = Puppet::Server.new( - :Handlers => { - :CA => {}, # so that certs autogenerate - :FileServer => { - :Config => fileserverconf - } - } - ) - - } - serverpid = fork { - assert_nothing_raised() { - #trap(:INT) { server.shutdown; Kernel.exit! } - trap(:INT) { server.shutdown } - server.start - } - } - @@tmppids << serverpid - - sleep(1) - - fromdir, todir = run_complex_sources("root") - assert_trees_equal(fromdir,todir) - recursive_source_test(fromdir, todir) - assert_trees_equal(fromdir,todir) - - assert_nothing_raised { - system("kill -INT %s" % serverpid) - } - end - - def test_networkSourcesWithoutService - server = nil - - Puppet[:autosign] = true - Puppet[:masterport] = 8765 - - serverpid = nil - assert_nothing_raised() { - server = Puppet::Server.new( - :Handlers => { - :CA => {}, # so that certs autogenerate - } - ) - - } - serverpid = fork { - assert_nothing_raised() { - #trap(:INT) { server.shutdown; Kernel.exit! } - trap(:INT) { server.shutdown } - server.start - } - } - @@tmppids << serverpid - - sleep(1) - - name = File.join(tmpdir(), "nosourcefile") - file = Puppet::Type::PFile.create( - :source => "puppet://localhost/dist/file", - :name => name - ) - - assert_nothing_raised { - file.retrieve - } - - comp = newcomp("nosource", file) - - assert_nothing_raised { - comp.evaluate - } - - assert(!FileTest.exists?(name), "File with no source exists anyway") - end - - def test_unmountedNetworkSources - server = nil - mounts = { - "/" => "root", - "/noexistokay" => "noexist" - } - - fileserverconf = mkfileserverconf(mounts) - - Puppet[:autosign] = true - Puppet[:masterport] = @port - - serverpid = nil - assert_nothing_raised() { - server = Puppet::Server.new( - :Port => @port, - :Handlers => { - :CA => {}, # so that certs autogenerate - :FileServer => { - :Config => fileserverconf - } - } - ) - - } - - serverpid = fork { - assert_nothing_raised() { - #trap(:INT) { server.shutdown; Kernel.exit! } - trap(:INT) { server.shutdown } - server.start - } - } - @@tmppids << serverpid - - sleep(1) - - name = File.join(tmpdir(), "nosourcefile") - file = Puppet::Type::PFile.create( - :source => "puppet://localhost/noexist/file", - :name => name - ) - - assert_nothing_raised { - file.retrieve - } - - comp = newcomp("nosource", file) - - assert_nothing_raised { - comp.evaluate - } - - assert(!FileTest.exists?(name), "File with no source exists anyway") - end -end - -# $Id$ diff --git a/test/types/tc_filetype.rb b/test/types/tc_filetype.rb deleted file mode 100644 index c6749ba3d..000000000 --- a/test/types/tc_filetype.rb +++ /dev/null @@ -1,162 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'puppet/type/typegen/filetype' -require 'puppet/type/typegen/filerecord' -require 'test/unit' - -# $Id$ - -#class TestFileType < Test::Unit::TestCase -class TestFileType - def disabled_setup - Puppet[:loglevel] = :debug if __FILE__ == $0 - - @passwdtype = Puppet::Type::FileType["passwd"] - if @passwdtype.nil? - assert_nothing_raised() { - @passwdtype = Puppet::Type::FileType.createtype( - :name => "passwd" - ) - @passwdtype.addrecord( - :name => "user", - :splitchar => ":", - :fields => %w{name password uid gid gcos home shell} - ) - } - end - - @syslogtype = Puppet::Type::FileType["syslog"] - if @syslogtype.nil? - assert_nothing_raised() { - @syslogtype = Puppet::Type::FileType.createtype( - :escapednewlines => true, - :name => "syslog" - ) - @syslogtype.addrecord( - :name => "data", - :regex => %r{^([^#\s]+)\s+(\S+)$}, - :joinchar => "\t", - :fields => %w{logs dest} - ) - @syslogtype.addrecord( - :name => "comment", - :regex => %r{^(#.*)$}, - :joinchar => "", # not really necessary... - :fields => %w{comment} - ) - @syslogtype.addrecord( - :name => "blank", - :regex => %r{^(\s*)$}, - :joinchar => "", # not really necessary... - :fields => %w{blank} - ) - } - end - - end - - def disabled_test_passwd1_nochange - file = nil - type = nil - assert_nothing_raised() { - file = @passwdtype.new("/etc/passwd") - } - assert_nothing_raised() { - file.retrieve - } - - assert(file.insync?) - - contents = "" - ::File.open("/etc/passwd") { |ofile| - ofile.each { |line| - contents += line - } - } - - assert_equal( - contents, - file.to_s - ) - - end - - def disabled_test_passwd2_change - file = nil - type = nil - Kernel.system("cp /etc/passwd /tmp/oparsepasswd") - assert_nothing_raised() { - file = @passwdtype.new("/tmp/oparsepasswd") - } - assert_nothing_raised() { - file.retrieve - } - - assert(file.insync?) - - assert_nothing_raised() { - file.add("user") { |obj| - obj["name"] = "yaytest" - obj["password"] = "x" - obj["uid"] = "10000" - obj["gid"] = "10000" - obj["home"] = "/home/yaytest" - obj["gcos"] = "The Yaytest" - obj["shell"] = "/bin/sh" - } - } - - assert(!file.insync?) - - assert_nothing_raised() { - file.sync - } - - assert(file.insync?) - - assert_nothing_raised() { - file.delete("bin") - } - - assert(!file.insync?) - - assert_nothing_raised() { - file.sync - } - - assert(file.insync?) - - Kernel.system("rm /tmp/oparsepasswd") - end - - def disabled_test_syslog_nochange - file = nil - type = nil - syslog = File.join($puppetbase, "examples/root/etc/debian-syslog.conf") - assert_nothing_raised() { - file = @syslogtype.new(syslog) - } - assert_nothing_raised() { - file.retrieve - } - - assert(file.insync?) - - contents = "" - ::File.open(syslog) { |ofile| - ofile.each { |line| - contents += line - } - } - #assert_equal( - # contents, - # file.to_s - #) - - end -end diff --git a/test/types/tc_group.rb b/test/types/tc_group.rb deleted file mode 100755 index dd705b6e5..000000000 --- a/test/types/tc_group.rb +++ /dev/null @@ -1,247 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -# $Id$ - -require 'etc' -require 'puppet/type' -require 'puppettest' -require 'test/unit' - -class TestGroup < Test::Unit::TestCase - include TestPuppet - def setup - @@tmpgroups = [] - super - end - - def teardown - Puppet::Type::Group.clear - @@tmpgroups.each { |group| - unless missing?(group) - remove(group) - end - } - super - end - - case Facter["operatingsystem"].value - when "Darwin": - def missing?(group) - output = %x{nidump -r /groups/#{group} / 2>/dev/null}.chomp - - if output == "" - return true - else - return false - end - - assert_equal("", output, "Group %s is present:\n%s" % [group, output]) - end - - def gid(name) - %x{nireport / /groups name gid}.split("\n").each { |line| - group, id = line.chomp.split(/\s+/) - if group == name - return Integer(id) - end - } - - return nil - end - - def remove(group) - system("niutil -destroy / /groups/%s" % group) - end - else - def missing?(group) - begin - obj = Etc.getgrnam(group) - return false - rescue ArgumentError - return true - end - end - - def gid(name) - assert_nothing_raised { - obj = Etc.getgrnam(name) - return obj.gid - } - - return nil - end - - def remove(group) - system("groupdel %s" % group) - end - end - - def groupnames - %x{groups}.chomp.split(/ /) - end - - def groupids - Process.groups - end - - def attrtest_gid(group) - obj = nil - #assert_nothing_raised { - # obj = Etc.getgrnam(group[:name]) - #} - group.retrieve - old = gid(group[:name]) - comp = newcomp("gidtest", group) - - group[:gid] = old - - trans = assert_events(comp, [], "group") - - newgid = old - while true - newgid += 1 - - if newgid - old > 1000 - $stderr.puts "Could not find extra test UID" - return - end - begin - Etc.getgrgid(newgid) - rescue ArgumentError => detail - break - end - end - - assert_nothing_raised("Failed to change group id") { - group[:gid] = newgid - } - - trans = assert_events(comp, [:group_modified], "group") - - curgid = nil - assert_nothing_raised { - curgid = gid(group[:name]) - } - - assert_equal(newgid, curgid, "GID was not changed") - - assert_rollback_events(trans, [:group_modified], "group") - - assert_nothing_raised { - curgid = gid(group[:name]) - } - - assert_equal(old, curgid, "UID was not reverted") - end - - def test_eachmethod - obj = Etc.getgrnam(groupnames()[0]) - - assert(obj, "Could not retrieve test group object") - - Puppet::Type::Group.validstates.each { |name, state| - assert_nothing_raised { - method = state.infomethod - assert(method, "State %s has no infomethod" % name) - assert(obj.respond_to?(method), - "State %s has an invalid method %s" % - [name, method] - ) - } - - assert_nothing_raised { - method = state.infomethod - assert(method, "State %s has no infomethod" % name) - assert(obj.respond_to?(method), - "State %s has an invalid method %s" % - [name, method] - ) - } - } - end - - def test_owngroups - groupnames().each { |group| - gobj = nil - comp = nil - assert_nothing_raised { - gobj = Puppet::Type::Group.create( - :name => group, - :check => [:gid] - ) - - comp = newcomp("grouptest %s" % group, gobj) - } - - trans = nil - assert_nothing_raised { - trans = comp.evaluate - } - - assert(gobj.is(:gid), "Failed to retrieve gid") - } - end - - if Process.uid == 0 - def test_mkgroup - gobj = nil - comp = nil - name = "pptestgr" - - os = Facter["operatingsystem"].value - - #if os == "Darwin" - # obj = nil - # assert_nothing_raised { - # obj = Etc.getgrnam(name) - # } - # assert_equal(-2, obj.gid, "Darwin GID is not -2") - #else - #assert_raise(ArgumentError) { - # obj = Etc.getgrnam(name) - #} - #end - assert(missing?(name), "Group %s is still present" % name) - - assert_nothing_raised { - gobj = Puppet::Type::Group.create( - :name => name - ) - - comp = newcomp("groupmaker %s" % name, gobj) - } - - @@tmpgroups << name - trans = assert_events(comp, [:group_created], "group") - - obj = nil - assert_nothing_raised { - obj = Etc.getgrnam(name) - } - assert(!missing?(name), "Group %s is missing" % name) - - tests = Puppet::Type::Group.validstates.collect { |sname, state| - state.name - } - - gobj.retrieve - tests.each { |test| - if self.respond_to?("attrtest_%s" % test) - self.send("attrtest_%s" % test, gobj) - else - #$stderr.puts "Not testing attr %s of group" % test - end - } - - assert_rollback_events(trans, [:group_deleted], "group") - - assert(missing?(name), "Group %s is still present" % name) - end - else - $stderr.puts "Not running as root; skipping group creation tests." - end -end diff --git a/test/types/tc_package.rb b/test/types/tc_package.rb deleted file mode 100644 index 1936c8bbc..000000000 --- a/test/types/tc_package.rb +++ /dev/null @@ -1,205 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppettest' -require 'puppet' -require 'test/unit' -require 'facter' - -$platform = Facter["operatingsystem"].value - -unless Puppet::Type::Package.default - puts "No default package type for %s; skipping package tests" % $platform -else - -class TestPackageSource < Test::Unit::TestCase - include TestPuppet - def test_filesource - system("touch /tmp/fakepackage") - assert_equal( - "/tmp/fakepackage", - Puppet::PackageSource.get("file:///tmp/fakepackage") - ) - system("rm -f /tmp/fakepackage") - end -end - -class TestPackages < Test::Unit::TestCase - include FileTesting - def setup - #@list = Puppet::Type::Package.getpkglist - Puppet::Type::Package.clear - super - end - - # These are packages that we're sure will be installed - def installedpkgs - pkgs = nil - case $platform - when "SunOS" - pkgs = %w{SMCossh} - when "Linux" - case Facter["distro"].value - when "Debian": pkgs = %w{ssh openssl} - when "Fedora": pkgs = %w{openssh} - #when "RedHat": type = :rpm - else - Puppet.notice "No test package for %s" % $platform - return [] - end - else - Puppet.notice "No test package for %s" % $platform - return [] - end - - return pkgs - end - - def tstpkg - case $platform - #when "SunOS" - # type = "sunpkg" - when "Linux" - case Facter["distro"].value - when "Debian": - return %w{zec} - #when "RedHat": type = :rpm - when "Fedora": - return %w{wv} - else - Puppet.notice "No test packags for %s" % $platform - return nil - end - else - Puppet.notice "No test packags for %s" % $platform - return nil - end - end - - def mkpkgcomp(pkg) - assert_nothing_raised { - pkg = Puppet::Type::Package.create(:name => pkg, :install => true) - } - assert_nothing_raised { - pkg.retrieve - } - - comp = newcomp("package", pkg) - - return comp - end - - def test_retrievepkg - installedpkgs().each { |pkg| - obj = nil - assert_nothing_raised { - obj = Puppet::Type::Package.create( - :name => pkg - ) - } - - assert(obj, "could not create package") - - assert_nothing_raised { - obj.retrieve - } - - assert(obj.is(:install), "Could not retrieve package version") - } - end - - def test_nosuchpkg - obj = nil - assert_nothing_raised { - obj = Puppet::Type::Package.create( - :name => "thispackagedoesnotexist" - ) - } - - assert_nothing_raised { - obj.retrieve - } - - assert_equal(:notinstalled, obj.is(:install), - "Somehow retrieved unknown pkg's version") - end - - def test_latestpkg - pkgs = tstpkg || return - - pkgs.each { |name| - pkg = Puppet::Type::Package.create(:name => name) - assert_nothing_raised { - assert(pkg.latest, "Package did not return value for 'latest'") - } - } - end - - unless Process.uid == 0 - $stderr.puts "Run as root to perform package installation tests" - else - def test_installpkg - pkgs = tstpkg || return - pkgs.each { |pkg| - # we first set install to 'true', and make sure something gets - # installed - assert_nothing_raised { - pkg = Puppet::Type::Package.create(:name => pkg, :install => true) - } - assert_nothing_raised { - pkg.retrieve - } - - if pkg.insync? - Puppet.notice "Test package %s is already installed; please choose a different package for testing" % pkg - next - end - - comp = newcomp("package", pkg) - - assert_events(comp, [:package_installed], "package") - - # then uninstall it - assert_nothing_raised { - pkg[:install] = false - } - - - pkg.retrieve - - assert(! pkg.insync?, "Package is insync") - - assert_events(comp, [:package_removed], "package") - - # and now set install to 'latest' and verify it installs - # FIXME this isn't really a very good test -- we should install - # a low version, and then upgrade using this. But, eh. - assert_nothing_raised { - pkg[:install] = "latest" - } - - assert_events(comp, [:package_installed], "package") - - pkg.retrieve - assert(pkg.insync?, "After install, package is not insync") - - assert_nothing_raised { - pkg[:install] = false - } - - - pkg.retrieve - - assert(! pkg.insync?, "Package is insync") - - assert_events(comp, [:package_removed], "package") - } - end - end -end -end - -# $Id$ diff --git a/test/types/tc_query.rb b/test/types/tc_query.rb deleted file mode 100644 index 1793e1e17..000000000 --- a/test/types/tc_query.rb +++ /dev/null @@ -1,109 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'test/unit' - -# $Id$ - -class TestQuery < Test::Unit::TestCase - def setup - Puppet[:loglevel] = :debug if __FILE__ == $0 - end - - def teardown - assert_nothing_raised() { - Puppet::Type.allclear - } - end - - # hmmm - # this is complicated, because we store references to the created - # objects in a central store - def file - assert_nothing_raised() { - cfile = File.join($puppetbase,"examples/root/etc/configfile") - unless Puppet::Type::PFile.has_key?(cfile) - Puppet::Type::PFile.create( - :path => cfile, - :check => [:mode, :owner, :checksum] - ) - end - @configfile = Puppet::Type::PFile[cfile] - } - return @configfile - end - - def service - assert_nothing_raised() { - unless Puppet::Type::Service.has_key?("sleeper") - Puppet::Type::Service.create( - :name => "sleeper", - :type => "init", - :path => File.join($puppetbase,"examples/root/etc/init.d"), - :hasstatus => true, - :check => [:running] - ) - end - @sleeper = Puppet::Type::Service["sleeper"] - } - - return @sleeper - end - - def component(name,*args) - assert_nothing_raised() { - @component = Puppet::Type::Component.create(:name => name) - } - - args.each { |arg| - assert_nothing_raised() { - @component.push arg - } - } - - return @component - end - - def test_file - yayfile = file() - #p yayfile - yayfile.eachstate { |state| - assert_nil(state.is) - } - - assert_nothing_raised() { - yayfile.retrieve - } - - assert_nothing_raised() { - yayfile[:check] = :group - } - - assert_nothing_raised() { - yayfile.retrieve - } - end - - def test_service - service = service() - service.eachstate { |state| - assert_nil(state.is) - } - - assert_nothing_raised() { - service.retrieve - } - end - - def test_component - component = component("a",file(),service()) - - assert_nothing_raised() { - component.retrieve - } - end -end diff --git a/test/types/tc_service.rb b/test/types/tc_service.rb deleted file mode 100644 index 5d99d662d..000000000 --- a/test/types/tc_service.rb +++ /dev/null @@ -1,101 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../.." -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -class TestService < Test::Unit::TestCase - include TestPuppet - # hmmm - # this is complicated, because we store references to the created - # objects in a central store - def setup - sleeper = nil - script = File.join($puppetbase,"examples/root/etc/init.d/sleeper") - @status = script + " status" - - super - end - - def teardown - stopservices - super - end - - def mksleeper(hash = {}) - hash[:name] = "sleeper" - hash[:path] = File.join($puppetbase,"examples/root/etc/init.d") - hash[:running] = true - hash[:type] = "init" - assert_nothing_raised() { - return Puppet::Type::Service.create(hash) - } - end - - def cyclesleeper(sleeper) - assert_nothing_raised() { - sleeper.retrieve - } - assert(!sleeper.insync?()) - assert_nothing_raised() { - sleeper.sync - } - assert_nothing_raised() { - sleeper.retrieve - } - assert(sleeper.insync?) - - # test refreshing it - assert_nothing_raised() { - sleeper.refresh - } - - assert(sleeper.respond_to?(:refresh)) - - # now stop it - assert_nothing_raised() { - sleeper[:running] = 0 - } - assert_nothing_raised() { - sleeper.retrieve - } - assert(!sleeper.insync?()) - assert_nothing_raised() { - sleeper.sync - } - assert_nothing_raised() { - sleeper.retrieve - } - assert(sleeper.insync?) - end - - def test_processStartWithPattern - sleeper = mksleeper(:pattern => "bin/sleeper") - - cyclesleeper(sleeper) - end - - def test_processStartWithStatus - sleeper = mksleeper(:hasstatus => true) - cyclesleeper(sleeper) - end - - unless Process.uid == 0 - puts "run as root to test service enable/disable" - else - case Puppet::Type::Service.defaulttype - when Puppet::ServiceTypes::InitSvc - when Puppet::ServiceTypes::SMFSvc - # yay - else - Puppet.notice "Not testing service type %s" % - Puppet::Type::Service.defaulttype - end - end -end - -# $Id$ diff --git a/test/types/tc_symlink.rb b/test/types/tc_symlink.rb deleted file mode 100755 index 3d288bc0a..000000000 --- a/test/types/tc_symlink.rb +++ /dev/null @@ -1,93 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -# $Id$ - -class TestSymlink < Test::Unit::TestCase - include FileTesting - def mktmpfile - # because luke's home directory is on nfs, it can't be used for testing - # as root - tmpfile = tempfile() - File.open(tmpfile, "w") { |f| f.puts rand(100) } - @@tmpfiles.push tmpfile - return tmpfile - end - - def mktmpdir - dir = File.join(tmpdir(), "puppetlinkdir") - unless FileTest.exists?(dir) - Dir.mkdir(dir) - end - @@tmpfiles.push dir - return dir - end - - def tmplink - link = File.join(tmpdir(), "puppetlinktest") - @@tmpfiles.push link - return link - end - - def newlink(hash = {}) - hash[:name] = tmplink() - unless hash.include?(:target) - hash[:target] = mktmpfile() - end - link = Puppet::Type::Symlink.create(hash) - return link - end - - def test_target - link = nil - file = mktmpfile() - assert_nothing_raised() { - link = newlink() - } - assert_nothing_raised() { - link.retrieve - } - # we might already be in sync - assert(!link.insync?()) - assert_nothing_raised() { - link.sync - } - assert_nothing_raised() { - link.retrieve - } - assert(link.insync?()) - end - - def test_recursion - source = mktmpdir() - FileUtils.cd(source) { - mkranddirsandfiles() - } - - link = nil - assert_nothing_raised { - link = newlink(:target => source, :recurse => true) - } - comp = newcomp("linktest",link) - cycle(comp) - - path = link.name - list = file_list(path) - FileUtils.cd(path) { - list.each { |file| - unless FileTest.directory?(file) - assert(FileTest.symlink?(file)) - target = File.readlink(file) - assert_equal(target,File.join(source,file.sub(/^\.\//,''))) - end - } - } - end -end diff --git a/test/types/tc_tidy.rb b/test/types/tc_tidy.rb deleted file mode 100755 index 02068b6ff..000000000 --- a/test/types/tc_tidy.rb +++ /dev/null @@ -1,124 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -require 'puppet' -require 'puppettest' -require 'test/unit' - -# $Id$ - -class TestTidy < Test::Unit::TestCase - include FileTesting - def mktmpfile - # because luke's home directory is on nfs, it can't be used for testing - # as root - tmpfile = tempfile() - File.open(tmpfile, "w") { |f| f.puts rand(100) } - @@tmpfiles.push tmpfile - return tmpfile - end - - def mktmpdir - dir = File.join(tmpdir(), "puppetlinkdir") - unless FileTest.exists?(dir) - Dir.mkdir(dir) - end - @@tmpfiles.push dir - return dir - end - - def test_simpletidy - dir = mktmpdir - file = File.join(dir, "tidytesting") - File.open(file, "w") { |f| - f.puts rand(100) - } - - tidy = Puppet::Type::Tidy.create( - :name => dir, - :size => "1b", - :recurse => true - ) - - comp = newcomp("tidytesting", tidy) - - trans = nil - assert_nothing_raised { - trans = comp.evaluate - } - event = nil - assert_nothing_raised { - event = trans.evaluate.collect { |e| e.event } - } - - assert_equal(1, event.length, "Got no events on tidy") - assert_equal([:file_tidied], event, "Got incorrect event on tidy") - - assert(!FileTest.exists?(file), "Tidied file still exists") - end - - def test_tidydirs - dir = mktmpdir - file = File.join(dir, "tidytesting") - File.open(file, "w") { |f| - f.puts rand(100) - } - - tidy = Puppet::Type::Tidy.create( - :name => dir, - :size => "1b", - :age => "1s", - :rmdirs => true, - :recurse => true - ) - - comp = newcomp("tidytesting", tidy) - - sleep(2) - trans = nil - assert_nothing_raised { - trans = comp.evaluate - } - event = nil - assert_nothing_raised { - event = trans.evaluate.collect { |e| e.event } - } - - assert(!FileTest.exists?(file), "Tidied %s still exists" % file) - assert(!FileTest.exists?(dir), "Tidied %s still exists" % dir) - - assert_equal(2, event.length, "Got %s events instead of %s on tidy" % - [event.length, 2]) - assert_equal([:file_tidied, :file_tidied], event, - "Got incorrect events on tidy") - end - - def disabled_test_recursion - source = mktmpdir() - FileUtils.cd(source) { - mkranddirsandfiles() - } - - link = nil - assert_nothing_raised { - link = newlink(:target => source, :recurse => true) - } - comp = newcomp("linktest",link) - cycle(comp) - - path = link.name - list = file_list(path) - FileUtils.cd(path) { - list.each { |file| - unless FileTest.directory?(file) - assert(FileTest.symlink?(file)) - target = File.readlink(file) - assert_equal(target,File.join(source,file.sub(/^\.\//,''))) - end - } - } - end -end diff --git a/test/types/tc_type.rb b/test/types/tc_type.rb deleted file mode 100644 index 509a4b402..000000000 --- a/test/types/tc_type.rb +++ /dev/null @@ -1,114 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -# $Id$ - -require 'puppet/type' -require 'puppettest' -require 'test/unit' - -class TestType < Test::Unit::TestCase - include TestPuppet - def test_typemethods - assert_nothing_raised() { - Puppet::Type.buildstatehash - } - - Puppet::Type.eachtype { |type| - name = nil - assert_nothing_raised("Searching for name for %s caused failure" % - type.to_s) { - name = type.name - } - - assert(name, "Could not find name for %s" % type.to_s) - - assert_equal( - type, - Puppet::Type.type(name), - "Failed to retrieve %s by name" % name - ) - - assert( - type.namevar, - "Failed to retrieve namevar for %s" % name - ) - - assert_not_nil( - type.states, - "States for %s are nil" % name - ) - - assert_not_nil( - type.validstates, - "Valid states for %s are nil" % name - ) - } - end - - def test_stringvssymbols - file = nil - path = "/tmp/testfile" - assert_nothing_raised() { - system("rm -f %s" % path) - file = Puppet::Type::PFile.create( - :path => path, - :create => true, - :recurse => true, - :checksum => "md5" - ) - } - assert_nothing_raised() { - file.retrieve - } - assert_nothing_raised() { - file.sync - } - Puppet::Type::PFile.clear - assert_nothing_raised() { - system("rm -f %s" % path) - file = Puppet::Type::PFile.create( - "path" => path, - "create" => true, - "recurse" => true, - "checksum" => "md5" - ) - } - assert_nothing_raised() { - file.retrieve - } - assert_nothing_raised() { - file[:path] - } - assert_nothing_raised() { - file["path"] - } - assert_nothing_raised() { - file[:recurse] - } - assert_nothing_raised() { - file["recurse"] - } - assert_nothing_raised() { - file.sync - } - end - - # This was supposed to test objects whose name was a state, but that - # fundamentally doesn't make much sense, and we now don't have any such - # types. - def disabled_test_nameasstate - # currently groups are the only objects with the namevar as a state - group = nil - assert_nothing_raised { - group = Puppet::Type::Group.create( - :name => "testing" - ) - } - - assert_equal("testing", group.name, "Could not retrieve name") - end -end diff --git a/test/types/tc_user.rb b/test/types/tc_user.rb deleted file mode 100755 index f418872a0..000000000 --- a/test/types/tc_user.rb +++ /dev/null @@ -1,350 +0,0 @@ -if __FILE__ == $0 - $:.unshift '..' - $:.unshift '../../lib' - $puppetbase = "../../../../language/trunk" -end - -# $Id$ - -require 'etc' -require 'puppet/type' -require 'puppettest' -require 'test/unit' - -class TestUser < Test::Unit::TestCase - include TestPuppet - def setup - @@tmpusers = [] - Puppet[:loglevel] = :debug if __FILE__ == $0 - super - end - - def teardown - @@tmpusers.each { |user| - unless missing?(user) - remove(user) - end - } - super - end - - case Facter["operatingsystem"].value - when "Darwin": - def missing?(user) - output = %x{nidump -r /users/#{user} / 2>/dev/null}.chomp - - if output == "" - return true - else - return false - end - - assert_equal("", output, "User %s is present:\n%s" % [user, output]) - end - - def current?(param, name) - state = Puppet::Type::User.states.find { |st| - st.name == param - } - - output = %x{nireport / /users name #{state.netinfokey}} - output.split("\n").each { |line| - if line =~ /^(\w+)\s+(.+)$/ - user = $1 - id = $2.sub(/\s+$/, '') - if user == name - if id =~ /^[-0-9]+$/ - return Integer(id) - else - return id - end - end - else - raise "Could not match %s" % line - end - } - - return nil - end - - def remove(user) - system("niutil -destroy / /users/%s" % user) - end - else - def missing?(user) - begin - obj = Etc.getpwnam(user) - return false - rescue ArgumentError - return true - end - end - - def current?(param, name) - state = Puppet::Type::User.states.find { |st| - st.name == param - } - - assert_nothing_raised { - obj = Etc.getpwnam(name) - return obj.send(state.posixmethod) - } - - return nil - end - - def remove(user) - system("userdel %s" % user) - end - end - - def findshell(old = nil) - %w{/bin/sh /bin/bash /sbin/sh /bin/ksh /bin/zsh /bin/csh /bin/tcsh - /usr/bin/sh /usr/bin/bash /usr/bin/ksh /usr/bin/zsh /usr/bin/csh - /usr/bin/tcsh}.find { |shell| - if old - FileTest.exists?(shell) and shell != old - else - FileTest.exists?(shell) - end - } - end - - def mkuser(name) - user = nil - assert_nothing_raised { - user = Puppet::Type::User.create( - :name => name, - :comment => "Puppet Testing User", - :gid => Process.gid, - :shell => findshell(), - :home => "/home/%s" % name - ) - } - - return user - end - - def attrtest_comment(user) - old = user.is(:comment) - user[:comment] = "A different comment" - - comp = newcomp("commenttest", user) - - trans = assert_events(comp, [:user_modified], "user") - - assert_equal("A different comment", current?(:comment, user[:name]), - "Comment was not changed") - - assert_rollback_events(trans, [:user_modified], "user") - - assert_equal(old, current?(:comment, user[:name]), - "Comment was not reverted") - end - - def attrtest_home(user) - obj = nil - comp = newcomp("hometest", user) - - old = current?(:home, user[:name]) - user[:home] = old - - trans = assert_events(comp, [], "user") - - user[:home] = "/tmp" - - trans = assert_events(comp, [:user_modified], "user") - - assert_equal("/tmp", current?(:home, user[:name]), "Home was not changed") - - assert_rollback_events(trans, [:user_modified], "user") - - assert_equal(old, current?(:home, user[:name]), "Home was not reverted") - end - - def attrtest_shell(user) - old = current?(:shell, user[:name]) - comp = newcomp("shelltest", user) - - user[:shell] = old - - trans = assert_events(comp, [], "user") - - newshell = findshell(old) - - unless newshell - $stderr.puts "Cannot find alternate shell; skipping shell test" - return - end - - user[:shell] = newshell - - trans = assert_events(comp, [:user_modified], "user") - - assert_equal(newshell, current?(:shell, user[:name]), - "Shell was not changed") - - assert_rollback_events(trans, [:user_modified], "user") - - assert_equal(old, current?(:shell, user[:name]), "Shell was not reverted") - end - - def attrtest_gid(user) - obj = nil - old = current?(:gid,user.name) - comp = newcomp("gidtest", user) - - user.retrieve - - user[:gid] = old - - trans = assert_events(comp, [], "user") - - newgid = %w{nogroup nobody staff users daemon}.find { |gid| - begin - group = Etc.getgrnam(gid) - rescue ArgumentError => detail - next - end - old != group.gid - } - - unless newgid - $stderr.puts "Cannot find alternate group; skipping gid test" - return - end - - # first test by name - assert_nothing_raised("Failed to specify group by name") { - user[:gid] = newgid - } - - trans = assert_events(comp, [:user_modified], "user") - - # then by id - newgid = Etc.getgrnam(newgid).gid - - assert_nothing_raised("Failed to specify group by id") { - user[:gid] = newgid - } - - user.retrieve - - assert_events(comp, [], "user") - - assert_equal(newgid, current?(:gid,user[:name]), "GID was not changed") - - assert_rollback_events(trans, [:user_modified], "user") - - assert_equal(old, current?(:gid,user[:name]), "GID was not reverted") - end - - def attrtest_uid(user) - obj = nil - comp = newcomp("uidtest", user) - - old = current?(:uid, user[:name]) - user[:uid] = old - - trans = assert_events(comp, [], "user") - - newuid = old - while true - newuid += 1 - - if newuid - old > 1000 - $stderr.puts "Could not find extra test UID" - return - end - begin - newuser = Etc.getpwuid(newuid) - rescue ArgumentError => detail - break - end - end - - assert_nothing_raised("Failed to change user id") { - user[:uid] = newuid - } - - trans = assert_events(comp, [:user_modified], "user") - - assert_equal(newuid, current?(:uid, user[:name]), "UID was not changed") - - assert_rollback_events(trans, [:user_modified], "user") - - assert_equal(old, current?(:uid, user[:name]), "UID was not reverted") - end - - def test_eachmethod - obj = Etc.getpwuid(Process.uid) - - assert(obj, "Could not retrieve test group object") - - Puppet::Type::User.validstates.each { |name, state| - assert_nothing_raised { - method = state.posixmethod - assert(method, "State %s has no infomethod" % name) - assert(obj.respond_to?(method), - "State %s has an invalid method %s" % - [name, method]) - } - } - end - - if Process.uid == 0 - def test_simpleuser - name = "pptest" - - assert(missing?(name), "User %s is present" % name) - - user = mkuser(name) - - @@tmpusers << name - - comp = newcomp("usercomp", user) - - trans = assert_events(comp, [:user_created], "user") - - assert_equal("Puppet Testing User", current?(:comment, user[:name]), - "Comment was not set") - - assert_rollback_events(trans, [:user_deleted], "user") - - assert(missing?(user[:name])) - end - - def test_allstates - user = nil - name = "pptest" - - assert(missing?(name), "User %s is present" % name) - - user = mkuser(name) - - @@tmpusers << name - - comp = newcomp("usercomp", user) - - trans = assert_events(comp, [:user_created], "user") - - assert_equal("Puppet Testing User", current?(:comment, user[:name]), - "Comment was not set") - - tests = Puppet::Type::User.validstates.collect { |name, state| - state.name - } - - user.retrieve - tests.each { |test| - if self.respond_to?("attrtest_%s" % test) - self.send("attrtest_%s" % test, user) - else - $stderr.puts "Not testing attr %s of user" % test - end - } - end - else - $stderr.puts "Not root; skipping user creation/modification tests" - end -end diff --git a/test/types/tidy.rb b/test/types/tidy.rb new file mode 100755 index 000000000..02068b6ff --- /dev/null +++ b/test/types/tidy.rb @@ -0,0 +1,124 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +require 'puppet' +require 'puppettest' +require 'test/unit' + +# $Id$ + +class TestTidy < Test::Unit::TestCase + include FileTesting + def mktmpfile + # because luke's home directory is on nfs, it can't be used for testing + # as root + tmpfile = tempfile() + File.open(tmpfile, "w") { |f| f.puts rand(100) } + @@tmpfiles.push tmpfile + return tmpfile + end + + def mktmpdir + dir = File.join(tmpdir(), "puppetlinkdir") + unless FileTest.exists?(dir) + Dir.mkdir(dir) + end + @@tmpfiles.push dir + return dir + end + + def test_simpletidy + dir = mktmpdir + file = File.join(dir, "tidytesting") + File.open(file, "w") { |f| + f.puts rand(100) + } + + tidy = Puppet::Type::Tidy.create( + :name => dir, + :size => "1b", + :recurse => true + ) + + comp = newcomp("tidytesting", tidy) + + trans = nil + assert_nothing_raised { + trans = comp.evaluate + } + event = nil + assert_nothing_raised { + event = trans.evaluate.collect { |e| e.event } + } + + assert_equal(1, event.length, "Got no events on tidy") + assert_equal([:file_tidied], event, "Got incorrect event on tidy") + + assert(!FileTest.exists?(file), "Tidied file still exists") + end + + def test_tidydirs + dir = mktmpdir + file = File.join(dir, "tidytesting") + File.open(file, "w") { |f| + f.puts rand(100) + } + + tidy = Puppet::Type::Tidy.create( + :name => dir, + :size => "1b", + :age => "1s", + :rmdirs => true, + :recurse => true + ) + + comp = newcomp("tidytesting", tidy) + + sleep(2) + trans = nil + assert_nothing_raised { + trans = comp.evaluate + } + event = nil + assert_nothing_raised { + event = trans.evaluate.collect { |e| e.event } + } + + assert(!FileTest.exists?(file), "Tidied %s still exists" % file) + assert(!FileTest.exists?(dir), "Tidied %s still exists" % dir) + + assert_equal(2, event.length, "Got %s events instead of %s on tidy" % + [event.length, 2]) + assert_equal([:file_tidied, :file_tidied], event, + "Got incorrect events on tidy") + end + + def disabled_test_recursion + source = mktmpdir() + FileUtils.cd(source) { + mkranddirsandfiles() + } + + link = nil + assert_nothing_raised { + link = newlink(:target => source, :recurse => true) + } + comp = newcomp("linktest",link) + cycle(comp) + + path = link.name + list = file_list(path) + FileUtils.cd(path) { + list.each { |file| + unless FileTest.directory?(file) + assert(FileTest.symlink?(file)) + target = File.readlink(file) + assert_equal(target,File.join(source,file.sub(/^\.\//,''))) + end + } + } + end +end diff --git a/test/types/type.rb b/test/types/type.rb new file mode 100644 index 000000000..509a4b402 --- /dev/null +++ b/test/types/type.rb @@ -0,0 +1,114 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +# $Id$ + +require 'puppet/type' +require 'puppettest' +require 'test/unit' + +class TestType < Test::Unit::TestCase + include TestPuppet + def test_typemethods + assert_nothing_raised() { + Puppet::Type.buildstatehash + } + + Puppet::Type.eachtype { |type| + name = nil + assert_nothing_raised("Searching for name for %s caused failure" % + type.to_s) { + name = type.name + } + + assert(name, "Could not find name for %s" % type.to_s) + + assert_equal( + type, + Puppet::Type.type(name), + "Failed to retrieve %s by name" % name + ) + + assert( + type.namevar, + "Failed to retrieve namevar for %s" % name + ) + + assert_not_nil( + type.states, + "States for %s are nil" % name + ) + + assert_not_nil( + type.validstates, + "Valid states for %s are nil" % name + ) + } + end + + def test_stringvssymbols + file = nil + path = "/tmp/testfile" + assert_nothing_raised() { + system("rm -f %s" % path) + file = Puppet::Type::PFile.create( + :path => path, + :create => true, + :recurse => true, + :checksum => "md5" + ) + } + assert_nothing_raised() { + file.retrieve + } + assert_nothing_raised() { + file.sync + } + Puppet::Type::PFile.clear + assert_nothing_raised() { + system("rm -f %s" % path) + file = Puppet::Type::PFile.create( + "path" => path, + "create" => true, + "recurse" => true, + "checksum" => "md5" + ) + } + assert_nothing_raised() { + file.retrieve + } + assert_nothing_raised() { + file[:path] + } + assert_nothing_raised() { + file["path"] + } + assert_nothing_raised() { + file[:recurse] + } + assert_nothing_raised() { + file["recurse"] + } + assert_nothing_raised() { + file.sync + } + end + + # This was supposed to test objects whose name was a state, but that + # fundamentally doesn't make much sense, and we now don't have any such + # types. + def disabled_test_nameasstate + # currently groups are the only objects with the namevar as a state + group = nil + assert_nothing_raised { + group = Puppet::Type::Group.create( + :name => "testing" + ) + } + + assert_equal("testing", group.name, "Could not retrieve name") + end +end diff --git a/test/types/user.rb b/test/types/user.rb new file mode 100755 index 000000000..f418872a0 --- /dev/null +++ b/test/types/user.rb @@ -0,0 +1,350 @@ +if __FILE__ == $0 + $:.unshift '..' + $:.unshift '../../lib' + $puppetbase = "../../../../language/trunk" +end + +# $Id$ + +require 'etc' +require 'puppet/type' +require 'puppettest' +require 'test/unit' + +class TestUser < Test::Unit::TestCase + include TestPuppet + def setup + @@tmpusers = [] + Puppet[:loglevel] = :debug if __FILE__ == $0 + super + end + + def teardown + @@tmpusers.each { |user| + unless missing?(user) + remove(user) + end + } + super + end + + case Facter["operatingsystem"].value + when "Darwin": + def missing?(user) + output = %x{nidump -r /users/#{user} / 2>/dev/null}.chomp + + if output == "" + return true + else + return false + end + + assert_equal("", output, "User %s is present:\n%s" % [user, output]) + end + + def current?(param, name) + state = Puppet::Type::User.states.find { |st| + st.name == param + } + + output = %x{nireport / /users name #{state.netinfokey}} + output.split("\n").each { |line| + if line =~ /^(\w+)\s+(.+)$/ + user = $1 + id = $2.sub(/\s+$/, '') + if user == name + if id =~ /^[-0-9]+$/ + return Integer(id) + else + return id + end + end + else + raise "Could not match %s" % line + end + } + + return nil + end + + def remove(user) + system("niutil -destroy / /users/%s" % user) + end + else + def missing?(user) + begin + obj = Etc.getpwnam(user) + return false + rescue ArgumentError + return true + end + end + + def current?(param, name) + state = Puppet::Type::User.states.find { |st| + st.name == param + } + + assert_nothing_raised { + obj = Etc.getpwnam(name) + return obj.send(state.posixmethod) + } + + return nil + end + + def remove(user) + system("userdel %s" % user) + end + end + + def findshell(old = nil) + %w{/bin/sh /bin/bash /sbin/sh /bin/ksh /bin/zsh /bin/csh /bin/tcsh + /usr/bin/sh /usr/bin/bash /usr/bin/ksh /usr/bin/zsh /usr/bin/csh + /usr/bin/tcsh}.find { |shell| + if old + FileTest.exists?(shell) and shell != old + else + FileTest.exists?(shell) + end + } + end + + def mkuser(name) + user = nil + assert_nothing_raised { + user = Puppet::Type::User.create( + :name => name, + :comment => "Puppet Testing User", + :gid => Process.gid, + :shell => findshell(), + :home => "/home/%s" % name + ) + } + + return user + end + + def attrtest_comment(user) + old = user.is(:comment) + user[:comment] = "A different comment" + + comp = newcomp("commenttest", user) + + trans = assert_events(comp, [:user_modified], "user") + + assert_equal("A different comment", current?(:comment, user[:name]), + "Comment was not changed") + + assert_rollback_events(trans, [:user_modified], "user") + + assert_equal(old, current?(:comment, user[:name]), + "Comment was not reverted") + end + + def attrtest_home(user) + obj = nil + comp = newcomp("hometest", user) + + old = current?(:home, user[:name]) + user[:home] = old + + trans = assert_events(comp, [], "user") + + user[:home] = "/tmp" + + trans = assert_events(comp, [:user_modified], "user") + + assert_equal("/tmp", current?(:home, user[:name]), "Home was not changed") + + assert_rollback_events(trans, [:user_modified], "user") + + assert_equal(old, current?(:home, user[:name]), "Home was not reverted") + end + + def attrtest_shell(user) + old = current?(:shell, user[:name]) + comp = newcomp("shelltest", user) + + user[:shell] = old + + trans = assert_events(comp, [], "user") + + newshell = findshell(old) + + unless newshell + $stderr.puts "Cannot find alternate shell; skipping shell test" + return + end + + user[:shell] = newshell + + trans = assert_events(comp, [:user_modified], "user") + + assert_equal(newshell, current?(:shell, user[:name]), + "Shell was not changed") + + assert_rollback_events(trans, [:user_modified], "user") + + assert_equal(old, current?(:shell, user[:name]), "Shell was not reverted") + end + + def attrtest_gid(user) + obj = nil + old = current?(:gid,user.name) + comp = newcomp("gidtest", user) + + user.retrieve + + user[:gid] = old + + trans = assert_events(comp, [], "user") + + newgid = %w{nogroup nobody staff users daemon}.find { |gid| + begin + group = Etc.getgrnam(gid) + rescue ArgumentError => detail + next + end + old != group.gid + } + + unless newgid + $stderr.puts "Cannot find alternate group; skipping gid test" + return + end + + # first test by name + assert_nothing_raised("Failed to specify group by name") { + user[:gid] = newgid + } + + trans = assert_events(comp, [:user_modified], "user") + + # then by id + newgid = Etc.getgrnam(newgid).gid + + assert_nothing_raised("Failed to specify group by id") { + user[:gid] = newgid + } + + user.retrieve + + assert_events(comp, [], "user") + + assert_equal(newgid, current?(:gid,user[:name]), "GID was not changed") + + assert_rollback_events(trans, [:user_modified], "user") + + assert_equal(old, current?(:gid,user[:name]), "GID was not reverted") + end + + def attrtest_uid(user) + obj = nil + comp = newcomp("uidtest", user) + + old = current?(:uid, user[:name]) + user[:uid] = old + + trans = assert_events(comp, [], "user") + + newuid = old + while true + newuid += 1 + + if newuid - old > 1000 + $stderr.puts "Could not find extra test UID" + return + end + begin + newuser = Etc.getpwuid(newuid) + rescue ArgumentError => detail + break + end + end + + assert_nothing_raised("Failed to change user id") { + user[:uid] = newuid + } + + trans = assert_events(comp, [:user_modified], "user") + + assert_equal(newuid, current?(:uid, user[:name]), "UID was not changed") + + assert_rollback_events(trans, [:user_modified], "user") + + assert_equal(old, current?(:uid, user[:name]), "UID was not reverted") + end + + def test_eachmethod + obj = Etc.getpwuid(Process.uid) + + assert(obj, "Could not retrieve test group object") + + Puppet::Type::User.validstates.each { |name, state| + assert_nothing_raised { + method = state.posixmethod + assert(method, "State %s has no infomethod" % name) + assert(obj.respond_to?(method), + "State %s has an invalid method %s" % + [name, method]) + } + } + end + + if Process.uid == 0 + def test_simpleuser + name = "pptest" + + assert(missing?(name), "User %s is present" % name) + + user = mkuser(name) + + @@tmpusers << name + + comp = newcomp("usercomp", user) + + trans = assert_events(comp, [:user_created], "user") + + assert_equal("Puppet Testing User", current?(:comment, user[:name]), + "Comment was not set") + + assert_rollback_events(trans, [:user_deleted], "user") + + assert(missing?(user[:name])) + end + + def test_allstates + user = nil + name = "pptest" + + assert(missing?(name), "User %s is present" % name) + + user = mkuser(name) + + @@tmpusers << name + + comp = newcomp("usercomp", user) + + trans = assert_events(comp, [:user_created], "user") + + assert_equal("Puppet Testing User", current?(:comment, user[:name]), + "Comment was not set") + + tests = Puppet::Type::User.validstates.collect { |name, state| + state.name + } + + user.retrieve + tests.each { |test| + if self.respond_to?("attrtest_%s" % test) + self.send("attrtest_%s" % test, user) + else + $stderr.puts "Not testing attr %s of user" % test + end + } + end + else + $stderr.puts "Not root; skipping user creation/modification tests" + end +end -- cgit