summaryrefslogtreecommitdiffstats
path: root/test
diff options
context:
space:
mode:
authorLuke Kanies <luke@madstop.com>2008-03-31 23:56:09 -0500
committerLuke Kanies <luke@madstop.com>2008-03-31 23:56:09 -0500
commit88dc49cb7b0efe757c92ce28c807b91335acb07a (patch)
tree13fe4561f1f524f97a8bb2c1ff84c1ef981d0241 /test
parent4165edaeb71ee2883b1bb85ff39a52d5628b259f (diff)
parenta8592f1009040ebf30a98268610915cc33bb3f63 (diff)
downloadpuppet-88dc49cb7b0efe757c92ce28c807b91335acb07a.tar.gz
puppet-88dc49cb7b0efe757c92ce28c807b91335acb07a.tar.xz
puppet-88dc49cb7b0efe757c92ce28c807b91335acb07a.zip
Merge branch 'master' into master_no_global_resources
Conflicts: lib/puppet/node/catalog.rb lib/puppet/type/pfile.rb lib/puppet/type/pfilebucket.rb lib/puppet/util/filetype.rb spec/unit/node/catalog.rb spec/unit/other/transbucket.rb spec/unit/ral/provider/mount/parsed.rb spec/unit/ral/types/file.rb spec/unit/ral/types/interface.rb spec/unit/ral/types/mount.rb spec/unit/ral/types/package.rb spec/unit/ral/types/schedule.rb spec/unit/ral/types/service.rb test/language/compile.rb test/language/lexer.rb test/language/snippets.rb test/lib/puppettest.rb test/ral/types/basic.rb test/ral/types/cron.rb test/ral/types/exec.rb test/ral/types/file.rb test/ral/types/file/target.rb test/ral/types/filebucket.rb test/ral/types/fileignoresource.rb test/ral/types/filesources.rb test/ral/types/group.rb test/ral/types/host.rb test/ral/types/parameter.rb test/ral/types/sshkey.rb test/ral/types/tidy.rb test/ral/types/user.rb test/ral/types/yumrepo.rb
Diffstat (limited to 'test')
-rw-r--r--test/data/snippets/collection_within_virtual_definitions.pp20
-rw-r--r--test/data/snippets/realize_defined_types.pp13
-rwxr-xr-xtest/executables/puppetbin.rb17
-rwxr-xr-xtest/language/ast.rb66
-rwxr-xr-xtest/language/ast/casestatement.rb6
-rwxr-xr-xtest/language/ast/definition.rb166
-rwxr-xr-xtest/language/ast/hostclass.rb184
-rwxr-xr-xtest/language/ast/resource.rb13
-rwxr-xr-xtest/language/ast/resource_reference.rb24
-rwxr-xr-xtest/language/ast/selector.rb4
-rwxr-xr-xtest/language/ast/variable.rb4
-rwxr-xr-xtest/language/compile.rb569
-rwxr-xr-xtest/language/functions.rb48
-rwxr-xr-xtest/language/lexer.rb275
-rwxr-xr-xtest/language/parser.rb29
-rwxr-xr-xtest/language/resource.rb202
-rwxr-xr-xtest/language/scope.rb58
-rwxr-xr-xtest/language/snippets.rb6
-rw-r--r--test/lib/mocha.rb19
-rw-r--r--test/lib/mocha/any_instance_method.rb35
-rw-r--r--test/lib/mocha/auto_verify.rb113
-rw-r--r--test/lib/mocha/central.rb35
-rw-r--r--test/lib/mocha/class_method.rb62
-rw-r--r--test/lib/mocha/deprecation.rb22
-rw-r--r--test/lib/mocha/exception_raiser.rb17
-rw-r--r--test/lib/mocha/expectation.rb378
-rw-r--r--test/lib/mocha/expectation_error.rb6
-rw-r--r--test/lib/mocha/infinite_range.rb25
-rw-r--r--test/lib/mocha/inspect.rb39
-rw-r--r--test/lib/mocha/instance_method.rb8
-rw-r--r--test/lib/mocha/is_a.rb9
-rw-r--r--test/lib/mocha/metaclass.rb7
-rw-r--r--test/lib/mocha/missing_expectation.rb27
-rw-r--r--test/lib/mocha/mock.rb207
-rw-r--r--test/lib/mocha/multiple_yields.rb20
-rw-r--r--test/lib/mocha/no_yields.rb11
-rw-r--r--test/lib/mocha/object.rb110
-rw-r--r--test/lib/mocha/parameter_matchers.rb9
-rw-r--r--test/lib/mocha/parameter_matchers/all_of.rb39
-rw-r--r--test/lib/mocha/parameter_matchers/any_of.rb44
-rw-r--r--test/lib/mocha/parameter_matchers/anything.rb30
-rw-r--r--test/lib/mocha/parameter_matchers/has_entry.rb39
-rw-r--r--test/lib/mocha/parameter_matchers/has_key.rb39
-rw-r--r--test/lib/mocha/parameter_matchers/has_value.rb39
-rw-r--r--test/lib/mocha/parameter_matchers/includes.rb37
-rw-r--r--test/lib/mocha/pretty_parameters.rb28
-rw-r--r--test/lib/mocha/return_values.rb31
-rw-r--r--test/lib/mocha/setup_and_teardown.rb23
-rw-r--r--test/lib/mocha/single_return_value.rb24
-rw-r--r--test/lib/mocha/single_yield.rb18
-rw-r--r--test/lib/mocha/standalone.rb32
-rw-r--r--test/lib/mocha/stub.rb18
-rw-r--r--test/lib/mocha/test_case_adapter.rb49
-rw-r--r--test/lib/mocha/yield_parameters.rb31
-rwxr-xr-xtest/lib/puppettest.rb49
-rw-r--r--test/lib/puppettest/parsertesting.rb20
-rwxr-xr-xtest/lib/puppettest/support/resources.rb2
-rwxr-xr-xtest/network/client/client.rb29
-rwxr-xr-xtest/network/client/master.rb41
-rwxr-xr-xtest/network/handler/fileserver.rb100
-rwxr-xr-xtest/network/handler/master.rb15
-rwxr-xr-xtest/network/server/webrick.rb2
-rwxr-xr-xtest/other/dsl.rb7
-rwxr-xr-xtest/other/transactions.rb8
-rwxr-xr-xtest/rails/ast.rb4
-rwxr-xr-xtest/rails/configuration.rb2
-rwxr-xr-xtest/rails/railsparameter.rb2
-rwxr-xr-xtest/rails/railsresource.rb1
-rwxr-xr-xtest/ral/manager/provider.rb26
-rwxr-xr-xtest/ral/manager/type.rb24
-rwxr-xr-xtest/ral/providers/cron/crontab.rb5
-rwxr-xr-xtest/ral/providers/mailalias/aliases.rb1
-rwxr-xr-xtest/ral/providers/sshkey/parsed.rb1
-rwxr-xr-xtest/ral/type/basic.rb (renamed from test/ral/types/basic.rb)16
-rwxr-xr-xtest/ral/type/cron.rb (renamed from test/ral/types/cron.rb)0
-rwxr-xr-xtest/ral/type/exec.rb (renamed from test/ral/types/exec.rb)51
-rwxr-xr-xtest/ral/type/file.rb (renamed from test/ral/types/file.rb)108
-rwxr-xr-xtest/ral/type/file/target.rb (renamed from test/ral/types/file/target.rb)0
-rwxr-xr-xtest/ral/type/filebucket.rb (renamed from test/ral/types/filebucket.rb)0
-rwxr-xr-xtest/ral/type/fileignoresource.rb (renamed from test/ral/types/fileignoresource.rb)0
-rwxr-xr-xtest/ral/type/filesources.rb (renamed from test/ral/types/filesources.rb)0
-rwxr-xr-xtest/ral/type/group.rb (renamed from test/ral/types/group.rb)0
-rwxr-xr-xtest/ral/type/host.rb (renamed from test/ral/types/host.rb)73
-rwxr-xr-xtest/ral/type/mailalias.rb (renamed from test/ral/types/mailalias.rb)0
-rwxr-xr-xtest/ral/type/parameter.rb (renamed from test/ral/types/parameter.rb)0
-rwxr-xr-xtest/ral/type/port.rb (renamed from test/ral/types/port.rb)0
-rwxr-xr-xtest/ral/type/property.rb (renamed from test/ral/types/property.rb)0
-rwxr-xr-xtest/ral/type/resources.rb (renamed from test/ral/types/resources.rb)0
-rwxr-xr-xtest/ral/type/service.rb (renamed from test/ral/types/service.rb)0
-rwxr-xr-xtest/ral/type/sshkey.rb (renamed from test/ral/types/sshkey.rb)0
-rwxr-xr-xtest/ral/type/tidy.rb (renamed from test/ral/types/tidy.rb)12
-rwxr-xr-xtest/ral/type/user.rb (renamed from test/ral/types/user.rb)0
-rwxr-xr-xtest/ral/type/yumrepo.rb (renamed from test/ral/types/yumrepo.rb)4
-rwxr-xr-xtest/ral/type/zone.rb (renamed from test/ral/types/zone.rb)0
-rwxr-xr-xtest/util/autoload.rb29
-rwxr-xr-xtest/util/settings.rb63
96 files changed, 529 insertions, 3550 deletions
diff --git a/test/data/snippets/collection_within_virtual_definitions.pp b/test/data/snippets/collection_within_virtual_definitions.pp
new file mode 100644
index 000000000..3c21468b0
--- /dev/null
+++ b/test/data/snippets/collection_within_virtual_definitions.pp
@@ -0,0 +1,20 @@
+define test($name) {
+ file {"/tmp/collection_within_virtual_definitions1_$name.txt":
+ content => "File name $name\n"
+ }
+ Test2 <||>
+}
+
+define test2() {
+ file {"/tmp/collection_within_virtual_definitions2_$name.txt":
+ content => "This is a test\n"
+ }
+}
+
+node default {
+ @test {"foo":
+ name => "foo"
+ }
+ @test2 {"foo2": }
+ Test <||>
+}
diff --git a/test/data/snippets/realize_defined_types.pp b/test/data/snippets/realize_defined_types.pp
deleted file mode 100644
index a4b562258..000000000
--- a/test/data/snippets/realize_defined_types.pp
+++ /dev/null
@@ -1,13 +0,0 @@
-define testing {
- file { "/tmp/realize_defined_test1": ensure => file }
-}
-@testing { yay: }
-
-define deeper {
- file { "/tmp/realize_defined_test2": ensure => file }
-}
-
-@deeper { boo: }
-
-realize Testing[yay]
-realize File["/tmp/realize_defined_test2"]
diff --git a/test/executables/puppetbin.rb b/test/executables/puppetbin.rb
index 218787c92..08329efb6 100755
--- a/test/executables/puppetbin.rb
+++ b/test/executables/puppetbin.rb
@@ -83,5 +83,22 @@ class TestPuppetBin < Test::Unit::TestCase
assert(FileTest.exists?(path), "Failed to create config'ed file")
end
+
+ def test_parseonly
+ path = tempfile()
+ manifest = tempfile()
+ puppet = %x{which puppet}.chomp
+ if puppet == ""
+ Puppet.info "cannot find puppet; cannot test parseonly"
+ return
+ end
+ code = 'File <<| |>>
+ include nosuchclass'
+
+ assert_nothing_raised {
+ IO.popen("#{puppet} --parseonly", 'w') { |p| p.puts code }
+ }
+ assert($? == 0, "parseonly test exited with code %s" % $?.to_i)
+ end
end
diff --git a/test/language/ast.rb b/test/language/ast.rb
index b31012d38..8c0f31aba 100755
--- a/test/language/ast.rb
+++ b/test/language/ast.rb
@@ -35,14 +35,14 @@ class TestAST < Test::Unit::TestCase
# We initialized it to true, so we should get that first
ret = nil
assert_nothing_raised {
- ret = astif.evaluate(:scope => "yay")
+ ret = astif.evaluate("yay")
}
assert_equal(:if, ret)
# Now set it to false and check that
faketest.evaluate = false
assert_nothing_raised {
- ret = astif.evaluate(:scope => "yay")
+ ret = astif.evaluate("yay")
}
assert_equal(:else, ret)
end
@@ -57,10 +57,10 @@ class TestAST < Test::Unit::TestCase
end
Puppet::Parser::Resource.expects(:new).with { |o| o.is_a?(Hash) }.returns(:override)
- scope.compile.expects(:store_override).with(:override)
+ scope.compiler.expects(:add_override).with(:override)
ret = nil
assert_nothing_raised do
- ret = ref.evaluate :scope => scope
+ ret = ref.evaluate scope
end
assert_equal(:override, ret, "Did not return override")
@@ -74,7 +74,7 @@ class TestAST < Test::Unit::TestCase
args = {:source => "/yay/ness", :group => "yayness"}
assert_nothing_raised do
obj = defaultobj "file", args
- obj.evaluate :scope => scope
+ obj.evaluate scope
end
hash = nil
@@ -93,56 +93,6 @@ class TestAST < Test::Unit::TestCase
end
end
- def test_node
- scope = mkscope
- parser = scope.compile.parser
-
- # Define a base node
- basenode = parser.newnode "basenode", :code => AST::ASTArray.new(:children => [
- resourcedef("file", "/tmp/base", "owner" => "root")
- ])
-
- # Now define a subnode
- nodes = parser.newnode ["mynode", "othernode"],
- :code => AST::ASTArray.new(:children => [
- resourcedef("file", "/tmp/mynode", "owner" => "root"),
- resourcedef("file", "/tmp/basenode", "owner" => "daemon")
- ])
-
- assert_instance_of(Array, nodes)
-
- # Make sure we can find them all.
- %w{mynode othernode}.each do |node|
- assert(parser.nodes[node], "Could not find %s" % node)
- end
- mynode = parser.nodes["mynode"]
-
- # Now try evaluating the node
- assert_nothing_raised do
- mynode.evaluate :scope => scope, :resource => scope.resource
- end
-
- # Make sure that we can find each of the files
- myfile = scope.findresource "File[/tmp/mynode]"
- assert(myfile, "Could not find file from node")
- assert_equal("root", myfile[:owner])
-
- basefile = scope.findresource "File[/tmp/basenode]"
- assert(basefile, "Could not find file from base node")
- assert_equal("daemon", basefile[:owner])
-
- # Now make sure we can evaluate nodes with parents
- child = parser.newnode(%w{child}, :parent => "basenode").shift
-
- newscope = mkscope :parser => parser
- assert_nothing_raised do
- child.evaluate :scope => newscope, :resource => scope.resource
- end
-
- assert(newscope.findresource("File[/tmp/base]"),
- "Could not find base resource")
- end
-
def test_collection
scope = mkscope
@@ -155,13 +105,13 @@ class TestAST < Test::Unit::TestCase
ret = nil
assert_nothing_raised do
- ret = coll.evaluate :scope => scope
+ ret = coll.evaluate scope
end
assert_instance_of(Puppet::Parser::Collector, ret)
# Now make sure we get it back from the scope
- colls = scope.compile.instance_variable_get("@collections")
+ colls = scope.compiler.instance_variable_get("@collections")
assert_equal([ret], colls, "Did not store collector in config's collection list")
end
@@ -175,7 +125,7 @@ class TestAST < Test::Unit::TestCase
run_collection_queries(:virtual) do |string, result, query|
code = nil
assert_nothing_raised do
- str, code = query.evaluate :scope => scope
+ str, code = query.evaluate scope
end
assert_instance_of(Proc, code)
diff --git a/test/language/ast/casestatement.rb b/test/language/ast/casestatement.rb
index 0a744b686..d95d788d9 100755
--- a/test/language/ast/casestatement.rb
+++ b/test/language/ast/casestatement.rb
@@ -45,7 +45,7 @@ class TestCaseStatement < Test::Unit::TestCase
result = nil
assert_nothing_raised do
- result = ast.evaluate :scope => scope
+ result = ast.evaluate scope
end
assert(result, "did not get valid result")
assert_equal(["upper"], $evaluated, "Did not match case-sensitively")
@@ -56,7 +56,7 @@ class TestCaseStatement < Test::Unit::TestCase
$evaluated.clear
hash["MyParam"].reset
assert_nothing_raised do
- result = ast.evaluate :scope => scope
+ result = ast.evaluate scope
end
assert(result, "did not get valid result")
assert_equal(["lower"], result, "Did not match case-insensitively")
@@ -92,7 +92,7 @@ class TestCaseStatement < Test::Unit::TestCase
scope = mkscope
scope.setvar("testparam", value)
assert_nothing_raised do
- result = ast.evaluate(:scope => scope)
+ result = ast.evaluate(scope)
end
assert_equal(should, result, "Got incorrect result for %s" % value)
diff --git a/test/language/ast/definition.rb b/test/language/ast/definition.rb
deleted file mode 100755
index 2a71aaa45..000000000
--- a/test/language/ast/definition.rb
+++ /dev/null
@@ -1,166 +0,0 @@
-#!/usr/bin/env ruby
-#
-# Created by Luke A. Kanies on 2006-02-20.
-# Copyright (c) 2006. All rights reserved.
-
-require File.dirname(__FILE__) + '/../../lib/puppettest'
-
-require 'puppettest'
-require 'mocha'
-require 'puppettest/parsertesting'
-require 'puppettest/resourcetesting'
-
-class TestASTDefinition < Test::Unit::TestCase
- include PuppetTest
- include PuppetTest::ParserTesting
- include PuppetTest::ResourceTesting
- AST = Puppet::Parser::AST
-
- def test_initialize
- parser = mkparser
-
- # Create a new definition
- klass = parser.newdefine "yayness",
- :arguments => [["owner", stringobj("nobody")], %w{mode}],
- :code => AST::ASTArray.new(
- :children => [resourcedef("file", "/tmp/$name",
- "owner" => varref("owner"), "mode" => varref("mode"))]
- )
-
- # Test validattr? a couple different ways
- [:owner, "owner", :schedule, "schedule"].each do |var|
- assert(klass.validattr?(var), "%s was not considered valid" % var.inspect)
- end
-
- [:random, "random"].each do |var|
- assert(! klass.validattr?(var), "%s was considered valid" % var.inspect)
- end
-
- end
-
- def test_evaluate
- parser = mkparser
- config = mkcompile
- config.send(:evaluate_main)
- scope = config.topscope
- klass = parser.newdefine "yayness",
- :arguments => [["owner", stringobj("nobody")], %w{mode}],
- :code => AST::ASTArray.new(
- :children => [resourcedef("file", "/tmp/$name",
- "owner" => varref("owner"), "mode" => varref("mode"))]
- )
-
- resource = Puppet::Parser::Resource.new(
- :title => "first",
- :type => "yayness",
- :exported => false,
- :virtual => false,
- :scope => scope,
- :source => scope.source
- )
- resource.send(:set_parameter, "name", "first")
- resource.send(:set_parameter, "mode", "755")
-
- resource.stubs(:title)
- assert_nothing_raised do
- klass.evaluate(:scope => scope, :resource => resource)
- end
-
- firstobj = config.findresource("File[/tmp/first]")
- assert(firstobj, "Did not create /tmp/first obj")
-
- assert_equal("File", firstobj.type)
- assert_equal("/tmp/first", firstobj.title)
- assert_equal("nobody", firstobj[:owner])
- assert_equal("755", firstobj[:mode])
-
- # Make sure we can't evaluate it with the same args
- assert_raise(Puppet::ParseError) do
- klass.evaluate(:scope => scope, :resource => resource)
- end
-
- # Now create another with different args
- resource2 = Puppet::Parser::Resource.new(
- :title => "second",
- :type => "yayness",
- :exported => false,
- :virtual => false,
- :scope => scope,
- :source => scope.source
- )
- resource2.send(:set_parameter, "name", "second")
- resource2.send(:set_parameter, "mode", "755")
- resource2.send(:set_parameter, "owner", "daemon")
-
- assert_nothing_raised do
- klass.evaluate(:scope => scope, :resource => resource2)
- end
-
- secondobj = config.findresource("File[/tmp/second]")
- assert(secondobj, "Did not create /tmp/second obj")
-
- assert_equal("File", secondobj.type)
- assert_equal("/tmp/second", secondobj.title)
- assert_equal("daemon", secondobj[:owner])
- assert_equal("755", secondobj[:mode])
- end
-
- # #539 - definitions should support both names and titles
- def test_names_and_titles
- parser = mkparser
- scope = mkscope :parser => parser
-
- [
- {:name => "one", :title => "two"},
- {:title => "mytitle"}
- ].each_with_index do |hash, i|
- # Create a definition that uses both name and title. Put this
- # inside the loop so the subscope expectations work.
- klass = parser.newdefine "yayness%s" % i
-
- resource = Puppet::Parser::Resource.new(
- :title => hash[:title],
- :type => "yayness%s" % i,
- :exported => false,
- :virtual => false,
- :scope => scope,
- :source => scope.source
- )
-
- subscope = klass.subscope(scope, resource)
-
- klass.expects(:subscope).returns(subscope)
-
- if hash[:name]
- resource.stubs(:to_hash).returns({:name => hash[:name]})
- end
-
- assert_nothing_raised("Could not evaluate definition with %s" % hash.inspect) do
- klass.evaluate(:scope => scope, :resource => resource)
- end
-
- name = hash[:name] || hash[:title]
- title = hash[:title]
-
- assert_equal(name, subscope.lookupvar("name"),
- "Name did not get set correctly")
- assert_equal(title, subscope.lookupvar("title"),
- "title did not get set correctly")
-
- [:name, :title].each do |param|
- val = resource.send(param)
- assert(subscope.tags.include?(val),
- "Scope was not tagged with %s '%s'" % [param, val])
- end
- end
- end
-
- # Testing the root cause of #615. We should be using the fqname for the type, instead
- # of just the short name.
- def test_fully_qualified_types
- parser = mkparser
- klass = parser.newclass("one::two")
-
- assert_equal("one::two", klass.classname, "Class did not get fully qualified class name")
- end
-end
diff --git a/test/language/ast/hostclass.rb b/test/language/ast/hostclass.rb
deleted file mode 100755
index 80032f30c..000000000
--- a/test/language/ast/hostclass.rb
+++ /dev/null
@@ -1,184 +0,0 @@
-#!/usr/bin/env ruby
-#
-# Created by Luke A. Kanies on 2006-02-20.
-# Copyright (c) 2006. All rights reserved.
-
-require File.dirname(__FILE__) + '/../../lib/puppettest'
-
-require 'puppettest'
-require 'puppettest/parsertesting'
-require 'puppettest/resourcetesting'
-require 'mocha'
-
-class TestASTHostClass < Test::Unit::TestCase
- include PuppetTest
- include PuppetTest::ParserTesting
- include PuppetTest::ResourceTesting
- AST = Puppet::Parser::AST
-
- def test_hostclass
- scope = mkscope
- parser = scope.compile.parser
-
- # Create the class we're testing, first with no parent
- klass = parser.newclass "first",
- :code => AST::ASTArray.new(
- :children => [resourcedef("file", "/tmp",
- "owner" => "nobody", "mode" => "755")]
- )
-
- resource = Puppet::Parser::Resource.new(:type => "class", :title => "first", :scope => scope)
- assert_nothing_raised do
- klass.evaluate(:scope => scope, :resource => resource)
- end
-
- # Then try it again
- assert_nothing_raised do
- klass.evaluate(:scope => scope, :resource => resource)
- end
-
- assert(scope.compile.class_scope(klass), "Class was not considered evaluated")
-
- tmp = scope.findresource("File[/tmp]")
- assert(tmp, "Could not find file /tmp")
- assert_equal("nobody", tmp[:owner])
- assert_equal("755", tmp[:mode])
-
- # Now create a couple more classes.
- newbase = parser.newclass "newbase",
- :code => AST::ASTArray.new(
- :children => [resourcedef("file", "/tmp/other",
- "owner" => "nobody", "mode" => "644")]
- )
-
- newsub = parser.newclass "newsub",
- :parent => "newbase",
- :code => AST::ASTArray.new(
- :children => [resourcedef("file", "/tmp/yay",
- "owner" => "nobody", "mode" => "755"),
- resourceoverride("file", "/tmp/other",
- "owner" => "daemon")
- ]
- )
-
- # Override a different variable in the top scope.
- moresub = parser.newclass "moresub",
- :parent => "newbase",
- :code => AST::ASTArray.new(
- :children => [resourceoverride("file", "/tmp/other",
- "mode" => "755")]
- )
-
- assert_nothing_raised do
- newsub.evaluate(:scope => scope, :resource => resource)
- end
-
- assert_nothing_raised do
- moresub.evaluate(:scope => scope, :resource => resource)
- end
-
- assert(scope.compile.class_scope(newbase), "Did not eval newbase")
- assert(scope.compile.class_scope(newsub), "Did not eval newsub")
-
- yay = scope.findresource("File[/tmp/yay]")
- assert(yay, "Did not find file /tmp/yay")
- assert_equal("nobody", yay[:owner])
- assert_equal("755", yay[:mode])
-
- other = scope.findresource("File[/tmp/other]")
- assert(other, "Did not find file /tmp/other")
- assert_equal("daemon", other[:owner])
- assert_equal("755", other[:mode])
- end
-
- # Make sure that classes set their namespaces to themselves. This
- # way they start looking for definitions in their own namespace.
- def test_hostclass_namespace
- scope = mkscope
- parser = scope.compile.parser
-
- # Create a new class
- klass = nil
- assert_nothing_raised do
- klass = parser.newclass "funtest"
- end
-
- # Now define a definition in that namespace
-
- define = nil
- assert_nothing_raised do
- define = parser.newdefine "funtest::mydefine"
- end
-
- assert_equal("funtest", klass.namespace,
- "component namespace was not set in the class")
-
- assert_equal("funtest", define.namespace,
- "component namespace was not set in the definition")
-
- newscope = klass.subscope(scope, mock("resource"))
-
- assert_equal(["funtest"], newscope.namespaces,
- "Scope did not inherit namespace")
-
- # Now make sure we can find the define
- assert(newscope.finddefine("mydefine"),
- "Could not find definition in my enclosing class")
- end
-
- # Make sure that our scope is a subscope of the parentclass's scope.
- # At the same time, make sure definitions in the parent class can be
- # found within the subclass (#517).
- def test_parent_scope_from_parentclass
- scope = mkscope
- parser = scope.compile.parser
-
- source = parser.newclass ""
- parser.newclass("base")
- fun = parser.newdefine("base::fun")
- parser.newclass("middle", :parent => "base")
- parser.newclass("sub", :parent => "middle")
- scope = mkscope :parser => parser
-
- ret = nil
- assert_nothing_raised do
- ret = scope.compile.evaluate_classes(["sub"], scope)
- end
- scope.compile.send(:evaluate_generators)
-
- subscope = scope.compile.class_scope(scope.findclass("sub"))
- assert(subscope, "could not find sub scope")
- mscope = scope.compile.class_scope(scope.findclass("middle"))
- assert(mscope, "could not find middle scope")
- pscope = scope.compile.class_scope(scope.findclass("base"))
- assert(pscope, "could not find parent scope")
-
- assert(pscope == mscope.parent, "parent scope of middle was not set correctly")
- assert(mscope == subscope.parent, "parent scope of sub was not set correctly")
-
- result = mscope.finddefine("fun")
- assert(result, "could not find parent-defined definition from middle")
- assert(fun == result, "found incorrect parent-defined definition from middle")
-
- result = subscope.finddefine("fun")
- assert(result, "could not find parent-defined definition from sub")
- assert(fun == result, "found incorrect parent-defined definition from sub")
- end
-
- # #795 - make sure the subclass's tags get set before we
- # evaluate the parent class, so we can be sure that the parent
- # class can switch based on the sub classes.
- def test_tags_set_before_parent_is_evaluated
- scope = mkscope
- parser = scope.compile.parser
- base = parser.newclass "base"
- sub = parser.newclass "sub", :parent => "base"
-
- base.expects(:safeevaluate).with do |args|
- assert(scope.compile.catalog.tags.include?("sub"), "Did not tag with sub class name before evaluating base class")
- base.evaluate(args)
- true
- end
- sub.evaluate :scope => scope, :resource => scope.resource
- end
-end
diff --git a/test/language/ast/resource.rb b/test/language/ast/resource.rb
index c99d98eeb..97541d92f 100755
--- a/test/language/ast/resource.rb
+++ b/test/language/ast/resource.rb
@@ -16,8 +16,7 @@ class TestASTResource< Test::Unit::TestCase
def setup
super
@scope = mkscope
- @parser = @scope.compile.parser
- @scope.compile.send(:evaluate_main)
+ @parser = @scope.compiler.parser
end
def newdef(type, title, params = nil)
@@ -36,24 +35,24 @@ class TestASTResource< Test::Unit::TestCase
title = "title"
# First try a qualified type
- assert_equal("One::Two", newdef("two", title).evaluate(:scope => twoscope)[0].type,
+ assert_equal("One::Two", newdef("two", title).evaluate(twoscope)[0].type,
"Defined type was not made fully qualified")
# Then try a type that does not need to be qualified
- assert_equal("One", newdef("one", title).evaluate(:scope => twoscope)[0].type,
+ assert_equal("One", newdef("one", title).evaluate(twoscope)[0].type,
"Unqualified defined type was not handled correctly")
# Then an unqualified type from within the one namespace
- assert_equal("Three", newdef("three", title).evaluate(:scope => twoscope)[0].type,
+ assert_equal("Three", newdef("three", title).evaluate(twoscope)[0].type,
"Defined type was not made fully qualified")
# Then a builtin type
- assert_equal("File", newdef("file", title).evaluate(:scope => twoscope)[0].type,
+ assert_equal("File", newdef("file", title).evaluate(twoscope)[0].type,
"Builtin type was not handled correctly")
# Now try a type that does not exist, which should throw an error.
assert_raise(Puppet::ParseError, "Did not fail on a missing type in a resource reference") do
- newdef("nosuchtype", title).evaluate(:scope => twoscope)
+ newdef("nosuchtype", title).evaluate(twoscope)
end
end
end
diff --git a/test/language/ast/resource_reference.rb b/test/language/ast/resource_reference.rb
index c9fde078f..1f554d90f 100755
--- a/test/language/ast/resource_reference.rb
+++ b/test/language/ast/resource_reference.rb
@@ -20,7 +20,7 @@ class TestASTResourceReference < Test::Unit::TestCase
def setup
super
@scope = mkscope
- @parser = @scope.compile.parser
+ @parser = @scope.compiler.parser
end
def test_evaluate
@@ -31,7 +31,7 @@ class TestASTResourceReference < Test::Unit::TestCase
evaled = nil
assert_nothing_raised("Could not evaluate resource ref") do
- evaled = ref.evaluate(:scope => @scope)
+ evaled = ref.evaluate(@scope)
end
assert_equal(type, evaled.type, "Type did not translate correctly")
@@ -44,7 +44,7 @@ class TestASTResourceReference < Test::Unit::TestCase
ref = newref("Class", "one")
evaled = nil
assert_nothing_raised("Could not evaluate resource ref") do
- evaled = ref.evaluate(:scope => @scope)
+ evaled = ref.evaluate(@scope)
end
assert_equal("Class", evaled.type, "Did not set type to 'class'")
@@ -61,24 +61,24 @@ class TestASTResourceReference < Test::Unit::TestCase
title = "title"
# First try a qualified type
- assert_equal("One::Two", newref("two", title).evaluate(:scope => twoscope).type,
+ assert_equal("One::Two", newref("two", title).evaluate(twoscope).type,
"Defined type was not made fully qualified")
# Then try a type that does not need to be qualified
- assert_equal("One", newref("one", title).evaluate(:scope => twoscope).type,
+ assert_equal("One", newref("one", title).evaluate(twoscope).type,
"Unqualified defined type was not handled correctly")
# Then an unqualified type from within the one namespace
- assert_equal("Three", newref("three", title).evaluate(:scope => twoscope).type,
+ assert_equal("Three", newref("three", title).evaluate(twoscope).type,
"Defined type was not made fully qualified")
# Then a builtin type
- assert_equal("File", newref("file", title).evaluate(:scope => twoscope).type,
+ assert_equal("File", newref("file", title).evaluate(twoscope).type,
"Builtin type was not handled correctly")
# Now try a type that does not exist, which should throw an error.
assert_raise(Puppet::ParseError, "Did not fail on a missing type in a resource reference") do
- newref("nosuchtype", title).evaluate(:scope => twoscope)
+ newref("nosuchtype", title).evaluate(twoscope)
end
# Now run the same tests, but with the classes
@@ -86,20 +86,20 @@ class TestASTResourceReference < Test::Unit::TestCase
@parser.newclass "one::five"
# First try an unqualified type
- assert_equal("four", newref("class", "four").evaluate(:scope => twoscope).title,
+ assert_equal("four", newref("class", "four").evaluate(twoscope).title,
"Unqualified class was not found")
# Then a qualified class
- assert_equal("one::five", newref("class", "five").evaluate(:scope => twoscope).title,
+ assert_equal("one::five", newref("class", "five").evaluate(twoscope).title,
"Class was not made fully qualified")
# Then try a type that does not need to be qualified
- assert_equal("four", newref("class", "four").evaluate(:scope => twoscope).title,
+ assert_equal("four", newref("class", "four").evaluate(twoscope).title,
"Unqualified class was not handled correctly")
# Now try a type that does not exist, which should throw an error.
assert_raise(Puppet::ParseError, "Did not fail on a missing type in a resource reference") do
- newref("class", "nosuchclass").evaluate(:scope => twoscope)
+ newref("class", "nosuchclass").evaluate(twoscope)
end
end
end
diff --git a/test/language/ast/selector.rb b/test/language/ast/selector.rb
index 535fcbf70..6e923bdcb 100755
--- a/test/language/ast/selector.rb
+++ b/test/language/ast/selector.rb
@@ -37,7 +37,7 @@ class TestSelector < Test::Unit::TestCase
params = maker.call()
sel = AST::Selector.new(:param => param, :values => params.values)
result = nil
- assert_nothing_raised { result = sel.evaluate(:scope => scope) }
+ assert_nothing_raised { result = sel.evaluate(scope) }
assert_equal(should[str], result, "did not case-sensitively match %s" % str)
end
@@ -53,7 +53,7 @@ class TestSelector < Test::Unit::TestCase
params.delete(:upper)
sel = AST::Selector.new(:param => param, :values => params.values)
result = nil
- assert_nothing_raised { result = sel.evaluate(:scope => scope) }
+ assert_nothing_raised { result = sel.evaluate(scope) }
assert_equal("lower", result, "did not case-insensitively match %s" % str)
end
end
diff --git a/test/language/ast/variable.rb b/test/language/ast/variable.rb
index 09122ce16..bde397bb4 100755
--- a/test/language/ast/variable.rb
+++ b/test/language/ast/variable.rb
@@ -22,9 +22,9 @@ class TestVariable < Test::Unit::TestCase
end
def test_evaluate
- assert_equal("", @var.evaluate(:scope => @scope), "did not return empty string on unset var")
+ assert_equal("", @var.evaluate(@scope), "did not return empty string on unset var")
@scope.setvar(@name, "something")
- assert_equal("something", @var.evaluate(:scope => @scope), "incorrect variable value")
+ assert_equal("something", @var.evaluate(@scope), "incorrect variable value")
end
end
diff --git a/test/language/compile.rb b/test/language/compile.rb
deleted file mode 100755
index 082b37a1c..000000000
--- a/test/language/compile.rb
+++ /dev/null
@@ -1,569 +0,0 @@
-#!/usr/bin/env ruby
-
-require File.dirname(__FILE__) + '/../lib/puppettest'
-
-require 'mocha'
-require 'puppettest'
-require 'puppettest/parsertesting'
-require 'puppet/parser/compile'
-
-# Test our compile object.
-class TestCompile < Test::Unit::TestCase
- include PuppetTest
- include PuppetTest::ParserTesting
-
- Compile = Puppet::Parser::Compile
- Scope = Puppet::Parser::Scope
- Node = Puppet::Network::Handler.handler(:node)
- SimpleNode = Puppet::Node
-
- def mknode(name = "foo")
- @node = SimpleNode.new(name)
- end
-
- def mkparser
- # This should mock an interpreter
- @parser = stub 'parser', :version => "1.0", :nodes => {}
- end
-
- def mkcompile(options = {})
- if node = options[:node]
- options.delete(:node)
- else
- node = mknode
- end
- @compile = Compile.new(node, mkparser, options)
- end
-
- def test_initialize
- compile = nil
- node = stub 'node', :name => "foo"
- parser = stub 'parser', :version => "1.0", :nodes => {}
- assert_nothing_raised("Could not init compile with all required options") do
- compile = Compile.new(node, parser)
- end
-
- assert_equal(node, compile.node, "Did not set node correctly")
- assert_equal(parser, compile.parser, "Did not set parser correctly")
-
- # We're not testing here whether we call initvars, because it's too difficult to
- # mock.
-
- # Now try it with some options
- assert_nothing_raised("Could not init compile with extra options") do
- compile = Compile.new(node, parser)
- end
-
- assert_equal(false, compile.ast_nodes?, "Did not set ast_nodes? correctly")
- end
-
- def test_initvars
- compile = mkcompile
- [:class_scopes, :resource_table, :exported_resources, :resource_overrides].each do |table|
- assert_instance_of(Hash, compile.send(:instance_variable_get, "@#{table}"), "Did not set %s table correctly" % table)
- end
- assert_instance_of(Scope, compile.topscope, "Did not create a topscope")
- graph = compile.instance_variable_get("@scope_graph")
- assert_instance_of(Puppet::SimpleGraph, graph, "Did not create scope graph")
- assert(graph.vertex?(compile.topscope), "Did not add top scope as a vertex in the graph")
- end
-
- # Make sure we store and can retrieve references to classes and their scopes.
- def test_class_set_and_class_scope
- klass = mock 'ast_class'
- klass.expects(:classname).returns("myname")
-
- compile = mkcompile
- compile.catalog.expects(:tag).with("myname")
-
- assert_nothing_raised("Could not set class") do
- compile.class_set "myname", "myscope"
- end
- # First try to retrieve it by name.
- assert_equal("myscope", compile.class_scope("myname"), "Could not retrieve class scope by name")
-
- # Then by object
- assert_equal("myscope", compile.class_scope(klass), "Could not retrieve class scope by object")
- end
-
- def test_classlist
- compile = mkcompile
-
- compile.class_set "", "empty"
- compile.class_set "one", "yep"
- compile.class_set "two", "nope"
-
- # Make sure our class list is correct
- assert_equal(%w{one two}.sort, compile.classlist.sort, "Did not get correct class list")
- end
-
- # Make sure collections get added to our internal array
- def test_add_collection
- compile = mkcompile
- assert_nothing_raised("Could not add collection") do
- compile.add_collection "nope"
- end
- assert_equal(%w{nope}, compile.instance_variable_get("@collections"), "Did not add collection")
- end
-
- # Make sure we create a graph of scopes.
- def test_newscope
- compile = mkcompile
- graph = compile.instance_variable_get("@scope_graph")
- assert_instance_of(Scope, compile.topscope, "Did not create top scope")
- assert_instance_of(Puppet::SimpleGraph, graph, "Did not create graph")
-
- assert(graph.vertex?(compile.topscope), "The top scope is not a vertex in the graph")
-
- # Now that we've got the top scope, create a new, subscope
- subscope = nil
- assert_nothing_raised("Could not create subscope") do
- subscope = compile.newscope(compile.topscope)
- end
- assert_instance_of(Scope, subscope, "Did not create subscope")
- assert(graph.edge?(compile.topscope, subscope), "An edge between top scope and subscope was not added")
-
- # Make sure a scope can find its parent.
- assert(compile.parent(subscope), "Could not look up parent scope on compile")
- assert_equal(compile.topscope.object_id, compile.parent(subscope).object_id, "Did not get correct parent scope from compile")
- assert_equal(compile.topscope.object_id, subscope.parent.object_id, "Scope did not correctly retrieve its parent scope")
-
- # Now create another, this time specifying options
- another = nil
- assert_nothing_raised("Could not create subscope") do
- another = compile.newscope(subscope, :level => 5)
- end
- assert_equal(5, another.level, "did not set scope option correctly")
- assert_instance_of(Scope, another, "Did not create second subscope")
- assert(graph.edge?(subscope, another), "An edge between parent scope and second subscope was not added")
-
- # Make sure it can find its parent.
- assert(compile.parent(another), "Could not look up parent scope of second subscope on compile")
- assert_equal(subscope.object_id, compile.parent(another).object_id, "Did not get correct parent scope of second subscope from compile")
- assert_equal(subscope.object_id, another.parent.object_id, "Second subscope did not correctly retrieve its parent scope")
-
- # And make sure both scopes show up in the right order in the search path
- assert_equal([another.object_id, subscope.object_id, compile.topscope.object_id], another.scope_path.collect { |p| p.object_id },
- "Did not get correct scope path")
- end
-
- # The heart of the action.
- def test_compile
- compile = mkcompile
- [:set_node_parameters, :evaluate_main, :evaluate_ast_node, :evaluate_node_classes, :evaluate_generators, :fail_on_unevaluated, :finish].each do |method|
- compile.expects(method)
- end
- assert_instance_of(Puppet::Node::Catalog, compile.compile, "Did not return the catalog")
- end
-
- # Test setting the node's parameters into the top scope.
- def test_set_node_parameters
- compile = mkcompile
- @node.parameters = {"a" => "b", "c" => "d"}
- scope = compile.topscope
- @node.parameters.each do |param, value|
- scope.expects(:setvar).with(param, value)
- end
-
- assert_nothing_raised("Could not call 'set_node_parameters'") do
- compile.send(:set_node_parameters)
- end
- end
-
- # Test that we can evaluate the main class, which is the one named "" in namespace
- # "".
- def test_evaluate_main
- compile = mkcompile
- main_class = mock 'main_class'
- compile.topscope.expects(:source=).with(main_class)
- @parser.expects(:findclass).with("", "").returns(main_class)
-
- main_resource = mock 'main resource'
- Puppet::Parser::Resource.expects(:new).with { |args| args[:title] == :main }.returns(main_resource)
-
- main_resource.expects(:evaluate)
-
- assert_nothing_raised("Could not call evaluate_main") do
- compile.send(:evaluate_main)
- end
- end
-
- def test_evaluate_node_classes
- compile = mkcompile
- @node.classes = %w{one two three four}
- compile.expects(:evaluate_classes).with(%w{one two three four}, compile.topscope)
- assert_nothing_raised("could not call evaluate_node_classes") do
- compile.send(:evaluate_node_classes)
- end
- end
-
- def test_evaluate_collections
- compile = mkcompile
-
- colls = []
-
- # Make sure we return false when there's nothing there.
- assert(! compile.send(:evaluate_collections), "Returned true when there were no collections")
-
- # And when the collections fail to evaluate.
- colls << mock("coll1-false")
- colls << mock("coll2-false")
- colls.each { |c| c.expects(:evaluate).returns(false) }
-
- compile.instance_variable_set("@collections", colls)
- assert(! compile.send(:evaluate_collections), "Returned true when collections both evaluated nothing")
-
- # Now have one of the colls evaluate
- colls.clear
- colls << mock("coll1-one-true")
- colls << mock("coll2-one-true")
- colls[0].expects(:evaluate).returns(true)
- colls[1].expects(:evaluate).returns(false)
- assert(compile.send(:evaluate_collections), "Did not return true when one collection evaluated true")
-
- # And have them both eval true
- colls.clear
- colls << mock("coll1-both-true")
- colls << mock("coll2-both-true")
- colls[0].expects(:evaluate).returns(true)
- colls[1].expects(:evaluate).returns(true)
- assert(compile.send(:evaluate_collections), "Did not return true when both collections evaluated true")
- end
-
- def test_unevaluated_resources
- compile = mkcompile
- resources = {}
- compile.instance_variable_set("@resource_table", resources)
-
- # First test it when the table is empty
- assert_nil(compile.send(:unevaluated_resources), "Somehow found unevaluated resources in an empty table")
-
- # Then add a builtin resources
- resources["one"] = mock("builtin only")
- resources["one"].expects(:builtin?).returns(true)
- assert_nil(compile.send(:unevaluated_resources), "Considered a builtin resource unevaluated")
-
- # And do both builtin and non-builtin but already evaluated
- resources.clear
- resources["one"] = mock("builtin (with eval)")
- resources["one"].expects(:builtin?).returns(true)
- resources["two"] = mock("evaled (with builtin)")
- resources["two"].expects(:builtin?).returns(false)
- resources["two"].expects(:evaluated?).returns(true)
- assert_nil(compile.send(:unevaluated_resources), "Considered either a builtin or evaluated resource unevaluated")
-
- # Now a single unevaluated resource.
- resources.clear
- resources["one"] = mock("unevaluated")
- resources["one"].expects(:builtin?).returns(false)
- resources["one"].expects(:evaluated?).returns(false)
- assert_equal([resources["one"]], compile.send(:unevaluated_resources), "Did not find unevaluated resource")
-
- # With two uneval'ed resources, and an eval'ed one thrown in
- resources.clear
- resources["one"] = mock("unevaluated one")
- resources["one"].expects(:builtin?).returns(false)
- resources["one"].expects(:evaluated?).returns(false)
- resources["two"] = mock("unevaluated two")
- resources["two"].expects(:builtin?).returns(false)
- resources["two"].expects(:evaluated?).returns(false)
- resources["three"] = mock("evaluated")
- resources["three"].expects(:builtin?).returns(false)
- resources["three"].expects(:evaluated?).returns(true)
-
- result = compile.send(:unevaluated_resources)
- %w{one two}.each do |name|
- assert(result.include?(resources[name]), "Did not find %s in the unevaluated list" % name)
- end
- end
-
- def test_evaluate_definitions
- # First try the case where there's nothing to return
- compile = mkcompile
- compile.expects(:unevaluated_resources).returns(nil)
-
- assert_nothing_raised("Could not test for unevaluated resources") do
- assert(! compile.send(:evaluate_definitions), "evaluate_definitions returned true when no resources were evaluated")
- end
-
- # Now try it with resources left to evaluate
- resources = []
- res1 = mock("resource1")
- res1.expects(:evaluate)
- res2 = mock("resource2")
- res2.expects(:evaluate)
- resources << res1 << res2
- compile = mkcompile
- compile.expects(:unevaluated_resources).returns(resources)
-
- assert_nothing_raised("Could not test for unevaluated resources") do
- assert(compile.send(:evaluate_definitions), "evaluate_definitions returned false when resources were evaluated")
- end
- end
-
- def test_evaluate_generators
- # First try the case where we have nothing to do
- compile = mkcompile
- compile.expects(:evaluate_definitions).returns(false)
- compile.expects(:evaluate_collections).returns(false)
-
- assert_nothing_raised("Could not call :eval_iterate") do
- compile.send(:evaluate_generators)
- end
-
- # FIXME I could not get this test to work, but the code is short
- # enough that I'm ok with it.
- # It's important that collections are evaluated before definitions,
- # so make sure that's the case by verifying that collections get tested
- # twice but definitions only once.
- #compile = mkcompile
- #compile.expects(:evaluate_collections).returns(true).returns(false)
- #compile.expects(:evaluate_definitions).returns(false)
- #compile.send(:eval_iterate)
- end
-
- def test_store
- compile = mkcompile
- Puppet.features.expects(:rails?).returns(true)
- Puppet::Rails.expects(:connect)
-
- node = mock 'node'
- resource_table = mock 'resources'
- resource_table.expects(:values).returns(:resources)
- compile.instance_variable_set("@node", node)
- compile.instance_variable_set("@resource_table", resource_table)
- compile.expects(:store_to_active_record).with(node, :resources)
- compile.send(:store)
- end
-
- def test_store_to_active_record
- compile = mkcompile
- node = mock 'node'
- node.expects(:name).returns("myname")
- Puppet::Rails::Host.stubs(:transaction).yields
- Puppet::Rails::Host.expects(:store).with(node, :resources)
- compile.send(:store_to_active_record, node, :resources)
- end
-
- # Make sure that 'finish' gets called on all of our resources.
- def test_finish
- compile = mkcompile
- table = compile.instance_variable_get("@resource_table")
-
- # Add a resource that does respond to :finish
- yep = mock("finisher")
- yep.expects(:respond_to?).with(:finish).returns(true)
- yep.expects(:finish)
- table["yep"] = yep
-
- # And one that does not
- dnf = mock("dnf")
- dnf.expects(:respond_to?).with(:finish).returns(false)
- table["dnf"] = dnf
-
- compile.send(:finish)
- end
-
- def test_verify_uniqueness
- compile = mkcompile
-
- resources = compile.instance_variable_get("@resource_table")
- resource = mock("noconflict")
- resource.expects(:ref).returns("File[yay]")
- assert_nothing_raised("Raised an exception when there should have been no conflict") do
- compile.send(:verify_uniqueness, resource)
- end
-
- # Now try the case where our type is isomorphic
- resources["thing"] = true
-
- isoconflict = mock("isoconflict")
- isoconflict.expects(:ref).returns("thing")
- isoconflict.expects(:type).returns("testtype")
- faketype = mock("faketype")
- faketype.expects(:isomorphic?).returns(false)
- faketype.expects(:name).returns("whatever")
- Puppet::Type.expects(:type).with("testtype").returns(faketype)
- assert_nothing_raised("Raised an exception when was a conflict in non-isomorphic types") do
- compile.send(:verify_uniqueness, isoconflict)
- end
-
- # Now test for when we actually have an exception
- initial = mock("initial")
- resources["thing"] = initial
- initial.expects(:file).returns(false)
-
- conflict = mock("conflict")
- conflict.expects(:ref).returns("thing").times(2)
- conflict.expects(:type).returns("conflict")
- conflict.expects(:file).returns(false)
- conflict.expects(:line).returns(false)
-
- faketype = mock("faketype")
- faketype.expects(:isomorphic?).returns(true)
- Puppet::Type.expects(:type).with("conflict").returns(faketype)
- assert_raise(Puppet::ParseError, "Did not fail when two isomorphic resources conflicted") do
- compile.send(:verify_uniqueness, conflict)
- end
- end
-
- def test_store_resource
- # Run once when there's no conflict
- compile = mkcompile
- table = compile.instance_variable_get("@resource_table")
- resource = mock("resource")
- resource.expects(:ref).returns("yay")
- compile.expects(:verify_uniqueness).with(resource)
- scope = stub("scope", :resource => mock('resource'))
-
- compile.catalog.expects(:add_edge!).with(scope.resource, resource)
-
- assert_nothing_raised("Could not store resource") do
- compile.store_resource(scope, resource)
- end
- assert_equal(resource, table["yay"], "Did not store resource in table")
-
- # Now for conflicts
- compile = mkcompile
- table = compile.instance_variable_get("@resource_table")
- resource = mock("resource")
- compile.expects(:verify_uniqueness).with(resource).raises(ArgumentError)
-
- assert_raise(ArgumentError, "Did not raise uniqueness exception") do
- compile.store_resource(scope, resource)
- end
- assert(table.empty?, "Conflicting resource was stored in table")
- end
-
- def test_fail_on_unevaluated
- compile = mkcompile
- compile.expects(:fail_on_unevaluated_overrides)
- compile.expects(:fail_on_unevaluated_resource_collections)
- compile.send :fail_on_unevaluated
- end
-
- def test_store_override
- # First test the case when the resource is not present.
- compile = mkcompile
- overrides = compile.instance_variable_get("@resource_overrides")
- override = Object.new
- override.expects(:ref).returns(:myref).times(2)
- override.expects(:override=).with(true)
-
- assert_nothing_raised("Could not call store_override") do
- compile.store_override(override)
- end
- assert_instance_of(Array, overrides[:myref], "Overrides table is not a hash of arrays")
- assert_equal(override, overrides[:myref][0], "Did not store override in appropriately named array")
-
- # And when the resource already exists.
- resource = mock 'resource'
- resources = compile.instance_variable_get("@resource_table")
- resources[:resref] = resource
-
- override = mock 'override'
- resource.expects(:merge).with(override)
- override.expects(:override=).with(true)
- override.expects(:ref).returns(:resref)
- assert_nothing_raised("Could not call store_override when the resource already exists.") do
- compile.store_override(override)
- end
- end
-
- def test_resource_overrides
- compile = mkcompile
- overrides = compile.instance_variable_get("@resource_overrides")
- overrides[:test] = :yay
- resource = mock 'resource'
- resource.expects(:ref).returns(:test)
-
- assert_equal(:yay, compile.resource_overrides(resource), "Did not return overrides from table")
- end
-
- def test_fail_on_unevaluated_resource_collections
- compile = mkcompile
- collections = compile.instance_variable_get("@collections")
-
- # Make sure we're fine when the list is empty
- assert_nothing_raised("Failed when no collections were present") do
- compile.send :fail_on_unevaluated_resource_collections
- end
-
- # And that we're fine when we've got collections but with no resources
- collections << mock('coll')
- collections[0].expects(:resources).returns(nil)
- assert_nothing_raised("Failed when no resource collections were present") do
- compile.send :fail_on_unevaluated_resource_collections
- end
-
- # But that we do fail when we've got resource collections left.
- collections.clear
-
- # return both an array and a string, because that's tested internally
- collections << mock('coll returns one')
- collections[0].expects(:resources).returns(:something)
-
- collections << mock('coll returns many')
- collections[1].expects(:resources).returns([:one, :two])
-
- assert_raise(Puppet::ParseError, "Did not fail on unevaluated resource collections") do
- compile.send :fail_on_unevaluated_resource_collections
- end
- end
-
- def test_fail_on_unevaluated_overrides
- compile = mkcompile
- overrides = compile.instance_variable_get("@resource_overrides")
-
- # Make sure we're fine when the list is empty
- assert_nothing_raised("Failed when no collections were present") do
- compile.send :fail_on_unevaluated_overrides
- end
-
- # But that we fail if there are any overrides left in the table.
- overrides[:yay] = []
- overrides[:foo] = []
- overrides[:bar] = [mock("override")]
- overrides[:bar][0].expects(:ref).returns("yay")
- assert_raise(Puppet::ParseError, "Failed to fail when overrides remain") do
- compile.send :fail_on_unevaluated_overrides
- end
- end
-
- def test_find_resource
- compile = mkcompile
- resources = compile.instance_variable_get("@resource_table")
-
- assert_nothing_raised("Could not call findresource when the resource table was empty") do
- assert_nil(compile.findresource("yay", "foo"), "Returned a non-existent resource")
- assert_nil(compile.findresource("yay[foo]"), "Returned a non-existent resource")
- end
-
- resources["Foo[bar]"] = :yay
- assert_nothing_raised("Could not call findresource when the resource table was not empty") do
- assert_equal(:yay, compile.findresource("foo", "bar"), "Returned a non-existent resource")
- assert_equal(:yay, compile.findresource("Foo[bar]"), "Returned a non-existent resource")
- end
- end
-
- # #620 - Nodes and classes should conflict, else classes don't get evaluated
- def test_nodes_and_classes_name_conflict
- # Test node then class
- compile = mkcompile
- node = stub :nodescope? => true
- klass = stub :nodescope? => false
- compile.class_set("one", node)
- assert_raise(Puppet::ParseError, "Did not fail when replacing node with class") do
- compile.class_set("one", klass)
- end
-
- # and class then node
- compile = mkcompile
- node = stub :nodescope? => true
- klass = stub :nodescope? => false
- compile.class_set("two", klass)
- assert_raise(Puppet::ParseError, "Did not fail when replacing node with class") do
- compile.class_set("two", node)
- end
- end
-end
diff --git a/test/language/functions.rb b/test/language/functions.rb
index 132ee97ac..a5d52d7ac 100755
--- a/test/language/functions.rb
+++ b/test/language/functions.rb
@@ -41,7 +41,7 @@ class TestLangFunctions < Test::Unit::TestCase
scope = mkscope
val = nil
assert_nothing_raised do
- val = func.evaluate(:scope => scope)
+ val = func.evaluate(scope)
end
assert_equal("output avalue", val)
@@ -57,7 +57,7 @@ class TestLangFunctions < Test::Unit::TestCase
val = nil
assert_nothing_raised do
- val = func.evaluate(:scope => scope)
+ val = func.evaluate(scope)
end
assert_equal(retval, val, "'tagged' returned %s for %s" % [val, tag])
@@ -66,7 +66,7 @@ class TestLangFunctions < Test::Unit::TestCase
# Now make sure we correctly get tags.
scope.resource.tag("resourcetag")
assert(scope.function_tagged("resourcetag"), "tagged function did not catch resource tags")
- scope.compile.catalog.tag("configtag")
+ scope.compiler.catalog.tag("configtag")
assert(scope.function_tagged("configtag"), "tagged function did not catch catalog tags")
end
@@ -86,7 +86,7 @@ class TestLangFunctions < Test::Unit::TestCase
scope = mkscope
val = nil
assert_raise(Puppet::ParseError) do
- val = func.evaluate(:scope => scope)
+ val = func.evaluate(scope)
end
end
@@ -117,16 +117,16 @@ class TestLangFunctions < Test::Unit::TestCase
scope = mkscope
assert_raise(Puppet::ParseError) do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
scope.setvar("one", "One")
assert_raise(Puppet::ParseError) do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
scope.setvar("two", "Two")
assert_nothing_raised do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
assert_equal("template One\ntemplate Two\n", scope.lookupvar("output"),
@@ -155,13 +155,13 @@ class TestLangFunctions < Test::Unit::TestCase
scope = mkscope
assert_raise(Puppet::ParseError) do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
scope.setvar("yayness", "this is yayness")
assert_nothing_raised do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
assert_equal("template this is yayness\n", scope.lookupvar("output"),
@@ -191,7 +191,7 @@ class TestLangFunctions < Test::Unit::TestCase
scope = mkscope
scope.setvar("myvar", "this is yayness")
assert_raise(Puppet::ParseError) do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
end
@@ -264,14 +264,14 @@ class TestLangFunctions < Test::Unit::TestCase
}.each do |string, value|
scope = mkscope
assert_raise(Puppet::ParseError) do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
scope.setvar("yayness", string)
assert_equal(string, scope.lookupvar("yayness", false))
assert_nothing_raised("An empty string was not a valid variable value") do
- ast.evaluate(:scope => scope)
+ ast.evaluate(scope)
end
assert_equal("template #{value}\n", scope.lookupvar("output"),
@@ -308,7 +308,7 @@ class TestLangFunctions < Test::Unit::TestCase
def test_realize
scope = mkscope
- parser = scope.compile.parser
+ parser = scope.compiler.parser
# Make a definition
parser.newdefine("mytype")
@@ -318,7 +318,7 @@ class TestLangFunctions < Test::Unit::TestCase
virtual = mkresource(:type => type, :title => title,
:virtual => true, :params => {}, :scope => scope)
- scope.compile.store_resource(scope, virtual)
+ scope.compiler.add_resource(scope, virtual)
ref = Puppet::Parser::Resource::Reference.new(
:type => type, :title => title,
@@ -330,13 +330,13 @@ class TestLangFunctions < Test::Unit::TestCase
end
# Make sure it created a collection
- assert_equal(1, scope.compile.collections.length,
+ assert_equal(1, scope.compiler.collections.length,
"Did not set collection")
assert_nothing_raised do
- scope.compile.collections.each do |coll| coll.evaluate end
+ scope.compiler.collections.each do |coll| coll.evaluate end
end
- scope.compile.collections.clear
+ scope.compiler.collections.clear
# Now make sure the virtual resource is no longer virtual
assert(! virtual.virtual?, "Did not make virtual resource real")
@@ -354,17 +354,17 @@ class TestLangFunctions < Test::Unit::TestCase
end
# Make sure it created a collection
- assert_equal(1, scope.compile.collections.length,
+ assert_equal(1, scope.compiler.collections.length,
"Did not set collection")
# And the collection has our resource in it
- assert_equal([none.to_s], scope.compile.collections[0].resources,
+ assert_equal([none.to_s], scope.compiler.collections[0].resources,
"Did not set resources in collection")
end
def test_defined
scope = mkscope
- parser = scope.compile.parser
+ parser = scope.compiler.parser
parser.newclass("yayness")
parser.newdefine("rahness")
@@ -385,7 +385,7 @@ class TestLangFunctions < Test::Unit::TestCase
"Multiple falses were somehow true")
# Now make sure we can test resources
- scope.compile.store_resource(scope, mkresource(:type => "file", :title => "/tmp/rahness",
+ scope.compiler.add_resource(scope, mkresource(:type => "file", :title => "/tmp/rahness",
:scope => scope, :source => scope.source,
:params => {:owner => "root"}))
@@ -420,7 +420,7 @@ class TestLangFunctions < Test::Unit::TestCase
def test_include
scope = mkscope
- parser = scope.compile.parser
+ parser = scope.compiler.parser
assert_raise(Puppet::ParseError, "did not throw error on missing class") do
scope.function_include("nosuchclass")
@@ -428,7 +428,7 @@ class TestLangFunctions < Test::Unit::TestCase
parser.newclass("myclass")
- scope.compile.expects(:evaluate_classes).with(%w{myclass otherclass}, scope, false).returns(%w{myclass otherclass})
+ scope.compiler.expects(:evaluate_classes).with(%w{myclass otherclass}, scope, false).returns(%w{myclass otherclass})
assert_nothing_raised do
scope.function_include(["myclass", "otherclass"])
@@ -480,7 +480,7 @@ class TestLangFunctions < Test::Unit::TestCase
assert_equal("yay-foo\n", %x{#{command} foo}, "command did not work")
scope = mkscope
- parser = scope.compile.parser
+ parser = scope.compiler.parser
val = nil
assert_nothing_raised("Could not call generator with no args") do
diff --git a/test/language/lexer.rb b/test/language/lexer.rb
deleted file mode 100755
index 5ac028052..000000000
--- a/test/language/lexer.rb
+++ /dev/null
@@ -1,275 +0,0 @@
-#!/usr/bin/env ruby
-
-require File.dirname(__FILE__) + '/../lib/puppettest'
-
-require 'puppet'
-require 'puppet/parser/lexer'
-require 'puppettest'
-
-#%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 PuppetTest
- def setup
- super
- mklexer
- end
-
- def mklexer
- @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"],[:DQTEXT,"scanner"],[:NAME,"test"],[false,false]],
-%q{a simple 'single quote scanner' test
-} => [[:NAME,"a"],[:NAME,"simple"],[:SQTEXT,"single quote scanner"],[:NAME,"test"],[false,false]],
-%q{a harder 'a $b \c"'
-} => [[:NAME,"a"],[:NAME,"harder"],[:SQTEXT,'a $b \c"'],[false,false]],
-%q{a harder "scanner test"
-} => [[:NAME,"a"],[:NAME,"harder"],[:DQTEXT,"scanner test"],[false,false]],
-%q{a hardest "scanner \"test\""
-} => [[:NAME,"a"],[:NAME,"hardest"],[:DQTEXT,'scanner "test"'],[false,false]],
-%q{a hardestest "scanner \"test\"
-"
-} => [[:NAME,"a"],[:NAME,"hardestest"],[:DQTEXT,'scanner "test"
-'],[false,false]],
-%q{function("call")} => [[:NAME,"function"],[:LPAREN,"("],[:DQTEXT,'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 = Puppet::Parser::Lexer.new()
- lexer.file = file
- assert_nothing_raised("Failed to lex %s" % file) {
- lexer.fullscan()
- }
- }
- 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(
- [[:CLASSREF,t],[false,false]],
- @lexer.fullscan
- )
- }
- end
-
- def test_emptystring
- bit = '$var = ""'
-
- assert_nothing_raised {
- @lexer.string = bit
- }
-
- assert_nothing_raised {
- @lexer.fullscan
- }
- end
-
- def test_collectlexing
- {"@" => :AT, "<|" => :LCOLLECT, "|>" => :RCOLLECT}.each do |string, token|
- assert_nothing_raised {
- @lexer.string = string
- }
-
- ret = nil
- assert_nothing_raised {
- ret = @lexer.fullscan
- }
-
- assert_equal([[token, string],[false, false]], ret)
- end
- end
-
- def test_collectabletype
- string = "@type {"
-
- assert_nothing_raised {
- @lexer.string = string
- }
-
- ret = nil
- assert_nothing_raised {
- ret = @lexer.fullscan
- }
-
- assert_equal([[:AT, "@"], [:NAME, "type"], [:LBRACE, "{"], [false,false]],ret)
- end
-
- def test_namespace
- @lexer.string = %{class myclass}
-
- assert_nothing_raised {
- @lexer.fullscan
- }
-
- assert_equal("myclass", @lexer.namespace)
-
- assert_nothing_raised do
- @lexer.namepop
- end
-
- assert_equal("", @lexer.namespace)
-
- @lexer.string = "class base { class sub { class more"
-
- assert_nothing_raised {
- @lexer.fullscan
- }
-
- assert_equal("base::sub::more", @lexer.namespace)
-
- assert_nothing_raised do
- @lexer.namepop
- end
-
- assert_equal("base::sub", @lexer.namespace)
-
- # Now try it with some fq names
- mklexer
-
- @lexer.string = "class base { class sub::more {"
-
- assert_nothing_raised {
- @lexer.fullscan
- }
-
- assert_equal("base::sub::more", @lexer.namespace)
-
- assert_nothing_raised do
- @lexer.namepop
- end
-
- assert_equal("base", @lexer.namespace)
- end
-
- def test_indefine
- @lexer.string = %{define me}
-
- assert_nothing_raised {
- @lexer.scan { |t,s| }
- }
-
- assert(@lexer.indefine?, "Lexer not considered in define")
-
- # Now make sure we throw an error when trying to nest defines.
- assert_raise(Puppet::ParseError) do
- @lexer.string = %{define another}
- @lexer.scan { |t,s| }
- end
-
- assert_nothing_raised do
- @lexer.indefine = false
- end
-
- assert(! @lexer.indefine?, "Lexer still considered in define")
- end
-
- # Make sure the different qualified variables work.
- def test_variable
- ["$variable", "$::variable", "$qualified::variable", "$further::qualified::variable"].each do |string|
- @lexer.string = string
-
- assert_nothing_raised("Could not lex %s" % string) do
- @lexer.scan do |t, s|
- assert_equal(:VARIABLE, t, "did not get variable as token")
- assert_equal(string.sub(/^\$/, ''), s, "did not get correct string back")
- break
- end
- end
- end
- end
-
- # Make sure the expected stack works as it should
- def test_expected
- @lexer.string = "[a{"
- expected = @lexer.instance_variable_get("@expected")
- @lexer.scan {}
- assert_equal("}", @lexer.expected, "expected value is wrong")
-
- @lexer.string = "}"
- @lexer.scan {}
- assert_equal("]", @lexer.expected, "expected value is wrong after pop")
- end
-
- # #774
- def test_classref_token
- string = ["Foo", "::Foo","Foo::Bar","::Foo::Bar"]
-
- string.each do |foo|
- assert_nothing_raised {
- @lexer.string = foo
- }
-
- ret = nil
- assert_nothing_raised {
- ret = @lexer.fullscan
- }
-
- assert_equal([:CLASSREF, foo],ret[0], "Did not correctly tokenize '%s'" % foo)
- end
- end
-end
-
diff --git a/test/language/parser.rb b/test/language/parser.rb
index 6ff83054a..f7e7d8762 100755
--- a/test/language/parser.rb
+++ b/test/language/parser.rb
@@ -36,9 +36,9 @@ class TestParser < Test::Unit::TestCase
assert_raise(Puppet::ParseError, "Did not fail while parsing %s" % file) {
parser.file = file
ast = parser.parse
- config = mkcompile(parser)
+ config = mkcompiler(parser)
config.compile
- #ast.classes[""].evaluate :scope => config.topscope
+ #ast.classes[""].evaluate config.topscope
}
}
end
@@ -857,7 +857,7 @@ file { "/tmp/yayness":
def test_newclass
scope = mkscope
- parser = scope.compile.parser
+ parser = scope.compiler.parser
mkcode = proc do |ary|
classes = ary.collect do |string|
@@ -880,7 +880,7 @@ file { "/tmp/yayness":
assert(parser.classes["myclass"], "Could not find definition")
assert_equal("myclass", parser.classes["myclass"].classname)
assert_equal(%w{original code},
- parser.classes["myclass"].code.evaluate(:scope => scope))
+ parser.classes["myclass"].code.evaluate(scope))
# Newclass behaves differently than the others -- it just appends
# the code to the existing class.
@@ -890,7 +890,7 @@ file { "/tmp/yayness":
end
assert(klass, "Did not return class when appending")
assert_equal(%w{original code something new},
- parser.classes["myclass"].code.evaluate(:scope => scope))
+ parser.classes["myclass"].code.evaluate(scope))
# Now create the same class name in a different scope
assert_nothing_raised {
@@ -903,7 +903,7 @@ file { "/tmp/yayness":
assert_equal("other::myclass", other.classname)
assert_equal("other::myclass", other.namespace)
assert_equal(%w{something diff},
- other.code.evaluate(:scope => scope))
+ other.code.evaluate(scope))
# Make sure newclass deals correctly with nodes with no code
klass = parser.newclass("nocode")
@@ -914,7 +914,7 @@ file { "/tmp/yayness":
end
assert(klass, "Did not return class with no code")
assert_equal(%w{yay test},
- parser.classes["nocode"].code.evaluate(:scope => scope))
+ parser.classes["nocode"].code.evaluate(scope))
# Then try merging something into nothing
parser.newclass("nocode2", :code => mkcode.call(%w{foo test}))
@@ -925,7 +925,7 @@ file { "/tmp/yayness":
end
assert(klass, "Did not return class with no code")
assert_equal(%w{foo test},
- parser.classes["nocode2"].code.evaluate(:scope => scope))
+ parser.classes["nocode2"].code.evaluate(scope))
# And lastly, nothing and nothing
klass = parser.newclass("nocode3")
@@ -1130,6 +1130,7 @@ file { "/tmp/yayness":
name = "sub"
mk_module(modname, :init => %w{separate}, :sub => %w{separate::sub})
+ Puppet.err :yay
# First try it with a namespace
klass = parser.findclass("separate", name)
assert_instance_of(AST::HostClass, klass, "Did not autoload sub class from separate file with a namespace")
@@ -1177,5 +1178,17 @@ file { "/tmp/yayness":
assert_equal(result, parser.finddefine("", "fUntEst"),
"%s was not matched" % "fUntEst")
end
+
+ def test_manifests_with_multiple_environments
+ parser = mkparser :environment => "something"
+
+ # We use an exception to cut short the processing to simplify our stubbing
+ #Puppet::Module.expects(:find_manifests).with("test", {:cwd => ".", :environment => "something"}).raises(Puppet::ParseError)
+ Puppet::Module.expects(:find_manifests).with("test", {:cwd => ".", :environment => "something"}).returns([])
+
+ assert_raise(Puppet::ImportError) do
+ parser.import("test")
+ end
+ end
end
diff --git a/test/language/resource.rb b/test/language/resource.rb
index 84a30b029..b3eaf0390 100755
--- a/test/language/resource.rb
+++ b/test/language/resource.rb
@@ -23,96 +23,6 @@ class TestResource < PuppetTest::TestCase
mocha_verify
end
- def test_initialize
- args = {:type => "resource", :title => "testing",
- :scope => mkscope}
- # Check our arg requirements
- args.each do |name, value|
- try = args.dup
- try.delete(name)
- assert_raise(ArgumentError, "Did not fail when %s was missing" % name) do
- Parser::Resource.new(try)
- end
- end
-
- res = nil
- assert_nothing_raised do
- res = Parser::Resource.new(args)
- end
-
- ref = res.instance_variable_get("@ref")
- assert_equal("Resource", ref.type, "did not set resource type")
- assert_equal("testing", ref.title, "did not set resource title")
- end
-
- def test_merge
- res = mkresource
- other = mkresource
-
- # First try the case where the resource is not allowed to override
- res.source = "source1"
- other.source = "source2"
- other.source.expects(:child_of?).with("source1").returns(false)
- assert_raise(Puppet::ParseError, "Allowed unrelated resources to override") do
- res.merge(other)
- end
-
- # Next try it when the sources are equal.
- res.source = "source3"
- other.source = res.source
- other.source.expects(:child_of?).with("source3").never
- params = {:a => :b, :c => :d}
- other.expects(:params).returns(params)
- res.expects(:override_parameter).with(:b)
- res.expects(:override_parameter).with(:d)
- res.merge(other)
-
- # And then parentage is involved
- other = mkresource
- res.source = "source3"
- other.source = "source4"
- other.source.expects(:child_of?).with("source3").returns(true)
- params = {:a => :b, :c => :d}
- other.expects(:params).returns(params)
- res.expects(:override_parameter).with(:b)
- res.expects(:override_parameter).with(:d)
- res.merge(other)
- end
-
- # the [] method
- def test_array_accessors
- res = mkresource
- params = res.instance_variable_get("@params")
- assert_nil(res[:missing], "Found a missing parameter somehow")
- params[:something] = stub(:value => "yay")
- assert_equal("yay", res[:something], "Did not correctly call value on the parameter")
-
- res.expects(:title).returns(:mytitle)
- assert_equal(:mytitle, res[:title], "Did not call title when asked for it as a param")
- end
-
- # Make sure any defaults stored in the scope get added to our resource.
- def test_add_defaults
- res = mkresource
- params = res.instance_variable_get("@params")
- params[:a] = :b
- res.scope.expects(:lookupdefaults).with(res.type).returns(:a => :replaced, :c => :d)
- res.expects(:debug)
-
- res.send(:add_defaults)
- assert_equal(:d, params[:c], "Did not set default")
- assert_equal(:b, params[:a], "Replaced parameter with default")
- end
-
- def test_finish
- res = mkresource
- res.expects(:add_overrides)
- res.expects(:add_defaults)
- res.expects(:add_metaparams)
- res.expects(:validate)
- res.finish
- end
-
# Make sure we paramcheck our params
def test_validate
res = mkresource
@@ -124,43 +34,6 @@ class TestResource < PuppetTest::TestCase
res.send(:validate)
end
- def test_override_parameter
- res = mkresource
- params = res.instance_variable_get("@params")
-
- # There are three cases, with the second having two options:
-
- # No existing parameter.
- param = stub(:name => "myparam")
- res.send(:override_parameter, param)
- assert_equal(param, params["myparam"], "Override was not added to param list")
-
- # An existing parameter that we can override.
- source = stub(:child_of? => true)
- # Start out without addition
- params["param2"] = stub(:source => :whatever)
- param = stub(:name => "param2", :source => source, :add => false)
- res.send(:override_parameter, param)
- assert_equal(param, params["param2"], "Override was not added to param list")
-
- # Try with addition.
- params["param2"] = stub(:value => :a, :source => :whatever)
- param = stub(:name => "param2", :source => source, :add => true, :value => :b)
- param.expects(:value=).with([:a, :b])
- res.send(:override_parameter, param)
- assert_equal(param, params["param2"], "Override was not added to param list")
-
- # And finally, make sure we throw an exception when the sources aren't related
- source = stub(:child_of? => false)
- params["param2"] = stub(:source => :whatever, :file => :f, :line => :l)
- old = params["param2"]
- param = stub(:name => "param2", :source => source, :file => :f, :line => :l)
- assert_raise(Puppet::ParseError, "Did not fail when params conflicted") do
- res.send(:override_parameter, param)
- end
- assert_equal(old, params["param2"], "Param was replaced irrespective of conflict")
- end
-
def test_set_parameter
res = mkresource
params = res.instance_variable_get("@params")
@@ -266,48 +139,12 @@ class TestResource < PuppetTest::TestCase
ref.expects(:definedtype).returns(type)
res.expects(:finish)
res.scope = mock("scope")
- config = mock("config")
- res.scope.expects(:compile).returns(config)
- config.expects(:delete_resource).with(res)
- args = {:scope => res.scope, :resource => res}
- type.expects(:evaluate).with(args)
+ type.expects(:evaluate_code).with(res)
res.evaluate
end
- def test_add_overrides
- # Try it with nil
- res = mkresource
- res.scope = mock('scope')
- config = mock("config")
- res.scope.expects(:compile).returns(config)
- config.expects(:resource_overrides).with(res).returns(nil)
- res.expects(:merge).never
- res.send(:add_overrides)
-
- # And an empty array
- res = mkresource
- res.scope = mock('scope')
- config = mock("config")
- res.scope.expects(:compile).returns(config)
- config.expects(:resource_overrides).with(res).returns([])
- res.expects(:merge).never
- res.send(:add_overrides)
-
- # And with some overrides
- res = mkresource
- res.scope = mock('scope')
- config = mock("config")
- res.scope.expects(:compile).returns(config)
- returns = %w{a b}
- config.expects(:resource_overrides).with(res).returns(returns)
- res.expects(:merge).with("a")
- res.expects(:merge).with("b")
- res.send(:add_overrides)
- assert(returns.empty?, "Did not clear overrides")
- end
-
def test_proxymethods
res = Parser::Resource.new :type => "evaltest", :title => "yay",
:source => mock("source"), :scope => mkscope
@@ -378,7 +215,7 @@ class TestResource < PuppetTest::TestCase
{:name => "one", :title => "two"},
{:title => "three"},
].each do |hash|
- config = mkcompile parser
+ config = mkcompiler parser
args = {:type => "yayness", :title => hash[:title],
:source => klass, :scope => config.topscope}
if hash[:name]
@@ -425,7 +262,7 @@ class TestResource < PuppetTest::TestCase
:code => resourcedef("file", varref("name"),
"mode" => "644"))
- config = mkcompile(parser)
+ config = mkcompiler(parser)
res = mkresource :type => "yayness", :title => "foo", :params => {}, :scope => config.topscope
res.virtual = true
@@ -457,37 +294,4 @@ class TestResource < PuppetTest::TestCase
assert(newres.exported?, "Exported defined resource generated non-exported resources")
assert(newres.virtual?, "Exported defined resource generated non-virtual resources")
end
-
- # Make sure tags behave appropriately.
- def test_tags
- scope_resource = stub 'scope_resource', :tags => %w{srone srtwo}
- scope = stub 'scope', :resource => scope_resource
- resource = Puppet::Parser::Resource.new(:type => "file", :title => "yay", :scope => scope, :source => mock('source'))
-
- # Make sure we get the scope resource's tags, plus the type and title
- %w{srone srtwo yay file}.each do |tag|
- assert(resource.tags.include?(tag), "Did not tag resource with %s" % tag)
- end
-
- # make sure we can only set legal tags
- ["an invalid tag", "-anotherinvalid", "bad*tag"].each do |tag|
- assert_raise(Puppet::ParseError, "Tag #{tag} was considered valid") do
- resource.tag tag
- end
- end
-
- # make sure good tags make it through.
- tags = %w{good-tag yaytag GoodTag another_tag a ab A}
- tags.each do |tag|
- assert_nothing_raised("Tag #{tag} was considered invalid") do
- resource.tag tag
- end
- end
-
- # make sure we get each of them.
- ptags = resource.tags
- tags.each do |tag|
- assert(ptags.include?(tag.downcase), "missing #{tag}")
- end
- end
end
diff --git a/test/language/scope.rb b/test/language/scope.rb
index ec11a864e..c96581a23 100755
--- a/test/language/scope.rb
+++ b/test/language/scope.rb
@@ -27,7 +27,7 @@ class TestScope < Test::Unit::TestCase
end
def test_variables
- config = mkcompile
+ config = mkcompiler
topscope = config.topscope
midscope = config.newscope(topscope)
botscope = config.newscope(midscope)
@@ -94,7 +94,7 @@ class TestScope < Test::Unit::TestCase
classes = ["", "one", "one::two", "one::two::three"].each do |name|
klass = parser.newclass(name)
Puppet::Parser::Resource.new(:type => "class", :title => name, :scope => scope, :source => mock('source')).evaluate
- scopes[name] = scope.compile.class_scope(klass)
+ scopes[name] = scope.compiler.class_scope(klass)
end
classes.each do |name|
@@ -125,7 +125,7 @@ class TestScope < Test::Unit::TestCase
end
def test_setdefaults
- config = mkcompile
+ config = mkcompiler
scope = config.topscope
@@ -151,7 +151,7 @@ class TestScope < Test::Unit::TestCase
end
def test_lookupdefaults
- config = mkcompile
+ config = mkcompiler
top = config.topscope
# Make a subscope
@@ -179,7 +179,7 @@ class TestScope < Test::Unit::TestCase
end
def test_parent
- config = mkcompile
+ config = mkcompiler
top = config.topscope
# Make a subscope
@@ -205,7 +205,7 @@ class TestScope < Test::Unit::TestCase
%w{one one::two one::two::three}.each do |name|
klass = parser.newclass(name)
Puppet::Parser::Resource.new(:type => "class", :title => name, :scope => scope, :source => mock('source')).evaluate
- scopes[name] = scope.compile.class_scope(klass)
+ scopes[name] = scope.compiler.class_scope(klass)
scopes[name].setvar("test", "value-%s" % name.sub(/.+::/,''))
end
@@ -284,13 +284,13 @@ class TestScope < Test::Unit::TestCase
)
assert_nothing_raised do
- function.evaluate :scope => scope
+ function.evaluate scope
end
- scope.compile.send(:evaluate_generators)
+ scope.compiler.send(:evaluate_generators)
[myclass, otherclass].each do |klass|
- assert(scope.compile.class_scope(klass),
+ assert(scope.compiler.class_scope(klass),
"%s was not set" % klass.classname)
end
end
@@ -328,18 +328,17 @@ class TestScope < Test::Unit::TestCase
"undef considered true")
end
- if defined? ActiveRecord
# Verify that we recursively mark as exported the results of collectable
# components.
- def test_exportedcomponents
- config = mkcompile
+ def test_virtual_definitions_do_not_get_evaluated
+ config = mkcompiler
parser = config.parser
# Create a default source
config.topscope.source = parser.newclass "", ""
# And a scope resource
- scope_res = stub 'scope_resource', :virtual? => true, :exported? => false, :tags => []
+ scope_res = stub 'scope_resource', :virtual? => true, :exported? => false, :tags => [], :builtin? => true, :type => "eh", :title => "bee"
config.topscope.resource = scope_res
args = AST::ASTArray.new(
@@ -348,7 +347,7 @@ class TestScope < Test::Unit::TestCase
:children => [nameobj("arg")]
)
- # Create a top-level component
+ # Create a top-level define
parser.newdefine "one", :arguments => [%w{arg}],
:code => AST::ASTArray.new(
:children => [
@@ -356,41 +355,26 @@ class TestScope < Test::Unit::TestCase
]
)
- # And a component that calls it
- parser.newdefine "two", :arguments => [%w{arg}],
- :code => AST::ASTArray.new(
- :children => [
- resourcedef("one", "ptest", {"arg" => varref("arg")})
- ]
- )
-
- # And then a third component that calls the second
- parser.newdefine "three", :arguments => [%w{arg}],
- :code => AST::ASTArray.new(
- :children => [
- resourcedef("two", "yay", {"arg" => varref("arg")})
- ]
- )
-
- # lastly, create an object that calls our third component
- obj = resourcedef("three", "boo", {"arg" => "parentfoo"})
+ # create a resource that calls our third define
+ obj = resourcedef("one", "boo", {"arg" => "parentfoo"})
- # And mark it as exported
- obj.exported = true
+ # And mark it as virtual
+ obj.virtual = true
# And then evaluate it
- obj.evaluate :scope => config.topscope
+ obj.evaluate config.topscope
# And run the loop.
config.send(:evaluate_generators)
%w{File}.each do |type|
- objects = config.resources.find_all { |r| r.type == type and r.exported }
+ objects = config.resources.find_all { |r| r.type == type and r.virtual }
- assert(!objects.empty?, "Did not get an exported %s" % type)
+ assert(objects.empty?, "Virtual define got evaluated")
end
end
+ if defined? ActiveRecord
# Verify that we can both store and collect an object in the same
# run, whether it's in the same scope as a collection or a different
# scope.
diff --git a/test/language/snippets.rb b/test/language/snippets.rb
index 01d77c265..95a518388 100755
--- a/test/language/snippets.rb
+++ b/test/language/snippets.rb
@@ -14,6 +14,7 @@ class TestSnippets < Test::Unit::TestCase
def setup
super
+ @file = Puppet::Type.type(:file)
Facter.stubs(:to_hash).returns({})
Facter.stubs(:value).returns("whatever")
end
@@ -422,6 +423,11 @@ class TestSnippets < Test::Unit::TestCase
assert_file("/tmp/realize_defined_test2")
end
+ def snippet_collection_within_virtual_definitions
+ assert_file("/tmp/collection_within_virtual_definitions1_foo.txt")
+ assert_file("/tmp/collection_within_virtual_definitions2_foo2.txt")
+ end
+
def snippet_fqparents
assert_file("/tmp/fqparent1", "Did not make file from parent class")
assert_file("/tmp/fqparent2", "Did not make file from subclass")
diff --git a/test/lib/mocha.rb b/test/lib/mocha.rb
deleted file mode 100644
index 58571156a..000000000
--- a/test/lib/mocha.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-require 'mocha_standalone'
-require 'mocha/test_case_adapter'
-
-require 'test/unit/testcase'
-
-module Test
-
- module Unit
-
- class TestCase
-
- include Mocha::Standalone
- include Mocha::TestCaseAdapter
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/any_instance_method.rb b/test/lib/mocha/any_instance_method.rb
deleted file mode 100644
index 4d55293b9..000000000
--- a/test/lib/mocha/any_instance_method.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-require 'mocha/class_method'
-
-module Mocha
-
- class AnyInstanceMethod < ClassMethod
-
- def unstub
- remove_new_method
- restore_original_method
- stubbee.any_instance.reset_mocha
- end
-
- def mock
- stubbee.any_instance.mocha
- end
-
- def hide_original_method
- stubbee.class_eval "alias_method :#{hidden_method}, :#{method}" if stubbee.method_defined?(method)
- end
-
- def define_new_method
- stubbee.class_eval "def #{method}(*args, &block); self.class.any_instance.mocha.method_missing(:#{method}, *args, &block); end"
- end
-
- def remove_new_method
- stubbee.class_eval "remove_method :#{method}"
- end
-
- def restore_original_method
- stubbee.class_eval "alias_method :#{method}, :#{hidden_method}; remove_method :#{hidden_method}" if stubbee.method_defined?(hidden_method)
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/auto_verify.rb b/test/lib/mocha/auto_verify.rb
deleted file mode 100644
index dce877bde..000000000
--- a/test/lib/mocha/auto_verify.rb
+++ /dev/null
@@ -1,113 +0,0 @@
-require 'mocha/mock'
-
-module Mocha # :nodoc:
-
- # Methods added to TestCase allowing creation of traditional mock objects.
- #
- # Mocks created this way will have their expectations automatically verified at the end of the test.
- #
- # See Mock for methods on mock objects.
- module AutoVerify
-
- def mocks # :nodoc:
- @mocks ||= []
- end
-
- def reset_mocks # :nodoc:
- @mocks = nil
- end
-
- # :call-seq: mock(name) -> mock object
- # mock(expected_methods = {}) -> mock object
- # mock(name, expected_methods = {}) -> mock object
- #
- # Creates a mock object.
- #
- # +name+ is a +String+ identifier for the mock object.
- #
- # +expected_methods+ is a +Hash+ with expected method name symbols as keys and corresponding return values as values.
- #
- # Note that (contrary to expectations set up by #stub) these expectations <b>must</b> be fulfilled during the test.
- # def test_product
- # product = mock('ipod_product', :manufacturer => 'ipod', :price => 100)
- # assert_equal 'ipod', product.manufacturer
- # assert_equal 100, product.price
- # # an error will be raised unless both Product#manufacturer and Product#price have been called
- # end
- def mock(*args)
- name, expectations = name_and_expectations_from_args(args)
- build_mock_with_expectations(:expects, expectations, name)
- end
-
- # :call-seq: stub(name) -> mock object
- # stub(stubbed_methods = {}) -> mock object
- # stub(name, stubbed_methods = {}) -> mock object
- #
- # Creates a mock object.
- #
- # +name+ is a +String+ identifier for the mock object.
- #
- # +stubbed_methods+ is a +Hash+ with stubbed method name symbols as keys and corresponding return values as values.
- #
- # Note that (contrary to expectations set up by #mock) these expectations <b>need not</b> be fulfilled during the test.
- # def test_product
- # product = stub('ipod_product', :manufacturer => 'ipod', :price => 100)
- # assert_equal 'ipod', product.manufacturer
- # assert_equal 100, product.price
- # # an error will not be raised even if Product#manufacturer and Product#price have not been called
- # end
- def stub(*args)
- name, expectations = name_and_expectations_from_args(args)
- build_mock_with_expectations(:stubs, expectations, name)
- end
-
- # :call-seq: stub_everything(name) -> mock object
- # stub_everything(stubbed_methods = {}) -> mock object
- # stub_everything(name, stubbed_methods = {}) -> mock object
- #
- # Creates a mock object that accepts calls to any method.
- #
- # By default it will return +nil+ for any method call.
- #
- # +name+ and +stubbed_methods+ work in the same way as for #stub.
- # def test_product
- # product = stub_everything('ipod_product', :price => 100)
- # assert_nil product.manufacturer
- # assert_nil product.any_old_method
- # assert_equal 100, product.price
- # end
- def stub_everything(*args)
- name, expectations = name_and_expectations_from_args(args)
- build_mock_with_expectations(:stub_everything, expectations, name)
- end
-
- def verify_mocks # :nodoc:
- mocks.each { |mock| mock.verify { yield if block_given? } }
- end
-
- def teardown_mocks # :nodoc:
- reset_mocks
- end
-
- def build_mock_with_expectations(expectation_type = :expects, expectations = {}, name = nil) # :nodoc:
- stub_everything = (expectation_type == :stub_everything)
- expectation_type = :stubs if expectation_type == :stub_everything
- mock = Mocha::Mock.new(stub_everything, name)
- expectations.each do |method, result|
- mock.__send__(expectation_type, method).returns(result)
- end
- mocks << mock
- mock
- end
-
- private
-
- def name_and_expectations_from_args(args) # :nodoc:
- name = args.first.is_a?(String) ? args.delete_at(0) : nil
- expectations = args.first || {}
- [name, expectations]
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/central.rb b/test/lib/mocha/central.rb
deleted file mode 100644
index 3dde7350f..000000000
--- a/test/lib/mocha/central.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-module Mocha
-
- class Central
-
- attr_accessor :stubba_methods
-
- def initialize
- self.stubba_methods = []
- end
-
- def stub(method)
- unless stubba_methods.include?(method)
- method.stub
- stubba_methods.push method
- end
- end
-
- def verify_all(&block)
- unique_mocks.each { |mock| mock.verify(&block) }
- end
-
- def unique_mocks
- stubba_methods.inject({}) { |mocks, method| mocks[method.mock.__id__] = method.mock; mocks }.values
- end
-
- def unstub_all
- while stubba_methods.size > 0
- method = stubba_methods.pop
- method.unstub
- end
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/class_method.rb b/test/lib/mocha/class_method.rb
deleted file mode 100644
index 915fe71b5..000000000
--- a/test/lib/mocha/class_method.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-require 'mocha/metaclass'
-
-module Mocha
-
- class ClassMethod
-
- attr_reader :stubbee, :method
-
- def initialize(stubbee, method)
- @stubbee, @method = stubbee, method
- end
-
- def stub
- hide_original_method
- define_new_method
- end
-
- def unstub
- remove_new_method
- restore_original_method
- stubbee.reset_mocha
- end
-
- def mock
- stubbee.mocha
- end
-
- def hide_original_method
- stubbee.__metaclass__.class_eval "alias_method :#{hidden_method}, :#{method}" if stubbee.__metaclass__.method_defined?(method)
- end
-
- def define_new_method
- stubbee.__metaclass__.class_eval "def #{method}(*args, &block); mocha.method_missing(:#{method}, *args, &block); end"
- end
-
- def remove_new_method
- stubbee.__metaclass__.class_eval "remove_method :#{method}"
- end
-
- def restore_original_method
- stubbee.__metaclass__.class_eval "alias_method :#{method}, :#{hidden_method}; remove_method :#{hidden_method}" if stubbee.__metaclass__.method_defined?(hidden_method)
- end
-
- def hidden_method
- method_name = method.to_s.gsub(/\W/) {|s| "_substituted_character_#{s[0]}_" }
- "__stubba__#{method_name}__stubba__"
- end
-
- def eql?(other)
- return false unless (other.class == self.class)
- (stubbee == other.stubbee) and (method == other.method)
- end
-
- alias_method :==, :eql?
-
- def to_s
- "#{stubbee}.#{method}"
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/deprecation.rb b/test/lib/mocha/deprecation.rb
deleted file mode 100644
index 7448510ec..000000000
--- a/test/lib/mocha/deprecation.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-module Mocha
-
- class Deprecation
-
- class << self
-
- attr_accessor :mode, :messages
-
- def warning(message)
- @messages << message
- $stderr.puts "Mocha deprecation warning: #{message}" unless mode == :disabled
- $stderr.puts caller.join("\n ") if mode == :debug
- end
-
- end
-
- self.mode = :enabled
- self.messages = []
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/exception_raiser.rb b/test/lib/mocha/exception_raiser.rb
deleted file mode 100644
index 266e209a2..000000000
--- a/test/lib/mocha/exception_raiser.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-module Mocha # :nodoc:
-
- class ExceptionRaiser # :nodoc:
-
- def initialize(exception, message)
- @exception, @message = exception, message
- end
-
- def evaluate
- raise @exception, @exception.to_s if @exception == Interrupt
- raise @exception, @message if @message
- raise @exception
- end
-
- end
-
-end
diff --git a/test/lib/mocha/expectation.rb b/test/lib/mocha/expectation.rb
deleted file mode 100644
index 49b39bea9..000000000
--- a/test/lib/mocha/expectation.rb
+++ /dev/null
@@ -1,378 +0,0 @@
-require 'mocha/infinite_range'
-require 'mocha/pretty_parameters'
-require 'mocha/expectation_error'
-require 'mocha/return_values'
-require 'mocha/exception_raiser'
-require 'mocha/yield_parameters'
-require 'mocha/is_a'
-
-module Mocha # :nodoc:
-
- # Methods on expectations returned from Mock#expects, Mock#stubs, Object#expects and Object#stubs.
- class Expectation
-
- # :stopdoc:
-
- class AlwaysEqual
- def ==(other)
- true
- end
- end
-
- attr_reader :method_name, :backtrace
-
- def initialize(mock, method_name, backtrace = nil)
- @mock, @method_name = mock, method_name
- @expected_count = 1
- @parameters, @parameter_block = AlwaysEqual.new, nil
- @invoked_count, @return_values = 0, ReturnValues.new
- @backtrace = backtrace || caller
- @yield_parameters = YieldParameters.new
- end
-
- def match?(method_name, *arguments)
- return false unless @method_name == method_name
- if @parameter_block then
- return false unless @parameter_block.call(*arguments)
- else
- return false unless (@parameters == arguments)
- end
- if @expected_count.is_a?(Range) then
- return false unless @invoked_count < @expected_count.last
- else
- return false unless @invoked_count < @expected_count
- end
- return true
- end
-
- # :startdoc:
-
- # :call-seq: times(range) -> expectation
- #
- # Modifies expectation so that the number of calls to the expected method must be within a specific +range+.
- #
- # +range+ can be specified as an exact integer or as a range of integers
- # object = mock()
- # object.expects(:expected_method).times(3)
- # 3.times { object.expected_method }
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).times(3)
- # 2.times { object.expected_method }
- # # => verify fails
- #
- # object = mock()
- # object.expects(:expected_method).times(2..4)
- # 3.times { object.expected_method }
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).times(2..4)
- # object.expected_method
- # # => verify fails
- def times(range)
- @expected_count = range
- self
- end
-
- # :call-seq: once() -> expectation
- #
- # Modifies expectation so that the expected method must be called exactly once.
- # Note that this is the default behaviour for an expectation, but you may wish to use it for clarity/emphasis.
- # object = mock()
- # object.expects(:expected_method).once
- # object.expected_method
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).once
- # object.expected_method
- # object.expected_method
- # # => verify fails
- #
- # object = mock()
- # object.expects(:expected_method).once
- # # => verify fails
- def once()
- times(1)
- self
- end
-
- # :call-seq: never() -> expectation
- #
- # Modifies expectation so that the expected method must never be called.
- # object = mock()
- # object.expects(:expected_method).never
- # object.expected_method
- # # => verify fails
- #
- # object = mock()
- # object.expects(:expected_method).never
- # object.expected_method
- # # => verify succeeds
- def never
- times(0)
- self
- end
-
- # :call-seq: at_least(minimum_number_of_times) -> expectation
- #
- # Modifies expectation so that the expected method must be called at least a +minimum_number_of_times+.
- # object = mock()
- # object.expects(:expected_method).at_least(2)
- # 3.times { object.expected_method }
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).at_least(2)
- # object.expected_method
- # # => verify fails
- def at_least(minimum_number_of_times)
- times(Range.at_least(minimum_number_of_times))
- self
- end
-
- # :call-seq: at_least_once() -> expectation
- #
- # Modifies expectation so that the expected method must be called at least once.
- # object = mock()
- # object.expects(:expected_method).at_least_once
- # object.expected_method
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).at_least_once
- # # => verify fails
- def at_least_once()
- at_least(1)
- self
- end
-
- # :call-seq: at_most(maximum_number_of_times) -> expectation
- #
- # Modifies expectation so that the expected method must be called at most a +maximum_number_of_times+.
- # object = mock()
- # object.expects(:expected_method).at_most(2)
- # 2.times { object.expected_method }
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).at_most(2)
- # 3.times { object.expected_method }
- # # => verify fails
- def at_most(maximum_number_of_times)
- times(Range.at_most(maximum_number_of_times))
- self
- end
-
- # :call-seq: at_most_once() -> expectation
- #
- # Modifies expectation so that the expected method must be called at most once.
- # object = mock()
- # object.expects(:expected_method).at_most_once
- # object.expected_method
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).at_most_once
- # 2.times { object.expected_method }
- # # => verify fails
- def at_most_once()
- at_most(1)
- self
- end
-
- # :call-seq: with(*arguments, &parameter_block) -> expectation
- #
- # Modifies expectation so that the expected method must be called with specified +arguments+.
- # object = mock()
- # object.expects(:expected_method).with(:param1, :param2)
- # object.expected_method(:param1, :param2)
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).with(:param1, :param2)
- # object.expected_method(:param3)
- # # => verify fails
- # May be used with parameter matchers in Mocha::ParameterMatchers.
- #
- # If a +parameter_block+ is given, the block is called with the parameters passed to the expected method.
- # The expectation is matched if the block evaluates to +true+.
- # object = mock()
- # object.expects(:expected_method).with() { |value| value % 4 == 0 }
- # object.expected_method(16)
- # # => verify succeeds
- #
- # object = mock()
- # object.expects(:expected_method).with() { |value| value % 4 == 0 }
- # object.expected_method(17)
- # # => verify fails
- def with(*arguments, &parameter_block)
- @parameters, @parameter_block = arguments, parameter_block
- class << @parameters; def to_s; join(', '); end; end
- self
- end
-
- # :call-seq: yields(*parameters) -> expectation
- #
- # Modifies expectation so that when the expected method is called, it yields with the specified +parameters+.
- # object = mock()
- # object.expects(:expected_method).yields('result')
- # yielded_value = nil
- # object.expected_method { |value| yielded_value = value }
- # yielded_value # => 'result'
- # May be called multiple times on the same expectation for consecutive invocations. Also see Expectation#then.
- # object = mock()
- # object.stubs(:expected_method).yields(1).then.yields(2)
- # yielded_values_from_first_invocation = []
- # yielded_values_from_second_invocation = []
- # object.expected_method { |value| yielded_values_from_first_invocation << value } # first invocation
- # object.expected_method { |value| yielded_values_from_second_invocation << value } # second invocation
- # yielded_values_from_first_invocation # => [1]
- # yielded_values_from_second_invocation # => [2]
- def yields(*parameters)
- @yield_parameters.add(*parameters)
- self
- end
-
- # :call-seq: multiple_yields(*parameter_groups) -> expectation
- #
- # Modifies expectation so that when the expected method is called, it yields multiple times per invocation with the specified +parameter_groups+.
- # object = mock()
- # object.expects(:expected_method).multiple_yields(['result_1', 'result_2'], ['result_3'])
- # yielded_values = []
- # object.expected_method { |*values| yielded_values << values }
- # yielded_values # => [['result_1', 'result_2'], ['result_3]]
- # May be called multiple times on the same expectation for consecutive invocations. Also see Expectation#then.
- # object = mock()
- # object.stubs(:expected_method).multiple_yields([1, 2], [3]).then.multiple_yields([4], [5, 6])
- # yielded_values_from_first_invocation = []
- # yielded_values_from_second_invocation = []
- # object.expected_method { |*values| yielded_values_from_first_invocation << values } # first invocation
- # object.expected_method { |*values| yielded_values_from_second_invocation << values } # second invocation
- # yielded_values_from_first_invocation # => [[1, 2], [3]]
- # yielded_values_from_second_invocation # => [[4], [5, 6]]
- def multiple_yields(*parameter_groups)
- @yield_parameters.multiple_add(*parameter_groups)
- self
- end
-
- # :call-seq: returns(value) -> expectation
- # :call-seq: returns(*values) -> expectation
- #
- # Modifies expectation so that when the expected method is called, it returns the specified +value+.
- # object = mock()
- # object.stubs(:stubbed_method).returns('result')
- # object.stubbed_method # => 'result'
- # object.stubbed_method # => 'result'
- # If multiple +values+ are given, these are returned in turn on consecutive calls to the method.
- # object = mock()
- # object.stubs(:stubbed_method).returns(1, 2)
- # object.stubbed_method # => 1
- # object.stubbed_method # => 2
- # May be called multiple times on the same expectation. Also see Expectation#then.
- # object = mock()
- # object.stubs(:expected_method).returns(1, 2).then.returns(3)
- # object.expected_method # => 1
- # object.expected_method # => 2
- # object.expected_method # => 3
- # May be called in conjunction with Expectation#raises on the same expectation.
- # object = mock()
- # object.stubs(:expected_method).returns(1, 2).then.raises(Exception)
- # object.expected_method # => 1
- # object.expected_method # => 2
- # object.expected_method # => raises exception of class Exception1
- # If +value+ is a +Proc+, then the expected method will return the result of calling <tt>Proc#call</tt>.
- #
- # This usage is _deprecated_.
- # Use explicit multiple return values and/or multiple expectations instead.
- #
- # A +Proc+ instance will be treated the same as any other value in a future release.
- # object = mock()
- # object.stubs(:stubbed_method).returns(lambda { rand(100) })
- # object.stubbed_method # => 41
- # object.stubbed_method # => 77
- def returns(*values)
- @return_values += ReturnValues.build(*values)
- self
- end
-
- # :call-seq: raises(exception = RuntimeError, message = nil) -> expectation
- #
- # Modifies expectation so that when the expected method is called, it raises the specified +exception+ with the specified +message+.
- # object = mock()
- # object.expects(:expected_method).raises(Exception, 'message')
- # object.expected_method # => raises exception of class Exception and with message 'message'
- # May be called multiple times on the same expectation. Also see Expectation#then.
- # object = mock()
- # object.stubs(:expected_method).raises(Exception1).then.raises(Exception2)
- # object.expected_method # => raises exception of class Exception1
- # object.expected_method # => raises exception of class Exception2
- # May be called in conjunction with Expectation#returns on the same expectation.
- # object = mock()
- # object.stubs(:expected_method).raises(Exception).then.returns(2, 3)
- # object.expected_method # => raises exception of class Exception1
- # object.expected_method # => 2
- # object.expected_method # => 3
- def raises(exception = RuntimeError, message = nil)
- @return_values += ReturnValues.new(ExceptionRaiser.new(exception, message))
- self
- end
-
- # :call-seq: then() -> expectation
- #
- # Syntactic sugar to improve readability. Has no effect on state of the expectation.
- # object = mock()
- # object.stubs(:expected_method).returns(1, 2).then.raises(Exception).then.returns(4)
- # object.expected_method # => 1
- # object.expected_method # => 2
- # object.expected_method # => raises exception of class Exception
- # object.expected_method # => 4
- def then
- self
- end
-
- # :stopdoc:
-
- def invoke
- @invoked_count += 1
- if block_given? then
- @yield_parameters.next_invocation.each do |yield_parameters|
- yield(*yield_parameters)
- end
- end
- @return_values.next
- end
-
- def verify
- yield(self) if block_given?
- unless (@expected_count === @invoked_count) then
- error = ExpectationError.new(error_message(@expected_count, @invoked_count))
- error.set_backtrace(filtered_backtrace)
- raise error
- end
- end
-
- def mocha_lib_directory
- File.expand_path(File.join(File.dirname(__FILE__), "..")) + File::SEPARATOR
- end
-
- def filtered_backtrace
- backtrace.reject { |location| Regexp.new(mocha_lib_directory).match(File.expand_path(location)) }
- end
-
- def method_signature
- return "#{method_name}" if @parameters.__is_a__(AlwaysEqual)
- "#{@method_name}(#{PrettyParameters.new(@parameters).pretty})"
- end
-
- def error_message(expected_count, actual_count)
- "#{@mock.mocha_inspect}.#{method_signature} - expected calls: #{expected_count.mocha_inspect}, actual calls: #{actual_count}"
- end
-
- # :startdoc:
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/expectation_error.rb b/test/lib/mocha/expectation_error.rb
deleted file mode 100644
index c01482e63..000000000
--- a/test/lib/mocha/expectation_error.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-module Mocha
-
- class ExpectationError < StandardError
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/infinite_range.rb b/test/lib/mocha/infinite_range.rb
deleted file mode 100644
index 05dfe559e..000000000
--- a/test/lib/mocha/infinite_range.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-class Range
-
- def self.at_least(minimum_value)
- Range.new(minimum_value, infinite)
- end
-
- def self.at_most(maximum_value)
- Range.new(-infinite, maximum_value, false)
- end
-
- def self.infinite
- 1/0.0
- end
-
- def mocha_inspect
- if first.respond_to?(:to_f) and first.to_f.infinite? then
- return "at most #{last}"
- elsif last.respond_to?(:to_f) and last.to_f.infinite? then
- return "at least #{first}"
- else
- to_s
- end
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/inspect.rb b/test/lib/mocha/inspect.rb
deleted file mode 100644
index ad82ef70e..000000000
--- a/test/lib/mocha/inspect.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-require 'date'
-
-class Object
- def mocha_inspect
- address = self.__id__ * 2
- address += 0x100000000 if address < 0
- inspect =~ /#</ ? "#<#{self.class}:0x#{'%x' % address}>" : inspect
- end
-end
-
-class String
- def mocha_inspect
- inspect.gsub(/\"/, "'")
- end
-end
-
-class Array
- def mocha_inspect
- "[#{collect { |member| member.mocha_inspect }.join(', ')}]"
- end
-end
-
-class Hash
- def mocha_inspect
- "{#{collect { |key, value| "#{key.mocha_inspect} => #{value.mocha_inspect}" }.join(', ')}}"
- end
-end
-
-class Time
- def mocha_inspect
- "#{inspect} (#{to_f} secs)"
- end
-end
-
-class Date
- def mocha_inspect
- to_s
- end
-end \ No newline at end of file
diff --git a/test/lib/mocha/instance_method.rb b/test/lib/mocha/instance_method.rb
deleted file mode 100644
index f0d4b04b8..000000000
--- a/test/lib/mocha/instance_method.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'mocha/class_method'
-
-module Mocha
-
- class InstanceMethod < ClassMethod
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/is_a.rb b/test/lib/mocha/is_a.rb
deleted file mode 100644
index ee23c86a9..000000000
--- a/test/lib/mocha/is_a.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-class Object
-
- # :stopdoc:
-
- alias_method :__is_a__, :is_a?
-
- # :startdoc:
-
-end
diff --git a/test/lib/mocha/metaclass.rb b/test/lib/mocha/metaclass.rb
deleted file mode 100644
index f78fb892b..000000000
--- a/test/lib/mocha/metaclass.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-class Object
-
- def __metaclass__
- class << self; self; end
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/missing_expectation.rb b/test/lib/mocha/missing_expectation.rb
deleted file mode 100644
index f84227d1a..000000000
--- a/test/lib/mocha/missing_expectation.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-require 'mocha/expectation'
-
-module Mocha # :nodoc:
-
- class MissingExpectation < Expectation # :nodoc:
-
- def initialize(mock, method_name)
- super
- @invoked_count = true
- end
-
- def verify
- msg = error_message(0, 1)
- similar_expectations_list = similar_expectations.collect { |expectation| expectation.method_signature }.join("\n")
- msg << "\nSimilar expectations:\n#{similar_expectations_list}" unless similar_expectations.empty?
- error = ExpectationError.new(msg)
- error.set_backtrace(filtered_backtrace)
- raise error if @invoked_count
- end
-
- def similar_expectations
- @mock.expectations.select { |expectation| expectation.method_name == self.method_name }
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/mock.rb b/test/lib/mocha/mock.rb
deleted file mode 100644
index 18c23fede..000000000
--- a/test/lib/mocha/mock.rb
+++ /dev/null
@@ -1,207 +0,0 @@
-require 'mocha/expectation'
-require 'mocha/stub'
-require 'mocha/missing_expectation'
-require 'mocha/metaclass'
-
-module Mocha # :nodoc:
-
- # Traditional mock object.
- #
- # Methods return an Expectation which can be further modified by methods on Expectation.
- class Mock
-
- # :stopdoc:
-
- def initialize(stub_everything = false, name = nil)
- @stub_everything = stub_everything
- @mock_name = name
- @expectations = []
- @responder = nil
- end
-
- attr_reader :stub_everything, :expectations
-
- # :startdoc:
-
- # :call-seq: expects(method_name) -> expectation
- # expects(method_names) -> last expectation
- #
- # Adds an expectation that a method identified by +method_name+ symbol must be called exactly once with any parameters.
- # Returns the new expectation which can be further modified by methods on Expectation.
- # object = mock()
- # object.expects(:method1)
- # object.method1
- # # no error raised
- #
- # object = mock()
- # object.expects(:method1)
- # # error raised, because method1 not called exactly once
- # If +method_names+ is a +Hash+, an expectation will be set up for each entry using the key as +method_name+ and value as +return_value+.
- # object = mock()
- # object.expects(:method1 => :result1, :method2 => :result2)
- #
- # # exactly equivalent to
- #
- # object = mock()
- # object.expects(:method1).returns(:result1)
- # object.expects(:method2).returns(:result2)
- #
- # Aliased by <tt>\_\_expects\_\_</tt>
- def expects(method_name_or_hash, backtrace = nil)
- if method_name_or_hash.is_a?(Hash) then
- method_name_or_hash.each do |method_name, return_value|
- add_expectation(Expectation.new(self, method_name, backtrace).returns(return_value))
- end
- else
- add_expectation(Expectation.new(self, method_name_or_hash, backtrace))
- end
- end
-
- # :call-seq: stubs(method_name) -> expectation
- # stubs(method_names) -> last expectation
- #
- # Adds an expectation that a method identified by +method_name+ symbol may be called any number of times with any parameters.
- # Returns the new expectation which can be further modified by methods on Expectation.
- # object = mock()
- # object.stubs(:method1)
- # object.method1
- # object.method1
- # # no error raised
- # If +method_names+ is a +Hash+, an expectation will be set up for each entry using the key as +method_name+ and value as +return_value+.
- # object = mock()
- # object.stubs(:method1 => :result1, :method2 => :result2)
- #
- # # exactly equivalent to
- #
- # object = mock()
- # object.stubs(:method1).returns(:result1)
- # object.stubs(:method2).returns(:result2)
- #
- # Aliased by <tt>\_\_stubs\_\_</tt>
- def stubs(method_name_or_hash, backtrace = nil)
- if method_name_or_hash.is_a?(Hash) then
- method_name_or_hash.each do |method_name, return_value|
- add_expectation(Stub.new(self, method_name, backtrace).returns(return_value))
- end
- else
- add_expectation(Stub.new(self, method_name_or_hash, backtrace))
- end
- end
-
- # :call-seq: responds_like(responder) -> mock
- #
- # Constrains the +mock+ so that it can only expect or stub methods to which +responder+ responds. The constraint is only applied at method invocation time.
- #
- # A +NoMethodError+ will be raised if the +responder+ does not <tt>respond_to?</tt> a method invocation (even if the method has been expected or stubbed).
- #
- # The +mock+ will delegate its <tt>respond_to?</tt> method to the +responder+.
- # class Sheep
- # def chew(grass); end
- # def self.number_of_legs; end
- # end
- #
- # sheep = mock('sheep')
- # sheep.expects(:chew)
- # sheep.expects(:foo)
- # sheep.respond_to?(:chew) # => true
- # sheep.respond_to?(:foo) # => true
- # sheep.chew
- # sheep.foo
- # # no error raised
- #
- # sheep = mock('sheep')
- # sheep.responds_like(Sheep.new)
- # sheep.expects(:chew)
- # sheep.expects(:foo)
- # sheep.respond_to?(:chew) # => true
- # sheep.respond_to?(:foo) # => false
- # sheep.chew
- # sheep.foo # => raises NoMethodError exception
- #
- # sheep_class = mock('sheep_class')
- # sheep_class.responds_like(Sheep)
- # sheep_class.stubs(:number_of_legs).returns(4)
- # sheep_class.expects(:foo)
- # sheep_class.respond_to?(:number_of_legs) # => true
- # sheep_class.respond_to?(:foo) # => false
- # assert_equal 4, sheep_class.number_of_legs
- # sheep_class.foo # => raises NoMethodError exception
- #
- # Aliased by +quacks_like+
- def responds_like(object)
- @responder = object
- self
- end
-
- # :stopdoc:
-
- alias_method :__expects__, :expects
-
- alias_method :__stubs__, :stubs
-
- alias_method :quacks_like, :responds_like
-
- def add_expectation(expectation)
- @expectations << expectation
- method_name = expectation.method_name
- self.__metaclass__.send(:undef_method, method_name) if self.__metaclass__.method_defined?(method_name)
- expectation
- end
-
- def method_missing(symbol, *arguments, &block)
- if @responder and not @responder.respond_to?(symbol)
- raise NoMethodError, "undefined method `#{symbol}' for #{self.mocha_inspect} which responds like #{@responder.mocha_inspect}"
- end
- matching_expectation = matching_expectation(symbol, *arguments)
- if matching_expectation then
- matching_expectation.invoke(&block)
- elsif stub_everything then
- return
- else
- begin
- super_method_missing(symbol, *arguments, &block)
- rescue NoMethodError
- unexpected_method_called(symbol, *arguments)
- end
- end
- end
-
- def respond_to?(symbol)
- if @responder then
- @responder.respond_to?(symbol)
- else
- @expectations.any? { |expectation| expectation.method_name == symbol }
- end
- end
-
- def super_method_missing(symbol, *arguments, &block)
- raise NoMethodError
- end
-
- def unexpected_method_called(symbol, *arguments)
- MissingExpectation.new(self, symbol).with(*arguments).verify
- end
-
- def matching_expectation(symbol, *arguments)
- @expectations.reverse.detect { |expectation| expectation.match?(symbol, *arguments) }
- end
-
- def verify(&block)
- @expectations.each { |expectation| expectation.verify(&block) }
- end
-
- def mocha_inspect
- address = self.__id__ * 2
- address += 0x100000000 if address < 0
- @mock_name ? "#<Mock:#{@mock_name}>" : "#<Mock:0x#{'%x' % address}>"
- end
-
- def inspect
- mocha_inspect
- end
-
- # :startdoc:
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/multiple_yields.rb b/test/lib/mocha/multiple_yields.rb
deleted file mode 100644
index 8186c3076..000000000
--- a/test/lib/mocha/multiple_yields.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-module Mocha # :nodoc:
-
- class MultipleYields # :nodoc:
-
- attr_reader :parameter_groups
-
- def initialize(*parameter_groups)
- @parameter_groups = parameter_groups
- end
-
- def each
- @parameter_groups.each do |parameter_group|
- yield(parameter_group)
- end
- end
-
- end
-
-end
-
diff --git a/test/lib/mocha/no_yields.rb b/test/lib/mocha/no_yields.rb
deleted file mode 100644
index b0fba415d..000000000
--- a/test/lib/mocha/no_yields.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-module Mocha # :nodoc:
-
- class NoYields # :nodoc:
-
- def each
- end
-
- end
-
-end
-
diff --git a/test/lib/mocha/object.rb b/test/lib/mocha/object.rb
deleted file mode 100644
index 7ccdbad0d..000000000
--- a/test/lib/mocha/object.rb
+++ /dev/null
@@ -1,110 +0,0 @@
-require 'mocha/mock'
-require 'mocha/instance_method'
-require 'mocha/class_method'
-require 'mocha/any_instance_method'
-
-# Methods added all objects to allow mocking and stubbing on real objects.
-#
-# Methods return a Mocha::Expectation which can be further modified by methods on Mocha::Expectation.
-class Object
-
- def mocha # :nodoc:
- @mocha ||= Mocha::Mock.new
- end
-
- def reset_mocha # :nodoc:
- @mocha = nil
- end
-
- def stubba_method # :nodoc:
- Mocha::InstanceMethod
- end
-
- def stubba_object # :nodoc:
- self
- end
-
- # :call-seq: expects(symbol) -> expectation
- #
- # Adds an expectation that a method identified by +symbol+ must be called exactly once with any parameters.
- # Returns the new expectation which can be further modified by methods on Mocha::Expectation.
- # product = Product.new
- # product.expects(:save).returns(true)
- # assert_equal false, product.save
- #
- # The original implementation of <tt>Product#save</tt> is replaced temporarily.
- #
- # The original implementation of <tt>Product#save</tt> is restored at the end of the test.
- def expects(symbol)
- method = stubba_method.new(stubba_object, symbol)
- $stubba.stub(method)
- mocha.expects(symbol, caller)
- end
-
- # :call-seq: stubs(symbol) -> expectation
- #
- # Adds an expectation that a method identified by +symbol+ may be called any number of times with any parameters.
- # Returns the new expectation which can be further modified by methods on Mocha::Expectation.
- # product = Product.new
- # product.stubs(:save).returns(true)
- # assert_equal false, product.save
- #
- # The original implementation of <tt>Product#save</tt> is replaced temporarily.
- #
- # The original implementation of <tt>Product#save</tt> is restored at the end of the test.
- def stubs(symbol)
- method = stubba_method.new(stubba_object, symbol)
- $stubba.stub(method)
- mocha.stubs(symbol, caller)
- end
-
- def verify # :nodoc:
- mocha.verify
- end
-
-end
-
-class Module # :nodoc:
-
- def stubba_method
- Mocha::ClassMethod
- end
-
-end
-
-class Class
-
- def stubba_method # :nodoc:
- Mocha::ClassMethod
- end
-
- class AnyInstance # :nodoc:
-
- def initialize(klass)
- @stubba_object = klass
- end
-
- def stubba_method
- Mocha::AnyInstanceMethod
- end
-
- def stubba_object
- @stubba_object
- end
-
- end
-
- # :call-seq: any_instance -> mock object
- #
- # Returns a mock object which will detect calls to any instance of this class.
- # Product.any_instance.stubs(:save).returns(false)
- # product_1 = Product.new
- # assert_equal false, product_1.save
- # product_2 = Product.new
- # assert_equal false, product_2.save
- def any_instance
- @any_instance ||= AnyInstance.new(self)
- end
-
-end
-
diff --git a/test/lib/mocha/parameter_matchers.rb b/test/lib/mocha/parameter_matchers.rb
deleted file mode 100644
index 193f77d93..000000000
--- a/test/lib/mocha/parameter_matchers.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-module Mocha
-
- # Used as parameters for Expectation#with to restrict the parameter values which will match the expectation.
- module ParameterMatchers; end
-
-end
-
-
-Dir[File.expand_path(File.join(File.dirname(__FILE__), 'parameter_matchers', "*.rb"))].each { |lib| require lib }
diff --git a/test/lib/mocha/parameter_matchers/all_of.rb b/test/lib/mocha/parameter_matchers/all_of.rb
deleted file mode 100644
index 343d9eea0..000000000
--- a/test/lib/mocha/parameter_matchers/all_of.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-module Mocha
-
- module ParameterMatchers
-
- # :call-seq: all_of -> parameter_matcher
- #
- # Matches if all +matchers+ match.
- # object = mock()
- # object.expects(:method_1).with(all_of(includes(1), includes(3)))
- # object.method_1([1, 3])
- # # no error raised
- #
- # object = mock()
- # object.expects(:method_1).with(all_of(includes(1), includes(3)))
- # object.method_1([1, 2])
- # # error raised, because method_1 was not called with object including 1 and 3
- def all_of(*matchers)
- AllOf.new(*matchers)
- end
-
- class AllOf # :nodoc:
-
- def initialize(*matchers)
- @matchers = matchers
- end
-
- def ==(parameter)
- @matchers.all? { |matcher| matcher == parameter }
- end
-
- def mocha_inspect
- "all_of(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })"
- end
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/parameter_matchers/any_of.rb b/test/lib/mocha/parameter_matchers/any_of.rb
deleted file mode 100644
index a1f88075d..000000000
--- a/test/lib/mocha/parameter_matchers/any_of.rb
+++ /dev/null
@@ -1,44 +0,0 @@
-module Mocha
-
- module ParameterMatchers
-
- # :call-seq: any_of -> parameter_matcher
- #
- # Matches if any +matchers+ match.
- # object = mock()
- # object.expects(:method_1).with(any_of(1, 3))
- # object.method_1(1)
- # # no error raised
- #
- # object = mock()
- # object.expects(:method_1).with(any_of(1, 3))
- # object.method_1(3)
- # # no error raised
- #
- # object = mock()
- # object.expects(:method_1).with(any_of(1, 3))
- # object.method_1(2)
- # # error raised, because method_1 was not called with 1 or 3
- def any_of(*matchers)
- AnyOf.new(*matchers)
- end
-
- class AnyOf # :nodoc:
-
- def initialize(*matchers)
- @matchers = matchers
- end
-
- def ==(parameter)
- @matchers.any? { |matcher| matcher == parameter }
- end
-
- def mocha_inspect
- "any_of(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })"
- end
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/parameter_matchers/anything.rb b/test/lib/mocha/parameter_matchers/anything.rb
deleted file mode 100644
index 57d0eeab4..000000000
--- a/test/lib/mocha/parameter_matchers/anything.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-module Mocha
-
- module ParameterMatchers
-
- # :call-seq: anything -> parameter_matcher
- #
- # Matches any object.
- # object = mock()
- # object.expects(:method_1).with(anything)
- # object.method_1('foo')
- # # no error raised
- def anything
- Anything.new
- end
-
- class Anything # :nodoc:
-
- def ==(parameter)
- return true
- end
-
- def mocha_inspect
- "anything"
- end
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/parameter_matchers/has_entry.rb b/test/lib/mocha/parameter_matchers/has_entry.rb
deleted file mode 100644
index 3d7cac4e6..000000000
--- a/test/lib/mocha/parameter_matchers/has_entry.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-module Mocha
-
- module ParameterMatchers
-
- # :call-seq: has_entry(key, value) -> parameter_matcher
- #
- # Matches +Hash+ containing entry with +key+ and +value+.
- # object = mock()
- # object.expects(:method_1).with(has_entry('key_1', 1))
- # object.method_1('key_1' => 1, 'key_2' => 2)
- # # no error raised
- #
- # object = mock()
- # object.expects(:method_1).with(has_entry('key_1', 1))
- # object.method_1('key_1' => 2, 'key_2' => 1)
- # # error raised, because method_1 was not called with Hash containing entry: 'key_1' => 1
- def has_entry(key, value)
- HasEntry.new(key, value)
- end
-
- class HasEntry # :nodoc:
-
- def initialize(key, value)
- @key, @value = key, value
- end
-
- def ==(parameter)
- parameter[@key] == @value
- end
-
- def mocha_inspect
- "has_entry(#{@key.mocha_inspect}, #{@value.mocha_inspect})"
- end
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/parameter_matchers/has_key.rb b/test/lib/mocha/parameter_matchers/has_key.rb
deleted file mode 100644
index 5a1fcd2e8..000000000
--- a/test/lib/mocha/parameter_matchers/has_key.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-module Mocha
-
- module ParameterMatchers
-
- # :call-seq: has_key(key) -> parameter_matcher
- #
- # Matches +Hash+ containing +key+.
- # object = mock()
- # object.expects(:method_1).with(has_key('key_1'))
- # object.method_1('key_1' => 1, 'key_2' => 2)
- # # no error raised
- #
- # object = mock()
- # object.expects(:method_1).with(has_key('key_1'))
- # object.method_1('key_2' => 2)
- # # error raised, because method_1 was not called with Hash containing key: 'key_1'
- def has_key(key)
- HasKey.new(key)
- end
-
- class HasKey # :nodoc:
-
- def initialize(key)
- @key = key
- end
-
- def ==(parameter)
- parameter.keys.include?(@key)
- end
-
- def mocha_inspect
- "has_key(#{@key.mocha_inspect})"
- end
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/parameter_matchers/has_value.rb b/test/lib/mocha/parameter_matchers/has_value.rb
deleted file mode 100644
index 742f84268..000000000
--- a/test/lib/mocha/parameter_matchers/has_value.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-module Mocha
-
- module ParameterMatchers
-
- # :call-seq: has_value(value) -> parameter_matcher
- #
- # Matches +Hash+ containing +value+.
- # object = mock()
- # object.expects(:method_1).with(has_value(1))
- # object.method_1('key_1' => 1, 'key_2' => 2)
- # # no error raised
- #
- # object = mock()
- # object.expects(:method_1).with(has_value(1))
- # object.method_1('key_2' => 2)
- # # error raised, because method_1 was not called with Hash containing value: 1
- def has_value(value)
- HasValue.new(value)
- end
-
- class HasValue # :nodoc:
-
- def initialize(value)
- @value = value
- end
-
- def ==(parameter)
- parameter.values.include?(@value)
- end
-
- def mocha_inspect
- "has_value(#{@value.mocha_inspect})"
- end
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/parameter_matchers/includes.rb b/test/lib/mocha/parameter_matchers/includes.rb
deleted file mode 100644
index 0e4fbe960..000000000
--- a/test/lib/mocha/parameter_matchers/includes.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-module Mocha
-
- module ParameterMatchers
-
- # :call-seq: includes(item) -> parameter_matcher
- #
- # Matches any object that responds true to include?(item)
- # object = mock()
- # object.expects(:method_1).with(includes('foo'))
- # object.method_1(['foo', 'bar'])
- # # no error raised
- #
- # object.method_1(['baz'])
- # # error raised, because ['baz'] does not include 'foo'.
- def includes(item)
- Includes.new(item)
- end
-
- class Includes # :nodoc:
-
- def initialize(item)
- @item = item
- end
-
- def ==(parameter)
- return parameter.include?(@item)
- end
-
- def mocha_inspect
- "includes(#{@item.mocha_inspect})"
- end
-
- end
-
- end
-
-end
diff --git a/test/lib/mocha/pretty_parameters.rb b/test/lib/mocha/pretty_parameters.rb
deleted file mode 100644
index 6d3c165f8..000000000
--- a/test/lib/mocha/pretty_parameters.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-require 'mocha/inspect'
-
-module Mocha
-
- class PrettyParameters
-
- def initialize(params)
- @params = params
- @params_string = params.mocha_inspect
- end
-
- def pretty
- remove_outer_array_braces!
- remove_outer_hash_braces!
- @params_string
- end
-
- def remove_outer_array_braces!
- @params_string = @params_string.gsub(/^\[|\]$/, '')
- end
-
- def remove_outer_hash_braces!
- @params_string = @params_string.gsub(/^\{|\}$/, '') if @params.size == 1
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/return_values.rb b/test/lib/mocha/return_values.rb
deleted file mode 100644
index ea0fbbd40..000000000
--- a/test/lib/mocha/return_values.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-require 'mocha/single_return_value'
-
-module Mocha # :nodoc:
-
- class ReturnValues # :nodoc:
-
- def self.build(*values)
- new(*values.map { |value| SingleReturnValue.new(value) })
- end
-
- attr_accessor :values
-
- def initialize(*values)
- @values = values
- end
-
- def next
- case @values.size
- when 0: nil
- when 1: @values.first.evaluate
- else @values.shift.evaluate
- end
- end
-
- def +(other)
- self.class.new(*(@values + other.values))
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/setup_and_teardown.rb b/test/lib/mocha/setup_and_teardown.rb
deleted file mode 100644
index 034ce1d6b..000000000
--- a/test/lib/mocha/setup_and_teardown.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-require 'mocha/central'
-
-module Mocha
-
- module SetupAndTeardown
-
- def setup_stubs
- $stubba = Mocha::Central.new
- end
-
- def verify_stubs
- $stubba.verify_all { yield if block_given? } if $stubba
- end
-
- def teardown_stubs
- if $stubba then
- $stubba.unstub_all
- $stubba = nil
- end
- end
-
- end
-end \ No newline at end of file
diff --git a/test/lib/mocha/single_return_value.rb b/test/lib/mocha/single_return_value.rb
deleted file mode 100644
index f420b8b8c..000000000
--- a/test/lib/mocha/single_return_value.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-require 'mocha/is_a'
-require 'mocha/deprecation'
-
-module Mocha # :nodoc:
-
- class SingleReturnValue # :nodoc:
-
- def initialize(value)
- @value = value
- end
-
- def evaluate
- if @value.__is_a__(Proc) then
- message = 'use of Expectation#returns with instance of Proc - see Expectation#returns RDoc for alternatives'
- Deprecation.warning(message)
- @value.call
- else
- @value
- end
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/single_yield.rb b/test/lib/mocha/single_yield.rb
deleted file mode 100644
index 5af571621..000000000
--- a/test/lib/mocha/single_yield.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module Mocha # :nodoc:
-
- class SingleYield # :nodoc:
-
- attr_reader :parameters
-
- def initialize(*parameters)
- @parameters = parameters
- end
-
- def each
- yield(@parameters)
- end
-
- end
-
-end
-
diff --git a/test/lib/mocha/standalone.rb b/test/lib/mocha/standalone.rb
deleted file mode 100644
index 8e3a7cefc..000000000
--- a/test/lib/mocha/standalone.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-require 'mocha/auto_verify'
-require 'mocha/parameter_matchers'
-require 'mocha/setup_and_teardown'
-
-module Mocha
-
- module Standalone
-
- include AutoVerify
- include ParameterMatchers
- include SetupAndTeardown
-
- def mocha_setup
- setup_stubs
- end
-
- def mocha_verify(&block)
- verify_mocks(&block)
- verify_stubs(&block)
- end
-
- def mocha_teardown
- begin
- teardown_mocks
- ensure
- teardown_stubs
- end
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/stub.rb b/test/lib/mocha/stub.rb
deleted file mode 100644
index 1b3cccb8a..000000000
--- a/test/lib/mocha/stub.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'mocha/expectation'
-
-module Mocha # :nodoc:
-
- class Stub < Expectation # :nodoc:
-
- def initialize(mock, method_name, backtrace = nil)
- super
- @expected_count = Range.at_least(0)
- end
-
- def verify
- true
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/test_case_adapter.rb b/test/lib/mocha/test_case_adapter.rb
deleted file mode 100644
index dc7e33b68..000000000
--- a/test/lib/mocha/test_case_adapter.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-require 'mocha/expectation_error'
-
-module Mocha
-
- module TestCaseAdapter
-
- def self.included(base)
- base.class_eval do
-
- alias_method :run_before_mocha_test_case_adapter, :run
-
- def run(result)
- yield(Test::Unit::TestCase::STARTED, name)
- @_result = result
- begin
- mocha_setup
- begin
- setup
- __send__(@method_name)
- mocha_verify { add_assertion }
- rescue Mocha::ExpectationError => e
- add_failure(e.message, e.backtrace)
- rescue Test::Unit::AssertionFailedError => e
- add_failure(e.message, e.backtrace)
- rescue StandardError, ScriptError
- add_error($!)
- ensure
- begin
- teardown
- rescue Test::Unit::AssertionFailedError => e
- add_failure(e.message, e.backtrace)
- rescue StandardError, ScriptError
- add_error($!)
- end
- end
- ensure
- mocha_teardown
- end
- result.add_run
- yield(Test::Unit::TestCase::FINISHED, name)
- end
-
- end
-
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/mocha/yield_parameters.rb b/test/lib/mocha/yield_parameters.rb
deleted file mode 100644
index b1623bf71..000000000
--- a/test/lib/mocha/yield_parameters.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-require 'mocha/no_yields'
-require 'mocha/single_yield'
-require 'mocha/multiple_yields'
-
-module Mocha # :nodoc:
-
- class YieldParameters # :nodoc:
-
- def initialize
- @parameter_groups = []
- end
-
- def next_invocation
- case @parameter_groups.size
- when 0: NoYields.new
- when 1: @parameter_groups.first
- else @parameter_groups.shift
- end
- end
-
- def add(*parameters)
- @parameter_groups << SingleYield.new(*parameters)
- end
-
- def multiple_add(*parameter_groups)
- @parameter_groups << MultipleYields.new(*parameter_groups)
- end
-
- end
-
-end \ No newline at end of file
diff --git a/test/lib/puppettest.rb b/test/lib/puppettest.rb
index 68add6dd5..40764e38c 100755
--- a/test/lib/puppettest.rb
+++ b/test/lib/puppettest.rb
@@ -6,6 +6,17 @@ mainlib = File.expand_path(File.join(File.dirname(__FILE__), '../../lib'))
$LOAD_PATH.unshift(mainlib) unless $LOAD_PATH.include?(mainlib)
require 'puppet'
+
+# include any gems in vendor/gems
+Dir["#{mainlib}/../vendor/gems/**"].each do |path|
+ libpath = File.join(path, "lib")
+ if File.directory?(libpath)
+ $LOAD_PATH.unshift(libpath)
+ else
+ $LOAD_PATH.unshift(path)
+ end
+end
+
require 'mocha'
# Only load the test/unit class if we're not in the spec directory.
@@ -25,13 +36,17 @@ class Class
def publicize_methods(*methods)
saved_private_instance_methods = methods.empty? ? self.private_instance_methods : methods
- self.class_eval { public *saved_private_instance_methods }
+ self.class_eval { public(*saved_private_instance_methods) }
yield
- self.class_eval { private *saved_private_instance_methods }
+ self.class_eval { private(*saved_private_instance_methods) }
end
end
module PuppetTest
+ # These need to be here for when rspec tests use these
+ # support methods.
+ @@tmpfiles = []
+
# Munge cli arguments, so we can enable debugging if we want
# and so we can run just specific methods.
def self.munge_argv
@@ -178,7 +193,7 @@ module PuppetTest
Dir.mkdir(@configpath)
end
- @@tmpfiles = [@configpath, tmpdir()]
+ @@tmpfiles << @configpath << tmpdir()
@@tmppids = []
@@cleaners = []
@@ -187,7 +202,7 @@ module PuppetTest
# If we're running under rake, then disable debugging and such.
#if rake? or ! Puppet[:debug]
- if defined?($puppet_debug) or ! rake?
+ #if defined?($puppet_debug) or ! rake?
if textmate?
Puppet[:color] = false
end
@@ -199,11 +214,11 @@ module PuppetTest
end
Puppet::Util::Log.level = :debug
#$VERBOSE = 1
- else
- Puppet::Util::Log.close
- Puppet::Util::Log.newdestination(@logs)
- Puppet[:httplog] = tempfile()
- end
+ #else
+ # Puppet::Util::Log.close
+ # Puppet::Util::Log.newdestination(@logs)
+ # Puppet[:httplog] = tempfile()
+ #end
Puppet[:ignoreschedules] = true
@@ -256,11 +271,7 @@ module PuppetTest
@tmpdir
end
- def teardown
- #@stop = Time.now
- #File.open("/tmp/test_times.log", ::File::WRONLY|::File::CREAT|::File::APPEND) { |f| f.puts "%0.4f %s %s" % [@stop - @start, @method_name, self.class] }
- @@cleaners.each { |cleaner| cleaner.call() }
-
+ def remove_tmp_files
@@tmpfiles.each { |file|
unless file =~ /tmp/
puts "Not deleting tmpfile %s" % file
@@ -272,12 +283,21 @@ module PuppetTest
end
}
@@tmpfiles.clear
+ end
+
+ def teardown
+ #@stop = Time.now
+ #File.open("/tmp/test_times.log", ::File::WRONLY|::File::CREAT|::File::APPEND) { |f| f.puts "%0.4f %s %s" % [@stop - @start, @method_name, self.class] }
+ @@cleaners.each { |cleaner| cleaner.call() }
+
+ remove_tmp_files
@@tmppids.each { |pid|
%x{kill -INT #{pid} 2>/dev/null}
}
@@tmppids.clear
+
Puppet::Util::Storage.clear
Puppet.clear
Puppet.settings.clear
@@ -305,7 +325,6 @@ module PuppetTest
rescue Timeout::Error
# just move on
end
- mocha_verify
end
def logstore
diff --git a/test/lib/puppettest/parsertesting.rb b/test/lib/puppettest/parsertesting.rb
index 6fd60180a..1a08ecbae 100644
--- a/test/lib/puppettest/parsertesting.rb
+++ b/test/lib/puppettest/parsertesting.rb
@@ -5,7 +5,7 @@ module PuppetTest::ParserTesting
include PuppetTest
AST = Puppet::Parser::AST
- Compile = Puppet::Parser::Compile
+ Compiler = Puppet::Parser::Compiler
# A fake class that we can use for testing evaluation.
class FakeAST
@@ -41,10 +41,10 @@ module PuppetTest::ParserTesting
)
end
- def mkcompile(parser = nil)
+ def mkcompiler(parser = nil)
parser ||= mkparser
node = mknode
- return Compile.new(node, parser)
+ return Compiler.new(node, parser)
end
def mknode(name = nil)
@@ -58,21 +58,21 @@ module PuppetTest::ParserTesting
Puppet::Parser::Interpreter.new
end
- def mkparser
- Puppet::Parser::Parser.new()
+ def mkparser(args = {})
+ Puppet::Parser::Parser.new(args)
end
def mkscope(hash = {})
hash[:parser] ||= mkparser
- compile ||= mkcompile(hash[:parser])
- compile.topscope.source = (hash[:parser].findclass("", "") || hash[:parser].newclass(""))
+ compiler ||= mkcompiler(hash[:parser])
+ compiler.topscope.source = (hash[:parser].findclass("", "") || hash[:parser].newclass(""))
- unless compile.topscope.source
+ unless compiler.topscope.source
raise "Could not find source for scope"
end
# Make the 'main' stuff
- compile.send(:evaluate_main)
- compile.topscope
+ compiler.send(:evaluate_main)
+ compiler.topscope
end
def classobj(name, hash = {})
diff --git a/test/lib/puppettest/support/resources.rb b/test/lib/puppettest/support/resources.rb
index 384f61c33..255c55569 100755
--- a/test/lib/puppettest/support/resources.rb
+++ b/test/lib/puppettest/support/resources.rb
@@ -18,7 +18,7 @@ module PuppetTest::Support::Resources
if resource.is_a?(String)
resource = tree_resource(resource)
end
- config.add_edge!(comp, resource)
+ config.add_edge(comp, resource)
config.add_resource resource unless config.resource(resource.ref)
end
return comp
diff --git a/test/network/client/client.rb b/test/network/client/client.rb
index b6b915d31..5f96cac11 100755
--- a/test/network/client/client.rb
+++ b/test/network/client/client.rb
@@ -140,35 +140,6 @@ class TestClient < Test::Unit::TestCase
}
end
- def test_classfile
- Puppet[:code] = "class yaytest {}\n class bootest {}\n include yaytest, bootest"
-
- Puppet::Node::Facts.indirection.stubs(:save)
-
- master = client = nil
- assert_nothing_raised() {
- master = Puppet::Network::Handler.master.new(
- :Local => false
- )
- }
- assert_nothing_raised() {
- client = Puppet::Network::Client.master.new(
- :Master => master
- )
- }
-
- # Fake that it's local, so it creates the class file
- client.local = false
-
- # We can't guarantee class ordering
- client.expects(:setclasses).with do |array|
- array.length == 2 and array.include?("yaytest") and array.include?("bootest")
- end
- assert_nothing_raised {
- client.getconfig
- }
- end
-
def test_client_loading
# Make sure we don't get a failure but that we also get nothing back
assert_nothing_raised do
diff --git a/test/network/client/master.rb b/test/network/client/master.rb
index 48be3cafa..682d48eb5 100755
--- a/test/network/client/master.rb
+++ b/test/network/client/master.rb
@@ -211,6 +211,16 @@ end
"Lost value to hostname")
end
+ # Make sure that setting environment by fact takes precedence to configuration
+ def test_setenvironmentwithfact
+ name = "environment"
+ value = "test_environment"
+
+ Facter.stubs(:to_hash).returns(name => value)
+
+ assert_equal(value, Puppet::Network::Client.master.facts[name])
+ end
+
# Make sure we load all facts on startup.
def test_loadfacts
dirs = [tempfile(), tempfile()]
@@ -339,6 +349,8 @@ end
File.open(source, "w") { |f| f.puts "something" }
dest = tempfile
Puppet[:noop] = true
+ node = stub 'node', :environment => "development"
+ Puppet::Node.stubs(:find).returns node
assert_nothing_raised("Could not download in noop") do
@master.download(:dest => dest, :source => source, :tag => "yay")
end
@@ -546,4 +558,33 @@ end
# Doesn't throw an exception, but definitely fails.
client.run
end
+
+ def test_classfile
+ Puppet[:code] = "class yaytest {}\n class bootest {}\n include yaytest, bootest"
+
+ Puppet::Node::Facts.indirection.stubs(:save)
+
+ master = client = nil
+ assert_nothing_raised() {
+ master = Puppet::Network::Handler.master.new(
+ :Local => false
+ )
+ }
+ assert_nothing_raised() {
+ client = Puppet::Network::Client.master.new(
+ :Master => master
+ )
+ }
+
+ # Fake that it's local, so it creates the class file
+ client.local = false
+
+ # We can't guarantee class ordering
+ client.expects(:setclasses).with do |array|
+ array.length == 2 and array.include?("yaytest") and array.include?("bootest")
+ end
+ assert_nothing_raised {
+ client.getconfig
+ }
+ end
end
diff --git a/test/network/handler/fileserver.rb b/test/network/handler/fileserver.rb
index e4b1ac3df..b3a9aef2b 100755
--- a/test/network/handler/fileserver.rb
+++ b/test/network/handler/fileserver.rb
@@ -109,13 +109,13 @@ class TestFileServer < Test::Unit::TestCase
# and verify different iterations of 'root' return the same value
list = nil
assert_nothing_raised {
- list = server.list("/test/", :ignore, true, false)
+ list = server.list("/test/", :manage, true, false)
}
assert(list =~ pattern)
assert_nothing_raised {
- list = server.list("/test", :ignore, true, false)
+ list = server.list("/test", :manage, true, false)
}
assert(list =~ pattern)
@@ -143,7 +143,7 @@ class TestFileServer < Test::Unit::TestCase
list = nil
sfile = "/test/tmpfile"
assert_nothing_raised {
- list = server.list(sfile, :ignore, true, false)
+ list = server.list(sfile, :manage, true, false)
}
output = "/\tfile"
@@ -196,7 +196,7 @@ class TestFileServer < Test::Unit::TestCase
list = nil
sfile = "/test/"
assert_nothing_raised {
- list = server.list(sfile, :ignore, true, false)
+ list = server.list(sfile, :manage, true, false)
}
# create the new file
@@ -206,7 +206,7 @@ class TestFileServer < Test::Unit::TestCase
newlist = nil
assert_nothing_raised {
- newlist = server.list(sfile, :ignore, true, false)
+ newlist = server.list(sfile, :manage, true, false)
}
# verify the list has changed
@@ -235,12 +235,12 @@ class TestFileServer < Test::Unit::TestCase
list = nil
assert_nothing_raised {
- list = server.list("/root/" + testdir, :ignore, true, false)
+ list = server.list("/root/" + testdir, :manage, true, false)
}
assert(list =~ pattern)
assert_nothing_raised {
- list = server.list("/root" + testdir, :ignore, true, false)
+ list = server.list("/root" + testdir, :manage, true, false)
}
assert(list =~ pattern)
@@ -275,7 +275,7 @@ class TestFileServer < Test::Unit::TestCase
# get our list
list = nil
assert_nothing_raised {
- list = server.list("/test/with", :ignore, false, false)
+ list = server.list("/test/with", :manage, false, false)
}
# make sure we only got one line, since we're not recursing
@@ -284,7 +284,7 @@ class TestFileServer < Test::Unit::TestCase
# 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", :ignore, num, false)
+ list = server.list("/test/with", :manage, num, false)
}
count = 0
@@ -328,13 +328,13 @@ class TestFileServer < Test::Unit::TestCase
list = nil
# and then check a few dirs
assert_nothing_raised {
- list = server.list("/localhost/with", :ignore, false, false)
+ list = server.list("/localhost/with", :manage, false, false)
}
assert(list !~ /with/)
assert_nothing_raised {
- list = server.list("/localhost/with/some/sub", :ignore, true, false)
+ list = server.list("/localhost/with/some/sub", :manage, true, false)
}
assert(list !~ /sub/)
@@ -366,7 +366,7 @@ class TestFileServer < Test::Unit::TestCase
list = nil
assert_nothing_raised {
- list = server.list("/localhost/", :ignore, 1, false)
+ list = server.list("/localhost/", :manage, 1, false)
}
assert_instance_of(String, list, "Server returned %s instead of string")
list = list.split("\n")
@@ -398,7 +398,7 @@ class TestFileServer < Test::Unit::TestCase
list = nil
sfile = "/test/"
assert_nothing_raised {
- list = server.list(sfile, :ignore, true, false)
+ list = server.list(sfile, :manage, true, false)
}
# and describe each file in the list
@@ -488,7 +488,7 @@ class TestFileServer < Test::Unit::TestCase
mounts.each { |mount, files|
mount = "/#{mount}/"
assert_nothing_raised {
- list = server.list(mount, :ignore, true, false)
+ list = server.list(mount, :manage, true, false)
}
assert_nothing_raised {
@@ -540,12 +540,12 @@ class TestFileServer < Test::Unit::TestCase
assert_raise(Puppet::AuthorizationError,
"Host %s, ip %s, allowed %s" %
[host, ip, mount]) {
- list = server.list(mount, :ignore, true, false, host, ip)
+ list = server.list(mount, :manage, true, false, host, ip)
}
when :allow:
assert_nothing_raised("Host %s, ip %s, denied %s" %
[host, ip, mount]) {
- list = server.list(mount, :ignore, true, false, host, ip)
+ list = server.list(mount, :manage, true, false, host, ip)
}
end
}
@@ -598,7 +598,7 @@ class TestFileServer < Test::Unit::TestCase
assert_raise(Puppet::Network::Handler::FileServerError,
"Invalid mount was mounted") {
- server.list(mount, :ignore)
+ server.list(mount, :manage)
}
}
@@ -650,13 +650,13 @@ class TestFileServer < Test::Unit::TestCase
list = nil
assert_nothing_raised {
- list = server.list("/thing/", :ignore, false, false,
+ list = server.list("/thing/", :manage, false, false,
"test1.domain.com", "127.0.0.1")
}
assert(list != "", "List returned nothing in rereard test")
assert_raise(Puppet::AuthorizationError, "List allowed invalid host") {
- list = server.list("/thing/", :ignore, false, false,
+ list = server.list("/thing/", :manage, false, false,
"test2.domain.com", "127.0.0.1")
}
@@ -671,12 +671,12 @@ class TestFileServer < Test::Unit::TestCase
}
assert_raise(Puppet::AuthorizationError, "List allowed invalid host") {
- list = server.list("/thing/", :ignore, false, false,
+ list = server.list("/thing/", :manage, false, false,
"test1.domain.com", "127.0.0.1")
}
assert_nothing_raised {
- list = server.list("/thing/", :ignore, false, false,
+ list = server.list("/thing/", :manage, false, false,
"test2.domain.com", "127.0.0.1")
}
@@ -731,7 +731,7 @@ class TestFileServer < Test::Unit::TestCase
# Then not
results = {}
assert_nothing_raised {
- server.describe("/mount/link", :ignore).split("\t").zip(
+ server.describe("/mount/link", :manage).split("\t").zip(
Puppet::Network::Handler.fileserver::CHECKPARAMS
).each { |v,p| results[p] = v }
}
@@ -797,28 +797,28 @@ allow *
list = nil
sfile = "/host/file.txt"
assert_nothing_raised {
- list = server.list(sfile, :ignore, true, false, client1, ip)
+ list = server.list(sfile, :manage, true, false, client1, ip)
}
assert_equal("/\tfile", list)
assert_nothing_raised {
- list = server.list(sfile, :ignore, true, false, client2, ip)
+ list = server.list(sfile, :manage, true, false, client2, ip)
}
assert_equal("", list)
sfile = "/fqdn/file.txt"
assert_nothing_raised {
- list = server.list(sfile, :ignore, true, false, client1, ip)
+ list = server.list(sfile, :manage, true, false, client1, ip)
}
assert_equal("", list)
assert_nothing_raised {
- list = server.list(sfile, :ignore, true, false, client2, ip)
+ list = server.list(sfile, :manage, true, false, client2, ip)
}
assert_equal("/\tfile", list)
# check describe
sfile = "/host/file.txt"
assert_nothing_raised {
- list = server.describe(sfile, :ignore, client1, ip).split("\t")
+ list = server.describe(sfile, :manage, client1, ip).split("\t")
}
assert_equal(5, list.size)
assert_equal("file", list[1])
@@ -826,18 +826,18 @@ allow *
assert_equal("{md5}#{md5}", list[4])
assert_nothing_raised {
- list = server.describe(sfile, :ignore, client2, ip).split("\t")
+ list = server.describe(sfile, :manage, client2, ip).split("\t")
}
assert_equal([], list)
sfile = "/fqdn/file.txt"
assert_nothing_raised {
- list = server.describe(sfile, :ignore, client1, ip).split("\t")
+ list = server.describe(sfile, :manage, client1, ip).split("\t")
}
assert_equal([], list)
assert_nothing_raised {
- list = server.describe(sfile, :ignore, client2, ip).split("\t")
+ list = server.describe(sfile, :manage, client2, ip).split("\t")
}
assert_equal(5, list.size)
assert_equal("file", list[1])
@@ -847,23 +847,23 @@ allow *
# Check retrieve
sfile = "/host/file.txt"
assert_nothing_raised {
- list = server.retrieve(sfile, :ignore, client1, ip).chomp
+ list = server.retrieve(sfile, :manage, client1, ip).chomp
}
assert_equal(contents[client1_hostdir].chomp, list)
assert_nothing_raised {
- list = server.retrieve(sfile, :ignore, client2, ip).chomp
+ list = server.retrieve(sfile, :manage, client2, ip).chomp
}
assert_equal("", list)
sfile = "/fqdn/file.txt"
assert_nothing_raised {
- list = server.retrieve(sfile, :ignore, client1, ip).chomp
+ list = server.retrieve(sfile, :manage, client1, ip).chomp
}
assert_equal("", list)
assert_nothing_raised {
- list = server.retrieve(sfile, :ignore, client2, ip).chomp
+ list = server.retrieve(sfile, :manage, client2, ip).chomp
}
assert_equal(contents[client2_fqdndir].chomp, list)
end
@@ -941,12 +941,14 @@ allow *
# Now, check that they use Facter info
Puppet.notice "The following messages are normal"
client = nil
- local = Facter["hostname"].value
- domain = Facter["domain"].value
- fqdn = [local, domain].join(".")
- {"%h" => local, # Short name
- "%H" => fqdn, # Full name
- "%d" => domain, # domain
+ Facter.stubs(:value).with(:ipaddress).returns("127.0.0.1")
+ Facter.stubs(:value).with { |v| v.to_s == "hostname" }.returns("myhost")
+ Facter.stubs(:value).with { |v| v.to_s == "domain" }.returns("mydomain.com")
+ Facter.stubs(:value).with(:domain).returns("mydomain.com")
+
+ {"%h" => "myhost", # Short name
+ "%H" => "myhost.mydomain.com", # Full name
+ "%d" => "mydomain.com", # domain
"%%" => "%", # escape
"%o" => "%o" # other
}.each do |pat, repl|
@@ -989,18 +991,18 @@ allow *
ret = nil
assert_nothing_raised do
- ret = server.list("/name", :ignore, false, false, host, ip)
+ ret = server.list("/name", :manage, false, false, host, ip)
end
assert_equal("/\tfile", ret)
assert_nothing_raised do
- ret = server.describe("/name", :ignore, host, ip)
+ ret = server.describe("/name", :manage, host, ip)
end
- assert(ret =~ /\tfile\t/, "Did not get valid a description")
+ assert(ret =~ /\tfile\t/, "Did not get valid a description (#{ret.inspect})")
assert_nothing_raised do
- ret = server.retrieve("/name", :ignore, host, ip)
+ ret = server.retrieve("/name", :manage, host, ip)
end
assert_equal(ret, File.read(file))
@@ -1046,7 +1048,7 @@ allow *
mount = "/#{mod.name}/"
list = nil
assert_nothing_raised {
- list = server.list(mount, :ignore, true, false)
+ list = server.list(mount, :manage, true, false)
}
list = list.split("\n")
if mod.name == "green"
@@ -1059,7 +1061,7 @@ allow *
end
assert_nothing_raised("Host 'allow' denied #{mount}") {
- server.list(mount, :ignore, true, false,
+ server.list(mount, :manage, true, false,
'allow.example.com', "192.168.0.1")
}
end
@@ -1102,7 +1104,7 @@ allow *
list = nil
mount = "/#{mod.name}/"
assert_nothing_raised {
- list = server.list(mount, :ignore, true, false)
+ list = server.list(mount, :manage, true, false)
}
assert_nothing_raised {
@@ -1117,11 +1119,11 @@ allow *
# now let's check that things are being correctly forbidden
assert_raise(Puppet::AuthorizationError,
"Host 'deny' allowed #{mount}") {
- server.list(mount, :ignore, true, false,
+ server.list(mount, :manage, true, false,
'deny.example.com', "192.168.1.1")
}
assert_nothing_raised("Host 'allow' denied #{mount}") {
- server.list(mount, :ignore, true, false,
+ server.list(mount, :manage, true, false,
'allow.example.com', "192.168.0.1")
}
end
diff --git a/test/network/handler/master.rb b/test/network/handler/master.rb
index 25117030e..55522237b 100755
--- a/test/network/handler/master.rb
+++ b/test/network/handler/master.rb
@@ -76,18 +76,29 @@ class TestMaster < Test::Unit::TestCase
Puppet[:node_name] = "cert"
# Make sure we get the fact data back when nothing is set
- facts = {"hostname" => "fact_hostname", "ipaddress" => "fact_ip"}
- certname = "cert_hostname"
+ facts = {
+ "hostname" => "fact_hostname",
+ "domain" => "fact_domain",
+ "fqdn" => "fact_hostname.fact_domain",
+ "ipaddress" => "fact_ip"
+ }
+ certhostname = "cert_hostname"
+ certdomain = "cert_domain"
+ certname = certhostname + "." + certdomain
certip = "cert_ip"
resname, resip = master.send(:clientname, nil, nil, facts)
assert_equal(facts["hostname"], resname, "Did not use fact hostname when no certname was present")
assert_equal(facts["ipaddress"], resip, "Did not use fact ip when no certname was present")
+ assert_equal(facts["domain"], "fact_domain", "Did not use fact domain when no certname was present")
+ assert_equal(facts["fqdn"], "fact_hostname.fact_domain", "Did not use fact fqdn when no certname was present")
# Now try it with the cert stuff present
resname, resip = master.send(:clientname, certname, certip, facts)
assert_equal(certname, resname, "Did not use cert hostname when certname was present")
assert_equal(certip, resip, "Did not use cert ip when certname was present")
+ assert_equal(facts["domain"], certdomain, "Did not use cert domain when certname was present")
+ assert_equal(facts["fqdn"], certname, "Did not use cert fqdn when certname was present")
# And reset the node_name stuff and make sure we use it.
Puppet[:node_name] = :facter
diff --git a/test/network/server/webrick.rb b/test/network/server/webrick.rb
index e44d84dda..f4e5398b8 100755
--- a/test/network/server/webrick.rb
+++ b/test/network/server/webrick.rb
@@ -95,7 +95,7 @@ class TestWebrickServer < Test::Unit::TestCase
# the client starts its connection immediately, thus throwing
# the error.
assert_raise(OpenSSL::SSL::SSLError) {
- client = Puppet::Network::Client.status.new(:Server => "localhost", :Port => @@port)
+ Puppet::Network::HttpPool.http_instance("localhost", @@port).start
}
end
diff --git a/test/other/dsl.rb b/test/other/dsl.rb
index b4dd0659b..45b51982d 100755
--- a/test/other/dsl.rb
+++ b/test/other/dsl.rb
@@ -12,7 +12,7 @@ class TestDSL < Test::Unit::TestCase
def teardown
super
- Puppet::Aspect.clear
+ Puppet::DSL::Aspect.clear
end
def test_aspect
@@ -22,7 +22,7 @@ class TestDSL < Test::Unit::TestCase
end
end
- assert_equal(a, Puppet::Aspect[:yaytest])
+ assert_equal(a, Puppet::DSL::Aspect[:yaytest])
# Now make a child aspect
b = nil
@@ -154,8 +154,7 @@ class TestDSL < Test::Unit::TestCase
resource = nil
assert_nothing_raised do
- resource = a.newresource filetype, path,
- :content => "yay", :mode => "640"
+ resource = a.newresource filetype, path, :content => "yay", :mode => "640"
end
assert_instance_of(Puppet::Parser::Resource, resource)
diff --git a/test/other/transactions.rb b/test/other/transactions.rb
index 649a3cd32..8cae3388b 100755
--- a/test/other/transactions.rb
+++ b/test/other/transactions.rb
@@ -350,12 +350,12 @@ class TestTransactions < Test::Unit::TestCase
fcomp = Puppet::Type.type(:component).create(:name => "file")
config.add_resource fcomp
config.add_resource file
- config.add_edge!(fcomp, file)
+ config.add_edge(fcomp, file)
ecomp = Puppet::Type.type(:component).create(:name => "exec")
config.add_resource ecomp
config.add_resource exec
- config.add_edge!(ecomp, exec)
+ config.add_edge(ecomp, exec)
# 'subscribe' expects an array of arrays
#component[:require] = [[file.class.name,file.name]]
@@ -826,10 +826,10 @@ class TestTransactions < Test::Unit::TestCase
c = trigger.new(:c)
nope = Puppet::Relationship.new(a, b)
yep = Puppet::Relationship.new(a, c, {:callback => :refresh})
- graph.add_edge!(nope)
+ graph.add_edge(nope)
# And a triggering one.
- graph.add_edge!(yep)
+ graph.add_edge(yep)
# Create our transaction
trans = Puppet::Transaction.new(graph)
diff --git a/test/rails/ast.rb b/test/rails/ast.rb
index e51fa6cf7..1deaec0f4 100755
--- a/test/rails/ast.rb
+++ b/test/rails/ast.rb
@@ -44,12 +44,12 @@ class TestRailsAST < PuppetTest::TestCase
# And if it is, make sure we throw an error.
if bad
assert_raise(Puppet::ParseError, "Evaluated '#{string}'") do
- str, code = query.evaluate :scope => @scope
+ str, code = query.evaluate @scope
end
next
else
assert_nothing_raised("Could not evaluate '#{string}'") do
- str, code = query.evaluate :scope => @scope
+ str, code = query.evaluate @scope
end
end
assert_nothing_raised("Could not find resource") do
diff --git a/test/rails/configuration.rb b/test/rails/configuration.rb
index 9e2ddfedd..a878d1381 100755
--- a/test/rails/configuration.rb
+++ b/test/rails/configuration.rb
@@ -24,7 +24,7 @@ class ConfigurationRailsTests < PuppetTest::TestCase
# We need to make sure finished objects are stored in the db.
def test_finish_before_store
railsinit
- compile = mkcompile
+ compile = mkcompiler
parser = compile.parser
node = parser.newnode [compile.node.name], :code => AST::ASTArray.new(:children => [
diff --git a/test/rails/railsparameter.rb b/test/rails/railsparameter.rb
index d83115b1a..7c99ac38d 100755
--- a/test/rails/railsparameter.rb
+++ b/test/rails/railsparameter.rb
@@ -25,6 +25,8 @@ class TestRailsParameter < Test::Unit::TestCase
source = parser.newclass "myclass"
host = Puppet::Rails::Host.new(:name => "myhost")
+
+ host.save
resource = host.resources.create(
:title => "/tmp/to_resource",
diff --git a/test/rails/railsresource.rb b/test/rails/railsresource.rb
index 58058472d..3df5001be 100755
--- a/test/rails/railsresource.rb
+++ b/test/rails/railsresource.rb
@@ -29,6 +29,7 @@ class TestRailsResource < Test::Unit::TestCase
def mktest_resource
# We need a host for resources
host = Puppet::Rails::Host.new(:name => "myhost")
+ host.save
# Now build a resource
resource = host.resources.create(
diff --git a/test/ral/manager/provider.rb b/test/ral/manager/provider.rb
index bb7a21485..89aa49b9e 100755
--- a/test/ral/manager/provider.rb
+++ b/test/ral/manager/provider.rb
@@ -73,11 +73,6 @@ class TestTypeProviders < Test::Unit::TestCase
confine :exists => "/no/such/file"
end
- inst = provider.new(:name => "bar")
- assert_raise(Puppet::Error, "Did not fail on unsuitable provider instance") do
- resource = @type.create :name => "bar", :provider => inst
- end
-
# And make sure the provider must be a valid provider type for this resource
pkgprov = Puppet::Type.type(:package).create(:name => "yayness").provider
assert(provider, "did not get package provider")
@@ -87,5 +82,26 @@ class TestTypeProviders < Test::Unit::TestCase
end
end
+
+ # #571 -- so we can cause a provider to become suitable within
+ # a run.
+ def test_unsuitable_providers_should_not_fail_at_initialization
+ Puppet::Type.type(:user).provider(:useradd).stubs(:suitable?).returns false
+
+ assert_nothing_raised("Unsuitable providers failed at initialization") do
+ Puppet::Type.type(:user).create :name => "luke", :ensure => :present, :provider => :useradd
+ end
+ end
+
+ # #571 -- so we can cause a provider to become suitable within
+ # a run.
+ def test_unsuitable_providers_should_fail_at_evaluation
+ Puppet::Type.type(:user).provider(:useradd).stubs(:suitable?).returns false
+
+ user = Puppet::Type.type(:user).create :name => "luke", :ensure => :present, :provider => :useradd
+ assert_raise(Puppet::Error, "Unsuitable provider did not fail at evaluation") do
+ user.evaluate
+ end
+ end
end
diff --git a/test/ral/manager/type.rb b/test/ral/manager/type.rb
index bb13a7b78..f3a116f6f 100755
--- a/test/ral/manager/type.rb
+++ b/test/ral/manager/type.rb
@@ -477,8 +477,8 @@ class TestType < Test::Unit::TestCase
assert_equal(greater, type.defaultprovider)
end
- # Make sure that we can have multiple isomorphic objects with the same name,
- # but not with non-isomorphic objects.
+ # Make sure that we can have multiple non-isomorphic objects with the same name,
+ # but not with isomorphic objects.
def test_isomorphic_names
catalog = mk_catalog
# First do execs, since they're not isomorphic.
@@ -562,22 +562,6 @@ class TestType < Test::Unit::TestCase
assert_equal("Exec[yay]", exec.ref)
end
- def test_noop_metaparam
- file = Puppet::Type.newfile :path => tempfile
- assert(!file.noop, "file incorrectly in noop")
-
- assert_nothing_raised do
- file[:noop] = true
- end
- assert(file.noop, "file should be in noop")
-
- # Now set the main one
- Puppet[:noop] = true
- assert(file.noop, "file should be in noop")
- file[:noop] = false
- assert(file.noop, "file should be in noop")
- end
-
def test_path
config = mk_catalog
@@ -592,7 +576,7 @@ class TestType < Test::Unit::TestCase
res = type.create(hash)
config.add_resource res
if parent
- config.add_edge!(parent, res)
+ config.add_edge(parent, res)
end
res
end
@@ -625,7 +609,7 @@ class TestType < Test::Unit::TestCase
newcomp = Puppet::Type.newcomponent :type => "yay", :name => "Good[bad]"
config.add_resource newcomp
- config.add_edge! comp, newcomp
+ config.add_edge comp, newcomp
exec = mk.call(6, :parent => newcomp)
assert_equal("//Good[bad]/Exec[exec6]", exec.path)
end
diff --git a/test/ral/providers/cron/crontab.rb b/test/ral/providers/cron/crontab.rb
index 2da4b1b57..53bd76c50 100755
--- a/test/ral/providers/cron/crontab.rb
+++ b/test/ral/providers/cron/crontab.rb
@@ -5,7 +5,6 @@ require File.dirname(__FILE__) + '/../../../lib/puppettest'
require 'puppettest'
require 'mocha'
require 'puppettest/fileparsing'
-require 'puppet/type/cron'
class TestCronParsedProvider < Test::Unit::TestCase
include PuppetTest
@@ -344,7 +343,9 @@ class TestCronParsedProvider < Test::Unit::TestCase
end
end
- # Make sure we can create a cron in an empty tab
+ # Make sure we can create a cron in an empty tab.
+ # LAK:FIXME This actually modifies the user's crontab,
+ # which is pretty heinous.
def test_mkcron_if_empty
setme
@provider.filetype = @oldfiletype
diff --git a/test/ral/providers/mailalias/aliases.rb b/test/ral/providers/mailalias/aliases.rb
index 663d4359c..ec8b84684 100755
--- a/test/ral/providers/mailalias/aliases.rb
+++ b/test/ral/providers/mailalias/aliases.rb
@@ -4,7 +4,6 @@ require File.dirname(__FILE__) + '/../../../lib/puppettest'
require 'puppettest'
require 'puppettest/fileparsing'
-require 'puppet/type/mailalias'
class TestMailaliasAliasesProvider < Test::Unit::TestCase
include PuppetTest
diff --git a/test/ral/providers/sshkey/parsed.rb b/test/ral/providers/sshkey/parsed.rb
index b94b7a69a..4f18e6494 100755
--- a/test/ral/providers/sshkey/parsed.rb
+++ b/test/ral/providers/sshkey/parsed.rb
@@ -4,7 +4,6 @@ require File.dirname(__FILE__) + '/../../../lib/puppettest'
require 'puppettest'
require 'puppettest/fileparsing'
-require 'puppet/type/sshkey'
class TestParsedSSHKey < Test::Unit::TestCase
include PuppetTest
diff --git a/test/ral/types/basic.rb b/test/ral/type/basic.rb
index e46d96d1c..3c5faeee0 100755
--- a/test/ral/types/basic.rb
+++ b/test/ral/type/basic.rb
@@ -36,8 +36,13 @@ class TestBasic < Test::Unit::TestCase
)
}
@config = mk_catalog(@component, @configfile, @command)
- @config.add_edge! @component, @configfile
- @config.add_edge! @component, @command
+ @config.add_edge @component, @configfile
+ @config.add_edge @component, @command
+ end
+
+ def teardown
+ super
+ stopservices
end
def test_values
@@ -63,6 +68,13 @@ class TestBasic < Test::Unit::TestCase
assert_equal("echo", @command.title)
end
+ def test_object_retrieval
+ [@command, @configfile].each { |obj|
+ assert_equal(obj.class[obj.name].object_id, obj.object_id,
+ "%s did not match class version" % obj.ref)
+ }
+ end
+
def test_paths
[@configfile, @command, @component].each { |obj|
assert_nothing_raised {
diff --git a/test/ral/types/cron.rb b/test/ral/type/cron.rb
index 8e3d25350..8e3d25350 100755
--- a/test/ral/types/cron.rb
+++ b/test/ral/type/cron.rb
diff --git a/test/ral/types/exec.rb b/test/ral/type/exec.rb
index 976e3f3ab..3444b1312 100755
--- a/test/ral/types/exec.rb
+++ b/test/ral/type/exec.rb
@@ -200,7 +200,6 @@ class TestExec < Test::Unit::TestCase
comp = mk_catalog("Testing", file, exec)
- Facter.stubs(:to_hash).returns({})
assert_events([:file_created, :executed_command], comp)
end
@@ -239,8 +238,6 @@ class TestExec < Test::Unit::TestCase
:command => "cat %s %s" % [exe, oexe],
:path => ENV["PATH"]
)
-
- catalog = mk_catalog(file, baseobj, ofile, exec, cat)
rels = nil
assert_nothing_raised do
@@ -350,6 +347,10 @@ class TestExec < Test::Unit::TestCase
if user
assert_equal(user.uid, File.stat(file).uid, "File UIDs do not match")
end
+
+ # We can't actually test group ownership, unfortunately, because
+ # behaviour changes wildlly based on platform.
+ Puppet::Type.allclear
end
def test_userngroup
@@ -389,8 +390,8 @@ class TestExec < Test::Unit::TestCase
assert_apply(exec)
assert_nothing_raised {
- exec[:command] = "echo logoutput is warning"
- exec[:logoutput] = "warning"
+ exec[:command] = "echo logoutput is on_failure"
+ exec[:logoutput] = "on_failure"
}
assert_apply(exec)
@@ -582,6 +583,46 @@ and stuff"
assert_equal("A B\n", output)
end
+ def test_environmentparam
+ exec = Puppet::Type.newexec(
+ :command => "echo $environmenttest",
+ :path => ENV["PATH"],
+ :environment => "environmenttest=yayness"
+ )
+
+ assert(exec, "Could not make exec")
+
+ output = status = nil
+ assert_nothing_raised {
+ output, status = exec.run("echo $environmenttest")
+ }
+
+ assert_equal("yayness\n", output)
+
+ # Now check whether we can do multiline settings
+ assert_nothing_raised do
+ exec[:environment] = "environmenttest=a list of things
+and stuff"
+ end
+
+ output = status = nil
+ assert_nothing_raised {
+ output, status = exec.run('echo "$environmenttest"')
+ }
+ assert_equal("a list of things\nand stuff\n", output)
+
+ # Now test arrays
+ assert_nothing_raised do
+ exec[:environment] = ["funtest=A", "yaytest=B"]
+ end
+
+ output = status = nil
+ assert_nothing_raised {
+ output, status = exec.run('echo "$funtest" "$yaytest"')
+ }
+ assert_equal("A B\n", output)
+ end
+
def test_timeout
exec = Puppet::Type.type(:exec).create(:command => "sleep 1", :path => ENV["PATH"], :timeout => "0.2")
time = Time.now
diff --git a/test/ral/types/file.rb b/test/ral/type/file.rb
index aaf007e24..fc7c39796 100755
--- a/test/ral/types/file.rb
+++ b/test/ral/type/file.rb
@@ -9,9 +9,7 @@ require 'fileutils'
class TestFile < Test::Unit::TestCase
include PuppetTest::Support::Utils
include PuppetTest::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 {
@@ -21,8 +19,6 @@ class TestFile < Test::Unit::TestCase
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
@@ -181,7 +177,7 @@ class TestFile < Test::Unit::TestCase
assert_equal(inituser, File.stat(file).uid)
obj.delete(:owner)
- obj[:links] = :ignore
+ obj[:links] = :follow
# And then test 'group'
group = nonrootgroup
@@ -189,12 +185,6 @@ class TestFile < Test::Unit::TestCase
initgroup = File.stat(file).gid
obj[:group] = group.name
- assert_events([:file_changed], obj)
- assert_equal(initgroup, File.stat(file).gid)
- assert_equal(group.gid, File.lstat(link).gid)
- File.chown(nil, initgroup, file)
- File.lchown(nil, initgroup, link)
-
obj[:links] = :follow
assert_events([:file_changed], obj)
assert_equal(group.gid, File.stat(file).gid)
@@ -407,8 +397,7 @@ class TestFile < Test::Unit::TestCase
assert(events)
- assert(! events.include?(:file_changed),
- "File incorrectly changed")
+ assert(! events.include?(:file_changed), "File incorrectly changed")
assert_events([], file)
# We have to sleep because the time resolution of the time-based
@@ -1001,66 +990,6 @@ class TestFile < Test::Unit::TestCase
"directory mode is incorrect")
end
- def test_followlinks
- File.umask(0022)
-
- basedir = tempfile()
- Dir.mkdir(basedir)
- file = File.join(basedir, "file")
- link = File.join(basedir, "link")
-
- File.open(file, "w", 0644) { |f| f.puts "yayness"; f.flush }
- File.symlink(file, link)
-
- obj = nil
- assert_nothing_raised {
- obj = Puppet.type(:file).create(
- :path => link,
- :mode => "755"
- )
- }
- obj.retrieve
-
- assert_events([], obj)
-
- # Assert that we default to not following links
- assert_equal("%o" % 0644, "%o" % (File.stat(file).mode & 007777))
-
- # Assert that we can manage the link directly, but modes still don't change
- obj[:links] = :manage
- assert_events([], obj)
-
- assert_equal("%o" % 0644, "%o" % (File.stat(file).mode & 007777))
-
- obj[:links] = :follow
- assert_events([:file_changed], obj)
-
- assert_equal("%o" % 0755, "%o" % (File.stat(file).mode & 007777))
-
- # Now verify that content and checksum don't update, either
- obj.delete(:mode)
- obj[:checksum] = "md5"
- obj[:links] = :ignore
-
- assert_events([], obj)
- File.open(file, "w") { |f| f.puts "more text" }
- assert_events([], obj)
- obj[:links] = :follow
- assert_events([], obj)
- File.open(file, "w") { |f| f.puts "even more text" }
- assert_events([:file_changed], obj)
-
- obj.delete(:checksum)
- obj[:content] = "this is some content"
- obj[:links] = :ignore
-
- assert_events([], obj)
- File.open(file, "w") { |f| f.puts "more text" }
- assert_events([], obj)
- obj[:links] = :follow
- assert_events([:file_changed], obj)
- end
-
# If both 'ensure' and 'content' are used, make sure that all of the other
# properties are handled correctly.
def test_contentwithmode
@@ -1244,6 +1173,7 @@ class TestFile < Test::Unit::TestCase
:title => "localfile",
:path => localfile,
:content => "rahtest",
+ :ensure => :file,
:backup => false
)
@@ -1256,8 +1186,8 @@ class TestFile < Test::Unit::TestCase
config.apply
assert(FileTest.exists?(dsourcefile), "File did not get copied")
- assert(FileTest.exists?(localfile), "File did not get created")
- assert(FileTest.exists?(purgee), "File got prematurely purged")
+ assert(FileTest.exists?(localfile), "Local file did not get created")
+ assert(FileTest.exists?(purgee), "Purge target got prematurely purged")
assert_nothing_raised { destobj[:purge] = true }
config.apply
@@ -1337,8 +1267,7 @@ class TestFile < Test::Unit::TestCase
File.symlink(dir, link)
File.open(file, "w") { |f| f.puts "" }
assert_equal(dir, File.readlink(link))
- obj = Puppet::Type.newfile :path => link, :ensure => :link,
- :target => file, :recurse => false, :backup => "main"
+ obj = Puppet::Type.newfile :path => link, :ensure => :link, :target => file, :recurse => false, :backup => "main"
catalog = mk_catalog(bucket, obj)
@@ -1774,5 +1703,26 @@ class TestFile < Test::Unit::TestCase
obj = Puppet::Type.newfile(:path => '/', :mode => 0755)
assert_equal("/", obj.title, "/ directory was changed to empty string")
end
-end
+ # #1010 and #1037 -- write should fail if the written checksum does not
+ # match the file we thought we were writing.
+ def test_write_validates_checksum
+ file = tempfile
+ inst = Puppet::Type.newfile(:path => file, :content => "something")
+
+ tmpfile = file + ".puppettmp"
+
+ wh = mock 'writehandle', :print => nil
+ rh = mock 'readhandle'
+ rh.expects(:read).with(512).times(2).returns("other").then.returns(nil)
+ File.expects(:open).with { |*args| args[0] == tmpfile and args[1] != "r" }.yields(wh)
+ File.expects(:open).with { |*args| args[0] == tmpfile and args[1] == "r" }.yields(rh)
+
+ File.stubs(:rename)
+ FileTest.stubs(:exist?).returns(true)
+ FileTest.stubs(:file?).returns(true)
+
+ inst.expects(:fail)
+ inst.write("something", :whatever)
+ end
+end
diff --git a/test/ral/types/file/target.rb b/test/ral/type/file/target.rb
index b6c84df99..b6c84df99 100755
--- a/test/ral/types/file/target.rb
+++ b/test/ral/type/file/target.rb
diff --git a/test/ral/types/filebucket.rb b/test/ral/type/filebucket.rb
index 28be67b0c..28be67b0c 100755
--- a/test/ral/types/filebucket.rb
+++ b/test/ral/type/filebucket.rb
diff --git a/test/ral/types/fileignoresource.rb b/test/ral/type/fileignoresource.rb
index 996bca424..996bca424 100755
--- a/test/ral/types/fileignoresource.rb
+++ b/test/ral/type/fileignoresource.rb
diff --git a/test/ral/types/filesources.rb b/test/ral/type/filesources.rb
index f21fc9b20..f21fc9b20 100755
--- a/test/ral/types/filesources.rb
+++ b/test/ral/type/filesources.rb
diff --git a/test/ral/types/group.rb b/test/ral/type/group.rb
index 3c29fe505..3c29fe505 100755
--- a/test/ral/types/group.rb
+++ b/test/ral/type/group.rb
diff --git a/test/ral/types/host.rb b/test/ral/type/host.rb
index d44fe888c..124563cbc 100755
--- a/test/ral/types/host.rb
+++ b/test/ral/type/host.rb
@@ -54,6 +54,19 @@ class TestHost < Test::Unit::TestCase
return host
end
+ def test_list
+ assert_nothing_raised do
+ @hosttype.defaultprovider.prefetch
+ end
+
+ count = 0
+ @hosttype.each do |h|
+ count += 1
+ end
+
+ assert_equal(0, count, "Found hosts in empty file somehow")
+ end
+
# Darwin will actually write to netinfo here.
if Facter.value(:operatingsystem) != "Darwin" or Process.uid == 0
def test_simplehost
@@ -125,8 +138,68 @@ class TestHost < Test::Unit::TestCase
host[:ensure] = :absent
assert_events([:host_removed], host)
end
+
+ def test_invalid_ipaddress
+ host = mkhost()
+
+ assert_raise(Puppet::Error) {
+ host[:ip] = "abc.def.ghi.jkl"
+ }
+ end
+
+ def test_invalid_hostname
+ host = mkhost()
+
+ assert_raise(Puppet::Error) {
+ host[:name] = "!invalid.hostname.$$$"
+ }
+
+ assert_raise(Puppet::Error) {
+ host[:name] = "-boo"
+ }
+
+ assert_raise(Puppet::Error) {
+ host[:name] = "boo-.ness"
+ }
+
+ assert_raise(Puppet::Error) {
+ host[:name] = "boo..ness"
+ }
+ end
+
+ def test_valid_hostname
+ host = mkhost()
+
+ assert_nothing_raised {
+ host[:name] = "yayness"
+ }
+
+ assert_nothing_raised {
+ host[:name] = "yay-ness"
+ }
+
+ assert_nothing_raised {
+ host[:name] = "yay.ness"
+ }
+
+ assert_nothing_raised {
+ host[:name] = "yay.ne-ss"
+ }
+
+ assert_nothing_raised {
+ host[:name] = "y.ay-ne-ss.com"
+ }
+
+ assert_nothing_raised {
+ host[:name] = "y4y.n3-ss"
+ }
+
+ assert_nothing_raised {
+ host[:name] = "y"
+ }
end
+ end
def test_aliasisproperty
assert_equal(:property, @hosttype.attrtype(:alias))
end
diff --git a/test/ral/types/mailalias.rb b/test/ral/type/mailalias.rb
index ff1dd562a..ff1dd562a 100755
--- a/test/ral/types/mailalias.rb
+++ b/test/ral/type/mailalias.rb
diff --git a/test/ral/types/parameter.rb b/test/ral/type/parameter.rb
index 04c4b0ce1..04c4b0ce1 100755
--- a/test/ral/types/parameter.rb
+++ b/test/ral/type/parameter.rb
diff --git a/test/ral/types/port.rb b/test/ral/type/port.rb
index e28904d55..e28904d55 100755
--- a/test/ral/types/port.rb
+++ b/test/ral/type/port.rb
diff --git a/test/ral/types/property.rb b/test/ral/type/property.rb
index 6a3370caa..6a3370caa 100755
--- a/test/ral/types/property.rb
+++ b/test/ral/type/property.rb
diff --git a/test/ral/types/resources.rb b/test/ral/type/resources.rb
index 0663fe795..0663fe795 100755
--- a/test/ral/types/resources.rb
+++ b/test/ral/type/resources.rb
diff --git a/test/ral/types/service.rb b/test/ral/type/service.rb
index 01533c63e..01533c63e 100755
--- a/test/ral/types/service.rb
+++ b/test/ral/type/service.rb
diff --git a/test/ral/types/sshkey.rb b/test/ral/type/sshkey.rb
index 333bc377d..333bc377d 100755
--- a/test/ral/types/sshkey.rb
+++ b/test/ral/type/sshkey.rb
diff --git a/test/ral/types/tidy.rb b/test/ral/type/tidy.rb
index 4e3bb53b7..a3a3b4b01 100755
--- a/test/ral/types/tidy.rb
+++ b/test/ral/type/tidy.rb
@@ -75,7 +75,7 @@ class TestTidy < Test::Unit::TestCase
# Test the different age iterations.
def test_age_conversions
- tidy = Puppet::Type.newtidy :path => tempfile(), :age => "1m"
+ tidy = Puppet::Type.type(:tidy).create :path => tempfile(), :age => "1m"
convertors = {
:second => 1,
@@ -118,7 +118,7 @@ class TestTidy < Test::Unit::TestCase
:gb => 3
}
- tidy = Puppet::Type.newtidy :path => tempfile(), :age => "1m"
+ tidy = Puppet::Type.type(:tidy).create :path => tempfile(), :age => "1m"
# First make sure we default to kb
assert_nothing_raised do
@@ -148,7 +148,7 @@ class TestTidy < Test::Unit::TestCase
end
def test_agetest
- tidy = Puppet::Type.newtidy :path => tempfile(), :age => "1m"
+ tidy = Puppet::Type.type(:tidy).create :path => tempfile(), :age => "1m"
age = tidy.property(:age)
@@ -160,7 +160,7 @@ class TestTidy < Test::Unit::TestCase
end
def test_sizetest
- tidy = Puppet::Type.newtidy :path => tempfile(), :size => "1k"
+ tidy = Puppet::Type.type(:tidy).create :path => tempfile(), :size => "1k"
size = tidy.property(:size)
@@ -174,7 +174,7 @@ class TestTidy < Test::Unit::TestCase
# Make sure we can remove different types of files
def test_tidytypes
path = tempfile()
- tidy = Puppet::Type.newtidy :path => path, :size => "1b", :age => "1s"
+ tidy = Puppet::Type.type(:tidy).create :path => path, :size => "1b", :age => "1s"
# Start with a file
File.open(path, "w") { |f| f.puts "this is a test" }
@@ -229,7 +229,7 @@ class TestTidy < Test::Unit::TestCase
Dir.mkdir(dir)
File.symlink(target, link)
- tidy = Puppet::Type.newtidy :path => dir, :size => "1b", :recurse => true
+ tidy = Puppet::Type.type(:tidy).create :path => dir, :size => "1b", :recurse => true
assert_apply(tidy)
assert(! FileTest.symlink?(link), "link was not tidied")
end
diff --git a/test/ral/types/user.rb b/test/ral/type/user.rb
index ec9b12923..ec9b12923 100755
--- a/test/ral/types/user.rb
+++ b/test/ral/type/user.rb
diff --git a/test/ral/types/yumrepo.rb b/test/ral/type/yumrepo.rb
index 65c4cb50c..899a02135 100755
--- a/test/ral/types/yumrepo.rb
+++ b/test/ral/type/yumrepo.rb
@@ -19,10 +19,6 @@ class TestYumRepo < Test::Unit::TestCase
Puppet.type(:yumrepo).yumconf = @yumconf
end
- def teardown
- Puppet.type(:yumrepo).clear
- end
-
# Modify one existing section
def test_modify
copy_datafiles
diff --git a/test/ral/types/zone.rb b/test/ral/type/zone.rb
index eb485b944..eb485b944 100755
--- a/test/ral/types/zone.rb
+++ b/test/ral/type/zone.rb
diff --git a/test/util/autoload.rb b/test/util/autoload.rb
index 6babed774..de503ab99 100755
--- a/test/util/autoload.rb
+++ b/test/util/autoload.rb
@@ -103,10 +103,10 @@ TestAutoload.newthing(:#{name.to_s})
assert(loader.send(:searchpath).include?(dir), "searchpath does not include the libdir")
end
- # This causes very strange behaviour in the tests. We need to make sure we
- # require the same path that a user would use, otherwise we'll result in
- # a reload of the
- def test_require_does_not_cause_reload
+ # This tests #1027, which was caused by using the unqualified
+ # path for requires, which was initially done so that the kernel
+ # would keep track of which files got loaded.
+ def test_require_uses_full_path
loadname = "testing"
loader = Puppet::Util::Autoload.new(self.class, loadname)
@@ -120,7 +120,26 @@ TestAutoload.newthing(:#{name.to_s})
Dir.expects(:glob).with("#{dir}/*.rb").returns(file)
- Kernel.expects(:require).with(File.join(loadname, subname))
+ Kernel.expects(:require).with(file)
loader.loadall
end
+
+ def test_searchpath_includes_plugin_dirs
+ moddir = "/what/ever"
+ libdir = "/other/dir"
+ Puppet.settings.stubs(:value).with(:modulepath).returns(moddir)
+ Puppet.settings.stubs(:value).with(:libdir).returns(libdir)
+
+ loadname = "testing"
+ loader = Puppet::Util::Autoload.new(self.class, loadname)
+
+ # Currently, include both plugins and libs.
+ paths = %w{plugins lib}.inject({}) { |hash, d| hash[d] = File.join(moddir, "testing", d); FileTest.stubs(:directory?).with(hash[d]).returns(true); hash }
+ Dir.expects(:glob).with("#{moddir}/*/{plugins,lib}").returns(paths.values)
+
+ searchpath = loader.searchpath
+ paths.each do |dir, path|
+ assert(searchpath.include?(path), "search path did not include path for %s" % dir)
+ end
+ end
end
diff --git a/test/util/settings.rb b/test/util/settings.rb
index cf5dca76d..de6fff946 100755
--- a/test/util/settings.rb
+++ b/test/util/settings.rb
@@ -256,69 +256,6 @@ yay = /a/path
end
end
- def test_old_parse
- text = %{
-one = this is a test
-two = another test
-owner = root
-group = root
-yay = /a/path
-
-[section1]
- attr = value
- owner = puppet
- group = puppet
- attrdir = /some/dir
- attr3 = $attrdir/other
- }
-
- file = tempfile()
- File.open(file, "w") { |f| f.puts text }
-
- assert_nothing_raised {
- @config.setdefaults("puppet",
- :one => ["a", "one"],
- :two => ["a", "two"],
- :yay => ["/default/path", "boo"],
- :mkusers => [true, "uh, yeah"]
- )
- }
-
- assert_nothing_raised {
- @config.setdefaults("section1",
- :attr => ["a", "one"],
- :attrdir => ["/another/dir", "two"],
- :attr3 => ["$attrdir/maybe", "boo"]
- )
- }
-
- assert_nothing_raised {
- @config.old_parse(file)
- }
-
- assert_equal("value", @config[:attr])
- assert_equal("/some/dir", @config[:attrdir])
- assert_equal(:directory, @config.element(:attrdir).type)
- assert_equal("/some/dir/other", @config[:attr3])
-
- elem = nil
- assert_nothing_raised {
- elem = @config.element(:attr3)
- }
-
- assert(elem)
- assert_equal("puppet", elem.owner)
-
- config = nil
- assert_nothing_raised {
- config = @config.to_config
- }
-
- assert_nothing_raised("Could not create transportable config") {
- @config.to_transportable
- }
- end
-
def test_parse
result = {
:main => {:main => "main", :bad => "invalid", :cliparam => "reset"},