repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/logical_ops_spec.rb | spec/unit/pops/evaluator/logical_ops_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include EvaluatorRspecHelper
context "When the evaluator performs boolean operations" do
context "using operator AND" do
it "true && true == true" do
expect(evaluate(literal(true).and(literal(true)))).to eq(true)
end
it "false && true == false" do
expect(evaluate(literal(false).and(literal(true)))).to eq(false)
end
it "true && false == false" do
expect(evaluate(literal(true).and(literal(false)))).to eq(false)
end
it "false && false == false" do
expect(evaluate(literal(false).and(literal(false)))).to eq(false)
end
end
context "using operator OR" do
it "true || true == true" do
expect(evaluate(literal(true).or(literal(true)))).to eq(true)
end
it "false || true == true" do
expect(evaluate(literal(false).or(literal(true)))).to eq(true)
end
it "true || false == true" do
expect(evaluate(literal(true).or(literal(false)))).to eq(true)
end
it "false || false == false" do
expect(evaluate(literal(false).or(literal(false)))).to eq(false)
end
end
context "using operator NOT" do
it "!false == true" do
expect(evaluate(literal(false).not())).to eq(true)
end
it "!true == false" do
expect(evaluate(literal(true).not())).to eq(false)
end
end
context "on values requiring boxing to Boolean" do
it "'x' == true" do
expect(evaluate(literal('x').not())).to eq(false)
end
it "'' == true" do
expect(evaluate(literal('').not())).to eq(false)
end
it ":undef == false" do
expect(evaluate(literal(:undef).not())).to eq(true)
end
end
context "connectives should stop when truth is obtained" do
it "true && false && error == false (and no failure)" do
expect(evaluate(literal(false).and(literal('0xwtf') + literal(1)).and(literal(true)))).to eq(false)
end
it "false || true || error == true (and no failure)" do
expect(evaluate(literal(true).or(literal('0xwtf') + literal(1)).or(literal(false)))).to eq(true)
end
it "false || false || error == error (false positive test)" do
# TODO: Change the exception type
expect {evaluate(literal(true).and(literal('0xwtf') + literal(1)).or(literal(false)))}.to raise_error(Puppet::ParseError)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/basic_expressions_spec.rb | spec/unit/pops/evaluator/basic_expressions_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include EvaluatorRspecHelper
context "When the evaluator evaluates literals" do
it 'should evaluator numbers to numbers' do
expect(evaluate(literal(1))).to eq(1)
expect(evaluate(literal(3.14))).to eq(3.14)
end
it 'should evaluate strings to string' do
expect(evaluate(literal('banana'))).to eq('banana')
end
it 'should evaluate booleans to booleans' do
expect(evaluate(literal(false))).to eq(false)
expect(evaluate(literal(true))).to eq(true)
end
it 'should evaluate names to strings' do
expect(evaluate(fqn('banana'))).to eq('banana')
end
it 'should evaluator types to types' do
array_type = Puppet::Pops::Types::PArrayType::DEFAULT
expect(evaluate(fqr('Array'))).to eq(array_type)
end
end
context "When the evaluator evaluates Lists" do
it "should create an Array when evaluating a LiteralList" do
expect(evaluate(literal([1,2,3]))).to eq([1,2,3])
end
it "[...[...[]]] should create nested arrays without trouble" do
expect(evaluate(literal([1,[2.0, 2.1, [2.2]],[3.0, 3.1]]))).to eq([1,[2.0, 2.1, [2.2]],[3.0, 3.1]])
end
it "[2 + 2] should evaluate expressions in entries" do
x = literal([literal(2) + literal(2)]);
expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x)).to eq("([] (+ 2 2))")
expect(evaluate(x)[0]).to eq(4)
end
it "[1,2,3] == [1,2,3] == true" do
expect(evaluate(literal([1,2,3]).eq(literal([1,2,3])))).to eq(true);
end
it "[1,2,3] != [2,3,4] == true" do
expect(evaluate(literal([1,2,3]).ne(literal([2,3,4])))).to eq(true);
end
it "[1, 2, 3][2] == 3" do
expect(evaluate(literal([1,2,3]))[2]).to eq(3)
end
end
context "When the evaluator evaluates Hashes" do
it "should create a Hash when evaluating a LiteralHash" do
expect(evaluate(literal({'a'=>1,'b'=>2}))).to eq({'a'=>1,'b'=>2})
end
it "{...{...{}}} should create nested hashes without trouble" do
expect(evaluate(literal({'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}))).to eq({'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}})
end
it "{'a'=> 2 + 2} should evaluate values in entries" do
expect(evaluate(literal({'a'=> literal(2) + literal(2)}))['a']).to eq(4)
end
it "{'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2} == true" do
expect(evaluate(literal({'a'=> 1, 'b'=>2}).eq(literal({'a'=> 1, 'b'=>2})))).to eq(true);
end
it "{'a'=> 1, 'b'=>2} != {'x'=> 1, 'y'=>3} == true" do
expect(evaluate(literal({'a'=> 1, 'b'=>2}).ne(literal({'x'=> 1, 'y'=>3})))).to eq(true);
end
it "{'a' => 1, 'b' => 2}['b'] == 2" do
expect(evaluate(literal({:a => 1, :b => 2}).access_at(:b))).to eq(2)
end
end
context 'When the evaluator evaluates a Block' do
it 'an empty block evaluates to nil' do
expect(evaluate(block())).to eq(nil)
end
it 'a block evaluates to its last expression' do
expect(evaluate(block(literal(1), literal(2)))).to eq(2)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/literal_evaluator_spec.rb | spec/unit/pops/evaluator/literal_evaluator_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/literal_evaluator'
describe "Puppet::Pops::Evaluator::LiteralEvaluator" do
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
let(:leval) { Puppet::Pops::Evaluator::LiteralEvaluator.new }
{ "1" => 1,
"3.14" => 3.14,
"true" => true,
"false" => false,
"'1'" => '1',
"'a'" => 'a',
'"a"' => 'a',
'a' => 'a',
'a::b' => 'a::b',
'Boolean[true]' => [true],
'Integer[1]' => [1],
'Integer[-1]' => [-1],
'Integer[-5, -1]' => [-5, -1],
'Integer[-5, 5]' => [-5, 5],
# we can't actually represent MIN_INTEGER below, because it's lexed as
# UnaryMinusExpression containing a positive LiteralInteger and the integer
# must be <= MAX_INTEGER. Therefore, the effective minimum is one greater.
"Integer[#{Puppet::Pops::MIN_INTEGER + 1}]" => [-0x7FFFFFFFFFFFFFFF],
"Integer[0, #{Puppet::Pops::MAX_INTEGER}]" => [0, 0x7FFFFFFFFFFFFFFF],
'Integer[0, default]' => [0, :default],
'Integer[Infinity]' => ['infinity'],
'Float[Infinity]' => ['infinity'],
'Array[Integer, 1]' => ['integer', 1],
'Hash[Integer, String, 1, 3]' => ['integer', 'string', 1, 3],
'Regexp[/-1/]' => [/-1/],
'Sensitive[-1]' => [-1],
'Timespan[-5, 5]' => [-5, 5],
'Timestamp["2012-10-10", 1]' => ['2012-10-10', 1],
'Undef' => 'undef',
'File' => "file",
# special values
'default' => :default,
'/.*/' => /.*/,
# collections
'[1,2,3]' => [1,2,3],
'{a=>1,b=>2}' => {'a' => 1, 'b' => 2},
}.each do |source, result|
it "evaluates '#{source}' to #{result}" do
expect(leval.literal(parser.parse_string(source))).to eq(result)
end
end
it "evaluates undef to nil" do
expect(leval.literal(parser.parse_string('undef'))).to be_nil
end
[ '',
'1+1',
'[1,2, 1+2]',
'{a=>1+1}',
'"x$y"',
'"x${y}z"',
'Integer[1-3]',
'Integer[-1-3]',
'Optional[[String]]'
].each do |source|
it "throws :not_literal for non literal expression '#{source}'" do
expect{leval.literal(parser.parse_string(source))}.to throw_symbol(:not_literal)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/evaluating_parser_spec.rb | spec/unit/pops/evaluator/evaluating_parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
require 'puppet/loaders'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
require 'puppet/parser/e4_parser_adapter'
# relative to this spec file (./) does not work as this file is loaded by rspec
#require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include PuppetSpec::Pops
include PuppetSpec::Scope
before(:each) do
Puppet[:strict_variables] = true
Puppet[:data_binding_terminus] = 'none'
# Tests needs a known configuration of node/scope/compiler since it parses and evaluates
# snippets as the compiler will evaluate them, butwithout the overhead of compiling a complete
# catalog for each tested expression.
#
@parser = Puppet::Pops::Parser::EvaluatingParser.new
@node = Puppet::Node.new('node.example.com')
@node.environment = environment
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = Puppet::Parser::Scope.new(@compiler)
@scope.source = Puppet::Resource::Type.new(:node, 'node.example.com')
@scope.parent = @compiler.topscope
Puppet.push_context(:loaders => @compiler.loaders)
end
after(:each) do
Puppet.pop_context
end
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
let(:parser) { @parser }
let(:scope) { @scope }
types = Puppet::Pops::Types::TypeFactory
context "When evaluator evaluates literals" do
{
"1" => 1,
"010" => 8,
"0x10" => 16,
"3.14" => 3.14,
"0.314e1" => 3.14,
"31.4e-1" => 3.14,
"'1'" => '1',
"'banana'" => 'banana',
'"banana"' => 'banana',
"banana" => 'banana',
"banana::split" => 'banana::split',
"false" => false,
"true" => true,
"Array" => types.array_of_any,
"/.*/" => /.*/
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
it 'should error when it encounters an unknown resource' do
expect {parser.evaluate_string(scope, '$a = SantaClause', __FILE__)}.to raise_error(/Resource type not found: SantaClause/)
end
it 'should error when it encounters an unknown resource with a parameter' do
expect {parser.evaluate_string(scope, '$b = ToothFairy[emea]', __FILE__)}.to raise_error(/Resource type not found: ToothFairy/)
end
end
context "When the evaluator evaluates Lists and Hashes" do
{
"[]" => [],
"[1,2,3]" => [1,2,3],
"[1,[2.0, 2.1, [2.2]],[3.0, 3.1]]" => [1,[2.0, 2.1, [2.2]],[3.0, 3.1]],
"[2 + 2]" => [4],
"[1,2,3] == [1,2,3]" => true,
"[1,2,3] != [2,3,4]" => true,
"[1,2,3] == [2,2,3]" => false,
"[1,2,3] != [1,2,3]" => false,
"[1,2,3][2]" => 3,
"[1,2,3] + [4,5]" => [1,2,3,4,5],
"[1,2,3, *[4,5]]" => [1,2,3,4,5],
"[1,2,3, (*[4,5])]" => [1,2,3,4,5],
"[1,2,3, ((*[4,5]))]" => [1,2,3,4,5],
"[1,2,3] + [[4,5]]" => [1,2,3,[4,5]],
"[1,2,3] + 4" => [1,2,3,4],
"[1,2,3] << [4,5]" => [1,2,3,[4,5]],
"[1,2,3] << {'a' => 1, 'b'=>2}" => [1,2,3,{'a' => 1, 'b'=>2}],
"[1,2,3] << 4" => [1,2,3,4],
"[1,2,3,4] - [2,3]" => [1,4],
"[1,2,3,4] - [2,5]" => [1,3,4],
"[1,2,3,4] - 2" => [1,3,4],
"[1,2,3,[2],4] - 2" => [1,3,[2],4],
"[1,2,3,[2,3],4] - [[2,3]]" => [1,2,3,4],
"[1,2,3,3,2,4,2,3] - [2,3]" => [1,4],
"[1,2,3,['a',1],['b',2]] - {'a' => 1, 'b'=>2}" => [1,2,3],
"[1,2,3,{'a'=>1,'b'=>2}] - [{'a' => 1, 'b'=>2}]" => [1,2,3],
"[1,2,3] + {'a' => 1, 'b'=>2}" => [1,2,3,['a',1],['b',2]],
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"[1,2,3][a]" => :error,
}.each do |source, result|
it "should parse and raise error for '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError)
end
end
{
"{}" => {},
"{'a'=>1,'b'=>2}" => {'a'=>1,'b'=>2},
"{'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}" => {'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}},
"{'a'=> 2 + 2}" => {'a'=> 4},
"{'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2}" => true,
"{'a'=> 1, 'b'=>2} != {'x'=> 1, 'b'=>2}" => true,
"{'a'=> 1, 'b'=>2} == {'a'=> 2, 'b'=>3}" => false,
"{'a'=> 1, 'b'=>2} != {'a'=> 1, 'b'=>2}" => false,
"{a => 1, b => 2}[b]" => 2,
"{2+2 => sum, b => 2}[4]" => 'sum',
"{'a'=>1, 'b'=>2} + {'c'=>3}" => {'a'=>1,'b'=>2,'c'=>3},
"{'a'=>1, 'b'=>2} + {'b'=>3}" => {'a'=>1,'b'=>3},
"{'a'=>1, 'b'=>2} + ['c', 3, 'b', 3]" => {'a'=>1,'b'=>3, 'c'=>3},
"{'a'=>1, 'b'=>2} + [['c', 3], ['b', 3]]" => {'a'=>1,'b'=>3, 'c'=>3},
"{'a'=>1, 'b'=>2} - {'b' => 3}" => {'a'=>1},
"{'a'=>1, 'b'=>2, 'c'=>3} - ['b', 'c']" => {'a'=>1},
"{'a'=>1, 'b'=>2, 'c'=>3} - 'c'" => {'a'=>1, 'b'=>2},
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"{'a' => 1, 'b'=>2} << 1" => :error,
}.each do |source, result|
it "should parse and raise error for '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError)
end
end
end
context "When the evaluator perform comparisons" do
{
"'a' == 'a'" => true,
"'a' == 'b'" => false,
"'a' != 'a'" => false,
"'a' != 'b'" => true,
"'a' < 'b' " => true,
"'a' < 'a' " => false,
"'b' < 'a' " => false,
"'a' <= 'b'" => true,
"'a' <= 'a'" => true,
"'b' <= 'a'" => false,
"'a' > 'b' " => false,
"'a' > 'a' " => false,
"'b' > 'a' " => true,
"'a' >= 'b'" => false,
"'a' >= 'a'" => true,
"'b' >= 'a'" => true,
"'a' == 'A'" => true,
"'a' != 'A'" => false,
"'a' > 'A'" => false,
"'a' >= 'A'" => true,
"'A' < 'a'" => false,
"'A' <= 'a'" => true,
"1 == 1" => true,
"1 == 2" => false,
"1 != 1" => false,
"1 != 2" => true,
"1 < 2 " => true,
"1 < 1 " => false,
"2 < 1 " => false,
"1 <= 2" => true,
"1 <= 1" => true,
"2 <= 1" => false,
"1 > 2 " => false,
"1 > 1 " => false,
"2 > 1 " => true,
"1 >= 2" => false,
"1 >= 1" => true,
"2 >= 1" => true,
"1 == 1.0 " => true,
"1 < 1.1 " => true,
"1.0 == 1 " => true,
"1.0 < 2 " => true,
"'1.0' < 'a'" => true,
"'1.0' < '' " => false,
"'1.0' < ' '" => false,
"'a' > '1.0'" => true,
"/.*/ == /.*/ " => true,
"/.*/ != /a.*/" => true,
"true == true " => true,
"false == false" => true,
"true == false" => false,
"Timestamp(1) < Timestamp(2)" => true,
"Timespan(1) < Timespan(2)" => true,
"Timestamp(1) > Timestamp(2)" => false,
"Timespan(1) > Timespan(2)" => false,
"Timestamp(1) == Timestamp(1)" => true,
"Timespan(1) == Timespan(1)" => true,
"1 < Timestamp(2)" => true,
"1 < Timespan(2)" => true,
"1 > Timestamp(2)" => false,
"1 > Timespan(2)" => false,
"1 == Timestamp(1)" => true,
"1 == Timespan(1)" => true,
"1.0 < Timestamp(2)" => true,
"1.0 < Timespan(2)" => true,
"1.0 > Timestamp(2)" => false,
"1.0 > Timespan(2)" => false,
"1.0 == Timestamp(1)" => true,
"1.0 == Timespan(1)" => true,
"Timestamp(1) < 2" => true,
"Timespan(1) < 2" => true,
"Timestamp(1) > 2" => false,
"Timespan(1) > 2" => false,
"Timestamp(1) == 1" => true,
"Timespan(1) == 1" => true,
"Timestamp(1) < 2.0" => true,
"Timespan(1) < 2.0" => true,
"Timestamp(1) > 2.0" => false,
"Timespan(1) > 2.0" => false,
"Timestamp(1) == 1.0" => true,
"Timespan(1) == 1.0" => true,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"a > 1" => /String > Integer/,
"a >= 1" => /String >= Integer/,
"a < 1" => /String < Integer/,
"a <= 1" => /String <= Integer/,
"1 > a" => /Integer > String/,
"1 >= a" => /Integer >= String/,
"1 < a" => /Integer < String/,
"1 <= a" => /Integer <= String/,
}.each do | source, error|
it "should not allow comparison of String and Number '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(error)
end
end
{
"'a' =~ /.*/" => true,
"'a' =~ '.*'" => true,
"/.*/ != /a.*/" => true,
"'a' !~ /b.*/" => true,
"'a' !~ 'b.*'" => true,
'$x = a; a =~ "$x.*"' => true,
"a =~ Pattern['a.*']" => true,
"a =~ Regexp['a.*']" => false, # String is not subtype of Regexp. PUP-957
"$x = /a.*/ a =~ $x" => true,
"$x = Pattern['a.*'] a =~ $x" => true,
"1 =~ Integer" => true,
"1 !~ Integer" => false,
"undef =~ NotUndef" => false,
"undef !~ NotUndef" => true,
"[1,2,3] =~ Array[Integer[1,10]]" => true,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"666 =~ /6/" => :error,
"[a] =~ /a/" => :error,
"{a=>1} =~ /a/" => :error,
"/a/ =~ /a/" => :error,
"Array =~ /A/" => :error,
}.each do |source, result|
it "should parse and raise error for '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError)
end
end
{
"1 in [1,2,3]" => true,
"4 in [1,2,3]" => false,
"a in {x=>1, a=>2}" => true,
"z in {x=>1, a=>2}" => false,
"ana in bananas" => true,
"xxx in bananas" => false,
"/ana/ in bananas" => true,
"/xxx/ in bananas" => false,
"FILE in profiler" => false, # FILE is a type, not a String
"'FILE' in profiler" => true,
"String[1] in bananas" => false, # Philosophically true though :-)
"ana in 'BANANAS'" => true,
"/ana/ in 'BANANAS'" => false,
"/ANA/ in 'BANANAS'" => true,
"xxx in 'BANANAS'" => false,
"[2,3] in [1,[2,3],4]" => true,
"[2,4] in [1,[2,3],4]" => false,
"[a,b] in ['A',['A','B'],'C']" => true,
"[x,y] in ['A',['A','B'],'C']" => false,
"a in {a=>1}" => true,
"x in {a=>1}" => false,
"'A' in {a=>1}" => true,
"'X' in {a=>1}" => false,
"a in {'A'=>1}" => true,
"x in {'A'=>1}" => false,
"/xxx/ in {'aaaxxxbbb'=>1}" => true,
"/yyy/ in {'aaaxxxbbb'=>1}" => false,
"15 in [1, 0xf]" => true,
"15 in [1, '0xf']" => false,
"'15' in [1, 0xf]" => false,
"15 in [1, 115]" => false,
"1 in [11, '111']" => false,
"'1' in [11, '111']" => false,
"Array[Integer] in [2, 3]" => false,
"Array[Integer] in [2, [3, 4]]" => true,
"Array[Integer] in [2, [a, 4]]" => false,
"Integer in { 2 =>'a'}" => true,
"Integer[5,10] in [1,5,3]" => true,
"Integer[5,10] in [1,2,3]" => false,
"Integer in {'a'=>'a'}" => false,
"Integer in {'a'=>1}" => false,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"if /(ana)/ in bananas {$1}" => 'ana',
"if /(xyz)/ in bananas {$1} else {$1}" => nil,
"$a = bananas =~ /(ana)/; $b = /(xyz)/ in bananas; $1" => 'ana',
"$a = xyz =~ /(xyz)/; $b = /(ana)/ in bananas; $1" => 'ana',
"if /p/ in [pineapple, bananas] {$0}" => 'p',
"if /b/ in [pineapple, bananas] {$0}" => 'b',
}.each do |source, result|
it "sets match variables for a regexp search using in such that '#{source}' produces '#{result}'" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
'Any' => ['NotUndef', 'Data', 'Scalar', 'Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern', 'Collection',
'Array', 'Hash', 'CatalogEntry', 'Resource', 'Class', 'Undef', 'File' ],
# Note, Data > Collection is false (so not included)
'Data' => ['ScalarData', 'Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern', 'Array[Data]', 'Hash[String,Data]',],
'Scalar' => ['Numeric', 'Integer', 'Float', 'Boolean', 'String', 'Pattern'],
'Numeric' => ['Integer', 'Float'],
'CatalogEntry' => ['Class', 'Resource', 'File'],
'Integer[1,10]' => ['Integer[2,3]'],
}.each do |general, specials|
specials.each do |special |
it "should compute that #{general} > #{special}" do
expect(parser.evaluate_string(scope, "#{general} > #{special}", __FILE__)).to eq(true)
end
it "should compute that #{special} < #{general}" do
expect(parser.evaluate_string(scope, "#{special} < #{general}", __FILE__)).to eq(true)
end
it "should compute that #{general} != #{special}" do
expect(parser.evaluate_string(scope, "#{special} != #{general}", __FILE__)).to eq(true)
end
end
end
{
'Integer[1,10] > Integer[2,3]' => true,
'Integer[1,10] == Integer[2,3]' => false,
'Integer[1,10] > Integer[0,5]' => false,
'Integer[1,10] > Integer[1,10]' => false,
'Integer[1,10] >= Integer[1,10]' => true,
'Integer[1,10] == Integer[1,10]' => true,
}.each do |source, result|
it "should parse and evaluate the integer range comparison expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
end
context "When the evaluator performs arithmetic" do
context "on Integers" do
{ "2+2" => 4,
"2 + 2" => 4,
"7 - 3" => 4,
"6 * 3" => 18,
"6 / 3" => 2,
"6 % 3" => 0,
"10 % 3" => 1,
"-(6/3)" => -2,
"-6/3 " => -2,
"8 >> 1" => 4,
"8 << 1" => 16,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
context "on Floats" do
{
"2.2 + 2.2" => 4.4,
"7.7 - 3.3" => 4.4,
"6.1 * 3.1" => 18.91,
"6.6 / 3.3" => 2.0,
"-(6.0/3.0)" => -2.0,
"-6.0/3.0 " => -2.0,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"3.14 << 2" => :error,
"3.14 >> 2" => :error,
"6.6 % 3.3" => 0.0,
"10.0 % 3.0" => 1.0,
}.each do |source, result|
it "should parse and raise error for '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError)
end
end
end
context "on strings requiring boxing to Numeric" do
# turn strict mode off so behavior is not stubbed out
before :each do
Puppet[:strict] = :off
end
let(:logs) { [] }
let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
let(:debugs) { logs.select { |log| log.level == :debug }.map { |log| log.message } }
{
"'2' + '2'" => 4,
"'-2' + '2'" => 0,
"'- 2' + '2'" => 0,
'"-\t 2" + "2"' => 0,
"'+2' + '2'" => 4,
"'+ 2' + '2'" => 4,
"'2.2' + '2.2'" => 4.4,
"'-2.2' + '2.2'" => 0.0,
"'0xF7' + '010'" => 0xFF,
"'0xF7' + '0x8'" => 0xFF,
"'0367' + '010'" => 0xFF,
"'012.3' + '010'" => 20.3,
"'-0x2' + '0x4'" => 2,
"'+0x2' + '0x4'" => 6,
"'-02' + '04'" => 2,
"'+02' + '04'" => 6,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"'2' + 2" => 2,
"'4' - 2" => 4,
"'2' * 2" => 2,
"'2' / 1" => 2,
"'8' >> 1" => 8,
"'4' << 1" => 4,
"'10' % 3" => 10,
}.each do |source, coerced_val|
it "should warn about numeric coercion in '#{source}' when strict = warning" do
Puppet[:strict] = :warning
expect(Puppet::Pops::Evaluator::Runtime3Support::EvaluationError).not_to receive(:new)
collect_notices(source)
expect(warnings).to include(/The string '#{coerced_val}' was automatically coerced to the numerical value #{coerced_val}/)
end
it "should not warn about numeric coercion in '#{source}' if strict = off" do
Puppet[:strict] = :off
expect(Puppet::Pops::Evaluator::Runtime3Support::EvaluationError).not_to receive(:new)
collect_notices(source)
expect(warnings).to_not include(/The string '#{coerced_val}' was automatically coerced to the numerical value #{coerced_val}/)
end
it "should error when finding numeric coercion in '#{source}' if strict = error" do
Puppet[:strict] = :error
expect {
parser.evaluate_string(scope, source, __FILE__)
}.to raise_error {|error|
expect(error.message).to match(/The string '#{coerced_val}' was automatically coerced to the numerical value #{coerced_val}/)
expect(error.backtrace.first).to match(/runtime3_support\.rb.+optionally_fail/)
}
end
end
{
"'0888' + '010'" => :error,
"'0xWTF' + '010'" => :error,
"'0x12.3' + '010'" => :error,
'"-\n 2" + "2"' => :error,
'"-\v 2" + "2"' => :error,
'"-2\n" + "2"' => :error,
'"-2\n " + "2"' => :error,
}.each do |source, result|
it "should parse and raise error for '#{source}'" do
expect { parser.evaluate_string(scope, source, __FILE__) }.to raise_error(Puppet::ParseError)
end
end
end
end
end # arithmetic
context "When the evaluator evaluates assignment" do
{
"$a = 5" => 5,
"$a = 5; $a" => 5,
"$a = 5; $b = 6; $a" => 5,
"$a = $b = 5; $a == $b" => true,
"[$a] = 1 $a" => 1,
"[$a] = [1] $a" => 1,
"[$a, $b] = [1,2] $a+$b" => 3,
"[$a, [$b, $c]] = [1,[2, 3]] $a+$b+$c" => 6,
"[$a] = {a => 1} $a" => 1,
"[$a, $b] = {a=>1,b=>2} $a+$b" => 3,
"[$a, [$b, $c]] = {a=>1,[b,c] =>{b=>2, c=>3}} $a+$b+$c" => 6,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
[
"[a,b,c] = [1,2,3]",
"[a,b,c] = {b=>2,c=>3,a=>1}",
"[$a, $b] = 1",
"[$a, $b] = [1,2,3]",
"[$a, [$b,$c]] = [1,[2]]",
"[$a, [$b,$c]] = [1,[2,3,4]]",
"[$a, $b] = {a=>1}",
"[$a, [$b, $c]] = {a=>1, b =>{b=>2, c=>3}}",
].each do |source|
it "should parse and evaluate the expression '#{source}' to error" do
expect { parser.evaluate_string(scope, source, __FILE__)}.to raise_error(Puppet::ParseError)
end
end
end
context "When the evaluator evaluates conditionals" do
{
"if true {5}" => 5,
"if false {5}" => nil,
"if false {2} else {5}" => 5,
"if false {2} elsif true {5}" => 5,
"if false {2} elsif false {5}" => nil,
"unless false {5}" => 5,
"unless true {5}" => nil,
"unless true {2} else {5}" => 5,
"unless true {} else {5}" => 5,
"$a = if true {5} $a" => 5,
"$a = if false {5} $a" => nil,
"$a = if false {2} else {5} $a" => 5,
"$a = if false {2} elsif true {5} $a" => 5,
"$a = if false {2} elsif false {5} $a" => nil,
"$a = unless false {5} $a" => 5,
"$a = unless true {5} $a" => nil,
"$a = unless true {2} else {5} $a" => 5,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"case 1 { 1 : { yes } }" => 'yes',
"case 2 { 1,2,3 : { yes} }" => 'yes',
"case 2 { 1,3 : { no } 2: { yes} }" => 'yes',
"case 2 { 1,3 : { no } 5: { no } default: { yes }}" => 'yes',
"case 2 { 1,3 : { no } 5: { no } }" => nil,
"case 'banana' { 1,3 : { no } /.*ana.*/: { yes } }" => 'yes',
"case 'banana' { /.*(ana).*/: { $1 } }" => 'ana',
"case [1] { Array : { yes } }" => 'yes',
"case [1] {
Array[String] : { no }
Array[Integer]: { yes }
}" => 'yes',
"case 1 {
Integer : { yes }
Type[Integer] : { no } }" => 'yes',
"case Integer {
Integer : { no }
Type[Integer] : { yes } }" => 'yes',
# supports unfold
"case ringo {
*[paul, john, ringo, george] : { 'beatle' } }" => 'beatle',
"case ringo {
(*[paul, john, ringo, george]) : { 'beatle' } }" => 'beatle',
"case undef {
undef : { 'yes' } }" => 'yes',
"case undef {
*undef : { 'no' }
default :{ 'yes' }}" => 'yes',
"case [green, 2, whatever] {
[/ee/, Integer[0,10], default] : { 'yes' }
default :{ 'no' }}" => 'yes',
"case [green, 2, whatever] {
default :{ 'no' }
[/ee/, Integer[0,10], default] : { 'yes' }}" => 'yes',
"case {a=>1, b=>2, whatever=>3, extra => ignored} {
{ a => Integer[0,5],
b => Integer[0,5],
whatever => default
} : { 'yes' }
default : { 'no' }}" => 'yes',
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"2 ? { 1 => no, 2 => yes}" => 'yes',
"3 ? { 1 => no, 2 => no, default => yes }" => 'yes',
"3 ? { 1 => no, default => yes, 3 => no }" => 'no',
"3 ? { 1 => no, 3 => no, default => yes }" => 'no',
"4 ? { 1 => no, default => yes, 3 => no }" => 'yes',
"4 ? { 1 => no, 3 => no, default => yes }" => 'yes',
"'banana' ? { /.*(ana).*/ => $1 }" => 'ana',
"[2] ? { Array[String] => yes, Array => yes}" => 'yes',
"ringo ? *[paul, john, ringo, george] => 'beatle'" => 'beatle',
"ringo ? (*[paul, john, ringo, george]) => 'beatle'"=> 'beatle',
"undef ? undef => 'yes'" => 'yes',
"undef ? {*undef => 'no', default => 'yes'}" => 'yes',
"[green, 2, whatever] ? {
[/ee/, Integer[0,10], default
] => 'yes',
default => 'no'}" => 'yes',
"{a=>1, b=>2, whatever=>3, extra => ignored} ?
{{ a => Integer[0,5],
b => Integer[0,5],
whatever => default
} => 'yes',
default => 'no' }" => 'yes',
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
it 'fails if a selector does not match' do
expect{parser.evaluate_string(scope, "2 ? 3 => 4")}.to raise_error(/No matching entry for selector parameter with value '2'/)
end
end
context "When evaluator evaluated unfold" do
{
"*[1,2,3]" => [1,2,3],
"*1" => [1],
"*'a'" => ['a']
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
it "should parse and evaluate the expression '*{a=>10, b=>20} to [['a',10],['b',20]]" do
result = parser.evaluate_string(scope, '*{a=>10, b=>20}', __FILE__)
expect(result).to include(['a', 10])
expect(result).to include(['b', 20])
end
it "should create an array from an Iterator" do
expect(parser.evaluate_string(scope, '[1,2,3].reverse_each', __FILE__).is_a?(Array)).to be(false)
result = parser.evaluate_string(scope, '*[1,2,3].reverse_each', __FILE__)
expect(result).to eql([3,2,1])
end
end
context "When evaluator performs [] operations" do
{
"[1,2,3][0]" => 1,
"[1,2,3][2]" => 3,
"[1,2,3][3]" => nil,
"[1,2,3][-1]" => 3,
"[1,2,3][-2]" => 2,
"[1,2,3][-4]" => nil,
"[1,2,3,4][0,2]" => [1,2],
"[1,2,3,4][1,3]" => [2,3,4],
"[1,2,3,4][-2,2]" => [3,4],
"[1,2,3,4][-3,2]" => [2,3],
"[1,2,3,4][3,5]" => [4],
"[1,2,3,4][5,2]" => [],
"[1,2,3,4][0,-1]" => [1,2,3,4],
"[1,2,3,4][0,-2]" => [1,2,3],
"[1,2,3,4][0,-4]" => [1],
"[1,2,3,4][0,-5]" => [],
"[1,2,3,4][-5,2]" => [1],
"[1,2,3,4][-5,-3]" => [1,2],
"[1,2,3,4][-6,-3]" => [1,2],
"[1,2,3,4][2,-3]" => [],
"[1,*[2,3],4]" => [1,2,3,4],
"[1,*[2,3],4][1]" => 2,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"{a=>1, b=>2, c=>3}[a]" => 1,
"{a=>1, b=>2, c=>3}[c]" => 3,
"{a=>1, b=>2, c=>3}[x]" => nil,
"{a=>1, b=>2, c=>3}[c,b]" => [3,2],
"{a=>1, b=>2, c=>3}[a,b,c]" => [1,2,3],
"{a=>{b=>{c=>'it works'}}}[a][b][c]" => 'it works',
"$a = {undef => 10} $a[free_lunch]" => nil,
"$a = {undef => 10} $a[undef]" => 10,
"$a = {undef => 10} $a[$a[free_lunch]]" => 10,
"$a = {} $a[free_lunch] == undef" => true,
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
{
"'abc'[0]" => 'a',
"'abc'[2]" => 'c',
"'abc'[-1]" => 'c',
"'abc'[-2]" => 'b',
"'abc'[-3]" => 'a',
"'abc'[-4]" => '',
"'abc'[3]" => '',
"abc[0]" => 'a',
"abc[2]" => 'c',
"abc[-1]" => 'c',
"abc[-2]" => 'b',
"abc[-3]" => 'a',
"abc[-4]" => '',
"abc[3]" => '',
"'abcd'[0,2]" => 'ab',
"'abcd'[1,3]" => 'bcd',
"'abcd'[-2,2]" => 'cd',
"'abcd'[-3,2]" => 'bc',
"'abcd'[3,5]" => 'd',
"'abcd'[5,2]" => '',
"'abcd'[0,-1]" => 'abcd',
"'abcd'[0,-2]" => 'abc',
"'abcd'[0,-4]" => 'a',
"'abcd'[0,-5]" => '',
"'abcd'[-5,2]" => 'a',
"'abcd'[-5,-3]" => 'ab',
"'abcd'[-6,-3]" => 'ab',
"'abcd'[2,-3]" => '',
}.each do |source, result|
it "should parse and evaluate the expression '#{source}' to #{result}" do
expect(parser.evaluate_string(scope, source, __FILE__)).to eq(result)
end
end
# Type operations (full set tested by tests covering type calculator)
{
"Array[Integer]" => types.array_of(types.integer),
"Array[Integer,1]" => types.array_of(types.integer, types.range(1, :default)),
"Array[Integer,1,2]" => types.array_of(types.integer, types.range(1, 2)),
"Array[Integer,Integer[1,2]]" => types.array_of(types.integer, types.range(1, 2)),
"Array[Integer,Integer[1]]" => types.array_of(types.integer, types.range(1, :default)),
"Hash[Integer,Integer]" => types.hash_of(types.integer, types.integer),
"Hash[Integer,Integer,1]" => types.hash_of(types.integer, types.integer, types.range(1, :default)),
"Hash[Integer,Integer,1,2]" => types.hash_of(types.integer, types.integer, types.range(1, 2)),
"Hash[Integer,Integer,Integer[1,2]]" => types.hash_of(types.integer, types.integer, types.range(1, 2)),
"Hash[Integer,Integer,Integer[1]]" => types.hash_of(types.integer, types.integer, types.range(1, :default)),
"Resource[File]" => types.resource('File'),
"Resource['File']" => types.resource(types.resource('File')),
"File[foo]" => types.resource('file', 'foo'),
"File[foo, bar]" => [types.resource('file', 'foo'), types.resource('file', 'bar')],
"Pattern[a, /b/, Pattern[c], Regexp[d]]" => types.pattern('a', 'b', 'c', 'd'),
"String[1,2]" => types.string(types.range(1, 2)),
"String[Integer[1,2]]" => types.string(types.range(1, 2)),
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/string_interpolation_spec.rb | spec/unit/pops/evaluator/string_interpolation_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include EvaluatorRspecHelper
context "When evaluator performs string interpolation" do
it "should interpolate a bare word as a variable name, \"${var}\"" do
a_block = block(var('a').set(literal(10)), string('value is ', text(fqn('a')), ' yo'))
expect(evaluate(a_block)).to eq('value is 10 yo')
end
it "should interpolate a variable in a text expression, \"${$var}\"" do
a_block = block(var('a').set(literal(10)), string('value is ', text(var(fqn('a'))), ' yo'))
expect(evaluate(a_block)).to eq('value is 10 yo')
end
it "should interpolate a variable, \"$var\"" do
a_block = block(var('a').set(literal(10)), string('value is ', var(fqn('a')), ' yo'))
expect(evaluate(a_block)).to eq('value is 10 yo')
end
it "should interpolate any expression in a text expression, \"${$var*2}\"" do
a_block = block(var('a').set(literal(5)), string('value is ', text(var(fqn('a')) * literal(2)) , ' yo'))
expect(evaluate(a_block)).to eq('value is 10 yo')
end
it "should interpolate any expression without a text expression, \"${$var*2}\"" do
# there is no concrete syntax for this, but the parser can generate this simpler
# equivalent form where the expression is not wrapped in a TextExpression
a_block = block(var('a').set(literal(5)), string('value is ', var(fqn('a')) * literal(2) , ' yo'))
expect(evaluate(a_block)).to eq('value is 10 yo')
end
# TODO: Add function call tests - Pending implementation of calls in the evaluator
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/evaluator_rspec_helper.rb | spec/unit/pops/evaluator/evaluator_rspec_helper.rb | require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
require File.join(File.dirname(__FILE__), '/../factory_rspec_helper')
module EvaluatorRspecHelper
include FactoryRspecHelper
# Evaluate a Factory wrapper round a model object in top scope + named scope
# Optionally pass two or three model objects (typically blocks) to be executed
# in top scope, named scope, and then top scope again. If a named_scope is used, it must
# be preceded by the name of the scope.
# The optional block is executed before the result of the last specified model object
# is evaluated. This block gets the top scope as an argument. The intent is to pass
# a block that asserts the state of the top scope after the operations.
#
def evaluate in_top_scope, scopename="x", in_named_scope = nil, in_top_scope_again = nil, &block
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
# compiler creates the top scope if one is not present
top_scope = compiler.topscope()
# top_scope = Puppet::Parser::Scope.new(compiler)
evaluator = Puppet::Pops::Evaluator::EvaluatorImpl.new
Puppet.override(:loaders => compiler.loaders) do
result = evaluator.evaluate(in_top_scope.model, top_scope)
if in_named_scope
other_scope = Puppet::Parser::Scope.new(compiler)
result = evaluator.evaluate(in_named_scope.model, other_scope)
end
if in_top_scope_again
result = evaluator.evaluate(in_top_scope_again.model, top_scope)
end
if block_given?
block.call(top_scope)
end
result
end
end
# Evaluate a Factory wrapper round a model object in top scope + local scope
# Optionally pass two or three model objects (typically blocks) to be executed
# in top scope, local scope, and then top scope again
# The optional block is executed before the result of the last specified model object
# is evaluated. This block gets the top scope as an argument. The intent is to pass
# a block that asserts the state of the top scope after the operations.
#
def evaluate_l in_top_scope, in_local_scope = nil, in_top_scope_again = nil, &block
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
# compiler creates the top scope if one is not present
top_scope = compiler.topscope()
evaluator = Puppet::Pops::Evaluator::EvaluatorImpl.new
Puppet.override(:loaders => compiler.loaders) do
result = evaluator.evaluate(in_top_scope.model, top_scope)
if in_local_scope
# This is really bad in 3.x scope
top_scope.with_guarded_scope do
top_scope.new_ephemeral(true)
result = evaluator.evaluate(in_local_scope.model, top_scope)
end
end
if in_top_scope_again
result = evaluator.evaluate(in_top_scope_again.model, top_scope)
end
if block_given?
block.call(top_scope)
end
result
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/json_strict_literal_evaluator_spec.rb | spec/unit/pops/evaluator/json_strict_literal_evaluator_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/json_strict_literal_evaluator'
describe "Puppet::Pops::Evaluator::JsonStrictLiteralEvaluator" do
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
let(:leval) { Puppet::Pops::Evaluator::JsonStrictLiteralEvaluator.new }
{ "1" => 1,
"3.14" => 3.14,
"true" => true,
"false" => false,
"'1'" => '1',
"'a'" => 'a',
'"a"' => 'a',
'a' => 'a',
'a::b' => 'a::b',
'undef' => nil,
# collections
'[1,2,3]' => [1,2,3],
'{a=>1,b=>2}' => {'a' => 1, 'b' => 2},
'[undef]' => [nil],
'{a=>undef}' => { 'a' => nil }
}.each do |source, result|
it "evaluates '#{source}' to #{result}" do
expect(leval.literal(parser.parse_string(source))).to eq(result)
end
end
[ '1+1',
'File',
'[1,2, 1+2]',
'{a=>1+1}',
'Integer[1]',
'"x$y"',
'"x${y}z"'
].each do |source|
it "throws :not_literal for non literal expression '#{source}'" do
expect{leval.literal(parser.parse_string('1+1'))}.to throw_symbol(:not_literal)
end
end
[ 'default',
'/.*/',
'{1=>100}',
'{undef => 10}',
'{default => 10}',
'{/.*/ => 10}',
'{"ok" => {1 => 100}}',
'[default]',
'[[default]]',
'[/.*/]',
'[[/.*/]]',
'[{1 => 100}]',
].each do |source|
it "throws :not_literal for values not representable as pure JSON '#{source}'" do
expect{leval.literal(parser.parse_string('1+1'))}.to throw_symbol(:not_literal)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/variables_spec.rb | spec/unit/pops/evaluator/variables_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
# This file contains basic testing of variable references and assignments
# using a top scope and a local scope.
# It does not test variables and named scopes.
#
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Impl::EvaluatorImpl' do
include EvaluatorRspecHelper
context "When the evaluator deals with variables" do
context "it should handle" do
it "simple assignment and dereference" do
expect(evaluate_l(block( var('a').set(literal(2)+literal(2)), var('a')))).to eq(4)
end
it "local scope shadows top scope" do
top_scope_block = block( var('a').set(literal(2)+literal(2)), var('a'))
local_scope_block = block( var('a').set(var('a') + literal(2)), var('a'))
expect(evaluate_l(top_scope_block, local_scope_block)).to eq(6)
end
it "shadowed in local does not affect parent scope" do
top_scope_block = block( var('a').set(literal(2)+literal(2)), var('a'))
local_scope_block = block( var('a').set(var('a') + literal(2)), var('a'))
top_scope_again = var('a')
expect(evaluate_l(top_scope_block, local_scope_block, top_scope_again)).to eq(4)
end
it "access to global names works in top scope" do
top_scope_block = block( var('a').set(literal(2)+literal(2)), var('::a'))
expect(evaluate_l(top_scope_block)).to eq(4)
end
it "access to global names works in local scope" do
top_scope_block = block( var('a').set(literal(2)+literal(2)))
local_scope_block = block( var('a').set(literal(100)), var('b').set(var('::a')+literal(2)), var('b'))
expect(evaluate_l(top_scope_block, local_scope_block)).to eq(6)
end
it "can not change a variable value in same scope" do
expect { evaluate_l(block(var('a').set(literal(10)), var('a').set(literal(20)))) }.to raise_error(/Cannot reassign variable '\$a'/)
end
context "access to numeric variables" do
it "without a match" do
expect(evaluate_l(block(literal(2) + literal(2),
[var(0), var(1), var(2), var(3)]))).to eq([nil, nil, nil, nil])
end
it "after a match" do
expect(evaluate_l(block(literal('abc') =~ literal(/(a)(b)(c)/),
[var(0), var(1), var(2), var(3)]))).to eq(['abc', 'a', 'b', 'c'])
end
it "after a failed match" do
expect(evaluate_l(block(literal('abc') =~ literal(/(x)(y)(z)/),
[var(0), var(1), var(2), var(3)]))).to eq([nil, nil, nil, nil])
end
it "a failed match does not alter previous match" do
expect(evaluate_l(block(
literal('abc') =~ literal(/(a)(b)(c)/),
literal('abc') =~ literal(/(x)(y)(z)/),
[var(0), var(1), var(2), var(3)]))).to eq(['abc', 'a', 'b', 'c'])
end
it "a new match completely shadows previous match" do
expect(evaluate_l(block(
literal('abc') =~ literal(/(a)(b)(c)/),
literal('abc') =~ literal(/(a)bc/),
[var(0), var(1), var(2), var(3)]))).to eq(['abc', 'a', nil, nil])
end
it "after a match with variable referencing a non existing group" do
expect(evaluate_l(block(literal('abc') =~ literal(/(a)(b)(c)/),
[var(0), var(1), var(2), var(3), var(4)]))).to eq(['abc', 'a', 'b', 'c', nil])
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/deferred_resolver_spec.rb | spec/unit/pops/evaluator/deferred_resolver_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
Puppet::Type.newtype(:test_deferred) do
newparam(:name)
newproperty(:value)
end
describe Puppet::Pops::Evaluator::DeferredResolver do
include PuppetSpec::Compiler
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
let(:facts) { Puppet::Node::Facts.new('node.example.com') }
def compile_and_resolve_catalog(code, preprocess = false)
catalog = compile_to_catalog(code)
described_class.resolve_and_replace(facts, catalog, environment, preprocess)
catalog
end
it 'resolves deferred values in a catalog' do
catalog = compile_and_resolve_catalog(<<~END, true)
notify { "deferred":
message => Deferred("join", [[1,2,3], ":"])
}
END
expect(catalog.resource(:notify, 'deferred')[:message]).to eq('1:2:3')
end
it 'lazily resolves deferred values in a catalog' do
catalog = compile_and_resolve_catalog(<<~END)
notify { "deferred":
message => Deferred("join", [[1,2,3], ":"])
}
END
deferred = catalog.resource(:notify, 'deferred')[:message]
expect(deferred.resolve).to eq('1:2:3')
end
it 'lazily resolves nested deferred values in a catalog' do
catalog = compile_and_resolve_catalog(<<~END)
$args = Deferred("inline_epp", ["<%= 'a,b,c' %>"])
notify { "deferred":
message => Deferred("split", [$args, ","])
}
END
deferred = catalog.resource(:notify, 'deferred')[:message]
expect(deferred.resolve).to eq(["a", "b", "c"])
end
it 'marks the parameter as sensitive when passed an array containing a Sensitive instance' do
catalog = compile_and_resolve_catalog(<<~END)
test_deferred { "deferred":
value => Deferred('join', [['a', Sensitive('b')], ':'])
}
END
resource = catalog.resource(:test_deferred, 'deferred')
expect(resource.sensitive_parameters).to eq([:value])
end
it 'marks the parameter as sensitive when passed a hash containing a Sensitive key' do
catalog = compile_and_resolve_catalog(<<~END)
test_deferred { "deferred":
value => Deferred('keys', [{Sensitive('key') => 'value'}])
}
END
resource = catalog.resource(:test_deferred, 'deferred')
expect(resource.sensitive_parameters).to eq([:value])
end
it 'marks the parameter as sensitive when passed a hash containing a Sensitive value' do
catalog = compile_and_resolve_catalog(<<~END)
test_deferred { "deferred":
value => Deferred('values', [{key => Sensitive('value')}])
}
END
resource = catalog.resource(:test_deferred, 'deferred')
expect(resource.sensitive_parameters).to eq([:value])
end
it 'marks the parameter as sensitive when passed a nested Deferred containing a Sensitive type' do
catalog = compile_and_resolve_catalog(<<~END)
$vars = {'token' => Deferred('new', [Sensitive, "hello"])}
test_deferred { "deferred":
value => Deferred('inline_epp', ['<%= $token %>', $vars])
}
END
resource = catalog.resource(:test_deferred, 'deferred')
expect(resource.sensitive_parameters).to eq([:value])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/conditionals_spec.rb | spec/unit/pops/evaluator/conditionals_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
# This file contains testing of Conditionals, if, case, unless, selector
#
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include EvaluatorRspecHelper
context "When the evaluator evaluates" do
context "an if expression" do
it 'should output the expected result when dumped' do
expect(dump(IF(literal(true), literal(2), literal(5)))).to eq unindent(<<-TEXT
(if true
(then 2)
(else 5))
TEXT
)
end
it 'if true {5} == 5' do
expect(evaluate(IF(literal(true), literal(5)))).to eq(5)
end
it 'if false {5} == nil' do
expect(evaluate(IF(literal(false), literal(5)))).to eq(nil)
end
it 'if false {2} else {5} == 5' do
expect(evaluate(IF(literal(false), literal(2), literal(5)))).to eq(5)
end
it 'if false {2} elsif true {5} == 5' do
expect(evaluate(IF(literal(false), literal(2), IF(literal(true), literal(5))))).to eq(5)
end
it 'if false {2} elsif false {5} == nil' do
expect(evaluate(IF(literal(false), literal(2), IF(literal(false), literal(5))))).to eq(nil)
end
end
context "an unless expression" do
it 'should output the expected result when dumped' do
expect(dump(UNLESS(literal(true), literal(2), literal(5)))).to eq unindent(<<-TEXT
(unless true
(then 2)
(else 5))
TEXT
)
end
it 'unless false {5} == 5' do
expect(evaluate(UNLESS(literal(false), literal(5)))).to eq(5)
end
it 'unless true {5} == nil' do
expect(evaluate(UNLESS(literal(true), literal(5)))).to eq(nil)
end
it 'unless true {2} else {5} == 5' do
expect(evaluate(UNLESS(literal(true), literal(2), literal(5)))).to eq(5)
end
it 'unless true {2} elsif true {5} == 5' do
# not supported by concrete syntax
expect(evaluate(UNLESS(literal(true), literal(2), IF(literal(true), literal(5))))).to eq(5)
end
it 'unless true {2} elsif false {5} == nil' do
# not supported by concrete syntax
expect(evaluate(UNLESS(literal(true), literal(2), IF(literal(false), literal(5))))).to eq(nil)
end
end
context "a case expression" do
it 'should output the expected result when dumped' do
expect(dump(CASE(literal(2),
WHEN(literal(1), literal('wat')),
WHEN([literal(2), literal(3)], literal('w00t'))
))).to eq unindent(<<-TEXT
(case 2
(when (1) (then 'wat'))
(when (2 3) (then 'w00t')))
TEXT
)
expect(dump(CASE(literal(2),
WHEN(literal(1), literal('wat')),
WHEN([literal(2), literal(3)], literal('w00t'))
).default(literal(4)))).to eq unindent(<<-TEXT
(case 2
(when (1) (then 'wat'))
(when (2 3) (then 'w00t'))
(when (:default) (then 4)))
TEXT
)
end
it "case 1 { 1 : { 'w00t'} } == 'w00t'" do
expect(evaluate(CASE(literal(1), WHEN(literal(1), literal('w00t'))))).to eq('w00t')
end
it "case 2 { 1,2,3 : { 'w00t'} } == 'w00t'" do
expect(evaluate(CASE(literal(2), WHEN([literal(1), literal(2), literal(3)], literal('w00t'))))).to eq('w00t')
end
it "case 2 { 1,3 : {'wat'} 2: { 'w00t'} } == 'w00t'" do
expect(evaluate(CASE(literal(2),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(2), literal('w00t'))))).to eq('w00t')
end
it "case 2 { 1,3 : {'wat'} 5: { 'wat'} default: {'w00t'}} == 'w00t'" do
expect(evaluate(CASE(literal(2),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(5), literal('wat'))).default(literal('w00t'))
)).to eq('w00t')
end
it "case 2 { 1,3 : {'wat'} 5: { 'wat'} } == nil" do
expect(evaluate(CASE(literal(2),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(5), literal('wat')))
)).to eq(nil)
end
it "case 'banana' { 1,3 : {'wat'} /.*ana.*/: { 'w00t'} } == w00t" do
expect(evaluate(CASE(literal('banana'),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(/.*ana.*/), literal('w00t')))
)).to eq('w00t')
end
context "with regular expressions" do
it "should set numeric variables from the match" do
expect(evaluate(CASE(literal('banana'),
WHEN([literal(1), literal(3)], literal('wat')),
WHEN(literal(/.*(ana).*/), var(1)))
)).to eq('ana')
end
end
end
context "select expressions" do
it 'should output the expected result when dumped' do
expect(dump(literal(2).select(
MAP(literal(1), literal('wat')),
MAP(literal(2), literal('w00t'))
))).to eq("(? 2 (1 => 'wat') (2 => 'w00t'))")
end
it "1 ? {1 => 'w00t'} == 'w00t'" do
expect(evaluate(literal(1).select(MAP(literal(1), literal('w00t'))))).to eq('w00t')
end
it "2 ? {1 => 'wat', 2 => 'w00t'} == 'w00t'" do
expect(evaluate(literal(2).select(
MAP(literal(1), literal('wat')),
MAP(literal(2), literal('w00t'))
))).to eq('w00t')
end
it "3 ? {1 => 'wat', 2 => 'wat', default => 'w00t'} == 'w00t'" do
expect(evaluate(literal(3).select(
MAP(literal(1), literal('wat')),
MAP(literal(2), literal('wat')),
MAP(literal(:default), literal('w00t'))
))).to eq('w00t')
end
it "3 ? {1 => 'wat', default => 'w00t', 2 => 'wat'} == 'w00t'" do
expect(evaluate(literal(3).select(
MAP(literal(1), literal('wat')),
MAP(literal(:default), literal('w00t')),
MAP(literal(2), literal('wat'))
))).to eq('w00t')
end
it "should set numerical variables from match" do
expect(evaluate(literal('banana').select(
MAP(literal(1), literal('wat')),
MAP(literal(/.*(ana).*/), var(1))
))).to eq('ana')
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/collections_ops_spec.rb | spec/unit/pops/evaluator/collections_ops_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
require 'puppet/pops/types/type_factory'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl/Concat/Delete' do
include EvaluatorRspecHelper
context 'The evaluator when operating on an Array' do
it 'concatenates another array using +' do
expect(evaluate(literal([1,2,3]) + literal([4,5]))).to eql([1,2,3,4,5])
end
it 'concatenates another nested array using +' do
expect(evaluate(literal([1,2,3]) + literal([[4,5]]))).to eql([1,2,3,[4,5]])
end
it 'concatenates a hash by converting it to array' do
expect(evaluate(literal([1,2,3]) + literal({'a' => 1, 'b'=>2}))).to eql([1,2,3,['a',1],['b',2]])
end
it 'concatenates a non array value with +' do
expect(evaluate(literal([1,2,3]) + literal(4))).to eql([1,2,3,4])
end
it 'appends another array using <<' do
expect(evaluate(literal([1,2,3]) << literal([4,5]))).to eql([1,2,3,[4,5]])
end
it 'appends a hash without conversion when << operator is used' do
expect(evaluate(literal([1,2,3]) << literal({'a' => 1, 'b'=>2}))).to eql([1,2,3,{'a' => 1, 'b'=>2}])
end
it 'appends another non array using <<' do
expect(evaluate(literal([1,2,3]) << literal(4))).to eql([1,2,3,4])
end
it 'computes the difference with another array using -' do
expect(evaluate(literal([1,2,3,4]) - literal([2,3]))).to eql([1,4])
end
it 'computes the difference with a non array using -' do
expect(evaluate(literal([1,2,3,4]) - literal(2))).to eql([1,3,4])
end
it 'does not recurse into nested arrays when computing diff' do
expect(evaluate(literal([1,2,3,[2],4]) - literal(2))).to eql([1,3,[2],4])
end
it 'can compute diff with sub arrays' do
expect(evaluate(literal([1,2,3,[2,3],4]) - literal([[2,3]]))).to eql([1,2,3,4])
end
it 'computes difference by removing all matching instances' do
expect(evaluate(literal([1,2,3,3,2,4,2,3]) - literal([2,3]))).to eql([1,4])
end
it 'computes difference with a hash by converting it to an array' do
expect(evaluate(literal([1,2,3,['a',1],['b',2]]) - literal({'a' => 1, 'b'=>2}))).to eql([1,2,3])
end
it 'diffs hashes when given in an array' do
expect(evaluate(literal([1,2,3,{'a'=>1,'b'=>2}]) - literal([{'a' => 1, 'b'=>2}]))).to eql([1,2,3])
end
it 'raises and error when LHS of << is a hash' do
expect {
evaluate(literal({'a' => 1, 'b'=>2}) << literal(1))
}.to raise_error(/Operator '<<' is not applicable to a Hash/)
end
end
context 'The evaluator when operating on a Hash' do
it 'merges with another Hash using +' do
expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal({'c' => 3}))).to eql({'a' => 1, 'b'=>2, 'c' => 3})
end
it 'merges RHS on top of LHS ' do
expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal({'c' => 3, 'b'=>3}))).to eql({'a' => 1, 'b'=>3, 'c' => 3})
end
it 'merges a flat array of pairs converted to a hash' do
expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal(['c', 3, 'b', 3]))).to eql({'a' => 1, 'b'=>3, 'c' => 3})
end
it 'merges an array converted to a hash' do
expect(evaluate(literal({'a' => 1, 'b'=>2}) + literal([['c', 3], ['b', 3]]))).to eql({'a' => 1, 'b'=>3, 'c' => 3})
end
it 'computes difference with another hash using the - operator' do
expect(evaluate(literal({'a' => 1, 'b'=>2}) - literal({'b' => 3}))).to eql({'a' => 1 })
end
it 'computes difference with an array by treating array as array of keys' do
expect(evaluate(literal({'a' => 1, 'b'=>2,'c'=>3}) - literal(['b', 'c']))).to eql({'a' => 1 })
end
it 'computes difference with a non array/hash by treating it as a key' do
expect(evaluate(literal({'a' => 1, 'b'=>2,'c'=>3}) - literal('c'))).to eql({'a' => 1, 'b' => 2 })
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/runtime3_converter_spec.rb | spec/unit/pops/evaluator/runtime3_converter_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/types/type_factory'
describe 'when converting to 3.x' do
let(:converter) { Puppet::Pops::Evaluator::Runtime3Converter.instance }
it "converts a resource type starting with Class without confusing it with exact match on 'class'" do
t = Puppet::Pops::Types::TypeFactory.resource('classroom', 'kermit')
converted = converter.catalog_type_to_split_type_title(t)
expect(converted).to eql(['classroom', 'kermit'])
end
it "converts a resource type of exactly 'Class'" do
t = Puppet::Pops::Types::TypeFactory.resource('class', 'kermit')
converted = converter.catalog_type_to_split_type_title(t)
expect(converted).to eql(['class', 'kermit'])
end
it "errors on attempts to convert an 'Iterator'" do
expect {
converter.convert(Puppet::Pops::Types::Iterable.on((1..3)), {}, nil)
}.to raise_error(Puppet::Error, /Use of an Iterator is not supported here/)
end
it 'does not convert a SemVer instance to string' do
v = SemanticPuppet::Version.parse('1.0.0')
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'converts top level symbol :undef to the given undef value' do
expect(converter.convert(:undef, {}, 'undef value')).to eql('undef value')
end
it 'converts top level nil value to the given undef value' do
expect(converter.convert(nil, {}, 'undef value')).to eql('undef value')
end
it 'converts nested :undef in a hash to nil' do
expect(converter.convert({'foo' => :undef}, {}, 'undef value')).to eql({'foo' => nil})
end
it 'converts nested :undef in an array to nil' do
expect(converter.convert(['boo', :undef], {}, 'undef value')).to eql(['boo', nil])
end
it 'converts deeply nested :undef in to nil' do
expect(converter.convert({'foo' => [[:undef]], 'bar' => { 'x' => :undef }}, {}, 'undef value')).to eql({'foo' => [[nil]], 'bar' => { 'x' => nil}})
end
it 'does not converts nil to given undef value when nested in an array' do
expect(converter.convert({'foo' => nil}, {}, 'undef value')).to eql({'foo' => nil})
end
it 'does not convert top level symbols' do
expect(converter.convert(:default, {}, 'undef value')).to eql(:default)
expect(converter.convert(:whatever, {}, 'undef value')).to eql(:whatever)
end
it 'does not convert nested symbols' do
expect(converter.convert([:default], {}, 'undef value')).to eql([:default])
expect(converter.convert([:whatever], {}, 'undef value')).to eql([:whatever])
end
it 'does not convert a Regex instance to string' do
v = /^[A-Z]$/
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'does not convert a Version instance to string' do
v = SemanticPuppet::Version.parse('1.0.0')
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'does not convert a VersionRange instance to string' do
v = SemanticPuppet::VersionRange.parse('>=1.0.0')
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'does not convert a Timespan instance to string' do
v = Puppet::Pops::Time::Timespan.new(1234)
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'does not convert a Timestamp instance to string' do
v = Puppet::Pops::Time::Timestamp.now
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'does not convert a Sensitive instance to string' do
v = Puppet::Pops::Types::PSensitiveType::Sensitive.new("don't reveal this")
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'does not convert a Binary instance to string' do
v = Puppet::Pops::Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
expect(converter.convert(v, {}, nil)).to equal(v)
end
context 'the Runtime3FunctionArgumentConverter' do
let(:converter) { Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.instance }
it 'converts a Regex instance to string' do
c = converter.convert(/^[A-Z]$/, {}, nil)
expect(c).to be_a(String)
expect(c).to eql('/^[A-Z]$/')
end
it 'converts a Version instance to string' do
c = converter.convert(SemanticPuppet::Version.parse('1.0.0'), {}, nil)
expect(c).to be_a(String)
expect(c).to eql('1.0.0')
end
it 'converts a VersionRange instance to string' do
c = converter.convert(SemanticPuppet::VersionRange.parse('>=1.0.0'), {}, nil)
expect(c).to be_a(String)
expect(c).to eql('>=1.0.0')
end
it 'converts a Timespan instance to string' do
c = converter.convert(Puppet::Pops::Time::Timespan.new(1234), {}, nil)
expect(c).to be_a(String)
expect(c).to eql('0-00:00:00.1234')
end
it 'converts a Timestamp instance to string' do
c = converter.convert(Puppet::Pops::Time::Timestamp.parse('2016-09-15T12:24:47.193 UTC'), {}, nil)
expect(c).to be_a(String)
expect(c).to eql('2016-09-15T12:24:47.193000000 UTC')
end
it 'converts a Binary instance to string' do
b64 = 'w5ZzdGVuIG1lZCByw7ZzdGVuCg=='
c = converter.convert(Puppet::Pops::Types::PBinaryType::Binary.from_base64(b64), {}, nil)
expect(c).to be_a(String)
expect(c).to eql(b64)
end
it 'does not convert a Sensitive instance to string' do
v = Puppet::Pops::Types::PSensitiveType::Sensitive.new("don't reveal this")
expect(converter.convert(v, {}, nil)).to equal(v)
end
it 'errors if an Integer is too big' do
too_big = 0x7fffffffffffffff + 1
expect do
converter.convert(too_big, {}, nil)
end.to raise_error(/Use of a Ruby Integer outside of Puppet Integer max range, got/)
end
it 'errors if an Integer is too small' do
too_small = -0x8000000000000000-1
expect do
converter.convert(too_small, {}, nil)
end.to raise_error(/Use of a Ruby Integer outside of Puppet Integer min range, got/)
end
it 'errors if a BigDecimal is out of range for Float' do
big_dec = BigDecimal("123456789123456789.1415")
expect do
converter.convert(big_dec, {}, nil)
end.to raise_error(/Use of a Ruby BigDecimal value outside Puppet Float range, got/)
end
it 'BigDecimal values in Float range are converted' do
big_dec = BigDecimal("3.1415")
f = converter.convert(big_dec, {}, nil)
expect(f.class).to be(Float)
end
it 'errors when Integer is out of range in a structure' do
structure = {'key' => [{ 'key' => [0x7fffffffffffffff + 1]}]}
expect do
converter.convert(structure, {}, nil)
end.to raise_error(/Use of a Ruby Integer outside of Puppet Integer max range, got/)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/arithmetic_ops_spec.rb | spec/unit/pops/evaluator/arithmetic_ops_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include EvaluatorRspecHelper
context "When the evaluator performs arithmetic" do
context "on Integers" do
it "2 + 2 == 4" do; expect(evaluate(literal(2) + literal(2))).to eq(4) ; end
it "7 - 3 == 4" do; expect(evaluate(literal(7) - literal(3))).to eq(4) ; end
it "6 * 3 == 18" do; expect(evaluate(literal(6) * literal(3))).to eq(18); end
it "6 / 3 == 2" do; expect(evaluate(literal(6) / literal(3))).to eq(2) ; end
it "6 % 3 == 0" do; expect(evaluate(literal(6) % literal(3))).to eq(0) ; end
it "10 % 3 == 1" do; expect(evaluate(literal(10) % literal(3))).to eq(1); end
it "-(6/3) == -2" do; expect(evaluate(minus(literal(6) / literal(3)))).to eq(-2) ; end
it "-6/3 == -2" do; expect(evaluate(minus(literal(6)) / literal(3))).to eq(-2) ; end
it "8 >> 1 == 4" do; expect(evaluate(literal(8) >> literal(1))).to eq(4) ; end
it "8 << 1 == 16" do; expect(evaluate(literal(8) << literal(1))).to eq(16); end
it "8 >> -1 == 16" do; expect(evaluate(literal(8) >> literal(-1))).to eq(16) ; end
it "8 << -1 == 4" do; expect(evaluate(literal(8) << literal(-1))).to eq(4); end
end
# 64 bit signed integer max and min
MAX_INTEGER = 0x7fffffffffffffff
MIN_INTEGER = -0x8000000000000000
context "on integer values that cause 64 bit overflow" do
it "MAX + 1 => error" do
expect{
evaluate(literal(MAX_INTEGER) + literal(1))
}.to raise_error(/resulted in a value outside of Puppet Integer max range/)
end
it "MAX - -1 => error" do
expect{
evaluate(literal(MAX_INTEGER) - literal(-1))
}.to raise_error(/resulted in a value outside of Puppet Integer max range/)
end
it "MAX * 2 => error" do
expect{
evaluate(literal(MAX_INTEGER) * literal(2))
}.to raise_error(/resulted in a value outside of Puppet Integer max range/)
end
it "(MAX+1)*2 / 2 => error" do
expect{
evaluate(literal((MAX_INTEGER+1)*2) / literal(2))
}.to raise_error(/resulted in a value outside of Puppet Integer max range/)
end
it "MAX << 1 => error" do
expect{
evaluate(literal(MAX_INTEGER) << literal(1))
}.to raise_error(/resulted in a value outside of Puppet Integer max range/)
end
it "((MAX+1)*2) << 1 => error" do
expect{
evaluate(literal((MAX_INTEGER+1)*2) >> literal(1))
}.to raise_error(/resulted in a value outside of Puppet Integer max range/)
end
it "MIN - 1 => error" do
expect{
evaluate(literal(MIN_INTEGER) - literal(1))
}.to raise_error(/resulted in a value outside of Puppet Integer min range/)
end
it "does not error on the border values" do
expect(evaluate(literal(MAX_INTEGER) + literal(MIN_INTEGER))).to eq(MAX_INTEGER+MIN_INTEGER)
end
end
context "on Floats" do
it "2.2 + 2.2 == 4.4" do; expect(evaluate(literal(2.2) + literal(2.2))).to eq(4.4) ; end
it "7.7 - 3.3 == 4.4" do; expect(evaluate(literal(7.7) - literal(3.3))).to eq(4.4) ; end
it "6.1 * 3.1 == 18.91" do; expect(evaluate(literal(6.1) * literal(3.1))).to eq(18.91); end
it "6.6 / 3.3 == 2.0" do; expect(evaluate(literal(6.6) / literal(3.3))).to eq(2.0) ; end
it "-(6.0/3.0) == -2.0" do; expect(evaluate(minus(literal(6.0) / literal(3.0)))).to eq(-2.0); end
it "-6.0/3.0 == -2.0" do; expect(evaluate(minus(literal(6.0)) / literal(3.0))).to eq(-2.0); end
it "6.6 % 3.3 == 0.0" do; expect { evaluate(literal(6.6) % literal(3.3))}.to raise_error(Puppet::ParseError); end
it "10.0 % 3.0 == 1.0" do; expect { evaluate(literal(10.0) % literal(3.0))}.to raise_error(Puppet::ParseError); end
it "3.14 << 2 == error" do; expect { evaluate(literal(3.14) << literal(2))}.to raise_error(Puppet::ParseError); end
it "3.14 >> 2 == error" do; expect { evaluate(literal(3.14) >> literal(2))}.to raise_error(Puppet::ParseError); end
end
context "on strings requiring boxing to Numeric" do
before :each do
Puppet[:strict] = :off
end
it "'2' + '2' == 4" do
expect(evaluate(literal('2') + literal('2'))).to eq(4)
end
it "'2.2' + '2.2' == 4.4" do
expect(evaluate(literal('2.2') + literal('2.2'))).to eq(4.4)
end
it "'0xF7' + '0x8' == 0xFF" do
expect(evaluate(literal('0xF7') + literal('0x8'))).to eq(0xFF)
end
it "'0367' + '010' == 0xFF" do
expect(evaluate(literal('0367') + literal('010'))).to eq(0xFF)
end
it "'0888' + '010' == error" do
expect { evaluate(literal('0888') + literal('010'))}.to raise_error(Puppet::ParseError)
end
it "'0xWTF' + '010' == error" do
expect { evaluate(literal('0xWTF') + literal('010'))}.to raise_error(Puppet::ParseError)
end
it "'0x12.3' + '010' == error" do
expect { evaluate(literal('0x12.3') + literal('010'))}.to raise_error(Puppet::ParseError)
end
it "'012.3' + '010' == 20.3 (not error, floats can start with 0)" do
expect(evaluate(literal('012.3') + literal('010'))).to eq(20.3)
end
it "raises an error when coercing string to numerical by default" do
Puppet[:strict] = :error
expect { evaluate(literal('2') + literal('2')) }.to raise_error(/Evaluation Error: The string '2' was automatically coerced to the numerical value 2/)
end
end
context 'on binary values' do
include PuppetSpec::Compiler
require 'base64'
encoded = Base64.encode64('Hello world').chomp
it 'Binary + Binary' do
code = 'notice(assert_type(Binary, Binary([72,101,108,108,111,32]) + Binary([119,111,114,108,100])))'
expect(eval_and_collect_notices(code)).to eql([encoded])
end
end
context 'on timespans' do
include PuppetSpec::Compiler
it 'Timespan + Timespan = Timespan' do
code = 'notice(assert_type(Timespan, Timespan({days => 3}) + Timespan({hours => 12})))'
expect(eval_and_collect_notices(code)).to eql(['3-12:00:00.0'])
end
it 'Timespan - Timespan = Timespan' do
code = 'notice(assert_type(Timespan, Timespan({days => 3}) - Timespan({hours => 12})))'
expect(eval_and_collect_notices(code)).to eql(['2-12:00:00.0'])
end
it 'Timespan + -Timespan = Timespan' do
code = 'notice(assert_type(Timespan, Timespan({days => 3}) + -Timespan({hours => 12})))'
expect(eval_and_collect_notices(code)).to eql(['2-12:00:00.0'])
end
it 'Timespan - -Timespan = Timespan' do
code = 'notice(assert_type(Timespan, Timespan({days => 3}) - -Timespan({hours => 12})))'
expect(eval_and_collect_notices(code)).to eql(['3-12:00:00.0'])
end
it 'Timespan / Timespan = Float' do
code = "notice(assert_type(Float, Timespan({days => 3}) / Timespan('0-12:00:00')))"
expect(eval_and_collect_notices(code)).to eql(['6.0'])
end
it 'Timespan * Timespan is an error' do
code = 'notice(Timespan({days => 3}) * Timespan({hours => 12}))'
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be multiplied by a Timespan/)
end
it 'Timespan + Numeric = Timespan (numeric treated as seconds)' do
code = 'notice(assert_type(Timespan, Timespan({days => 3}) + 7300.0))'
expect(eval_and_collect_notices(code)).to eql(['3-02:01:40.0'])
end
it 'Timespan - Numeric = Timespan (numeric treated as seconds)' do
code = "notice(assert_type(Timespan, Timespan({days => 3}) - 7300.123))"
expect(eval_and_collect_notices(code)).to eql(['2-21:58:19.877'])
end
it 'Timespan * Numeric = Timespan (numeric treated as seconds)' do
code = "notice(strftime(assert_type(Timespan, Timespan({days => 3}) * 2), '%D'))"
expect(eval_and_collect_notices(code)).to eql(['6'])
end
it 'Numeric + Timespan = Timespan (numeric treated as seconds)' do
code = 'notice(assert_type(Timespan, 7300.0 + Timespan({days => 3})))'
expect(eval_and_collect_notices(code)).to eql(['3-02:01:40.0'])
end
it 'Numeric - Timespan = Timespan (numeric treated as seconds)' do
code = "notice(strftime(assert_type(Timespan, 300000 - Timespan({days => 3})), '%H:%M'))"
expect(eval_and_collect_notices(code)).to eql(['11:20'])
end
it 'Numeric * Timespan = Timespan (numeric treated as seconds)' do
code = "notice(strftime(assert_type(Timespan, 2 * Timespan({days => 3})), '%D'))"
expect(eval_and_collect_notices(code)).to eql(['6'])
end
it 'Timespan + Timestamp = Timestamp' do
code = "notice(assert_type(Timestamp, Timespan({days => 3}) + Timestamp('2016-08-27T16:44:49.999 UTC')))"
expect(eval_and_collect_notices(code)).to eql(['2016-08-30T16:44:49.999000000 UTC'])
end
it 'Timespan - Timestamp is an error' do
code = 'notice(Timespan({days => 3}) - Timestamp())'
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be subtracted from a Timespan/)
end
it 'Timespan * Timestamp is an error' do
code = 'notice(Timespan({days => 3}) * Timestamp())'
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be multiplied by a Timestamp/)
end
it 'Timespan / Timestamp is an error' do
code = 'notice(Timespan({days => 3}) / Timestamp())'
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timespan cannot be divided by a Timestamp/)
end
end
context 'on timestamps' do
include PuppetSpec::Compiler
it 'Timestamp + Timestamp is an error' do
code = 'notice(Timestamp() + Timestamp())'
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /A Timestamp cannot be added to a Timestamp/)
end
it 'Timestamp + Timespan = Timestamp' do
code = "notice(assert_type(Timestamp, Timestamp('2016-10-10') + Timespan('0-12:00:00')))"
expect(eval_and_collect_notices(code)).to eql(['2016-10-10T12:00:00.000000000 UTC'])
end
it 'Timestamp + Numeric = Timestamp' do
code = "notice(assert_type(Timestamp, Timestamp('2016-10-10T12:00:00.000') + 3600.123))"
expect(eval_and_collect_notices(code)).to eql(['2016-10-10T13:00:00.123000000 UTC'])
end
it 'Numeric + Timestamp = Timestamp' do
code = "notice(assert_type(Timestamp, 3600.123 + Timestamp('2016-10-10T12:00:00.000')))"
expect(eval_and_collect_notices(code)).to eql(['2016-10-10T13:00:00.123000000 UTC'])
end
it 'Timestamp - Timestamp = Timespan' do
code = "notice(assert_type(Timespan, Timestamp('2016-10-10') - Timestamp('2015-10-10')))"
expect(eval_and_collect_notices(code)).to eql(['366-00:00:00.0'])
end
it 'Timestamp - Timespan = Timestamp' do
code = "notice(assert_type(Timestamp, Timestamp('2016-10-10') - Timespan('0-12:00:00')))"
expect(eval_and_collect_notices(code)).to eql(['2016-10-09T12:00:00.000000000 UTC'])
end
it 'Timestamp - Numeric = Timestamp' do
code = "notice(assert_type(Timestamp, Timestamp('2016-10-10') - 3600.123))"
expect(eval_and_collect_notices(code)).to eql(['2016-10-09T22:59:59.877000000 UTC'])
end
it 'Numeric - Timestamp = Timestamp' do
code = "notice(assert_type(Timestamp, 123 - Timestamp('2016-10-10')))"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '-' is not applicable.*when right side is a Timestamp/)
end
it 'Timestamp / Timestamp is an error' do
code = "notice(Timestamp('2016-10-10') / Timestamp())"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable to a Timestamp/)
end
it 'Timestamp / Timespan is an error' do
code = "notice(Timestamp('2016-10-10') / Timespan('0-12:00:00'))"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable to a Timestamp/)
end
it 'Timestamp / Numeric is an error' do
code = "notice(Timestamp('2016-10-10') / 3600.123)"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable to a Timestamp/)
end
it 'Numeric / Timestamp is an error' do
code = "notice(3600.123 / Timestamp('2016-10-10'))"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\/' is not applicable.*when right side is a Timestamp/)
end
it 'Timestamp * Timestamp is an error' do
code = "notice(Timestamp('2016-10-10') * Timestamp())"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable to a Timestamp/)
end
it 'Timestamp * Timespan is an error' do
code = "notice(Timestamp('2016-10-10') * Timespan('0-12:00:00'))"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable to a Timestamp/)
end
it 'Timestamp * Numeric is an error' do
code = "notice(Timestamp('2016-10-10') * 3600.123)"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable to a Timestamp/)
end
it 'Numeric * Timestamp is an error' do
code = "notice(3600.123 * Timestamp('2016-10-10'))"
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Operator '\*' is not applicable.*when right side is a Timestamp/)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/comparison_ops_spec.rb | spec/unit/pops/evaluator/comparison_ops_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include EvaluatorRspecHelper
context "When the evaluator performs comparisons" do
context "of string values" do
it "'a' == 'a' == true" do; expect(evaluate(literal('a').eq(literal('a')))).to eq(true) ; end
it "'a' == 'b' == false" do; expect(evaluate(literal('a').eq(literal('b')))).to eq(false) ; end
it "'a' != 'a' == false" do; expect(evaluate(literal('a').ne(literal('a')))).to eq(false) ; end
it "'a' != 'b' == true" do; expect(evaluate(literal('a').ne(literal('b')))).to eq(true) ; end
it "'a' < 'b' == true" do; expect(evaluate(literal('a') < literal('b'))).to eq(true) ; end
it "'a' < 'a' == false" do; expect(evaluate(literal('a') < literal('a'))).to eq(false) ; end
it "'b' < 'a' == false" do; expect(evaluate(literal('b') < literal('a'))).to eq(false) ; end
it "'a' <= 'b' == true" do; expect(evaluate(literal('a') <= literal('b'))).to eq(true) ; end
it "'a' <= 'a' == true" do; expect(evaluate(literal('a') <= literal('a'))).to eq(true) ; end
it "'b' <= 'a' == false" do; expect(evaluate(literal('b') <= literal('a'))).to eq(false) ; end
it "'a' > 'b' == false" do; expect(evaluate(literal('a') > literal('b'))).to eq(false) ; end
it "'a' > 'a' == false" do; expect(evaluate(literal('a') > literal('a'))).to eq(false) ; end
it "'b' > 'a' == true" do; expect(evaluate(literal('b') > literal('a'))).to eq(true) ; end
it "'a' >= 'b' == false" do; expect(evaluate(literal('a') >= literal('b'))).to eq(false) ; end
it "'a' >= 'a' == true" do; expect(evaluate(literal('a') >= literal('a'))).to eq(true) ; end
it "'b' >= 'a' == true" do; expect(evaluate(literal('b') >= literal('a'))).to eq(true) ; end
context "with mixed case" do
it "'a' == 'A' == true" do; expect(evaluate(literal('a').eq(literal('A')))).to eq(true) ; end
it "'a' != 'A' == false" do; expect(evaluate(literal('a').ne(literal('A')))).to eq(false) ; end
it "'a' > 'A' == false" do; expect(evaluate(literal('a') > literal('A'))).to eq(false) ; end
it "'a' >= 'A' == true" do; expect(evaluate(literal('a') >= literal('A'))).to eq(true) ; end
it "'A' < 'a' == false" do; expect(evaluate(literal('A') < literal('a'))).to eq(false) ; end
it "'A' <= 'a' == true" do; expect(evaluate(literal('A') <= literal('a'))).to eq(true) ; end
end
end
context "of integer values" do
it "1 == 1 == true" do; expect(evaluate(literal(1).eq(literal(1)))).to eq(true) ; end
it "1 == 2 == false" do; expect(evaluate(literal(1).eq(literal(2)))).to eq(false) ; end
it "1 != 1 == false" do; expect(evaluate(literal(1).ne(literal(1)))).to eq(false) ; end
it "1 != 2 == true" do; expect(evaluate(literal(1).ne(literal(2)))).to eq(true) ; end
it "1 < 2 == true" do; expect(evaluate(literal(1) < literal(2))).to eq(true) ; end
it "1 < 1 == false" do; expect(evaluate(literal(1) < literal(1))).to eq(false) ; end
it "2 < 1 == false" do; expect(evaluate(literal(2) < literal(1))).to eq(false) ; end
it "1 <= 2 == true" do; expect(evaluate(literal(1) <= literal(2))).to eq(true) ; end
it "1 <= 1 == true" do; expect(evaluate(literal(1) <= literal(1))).to eq(true) ; end
it "2 <= 1 == false" do; expect(evaluate(literal(2) <= literal(1))).to eq(false) ; end
it "1 > 2 == false" do; expect(evaluate(literal(1) > literal(2))).to eq(false) ; end
it "1 > 1 == false" do; expect(evaluate(literal(1) > literal(1))).to eq(false) ; end
it "2 > 1 == true" do; expect(evaluate(literal(2) > literal(1))).to eq(true) ; end
it "1 >= 2 == false" do; expect(evaluate(literal(1) >= literal(2))).to eq(false) ; end
it "1 >= 1 == true" do; expect(evaluate(literal(1) >= literal(1))).to eq(true) ; end
it "2 >= 1 == true" do; expect(evaluate(literal(2) >= literal(1))).to eq(true) ; end
end
context "of mixed value types" do
it "1 == 1.0 == true" do; expect(evaluate(literal(1).eq( literal(1.0)))).to eq(true) ; end
it "1 < 1.1 == true" do; expect(evaluate(literal(1) < literal(1.1))).to eq(true) ; end
it "1.0 == 1 == true" do; expect(evaluate(literal(1.0).eq( literal(1)))).to eq(true) ; end
it "1.0 < 2 == true" do; expect(evaluate(literal(1.0) < literal(2))).to eq(true) ; end
it "'1.0' < 'a' == true" do; expect(evaluate(literal('1.0') < literal('a'))).to eq(true) ; end
it "'1.0' < '' == true" do; expect(evaluate(literal('1.0') < literal(''))).to eq(false) ; end
it "'1.0' < ' ' == true" do; expect(evaluate(literal('1.0') < literal(' '))).to eq(false) ; end
it "'a' > '1.0' == true" do; expect(evaluate(literal('a') > literal('1.0'))).to eq(true) ; end
end
context "of unsupported mixed value types" do
it "'1' < 1.1 == true" do
expect{ evaluate(literal('1') < literal(1.1))}.to raise_error(/String < Float/)
end
it "'1.0' < 1.1 == true" do
expect{evaluate(literal('1.0') < literal(1.1))}.to raise_error(/String < Float/)
end
it "undef < 1.1 == true" do
expect{evaluate(literal(nil) < literal(1.1))}.to raise_error(/Undef Value < Float/)
end
end
context "of regular expressions" do
it "/.*/ == /.*/ == true" do; expect(evaluate(literal(/.*/).eq(literal(/.*/)))).to eq(true) ; end
it "/.*/ != /a.*/ == true" do; expect(evaluate(literal(/.*/).ne(literal(/a.*/)))).to eq(true) ; end
end
context "of booleans" do
it "true == true == true" do; expect(evaluate(literal(true).eq(literal(true)))).to eq(true) ; end;
it "false == false == true" do; expect(evaluate(literal(false).eq(literal(false)))).to eq(true) ; end;
it "true == false != true" do; expect(evaluate(literal(true).eq(literal(false)))).to eq(false) ; end;
it "false == '' == false" do; expect(evaluate(literal(false).eq(literal('')))).to eq(false) ; end;
it "undef == '' == false" do; expect(evaluate(literal(:undef).eq(literal('')))).to eq(false) ; end;
it "undef == undef == true" do; expect(evaluate(literal(:undef).eq(literal(:undef)))).to eq(true) ; end;
it "nil == undef == true" do; expect(evaluate(literal(nil).eq(literal(:undef)))).to eq(true) ; end;
end
context "of collections" do
it "[1,2,3] == [1,2,3] == true" do
expect(evaluate(literal([1,2,3]).eq(literal([1,2,3])))).to eq(true)
expect(evaluate(literal([1,2,3]).ne(literal([1,2,3])))).to eq(false)
expect(evaluate(literal([1,2,4]).eq(literal([1,2,3])))).to eq(false)
expect(evaluate(literal([1,2,4]).ne(literal([1,2,3])))).to eq(true)
end
it "{'a'=>1, 'b'=>2} == {'a'=>1, 'b'=>2} == true" do
expect(evaluate(literal({'a'=>1, 'b'=>2}).eq(literal({'a'=>1, 'b'=>2})))).to eq(true)
expect(evaluate(literal({'a'=>1, 'b'=>2}).ne(literal({'a'=>1, 'b'=>2})))).to eq(false)
expect(evaluate(literal({'a'=>1, 'b'=>2}).eq(literal({'x'=>1, 'b'=>2})))).to eq(false)
expect(evaluate(literal({'a'=>1, 'b'=>2}).ne(literal({'x'=>1, 'b'=>2})))).to eq(true)
end
end
context "of non comparable types" do
# TODO: Change the exception type
it "false < true == error" do; expect { evaluate(literal(true) < literal(false))}.to raise_error(Puppet::ParseError); end
it "false <= true == error" do; expect { evaluate(literal(true) <= literal(false))}.to raise_error(Puppet::ParseError); end
it "false > true == error" do; expect { evaluate(literal(true) > literal(false))}.to raise_error(Puppet::ParseError); end
it "false >= true == error" do; expect { evaluate(literal(true) >= literal(false))}.to raise_error(Puppet::ParseError); end
it "/a/ < /b/ == error" do; expect { evaluate(literal(/a/) < literal(/b/))}.to raise_error(Puppet::ParseError); end
it "/a/ <= /b/ == error" do; expect { evaluate(literal(/a/) <= literal(/b/))}.to raise_error(Puppet::ParseError); end
it "/a/ > /b/ == error" do; expect { evaluate(literal(/a/) > literal(/b/))}.to raise_error(Puppet::ParseError); end
it "/a/ >= /b/ == error" do; expect { evaluate(literal(/a/) >= literal(/b/))}.to raise_error(Puppet::ParseError); end
it "[1,2,3] < [1,2,3] == error" do
expect{ evaluate(literal([1,2,3]) < literal([1,2,3]))}.to raise_error(Puppet::ParseError)
end
it "[1,2,3] > [1,2,3] == error" do
expect{ evaluate(literal([1,2,3]) > literal([1,2,3]))}.to raise_error(Puppet::ParseError)
end
it "[1,2,3] >= [1,2,3] == error" do
expect{ evaluate(literal([1,2,3]) >= literal([1,2,3]))}.to raise_error(Puppet::ParseError)
end
it "[1,2,3] <= [1,2,3] == error" do
expect{ evaluate(literal([1,2,3]) <= literal([1,2,3]))}.to raise_error(Puppet::ParseError)
end
it "{'a'=>1, 'b'=>2} < {'a'=>1, 'b'=>2} == error" do
expect{ evaluate(literal({'a'=>1, 'b'=>2}) < literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError)
end
it "{'a'=>1, 'b'=>2} > {'a'=>1, 'b'=>2} == error" do
expect{ evaluate(literal({'a'=>1, 'b'=>2}) > literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError)
end
it "{'a'=>1, 'b'=>2} <= {'a'=>1, 'b'=>2} == error" do
expect{ evaluate(literal({'a'=>1, 'b'=>2}) <= literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError)
end
it "{'a'=>1, 'b'=>2} >= {'a'=>1, 'b'=>2} == error" do
expect{ evaluate(literal({'a'=>1, 'b'=>2}) >= literal({'a'=>1, 'b'=>2}))}.to raise_error(Puppet::ParseError)
end
end
end
context "When the evaluator performs Regular Expression matching" do
it "'a' =~ /.*/ == true" do; expect(evaluate(literal('a') =~ literal(/.*/))).to eq(true) ; end
it "'a' =~ '.*' == true" do; expect(evaluate(literal('a') =~ literal(".*"))).to eq(true) ; end
it "'a' !~ /b.*/ == true" do; expect(evaluate(literal('a').mne(literal(/b.*/)))).to eq(true) ; end
it "'a' !~ 'b.*' == true" do; expect(evaluate(literal('a').mne(literal("b.*")))).to eq(true) ; end
it "'a' =~ Pattern['.*'] == true" do
expect(evaluate(literal('a') =~ fqr('Pattern').access_at(literal(".*")))).to eq(true)
end
it "$a = Pattern['.*']; 'a' =~ $a == true" do
expr = block(var('a').set(fqr('Pattern').access_at('.*')), literal('foo') =~ var('a'))
expect(evaluate(expr)).to eq(true)
end
it 'should fail if LHS is not a string' do
expect { evaluate(literal(666) =~ literal(/6/))}.to raise_error(Puppet::ParseError)
end
end
context "When evaluator evaluates the 'in' operator" do
it "should find elements in an array" do
expect(evaluate(literal(1).in(literal([1,2,3])))).to eq(true)
expect(evaluate(literal(4).in(literal([1,2,3])))).to eq(false)
end
it "should find keys in a hash" do
expect(evaluate(literal('a').in(literal({'x'=>1, 'a'=>2, 'y'=> 3})))).to eq(true)
expect(evaluate(literal('z').in(literal({'x'=>1, 'a'=>2, 'y'=> 3})))).to eq(false)
end
it "should find substrings in a string" do
expect(evaluate(literal('ana').in(literal('bananas')))).to eq(true)
expect(evaluate(literal('xxx').in(literal('bananas')))).to eq(false)
end
it "should find substrings in a string (regexp)" do
expect(evaluate(literal(/ana/).in(literal('bananas')))).to eq(true)
expect(evaluate(literal(/xxx/).in(literal('bananas')))).to eq(false)
end
it "should find substrings in a string (ignoring case)" do
expect(evaluate(literal('ANA').in(literal('bananas')))).to eq(true)
expect(evaluate(literal('ana').in(literal('BANANAS')))).to eq(true)
expect(evaluate(literal('xxx').in(literal('BANANAS')))).to eq(false)
end
it "should find sublists in a list" do
expect(evaluate(literal([2,3]).in(literal([1,[2,3],4])))).to eq(true)
expect(evaluate(literal([2,4]).in(literal([1,[2,3],4])))).to eq(false)
end
it "should find sublists in a list (case insensitive)" do
expect(evaluate(literal(['a','b']).in(literal(['A',['A','B'],'C'])))).to eq(true)
expect(evaluate(literal(['x','y']).in(literal(['A',['A','B'],'C'])))).to eq(false)
end
it "should find keys in a hash" do
expect(evaluate(literal('a').in(literal({'a' => 10, 'b' => 20})))).to eq(true)
expect(evaluate(literal('x').in(literal({'a' => 10, 'b' => 20})))).to eq(false)
end
it "should find keys in a hash (case insensitive)" do
expect(evaluate(literal('A').in(literal({'a' => 10, 'b' => 20})))).to eq(true)
expect(evaluate(literal('X').in(literal({'a' => 10, 'b' => 20})))).to eq(false)
end
it "should find keys in a hash (regexp)" do
expect(evaluate(literal(/xxx/).in(literal({'abcxxxabc' => 10, 'xyz' => 20})))).to eq(true)
expect(evaluate(literal(/yyy/).in(literal({'abcxxxabc' => 10, 'xyz' => 20})))).to eq(false)
end
it "should find numbers as numbers" do
expect(evaluate(literal(15).in(literal([1,0xf,2])))).to eq(true)
end
it "should not find numbers as strings" do
expect(evaluate(literal(15).in(literal([1, '0xf',2])))).to eq(false)
expect(evaluate(literal('15').in(literal([1, 0xf,2])))).to eq(false)
end
it "should not find numbers embedded in strings, nor digits in numbers" do
expect(evaluate(literal(15).in(literal([1, '115', 2])))).to eq(false)
expect(evaluate(literal(1).in(literal([11, 111, 2])))).to eq(false)
expect(evaluate(literal('1').in(literal([11, 111, 2])))).to eq(false)
end
it 'should find an entry with compatible type in an Array' do
expect(evaluate(fqr('Array').access_at(fqr('Integer')).in(literal(['a', [1,2,3], 'b'])))).to eq(true)
expect(evaluate(fqr('Array').access_at(fqr('Integer')).in(literal(['a', [1,2,'not integer'], 'b'])))).to eq(false)
end
it 'should find an entry with compatible type in a Hash' do
expect(evaluate(fqr('Integer').in(literal({1 => 'a', 'a' => 'b'})))).to eq(true)
expect(evaluate(fqr('Integer').in(literal({'a' => 'a', 'b' => 'b'})))).to eq(false)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/time/timespan_spec.rb | spec/unit/pops/time/timespan_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Time
describe 'Timespan' do
include PuppetSpec::Compiler
let! (:simple) { Timespan.from_fields(false, 1, 3, 10, 11) }
let! (:all_fields_hash) { {'days' => 1, 'hours' => 7, 'minutes' => 10, 'seconds' => 11, 'milliseconds' => 123, 'microseconds' => 456, 'nanoseconds' => 789} }
let! (:complex) { Timespan.from_fields_hash(all_fields_hash) }
context 'can be created from a String' do
it 'using default format' do
expect(Timespan.parse('1-03:10:11')).to eql(simple)
end
it 'using explicit format' do
expect(Timespan.parse('1-7:10:11.123456789', '%D-%H:%M:%S.%N')).to eql(complex)
end
it 'using leading minus and explicit format' do
expect(Timespan.parse('-1-7:10:11.123456789', '%D-%H:%M:%S.%N')).to eql(-complex)
end
it 'using %H as the biggest quantity' do
expect(Timespan.parse('27:10:11', '%H:%M:%S')).to eql(simple)
end
it 'using %M as the biggest quantity' do
expect(Timespan.parse('1630:11', '%M:%S')).to eql(simple)
end
it 'using %S as the biggest quantity' do
expect(Timespan.parse('97811', '%S')).to eql(simple)
end
it 'where biggest quantity is not frist' do
expect(Timespan.parse('11:1630', '%S:%M')).to eql(simple)
end
it 'raises an error when using %L as the biggest quantity' do
expect { Timespan.parse('123', '%L') }.to raise_error(ArgumentError, /denotes fractions and must be used together with a specifier of higher magnitude/)
end
it 'raises an error when using %N as the biggest quantity' do
expect { Timespan.parse('123', '%N') }.to raise_error(ArgumentError, /denotes fractions and must be used together with a specifier of higher magnitude/)
end
it 'where %L is treated as fractions of a second' do
expect(Timespan.parse('0.4', '%S.%L')).to eql(Timespan.from_fields(false, 0, 0, 0, 0, 400))
end
it 'where %N is treated as fractions of a second' do
expect(Timespan.parse('0.4', '%S.%N')).to eql(Timespan.from_fields(false, 0, 0, 0, 0, 400))
end
end
context 'when presented as a String' do
it 'uses default format for #to_s' do
expect(simple.to_s).to eql('1-03:10:11.0')
end
context 'using a format' do
it 'produces a string containing all components' do
expect(complex.format('%D-%H:%M:%S.%N')).to eql('1-07:10:11.123456789')
end
it 'produces a literal % for %%' do
expect(complex.format('%D%%%H:%M:%S')).to eql('1%07:10:11')
end
it 'produces a leading dash for negative instance' do
expect((-complex).format('%D-%H:%M:%S')).to eql('-1-07:10:11')
end
it 'produces a string without trailing zeros for %-N' do
expect(Timespan.parse('2.345', '%S.%N').format('%-S.%-N')).to eql('2.345')
end
it 'produces a string with trailing zeros for %N' do
expect(Timespan.parse('2.345', '%S.%N').format('%-S.%N')).to eql('2.345000000')
end
it 'produces a string with trailing zeros for %0N' do
expect(Timespan.parse('2.345', '%S.%N').format('%-S.%0N')).to eql('2.345000000')
end
it 'produces a string with trailing spaces for %_N' do
expect(Timespan.parse('2.345', '%S.%N').format('%-S.%_N')).to eql('2.345 ')
end
end
end
context 'when converted to a hash' do
it 'produces a hash with all numeric keys' do
hash = complex.to_hash
expect(hash).to eql(all_fields_hash)
end
it 'produces a compact hash with seconds and nanoseconds for #to_hash(true)' do
hash = complex.to_hash(true)
expect(hash).to eql({'seconds' => 112211, 'nanoseconds' => 123456789})
end
context 'from a negative value' do
it 'produces a hash with all numeric keys and negative = true' do
hash = (-complex).to_hash
expect(hash).to eql(all_fields_hash.merge('negative' => true))
end
it 'produces a compact hash with negative seconds and negative nanoseconds for #to_hash(true)' do
hash = (-complex).to_hash(true)
expect(hash).to eql({'seconds' => -112211, 'nanoseconds' => -123456789})
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/time/timestamp_spec.rb | spec/unit/pops/time/timestamp_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Time
describe 'Timestamp' do
it 'Does not loose microsecond precision when converted to/from String' do
ts = Timestamp.new(1495789430910161286)
expect(Timestamp.parse(ts.to_s)).to eql(ts)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_timespan_type_spec.rb | spec/unit/pops/types/p_timespan_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Timespan type' do
it 'is normalized in a Variant' do
t = TypeFactory.variant(TypeFactory.timespan('10:00:00', '15:00:00'), TypeFactory.timespan('14:00:00', '17:00:00')).normalize
expect(t).to be_a(PTimespanType)
expect(t).to eql(TypeFactory.timespan('10:00:00', '17:00:00'))
end
context 'when used in Puppet expressions' do
include PuppetSpec::Compiler
it 'is equal to itself only' do
code = <<-CODE
$t = Timespan
notice(Timespan =~ Type[Timespan])
notice(Timespan == Timespan)
notice(Timespan < Timespan)
notice(Timespan > Timespan)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true false false))
end
it 'does not consider an Integer to be an instance' do
code = <<-CODE
notice(assert_type(Timespan, 1234))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timespan value, got Integer/)
end
it 'does not consider a Float to be an instance' do
code = <<-CODE
notice(assert_type(Timespan, 1.234))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timespan value, got Float/)
end
context "when parameterized" do
it 'is equal other types with the same parameterization' do
code = <<-CODE
notice(Timespan['01:00:00', '13:00:00'] == Timespan['01:00:00', '13:00:00'])
notice(Timespan['01:00:00', '13:00:00'] != Timespan['01:12:20', '13:00:00'])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true))
end
it 'using just one parameter is the same as using default for the second parameter' do
code = <<-CODE
notice(Timespan['01:00:00'] == Timespan['01:00:00', default])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true))
end
it 'if the second parameter is default, it is unlimited' do
code = <<-CODE
notice(Timespan('12345-23:59:59') =~ Timespan['01:00:00', default])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true))
end
it 'orders parameterized types based on range inclusion' do
code = <<-CODE
notice(Timespan['01:00:00', '13:00:00'] < Timespan['00:00:00', '14:00:00'])
notice(Timespan['01:00:00', '13:00:00'] > Timespan['00:00:00', '14:00:00'])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false))
end
it 'accepts integer values when specifying the range' do
code = <<-CODE
notice(Timespan(1) =~ Timespan[1, 2])
notice(Timespan(3) =~ Timespan[1])
notice(Timespan(0) =~ Timespan[default, 2])
notice(Timespan(0) =~ Timespan[1, 2])
notice(Timespan(3) =~ Timespan[1, 2])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true true false false))
end
it 'accepts float values when specifying the range' do
code = <<-CODE
notice(Timespan(1.0) =~ Timespan[1.0, 2.0])
notice(Timespan(3.0) =~ Timespan[1.0])
notice(Timespan(0.0) =~ Timespan[default, 2.0])
notice(Timespan(0.0) =~ Timespan[1.0, 2.0])
notice(Timespan(3.0) =~ Timespan[1.0, 2.0])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true true false false))
end
end
context 'a Timespan instance' do
it 'can be created from a string' do
code = <<-CODE
$o = Timespan('3-11:00')
notice($o)
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(3-11:00:00.0 Timespan['3-11:00:00.0']))
end
it 'can be created from a string and format' do
code = <<-CODE
$o = Timespan('1d11h23m', '%Dd%Hh%Mm')
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(1-11:23:00.0))
end
it 'can be created from a hash with string and format' do
code = <<-CODE
$o = Timespan({string => '1d11h23m', format => '%Dd%Hh%Mm'})
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(1-11:23:00.0))
end
it 'can be created from a string and array of formats' do
code = <<-CODE
$fmts = ['%Dd%Hh%Mm%Ss', '%Hh%Mm%Ss', '%Dd%Hh%Mm', '%Dd%Hh', '%Hh%Mm', '%Mm%Ss', '%Dd', '%Hh', '%Mm', '%Ss' ]
notice(Timespan('1d11h23m13s', $fmts))
notice(Timespan('11h23m13s', $fmts))
notice(Timespan('1d11h23m', $fmts))
notice(Timespan('1d11h', $fmts))
notice(Timespan('11h23m', $fmts))
notice(Timespan('23m13s', $fmts))
notice(Timespan('1d', $fmts))
notice(Timespan('11h', $fmts))
notice(Timespan('23m', $fmts))
notice(Timespan('13s', $fmts))
CODE
expect(eval_and_collect_notices(code)).to eq(
%w(1-11:23:13.0 0-11:23:13.0 1-11:23:00.0 1-11:00:00.0 0-11:23:00.0 0-00:23:13.0 1-00:00:00.0 0-11:00:00.0 0-00:23:00.0 0-00:00:13.0))
end
it 'it cannot be created using an empty formats array' do
code = <<-CODE
notice(Timespan('1d11h23m13s', []))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /parameter 'format' variant 1 expects size to be at least 1, got 0/)
end
it 'can be created from a integer that represents seconds' do
code = <<-CODE
$o = Timespan(6800)
notice(Integer($o) == 6800)
notice($o == Timespan('01:53:20'))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true))
end
it 'can be created from a float that represents seconds with fraction' do
code = <<-CODE
$o = Timespan(6800.123456789)
notice(Float($o) == 6800.123456789)
notice($o == Timespan('01:53:20.123456789', '%H:%M:%S.%N'))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true))
end
it 'matches the appropriate parameterized type' do
code = <<-CODE
$o = Timespan('3-11:12:13')
notice(assert_type(Timespan['3-00:00:00', '4-00:00:00'], $o))
CODE
expect(eval_and_collect_notices(code)).to eq(['3-11:12:13.0'])
end
it 'does not match an inappropriate parameterized type' do
code = <<-CODE
$o = Timespan('1-03:04:05')
notice(assert_type(Timespan['2-00:00:00', '3-00:00:00'], $o) |$e, $a| { 'nope' })
CODE
expect(eval_and_collect_notices(code)).to eq(['nope'])
end
it 'can be compared to other instances' do
code = <<-CODE
$o1 = Timespan('00:00:01')
$o2 = Timespan('00:00:02')
$o3 = Timespan('00:00:02')
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o1 == $o3)
notice($o1 != $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
notice($o2 == $o3)
notice($o2 != $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false true false false true true true false))
end
it 'can be compared to integer that represents seconds' do
code = <<-CODE
$o1 = Timespan('00:00:01')
$o2 = Timespan('00:00:02')
$o3 = 2
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'integer that represents seconds can be compared to it' do
code = <<-CODE
$o1 = 1
$o2 = 2
$o3 = Timespan('00:00:02')
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'is equal to integer that represents seconds' do
code = <<-CODE
$o1 = Timespan('02', '%S')
$o2 = 2
notice($o1 == $o2)
notice($o1 != $o2)
notice(Integer($o1) == $o2)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'integer that represents seconds is equal to it' do
code = <<-CODE
$o1 = 2
$o2 = Timespan('02', '%S')
notice($o1 == $o2)
notice($o1 != $o2)
notice($o1 == Integer($o2))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'can be compared to float that represents seconds with fraction' do
code = <<-CODE
$o1 = Timespan('01.123456789', '%S.%N')
$o2 = Timespan('02.123456789', '%S.%N')
$o3 = 2.123456789
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'float that represents seconds with fraction can be compared to it' do
code = <<-CODE
$o1 = 1.123456789
$o2 = 2.123456789
$o3 = Timespan('02.123456789', '%S.%N')
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'is equal to float that represents seconds with fraction' do
code = <<-CODE
$o1 = Timespan('02.123456789', '%S.%N')
$o2 = 2.123456789
notice($o1 == $o2)
notice($o1 != $o2)
notice(Float($o1) == $o2)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'float that represents seconds with fraction is equal to it' do
code = <<-CODE
$o1 = 2.123456789
$o2 = Timespan('02.123456789', '%S.%N')
notice($o1 == $o2)
notice($o1 != $o2)
notice($o1 == Float($o2))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'it cannot be compared to a Timestamp' do
code = <<-CODE
notice(Timespan(3) < Timestamp())
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Timespans are only comparable to Timespans, Integers, and Floats/)
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_init_type_spec.rb | spec/unit/pops/types/p_init_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'The Init Type' do
include PuppetSpec::Compiler
include_context 'types_setup'
context 'when used in Puppet expressions' do
it 'an unparameterized type can be used' do
code = <<-CODE
notice(type(Init))
CODE
expect(eval_and_collect_notices(code)).to eql(['Type[Init]'])
end
it 'a parameterized type can be used' do
code = <<-CODE
notice(type(Init[Integer]))
CODE
expect(eval_and_collect_notices(code)).to eql(['Type[Init[Integer]]'])
end
it 'a parameterized type can have additional arguments' do
code = <<-CODE
notice(type(Init[Integer, 16]))
CODE
expect(eval_and_collect_notices(code)).to eql(['Type[Init[Integer, 16]]'])
end
(all_types - abstract_types - internal_types).map { |tc| tc::DEFAULT.name }.each do |type_name|
it "can be created on a #{type_name}" do
code = <<-CODE
notice(type(Init[#{type_name}]))
CODE
expect(eval_and_collect_notices(code)).to eql(["Type[Init[#{type_name}]]"])
end
end
(abstract_types - internal_types).map { |tc| tc::DEFAULT.name }.each do |type_name|
it "cannot be created on a #{type_name}" do
code = <<-CODE
type(Init[#{type_name}]('x'))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/Creation of new instance of type '#{type_name}' is not supported/)
end
end
it 'an Init[Integer, 16] can create an instance from a String' do
code = <<-CODE
notice(Init[Integer, 16]('100'))
CODE
expect(eval_and_collect_notices(code)).to eql(['256'])
end
it "an Init[String,'%x'] can create an instance from an Integer" do
code = <<-CODE
notice(Init[String,'%x'](128))
CODE
expect(eval_and_collect_notices(code)).to eql(['80'])
end
it "an Init[String,23] raises an error because no available dispatcher exists" do
code = <<-CODE
notice(Init[String,23](128))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(
/The type 'Init\[String, 23\]' does not represent a valid set of parameters for String\.new\(\)/)
end
it 'an Init[String] can create an instance from an Integer' do
code = <<-CODE
notice(Init[String](128))
CODE
expect(eval_and_collect_notices(code)).to eql(['128'])
end
it 'an Init[String] can create an instance from an array with an Integer' do
code = <<-CODE
notice(Init[String]([128]))
CODE
expect(eval_and_collect_notices(code)).to eql(['128'])
end
it 'an Init[String] can create an instance from an array with an Integer and a format' do
code = <<-CODE
notice(Init[String]([128, '%x']))
CODE
expect(eval_and_collect_notices(code)).to eql(['80'])
end
it 'an Init[String] can create an instance from an array with an array' do
code = <<-CODE
notice(Init[String]([[128, '%x']]))
CODE
expect(eval_and_collect_notices(code)).to eql(["[128, '%x']"])
end
it 'an Init[Binary] can create an instance from a string' do
code = <<-CODE
notice(Init[Binary]('b25lIHR3byB0aHJlZQ=='))
CODE
expect(eval_and_collect_notices(code)).to eql(['b25lIHR3byB0aHJlZQ=='])
end
it 'an Init[String] can not create an instance from an Integer and a format unless given as an array argument' do
code = <<-CODE
notice(Init[String](128, '%x'))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/'new_Init' expects 1 argument, got 2/)
end
it 'the array [128] is an instance of Init[String]' do
code = <<-CODE
notice(assert_type(Init[String], [128]))
CODE
expect(eval_and_collect_notices(code)).to eql(['[128]'])
end
it 'the value 128 is an instance of Init[String]' do
code = <<-CODE
notice(assert_type(Init[String], 128))
CODE
expect(eval_and_collect_notices(code)).to eql(['128'])
end
it "the array [128] is an instance of Init[String]" do
code = <<-CODE
notice(assert_type(Init[String], [128]))
CODE
expect(eval_and_collect_notices(code)).to eql(['[128]'])
end
it "the array [128, '%x'] is an instance of Init[String]" do
code = <<-CODE
notice(assert_type(Init[String], [128, '%x']))
CODE
expect(eval_and_collect_notices(code)).to eql(['[128, %x]'])
end
it "the array [[128, '%x']] is an instance of Init[String]" do
code = <<-CODE
notice(assert_type(Init[String], [[128, '%x']]))
CODE
expect(eval_and_collect_notices(code)).to eql(['[[128, %x]]'])
end
it 'RichData is assignable to Init' do
code = <<-CODE
notice(Init > RichData)
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'Runtime is not assignable to Init' do
code = <<-CODE
notice(Init > Runtime['ruby', 'Time'])
CODE
expect(eval_and_collect_notices(code)).to eql(['false'])
end
it 'Init is not assignable to RichData' do
code = <<-CODE
notice(Init < RichData)
CODE
expect(eval_and_collect_notices(code)).to eql(['false'])
end
it 'Init[T1] is assignable to Init[T2] when T1 is assignable to T2' do
code = <<-CODE
notice(Init[Integer] < Init[Numeric])
notice(Init[Tuple[Integer]] < Init[Array[Integer]])
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'true'])
end
it 'Init[T1] is not assignable to Init[T2] unless T1 is assignable to T2' do
code = <<-CODE
notice(Init[Integer] > Init[Numeric])
notice(Init[Tuple[Integer]] > Init[Array[Integer]])
CODE
expect(eval_and_collect_notices(code)).to eql(['false', 'false'])
end
it 'T is assignable to Init[T]' do
code = <<-CODE
notice(Integer < Init[Integer])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'T1 is assignable to Init[T2] if T2 can be created from instance of T1' do
code = <<-CODE
notice(Integer < Init[String])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'a RichData value is an instance of Init' do
code = <<-CODE
notice(
String(assert_type(Init, { 'a' => [ 1, 2, Sensitive(3) ], 2 => Timestamp('2014-12-01T13:15:00') }),
{ Any => { format => '%s', string_formats => { Any => '%s' }}}))
CODE
expect(eval_and_collect_notices(code)).to eql(['{a => [1, 2, Sensitive [value redacted]], 2 => 2014-12-01T13:15:00.000000000 UTC}'])
end
it 'an Init[Sensitive[String]] can create an instance from a String' do
code = <<-CODE
notice(Init[Sensitive[String]]('256'))
CODE
expect(eval_and_collect_notices(code)).to eql(['Sensitive [value redacted]'])
end
it 'an Init[Type] can create an instance from a String' do
code = <<-CODE
notice(Init[Type]('Integer[2,3]'))
CODE
expect(eval_and_collect_notices(code)).to eql(['Integer[2, 3]'])
end
it 'an Init[Type[Numeric]] can not create an unassignable type from a String' do
code = <<-CODE
notice(Init[Type[Numeric]]('String'))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(
/Converted value from Type\[Numeric\]\.new\(\) has wrong type, expects a Type\[Numeric\] value, got Type\[String\]/)
end
it 'an Init with a custom object type can create an instance from a Hash' do
code = <<-CODE
type MyType = Object[{
attributes => {
granularity => String,
price => String,
category => Integer
}
}]
notice(Init[MyType]({ granularity => 'fine', price => '$10', category => 23 }))
CODE
expect(eval_and_collect_notices(code)).to eql(["MyType({'granularity' => 'fine', 'price' => '$10', 'category' => 23})"])
end
it 'an Init with a custom object type and additional parameters can create an instance from a value' do
code = <<-CODE
type MyType = Object[{
attributes => {
granularity => String,
price => String,
category => Integer
}
}]
notice(Init[MyType,'$5',20]('coarse'))
CODE
expect(eval_and_collect_notices(code)).to eql(["MyType({'granularity' => 'coarse', 'price' => '$5', 'category' => 20})"])
end
it 'an Init with a custom object with one Array parameter, can be created from an Array' do
code = <<-CODE
type MyType = Object[{
attributes => { array => Array[String] }
}]
notice(Init[MyType](['a']))
CODE
expect(eval_and_collect_notices(code)).to eql(["MyType({'array' => ['a']})"])
end
it 'an Init type can be used recursively' do
# Even if it doesn't make sense, it should not crash
code = <<-CODE
type One = Object[{
attributes => {
init_one => Variant[Init[One],String]
}
}]
notice(Init[One]('w'))
CODE
expect(eval_and_collect_notices(code)).to eql(["One({'init_one' => 'w'})"])
end
context 'computes if x is an instance such that' do
%w(true false True False TRUE FALSE tRuE FaLsE Yes No yes no YES NO YeS nO y n Y N).each do |str|
it "string '#{str}' is an instance of Init[Boolean]" do
expect(eval_and_collect_notices("notice('#{str}' =~ Init[Boolean])")).to eql(['true'])
end
end
it 'arbitrary string is not an instance of Init[Boolean]' do
expect(eval_and_collect_notices("notice('blue' =~ Init[Boolean])")).to eql(['false'])
end
it 'empty string is not an instance of Init[Boolean]' do
expect(eval_and_collect_notices("notice('' =~ Init[Boolean])")).to eql(['false'])
end
it 'undef string is not an instance of Init[Boolean]' do
expect(eval_and_collect_notices("notice(undef =~ Init[Boolean])")).to eql(['false'])
end
%w(0 1 0634 0x3b -0xba 0b1001 +0b1111 23.14 -2.3 2e-21 1.23e18 -0.23e18).each do |str|
it "string '#{str}' is an instance of Init[Numeric]" do
expect(eval_and_collect_notices("notice('#{str}' =~ Init[Numeric])")).to eql(['true'])
end
end
it 'non numeric string is not an instance of Init[Numeric]' do
expect(eval_and_collect_notices("notice('blue' =~ Init[Numeric])")).to eql(['false'])
end
it 'empty string is not an instance of Init[Numeric]' do
expect(eval_and_collect_notices("notice('' =~ Init[Numeric])")).to eql(['false'])
end
it 'undef is not an instance of Init[Numeric]' do
expect(eval_and_collect_notices("notice(undef =~ Init[Numeric])")).to eql(['false'])
end
%w(0 1 0634 0x3b -0xba 0b1001 +0b1111 23.14 -2.3 2e-21 1.23e18 -0.23e18).each do |str|
it "string '#{str}' is an instance of Init[Float]" do
expect(eval_and_collect_notices("notice('#{str}' =~ Init[Float])")).to eql(['true'])
end
end
it 'non numeric string is not an instance of Init[Float]' do
expect(eval_and_collect_notices("notice('blue' =~ Init[Float])")).to eql(['false'])
end
it 'empty string is not an instance of Init[Float]' do
expect(eval_and_collect_notices("notice('' =~ Init[Float])")).to eql(['false'])
end
it 'undef is not an instance of Init[Float]' do
expect(eval_and_collect_notices("notice(undef =~ Init[Float])")).to eql(['false'])
end
%w(0 1 0634 0x3b -0xba 0b1001 0b1111).each do |str|
it "string '#{str}' is an instance of Init[Integer]" do
expect(eval_and_collect_notices("notice('#{str}' =~ Init[Integer])")).to eql(['true'])
end
end
%w(23.14 -2.3 2e-21 1.23e18 -0.23e18).each do |str|
it "valid float string '#{str}' is not an instance of Init[Integer]" do
expect(eval_and_collect_notices("notice('#{str}' =~ Init[Integer])")).to eql(['false'])
end
end
it 'non numeric string is not an instance of Init[Integer]' do
expect(eval_and_collect_notices("notice('blue' =~ Init[Integer])")).to eql(['false'])
end
it 'empty string is not an instance of Init[Integer]' do
expect(eval_and_collect_notices("notice('' =~ Init[Integer])")).to eql(['false'])
end
it 'undef is not an instance of Init[Integer]' do
expect(eval_and_collect_notices("notice(undef =~ Init[Integer])")).to eql(['false'])
end
%w(1.2.3 1.1.1-a3 1.2.3+b3 1.2.3-a3+b3).each do |str|
it "string '#{str}' is an instance of Init[SemVer]" do
expect(eval_and_collect_notices("notice('#{str}' =~ Init[SemVer])")).to eql(['true'])
end
end
it 'non SemVer compliant string is not an instance of Init[SemVer]' do
expect(eval_and_collect_notices("notice('blue' =~ Init[SemVer])")).to eql(['false'])
end
it 'empty string is not an instance of Init[SemVer]' do
expect(eval_and_collect_notices("notice('' =~ Init[SemVer])")).to eql(['false'])
end
it 'undef is not an instance of Init[SemVer]' do
expect(eval_and_collect_notices("notice(undef =~ Init[SemVer])")).to eql(['false'])
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/string_converter_spec.rb | spec/unit/pops/types/string_converter_spec.rb | require 'spec_helper'
require 'puppet/pops'
describe 'The string converter' do
let(:converter) { Puppet::Pops::Types::StringConverter.singleton }
let(:factory) { Puppet::Pops::Types::TypeFactory }
let(:format) { Puppet::Pops::Types::StringConverter::Format }
let(:binary) { Puppet::Pops::Types::PBinaryType::Binary }
describe 'helper Format' do
it 'parses a single character like "%d" as a format' do
fmt = format.new("%d")
expect(fmt.format()).to be(:d)
expect(fmt.alt()).to be(false)
expect(fmt.left()).to be(false)
expect(fmt.width()).to be_nil
expect(fmt.prec()).to be_nil
expect(fmt.plus()).to eq(:ignore)
end
it 'alternative form can be given with "%#d"' do
fmt = format.new("%#d")
expect(fmt.format()).to be(:d)
expect(fmt.alt()).to be(true)
end
it 'left adjust can be given with "%-d"' do
fmt = format.new("%-d")
expect(fmt.format()).to be(:d)
expect(fmt.left()).to be(true)
end
it 'plus sign can be used to indicate how positive numbers are displayed' do
fmt = format.new("%+d")
expect(fmt.format()).to be(:d)
expect(fmt.plus()).to eq(:plus)
end
it 'a space can be used to output " " instead of "+" for positive numbers' do
fmt = format.new("% d")
expect(fmt.format()).to be(:d)
expect(fmt.plus()).to eq(:space)
end
it 'padding with zero can be specified with a "0" flag' do
fmt = format.new("%0d")
expect(fmt.format()).to be(:d)
expect(fmt.zero_pad()).to be(true)
end
it 'width can be specified as an integer >= 1' do
fmt = format.new("%1d")
expect(fmt.format()).to be(:d)
expect(fmt.width()).to be(1)
fmt = format.new("%10d")
expect(fmt.width()).to be(10)
end
it 'precision can be specified as an integer >= 0' do
fmt = format.new("%.0d")
expect(fmt.format()).to be(:d)
expect(fmt.prec()).to be(0)
fmt = format.new("%.10d")
expect(fmt.prec()).to be(10)
end
it 'width and precision can both be specified' do
fmt = format.new("%2.3d")
expect(fmt.format()).to be(:d)
expect(fmt.width()).to be(2)
expect(fmt.prec()).to be(3)
end
[
'[', '{', '(', '<', '|',
].each do | delim |
it "a container delimiter pair can be set with '#{delim}'" do
fmt = format.new("%#{delim}d")
expect(fmt.format()).to be(:d)
expect(fmt.delimiters()).to eql(delim)
end
end
it "Is an error to specify different delimiters at the same time" do
expect do
format.new("%[{d")
end.to raise_error(/Only one of the delimiters/)
end
it "Is an error to have trailing characters after the format" do
expect do
format.new("%dv")
end.to raise_error(/The format '%dv' is not a valid format/)
end
it "Is an error to specify the same flag more than once" do
expect do
format.new("%[[d")
end.to raise_error(/The same flag can only be used once/)
end
end
context 'when converting to string' do
{
42 => "42",
3.14 => "3.140000",
"hello world" => "hello world",
"hello\tworld" => "hello\tworld",
}.each do |from, to|
it "the string value of #{from} is '#{to}'" do
expect(converter.convert(from, :default)).to eq(to)
end
end
it 'float point value decimal digits can be specified' do
string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => '%.2f'}
expect(converter.convert(3.14, string_formats)).to eq('3.14')
end
it 'when specifying format for one type, other formats are not affected' do
string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => '%.2f'}
expect(converter.convert('3.1415', string_formats)).to eq('3.1415')
end
context 'The %p format for string produces' do
let!(:string_formats) { { Puppet::Pops::Types::PStringType::DEFAULT => '%p'} }
it 'double quoted result for string that contains control characters' do
expect(converter.convert("hello\tworld.\r\nSun is brigth today.", string_formats)).to eq('"hello\\tworld.\\r\\nSun is brigth today."')
end
it 'single quoted result for string that is plain ascii without \\, $ or control characters' do
expect(converter.convert('hello world', string_formats)).to eq("'hello world'")
end
it 'double quoted result when using %#p if it would otherwise be single quoted' do
expect(converter.convert('hello world', '%#p')).to eq('"hello world"')
end
it 'quoted 5-byte unicode chars' do
expect(converter.convert("smile \u{1f603}.", string_formats)).to eq("'smile \u{1F603}.'")
end
it 'quoted 2-byte unicode chars' do
expect(converter.convert("esc \u{1b}.", string_formats)).to eq('"esc \\u{1B}."')
end
it 'escape for $ in double quoted string' do
# Use \n in string to force double quotes
expect(converter.convert("escape the $ sign\n", string_formats)).to eq('"escape the \$ sign\n"')
end
it 'no escape for $ in single quoted string' do
expect(converter.convert('don\'t escape the $ sign', string_formats)).to eq("'don\\'t escape the $ sign'")
end
it 'escape for double quote but not for single quote in double quoted string' do
# Use \n in string to force double quotes
expect(converter.convert("the ' single and \" double quote\n", string_formats)).to eq('"the \' single and \\" double quote\n"')
end
it 'escape for single quote but not for double quote in single quoted string' do
expect(converter.convert('the \' single and " double quote', string_formats)).to eq("'the \\' single and \" double quote'")
end
it 'no escape for #' do
expect(converter.convert('do not escape #{x}', string_formats)).to eq('\'do not escape #{x}\'')
end
it 'escape for last \\' do
expect(converter.convert('escape the last \\', string_formats)).to eq("'escape the last \\'")
end
end
{
'%s' => 'hello::world',
'%p' => "'hello::world'",
'%c' => 'Hello::world',
'%#c' => "'Hello::world'",
'%u' => 'HELLO::WORLD',
'%#u' => "'HELLO::WORLD'",
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => fmt}
expect(converter.convert('hello::world', string_formats)).to eq(result)
end
end
{
'%c' => 'Hello::world',
'%#c' => "'Hello::world'",
'%d' => 'hello::world',
'%#d' => "'hello::world'",
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => fmt}
expect(converter.convert('HELLO::WORLD', string_formats)).to eq(result)
end
end
{
[nil, '%.1p'] => 'u',
[nil, '%#.2p'] => '"u',
[:default, '%.1p'] => 'd',
[true, '%.2s'] => 'tr',
[true, '%.2y'] => 'ye',
}.each do |args, result |
it "the format #{args[1]} produces #{result} for value #{args[0]}" do
expect(converter.convert(*args)).to eq(result)
end
end
{
' a b ' => 'a b',
'a b ' => 'a b',
' a b' => 'a b',
}.each do |input, result |
it "the input #{input} is trimmed to #{result} by using format '%t'" do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%t'}
expect(converter.convert(input, string_formats)).to eq(result)
end
end
{
' a b ' => "'a b'",
'a b ' => "'a b'",
' a b' => "'a b'",
}.each do |input, result |
it "the input #{input} is trimmed to #{result} by using format '%#t'" do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%#t'}
expect(converter.convert(input, string_formats)).to eq(result)
end
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => "%k"}
converter.convert('wat', string_formats)
end.to raise_error(/Illegal format 'k' specified for value of String type - expected one of the characters 'cCudspt'/)
end
it 'Width pads a string left with spaces to given width' do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%6s'}
expect(converter.convert("abcd", string_formats)).to eq(' abcd')
end
it 'Width pads a string right with spaces to given width and - flag' do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%-6s'}
expect(converter.convert("abcd", string_formats)).to eq('abcd ')
end
it 'Precision truncates the string if precision < length' do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => '%-6.2s'}
expect(converter.convert("abcd", string_formats)).to eq('ab ')
end
{
'%4.2s' => ' he',
'%4.2p' => " 'h",
'%4.2c' => ' He',
'%#4.2c' => " 'H",
'%4.2u' => ' HE',
'%#4.2u' => " 'H",
'%4.2d' => ' he',
'%#4.2d' => " 'h"
}.each do |fmt, result |
it "width and precision can be combined with #{fmt}" do
string_formats = { Puppet::Pops::Types::PStringType::DEFAULT => fmt}
expect(converter.convert('hello::world', string_formats)).to eq(result)
end
end
end
context 'when converting integer' do
it 'the default string representation is decimal' do
expect(converter.convert(42, :default)).to eq('42')
end
{
'%s' => '18',
'%4.1s' => ' 1',
'%p' => '18',
'%4.2p' => ' 18',
'%4.1p' => ' 1',
'%#s' => '"18"',
'%#6.4s' => ' "18"',
'%#p' => '18',
'%#6.4p' => ' 18',
'%d' => '18',
'%4.1d' => ' 18',
'%4.3d' => ' 018',
'%x' => '12',
'%4.3x' => ' 012',
'%#x' => '0x12',
'%#6.4x' => '0x0012',
'%X' => '12',
'%4.3X' => ' 012',
'%#X' => '0X12',
'%#6.4X' => '0X0012',
'%o' => '22',
'%4.2o' => ' 22',
'%#o' => '022',
'%b' => '10010',
'%7.6b' => ' 010010',
'%#b' => '0b10010',
'%#9.6b' => ' 0b010010',
'%#B' => '0B10010',
'%#9.6B' => ' 0B010010',
# Integer to float then a float format - fully tested for float
'%e' => '1.800000e+01',
'%E' => '1.800000E+01',
'%f' => '18.000000',
'%g' => '18',
'%a' => '0x1.2p+4',
'%A' => '0X1.2P+4',
'%.1f' => '18.0',
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
pending("PUP-8612 %a and %A not support on JRuby") if RUBY_PLATFORM == 'java' && fmt =~ /^%[aA]$/
string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => fmt}
expect(converter.convert(18, string_formats)).to eq(result)
end
end
it 'the format %#6.4o produces 0022' do
string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => '%#6.4o' }
result = RUBY_PLATFORM == 'java' ? ' 00022' : ' 0022'
expect(converter.convert(18, string_formats)).to eq(result)
end
it 'produces a unicode char string by using format %c' do
string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => '%c'}
expect(converter.convert(0x1F603, string_formats)).to eq("\u{1F603}")
end
it 'produces a quoted unicode char string by using format %#c' do
string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => '%#c'}
expect(converter.convert(0x1F603, string_formats)).to eq("\"\u{1F603}\"")
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PIntegerType::DEFAULT => "%k"}
converter.convert(18, string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Integer type - expected one of the characters 'dxXobBeEfgGaAspc'/)
end
end
context 'when converting float' do
it 'the default string representation is decimal' do
expect(converter.convert(42.0, :default)).to eq('42.000000')
end
{
'%s' => '18.0',
'%#s' => '"18.0"',
'%5s' => ' 18.0',
'%#8s' => ' "18.0"',
'%05.1s' => ' 1',
'%p' => '18.0',
'%7.2p' => ' 18',
'%e' => '1.800000e+01',
'%+e' => '+1.800000e+01',
'% e' => ' 1.800000e+01',
'%.2e' => '1.80e+01',
'%10.2e' => ' 1.80e+01',
'%-10.2e' => '1.80e+01 ',
'%010.2e' => '001.80e+01',
'%E' => '1.800000E+01',
'%+E' => '+1.800000E+01',
'% E' => ' 1.800000E+01',
'%.2E' => '1.80E+01',
'%10.2E' => ' 1.80E+01',
'%-10.2E' => '1.80E+01 ',
'%010.2E' => '001.80E+01',
'%f' => '18.000000',
'%+f' => '+18.000000',
'% f' => ' 18.000000',
'%.2f' => '18.00',
'%10.2f' => ' 18.00',
'%-10.2f' => '18.00 ',
'%010.2f' => '0000018.00',
'%g' => '18',
'%5g' => ' 18',
'%05g' => '00018',
'%-5g' => '18 ',
'%5.4g' => ' 18', # precision has no effect
'%a' => '0x1.2p+4',
'%.4a' => '0x1.2000p+4',
'%10a' => ' 0x1.2p+4',
'%010a' => '0x001.2p+4',
'%-10a' => '0x1.2p+4 ',
'%A' => '0X1.2P+4',
'%.4A' => '0X1.2000P+4',
'%10A' => ' 0X1.2P+4',
'%-10A' => '0X1.2P+4 ',
'%010A' => '0X001.2P+4',
# integer formats fully tested for integer
'%d' => '18',
'%x' => '12',
'%X' => '12',
'%o' => '22',
'%b' => '10010',
'%#B' => '0B10010',
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
pending("PUP-8612 %a and %A not support on JRuby") if RUBY_PLATFORM == 'java' && fmt =~ /^%[-.014]*[aA]$/
string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => fmt}
expect(converter.convert(18.0, string_formats)).to eq(result)
end
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PFloatType::DEFAULT => "%k"}
converter.convert(18.0, string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Float type - expected one of the characters 'dxXobBeEfgGaAsp'/)
end
end
context 'when converting undef' do
it 'the default string representation is empty string' do
expect(converter.convert(nil, :default)).to eq('')
end
{ "%u" => "undef",
"%#u" => "undefined",
"%s" => "",
"%#s" => '""',
"%p" => 'undef',
"%#p" => '"undef"',
"%n" => 'nil',
"%#n" => 'null',
"%v" => 'n/a',
"%V" => 'N/A',
"%d" => 'NaN',
"%x" => 'NaN',
"%o" => 'NaN',
"%b" => 'NaN',
"%B" => 'NaN',
"%e" => 'NaN',
"%E" => 'NaN',
"%f" => 'NaN',
"%g" => 'NaN',
"%G" => 'NaN',
"%a" => 'NaN',
"%A" => 'NaN',
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PUndefType::DEFAULT => fmt}
expect(converter.convert(nil, string_formats)).to eq(result)
end
end
{ "%7u" => " undef",
"%-7u" => "undef ",
"%#10u" => " undefined",
"%#-10u" => "undefined ",
"%7.2u" => " un",
"%4s" => " ",
"%#4s" => ' ""',
"%7p" => ' undef',
"%7.1p" => ' u',
"%#8p" => ' "undef"',
"%5n" => ' nil',
"%.1n" => 'n',
"%-5n" => 'nil ',
"%#5n" => ' null',
"%#-5n" => 'null ',
"%5v" => ' n/a',
"%5.2v" => ' n/',
"%-5v" => 'n/a ',
"%5V" => ' N/A',
"%5.1V" => ' N',
"%-5V" => 'N/A ',
"%5d" => ' NaN',
"%5.2d" => ' Na',
"%-5d" => 'NaN ',
"%5x" => ' NaN',
"%5.2x" => ' Na',
"%-5x" => 'NaN ',
"%5o" => ' NaN',
"%5.2o" => ' Na',
"%-5o" => 'NaN ',
"%5b" => ' NaN',
"%5.2b" => ' Na',
"%-5b" => 'NaN ',
"%5B" => ' NaN',
"%5.2B" => ' Na',
"%-5B" => 'NaN ',
"%5e" => ' NaN',
"%5.2e" => ' Na',
"%-5e" => 'NaN ',
"%5E" => ' NaN',
"%5.2E" => ' Na',
"%-5E" => 'NaN ',
"%5f" => ' NaN',
"%5.2f" => ' Na',
"%-5f" => 'NaN ',
"%5g" => ' NaN',
"%5.2g" => ' Na',
"%-5g" => 'NaN ',
"%5G" => ' NaN',
"%5.2G" => ' Na',
"%-5G" => 'NaN ',
"%5a" => ' NaN',
"%5.2a" => ' Na',
"%-5a" => 'NaN ',
"%5A" => ' NaN',
"%5.2A" => ' Na',
"%-5A" => 'NaN ',
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PUndefType::DEFAULT => fmt}
expect(converter.convert(nil, string_formats)).to eq(result)
end
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PUndefType::DEFAULT => "%k"}
converter.convert(nil, string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Undef type - expected one of the characters 'nudxXobBeEfgGaAvVsp'/)
end
end
context 'when converting default' do
it 'the default string representation is unquoted "default"' do
expect(converter.convert(:default, :default)).to eq('default')
end
{ "%d" => 'default',
"%D" => 'Default',
"%#d" => '"default"',
"%#D" => '"Default"',
"%s" => 'default',
"%p" => 'default',
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PDefaultType::DEFAULT => fmt}
expect(converter.convert(:default, string_formats)).to eq(result)
end
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PDefaultType::DEFAULT => "%k"}
converter.convert(:default, string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Default type - expected one of the characters 'dDsp'/)
end
end
context 'when converting boolean true' do
it 'the default string representation is unquoted "true"' do
expect(converter.convert(true, :default)).to eq('true')
end
{ "%t" => 'true',
"%#t" => 't',
"%T" => 'True',
"%#T" => 'T',
"%s" => 'true',
"%p" => 'true',
"%d" => '1',
"%x" => '1',
"%#x" => '0x1',
"%o" => '1',
"%#o" => '01',
"%b" => '1',
"%#b" => '0b1',
"%#B" => '0B1',
"%e" => '1.000000e+00',
"%f" => '1.000000',
"%g" => '1',
"%a" => '0x1p+0',
"%A" => '0X1P+0',
"%.1f" => '1.0',
"%y" => 'yes',
"%Y" => 'Yes',
"%#y" => 'y',
"%#Y" => 'Y',
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
pending("PUP-8612 %a and %A not support on JRuby") if RUBY_PLATFORM == 'java' && fmt =~ /^%[aA]$/
string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => fmt}
expect(converter.convert(true, string_formats)).to eq(result)
end
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => "%k"}
converter.convert(true, string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Boolean type - expected one of the characters 'tTyYdxXobBeEfgGaAsp'/)
end
end
context 'when converting boolean false' do
it 'the default string representation is unquoted "false"' do
expect(converter.convert(false, :default)).to eq('false')
end
{ "%t" => 'false',
"%#t" => 'f',
"%T" => 'False',
"%#T" => 'F',
"%s" => 'false',
"%p" => 'false',
"%d" => '0',
"%x" => '0',
"%#x" => '0',
"%o" => '0',
"%#o" => '0',
"%b" => '0',
"%#b" => '0',
"%#B" => '0',
"%e" => '0.000000e+00',
"%E" => '0.000000E+00',
"%f" => '0.000000',
"%g" => '0',
"%a" => '0x0p+0',
"%A" => '0X0P+0',
"%.1f" => '0.0',
"%y" => 'no',
"%Y" => 'No',
"%#y" => 'n',
"%#Y" => 'N',
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
pending("PUP-8612 %a and %A not support on JRuby") if RUBY_PLATFORM == 'java' && fmt =~ /^%[aA]$/
string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => fmt}
expect(converter.convert(false, string_formats)).to eq(result)
end
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PBooleanType::DEFAULT => "%k"}
converter.convert(false, string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Boolean type - expected one of the characters 'tTyYdxXobBeEfgGaAsp'/)
end
end
context 'when converting array' do
it 'the default string representation is using [] delimiters, joins with ',' and uses %p for values' do
expect(converter.convert(["hello", "world"], :default)).to eq("['hello', 'world']")
end
{ "%s" => "[1, 'hello']",
"%p" => "[1, 'hello']",
"%a" => "[1, 'hello']",
"%<a" => "<1, 'hello'>",
"%[a" => "[1, 'hello']",
"%(a" => "(1, 'hello')",
"%{a" => "{1, 'hello'}",
"% a" => "1, 'hello'",
{'format' => '%(a',
'separator' => ' '
} => "(1 'hello')",
{'format' => '%(a',
'separator' => ''
} => "(1'hello')",
{'format' => '%|a',
'separator' => ' '
} => "|1 'hello'|",
{'format' => '%(a',
'separator' => ' ',
'string_formats' => {Puppet::Pops::Types::PIntegerType::DEFAULT => '%#x'}
} => "(0x1 'hello')",
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => fmt}
expect(converter.convert([1, "hello"], string_formats)).to eq(result)
end
end
it "multiple rules selects most specific" do
short_array_t = factory.array_of(factory.integer, factory.range(1,2))
long_array_t = factory.array_of(factory.integer, factory.range(3,100))
string_formats = {
short_array_t => "%(a",
long_array_t => "%[a",
}
expect(converter.convert([1, 2], string_formats)).to eq('(1, 2)') unless RUBY_PLATFORM == 'java' # PUP-8615
expect(converter.convert([1, 2, 3], string_formats)).to eq('[1, 2, 3]')
end
it 'indents elements in alternate mode' do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#a', 'separator' =>", " } }
# formatting matters here
result = [
"[1, 2, 9, 9,",
" [3, 4],",
" [5,",
" [6, 7]],",
" 8, 9]"
].join("\n")
formatted = converter.convert([1, 2, 9, 9, [3, 4], [5, [6, 7]], 8, 9], string_formats)
expect(formatted).to eq(result)
end
it 'applies a short form format' do
result = [
"[1,",
" [2, 3],",
" 4]"
].join("\n")
expect(converter.convert([1, [2,3], 4], '%#a')).to eq(result)
end
it 'treats hashes as nested arrays wrt indentation' do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#a', 'separator' =>", " } }
# formatting matters here
result = [
"[1, 2, 9, 9,",
" {3 => 4, 5 => 6},",
" [5,",
" [6, 7]],",
" 8, 9]"
].join("\n")
formatted = converter.convert([1, 2, 9, 9, {3 => 4, 5 => 6}, [5, [6, 7]], 8, 9], string_formats)
expect(formatted).to eq(result)
end
it 'indents and breaks when a sequence > given width, in alternate mode' do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#3a', 'separator' =>", " } }
# formatting matters here
result = [
"[ 1,",
" 2,",
" 90,", # this sequence has length 4 (1,2,90) which is > 3
" [3, 4],",
" [5,",
" [6, 7]],",
" 8,",
" 9]",
].join("\n")
formatted = converter.convert([1, 2, 90, [3, 4], [5, [6, 7]], 8, 9], string_formats)
expect(formatted).to eq(result)
end
it 'indents and breaks when a sequence (placed last) > given width, in alternate mode' do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#3a', 'separator' =>", " } }
# formatting matters here
result = [
"[ 1,",
" 2,",
" 9,", # this sequence has length 3 (1,2,9) which does not cause breaking on each
" [3, 4],",
" [5,",
" [6, 7]],",
" 8,",
" 900]", # this sequence has length 4 (8, 900) which causes breaking on each
].join("\n")
formatted = converter.convert([1, 2, 9, [3, 4], [5, [6, 7]], 8, 900], string_formats)
expect(formatted).to eq(result)
end
it 'indents and breaks nested sequences when one is placed first' do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#a', 'separator' =>", " } }
# formatting matters here
result = [
"[",
" [",
" [1, 2,",
" [3, 4]]],",
" [5,",
" [6, 7]],",
" 8, 900]",
].join("\n")
formatted = converter.convert([[[1, 2, [3, 4]]], [5, [6, 7]], 8, 900], string_formats)
expect(formatted).to eq(result)
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => "%k"}
converter.convert([1,2], string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Array type - expected one of the characters 'asp'/)
end
end
context 'when converting hash' do
it 'the default string representation is using {} delimiters, joins with '=>' and uses %p for values' do
expect(converter.convert({"hello" => "world"}, :default)).to eq("{'hello' => 'world'}")
end
{ "%s" => "{1 => 'world'}",
"%p" => "{1 => 'world'}",
"%h" => "{1 => 'world'}",
"%a" => "[[1, 'world']]",
"%<h" => "<1 => 'world'>",
"%[h" => "[1 => 'world']",
"%(h" => "(1 => 'world')",
"%{h" => "{1 => 'world'}",
"% h" => "1 => 'world'",
{'format' => '%(h',
'separator2' => ' '
} => "(1 'world')",
{'format' => '%(h',
'separator2' => ' ',
'string_formats' => {Puppet::Pops::Types::PIntegerType::DEFAULT => '%#x'}
} => "(0x1 'world')",
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => fmt}
expect(converter.convert({1 => "world"}, string_formats)).to eq(result)
end
end
{ "%s" => "{1 => 'hello', 2 => 'world'}",
{'format' => '%(h',
'separator2' => ' '
} => "(1 'hello', 2 'world')",
{'format' => '%(h',
'separator' => '',
'separator2' => ''
} => "(1'hello'2'world')",
{'format' => '%(h',
'separator' => ' >> ',
'separator2' => ' <=> ',
'string_formats' => {Puppet::Pops::Types::PIntegerType::DEFAULT => '%#x'}
} => "(0x1 <=> 'hello' >> 0x2 <=> 'world')",
}.each do |fmt, result |
it "the format #{fmt} produces #{result}" do
string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => fmt}
expect(converter.convert({1 => "hello", 2 => "world"}, string_formats)).to eq(result)
end
end
it 'indents elements in alternative mode #' do
string_formats = {
Puppet::Pops::Types::PHashType::DEFAULT => {
'format' => '%#h',
}
}
# formatting matters here
result = [
"{",
" 1 => 'hello',",
" 2 => {",
" 3 => 'world'",
" }",
"}"
].join("\n")
expect(converter.convert({1 => "hello", 2 => {3=> "world"}}, string_formats)).to eq(result)
end
it 'applies a short form format' do
result = [
"{",
" 1 => {",
" 2 => 3",
" },",
" 4 => 5",
"}"].join("\n")
expect(converter.convert({1 => {2 => 3}, 4 => 5}, '%#h')).to eq(result)
end
context "containing an array" do
it 'the hash and array renders without breaks and indentation by default' do
result = "{1 => [1, 2, 3]}"
formatted = converter.convert({ 1 => [1, 2, 3] }, :default)
expect(formatted).to eq(result)
end
it 'the array renders with breaks if so specified' do
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#1a', 'separator' =>"," } }
result = [
"{1 => [ 1,",
" 2,",
" 3]}"
].join("\n")
formatted = converter.convert({ 1 => [1, 2, 3] }, string_formats)
expect(formatted).to eq(result)
end
it 'both hash and array renders with breaks and indentation if so specified for both' do
string_formats = {
Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#1a', 'separator' =>", " },
Puppet::Pops::Types::PHashType::DEFAULT => { 'format' => '%#h', 'separator' =>"," }
}
result = [
"{",
" 1 => [ 1,",
" 2,",
" 3]",
"}"
].join("\n")
formatted = converter.convert({ 1 => [1, 2, 3] }, string_formats)
expect(formatted).to eq(result)
end
it 'hash, but not array is rendered with breaks and indentation if so specified only for the hash' do
string_formats = {
Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%a', 'separator' =>", " },
Puppet::Pops::Types::PHashType::DEFAULT => { 'format' => '%#h', 'separator' =>"," }
}
result = [
"{",
" 1 => [1, 2, 3]",
"}"
].join("\n")
formatted = converter.convert({ 1 => [1, 2, 3] }, string_formats)
expect(formatted).to eq(result)
end
end
context 'that is subclassed' do
let(:array) { ['a', 2] }
let(:derived_array) do
Class.new(Array) do
def to_a
self # Dead wrong! Should return a plain Array copy
end
end.new(array)
end
let(:derived_with_to_a) do
Class.new(Array) do
def to_a
super
end
end.new(array)
end
let(:hash) { {'first' => 1, 'second' => 2} }
let(:derived_hash) do
Class.new(Hash)[hash]
end
let(:derived_with_to_hash) do
Class.new(Hash) do
def to_hash
{}.merge(self)
end
end[hash]
end
it 'formats a derived array as a Runtime' do
expect(converter.convert(array)).to eq('[\'a\', 2]')
expect(converter.convert(derived_array)).to eq('["a", 2]')
end
it 'formats a derived array with #to_a retuning plain Array as an Array' do
expect(converter.convert(derived_with_to_a)).to eq('[\'a\', 2]')
end
it 'formats a derived hash as a Runtime' do
expect(converter.convert(hash)).to eq('{\'first\' => 1, \'second\' => 2}')
expect(converter.convert(derived_hash)).to eq('{"first"=>1, "second"=>2}')
end
it 'formats a derived hash with #to_hash retuning plain Hash as a Hash' do
expect(converter.convert(derived_with_to_hash, '%p')).to eq('{\'first\' => 1, \'second\' => 2}')
end
end
it 'errors when format is not recognized' do
expect do
string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => "%k"}
converter.convert({1 => 2}, string_formats)
end.to raise_error(/Illegal format 'k' specified for value of Hash type - expected one of the characters 'hasp'/)
end
end
context 'when converting a runtime type' do
[ :sym, (1..3), Time.now ].each do |value|
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_object_type_spec.rb | spec/unit/pops/types/p_object_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'The Object Type' do
include PuppetSpec::Compiler
let(:parser) { TypeParser.singleton }
let(:pp_parser) { Parser::EvaluatingParser.new }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:node) { Puppet::Node.new('testnode', :environment => env) }
let(:loader) { Loaders.find_loader(nil) }
let(:factory) { TypeFactory }
before(:each) do
Puppet.push_context(:loaders => Loaders.new(env))
end
after(:each) do
Puppet.pop_context()
end
def type_object_t(name, body_string)
object = PObjectType.new(name, pp_parser.parse_string("{#{body_string}}").body)
loader.set_entry(Loader::TypedName.new(:type, name), object)
object
end
def parse_object(name, body_string)
type_object_t(name, body_string)
parser.parse(name, loader).resolve(loader)
end
context 'when dealing with attributes' do
it 'raises an error when the attribute type is not a type' do
obj = <<-OBJECT
attributes => {
a => 23
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError,
/attribute MyObject\[a\] has wrong type, expects a Type value, got Integer/)
end
it 'raises an error if the type is missing' do
obj = <<-OBJECT
attributes => {
a => { kind => derived }
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError,
/expects a value for key 'type'/)
end
it 'raises an error when value is of incompatible type' do
obj = <<-OBJECT
attributes => {
a => { type => Integer, value => 'three' }
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError,
/attribute MyObject\[a\] value has wrong type, expects an Integer value, got String/)
end
it 'raises an error if the kind is invalid' do
obj = <<-OBJECT
attributes => {
a => { type => String, kind => derivd }
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError,
/expects a match for Enum\['constant', 'derived', 'given_or_derived', 'reference'\], got 'derivd'/)
end
it 'raises an error if the name is __ptype' do
obj = <<-OBJECT
attributes => {
__ptype => String
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
/The attribute '__ptype' is reserved and cannot be used/)
end
it 'raises an error if the name is __pvalue' do
obj = <<-OBJECT
attributes => {
__pvalue => String
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
/The attribute '__pvalue' is reserved and cannot be used/)
end
it 'stores value in attribute' do
tp = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer, value => 3 }
}
OBJECT
attr = tp['a']
expect(attr).to be_a(PObjectType::PAttribute)
expect(attr.value).to eql(3)
end
it 'attribute with defined value responds true to value?' do
tp = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer, value => 3 }
}
OBJECT
attr = tp['a']
expect(attr.value?).to be_truthy
end
it 'attribute value can be defined using heredoc?' do
tp = parse_object('MyObject', <<-OBJECT.unindent)
attributes => {
a => { type => String, value => @(END) }
The value is some
multiline text
|-END
}
OBJECT
attr = tp['a']
expect(attr.value).to eql("The value is some\nmultiline text")
end
it 'attribute without defined value responds false to value?' do
tp = parse_object('MyObject', <<-OBJECT)
attributes => {
a => Integer
}
OBJECT
attr = tp['a']
expect(attr.value?).to be_falsey
end
it 'attribute without defined value but optional type responds true to value?' do
tp = parse_object('MyObject', <<-OBJECT)
attributes => {
a => Optional[Integer]
}
OBJECT
attr = tp['a']
expect(attr.value?).to be_truthy
expect(attr.value).to be_nil
end
it 'raises an error when value is requested from an attribute that has no value' do
tp = parse_object('MyObject', <<-OBJECT)
attributes => {
a => Integer
}
OBJECT
expect { tp['a'].value }.to raise_error(Puppet::Error, 'attribute MyObject[a] has no value')
end
context 'that are constants' do
context 'and declared under key "constants"' do
it 'sets final => true' do
tp = parse_object('MyObject', <<-OBJECT)
constants => {
a => 3
}
OBJECT
expect(tp['a'].final?).to be_truthy
end
it 'sets kind => constant' do
tp = parse_object('MyObject', <<-OBJECT)
constants => {
a => 3
}
OBJECT
expect(tp['a'].constant?).to be_truthy
end
it 'infers generic type from value' do
tp = parse_object('MyObject', <<-OBJECT)
constants => {
a => 3
}
OBJECT
expect(tp['a'].type.to_s).to eql('Integer')
end
it 'cannot have the same name as an attribute' do
obj = <<-OBJECT
constants => {
a => 3
},
attributes => {
a => Integer
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
'attribute MyObject[a] is defined as both a constant and an attribute')
end
end
context 'and declared under key "attributes"' do
it 'sets final => true when declard in attributes' do
tp = parse_object('MyObject', <<-OBJECT)
attributes => {
a => {
type => Integer,
kind => constant,
value => 3
}
}
OBJECT
expect(tp['a'].final?).to be_truthy
end
it 'raises an error when no value is declared' do
obj = <<-OBJECT
attributes => {
a => {
type => Integer,
kind => constant
}
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
"attribute MyObject[a] of kind 'constant' requires a value")
end
it 'raises an error when final => false' do
obj = <<-OBJECT
attributes => {
a => {
type => Integer,
kind => constant,
final => false
}
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
"attribute MyObject[a] of kind 'constant' cannot be combined with final => false")
end
end
end
end
context 'when dealing with functions' do
it 'raises an error unless the function type is a Type[Callable]' do
obj = <<-OBJECT
functions => {
a => String
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError,
/function MyObject\[a\] has wrong type, expects a Type\[Callable\] value, got Type\[String\]/)
end
it 'raises an error when a function has the same name as an attribute' do
obj = <<-OBJECT
attributes => {
a => Integer
},
functions => {
a => Callable
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
'function MyObject[a] conflicts with attribute with the same name')
end
end
context 'when dealing with overrides' do
it 'can redefine inherited member to assignable type' do
parent = <<-OBJECT
attributes => {
a => Integer
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
a => { type => Integer[0,10], override => true }
}
OBJECT
parse_object('MyObject', parent)
tp = parse_object('MyDerivedObject', obj)
expect(tp['a'].type).to eql(PIntegerType.new(0,10))
end
it 'can redefine inherited constant to assignable type' do
parent = <<-OBJECT
constants => {
a => 23
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
constants => {
a => 46
}
OBJECT
tp = parse_object('MyObject', parent)
td = parse_object('MyDerivedObject', obj)
expect(tp['a'].value).to eql(23)
expect(td['a'].value).to eql(46)
end
it 'raises an error when an attribute overrides a function' do
parent = <<-OBJECT
attributes => {
a => Integer
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
functions => {
a => { type => Callable, override => true }
}
OBJECT
parse_object('MyObject', parent)
expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError,
'function MyDerivedObject[a] attempts to override attribute MyObject[a]')
end
it 'raises an error when the a function overrides an attribute' do
parent = <<-OBJECT
functions => {
a => Callable
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
a => { type => Integer, override => true }
}
OBJECT
parse_object('MyObject', parent)
expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError,
'attribute MyDerivedObject[a] attempts to override function MyObject[a]')
end
it 'raises an error on attempts to redefine inherited member to unassignable type' do
parent = <<-OBJECT
attributes => {
a => Integer
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
a => { type => String, override => true }
}
OBJECT
parse_object('MyObject', parent)
expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError,
'attribute MyDerivedObject[a] attempts to override attribute MyObject[a] with a type that does not match')
end
it 'raises an error when an attribute overrides a final attribute' do
parent = <<-OBJECT
attributes => {
a => { type => Integer, final => true }
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
a => { type => Integer, override => true }
}
OBJECT
parse_object('MyObject', parent)
expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError,
'attribute MyDerivedObject[a] attempts to override final attribute MyObject[a]')
end
it 'raises an error when an overriding attribute is not declared with override => true' do
parent = <<-OBJECT
attributes => {
a => Integer
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
a => Integer
}
OBJECT
parse_object('MyObject', parent)
expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError,
'attribute MyDerivedObject[a] attempts to override attribute MyObject[a] without having override => true')
end
it 'raises an error when an attribute declared with override => true does not override' do
parent = <<-OBJECT
attributes => {
a => Integer
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
b => { type => Integer, override => true }
}
OBJECT
parse_object('MyObject', parent)
expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError,
"expected attribute MyDerivedObject[b] to override an inherited attribute, but no such attribute was found")
end
end
context 'when dealing with equality' do
it 'the attributes can be declared as an array of names' do
obj = <<-OBJECT
attributes => {
a => Integer,
b => Integer
},
equality => [a,b]
OBJECT
tp = parse_object('MyObject', obj)
expect(tp.equality).to eq(['a','b'])
expect(tp.equality_attributes.keys).to eq(['a','b'])
end
it 'a single [<name>] can be declared as <name>' do
obj = <<-OBJECT
attributes => {
a => Integer,
b => Integer
},
equality => a
OBJECT
tp = parse_object('MyObject', obj)
expect(tp.equality).to eq(['a'])
end
it 'includes all non-constant attributes by default' do
obj = <<-OBJECT
attributes => {
a => Integer,
b => { type => Integer, kind => constant, value => 3 },
c => Integer
}
OBJECT
tp = parse_object('MyObject', obj)
expect(tp.equality).to be_nil
expect(tp.equality_attributes.keys).to eq(['a','c'])
end
it 'equality_include_type is true by default' do
obj = <<-OBJECT
attributes => {
a => Integer
},
equality => a
OBJECT
expect(parse_object('MyObject', obj).equality_include_type?).to be_truthy
end
it 'will allow an empty list of attributes' do
obj = <<-OBJECT
attributes => {
a => Integer,
b => Integer
},
equality => []
OBJECT
tp = parse_object('MyObject', obj)
expect(tp.equality).to be_empty
expect(tp.equality_attributes).to be_empty
end
it 'will extend default equality in parent' do
parent = <<-OBJECT
attributes => {
a => Integer,
b => Integer
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
c => Integer,
d => Integer
}
OBJECT
parse_object('MyObject', parent)
tp = parse_object('MyDerivedObject', obj)
expect(tp.equality).to be_nil
expect(tp.equality_attributes.keys).to eq(['a','b','c','d'])
end
it 'extends equality declared in parent' do
parent = <<-OBJECT
attributes => {
a => Integer,
b => Integer
},
equality => a
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
c => Integer,
d => Integer
}
OBJECT
parse_object('MyObject', parent)
tp = parse_object('MyDerivedObject', obj)
expect(tp.equality).to be_nil
expect(tp.equality_attributes.keys).to eq(['a','c','d'])
end
it 'parent defined attributes can be included in equality if not already included by a parent' do
parent = <<-OBJECT
attributes => {
a => Integer,
b => Integer
},
equality => a
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
c => Integer,
d => Integer
},
equality => [b,c]
OBJECT
parse_object('MyObject', parent)
tp = parse_object('MyDerivedObject', obj)
expect(tp.equality).to eq(['b','c'])
expect(tp.equality_attributes.keys).to eq(['a','b','c'])
end
it 'raises an error when attempting to extend default equality in parent' do
parent = <<-OBJECT
attributes => {
a => Integer,
b => Integer
}
OBJECT
obj = <<-OBJECT
parent => MyObject,
attributes => {
c => Integer,
d => Integer
},
equality => a
OBJECT
parse_object('MyObject', parent)
expect { parse_object('MyDerivedObject', obj) }.to raise_error(Puppet::ParseError,
"MyDerivedObject equality is referencing attribute MyObject[a] which is included in equality of MyObject")
end
it 'raises an error when equality references a constant attribute' do
obj = <<-OBJECT
attributes => {
a => Integer,
b => { type => Integer, kind => constant, value => 3 }
},
equality => [a,b]
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
'MyObject equality is referencing constant attribute MyObject[b]. Reference to constant is not allowed in equality')
end
it 'raises an error when equality references a function' do
obj = <<-OBJECT
attributes => {
a => Integer,
},
functions => {
b => Callable
},
equality => [a,b]
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
'MyObject equality is referencing function MyObject[b]. Only attribute references are allowed')
end
it 'raises an error when equality references a non existent attributes' do
obj = <<-OBJECT
attributes => {
a => Integer
},
equality => [a,b]
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
"MyObject equality is referencing non existent attribute 'b'")
end
it 'raises an error when equality_include_type = false and attributes are provided' do
obj = <<-OBJECT
attributes => {
a => Integer
},
equality => a,
equality_include_type => false
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(Puppet::ParseError,
'equality_include_type = false cannot be combined with non empty equality specification')
end
end
it 'raises an error when initialization hash contains invalid keys' do
obj = <<-OBJECT
attribrutes => {
a => Integer
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /object initializer has wrong type, unrecognized key 'attribrutes'/)
end
it 'raises an error when attribute contains invalid keys' do
obj = <<-OBJECT
attributes => {
a => { type => Integer, knid => constant }
}
OBJECT
expect { parse_object('MyObject', obj) }.to raise_error(TypeAssertionError, /initializer for attribute MyObject\[a\] has wrong type, unrecognized key 'knid'/)
end
context 'when inheriting from a another Object type' do
let(:parent) { <<-OBJECT }
attributes => {
a => Integer
},
functions => {
b => Callable
}
OBJECT
let(:derived) { <<-OBJECT }
parent => MyObject,
attributes => {
c => String,
d => Boolean
}
OBJECT
it 'includes the inherited type and its members' do
parse_object('MyObject', parent)
t = parse_object('MyDerivedObject', derived)
members = t.members.values
expect{ |b| members.each {|m| m.name.tap(&b) }}.to yield_successive_args('c', 'd')
expect{ |b| members.each {|m| m.type.simple_name.tap(&b) }}.to yield_successive_args('String', 'Boolean')
members = t.members(true).values
expect{ |b| members.each {|m| m.name.tap(&b) }}.to yield_successive_args('a', 'b', 'c', 'd')
expect{ |b| members.each {|m| m.type.simple_name.tap(&b) }}.to(yield_successive_args('Integer', 'Callable', 'String', 'Boolean'))
end
it 'is assignable to its inherited type' do
p = parse_object('MyObject', parent)
t = parse_object('MyDerivedObject', derived)
expect(p).to be_assignable(t)
end
it 'does not consider inherited type to be assignable' do
p = parse_object('MyObject', parent)
d = parse_object('MyDerivedObject', derived)
expect(d).not_to be_assignable(p)
end
it 'ruby access operator can retrieve parent member' do
p = parse_object('MyObject', parent)
d = parse_object('MyDerivedObject', derived)
expect(d['b'].container).to equal(p)
end
context 'that in turn inherits another Object type' do
let(:derived2) { <<-OBJECT }
parent => MyDerivedObject,
attributes => {
e => String,
f => Boolean
}
OBJECT
it 'is assignable to all inherited types' do
p = parse_object('MyObject', parent)
d1 = parse_object('MyDerivedObject', derived)
d2 = parse_object('MyDerivedObject2', derived2)
expect(p).to be_assignable(d2)
expect(d1).to be_assignable(d2)
end
it 'does not consider any of the inherited types to be assignable' do
p = parse_object('MyObject', parent)
d1 = parse_object('MyDerivedObject', derived)
d2 = parse_object('MyDerivedObject2', derived2)
expect(d2).not_to be_assignable(p)
expect(d2).not_to be_assignable(d1)
end
end
end
context 'when producing an init_hash_type' do
it 'produces a struct of all attributes that are not derived or constant' do
t = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer },
b => { type => Integer, kind => given_or_derived },
c => { type => Integer, kind => derived },
d => { type => Integer, kind => constant, value => 4 }
}
OBJECT
expect(t.init_hash_type).to eql(factory.struct({
'a' => factory.integer,
'b' => factory.integer
}))
end
it 'produces a struct where optional entires are denoted with an optional key' do
t = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer },
b => { type => Integer, value => 4 }
}
OBJECT
expect(t.init_hash_type).to eql(factory.struct({
'a' => factory.integer,
factory.optional('b') => factory.integer
}))
end
it 'produces a struct that includes parameters from parent type' do
t1 = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer }
}
OBJECT
t2 = parse_object('MyDerivedObject', <<-OBJECT)
parent => MyObject,
attributes => {
b => { type => Integer }
}
OBJECT
expect(t1.init_hash_type).to eql(factory.struct({ 'a' => factory.integer }))
expect(t2.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, 'b' => factory.integer }))
end
it 'produces a struct that reflects overrides made in derived type' do
t1 = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer },
b => { type => Integer }
}
OBJECT
t2 = parse_object('MyDerivedObject', <<-OBJECT)
parent => MyObject,
attributes => {
b => { type => Integer, override => true, value => 5 }
}
OBJECT
expect(t1.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, 'b' => factory.integer }))
expect(t2.init_hash_type).to eql(factory.struct({ 'a' => factory.integer, factory.optional('b') => factory.integer }))
end
end
context 'with attributes and parameters of its own type' do
it 'resolves an attribute type' do
t = parse_object('MyObject', <<-OBJECT)
attributes => {
a => MyObject
}
OBJECT
expect(t['a'].type).to equal(t)
end
it 'resolves a parameter type' do
t = parse_object('MyObject', <<-OBJECT)
functions => {
a => Callable[MyObject]
}
OBJECT
expect(t['a'].type).to eql(PCallableType.new(PTupleType.new([t])))
end
end
context 'when using the initialization hash' do
it 'produced hash that contains features using short form (type instead of detailed hash when only type is declared)' do
obj = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer }
}
OBJECT
expect(obj.to_s).to eql("Object[{name => 'MyObject', attributes => {'a' => Integer}}]")
end
it 'produced hash that does not include default for equality_include_type' do
obj = parse_object('MyObject', <<-OBJECT)
attributes => { a => Integer },
equality_include_type => true
OBJECT
expect(obj.to_s).to eql("Object[{name => 'MyObject', attributes => {'a' => Integer}}]")
end
it 'constants are presented in a separate hash if they use a generic type' do
obj = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer, value => 23, kind => constant },
},
OBJECT
expect(obj.to_s).to eql("Object[{name => 'MyObject', constants => {'a' => 23}}]")
end
it 'constants are not presented in a separate hash unless they use a generic type' do
obj = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer[0, 30], value => 23, kind => constant },
},
OBJECT
expect(obj.to_s).to eql("Object[{name => 'MyObject', attributes => {'a' => {type => Integer[0, 30], kind => constant, value => 23}}}]")
end
it 'can create an equal copy from produced hash' do
obj = parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Struct[{x => Integer, y => Integer}], value => {x => 4, y => 9}, kind => constant },
b => Integer
},
functions => {
x => Callable[MyObject,Integer]
},
equality => [b]
OBJECT
obj2 = PObjectType.new(obj._pcore_init_hash)
expect(obj).to eql(obj2)
end
end
context 'when stringifying created instances' do
it 'outputs a Puppet constructor using the initializer hash' do
code = <<-CODE
type Spec::MyObject = Object[{attributes => { a => Integer }}]
type Spec::MySecondObject = Object[{parent => Spec::MyObject, attributes => { b => String }}]
notice(Spec::MySecondObject(42, 'Meaning of life'))
CODE
expect(eval_and_collect_notices(code)).to eql(["Spec::MySecondObject({'a' => 42, 'b' => 'Meaning of life'})"])
end
end
context 'when used from Ruby' do
it 'can create an instance without scope using positional arguments' do
parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer }
}
OBJECT
t = Puppet::Pops::Types::TypeParser.singleton.parse('MyObject', Puppet::Pops::Loaders.find_loader(nil))
instance = t.create(32)
expect(instance.a).to eql(32)
end
it 'can create an instance without scope using initialization hash' do
parse_object('MyObject', <<-OBJECT)
attributes => {
a => { type => Integer }
}
OBJECT
t = Puppet::Pops::Types::TypeParser.singleton.parse('MyObject', Puppet::Pops::Loaders.find_loader(nil))
instance = t.from_hash('a' => 32)
expect(instance.a).to eql(32)
end
end
context 'when used in Puppet expressions' do
it 'two anonymous empty objects are equal' do
code = <<-CODE
$x = Object[{}]
$y = Object[{}]
notice($x == $y)
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'two objects where one object inherits another object are different' do
code = <<-CODE
type MyFirstObject = Object[{}]
type MySecondObject = Object[{ parent => MyFirstObject }]
notice(MyFirstObject == MySecondObject)
CODE
expect(eval_and_collect_notices(code)).to eql(['false'])
end
it 'two anonymous objects that inherits the same parent are equal' do
code = <<-CODE
type MyFirstObject = Object[{}]
$x = Object[{ parent => MyFirstObject }]
$y = Object[{ parent => MyFirstObject }]
notice($x == $y)
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'declared Object type is assignable to default Object type' do
code = <<-CODE
type MyObject = Object[{ attributes => { a => Integer }}]
notice(MyObject < Object)
notice(MyObject <= Object)
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'true'])
end
it 'default Object type not is assignable to declared Object type' do
code = <<-CODE
type MyObject = Object[{ attributes => { a => Integer }}]
notice(Object < MyObject)
notice(Object <= MyObject)
CODE
expect(eval_and_collect_notices(code)).to eql(['false', 'false'])
end
it 'default Object type is assignable to itself' do
code = <<-CODE
notice(Object < Object)
notice(Object <= Object)
notice(Object > Object)
notice(Object >= Object)
CODE
expect(eval_and_collect_notices(code)).to eql(['false', 'true', 'false', 'true'])
end
it 'an object type is an instance of an object type type' do
code = <<-CODE
type MyObject = Object[{ attributes => { a => Integer }}]
notice(MyObject =~ Type[MyObject])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'an object that inherits another object is an instance of the type of its parent' do
code = <<-CODE
type MyFirstObject = Object[{}]
type MySecondObject = Object[{ parent => MyFirstObject }]
notice(MySecondObject =~ Type[MyFirstObject])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'a named object is not added to the loader unless a type <name> = <definition> is made' do
code = <<-CODE
$x = Object[{ name => 'MyFirstObject' }]
notice($x == MyFirstObject)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Resource type not found: MyFirstObject/)
end
it 'a type alias on a named object overrides the name' do
code = <<-CODE
type MyObject = Object[{ name => 'MyFirstObject', attributes => { a => { type => Integer, final => true }}}]
type MySecondObject = Object[{ parent => MyObject, attributes => { a => { type => Integer[10], override => true }}}]
notice(MySecondObject =~ Type)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error,
/attribute MySecondObject\[a\] attempts to override final attribute MyObject\[a\]/)
end
it 'a type cannot be created using an unresolved parent' do
code = <<-CODE
notice(Object[{ name => 'MyObject', parent => Type('NoneSuch'), attributes => { a => String}}].new('hello'))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error,
/reference to unresolved type 'NoneSuch'/)
end
context 'type alias using bracket-less (implicit Object) form' do
let(:logs) { [] }
let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
let(:node) { Puppet::Node.new('example.com') }
let(:compiler) { Puppet::Parser::Compiler.new(node) }
def compile(code)
Puppet[:code] = code
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) { compiler.compile }
end
it 'Object is implicit' do
compile(<<-CODE)
type MyObject = { name => 'MyFirstObject', attributes => { a => Integer}}
notice(MyObject =~ Type)
notice(MyObject(3))
CODE
expect(warnings).to be_empty
expect(notices).to eql(['true', "MyObject({'a' => 3})"])
end
it 'Object can be specified' do
compile(<<-CODE)
type MyObject = Object { name => 'MyFirstObject', attributes => { a =>Integer }}
notice(MyObject =~ Type)
notice(MyObject(3))
CODE
expect(warnings).to be_empty
expect(notices).to eql(['true', "MyObject({'a' => 3})"])
end
it 'parent can be specified before the hash' do
compile(<<-CODE)
type MyObject = { name => 'MyFirstObject', attributes => { a => String }}
type MySecondObject = MyObject { attributes => { b => String }}
notice(MySecondObject =~ Type)
notice(MySecondObject < MyObject)
notice(MyObject('hi'))
notice(MySecondObject('hello', 'world'))
CODE
expect(warnings).to be_empty
expect(notices).to eql(
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_uri_type_spec.rb | spec/unit/pops/types/p_uri_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'URI type' do
context 'when used in Puppet expressions' do
include PuppetSpec::Compiler
it 'is equal to itself only' do
expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true false false))
$t = URI
notice(URI =~ Type[URI])
notice(URI == URI)
notice(URI < URI)
notice(URI > URI)
CODE
end
context "when parameterized" do
it 'is equal other types with the same parameterization' do
code = <<-CODE
notice(URI == URI[{}])
notice(URI['http://example.com'] == URI[scheme => http, host => 'example.com'])
notice(URI['urn:a:b:c'] == URI[scheme => urn, opaque => 'a:b:c'])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true true))
end
it 'is assignable from more qualified types' do
expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true true))
notice(URI > URI['http://example.com'])
notice(URI['http://example.com'] > URI['http://example.com/path'])
notice(URI[scheme => Enum[http, https]] > URI['http://example.com'])
CODE
end
it 'is not assignable unless scheme is assignable' do
expect(eval_and_collect_notices(<<-CODE)).to eq(%w(false))
notice(URI[scheme => Enum[http, https]] > URI[scheme => 'ftp'])
CODE
end
it 'presents parsable string form' do
code = <<-CODE
notice(URI['https://user:password@www.example.com:3000/some/path?x=y#frag'])
CODE
expect(eval_and_collect_notices(code)).to eq([
"URI[{'scheme' => 'https', 'userinfo' => 'user:password', 'host' => 'www.example.com', 'port' => '3000', 'path' => '/some/path', 'query' => 'x=y', 'fragment' => 'frag'}]",
])
end
end
context 'a URI instance' do
it 'can be created from a string' do
code = <<-CODE
$o = URI('https://example.com/a/b')
notice(String($o, '%p'))
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq([
"URI('https://example.com/a/b')",
"URI[{'scheme' => 'https', 'host' => 'example.com', 'path' => '/a/b'}]"
])
end
it 'which is opaque, can be created from a string' do
code = <<-CODE
$o = URI('urn:a:b:c')
notice(String($o, '%p'))
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq([
"URI('urn:a:b:c')",
"URI[{'scheme' => 'urn', 'opaque' => 'a:b:c'}]"
])
end
it 'can be created from a hash' do
code = <<-CODE
$o = URI(scheme => 'https', host => 'example.com', path => '/a/b')
notice(String($o, '%p'))
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq([
"URI('https://example.com/a/b')",
"URI[{'scheme' => 'https', 'host' => 'example.com', 'path' => '/a/b'}]"
])
end
it 'which is opaque, can be created from a hash' do
code = <<-CODE
$o = URI(scheme => 'urn', opaque => 'a:b:c')
notice(String($o, '%p'))
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq([
"URI('urn:a:b:c')",
"URI[{'scheme' => 'urn', 'opaque' => 'a:b:c'}]"
])
end
it 'is an instance of its type' do
code = <<-CODE
$o = URI('https://example.com/a/b')
notice($o =~ type($o))
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'is an instance of matching parameterized URI' do
code = <<-CODE
$o = URI('https://example.com/a/b')
notice($o =~ URI[scheme => https, host => 'example.com'])
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'is an instance of matching default URI' do
code = <<-CODE
$o = URI('https://example.com/a/b')
notice($o =~ URI)
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'path is not matched by opaque' do
code = <<-CODE
$o = URI('urn:a:b:c')
notice($o =~ URI[path => 'a:b:c'])
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'opaque is not matched by path' do
code = <<-CODE
$o = URI('https://example.com/a/b')
notice($o =~ URI[opaque => '/a/b'])
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'is not an instance unless parameters matches' do
code = <<-CODE
$o = URI('https://example.com/a/b')
notice($o =~ URI[scheme => http])
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'individual parts of URI can be accessed using accessor methods' do
code = <<-CODE
$o = URI('https://bob:pw@example.com:8080/a/b?a=b#frag')
notice($o.scheme)
notice($o.userinfo)
notice($o.host)
notice($o.port)
notice($o.path)
notice($o.query)
notice($o.fragment)
CODE
expect(eval_and_collect_notices(code)).to eq(['https', 'bob:pw', 'example.com', '8080', '/a/b', 'a=b', 'frag'])
end
it 'individual parts of opaque URI can be accessed using accessor methods' do
code = <<-CODE
$o = URI('urn:a:b:c')
notice($o.scheme)
notice($o.opaque)
CODE
expect(eval_and_collect_notices(code)).to eq(['urn', 'a:b:c'])
end
it 'An URI can be merged with a String using the + operator' do
code = <<-CODE
notice(String(URI('https://example.com') + '/a/b', '%p'))
CODE
expect(eval_and_collect_notices(code)).to eq(["URI('https://example.com/a/b')"])
end
it 'An URI can be merged with another URI using the + operator' do
code = <<-CODE
notice(String(URI('https://example.com') + URI('/a/b'), '%p'))
CODE
expect(eval_and_collect_notices(code)).to eq(["URI('https://example.com/a/b')"])
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_sem_ver_type_spec.rb | spec/unit/pops/types/p_sem_ver_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Semantic Versions' do
include PuppetSpec::Compiler
context 'the SemVer type' do
it 'is normalized in a Variant' do
t = TypeFactory.variant(TypeFactory.sem_ver('>=1.0.0 <2.0.0'), TypeFactory.sem_ver('>=1.5.0 <4.0.0')).normalize
expect(t).to be_a(PSemVerType)
expect(t).to eql(TypeFactory.sem_ver('>=1.0.0 <4.0.0'))
end
context 'convert method' do
it 'returns nil on a nil argument' do
expect(PSemVerType.convert(nil)).to be_nil
end
it 'returns its argument when the argument is a version' do
v = SemanticPuppet::Version.new(1,0,0)
expect(PSemVerType.convert(v)).to equal(v)
end
it 'converts a valid version string argument to a version' do
v = SemanticPuppet::Version.new(1,0,0)
expect(PSemVerType.convert('1.0.0')).to eq(v)
end
it 'raises an error string that does not represent a valid version' do
expect{PSemVerType.convert('1-3')}.to raise_error(ArgumentError)
end
end
end
context 'the SemVerRange type' do
context 'convert method' do
it 'returns nil on a nil argument' do
expect(PSemVerRangeType.convert(nil)).to be_nil
end
it 'returns its argument when the argument is a version range' do
vr = SemanticPuppet::VersionRange.parse('1.x')
expect(PSemVerRangeType.convert(vr)).to equal(vr)
end
it 'converts a valid version string argument to a version range' do
vr = SemanticPuppet::VersionRange.parse('1.x')
expect(PSemVerRangeType.convert('1.x')).to eq(vr)
end
it 'raises an error string that does not represent a valid version range' do
expect{PSemVerRangeType.convert('x3')}.to raise_error(ArgumentError)
end
end
end
context 'when used in Puppet expressions' do
context 'the SemVer type' do
it 'can have multiple range arguments' do
code = <<-CODE
$t = SemVer[SemVerRange('>=1.0.0 <2.0.0'), SemVerRange('>=3.0.0 <4.0.0')]
notice(SemVer('1.2.3') =~ $t)
notice(SemVer('2.3.4') =~ $t)
notice(SemVer('3.4.5') =~ $t)
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true'])
end
it 'can have multiple range arguments in string form' do
code = <<-CODE
$t = SemVer['>=1.0.0 <2.0.0', '>=3.0.0 <4.0.0']
notice(SemVer('1.2.3') =~ $t)
notice(SemVer('2.3.4') =~ $t)
notice(SemVer('3.4.5') =~ $t)
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true'])
end
it 'range arguments are normalized' do
code = <<-CODE
notice(SemVer['>=1.0.0 <2.0.0', '>=1.5.0 <4.0.0'] == SemVer['>=1.0.0 <4.0.0'])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'is assignable to a type containing ranges with a merged range that is assignable but individual ranges are not' do
code = <<-CODE
$x = SemVer['>=1.0.0 <2.0.0', '>=1.5.0 <3.0.0']
$y = SemVer['>=1.2.0 <2.8.0']
notice($y < $x)
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
end
context 'the SemVerRange type' do
it 'a range is an instance of the type' do
code = <<-CODE
notice(SemVerRange('3.0.0 - 4.0.0') =~ SemVerRange)
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
end
context 'a SemVer instance' do
it 'can be created from a String' do
code = <<-CODE
$x = SemVer('1.2.3')
notice(assert_type(SemVer, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['1.2.3'])
end
it 'can be compared to another instance for equality' do
code = <<-CODE
$x = SemVer('1.2.3')
$y = SemVer('1.2.3')
notice($x == $y)
notice($x != $y)
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'false'])
end
it 'can be compared to another instance created from arguments' do
code = <<-CODE
$x = SemVer('1.2.3-rc4+5')
$y = SemVer(1, 2, 3, 'rc4', '5')
notice($x == $y)
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'can be compared to another instance created from a hash' do
code = <<-CODE
$x = SemVer('1.2.3-rc4+5')
$y = SemVer(major => 1, minor => 2, patch => 3, prerelease => 'rc4', build => '5')
notice($x == $y)
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it 'can be compared to another instance for magnitude' do
code = <<-CODE
$x = SemVer('1.1.1')
$y = SemVer('1.2.3')
notice($x < $y)
notice($x <= $y)
notice($x > $y)
notice($x >= $y)
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'true', 'false', 'false'])
end
it 'can be matched against a version range' do
code = <<-CODE
$v = SemVer('1.1.1')
notice($v =~ SemVerRange('>1.0.0'))
notice($v =~ SemVerRange('>1.1.1'))
notice($v =~ SemVerRange('>=1.1.1'))
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true'])
end
it 'can be matched against a SemVerRange in case expression' do
code = <<-CODE
case SemVer('1.1.1') {
SemVerRange('>1.1.1'): {
notice('high')
}
SemVerRange('>1.0.0'): {
notice('mid')
}
default: {
notice('low')
}
}
CODE
expect(eval_and_collect_notices(code)).to eql(['mid'])
end
it 'can be matched against a SemVer in case expression' do
code = <<-CODE
case SemVer('1.1.1') {
SemVer('1.1.0'): {
notice('high')
}
SemVer('1.1.1'): {
notice('mid')
}
default: {
notice('low')
}
}
CODE
expect(eval_and_collect_notices(code)).to eql(['mid'])
end
it "can be matched against a versions in 'in' expression" do
code = <<-CODE
notice(SemVer('1.1.1') in [SemVer('1.0.0'), SemVer('1.1.1'), SemVer('2.3.4')])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it "can be matched against a VersionRange using an 'in' expression" do
code = <<-CODE
notice(SemVer('1.1.1') in SemVerRange('>1.0.0'))
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it "can be matched against multiple VersionRanges using an 'in' expression" do
code = <<-CODE
notice(SemVer('1.1.1') in [SemVerRange('>=1.0.0 <1.0.2'), SemVerRange('>=1.1.0 <1.1.2')])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
end
context 'a String representing a SemVer' do
it 'can be matched against a version range' do
code = <<-CODE
$v = '1.1.1'
notice($v =~ SemVerRange('>1.0.0'))
notice($v =~ SemVerRange('>1.1.1'))
notice($v =~ SemVerRange('>=1.1.1'))
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'false', 'true'])
end
it 'can be matched against a SemVerRange in case expression' do
code = <<-CODE
case '1.1.1' {
SemVerRange('>1.1.1'): {
notice('high')
}
SemVerRange('>1.0.0'): {
notice('mid')
}
default: {
notice('low')
}
}
CODE
expect(eval_and_collect_notices(code)).to eql(['mid'])
end
it 'can be matched against a SemVer in case expression' do
code = <<-CODE
case '1.1.1' {
SemVer('1.1.0'): {
notice('high')
}
SemVer('1.1.1'): {
notice('mid')
}
default: {
notice('low')
}
}
CODE
expect(eval_and_collect_notices(code)).to eql(['mid'])
end
it "can be matched against a VersionRange using an 'in' expression" do
code = <<-CODE
notice('1.1.1' in SemVerRange('>1.0.0'))
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
it "can be matched against multiple VersionRanges using an 'in' expression" do
code = <<-CODE
notice('1.1.1' in [SemVerRange('>=1.0.0 <1.0.2'), SemVerRange('>=1.1.0 <1.1.2')])
CODE
expect(eval_and_collect_notices(code)).to eql(['true'])
end
end
context 'matching SemVer' do
suitability = {
[ '1.2.3', '1.2.2' ] => false,
[ '>=1.2.3', '1.2.2' ] => false,
[ '<=1.2.3', '1.2.2' ] => true,
[ '1.2.3 - 1.2.4', '1.2.2' ] => false,
[ '~1.2.3', '1.2.2' ] => false,
[ '~1.2', '1.2.2' ] => true,
[ '~1', '1.2.2' ] => true,
[ '1.2.x', '1.2.2' ] => true,
[ '1.x', '1.2.2' ] => true,
[ '1.2.3-alpha', '1.2.3-alpha' ] => true,
[ '>=1.2.3-alpha', '1.2.3-alpha' ] => true,
[ '<=1.2.3-alpha', '1.2.3-alpha' ] => true,
[ '<=1.2.3-alpha', '1.2.3-a' ] => true,
[ '>1.2.3-alpha', '1.2.3-alpha' ] => false,
[ '>1.2.3-a', '1.2.3-alpha' ] => true,
[ '<1.2.3-alpha', '1.2.3-alpha' ] => false,
[ '<1.2.3-alpha', '1.2.3-a' ] => true,
[ '1.2.3-alpha - 1.2.4', '1.2.3-alpha' ] => true,
[ '1.2.3 - 1.2.4-alpha', '1.2.4-alpha' ] => true,
[ '1.2.3 - 1.2.4', '1.2.5-alpha' ] => false,
[ '~1.2.3-alhpa', '1.2.3-alpha' ] => true,
[ '~1.2.3-alpha', '1.3.0-alpha' ] => false,
[ '1.2.3', '1.2.3' ] => true,
[ '>=1.2.3', '1.2.3' ] => true,
[ '<=1.2.3', '1.2.3' ] => true,
[ '1.2.3 - 1.2.4', '1.2.3' ] => true,
[ '~1.2.3', '1.2.3' ] => true,
[ '~1.2', '1.2.3' ] => true,
[ '~1', '1.2.3' ] => true,
[ '1.2.x', '1.2.3' ] => true,
[ '1.x', '1.2.3' ] => true,
[ '1.2.3', '1.2.4' ] => false,
[ '>=1.2.3', '1.2.4' ] => true,
[ '<=1.2.3', '1.2.4' ] => false,
[ '1.2.3 - 1.2.4', '1.2.4' ] => true,
# [ '~1.2.3', '1.2.4' ] => true, Awaits fix for PUP-6242
[ '~1.2', '1.2.4' ] => true,
[ '~1', '1.2.4' ] => true,
[ '1.2.x', '1.2.4' ] => true,
[ '1.x', '1.2.4' ] => true,
}
suitability.each do |arguments, expected|
it "'#{arguments[1]}' against SemVerRange '#{arguments[0]}', yields #{expected}" do
code = "notice(SemVer('#{arguments[1]}') =~ SemVerRange('#{arguments[0]}'))"
expect(eval_and_collect_notices(code)).to eql([expected.to_s])
end
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/types_spec.rb | spec/unit/pops/types/types_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Puppet Type System' do
include PuppetSpec::Compiler
let(:tf) { TypeFactory }
context 'Integer type' do
let!(:a) { tf.range(10, 20) }
let!(:b) { tf.range(18, 28) }
let!(:c) { tf.range( 2, 12) }
let!(:d) { tf.range(12, 18) }
let!(:e) { tf.range( 8, 22) }
let!(:f) { tf.range( 8, 9) }
let!(:g) { tf.range(21, 22) }
let!(:h) { tf.range(30, 31) }
let!(:i) { tf.float_range(1.0, 30.0) }
let!(:j) { tf.float_range(1.0, 9.0) }
context 'when testing if ranges intersect' do
it 'detects an intersection when self is before its argument' do
expect(a.intersect?(b)).to be_truthy
end
it 'detects an intersection when self is after its argument' do
expect(a.intersect?(c)).to be_truthy
end
it 'detects an intersection when self covers its argument' do
expect(a.intersect?(d)).to be_truthy
end
it 'detects an intersection when self equals its argument' do
expect(a.intersect?(a)).to be_truthy
end
it 'detects an intersection when self is covered by its argument' do
expect(a.intersect?(e)).to be_truthy
end
it 'does not consider an adjacent range to be intersecting' do
[f, g].each {|x| expect(a.intersect?(x)).to be_falsey }
end
it 'does not consider an range that is apart to be intersecting' do
expect(a.intersect?(h)).to be_falsey
end
it 'does not consider an overlapping float range to be intersecting' do
expect(a.intersect?(i)).to be_falsey
end
end
context 'when testing if ranges are adjacent' do
it 'detects an adjacent type when self is after its argument' do
expect(a.adjacent?(f)).to be_truthy
end
it 'detects an adjacent type when self is before its argument' do
expect(a.adjacent?(g)).to be_truthy
end
it 'does not consider overlapping types to be adjacent' do
[a, b, c, d, e].each { |x| expect(a.adjacent?(x)).to be_falsey }
end
it 'does not consider an range that is apart to be adjacent' do
expect(a.adjacent?(h)).to be_falsey
end
it 'does not consider an adjacent float range to be adjancent' do
expect(a.adjacent?(j)).to be_falsey
end
end
context 'when merging ranges' do
it 'will merge intersecting ranges' do
expect(a.merge(b)).to eq(tf.range(10, 28))
end
it 'will merge adjacent ranges' do
expect(a.merge(g)).to eq(tf.range(10, 22))
end
it 'will not merge ranges that are apart' do
expect(a.merge(h)).to be_nil
end
it 'will not merge overlapping float ranges' do
expect(a.merge(i)).to be_nil
end
it 'will not merge adjacent float ranges' do
expect(a.merge(j)).to be_nil
end
end
end
context 'Float type' do
let!(:a) { tf.float_range(10.0, 20.0) }
let!(:b) { tf.float_range(18.0, 28.0) }
let!(:c) { tf.float_range( 2.0, 12.0) }
let!(:d) { tf.float_range(12.0, 18.0) }
let!(:e) { tf.float_range( 8.0, 22.0) }
let!(:f) { tf.float_range(30.0, 31.0) }
let!(:g) { tf.range(1, 30) }
context 'when testing if ranges intersect' do
it 'detects an intersection when self is before its argument' do
expect(a.intersect?(b)).to be_truthy
end
it 'detects an intersection when self is after its argument' do
expect(a.intersect?(c)).to be_truthy
end
it 'detects an intersection when self covers its argument' do
expect(a.intersect?(d)).to be_truthy
end
it 'detects an intersection when self equals its argument' do
expect(a.intersect?(a)).to be_truthy
end
it 'detects an intersection when self is covered by its argument' do
expect(a.intersect?(e)).to be_truthy
end
it 'does not consider an range that is apart to be intersecting' do
expect(a.intersect?(f)).to be_falsey
end
it 'does not consider an overlapping integer range to be intersecting' do
expect(a.intersect?(g)).to be_falsey
end
end
context 'when merging ranges' do
it 'will merge intersecting ranges' do
expect(a.merge(b)).to eq(tf.float_range(10.0, 28.0))
end
it 'will not merge ranges that are apart' do
expect(a.merge(f)).to be_nil
end
it 'will not merge overlapping integer ranges' do
expect(a.merge(g)).to be_nil
end
end
end
context 'Boolean type' do
it 'parameterized type is assignable to base type' do
code = <<-CODE
notice(Boolean[true] < Boolean)
notice(Boolean[false] < Boolean)
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true'])
end
it 'boolean literals are instances of the base type' do
code = <<-CODE
notice(true =~ Boolean)
notice(false =~ Boolean)
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true'])
end
it 'boolean literals are instances of type parameterized with the same literal' do
code = <<-CODE
notice(true =~ Boolean[true])
notice(false =~ Boolean[false])
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true'])
end
it 'boolean literals are not instances of type parameterized with a different literal' do
code = <<-CODE
notice(true =~ Boolean[false])
notice(false =~ Boolean[true])
CODE
expect(eval_and_collect_notices(code)).to eq(['false', 'false'])
end
end
context 'Enum type' do
it 'sorts its entries' do
code = <<-CODE
Enum[c,b,a].each |$e| { notice $e }
CODE
expect(eval_and_collect_notices(code)).to eq(['a', 'b', 'c'])
end
it 'makes entries unique' do
code = <<-CODE
Enum[a,b,c,b,a].each |$e| { notice $e }
CODE
expect(eval_and_collect_notices(code)).to eq(['a', 'b', 'c'])
end
it 'is case sensitive by default' do
code = <<-CODE
notice('A' =~ Enum[a,b])
notice('a' =~ Enum[a,b])
CODE
expect(eval_and_collect_notices(code)).to eq(['false', 'true'])
end
it 'is case insensitive when last parameter argument is true' do
code = <<-CODE
notice('A' =~ Enum[a,b,true])
notice('a' =~ Enum[a,b,true])
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true'])
end
end
context 'Regexp type' do
it 'parameterized type is assignable to base type' do
code = <<-CODE
notice(Regexp[a] < Regexp)
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'new function creates a new regexp' do
code = <<-CODE
$r = Regexp('abc')
notice('abc' =~ $r)
notice(type($r) =~ Type[Regexp])
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true'])
end
it 'special characters are escaped with second parameter to Regexp.new set to true' do
code = <<-CODE
$r = Regexp('.[]', true)
notice('.[]' =~ $r)
notice(String($r) == "\\.\\[\\]")
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true'])
end
end
context 'Iterable type' do
it 'can be parameterized with element type' do
code = <<-CODE
function foo(Iterable[String] $x) {
$x.each |$e| {
notice $e
}
}
foo([bar, baz, cake])
CODE
expect(eval_and_collect_notices(code)).to eq(['bar', 'baz', 'cake'])
end
end
context 'Iterator type' do
let!(:iterint) { tf.iterator(tf.integer) }
context 'when testing instance?' do
it 'will consider an iterable on an integer is an instance of Iterator[Integer]' do
expect(iterint.instance?(Iterable.on(3))).to be_truthy
end
it 'will consider an iterable on string to be an instance of Iterator[Integer]' do
expect(iterint.instance?(Iterable.on('string'))).to be_falsey
end
end
context 'when testing assignable?' do
it 'will consider an iterator with an assignable type as assignable' do
expect(tf.iterator(tf.numeric).assignable?(iterint)).to be_truthy
end
it 'will not consider an iterator with a non assignable type as assignable' do
expect(tf.iterator(tf.string).assignable?(iterint)).to be_falsey
end
end
context 'when asked for an iterable type' do
it 'the default iterator type returns the default iterable type' do
expect(PIteratorType::DEFAULT.iterable_type).to be(PIterableType::DEFAULT)
end
it 'a typed iterator type returns the an equally typed iterable type' do
expect(iterint.iterable_type).to eq(tf.iterable(tf.integer))
end
end
it 'can be parameterized with an element type' do
code = <<-CODE
function foo(Iterator[String] $x) {
$x.each |$e| {
notice $e
}
}
foo([bar, baz, cake].reverse_each)
CODE
expect(eval_and_collect_notices(code)).to eq(['cake', 'baz', 'bar'])
end
end
context 'Collection type' do
it 'can be parameterized with a range' do
code = <<-CODE
notice(Collection[5, default] == Collection[5])
notice(Collection[5, 5] > Tuple[Integer, 0, 10])
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'false'])
end
end
context 'Struct type' do
context 'can be used as key in hash' do
it 'compacts optional in optional in optional to just optional' do
key1 = tf.struct({'foo' => tf.string})
key2 = tf.struct({'foo' => tf.string})
expect({key1 => 'hi'}[key2]).to eq('hi')
end
end
end
context 'Optional type' do
let!(:overlapping_ints) { tf.variant(tf.range(10, 20), tf.range(18, 28)) }
let!(:optoptopt) { tf.optional(tf.optional(tf.optional(overlapping_ints))) }
let!(:optnu) { tf.optional(tf.not_undef(overlapping_ints)) }
context 'when normalizing' do
it 'compacts optional in optional in optional to just optional' do
expect(optoptopt.normalize).to eq(tf.optional(tf.range(10, 28)))
end
end
it 'compacts NotUndef in Optional to just Optional' do
expect(optnu.normalize).to eq(tf.optional(tf.range(10, 28)))
end
end
context 'NotUndef type' do
let!(:nununu) { tf.not_undef(tf.not_undef(tf.not_undef(tf.any))) }
let!(:nuopt) { tf.not_undef(tf.optional(tf.any)) }
let!(:nuoptint) { tf.not_undef(tf.optional(tf.integer)) }
context 'when normalizing' do
it 'compacts NotUndef in NotUndef in NotUndef to just NotUndef' do
expect(nununu.normalize).to eq(tf.not_undef(tf.any))
end
it 'compacts Optional in NotUndef to just NotUndef' do
expect(nuopt.normalize).to eq(tf.not_undef(tf.any))
end
it 'compacts NotUndef[Optional[Integer]] in NotUndef to just Integer' do
expect(nuoptint.normalize).to eq(tf.integer)
end
end
end
context 'Variant type' do
let!(:overlapping_ints) { tf.variant(tf.range(10, 20), tf.range(18, 28)) }
let!(:adjacent_ints) { tf.variant(tf.range(10, 20), tf.range(8, 9)) }
let!(:mix_ints) { tf.variant(overlapping_ints, adjacent_ints) }
let!(:overlapping_floats) { tf.variant(tf.float_range(10.0, 20.0), tf.float_range(18.0, 28.0)) }
let!(:enums) { tf.variant(tf.enum('a', 'b'), tf.enum('b', 'c')) }
let!(:enums_s_is) { tf.variant(tf.enum('a', 'b'), tf.enum('b', 'c', true)) }
let!(:enums_is_is) { tf.variant(tf.enum('A', 'b', true), tf.enum('B', 'c', true)) }
let!(:patterns) { tf.variant(tf.pattern('a', 'b'), tf.pattern('b', 'c')) }
let!(:with_undef) { tf.variant(tf.undef, tf.range(1,10)) }
let!(:all_optional) { tf.variant(tf.optional(tf.range(1,10)), tf.optional(tf.range(11,20))) }
let!(:groups) { tf.variant(mix_ints, overlapping_floats, enums, patterns, with_undef, all_optional) }
context 'when normalizing contained types that' do
it 'are overlapping ints, the result is a range' do
expect(overlapping_ints.normalize).to eq(tf.range(10, 28))
end
it 'are adjacent ints, the result is a range' do
expect(adjacent_ints.normalize).to eq(tf.range(8, 20))
end
it 'are mixed variants with adjacent and overlapping ints, the result is a range' do
expect(mix_ints.normalize).to eq(tf.range(8, 28))
end
it 'are overlapping floats, the result is a float range' do
expect(overlapping_floats.normalize).to eq(tf.float_range(10.0, 28.0))
end
it 'are enums, the result is an enum' do
expect(enums.normalize).to eq(tf.enum('a', 'b', 'c'))
end
it 'are case sensitive versus case insensitive enums, does not merge the enums' do
expect(enums_s_is.normalize).to eq(enums_s_is)
end
it 'are case insensitive enums, result is case insensitive and unique irrespective of case' do
expect(enums_is_is.normalize).to eq(tf.enum('a', 'b', 'c', true))
end
it 'are patterns, the result is a pattern' do
expect(patterns.normalize).to eq(tf.pattern('a', 'b', 'c'))
end
it 'contains an Undef, the result is Optional' do
expect(with_undef.normalize).to eq(tf.optional(tf.range(1,10)))
end
it 'are all Optional, the result is an Optional with normalized type' do
expect(all_optional.normalize).to eq(tf.optional(tf.range(1,20)))
end
it 'can be normalized in groups, the result is a Variant containing the resulting normalizations' do
expect(groups.normalize).to eq(tf.optional(
tf.variant(
tf.range(1, 28),
tf.float_range(10.0, 28.0),
tf.enum('a', 'b', 'c'),
tf.pattern('a', 'b', 'c'))))
end
end
context 'when generalizing' do
it 'will generalize and compact contained types' do
expect(tf.variant(tf.string(tf.range(3,3)), tf.string(tf.range(5,5))).generalize).to eq(tf.variant(tf.string))
end
end
end
context 'Runtime type' do
it 'can be created with a runtime and a runtime type name' do
expect(tf.runtime('ruby', 'Hash').to_s).to eq("Runtime[ruby, 'Hash']")
end
it 'can be created with a runtime and, puppet name pattern, and runtime replacement' do
expect(tf.runtime('ruby', [/^MyPackage::(.*)$/, 'MyModule::\1']).to_s).to eq("Runtime[ruby, [/^MyPackage::(.*)$/, 'MyModule::\\1']]")
end
it 'will map a Puppet name to a runtime type' do
t = tf.runtime('ruby', [/^MyPackage::(.*)$/, 'MyModule::\1'])
expect(t.from_puppet_name('MyPackage::MyType').to_s).to eq("Runtime[ruby, 'MyModule::MyType']")
end
it 'with parameters is assignable to the default Runtime type' do
code = <<-CODE
notice(Runtime[ruby, 'Symbol'] < Runtime)
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'with parameters is not assignable from the default Runtime type' do
code = <<-CODE
notice(Runtime < Runtime[ruby, 'Symbol'])
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'default is assignable to itself' do
code = <<-CODE
notice(Runtime < Runtime)
notice(Runtime <= Runtime)
CODE
expect(eval_and_collect_notices(code)).to eq(['false', 'true'])
end
end
context 'Type aliases' do
it 'will resolve nested objects using self recursion' do
code = <<-CODE
type Tree = Hash[String,Variant[String,Tree]]
notice({a => {b => {c => d}}} =~ Tree)
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'will find mismatches using self recursion' do
code = <<-CODE
type Tree = Hash[String,Variant[String,Tree]]
notice({a => {b => {c => 1}}} =~ Tree)
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'will not allow an alias chain to only contain aliases' do
code = <<-CODE
type Foo = Bar
type Fee = Foo
type Bar = Fee
notice(0 =~ Bar)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Type alias 'Bar' cannot be resolved to a real type/)
end
it 'will not allow an alias chain that contains nothing but aliases and variants' do
code = <<-CODE
type Foo = Bar
type Fee = Foo
type Bar = Variant[Fee,Foo]
notice(0 =~ Bar)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Type alias 'Bar' cannot be resolved to a real type/)
end
it 'will not allow an alias to directly reference itself' do
code = <<-CODE
type Foo = Foo
notice(0 =~ Foo)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Type alias 'Foo' cannot be resolved to a real type/)
end
it 'will allow an alias to directly reference itself in a variant with other types' do
code = <<-CODE
type Foo = Variant[Foo,String]
notice(a =~ Foo)
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'will allow an alias where a variant references an alias with a variant that references itself' do
code = <<-CODE
type X = Variant[Y, Integer]
type Y = Variant[X, String]
notice(X >= X)
notice(X >= Y)
notice(Y >= X)
CODE
expect(eval_and_collect_notices(code)).to eq(['true','true','true'])
end
it 'will detect a mismatch in an alias that directly references itself in a variant with other types' do
code = <<-CODE
type Foo = Variant[Foo,String]
notice(3 =~ Foo)
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'will normalize a Variant containing a self reference so that the self reference is removed' do
code = <<-CODE
type Foo = Variant[Foo,String,Integer]
assert_type(Foo, /x/)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/expects a Foo = Variant\[String, Integer\] value, got Regexp/)
end
it 'will handle a scalar correctly in combinations of nested aliased variants' do
code = <<-CODE
type Bar = Variant[Foo,Integer]
type Foo = Variant[Bar,String]
notice(a =~ Foo)
notice(1 =~ Foo)
notice(/x/ =~ Foo)
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false'])
end
it 'will handle a non scalar correctly in combinations of nested aliased array with nested variants' do
code = <<-CODE
type Bar = Variant[Foo,Integer]
type Foo = Array[Variant[Bar,String]]
notice([a] =~ Foo)
notice([1] =~ Foo)
notice([/x/] =~ Foo)
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false'])
end
it 'will handle a non scalar correctly in combinations of nested aliased variants with array' do
code = <<-CODE
type Bar = Variant[Foo,Array[Integer]]
type Foo = Variant[Bar,Array[String]]
notice([a] =~ Foo)
notice([1] =~ Foo)
notice([/x/] =~ Foo)
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false'])
end
it 'will not allow dynamic constructs in type definition' do
code = <<-CODE
type Foo = Enum[$facts[os][family]]
notice(Foo)
CODE
expect{ eval_and_collect_notices(code) }.to raise_error(Puppet::Error,
/The expression <\$facts\[os\]\[family\]> is not a valid type specification/)
end
end
context 'Type mappings' do
it 'can register a singe type mapping' do
source = <<-CODE
type MyModule::ImplementationRegistry = Object[{}]
type Runtime[ruby, 'Puppet::Pops::Types::ImplementationRegistry'] = MyModule::ImplementationRegistry
notice(true)
CODE
collect_notices(source) do |compiler|
compiler.compile do |catalog|
type = Loaders.implementation_registry.type_for_module(ImplementationRegistry)
expect(type).to be_a(PObjectType)
expect(type.name).to eql('MyModule::ImplementationRegistry')
catalog
end
end
end
it 'can register a regexp based mapping' do
source = <<-CODE
type MyModule::TypeMismatchDescriber = Object[{}]
type Runtime[ruby, [/^Puppet::Pops::Types::(\\w+)$/, 'MyModule::\\1']] = [/^MyModule::(\\w+)$/, 'Puppet::Pops::Types::\\1']
notice(true)
CODE
collect_notices(source) do |compiler|
compiler.compile do |catalog|
type = Loaders.implementation_registry.type_for_module(TypeMismatchDescriber)
expect(type).to be_a(PObjectType)
expect(type.name).to eql('MyModule::TypeMismatchDescriber')
catalog
end
end
end
it 'a type mapping affects type inference' do
source = <<-CODE
type MyModule::ImplementationRegistry = Object[{}]
type Runtime[ruby, 'Puppet::Pops::Types::ImplementationRegistry'] = MyModule::ImplementationRegistry
notice(true)
CODE
collect_notices(source) do |compiler|
compiler.compile do |catalog|
type = TypeCalculator.singleton.infer(Loaders.implementation_registry)
expect(type).to be_a(PObjectType)
expect(type.name).to eql('MyModule::ImplementationRegistry')
catalog
end
end
end
end
context 'When attempting to redefine a built in type' do
it 'such as Integer, an error is raised' do
code = <<-CODE
type Integer = String
notice 'hello' =~ Integer
CODE
expect{ eval_and_collect_notices(code) }.to raise_error(/Attempt to redefine entity 'http:\/\/puppet\.com\/2016\.1\/runtime\/type\/integer'. Originally set by Puppet-Type-System\/Static-Loader/)
end
end
context 'instantiation via new_function is supported by' do
let(:loader) { Loader::BaseLoader.new(nil, "types_unit_test_loader") }
it 'Integer' do
func_class = tf.integer.new_function
expect(func_class).to be_a(Class)
expect(func_class.superclass).to be(Puppet::Functions::Function)
end
it 'Optional[Integer]' do
func_class = tf.optional(tf.integer).new_function
expect(func_class).to be_a(Class)
expect(func_class.superclass).to be(Puppet::Functions::Function)
end
it 'Regexp' do
func_class = tf.regexp.new_function
expect(func_class).to be_a(Class)
expect(func_class.superclass).to be(Puppet::Functions::Function)
end
end
context 'instantiation via new_function is not supported by' do
let(:loader) { Loader::BaseLoader.new(nil, "types_unit_test_loader") }
it 'Any, Scalar, Collection' do
[tf.any, tf.scalar, tf.collection ].each do |t|
expect { t.new_function
}.to raise_error(ArgumentError, /Creation of new instance of type '#{t.to_s}' is not supported/)
end
end
end
context 'instantiation via ruby create function' do
before(:each) do
Puppet.push_context(:loaders => Loaders.new(Puppet::Node::Environment.create(:testing, []))) do
end
end
after(:each) do
Puppet.pop_context()
end
it 'is supported by Integer' do
int = tf.integer.create('32')
expect(int).to eq(32)
end
it 'is supported by Regexp' do
rx = tf.regexp.create('[a-z]+')
expect(rx).to eq(/[a-z]+/)
end
it 'is supported by Optional[Integer]' do
int = tf.optional(tf.integer).create('32')
expect(int).to eq(32)
end
it 'is not supported by Any, Scalar, Collection' do
[tf.any, tf.scalar, tf.collection ].each do |t|
expect { t.create }.to raise_error(ArgumentError, /Creation of new instance of type '#{t.to_s}' is not supported/)
end
end
end
context 'creation of parameterized type via ruby create function on class' do
before(:each) do
Puppet.push_context(:loaders => Loaders.new(Puppet::Node::Environment.create(:testing, []))) do
end
end
after(:each) do
Puppet.pop_context()
end
it 'is supported by Integer' do
int_type = tf.integer.class.create(0, 32)
expect(int_type).to eq(tf.range(0, 32))
end
it 'is supported by Regexp' do
rx_type = tf.regexp.class.create('[a-z]+')
expect(rx_type).to eq(tf.regexp(/[a-z]+/))
end
end
context 'backward compatibility' do
it 'PTypeType can be accessed from PType' do
# should appoint the exact same instance
expect(PType).to equal(PTypeType)
end
it 'PClassType can be accessed from PHostClassType' do
# should appoint the exact same instance
expect(PHostClassType).to equal(PClassType)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_type_set_type_spec.rb | spec/unit/pops/types/p_type_set_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'The TypeSet Type' do
include PuppetSpec::Compiler
let(:parser) { TypeParser.singleton }
let(:pp_parser) { Parser::EvaluatingParser.new }
let(:env) { Puppet::Node::Environment.create('test', []) }
let(:loaders) { Loaders.new(env) }
let(:loader) { loaders.find_loader(nil) }
def type_set_t(name, body_string, name_authority)
init_literal_hash = pp_parser.parse_string("{#{body_string}}").body
typeset = PTypeSetType.new(name, init_literal_hash, name_authority)
loader.set_entry(Loader::TypedName.new(:type, name, name_authority), typeset)
typeset
end
# Creates and parses an alias type declaration of a TypeSet, e.g.
# ```
# type <name> = TypeSet[{<body_string>}]
# ```
# The declaration implies the name authority {Pcore::RUNTIME_NAME_AUTHORITY}
#
# @param name [String] the name of the type set
# @param body [String] the body (initialization hash) of the type-set
# @return [PTypeSetType] the created type set
def parse_type_set(name, body, name_authority = Pcore::RUNTIME_NAME_AUTHORITY)
type_set_t(name, body, name_authority)
parser.parse(name, loader)
end
context 'when validating the initialization hash' do
context 'it will allow that it' do
it 'has no types and no references' do
ts = <<-OBJECT
version => '1.0.0',
pcore_version => '1.0.0',
OBJECT
expect { parse_type_set('MySet', ts) }.not_to raise_error
end
it 'has only references' do
parse_type_set('FirstSet', <<-OBJECT)
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Car => Object[{}]
}
OBJECT
expect { parse_type_set('SecondSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
references => {
First => {
name => 'FirstSet',
version_range => '1.x'
}
}
OBJECT
end
it 'has multiple references to equally named TypeSets using different name authorities' do
parse_type_set('FirstSet', <<-OBJECT, 'http://example.com/ns1')
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Car => Object[{}]
}
OBJECT
parse_type_set('FirstSet', <<-OBJECT, 'http://example.com/ns2')
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Car => Object[{}]
}
OBJECT
expect { parse_type_set('SecondSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
references => {
First_1 => {
name_authority => 'http://example.com/ns1',
name => 'FirstSet',
version_range => '1.x'
},
First_2 => {
name => 'FirstSet',
name_authority => 'http://example.com/ns2',
version_range => '1.x'
}
}
OBJECT
end
end
context 'it raises an error when' do
it 'pcore_version is missing' do
ts = <<-OBJECT
version => '1.0.0',
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/expects a value for key 'pcore_version'/)
end
it 'the version is an invalid semantic version' do
ts = <<-OBJECT
version => '1.x',
pcore_version => '1.0.0',
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(SemanticPuppet::Version::ValidationFailure)
end
it 'the pcore_version is an invalid semantic version' do
ts = <<-OBJECT
version => '1.0.0',
pcore_version => '1.x',
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(SemanticPuppet::Version::ValidationFailure)
end
it 'the pcore_version is outside of the range of that is parsable by this runtime' do
ts = <<-OBJECT
version => '1.0.0',
pcore_version => '2.0.0',
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError,
/The pcore version for TypeSet 'MySet' is not understood by this runtime. Expected range 1\.x, got 2\.0\.0/)
end
it 'the name authority is an invalid URI' do
ts = <<-OBJECT
version => '1.0.0',
pcore_version => '1.0.0',
name_authority => 'not a valid URI'
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'name_authority' expects a match for Pattern\[.*\], got 'not a valid URI'/m)
end
context 'the types map' do
it 'is empty' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
types => {}
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'types' expects size to be at least 1, got 0/)
end
it 'is not a map' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
types => []
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(Puppet::Error,
/entry 'types' expects a Hash value, got Array/)
end
it 'contains values that are not types' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
types => {
Car => 'brum'
}
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(Puppet::Error,
/The expression <'brum'> is not a valid type specification/)
end
it 'contains keys that are not SimpleNames' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
types => {
car => Integer
}
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/key of entry 'car' expects a match for Pattern\[\/\\A\[A-Z\]\\w\*\\z\/\], got 'car'/)
end
end
context 'the references hash' do
it 'is empty' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => {}
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'references' expects size to be at least 1, got 0/)
end
it 'is not a hash' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => []
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'references' expects a Hash value, got Array/)
end
it 'contains something other than reference initialization maps' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => {Ref => 2}
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'references' entry 'Ref' expects a Struct value, got Integer/)
end
it 'contains several initialization that refers to the same TypeSet' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => {
A => { name => 'Vehicle::Cars', version_range => '1.x' },
V => { name => 'Vehicle::Cars', version_range => '1.x' },
}
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError,
/references TypeSet 'http:\/\/puppet\.com\/2016\.1\/runtime\/Vehicle::Cars' more than once using overlapping version ranges/)
end
it 'contains an initialization maps with an alias that collides with a type name' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
types => {
Car => Object[{}]
},
references => {
Car => { name => 'Vehicle::Car', version_range => '1.x' }
}
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError,
/references a TypeSet using alias 'Car'. The alias collides with the name of a declared type/)
end
context 'contains an initialization map that' do
it 'has no version range' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => { Ref => { name => 'X' } }
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'references' entry 'Ref' expects a value for key 'version_range'/)
end
it 'has no name' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => { Ref => { version_range => '1.x' } }
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'references' entry 'Ref' expects a value for key 'name'/)
end
it 'has a name that is not a QRef' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => { Ref => { name => 'cars', version_range => '1.x' } }
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'references' entry 'Ref' entry 'name' expects a match for Pattern\[\/\\A\[A-Z\]\\w\*\(\?:::\[A-Z\]\\w\*\)\*\\z\/\], got 'cars'/)
end
it 'has a version_range that is not a valid SemVer range' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => { Ref => { name => 'Cars', version_range => 'N' } }
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(ArgumentError,
/Unparsable version range: "N"/)
end
it 'has an alias that is not a SimpleName' do
ts = <<-OBJECT
pcore_version => '1.0.0',
version => '1.0.0',
references => { 'cars' => { name => 'X', version_range => '1.x' } }
OBJECT
expect { parse_type_set('MySet', ts) }.to raise_error(TypeAssertionError,
/entry 'references' key of entry 'cars' expects a match for Pattern\[\/\\A\[A-Z\]\\w\*\\z\/\], got 'cars'/)
end
end
end
end
end
context 'when declaring types' do
it 'can declare a type Alias' do
expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
types => { PositiveInt => Integer[0, default] }
OBJECT
end
it 'can declare an Object type using Object[{}]' do
expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
types => { Complex => Object[{}] }
OBJECT
end
it 'can declare an Object type that references other types in the same set' do
expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Real => Float,
Complex => Object[{
attributes => {
real => Real,
imaginary => Real
}
}]
}
OBJECT
end
it 'can declare an alias that references itself' do
expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Tree => Hash[String,Variant[String,Tree]]
}
OBJECT
end
it 'can declare a type that references types in another type set' do
parse_type_set('Vehicles', <<-OBJECT)
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Car => Object[{}],
Bicycle => Object[{}]
}
OBJECT
expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Transports => Variant[Vecs::Car,Vecs::Bicycle]
},
references => {
Vecs => {
name => 'Vehicles',
version_range => '1.x'
}
}
OBJECT
end
it 'can declare a type that references types in a type set referenced by another type set' do
parse_type_set('Vehicles', <<-OBJECT)
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Car => Object[{}],
Bicycle => Object[{}]
}
OBJECT
parse_type_set('Transports', <<-OBJECT)
version => '1.0.0',
pcore_version => '1.0.0',
types => {
Transports => Variant[Vecs::Car,Vecs::Bicycle]
},
references => {
Vecs => {
name => 'Vehicles',
version_range => '1.x'
}
}
OBJECT
expect { parse_type_set('TheSet', <<-OBJECT) }.not_to raise_error
version => '1.0.0',
pcore_version => '1.0.0',
types => {
MotorPowered => Variant[T::Vecs::Car],
Pedaled => Variant[T::Vecs::Bicycle],
All => T::Transports
},
references => {
T => {
name => 'Transports',
version_range => '1.x'
}
}
OBJECT
end
context 'allows bracket-less form' do
let(:logs) { [] }
let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
let(:node) { Puppet::Node.new('example.com') }
let(:compiler) { Puppet::Parser::Compiler.new(node) }
def compile(code)
Puppet[:code] = code
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) { compiler.compile }
end
it 'on the TypeSet declaration itself' do
compile(<<-PUPPET)
type TS = TypeSet { pcore_version => '1.0.0' }
notice(TS =~ Type[TypeSet])
PUPPET
expect(warnings).to be_empty
expect(notices).to eql(['true'])
end
it 'without prefix on declared types (implies Object)' do
compile(<<-PUPPET)
type TS = TypeSet {
pcore_version => '1.0.0',
types => {
MyObject => { attributes => { a => Integer} }
}
}
notice(TS =~ Type[TypeSet])
notice(TS::MyObject =~ Type)
notice(TS::MyObject(3))
PUPPET
expect(warnings).to be_empty
expect(notices).to eql(['true', 'true', "TS::MyObject({'a' => 3})"])
end
it "prefixed with QREF 'Object' on declared types" do
compile(<<-PUPPET)
type TS = TypeSet {
pcore_version => '1.0.0',
types => {
MyObject => Object { attributes => { a => Integer} }
}
}
notice(TS =~ Type[TypeSet])
notice(TS::MyObject =~ Type)
notice(TS::MyObject(3))
PUPPET
expect(warnings).to be_empty
expect(notices).to eql(['true', 'true', "TS::MyObject({'a' => 3})"])
end
it 'prefixed with QREF to declare parent on declared types' do
compile(<<-PUPPET)
type TS = TypeSet {
pcore_version => '1.0.0',
types => {
MyObject => { attributes => { a => String }},
MySecondObject => MyObject { attributes => { b => String }}
}
}
notice(TS =~ Type[TypeSet])
notice(TS::MySecondObject =~ Type)
notice(TS::MySecondObject < TS::MyObject)
notice(TS::MyObject('hi'))
notice(TS::MySecondObject('hello', 'world'))
PUPPET
expect(warnings).to be_empty
expect(notices).to eql(
['true', 'true', 'true', "TS::MyObject({'a' => 'hi'})", "TS::MySecondObject({'a' => 'hello', 'b' => 'world'})"])
end
it 'and warns when parent is specified both before and inside the hash if strict == warning' do
Puppet[:strict] = 'warning'
compile(<<-PUPPET)
type TS = TypeSet {
pcore_version => '1.0.0',
types => {
MyObject => { attributes => { a => String }},
MySecondObject => MyObject { parent => MyObject, attributes => { b => String }}
}
}
notice(TS =~ Type[TypeSet])
PUPPET
expect(warnings).to eql(["The key 'parent' is declared more than once"])
expect(notices).to eql(['true'])
end
it 'and errors when parent is specified both before and inside the hash if strict == error' do
Puppet[:strict] = 'error'
expect{ compile(<<-PUPPET) }.to raise_error(/The key 'parent' is declared more than once/)
type TS = TypeSet {
pcore_version => '1.0.0',
types => {
MyObject => { attributes => { a => String }},
MySecondObject => MyObject { parent => MyObject, attributes => { b => String }}
}
}
notice(TS =~ Type[TypeSet])
PUPPET
end
end
end
it '#name_for method reports the name of deeply nested type correctly' do
tv = parse_type_set('Vehicles', <<-OBJECT)
version => '1.0.0',
pcore_version => '1.0.0',
types => { Car => Object[{}] }
OBJECT
parse_type_set('Transports', <<-OBJECT)
version => '1.0.0',
pcore_version => '1.0.0',
references => {
Vecs => {
name => 'Vehicles',
version_range => '1.x'
}
}
OBJECT
ts = parse_type_set('TheSet', <<-OBJECT)
version => '1.0.0',
pcore_version => '1.0.0',
references => {
T => {
name => 'Transports',
version_range => '1.x'
}
}
OBJECT
expect(ts.name_for(tv['Car'], nil)).to eql('T::Vecs::Car')
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/type_parser_spec.rb | spec/unit/pops/types/type_parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Types
describe TypeParser do
extend RSpec::Matchers::DSL
let(:parser) { TypeParser.singleton }
let(:types) { TypeFactory }
it "rejects a puppet expression" do
expect { parser.parse("1 + 1") }.to raise_error(Puppet::ParseError, /The expression <1 \+ 1> is not a valid type specification/)
end
it "rejects a empty type specification" do
expect { parser.parse("") }.to raise_error(Puppet::ParseError, /The expression <> is not a valid type specification/)
end
it "rejects an invalid type simple type" do
expect { parser.parse("notAType") }.to raise_error(Puppet::ParseError, /The expression <notAType> is not a valid type specification/)
end
it "rejects an unknown parameterized type" do
expect { parser.parse("notAType[Integer]") }.to raise_error(Puppet::ParseError,
/The expression <notAType\[Integer\]> is not a valid type specification/)
end
it "rejects an unknown type parameter" do
expect { parser.parse("Array[notAType]") }.to raise_error(Puppet::ParseError,
/The expression <Array\[notAType\]> is not a valid type specification/)
end
it "rejects an unknown type parameter in a variant" do
expect { parser.parse("Variant[Integer,'not a type']") }.to raise_error(Puppet::ParseError,
/The expression <Variant\[Integer,'not a type'\]> is not a valid type specification/)
end
[
'Any', 'Data', 'CatalogEntry', 'Scalar', 'Undef', 'Numeric', 'Default'
].each do |name|
it "does not support parameterizing unparameterized type <#{name}>" do
expect { parser.parse("#{name}[Integer]") }.to raise_unparameterized_error_for(name)
end
end
it "parses a simple, unparameterized type into the type object" do
expect(the_type_parsed_from(types.any)).to be_the_type(types.any)
expect(the_type_parsed_from(types.integer)).to be_the_type(types.integer)
expect(the_type_parsed_from(types.float)).to be_the_type(types.float)
expect(the_type_parsed_from(types.string)).to be_the_type(types.string)
expect(the_type_parsed_from(types.boolean)).to be_the_type(types.boolean)
expect(the_type_parsed_from(types.pattern)).to be_the_type(types.pattern)
expect(the_type_parsed_from(types.data)).to be_the_type(types.data)
expect(the_type_parsed_from(types.catalog_entry)).to be_the_type(types.catalog_entry)
expect(the_type_parsed_from(types.collection)).to be_the_type(types.collection)
expect(the_type_parsed_from(types.tuple)).to be_the_type(types.tuple)
expect(the_type_parsed_from(types.struct)).to be_the_type(types.struct)
expect(the_type_parsed_from(types.optional)).to be_the_type(types.optional)
expect(the_type_parsed_from(types.default)).to be_the_type(types.default)
end
it "interprets an unparameterized Array as an Array of Any" do
expect(parser.parse("Array")).to be_the_type(types.array_of_any)
end
it "interprets an unparameterized Hash as a Hash of Any, Any" do
expect(parser.parse("Hash")).to be_the_type(types.hash_of_any)
end
it "interprets a parameterized Array[0, 0] as an empty hash with no key and value type" do
expect(parser.parse("Array[0, 0]")).to be_the_type(types.array_of(types.default, types.range(0, 0)))
end
it "interprets a parameterized Hash[0, 0] as an empty hash with no key and value type" do
expect(parser.parse("Hash[0, 0]")).to be_the_type(types.hash_of(types.default, types.default, types.range(0, 0)))
end
it "interprets a parameterized Hash[t] as a Hash of Scalar to t" do
expect(parser.parse("Hash[Scalar, Integer]")).to be_the_type(types.hash_of(types.integer))
end
it 'interprets an Boolean with a true parameter to represent boolean true' do
expect(parser.parse('Boolean[true]')).to be_the_type(types.boolean(true))
end
it 'interprets an Boolean with a false parameter to represent boolean false' do
expect(parser.parse('Boolean[false]')).to be_the_type(types.boolean(false))
end
it 'does not accept non-boolean parameters' do
expect{parser.parse('Boolean["false"]')}.to raise_error(/Boolean parameter must be true or false/)
end
it 'interprets an Integer with one parameter to have unbounded upper range' do
expect(parser.parse('Integer[0]')).to eq(parser.parse('Integer[0,default]'))
end
it 'interprets a Float with one parameter to have unbounded upper range' do
expect(parser.parse('Float[0]')).to eq(parser.parse('Float[0,default]'))
end
it "parses a parameterized type into the type object" do
parameterized_array = types.array_of(types.integer)
parameterized_hash = types.hash_of(types.integer, types.boolean)
expect(the_type_parsed_from(parameterized_array)).to be_the_type(parameterized_array)
expect(the_type_parsed_from(parameterized_hash)).to be_the_type(parameterized_hash)
end
it "parses a size constrained collection using capped range" do
parameterized_array = types.array_of(types.integer, types.range(1,2))
parameterized_hash = types.hash_of(types.integer, types.boolean, types.range(1,2))
expect(the_type_parsed_from(parameterized_array)).to be_the_type(parameterized_array)
expect(the_type_parsed_from(parameterized_hash)).to be_the_type(parameterized_hash)
end
it "parses a size constrained collection with open range" do
parameterized_array = types.array_of(types.integer, types.range(1, :default))
parameterized_hash = types.hash_of(types.integer, types.boolean, types.range(1, :default))
expect(the_type_parsed_from(parameterized_array)).to be_the_type(parameterized_array)
expect(the_type_parsed_from(parameterized_hash)).to be_the_type(parameterized_hash)
end
it "parses optional type" do
opt_t = types.optional(Integer)
expect(the_type_parsed_from(opt_t)).to be_the_type(opt_t)
end
it "parses timespan type" do
timespan_t = types.timespan
expect(the_type_parsed_from(timespan_t)).to be_the_type(timespan_t)
end
it "parses timestamp type" do
timestamp_t = types.timestamp
expect(the_type_parsed_from(timestamp_t)).to be_the_type(timestamp_t)
end
it "parses tuple type" do
tuple_t = types.tuple([Integer, String])
expect(the_type_parsed_from(tuple_t)).to be_the_type(tuple_t)
end
it "parses tuple type with occurrence constraint" do
tuple_t = types.tuple([Integer, String], types.range(2, 5))
expect(the_type_parsed_from(tuple_t)).to be_the_type(tuple_t)
end
it "parses struct type" do
struct_t = types.struct({'a'=>Integer, 'b'=>String})
expect(the_type_parsed_from(struct_t)).to be_the_type(struct_t)
end
describe "handles parsing of patterns and regexp" do
{ 'Pattern[/([a-z]+)([1-9]+)/]' => [:pattern, [/([a-z]+)([1-9]+)/]],
'Pattern["([a-z]+)([1-9]+)"]' => [:pattern, [/([a-z]+)([1-9]+)/]],
'Regexp[/([a-z]+)([1-9]+)/]' => [:regexp, [/([a-z]+)([1-9]+)/]],
'Pattern[/x9/, /([a-z]+)([1-9]+)/]' => [:pattern, [/x9/, /([a-z]+)([1-9]+)/]],
}.each do |source, type|
it "such that the source '#{source}' yields the type #{type.to_s}" do
expect(parser.parse(source)).to be_the_type(TypeFactory.send(type[0], *type[1]))
end
end
end
it "rejects an collection spec with the wrong number of parameters" do
expect { parser.parse("Array[Integer, 1,2,3]") }.to raise_the_parameter_error("Array", "1 to 3", 4)
expect { parser.parse("Hash[Integer, Integer, 1,2,3]") }.to raise_the_parameter_error("Hash", "2 to 4", 5)
end
context 'with scope context and loader' do
let!(:scope) { {} }
let(:loader) { double }
before :each do
expect(Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(loader)
end
it 'interprets anything that is not found by the loader to be a type reference' do
expect(loader).to receive(:load).with(:type, 'nonesuch').and_return(nil)
expect(parser.parse('Nonesuch', scope)).to be_the_type(types.type_reference('Nonesuch'))
end
it 'interprets anything that is found by the loader to be what the loader found' do
expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File'))
expect(parser.parse('File', scope)).to be_the_type(types.resource('File'))
end
it "parses a resource type with title" do
expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File'))
expect(parser.parse("File['/tmp/foo']", scope)).to be_the_type(types.resource('file', '/tmp/foo'))
end
it "parses a resource type using 'Resource[type]' form" do
expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File'))
expect(parser.parse("Resource[File]", scope)).to be_the_type(types.resource('file'))
end
it "parses a resource type with title using 'Resource[type, title]'" do
expect(loader).to receive(:load).with(:type, 'file').and_return(nil)
expect(parser.parse("Resource[File, '/tmp/foo']", scope)).to be_the_type(types.resource('file', '/tmp/foo'))
end
it "parses a resource type with title using 'Resource[Type[title]]'" do
expect(loader).to receive(:load).with(:type, 'nonesuch').and_return(nil)
expect(parser.parse("Resource[Nonesuch['fife']]", scope)).to be_the_type(types.resource('nonesuch', 'fife'))
end
end
context 'with loader context' do
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
let(:loader) { Puppet::Pops::Loader::BaseLoader.new(nil, "type_parser_unit_test_loader", environment) }
it 'interprets anything that is not found by the loader to be a type reference' do
expect(loader).to receive(:load).with(:type, 'nonesuch').and_return(nil)
expect(parser.parse('Nonesuch', loader)).to be_the_type(types.type_reference('Nonesuch'))
end
it 'interprets anything that is found by the loader to be what the loader found' do
expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File'))
expect(parser.parse('File', loader)).to be_the_type(types.resource('file'))
end
it "parses a resource type with title" do
expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File'))
expect(parser.parse("File['/tmp/foo']", loader)).to be_the_type(types.resource('file', '/tmp/foo'))
end
it "parses a resource type using 'Resource[type]' form" do
expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File'))
expect(parser.parse("Resource[File]", loader)).to be_the_type(types.resource('file'))
end
it "parses a resource type with title using 'Resource[type, title]'" do
expect(loader).to receive(:load).with(:type, 'file').and_return(types.resource('File'))
expect(parser.parse("Resource[File, '/tmp/foo']", loader)).to be_the_type(types.resource('file', '/tmp/foo'))
end
end
context 'without a scope' do
it "interprets anything that is not a built in type to be a type reference" do
expect(parser.parse('TestType')).to eq(types.type_reference('TestType'))
end
it "interprets anything that is not a built in type with parameterers to be type reference with parameters" do
expect(parser.parse("TestType['/tmp/foo']")).to eq(types.type_reference("TestType['/tmp/foo']"))
end
end
it "parses a host class type" do
expect(parser.parse("Class")).to be_the_type(types.host_class())
end
it "parses a parameterized host class type" do
expect(parser.parse("Class[foo::bar]")).to be_the_type(types.host_class('foo::bar'))
end
it 'parses an integer range' do
expect(parser.parse("Integer[1,2]")).to be_the_type(types.range(1,2))
end
it 'parses a negative integer range' do
expect(parser.parse("Integer[-3,-1]")).to be_the_type(types.range(-3,-1))
end
it 'parses a float range' do
expect(parser.parse("Float[1.0,2.0]")).to be_the_type(types.float_range(1.0,2.0))
end
it 'parses a collection size range' do
expect(parser.parse("Collection[1,2]")).to be_the_type(types.collection(types.range(1,2)))
end
it 'parses a timespan type' do
expect(parser.parse("Timespan")).to be_the_type(types.timespan)
end
it 'parses a timespan type with a lower bound' do
expect(parser.parse("Timespan[{hours => 3}]")).to be_the_type(types.timespan({'hours' => 3}))
end
it 'parses a timespan type with an upper bound' do
expect(parser.parse("Timespan[default, {hours => 9}]")).to be_the_type(types.timespan(nil, {'hours' => 9}))
end
it 'parses a timespan type with both lower and upper bounds' do
expect(parser.parse("Timespan[{hours => 3}, {hours => 9}]")).to be_the_type(types.timespan({'hours' => 3}, {'hours' => 9}))
end
it 'parses a timestamp type' do
expect(parser.parse("Timestamp")).to be_the_type(types.timestamp)
end
it 'parses a timestamp type with a lower bound' do
expect(parser.parse("Timestamp['2014-12-12T13:14:15 CET']")).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET'))
end
it 'parses a timestamp type with an upper bound' do
expect(parser.parse("Timestamp[default, '2014-12-12T13:14:15 CET']")).to be_the_type(types.timestamp(nil, '2014-12-12T13:14:15 CET'))
end
it 'parses a timestamp type with both lower and upper bounds' do
expect(parser.parse("Timestamp['2014-12-12T13:14:15 CET', '2016-08-23T17:50:00 CET']")).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET', '2016-08-23T17:50:00 CET'))
end
it 'parses a type type' do
expect(parser.parse("Type[Integer]")).to be_the_type(types.type_type(types.integer))
end
it 'parses a ruby type' do
expect(parser.parse("Runtime[ruby, 'Integer']")).to be_the_type(types.ruby_type('Integer'))
end
it 'parses a callable type' do
t = parser.parse("Callable")
expect(t).to be_the_type(types.all_callables())
expect(t.return_type).to be_nil
end
it 'parses a parameterized callable type' do
t = parser.parse("Callable[String, Integer]")
expect(t).to be_the_type(types.callable(String, Integer))
expect(t.return_type).to be_nil
end
it 'parses a parameterized callable type with min/max' do
t = parser.parse("Callable[String, Integer, 1, default]")
expect(t).to be_the_type(types.callable(String, Integer, 1, :default))
expect(t.return_type).to be_nil
end
it 'parses a parameterized callable type with block' do
t = parser.parse("Callable[String, Callable[Boolean]]")
expect(t).to be_the_type(types.callable(String, types.callable(true)))
expect(t.return_type).to be_nil
end
it 'parses a callable with no parameters and return type' do
expect(parser.parse("Callable[[],Float]")).to be_the_type(types.callable([],Float))
end
it 'parses a parameterized callable type with return type' do
expect(parser.parse("Callable[[String, Integer],Float]")).to be_the_type(types.callable([String, Integer],Float))
end
it 'parses a parameterized callable type with min/max and return type' do
expect(parser.parse("Callable[[String, Integer, 1, default],Float]")).to be_the_type(types.callable([String, Integer, 1, :default], Float))
end
it 'parses a parameterized callable type with block and return type' do
expect(parser.parse("Callable[[String, Callable[Boolean]],Float]")).to be_the_type(types.callable([String, types.callable(true)], Float))
end
it 'parses a parameterized callable type with 0 min/max' do
t = parser.parse("Callable[0,0]")
expect(t).to be_the_type(types.callable(0,0))
expect(t.param_types.types).to be_empty
expect(t.return_type).to be_nil
end
it 'parses a parameterized callable type with 0 min/max and return_type' do
t = parser.parse("Callable[[0,0],Float]")
expect(t).to be_the_type(types.callable([0,0],Float))
expect(t.param_types.types).to be_empty
expect(t.return_type).to be_the_type(types.float)
end
it 'parses a parameterized callable type with >0 min/max' do
t = parser.parse("Callable[0,1]")
expect(t).to be_the_type(types.callable(0,1))
# Contains a Unit type to indicate "called with what you accept"
expect(t.param_types.types[0]).to be_the_type(PUnitType.new())
expect(t.return_type).to be_nil
end
it 'parses a parameterized callable type with >0 min/max and a return type' do
t = parser.parse("Callable[[0,1],Float]")
expect(t).to be_the_type(types.callable([0,1], Float))
# Contains a Unit type to indicate "called with what you accept"
expect(t.param_types.types[0]).to be_the_type(PUnitType.new())
expect(t.return_type).to be_the_type(types.float)
end
it 'parses all known literals' do
t = parser.parse('Nonesuch[{a=>undef,b=>true,c=>false,d=>default,e=>"string",f=>0,g=>1.0,h=>[1,2,3]}]')
expect(t).to be_a(PTypeReferenceType)
expect(t.type_string).to eql('Nonesuch[{a=>undef,b=>true,c=>false,d=>default,e=>"string",f=>0,g=>1.0,h=>[1,2,3]}]')
end
it 'parses a parameterized Enum using identifiers' do
t = parser.parse('Enum[a, b]')
expect(t).to be_a(PEnumType)
expect(t.to_s).to eql("Enum['a', 'b']")
end
it 'parses a parameterized Enum using strings' do
t = parser.parse("Enum['a', 'b']")
expect(t).to be_a(PEnumType)
expect(t.to_s).to eql("Enum['a', 'b']")
end
it 'rejects a parameterized Enum using type refs' do
expect { parser.parse('Enum[A, B]') }.to raise_error(/Enum parameters must be identifiers or strings/)
end
it 'rejects a parameterized Enum using integers' do
expect { parser.parse('Enum[1, 2]') }.to raise_error(/Enum parameters must be identifiers or strings/)
end
matcher :be_the_type do |type|
calc = TypeCalculator.new
match do |actual|
calc.assignable?(actual, type) && calc.assignable?(type, actual)
end
failure_message do |actual|
"expected #{calc.string(type)}, but was #{calc.string(actual)}"
end
end
def raise_the_parameter_error(type, required, given)
raise_error(Puppet::ParseError, /#{type} requires #{required}, #{given} provided/)
end
def raise_type_error_for(type_name)
raise_error(Puppet::ParseError, /Unknown type <#{type_name}>/)
end
def raise_unparameterized_error_for(type_name)
raise_error(Puppet::ParseError, /Not a parameterized type <#{type_name}>/)
end
def the_type_parsed_from(type)
parser.parse(the_type_spec_for(type))
end
def the_type_spec_for(type)
TypeFormatter.string(type)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/type_mismatch_describer_spec.rb | spec/unit/pops/types/type_mismatch_describer_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
require 'puppet_spec/files'
require 'puppet/loaders'
module Puppet::Pops
module Types
describe 'the type mismatch describer' do
include PuppetSpec::Compiler, PuppetSpec::Files
context 'with deferred functions' do
let(:env_name) { 'spec' }
let(:code_dir) { Puppet[:environmentpath] }
let(:env_dir) { File.join(code_dir, env_name) }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_code_dir, env_name, 'modules')]) }
let(:node) { Puppet::Node.new('fooname', environment: env) }
let(:populated_code_dir) do
dir_contained_in(code_dir, env_name => env_content)
PuppetSpec::Files.record_tmp(env_dir)
code_dir
end
let(:env_content) {
{
'lib' => {
'puppet' => {
'functions' => {
'string_return.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:string_return) do
dispatch :string_return do
param 'String', :arg1
return_type 'String'
end
def string_return(arg1)
arg1
end
end
RUBY
'variant_return.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:variant_return) do
dispatch :variant_return do
param 'String', :arg1
return_type 'Variant[Integer,Float]'
end
def variant_return(arg1)
arg1
end
end
RUBY
'no_return.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:no_return) do
dispatch :no_return do
param 'String', :arg1
end
def variant_return(arg1)
arg1
end
end
RUBY
}
}
}
}
}
before(:each) do
Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env))
end
after(:each) do
Puppet.pop_context
end
it 'will compile when the parameter type matches the function return_type' do
code = <<-CODE
$d = Deferred("string_return", ['/a/non/existing/path'])
class testclass(String $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect { eval_and_collect_notices(code, node) }.to_not raise_error
end
it "will compile when a Variant parameter's types matches the return type" do
code = <<-CODE
$d = Deferred("string_return", ['/a/non/existing/path'])
class testclass(Variant[String, Float] $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect { eval_and_collect_notices(code, node) }.to_not raise_error
end
it "will compile with a union of a Variant parameters' types and Variant return types" do
code = <<-CODE
$d = Deferred("variant_return", ['/a/non/existing/path'])
class testclass(Variant[Any,Float] $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect { eval_and_collect_notices(code, node) }.to_not raise_error
end
it 'will warn when there is no defined return_type for the function definition' do
code = <<-CODE
$d = Deferred("no_return", ['/a/non/existing/path'])
class testclass(Variant[String,Boolean] $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect(Puppet).to receive(:warn_once).with(anything, anything, /.+function no_return has no return_type/).at_least(:once)
expect { eval_and_collect_notices(code, node) }.to_not raise_error
end
it 'will report a mismatch between a deferred function return type and class parameter value' do
code = <<-CODE
$d = Deferred("string_return", ['/a/non/existing/path'])
class testclass(Integer $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect { eval_and_collect_notices(code, node) }.to raise_error(Puppet::Error, /.+'classparam' expects an Integer value, got String/)
end
it 'will report an argument error when no matching arity is found' do
code = <<-CODE
$d = Deferred("string_return", ['/a/non/existing/path', 'second-invalid-arg'])
class testclass(Integer $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect { eval_and_collect_notices(code,node) }.to raise_error(Puppet::Error, /.+ No matching arity found for string_return/)
end
it 'will error with no matching Variant class parameters and return_type' do
code = <<-CODE
$d = Deferred("string_return", ['/a/non/existing/path'])
class testclass(Variant[Integer,Float] $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect { eval_and_collect_notices(code,node) }.to raise_error(Puppet::Error, /.+'classparam' expects a value of type Integer or Float, got String/)
end
# This test exposes a shortcoming in the #message function for Puppet::Pops::Type::TypeMismatch
# where the `actual` is not introspected for the list of Variant types, so the error message
# shows that the list of expected types does not match Variant, instead of a list of actual types.
it 'will error with no matching Variant class parameters and Variant return_type' do
code = <<-CODE
$d = Deferred("variant_return", ['/a/non/existing/path'])
class testclass(Variant[String,Boolean] $classparam) {
}
class { 'testclass':
classparam => $d
}
CODE
expect { eval_and_collect_notices(code, node) }.to raise_error(Puppet::Error, /.+'classparam' expects a value of type String or Boolean, got Variant/)
end
end
it 'will report a mismatch between a hash and a struct with details' do
code = <<-CODE
function f(Hash[String,String] $h) {
$h['a']
}
f({'a' => 'a', 'b' => 23})
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /'f' parameter 'h' entry 'b' expects a String value, got Integer/)
end
it 'will report a mismatch between a array and tuple with details' do
code = <<-CODE
function f(Array[String] $h) {
$h[0]
}
f(['a', 23])
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /'f' parameter 'h' index 1 expects a String value, got Integer/)
end
it 'will not report details for a mismatch between an array and a struct' do
code = <<-CODE
function f(Array[String] $h) {
$h[0]
}
f({'a' => 'a string', 'b' => 23})
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects an Array value, got Struct/)
end
it 'will not report details for a mismatch between a hash and a tuple' do
code = <<-CODE
function f(Hash[String,String] $h) {
$h['a']
}
f(['a', 23])
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects a Hash value, got Tuple/)
end
it 'will report an array size mismatch' do
code = <<-CODE
function f(Array[String,1,default] $h) {
$h[0]
}
f([])
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects size to be at least 1, got 0/)
end
it 'will report a hash size mismatch' do
code = <<-CODE
function f(Hash[String,String,1,default] $h) {
$h['a']
}
f({})
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects size to be at least 1, got 0/)
end
it 'will include the aliased type when reporting a mismatch that involves an alias' do
code = <<-CODE
type UnprivilegedPort = Integer[1024,65537]
function check_port(UnprivilegedPort $port) {}
check_port(34)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /parameter 'port' expects an UnprivilegedPort = Integer\[1024, 65537\] value, got Integer\[34, 34\]/)
end
it 'will include the aliased type when reporting a mismatch that involves an alias nested in another type' do
code = <<-CODE
type UnprivilegedPort = Integer[1024,65537]
type PortMap = Hash[UnprivilegedPort,String]
function check_port(PortMap $ports) {}
check_port({ 34 => 'some service'})
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'ports' expects a PortMap = Hash\[UnprivilegedPort = Integer\[1024, 65537\], String\] value, got Hash\[Integer\[34, 34\], String\]/))
end
it 'will not include the aliased type more than once when reporting a mismatch that involves an alias that is self recursive' do
code = <<-CODE
type Tree = Hash[String,Tree]
function check_tree(Tree $tree) {}
check_tree({ 'x' => {'y' => {32 => 'n'}}})
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'tree' entry 'x' entry 'y' expects a Tree = Hash\[String, Tree\] value, got Hash\[Integer\[32, 32\], String\]/))
end
it 'will use type normalization' do
code = <<-CODE
type EVariants = Variant[Enum[a,b],Enum[b,c],Enum[c,d]]
function check_enums(EVariants $evars) {}
check_enums('n')
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'evars' expects a match for EVariants = Enum\['a', 'b', 'c', 'd'\], got 'n'/))
end
it "will not generalize a string that doesn't match an enum in a function call" do
code = <<-CODE
function check_enums(Enum[a,b] $arg) {}
check_enums('c')
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'arg' expects a match for Enum\['a', 'b'\], got 'c'/))
end
it "will not disclose a Sensitive that doesn't match an enum in a function call" do
code = <<-CODE
function check_enums(Enum[a,b] $arg) {}
check_enums(Sensitive('c'))
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'arg' expects a match for Enum\['a', 'b'\], got Sensitive/))
end
it "reports errors on the first failing parameter when that parameter is not the first in order" do
code = <<-CODE
type Abc = Enum['a', 'b', 'c']
type Cde = Enum['c', 'd', 'e']
function two_params(Abc $a, Cde $b) {}
two_params('a', 'x')
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'b' expects a match for Cde = Enum\['c', 'd', 'e'\], got 'x'/))
end
it "will not generalize a string that doesn't match an enum in a define call" do
code = <<-CODE
define check_enums(Enum[a,b] $arg) {}
check_enums { x: arg => 'c' }
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'arg' expects a match for Enum\['a', 'b'\], got 'c'/))
end
it "will include Undef when describing a mismatch against a Variant where one of the types is Undef" do
code = <<-CODE
define check(Variant[Undef,String,Integer,Hash,Array] $arg) {}
check{ x: arg => 2.4 }
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'arg' expects a value of type Undef, String, Integer, Hash, or Array/))
end
it "will not disclose a Sensitive that doesn't match an enum in a define call" do
code = <<-CODE
define check_enums(Enum[a,b] $arg) {}
check_enums { x: arg => Sensitive('c') }
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/parameter 'arg' expects a match for Enum\['a', 'b'\], got Sensitive/))
end
it "will report the parameter of Type[<type alias>] using the alias name" do
code = <<-CODE
type Custom = String[1]
Custom.each |$x| { notice($x) }
CODE
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/expects an Iterable value, got Type\[Custom\]/))
end
context 'when reporting a mismatch between' do
let(:parser) { TypeParser.singleton }
let(:subject) { TypeMismatchDescriber.singleton }
context 'hash and struct' do
it 'reports a size mismatch when hash has unlimited size' do
expected = parser.parse('Struct[{a=>Integer,b=>Integer}]')
actual = parser.parse('Hash[String,Integer]')
expect(subject.describe_mismatch('', expected, actual)).to eq('expects size to be 2, got unlimited')
end
it 'reports a size mismatch when hash has specified but incorrect size' do
expected = parser.parse('Struct[{a=>Integer,b=>Integer}]')
actual = parser.parse('Hash[String,Integer,1,1]')
expect(subject.describe_mismatch('', expected, actual)).to eq('expects size to be 2, got 1')
end
it 'reports a full type mismatch when size is correct but hash value type is incorrect' do
expected = parser.parse('Struct[{a=>Integer,b=>String}]')
actual = parser.parse('Hash[String,Integer,2,2]')
expect(subject.describe_mismatch('', expected, actual)).to eq("expects a Struct[{'a' => Integer, 'b' => String}] value, got Hash[String, Integer]")
end
end
it 'reports a missing parameter as "has no parameter"' do
t = parser.parse('Struct[{a=>String}]')
expect { subject.validate_parameters('v', t, {'a'=>'a','b'=>'b'}, false) }.to raise_error(Puppet::Error, "v: has no parameter named 'b'")
end
it 'reports a missing value as "expects a value"' do
t = parser.parse('Struct[{a=>String,b=>String}]')
expect { subject.validate_parameters('v', t, {'a'=>'a'}, false) }.to raise_error(Puppet::Error, "v: expects a value for parameter 'b'")
end
it 'reports a missing block as "expects a block"' do
callable = parser.parse('Callable[String,String,Callable]')
args_tuple = parser.parse('Tuple[String,String]')
dispatch = Functions::Dispatch.new(callable, 'foo', ['a','b'], false, 'block')
expect(subject.describe_signatures('function', [dispatch], args_tuple)).to eq("'function' expects a block")
end
it 'reports an unexpected block as "does not expect a block"' do
callable = parser.parse('Callable[String,String]')
args_tuple = parser.parse('Tuple[String,String,Callable]')
dispatch = Functions::Dispatch.new(callable, 'foo', ['a','b'])
expect(subject.describe_signatures('function', [dispatch], args_tuple)).to eq("'function' does not expect a block")
end
it 'reports a block return type mismatch' do
callable = parser.parse('Callable[[0,0,Callable[ [0,0],String]],Undef]')
args_tuple = parser.parse('Tuple[Callable[[0,0],Integer]]')
dispatch = Functions::Dispatch.new(callable, 'foo', [], false, 'block')
expect(subject.describe_signatures('function', [dispatch], args_tuple)).to eq("'function' block return expects a String value, got Integer")
end
end
it "reports struct mismatch correctly when hash doesn't contain required keys" do
code = <<-PUPPET
type Test::Options = Struct[{
var => String
}]
class test(String $var, Test::Options $opts) {}
class { 'test': var => 'hello', opts => {} }
PUPPET
expect { eval_and_collect_notices(code) }.to(raise_error(Puppet::Error,
/Class\[Test\]: parameter 'opts' expects size to be 1, got 0/))
end
it "treats Optional as Optional[Any]" do
code = <<-PUPPET
class test(Optional $var=undef) {}
class { 'test': var => 'hello' }
PUPPET
expect { eval_and_collect_notices(code) }.not_to raise_error
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_timestamp_type_spec.rb | spec/unit/pops/types/p_timestamp_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Timestamp type' do
it 'is normalized in a Variant' do
t = TypeFactory.variant(TypeFactory.timestamp('2015-03-01', '2016-01-01'), TypeFactory.timestamp('2015-11-03', '2016-12-24')).normalize
expect(t).to be_a(PTimestampType)
expect(t).to eql(TypeFactory.timestamp('2015-03-01', '2016-12-24'))
end
it 'DateTime#_strptime creates hash with :leftover field' do
expect(DateTime._strptime('2015-05-04 and bogus', '%F')).to include(:leftover)
expect(DateTime._strptime('2015-05-04T10:34:11.003 UTC and bogus', '%FT%T.%N %Z')).to include(:leftover)
end
context 'when used in Puppet expressions' do
include PuppetSpec::Compiler
it 'is equal to itself only' do
code = <<-CODE
$t = Timestamp
notice(Timestamp =~ Type[Timestamp])
notice(Timestamp == Timestamp)
notice(Timestamp < Timestamp)
notice(Timestamp > Timestamp)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true false false))
end
it 'does not consider an Integer to be an instance' do
code = <<-CODE
notice(assert_type(Timestamp, 1234))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timestamp value, got Integer/)
end
it 'does not consider a Float to be an instance' do
code = <<-CODE
notice(assert_type(Timestamp, 1.234))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/expects a Timestamp value, got Float/)
end
context "when parameterized" do
it 'is equal other types with the same parameterization' do
code = <<-CODE
notice(Timestamp['2015-03-01', '2016-01-01'] == Timestamp['2015-03-01', '2016-01-01'])
notice(Timestamp['2015-03-01', '2016-01-01'] != Timestamp['2015-11-03', '2016-12-24'])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true))
end
it 'using just one parameter is the same as using default for the second parameter' do
code = <<-CODE
notice(Timestamp['2015-03-01'] == Timestamp['2015-03-01', default])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true))
end
it 'if the second parameter is default, it is unlimited' do
code = <<-CODE
notice(Timestamp('5553-12-31') =~ Timestamp['2015-03-01', default])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true))
end
it 'orders parameterized types based on range inclusion' do
code = <<-CODE
notice(Timestamp['2015-03-01', '2015-09-30'] < Timestamp['2015-02-01', '2015-10-30'])
notice(Timestamp['2015-03-01', '2015-09-30'] > Timestamp['2015-02-01', '2015-10-30'])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false))
end
it 'accepts integer values when specifying the range' do
code = <<-CODE
notice(Timestamp(1) =~ Timestamp[1, 2])
notice(Timestamp(3) =~ Timestamp[1])
notice(Timestamp(0) =~ Timestamp[default, 2])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true true))
end
it 'accepts float values when specifying the range' do
code = <<-CODE
notice(Timestamp(1.0) =~ Timestamp[1.0, 2.0])
notice(Timestamp(3.0) =~ Timestamp[1.0])
notice(Timestamp(0.0) =~ Timestamp[default, 2.0])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true true))
end
end
context 'a Timestamp instance' do
it 'can be created from a string with just a date' do
code = <<-CODE
$o = Timestamp('2015-03-01')
notice($o)
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq(['2015-03-01T00:00:00.000000000 UTC', "Timestamp['2015-03-01T00:00:00.000000000 UTC']"])
end
it 'can be created from a string and time separated by "T"' do
code = <<-CODE
notice(Timestamp('2015-03-01T11:12:13'))
CODE
expect(eval_and_collect_notices(code)).to eq(['2015-03-01T11:12:13.000000000 UTC'])
end
it 'can be created from a string and time separated by space' do
code = <<-CODE
notice(Timestamp('2015-03-01 11:12:13'))
CODE
expect(eval_and_collect_notices(code)).to eq(['2015-03-01T11:12:13.000000000 UTC'])
end
it 'should error when none of the default formats can parse the string' do
code = <<-CODE
notice(Timestamp('2015#03#01 11:12:13'))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/Unable to parse/)
end
it 'should error when only part of the string is parsed' do
code = <<-CODE
notice(Timestamp('2015-03-01T11:12:13 bogus after'))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/Unable to parse/)
end
it 'can be created from a string and format' do
code = <<-CODE
$o = Timestamp('Sunday, 28 August, 2016', '%A, %d %B, %Y')
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq(['2016-08-28T00:00:00.000000000 UTC'])
end
it 'can be created from a string, format, and a timezone' do
code = <<-CODE
$o = Timestamp('Sunday, 28 August, 2016', '%A, %d %B, %Y', 'EST')
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq(['2016-08-28T05:00:00.000000000 UTC'])
end
it 'can be not be created from a string, format with timezone designator, and a timezone' do
code = <<-CODE
$o = Timestamp('Sunday, 28 August, 2016 UTC', '%A, %d %B, %Y %z', 'EST')
notice($o)
CODE
expect { eval_and_collect_notices(code) }.to raise_error(
/Using a Timezone designator in format specification is mutually exclusive to providing an explicit timezone argument/)
end
it 'can be created from a hash with string and format' do
code = <<-CODE
$o = Timestamp({ string => 'Sunday, 28 August, 2016', format => '%A, %d %B, %Y' })
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq(['2016-08-28T00:00:00.000000000 UTC'])
end
it 'can be created from a hash with string, format, and a timezone' do
code = <<-CODE
$o = Timestamp({ string => 'Sunday, 28 August, 2016', format => '%A, %d %B, %Y', timezone => 'EST' })
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq(['2016-08-28T05:00:00.000000000 UTC'])
end
it 'can be created from a string and array of formats' do
code = <<-CODE
$fmts = [
'%A, %d %B, %Y at %r',
'%b %d, %Y, %l:%M %P',
'%y-%m-%d %H:%M:%S %z'
]
notice(Timestamp('Sunday, 28 August, 2016 at 12:15:00 PM', $fmts))
notice(Timestamp('Jul 24, 2016, 1:20 am', $fmts))
notice(Timestamp('16-06-21 18:23:15 UTC', $fmts))
CODE
expect(eval_and_collect_notices(code)).to eq(
['2016-08-28T12:15:00.000000000 UTC', '2016-07-24T01:20:00.000000000 UTC', '2016-06-21T18:23:15.000000000 UTC'])
end
it 'it cannot be created using an empty formats array' do
code = <<-CODE
notice(Timestamp('2015-03-01T11:12:13', []))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /parameter 'format' variant 1 expects size to be at least 1, got 0/)
end
it 'can be created from a string, array of formats, and a timezone' do
code = <<-CODE
$fmts = [
'%A, %d %B, %Y at %r',
'%b %d, %Y, %l:%M %P',
'%y-%m-%d %H:%M:%S'
]
notice(Timestamp('Sunday, 28 August, 2016 at 12:15:00 PM', $fmts, 'CET'))
notice(Timestamp('Jul 24, 2016, 1:20 am', $fmts, 'CET'))
notice(Timestamp('16-06-21 18:23:15', $fmts, 'CET'))
CODE
expect(eval_and_collect_notices(code)).to eq(
['2016-08-28T11:15:00.000000000 UTC', '2016-07-24T00:20:00.000000000 UTC', '2016-06-21T17:23:15.000000000 UTC'])
end
it 'can be created from a integer that represents seconds since epoch' do
code = <<-CODE
$o = Timestamp(1433116800)
notice(Integer($o) == 1433116800)
notice($o == Timestamp('2015-06-01T00:00:00 UTC'))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true))
end
it 'can be created from a float that represents seconds with fraction since epoch' do
code = <<-CODE
$o = Timestamp(1433116800.123456)
notice(Float($o) == 1433116800.123456)
notice($o == Timestamp('2015-06-01T00:00:00.123456 UTC'))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true))
end
it 'matches the appropriate parameterized type' do
code = <<-CODE
$o = Timestamp('2015-05-01')
notice(assert_type(Timestamp['2015-03-01', '2015-09-30'], $o))
CODE
expect(eval_and_collect_notices(code)).to eq(['2015-05-01T00:00:00.000000000 UTC'])
end
it 'does not match an inappropriate parameterized type' do
code = <<-CODE
$o = Timestamp('2015-05-01')
notice(assert_type(Timestamp['2016-03-01', '2016-09-30'], $o) |$e, $a| { 'nope' })
CODE
expect(eval_and_collect_notices(code)).to eq(['nope'])
end
it 'can be compared to other instances' do
code = <<-CODE
$o1 = Timestamp('2015-05-01')
$o2 = Timestamp('2015-06-01')
$o3 = Timestamp('2015-06-01')
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o1 == $o3)
notice($o1 != $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
notice($o2 == $o3)
notice($o2 != $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false true false false true true true false))
end
it 'can be compared to integer that represents seconds since epoch' do
code = <<-CODE
$o1 = Timestamp('2015-05-01')
$o2 = Timestamp('2015-06-01')
$o3 = 1433116800
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'integer that represents seconds since epoch can be compared to it' do
code = <<-CODE
$o1 = 1430438400
$o2 = 1433116800
$o3 = Timestamp('2015-06-01')
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'is equal to integer that represents seconds since epoch' do
code = <<-CODE
$o1 = Timestamp('2015-06-01T00:00:00 UTC')
$o2 = 1433116800
notice($o1 == $o2)
notice($o1 != $o2)
notice(Integer($o1) == $o2)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'integer that represents seconds is equal to it' do
code = <<-CODE
$o1 = 1433116800
$o2 = Timestamp('2015-06-01T00:00:00 UTC')
notice($o1 == $o2)
notice($o1 != $o2)
notice($o1 == Integer($o2))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'can be compared to float that represents seconds with fraction since epoch' do
code = <<-CODE
$o1 = Timestamp('2015-05-01T00:00:00.123456789 UTC')
$o2 = Timestamp('2015-06-01T00:00:00.123456789 UTC')
$o3 = 1433116800.123456789
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'float that represents seconds with fraction since epoch can be compared to it' do
code = <<-CODE
$o1 = 1430438400.123456789
$o2 = 1433116800.123456789
$o3 = Timestamp('2015-06-01T00:00:00.123456789 UTC')
notice($o1 > $o3)
notice($o1 >= $o3)
notice($o1 < $o3)
notice($o1 <= $o3)
notice($o2 > $o3)
notice($o2 < $o3)
notice($o2 >= $o3)
notice($o2 <= $o3)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(false false true true false false true true))
end
it 'is equal to float that represents seconds with fraction since epoch' do
code = <<-CODE
$o1 = Timestamp('2015-06-01T00:00:00.123456789 UTC')
$o2 = 1433116800.123456789
notice($o1 == $o2)
notice($o1 != $o2)
notice(Float($o1) == $o2)
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'float that represents seconds with fraction is equal to it' do
code = <<-CODE
$o1 = 1433116800.123456789
$o2 = Timestamp('2015-06-01T00:00:00.123456789 UTC')
notice($o1 == $o2)
notice($o1 != $o2)
notice($o1 == Float($o2))
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true false true))
end
it 'it cannot be compared to a Timespan' do
code = <<-CODE
notice(Timestamp() > Timespan(3))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /Timestamps are only comparable to Timestamps, Integers, and Floats/)
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/iterable_spec.rb | spec/unit/pops/types/iterable_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops::Types
describe 'The iterable support' do
[
0,
5,
(3..10),
%w(a b c),
{'a'=>2},
'hello',
PIntegerType.new(1, 4),
PEnumType.new(%w(yes no))
].each do |obj|
it "should consider instances of #{obj.class.name} to be Iterable" do
expect(PIterableType::DEFAULT.instance?(obj)).to eq(true)
end
it "should yield an Iterable instance when Iterable.on is called with a #{obj.class.name}" do
expect(Iterable.on(obj)).to be_a(Iterable)
end
end
{
-1 => 'a negative Integer',
5.times => 'an Enumerable',
PIntegerType.new(nil, nil) => 'an unbounded Integer type'
}.each_pair do |obj, desc|
it "does not consider #{desc} to be Iterable" do
expect(PIterableType::DEFAULT.instance?(obj)).to eq(false)
end
it "does not yield an Iterable when Iterable.on is called with #{desc}" do
expect(Iterable.on(obj)).to be_nil
end
end
context 'when testing assignability' do
iterable_types = [
PIntegerType::DEFAULT,
PStringType::DEFAULT,
PIterableType::DEFAULT,
PIteratorType::DEFAULT,
PCollectionType::DEFAULT,
PArrayType::DEFAULT,
PHashType::DEFAULT,
PTupleType::DEFAULT,
PStructType::DEFAULT,
PUnitType::DEFAULT
]
iterable_types << PTypeType.new(PIntegerType.new(0, 10))
iterable_types << PTypeType.new(PEnumType.new(%w(yes no)))
iterable_types << PRuntimeType.new(:ruby, 'Puppet::Pops::Types::Iterator')
iterable_types << PVariantType.new(iterable_types.clone)
not_iterable_types = [
PAnyType::DEFAULT,
PBooleanType::DEFAULT,
PCallableType::DEFAULT,
PCatalogEntryType::DEFAULT,
PDefaultType::DEFAULT,
PFloatType::DEFAULT,
PClassType::DEFAULT,
PNotUndefType::DEFAULT,
PNumericType::DEFAULT,
POptionalType::DEFAULT,
PPatternType::DEFAULT,
PRegexpType::DEFAULT,
PResourceType::DEFAULT,
PRuntimeType::DEFAULT,
PScalarType::DEFAULT,
PScalarDataType::DEFAULT,
PTypeType::DEFAULT,
PUndefType::DEFAULT
]
not_iterable_types << PTypeType.new(PIntegerType::DEFAULT)
not_iterable_types << PVariantType.new([iterable_types[0], not_iterable_types[0]])
iterable_types.each do |type|
it "should consider #{type} to be assignable to Iterable type" do
expect(PIterableType::DEFAULT.assignable?(type)).to eq(true)
end
end
not_iterable_types.each do |type|
it "should not consider #{type} to be assignable to Iterable type" do
expect(PIterableType::DEFAULT.assignable?(type)).to eq(false)
end
end
it "should consider Type[Integer[0,5]] to be assignable to Iterable[Integer[0,5]]" do
expect(PIterableType.new(PIntegerType.new(0,5)).assignable?(PTypeType.new(PIntegerType.new(0,5)))).to eq(true)
end
it "should consider Type[Enum[yes,no]] to be assignable to Iterable[Enum[yes,no]]" do
expect(PIterableType.new(PEnumType.new(%w(yes no))).assignable?(PTypeType.new(PEnumType.new(%w(yes no))))).to eq(true)
end
it "should not consider Type[Enum[ok,fail]] to be assignable to Iterable[Enum[yes,no]]" do
expect(PIterableType.new(PEnumType.new(%w(ok fail))).assignable?(PTypeType.new(PEnumType.new(%w(yes no))))).to eq(false)
end
it "should not consider Type[String] to be assignable to Iterable[String]" do
expect(PIterableType.new(PStringType::DEFAULT).assignable?(PTypeType.new(PStringType::DEFAULT))).to eq(false)
end
end
it 'does not wrap an Iterable in another Iterable' do
x = Iterable.on(5)
expect(Iterable.on(x)).to equal(x)
end
it 'produces a "times" iterable on integer' do
expect{ |b| Iterable.on(3).each(&b) }.to yield_successive_args(0,1,2)
end
it 'produces an iterable with element type Integer[0,X-1] for an iterable on an integer X' do
expect(Iterable.on(3).element_type).to eq(PIntegerType.new(0,2))
end
it 'produces a step iterable on an integer' do
expect{ |b| Iterable.on(8).step(3, &b) }.to yield_successive_args(0, 3, 6)
end
it 'produces a reverse iterable on an integer' do
expect{ |b| Iterable.on(5).reverse_each(&b) }.to yield_successive_args(4,3,2,1,0)
end
it 'produces an iterable on a integer range' do
expect{ |b| Iterable.on(2..7).each(&b) }.to yield_successive_args(2,3,4,5,6,7)
end
it 'produces an iterable with element type Integer[X,Y] for an iterable on an integer range (X..Y)' do
expect(Iterable.on(2..7).element_type).to eq(PIntegerType.new(2,7))
end
it 'produces an iterable on a character range' do
expect{ |b| Iterable.on('a'..'f').each(&b) }.to yield_successive_args('a', 'b', 'c', 'd', 'e', 'f')
end
it 'produces a step iterable on a range' do
expect{ |b| Iterable.on(1..5).step(2, &b) }.to yield_successive_args(1,3,5)
end
it 'produces a reverse iterable on a range' do
expect{ |b| Iterable.on(2..7).reverse_each(&b) }.to yield_successive_args(7,6,5,4,3,2)
end
it 'produces an iterable with element type String with a size constraint for an iterable on a character range' do
expect(Iterable.on('a'..'fe').element_type).to eq(PStringType.new(PIntegerType.new(1,2)))
end
it 'produces an iterable on a bounded Integer type' do
expect{ |b| Iterable.on(PIntegerType.new(2,7)).each(&b) }.to yield_successive_args(2,3,4,5,6,7)
end
it 'produces an iterable with element type Integer[X,Y] for an iterable on Integer[X,Y]' do
expect(Iterable.on(PIntegerType.new(2,7)).element_type).to eq(PIntegerType.new(2,7))
end
it 'produces an iterable on String' do
expect{ |b| Iterable.on('eat this').each(&b) }.to yield_successive_args('e', 'a', 't', ' ', 't', 'h', 'i', 's')
end
it 'produces an iterable with element type String[1,1] for an iterable created on a String' do
expect(Iterable.on('eat this').element_type).to eq(PStringType.new(PIntegerType.new(1,1)))
end
it 'produces an iterable on Array' do
expect{ |b| Iterable.on([1,5,9]).each(&b) }.to yield_successive_args(1,5,9)
end
it 'produces an iterable with element type inferred from the array elements for an iterable on Array' do
expect(Iterable.on([1,5,5,9,9,9]).element_type).to eq(PVariantType.new([PIntegerType.new(1,1), PIntegerType.new(5,5), PIntegerType.new(9,9)]))
end
it 'can chain reverse_each after step on Iterable' do
expect{ |b| Iterable.on(6).step(2).reverse_each(&b) }.to yield_successive_args(4,2,0)
end
it 'can chain reverse_each after step on Integer range' do
expect{ |b| Iterable.on(PIntegerType.new(0, 5)).step(2).reverse_each(&b) }.to yield_successive_args(4,2,0)
end
it 'can chain step after reverse_each on Iterable' do
expect{ |b| Iterable.on(6).reverse_each.step(2, &b) }.to yield_successive_args(5,3,1)
end
it 'can chain step after reverse_each on Integer range' do
expect{ |b| Iterable.on(PIntegerType.new(0, 5)).reverse_each.step(2, &b) }.to yield_successive_args(5,3,1)
end
it 'will produce the same result for each as for reverse_each.reverse_each' do
x1 = Iterable.on(5)
x2 = Iterable.on(5)
expect(x1.reduce([]) { |a,i| a << i; a}).to eq(x2.reverse_each.reverse_each.reduce([]) { |a,i| a << i; a})
end
it 'can chain many nested step/reverse_each calls' do
# x = Iterable.on(18).step(3) (0, 3, 6, 9, 12, 15)
# x = x.reverse_each (15, 12, 9, 6, 3, 0)
# x = x.step(2) (15, 9, 3)
# x = x.reverse_each(3, 9, 15)
expect{ |b| Iterable.on(18).step(3).reverse_each.step(2).reverse_each(&b) }.to yield_successive_args(3, 9, 15)
end
it 'can chain many nested step/reverse_each calls on Array iterable' do
expect{ |b| Iterable.on(18.times.to_a).step(3).reverse_each.step(2).reverse_each(&b) }.to yield_successive_args(3, 9, 15)
end
it 'produces an steppable iterable for Array' do
expect{ |b| Iterable.on(%w(a b c d e f g h i)).step(3, &b) }.to yield_successive_args('a', 'd', 'g')
end
it 'produces an reverse steppable iterable for Array' do
expect{ |b| Iterable.on(%w(a b c d e f g h i)).reverse_each.step(3, &b) }.to yield_successive_args('i', 'f', 'c')
end
it 'responds false when a bounded Iterable is passed to Iterable.unbounded?' do
expect(Iterable.unbounded?(Iterable.on(%w(a b c d e f g h i)))).to eq(false)
end
it 'can create an Array from a bounded Iterable' do
expect(Iterable.on(%w(a b c d e f g h i)).to_a).to eq(%w(a b c d e f g h i))
end
class TestUnboundedIterator
include Enumerable
include Iterable
def step(step_size)
if block_given?
begin
current = 0
loop do
yield(@current)
current = current + step_size
end
rescue StopIteration
end
end
self
end
end
it 'responds true when an unbounded Iterable is passed to Iterable.unbounded?' do
ubi = TestUnboundedIterator.new
expect(Iterable.unbounded?(Iterable.on(ubi))).to eq(true)
end
it 'can not create an Array from an unbounded Iterable' do
ubi = TestUnboundedIterator.new
expect{ Iterable.on(ubi).to_a }.to raise_error(Puppet::Error, /Attempt to create an Array from an unbounded Iterable/)
end
it 'will produce the string Iterator[T] on to_s on an iterator instance with element type T' do
expect(Iterable.on(18).to_s).to eq('Iterator[Integer]-Value')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/type_calculator_spec.rb | spec/unit/pops/types/type_calculator_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Types
describe 'The type calculator' do
let(:calculator) { TypeCalculator.new }
def range_t(from, to)
PIntegerType.new(from, to)
end
def pattern_t(*patterns)
TypeFactory.pattern(*patterns)
end
def regexp_t(pattern)
TypeFactory.regexp(pattern)
end
def string_t(string = nil)
TypeFactory.string(string)
end
def constrained_string_t(size_type)
TypeFactory.string(size_type)
end
def callable_t(*params)
TypeFactory.callable(*params)
end
def all_callables_t
TypeFactory.all_callables
end
def enum_t(*strings)
TypeFactory.enum(*strings)
end
def variant_t(*types)
TypeFactory.variant(*types)
end
def empty_variant_t()
t = TypeFactory.variant()
# assert this to ensure we did get an empty variant (or tests may pass when not being empty)
raise 'typefactory did not return empty variant' unless t.types.empty?
t
end
def type_alias_t(name, type_string)
type_expr = Parser::EvaluatingParser.new.parse_string(type_string)
TypeFactory.type_alias(name, type_expr)
end
def type_reference_t(type_string)
TypeFactory.type_reference(type_string)
end
def integer_t
TypeFactory.integer
end
def array_t(t, s = nil)
TypeFactory.array_of(t, s)
end
def empty_array_t
array_t(unit_t, range_t(0,0))
end
def hash_t(k,v,s = nil)
TypeFactory.hash_of(v, k, s)
end
def data_t
TypeFactory.data
end
def factory
TypeFactory
end
def collection_t(size_type = nil)
TypeFactory.collection(size_type)
end
def tuple_t(*types)
TypeFactory.tuple(types)
end
def constrained_tuple_t(size_type, *types)
TypeFactory.tuple(types, size_type)
end
def struct_t(type_hash)
TypeFactory.struct(type_hash)
end
def any_t
TypeFactory.any
end
def optional_t(t)
TypeFactory.optional(t)
end
def type_t(t)
TypeFactory.type_type(t)
end
def not_undef_t(t = nil)
TypeFactory.not_undef(t)
end
def undef_t
TypeFactory.undef
end
def unit_t
# Cannot be created via factory, the type is private to the type system
PUnitType::DEFAULT
end
def runtime_t(t, c)
TypeFactory.runtime(t, c)
end
def object_t(hash)
TypeFactory.object(hash)
end
def iterable_t(t = nil)
TypeFactory.iterable(t)
end
def types
Types
end
context 'when inferring ruby' do
it 'integer translates to PIntegerType' do
expect(calculator.infer(1).class).to eq(PIntegerType)
end
it 'large integer translates to PIntegerType' do
expect(calculator.infer(2**33).class).to eq(PIntegerType)
end
it 'float translates to PFloatType' do
expect(calculator.infer(1.3).class).to eq(PFloatType)
end
it 'string translates to PStringType' do
expect(calculator.infer('foo').class).to eq(PStringType)
end
it 'inferred string type knows the string value' do
t = calculator.infer('foo')
expect(t.class).to eq(PStringType)
expect(t.value).to eq('foo')
end
it 'boolean true translates to PBooleanType::TRUE' do
expect(calculator.infer(true)).to eq(PBooleanType::TRUE)
end
it 'boolean false translates to PBooleanType::FALSE' do
expect(calculator.infer(false)).to eq(PBooleanType::FALSE)
end
it 'regexp translates to PRegexpType' do
expect(calculator.infer(/^a regular expression$/).class).to eq(PRegexpType)
end
it 'iterable translates to PIteratorType' do
expect(calculator.infer(Iterable.on(1))).to be_a(PIteratorType)
end
it 'nil translates to PUndefType' do
expect(calculator.infer(nil).class).to eq(PUndefType)
end
it ':undef translates to PUndefType' do
expect(calculator.infer(:undef).class).to eq(PUndefType)
end
it 'an instance of class Foo translates to PRuntimeType[ruby, Foo]' do
::Foo = Class.new
begin
t = calculator.infer(::Foo.new)
expect(t.class).to eq(PRuntimeType)
expect(t.runtime).to eq(:ruby)
expect(t.runtime_type_name).to eq('Foo')
ensure
Object.send(:remove_const, :Foo)
end
end
it 'Class Foo translates to PTypeType[PRuntimeType[ruby, Foo]]' do
::Foo = Class.new
begin
t = calculator.infer(::Foo)
expect(t.class).to eq(PTypeType)
tt = t.type
expect(tt.class).to eq(PRuntimeType)
expect(tt.runtime).to eq(:ruby)
expect(tt.runtime_type_name).to eq('Foo')
ensure
Object.send(:remove_const, :Foo)
end
end
it 'Module FooModule translates to PTypeType[PRuntimeType[ruby, FooModule]]' do
::FooModule = Module.new
begin
t = calculator.infer(::FooModule)
expect(t.class).to eq(PTypeType)
tt = t.type
expect(tt.class).to eq(PRuntimeType)
expect(tt.runtime).to eq(:ruby)
expect(tt.runtime_type_name).to eq('FooModule')
ensure
Object.send(:remove_const, :FooModule)
end
end
context 'sensitive' do
it 'translates to PSensitiveType' do
expect(calculator.infer(PSensitiveType::Sensitive.new("hunter2")).class).to eq(PSensitiveType)
end
end
context 'binary' do
it 'translates to PBinaryType' do
expect(calculator.infer(PBinaryType::Binary.from_binary_string("binary")).class).to eq(PBinaryType)
end
end
context 'version' do
it 'translates to PVersionType' do
expect(calculator.infer(SemanticPuppet::Version.new(1,0,0)).class).to eq(PSemVerType)
end
it 'range translates to PVersionRangeType' do
expect(calculator.infer(SemanticPuppet::VersionRange.parse('1.x')).class).to eq(PSemVerRangeType)
end
it 'translates to a limited PVersionType by infer_set' do
v = SemanticPuppet::Version.new(1,0,0)
t = calculator.infer_set(v)
expect(t.class).to eq(PSemVerType)
expect(t.ranges.size).to eq(1)
expect(t.ranges[0].begin).to eq(v)
expect(t.ranges[0].end).to eq(v)
end
end
context 'timespan' do
it 'translates to PTimespanType' do
expect(calculator.infer(Time::Timespan.from_fields_hash('days' => 2))).to be_a(PTimespanType)
end
it 'translates to a limited PTimespanType by infer_set' do
ts = Time::Timespan.from_fields_hash('days' => 2)
t = calculator.infer_set(ts)
expect(t.class).to eq(PTimespanType)
expect(t.from).to be(ts)
expect(t.to).to be(ts)
end
end
context 'timestamp' do
it 'translates to PTimespanType' do
expect(calculator.infer(Time::Timestamp.now)).to be_a(PTimestampType)
end
it 'translates to a limited PTimespanType by infer_set' do
ts = Time::Timestamp.now
t = calculator.infer_set(ts)
expect(t.class).to eq(PTimestampType)
expect(t.from).to be(ts)
expect(t.to).to be(ts)
end
end
context 'array' do
let(:derived) do
Class.new(Array).new([1,2])
end
let(:derived_object) do
Class.new(Array) do
include PuppetObject
def self._pcore_type
@type ||= TypeFactory.object('name' => 'DerivedObjectArray')
end
end.new([1,2])
end
it 'translates to PArrayType' do
expect(calculator.infer([1,2]).class).to eq(PArrayType)
end
it 'translates derived Array to PRuntimeType' do
expect(calculator.infer(derived).class).to eq(PRuntimeType)
end
it 'translates derived Puppet Object Array to PObjectType' do
expect(calculator.infer(derived_object).class).to eq(PObjectType)
end
it 'Instance of derived Array class is not instance of Array type' do
expect(PArrayType::DEFAULT).not_to be_instance(derived)
end
it 'Instance of derived Array class is instance of Runtime type' do
expect(runtime_t('ruby', nil)).to be_instance(derived)
end
it 'Instance of derived Puppet Object Array class is not instance of Array type' do
expect(PArrayType::DEFAULT).not_to be_instance(derived_object)
end
it 'Instance of derived Puppet Object Array class is instance of Object type' do
expect(object_t('name' => 'DerivedObjectArray')).to be_instance(derived_object)
end
it 'with integer values translates to PArrayType[PIntegerType]' do
expect(calculator.infer([1,2]).element_type.class).to eq(PIntegerType)
end
it 'with 32 and 64 bit integer values translates to PArrayType[PIntegerType]' do
expect(calculator.infer([1,2**33]).element_type.class).to eq(PIntegerType)
end
it 'Range of integer values are computed' do
t = calculator.infer([-3,0,42]).element_type
expect(t.class).to eq(PIntegerType)
expect(t.from).to eq(-3)
expect(t.to).to eq(42)
end
it 'Compound string values are converted to enums' do
t = calculator.infer(['a','b', 'c']).element_type
expect(t.class).to eq(PEnumType)
expect(t.values).to eq(['a', 'b', 'c'])
end
it 'with integer and float values translates to PArrayType[PNumericType]' do
expect(calculator.infer([1,2.0]).element_type.class).to eq(PNumericType)
end
it 'with integer and string values translates to PArrayType[PScalarDataType]' do
expect(calculator.infer([1,'two']).element_type.class).to eq(PScalarDataType)
end
it 'with float and string values translates to PArrayType[PScalarDataType]' do
expect(calculator.infer([1.0,'two']).element_type.class).to eq(PScalarDataType)
end
it 'with integer, float, and string values translates to PArrayType[PScalarDataType]' do
expect(calculator.infer([1, 2.0,'two']).element_type.class).to eq(PScalarDataType)
end
it 'with integer and regexp values translates to PArrayType[PScalarType]' do
expect(calculator.infer([1, /two/]).element_type.class).to eq(PScalarType)
end
it 'with string and regexp values translates to PArrayType[PScalarType]' do
expect(calculator.infer(['one', /two/]).element_type.class).to eq(PScalarType)
end
it 'with string and symbol values translates to PArrayType[PAnyType]' do
expect(calculator.infer(['one', :two]).element_type.class).to eq(PAnyType)
end
it 'with integer and nil values translates to PArrayType[PIntegerType]' do
expect(calculator.infer([1, nil]).element_type.class).to eq(PIntegerType)
end
it 'with integer value, and array of string values, translates to Array[Data]' do
expect(calculator.infer([1, ['two']]).element_type.name).to eq('Data')
end
it 'with integer value, and hash of string => string values, translates to Array[Data]' do
expect(calculator.infer([1, {'two' => 'three'} ]).element_type.name).to eq('Data')
end
it 'with integer value, and hash of integer => string values, translates to Array[RichData]' do
expect(calculator.infer([1, {2 => 'three'} ]).element_type.name).to eq('RichData')
end
it 'with integer, regexp, and binary values translates to Array[RichData]' do
expect(calculator.infer([1, /two/, PBinaryType::Binary.from_string('three')]).element_type.name).to eq('RichData')
end
it 'with arrays of string values translates to PArrayType[PArrayType[PStringType]]' do
et = calculator.infer([['first', 'array'], ['second','array']])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PEnumType)
end
it 'with array of string values and array of integers translates to PArrayType[PArrayType[PScalarDataType]]' do
et = calculator.infer([['first', 'array'], [1,2]])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PScalarDataType)
end
it 'with hashes of string values translates to PArrayType[PHashType[PEnumType]]' do
et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 'first', :second => 'second' }])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PHashType)
et = et.value_type
expect(et.class).to eq(PEnumType)
end
it 'with hash of string values and hash of integers translates to PArrayType[PHashType[PScalarDataType]]' do
et = calculator.infer([{:first => 'first', :second => 'second' }, {:first => 1, :second => 2 }])
expect(et.class).to eq(PArrayType)
et = et.element_type
expect(et.class).to eq(PHashType)
et = et.value_type
expect(et.class).to eq(PScalarDataType)
end
end
context 'hash' do
let(:derived) do
Class.new(Hash)[:first => 1, :second => 2]
end
let(:derived_object) do
Class.new(Hash) do
include PuppetObject
def self._pcore_type
@type ||= TypeFactory.object('name' => 'DerivedObjectHash')
end
end[:first => 1, :second => 2]
end
it 'translates to PHashType' do
expect(calculator.infer({:first => 1, :second => 2}).class).to eq(PHashType)
end
it 'translates derived Hash to PRuntimeType' do
expect(calculator.infer(derived).class).to eq(PRuntimeType)
end
it 'translates derived Puppet Object Hash to PObjectType' do
expect(calculator.infer(derived_object).class).to eq(PObjectType)
end
it 'Instance of derived Hash class is not instance of Hash type' do
expect(PHashType::DEFAULT).not_to be_instance(derived)
end
it 'Instance of derived Hash class is instance of Runtime type' do
expect(runtime_t('ruby', nil)).to be_instance(derived)
end
it 'Instance of derived Puppet Object Hash class is not instance of Hash type' do
expect(PHashType::DEFAULT).not_to be_instance(derived_object)
end
it 'Instance of derived Puppet Object Hash class is instance of Object type' do
expect(object_t('name' => 'DerivedObjectHash')).to be_instance(derived_object)
end
it 'with symbolic keys translates to PHashType[PRuntimeType[ruby, Symbol], value]' do
k = calculator.infer({:first => 1, :second => 2}).key_type
expect(k.class).to eq(PRuntimeType)
expect(k.runtime).to eq(:ruby)
expect(k.runtime_type_name).to eq('Symbol')
end
it 'with string keys translates to PHashType[PEnumType, value]' do
expect(calculator.infer({'first' => 1, 'second' => 2}).key_type.class).to eq(PEnumType)
end
it 'with integer values translates to PHashType[key, PIntegerType]' do
expect(calculator.infer({:first => 1, :second => 2}).value_type.class).to eq(PIntegerType)
end
it 'when empty infers a type that answers true to is_the_empty_hash?' do
expect(calculator.infer({}).is_the_empty_hash?).to eq(true)
expect(calculator.infer_set({}).is_the_empty_hash?).to eq(true)
end
it 'when empty is assignable to any PHashType' do
expect(calculator.assignable?(hash_t(string_t, string_t), calculator.infer({}))).to eq(true)
end
it 'when empty is not assignable to a PHashType with from size > 0' do
expect(calculator.assignable?(hash_t(string_t,string_t,range_t(1, 1)), calculator.infer({}))).to eq(false)
end
context 'using infer_set' do
it "with 'first' and 'second' keys translates to PStructType[{first=>value,second=>value}]" do
t = calculator.infer_set({'first' => 1, 'second' => 2})
expect(t.class).to eq(PStructType)
expect(t.elements.size).to eq(2)
expect(t.elements.map { |e| e.name }.sort).to eq(['first', 'second'])
end
it 'with string keys and string and array values translates to PStructType[{key1=>PStringType,key2=>PTupleType}]' do
t = calculator.infer_set({ 'mode' => 'read', 'path' => ['foo', 'fee' ] })
expect(t.class).to eq(PStructType)
expect(t.elements.size).to eq(2)
els = t.elements.map { |e| e.value_type }.sort {|a,b| a.to_s <=> b.to_s }
expect(els[0].class).to eq(PStringType)
expect(els[1].class).to eq(PTupleType)
end
it 'with mixed string and non-string keys translates to PHashType' do
t = calculator.infer_set({ 1 => 'first', 'second' => 'second' })
expect(t.class).to eq(PHashType)
end
it 'with empty string keys translates to PHashType' do
t = calculator.infer_set({ '' => 'first', 'second' => 'second' })
expect(t.class).to eq(PHashType)
end
end
end
it 'infers an instance of an anonymous class to Runtime[ruby]' do
cls = Class.new do
attr_reader :name
def initialize(name)
@name = name
end
end
t = calculator.infer(cls.new('test'))
expect(t.class).to eql(PRuntimeType)
expect(t.runtime).to eql(:ruby)
expect(t.name_or_pattern).to eql(nil)
end
end
context 'patterns' do
it 'constructs a PPatternType' do
t = pattern_t('a(b)c')
expect(t.class).to eq(PPatternType)
expect(t.patterns.size).to eq(1)
expect(t.patterns[0].class).to eq(PRegexpType)
expect(t.patterns[0].pattern).to eq('a(b)c')
expect(t.patterns[0].regexp.match('abc')[1]).to eq('b')
end
it 'constructs a PEnumType with multiple strings' do
t = enum_t('a', 'b', 'c', 'abc')
expect(t.values).to eq(['a', 'b', 'c', 'abc'].sort)
end
end
# Deal with cases not covered by computing common type
context 'when computing common type' do
it 'computes given resource type commonality' do
r1 = PResourceType.new('File', nil)
r2 = PResourceType.new('File', nil)
expect(calculator.common_type(r1, r2).to_s).to eq('File')
r2 = PResourceType.new('File', '/tmp/foo')
expect(calculator.common_type(r1, r2).to_s).to eq('File')
r1 = PResourceType.new('File', '/tmp/foo')
expect(calculator.common_type(r1, r2).to_s).to eq("File['/tmp/foo']")
r1 = PResourceType.new('File', '/tmp/bar')
expect(calculator.common_type(r1, r2).to_s).to eq('File')
r2 = PResourceType.new('Package', 'apache')
expect(calculator.common_type(r1, r2).to_s).to eq('Resource')
end
it 'computes given hostclass type commonality' do
r1 = PClassType.new('foo')
r2 = PClassType.new('foo')
expect(calculator.common_type(r1, r2).to_s).to eq('Class[foo]')
r2 = PClassType.new('bar')
expect(calculator.common_type(r1, r2).to_s).to eq('Class')
r2 = PClassType.new(nil)
expect(calculator.common_type(r1, r2).to_s).to eq('Class')
r1 = PClassType.new(nil)
expect(calculator.common_type(r1, r2).to_s).to eq('Class')
end
context 'of strings' do
it 'computes commonality' do
t1 = string_t('abc')
t2 = string_t('xyz')
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PEnumType)
expect(common_t.values).to eq(['abc', 'xyz'])
end
it 'computes common size_type' do
t1 = constrained_string_t(range_t(3,6))
t2 = constrained_string_t(range_t(2,4))
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PStringType)
expect(common_t.size_type).to eq(range_t(2,6))
end
it 'computes common size_type to be undef when one of the types has no size_type' do
t1 = string_t
t2 = constrained_string_t(range_t(2,4))
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PStringType)
expect(common_t.size_type).to be_nil
end
it 'computes values to be empty if the one has empty values' do
t1 = string_t('apa')
t2 = constrained_string_t(range_t(2,4))
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PStringType)
expect(common_t.value).to be_nil
end
end
it 'computes pattern commonality' do
t1 = pattern_t('abc')
t2 = pattern_t('xyz')
common_t = calculator.common_type(t1,t2)
expect(common_t.class).to eq(PPatternType)
expect(common_t.patterns.map { |pr| pr.pattern }).to eq(['abc', 'xyz'])
expect(common_t.to_s).to eq('Pattern[/abc/, /xyz/]')
end
it 'computes enum commonality to value set sum' do
t1 = enum_t('a', 'b', 'c')
t2 = enum_t('x', 'y', 'z')
common_t = calculator.common_type(t1, t2)
expect(common_t).to eq(enum_t('a', 'b', 'c', 'x', 'y', 'z'))
end
it 'computed variant commonality to type union where added types are not sub-types' do
a_t1 = integer_t
a_t2 = enum_t('b')
v_a = variant_t(a_t1, a_t2)
b_t1 = integer_t
b_t2 = enum_t('a')
v_b = variant_t(b_t1, b_t2)
common_t = calculator.common_type(v_a, v_b)
expect(common_t.class).to eq(PVariantType)
expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2, b_t1, b_t2]))
end
it 'computed variant commonality to type union where added types are sub-types' do
a_t1 = integer_t
a_t2 = string_t
v_a = variant_t(a_t1, a_t2)
b_t1 = integer_t
b_t2 = enum_t('a')
v_b = variant_t(b_t1, b_t2)
common_t = calculator.common_type(v_a, v_b)
expect(common_t.class).to eq(PVariantType)
expect(Set.new(common_t.types)).to eq(Set.new([a_t1, a_t2]))
end
context 'commonality of scalar data types' do
it 'Numeric and String == ScalarData' do
expect(calculator.common_type(PNumericType::DEFAULT, PStringType::DEFAULT).class).to eq(PScalarDataType)
end
it 'Numeric and Boolean == ScalarData' do
expect(calculator.common_type(PNumericType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarDataType)
end
it 'String and Boolean == ScalarData' do
expect(calculator.common_type(PStringType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarDataType)
end
end
context 'commonality of scalar types' do
it 'Regexp and Integer == Scalar' do
expect(calculator.common_type(PRegexpType::DEFAULT, PScalarDataType::DEFAULT).class).to eq(PScalarType)
end
it 'Regexp and SemVer == ScalarData' do
expect(calculator.common_type(PRegexpType::DEFAULT, PSemVerType::DEFAULT).class).to eq(PScalarType)
end
it 'Timestamp and Timespan == ScalarData' do
expect(calculator.common_type(PTimestampType::DEFAULT, PTimespanType::DEFAULT).class).to eq(PScalarType)
end
it 'Timestamp and Boolean == ScalarData' do
expect(calculator.common_type(PTimestampType::DEFAULT, PBooleanType::DEFAULT).class).to eq(PScalarType)
end
end
context 'of callables' do
it 'incompatible instances => generic callable' do
t1 = callable_t(String)
t2 = callable_t(Integer)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_nil
expect(common_t.block_type).to be_nil
end
it 'compatible instances => the most specific' do
t1 = callable_t(String)
scalar_t = PScalarType.new
t2 = callable_t(scalar_t)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types.class).to be(PTupleType)
expect(common_t.param_types.types).to eql([string_t])
expect(common_t.block_type).to be_nil
end
it 'block_type is included in the check (incompatible block)' do
b1 = callable_t(String)
b2 = callable_t(Integer)
t1 = callable_t(String, b1)
t2 = callable_t(String, b2)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_nil
expect(common_t.block_type).to be_nil
end
it 'block_type is included in the check (compatible block)' do
b1 = callable_t(String)
t1 = callable_t(String, b1)
scalar_t = PScalarType::DEFAULT
b2 = callable_t(scalar_t)
t2 = callable_t(String, b2)
common_t = calculator.common_type(t1, t2)
expect(common_t.param_types.class).to be(PTupleType)
expect(common_t.block_type).to eql(callable_t(scalar_t))
end
it 'return_type is included in the check (incompatible return_type)' do
t1 = callable_t([String], String)
t2 = callable_t([String], Integer)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_nil
expect(common_t.return_type).to be_nil
end
it 'return_type is included in the check (compatible return_type)' do
t1 = callable_t([String], Numeric)
t2 = callable_t([String], Integer)
common_t = calculator.common_type(t1, t2)
expect(common_t.class).to be(PCallableType)
expect(common_t.param_types).to be_a(PTupleType)
expect(common_t.return_type).to eql(PNumericType::DEFAULT)
end
end
end
context 'computes assignability' do
include_context 'types_setup'
it 'such that all types are assignable to themselves' do
all_types.each do |tc|
t = tc::DEFAULT
expect(t).to be_assignable_to(t)
end
end
context 'for Unit, such that' do
it 'all types are assignable to Unit' do
t = PUnitType::DEFAULT
all_types.each { |t2| expect(t2::DEFAULT).to be_assignable_to(t) }
end
it 'Unit is assignable to all other types' do
t = PUnitType::DEFAULT
all_types.each { |t2| expect(t).to be_assignable_to(t2::DEFAULT) }
end
it 'Unit is assignable to Unit' do
t = PUnitType::DEFAULT
t2 = PUnitType::DEFAULT
expect(t).to be_assignable_to(t2)
end
end
context 'for Any, such that' do
it 'all types are assignable to Any' do
t = PAnyType::DEFAULT
all_types.each { |t2| expect(t2::DEFAULT).to be_assignable_to(t) }
end
it 'Any is not assignable to anything but Any and Optional (implied Optional[Any])' do
tested_types = all_types() - [PAnyType, POptionalType]
t = PAnyType::DEFAULT
tested_types.each { |t2| expect(t).not_to be_assignable_to(t2::DEFAULT) }
end
end
context "for NotUndef, such that" do
it 'all types except types assignable from Undef are assignable to NotUndef' do
t = not_undef_t
tc = TypeCalculator.singleton
undef_t = PUndefType::DEFAULT
all_types.each do |c|
t2 = c::DEFAULT
if tc.assignable?(t2, undef_t)
expect(t2).not_to be_assignable_to(t)
else
expect(t2).to be_assignable_to(t)
end
end
end
it 'type NotUndef[T] is assignable from T unless T is assignable from Undef ' do
tc = TypeCalculator.singleton
undef_t = PUndefType::DEFAULT
all_types().select do |c|
t2 = c::DEFAULT
not_undef_t = not_undef_t(t2)
if tc.assignable?(t2, undef_t)
expect(t2).not_to be_assignable_to(not_undef_t)
else
expect(t2).to be_assignable_to(not_undef_t)
end
end
end
it 'type T is assignable from NotUndef[T] unless T is assignable from Undef' do
tc = TypeCalculator.singleton
undef_t = PUndefType::DEFAULT
all_types().select do |c|
t2 = c::DEFAULT
not_undef_t = not_undef_t(t2)
unless tc.assignable?(t2, undef_t)
expect(not_undef_t).to be_assignable_to(t2)
end
end
end
end
context "for TypeReference, such that" do
it 'no other type is assignable' do
t = PTypeReferenceType::DEFAULT
all_instances = (all_types - [
PTypeReferenceType, # Avoid comparison with t
PTypeAliasType # DEFAULT resolves to PTypeReferenceType::DEFAULT, i.e. t
]).map {|c| c::DEFAULT }
# Add a non-empty variant
all_instances << variant_t(PAnyType::DEFAULT, PUnitType::DEFAULT)
# Add a type alias that doesn't resolve to 't'
all_instances << type_alias_t('MyInt', 'Integer').resolve(nil)
all_instances.each { |i| expect(i).not_to be_assignable_to(t) }
end
it 'a TypeReference to the exact same type is assignable' do
expect(type_reference_t('Integer[0,10]')).to be_assignable_to(type_reference_t('Integer[0,10]'))
end
it 'a TypeReference to the different type is not assignable' do
expect(type_reference_t('String')).not_to be_assignable_to(type_reference_t('Integer'))
end
it 'a TypeReference to the different type is not assignable even if the referenced type is' do
expect(type_reference_t('Integer[1,2]')).not_to be_assignable_to(type_reference_t('Integer[0,3]'))
end
end
context 'for Data, such that' do
let(:data) { TypeFactory.data }
data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from #{tc.name}" do
expect(tc).to be_assignable_to(data)
end
end
data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from Optional[#{tc.name}]" do
expect(optional_t(tc)).to be_assignable_to(data)
end
end
it 'it is not assignable to any of its subtypes' do
types_to_test = data_compatible_types
types_to_test.each {|t2| expect(data).not_to be_assignable_to(type_from_class(t2)) }
end
it 'it is not assignable to any disjunct type' do
tested_types = all_types - [PAnyType, POptionalType, PInitType] - scalar_data_types
tested_types.each {|t2| expect(data).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Rich Data, such that' do
let(:rich_data) { TypeFactory.rich_data }
rich_data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from #{tc.name}" do
expect(tc).to be_assignable_to(rich_data)
end
end
rich_data_compatible_types.map { |t2| type_from_class(t2) }.each do |tc|
it "it is assignable from Optional[#{tc.name}]" do
expect(optional_t(tc)).to be_assignable_to(rich_data)
end
end
it 'it is not assignable to any of its subtypes' do
types_to_test = rich_data_compatible_types
types_to_test.each {|t2| expect(rich_data).not_to be_assignable_to(type_from_class(t2)) }
end
it 'it is not assignable to any disjunct type' do
tested_types = all_types - [PAnyType, POptionalType, PInitType] - scalar_types
tested_types.each {|t2| expect(rich_data).not_to be_assignable_to(t2::DEFAULT) }
end
end
context 'for Variant, such that' do
it 'it is assignable to a type if all contained types are assignable to that type' do
v = variant_t(range_t(10, 12),range_t(14, 20))
expect(v).to be_assignable_to(integer_t)
expect(v).to be_assignable_to(range_t(10, 20))
# test that both types are assignable to one of the variants OK
expect(v).to be_assignable_to(variant_t(range_t(10, 20), range_t(30, 40)))
# test where each type is assignable to different types in a variant is OK
expect(v).to be_assignable_to(variant_t(range_t(10, 13), range_t(14, 40)))
# not acceptable
expect(v).not_to be_assignable_to(range_t(0, 4))
expect(v).not_to be_assignable_to(string_t)
end
it 'an empty Variant is assignable to another empty Variant' do
expect(empty_variant_t).to be_assignable_to(empty_variant_t)
end
it 'an empty Variant is assignable to Any' do
expect(empty_variant_t).to be_assignable_to(PAnyType::DEFAULT)
end
it 'an empty Variant is assignable to Unit' do
expect(empty_variant_t).to be_assignable_to(PUnitType::DEFAULT)
end
it 'an empty Variant is not assignable to any type except empty Variant, Any, NotUndef, and Unit' do
assignables = [PUnitType, PAnyType, PNotUndefType]
unassignables = all_types - assignables
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/recursion_guard_spec.rb | spec/unit/pops/types/recursion_guard_spec.rb | require 'spec_helper'
require 'puppet/pops/types/recursion_guard'
module Puppet::Pops::Types
describe 'the RecursionGuard' do
let(:guard) { RecursionGuard.new }
it "should detect recursion in 'this' context" do
x = Object.new
expect(guard.add_this(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
expect(guard.add_this(x)).to eq(RecursionGuard::SELF_RECURSION_IN_THIS)
end
it "should detect recursion in 'that' context" do
x = Object.new
expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
expect(guard.add_that(x)).to eq(RecursionGuard::SELF_RECURSION_IN_THAT)
end
it "should keep 'this' and 'that' context separate" do
x = Object.new
expect(guard.add_this(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
end
it "should detect when there's a recursion in both 'this' and 'that' context" do
x = Object.new
y = Object.new
expect(guard.add_this(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
expect(guard.add_that(y)).to eq(RecursionGuard::NO_SELF_RECURSION)
expect(guard.add_this(x)).to eq(RecursionGuard::SELF_RECURSION_IN_THIS)
expect(guard.add_that(y)).to eq(RecursionGuard::SELF_RECURSION_IN_BOTH)
end
it "should report that 'this' is recursive after a recursion has been detected" do
x = Object.new
guard.add_this(x)
guard.add_this(x)
expect(guard.recursive_this?(x)).to be_truthy
end
it "should report that 'that' is recursive after a recursion has been detected" do
x = Object.new
guard.add_that(x)
guard.add_that(x)
expect(guard.recursive_that?(x)).to be_truthy
end
it "should not report that 'this' is recursive after a recursion of 'that' has been detected" do
x = Object.new
guard.add_that(x)
guard.add_that(x)
expect(guard.recursive_this?(x)).to be_falsey
end
it "should not report that 'that' is recursive after a recursion of 'this' has been detected" do
x = Object.new
guard.add_that(x)
guard.add_that(x)
expect(guard.recursive_this?(x)).to be_falsey
end
it "should not call 'hash' on an added instance" do
x = double()
expect(x).not_to receive(:hash)
expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
end
it "should not call '==' on an added instance" do
x = double()
expect(x).not_to receive(:==)
expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
end
it "should not call 'eq?' on an added instance" do
x = double()
expect(x).not_to receive(:eq?)
expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
end
it "should not call 'eql?' on an added instance" do
x = double()
expect(x).not_to receive(:eql?)
expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
end
it "should not call 'equal?' on an added instance" do
x = double()
expect(x).not_to receive(:equal?)
expect(guard.add_that(x)).to eq(RecursionGuard::NO_SELF_RECURSION)
end
end
end | ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/type_factory_spec.rb | spec/unit/pops/types/type_factory_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Types
describe 'The type factory' do
context 'when creating' do
it 'integer() returns PIntegerType' do
expect(TypeFactory.integer().class()).to eq(PIntegerType)
end
it 'float() returns PFloatType' do
expect(TypeFactory.float().class()).to eq(PFloatType)
end
it 'string() returns PStringType' do
expect(TypeFactory.string().class()).to eq(PStringType)
end
it 'boolean() returns PBooleanType' do
expect(TypeFactory.boolean().class()).to eq(PBooleanType)
end
it 'pattern() returns PPatternType' do
expect(TypeFactory.pattern().class()).to eq(PPatternType)
end
it 'regexp() returns PRegexpType' do
expect(TypeFactory.regexp().class()).to eq(PRegexpType)
end
it 'enum() returns PEnumType' do
expect(TypeFactory.enum().class()).to eq(PEnumType)
end
it 'variant() returns PVariantType' do
expect(TypeFactory.variant().class()).to eq(PVariantType)
end
it 'scalar() returns PScalarType' do
expect(TypeFactory.scalar().class()).to eq(PScalarType)
end
it 'data() returns Data' do
expect(TypeFactory.data.name).to eq('Data')
end
it 'optional() returns POptionalType' do
expect(TypeFactory.optional().class()).to eq(POptionalType)
end
it 'collection() returns PCollectionType' do
expect(TypeFactory.collection().class()).to eq(PCollectionType)
end
it 'catalog_entry() returns PCatalogEntryType' do
expect(TypeFactory.catalog_entry().class()).to eq(PCatalogEntryType)
end
it 'struct() returns PStructType' do
expect(TypeFactory.struct().class()).to eq(PStructType)
end
it "object() returns PObjectType" do
expect(TypeFactory.object.class).to eq(PObjectType)
end
it 'tuple() returns PTupleType' do
expect(TypeFactory.tuple.class()).to eq(PTupleType)
end
it 'undef() returns PUndefType' do
expect(TypeFactory.undef().class()).to eq(PUndefType)
end
it 'type_alias() returns PTypeAliasType' do
expect(TypeFactory.type_alias().class()).to eq(PTypeAliasType)
end
it 'sem_ver() returns PSemVerType' do
expect(TypeFactory.sem_ver.class).to eq(PSemVerType)
end
it 'sem_ver(r1, r2) returns constrained PSemVerType' do
expect(TypeFactory.sem_ver('1.x', '3.x').ranges).to include(SemanticPuppet::VersionRange.parse('1.x'), SemanticPuppet::VersionRange.parse('3.x'))
end
it 'sem_ver_range() returns PSemVerRangeType' do
expect(TypeFactory.sem_ver_range.class).to eq(PSemVerRangeType)
end
it 'default() returns PDefaultType' do
expect(TypeFactory.default().class()).to eq(PDefaultType)
end
it 'range(to, from) returns PIntegerType' do
t = TypeFactory.range(1,2)
expect(t.class()).to eq(PIntegerType)
expect(t.from).to eq(1)
expect(t.to).to eq(2)
end
it 'range(default, default) returns PIntegerType' do
t = TypeFactory.range(:default,:default)
expect(t.class()).to eq(PIntegerType)
expect(t.from).to eq(nil)
expect(t.to).to eq(nil)
end
it 'float_range(to, from) returns PFloatType' do
t = TypeFactory.float_range(1.0, 2.0)
expect(t.class()).to eq(PFloatType)
expect(t.from).to eq(1.0)
expect(t.to).to eq(2.0)
end
it 'float_range(default, default) returns PFloatType' do
t = TypeFactory.float_range(:default, :default)
expect(t.class()).to eq(PFloatType)
expect(t.from).to eq(nil)
expect(t.to).to eq(nil)
end
it 'resource() creates a generic PResourceType' do
pr = TypeFactory.resource()
expect(pr.class()).to eq(PResourceType)
expect(pr.type_name).to eq(nil)
end
it 'resource(x) creates a PResourceType[x]' do
pr = TypeFactory.resource('x')
expect(pr.class()).to eq(PResourceType)
expect(pr.type_name).to eq('X')
end
it 'host_class() creates a generic PClassType' do
hc = TypeFactory.host_class()
expect(hc.class()).to eq(PClassType)
expect(hc.class_name).to eq(nil)
end
it 'host_class(x) creates a PClassType[x]' do
hc = TypeFactory.host_class('x')
expect(hc.class()).to eq(PClassType)
expect(hc.class_name).to eq('x')
end
it 'host_class(::x) creates a PClassType[x]' do
hc = TypeFactory.host_class('::x')
expect(hc.class()).to eq(PClassType)
expect(hc.class_name).to eq('x')
end
it 'array_of(integer) returns PArrayType[PIntegerType]' do
at = TypeFactory.array_of(1)
expect(at.class()).to eq(PArrayType)
expect(at.element_type.class).to eq(PIntegerType)
end
it 'array_of(PIntegerType) returns PArrayType[PIntegerType]' do
at = TypeFactory.array_of(PIntegerType::DEFAULT)
expect(at.class()).to eq(PArrayType)
expect(at.element_type.class).to eq(PIntegerType)
end
it 'array_of_data returns Array[Data]' do
at = TypeFactory.array_of_data
expect(at.class()).to eq(PArrayType)
expect(at.element_type.name).to eq('Data')
end
it 'hash_of_data returns Hash[String,Data]' do
ht = TypeFactory.hash_of_data
expect(ht.class()).to eq(PHashType)
expect(ht.key_type.class).to eq(PStringType)
expect(ht.value_type.name).to eq('Data')
end
it 'ruby(1) returns PRuntimeType[ruby, \'Integer\']' do
ht = TypeFactory.ruby(1)
expect(ht.class()).to eq(PRuntimeType)
expect(ht.runtime).to eq(:ruby)
expect(ht.runtime_type_name).to eq(1.class.name)
end
it 'a size constrained collection can be created from array' do
t = TypeFactory.array_of(TypeFactory.data, TypeFactory.range(1,2))
expect(t.size_type.class).to eq(PIntegerType)
expect(t.size_type.from).to eq(1)
expect(t.size_type.to).to eq(2)
end
it 'a size constrained collection can be created from hash' do
t = TypeFactory.hash_of(TypeFactory.scalar, TypeFactory.data, TypeFactory.range(1,2))
expect(t.size_type.class).to eq(PIntegerType)
expect(t.size_type.from).to eq(1)
expect(t.size_type.to).to eq(2)
end
it 'a typed empty array, the resulting array erases the type' do
t = Puppet::Pops::Types::TypeFactory.array_of(Puppet::Pops::Types::TypeFactory.data, Puppet::Pops::Types::TypeFactory.range(0,0))
expect(t.size_type.class).to eq(Puppet::Pops::Types::PIntegerType)
expect(t.size_type.from).to eq(0)
expect(t.size_type.to).to eq(0)
expect(t.element_type).to eq(Puppet::Pops::Types::PUnitType::DEFAULT)
end
it 'a typed empty hash, the resulting hash erases the key and value type' do
t = Puppet::Pops::Types::TypeFactory.hash_of(Puppet::Pops::Types::TypeFactory.scalar, Puppet::Pops::Types::TypeFactory.data, Puppet::Pops::Types::TypeFactory.range(0,0))
expect(t.size_type.class).to eq(Puppet::Pops::Types::PIntegerType)
expect(t.size_type.from).to eq(0)
expect(t.size_type.to).to eq(0)
expect(t.key_type).to eq(Puppet::Pops::Types::PUnitType::DEFAULT)
expect(t.value_type).to eq(Puppet::Pops::Types::PUnitType::DEFAULT)
end
context 'callable types' do
it 'the callable methods produces a Callable' do
t = TypeFactory.callable()
expect(t.class).to be(PCallableType)
expect(t.param_types.class).to be(PTupleType)
expect(t.param_types.types).to be_empty
expect(t.block_type).to be_nil
end
it 'callable method with types produces the corresponding Tuple for parameters and generated names' do
tf = TypeFactory
t = tf.callable(tf.integer, tf.string)
expect(t.class).to be(PCallableType)
expect(t.param_types.class).to be(PTupleType)
expect(t.param_types.types).to eql([tf.integer, tf.string])
expect(t.block_type).to be_nil
end
it 'callable accepts min range to be given' do
tf = TypeFactory
t = tf.callable(tf.integer, tf.string, 1)
expect(t.class).to be(PCallableType)
expect(t.param_types.class).to be(PTupleType)
expect(t.param_types.size_type.from).to eql(1)
expect(t.param_types.size_type.to).to be_nil
end
it 'callable accepts max range to be given' do
tf = TypeFactory
t = tf.callable(tf.integer, tf.string, 1, 3)
expect(t.class).to be(PCallableType)
expect(t.param_types.class).to be(PTupleType)
expect(t.param_types.size_type.from).to eql(1)
expect(t.param_types.size_type.to).to eql(3)
end
it 'callable accepts max range to be given as :default' do
tf = TypeFactory
t = tf.callable(tf.integer, tf.string, 1, :default)
expect(t.class).to be(PCallableType)
expect(t.param_types.class).to be(PTupleType)
expect(t.param_types.size_type.from).to eql(1)
expect(t.param_types.size_type.to).to be_nil
end
it 'the all_callables method produces a Callable matching any Callable' do
t = TypeFactory.all_callables()
expect(t.class).to be(PCallableType)
expect(t.param_types).to be_nil
expect(t.block_type).to be_nil
end
it 'with block are created by placing a Callable last' do
block_t = TypeFactory.callable(String)
t = TypeFactory.callable(String, block_t)
expect(t.block_type).to be(block_t)
end
it 'min size constraint can be used with a block last' do
block_t = TypeFactory.callable(String)
t = TypeFactory.callable(String, 1, block_t)
expect(t.block_type).to be(block_t)
expect(t.param_types.size_type.from).to eql(1)
expect(t.param_types.size_type.to).to be_nil
end
it 'min, max size constraint can be used with a block last' do
block_t = TypeFactory.callable(String)
t = TypeFactory.callable(String, 1, 3, block_t)
expect(t.block_type).to be(block_t)
expect(t.param_types.size_type.from).to eql(1)
expect(t.param_types.size_type.to).to eql(3)
end
it 'the with_block methods decorates a Callable with a block_type' do
t = TypeFactory.callable
t2 = TypeFactory.callable(t)
block_t = t2.block_type
# given t is returned after mutation
expect(block_t).to be(t)
expect(block_t.class).to be(PCallableType)
expect(block_t.param_types.class).to be(PTupleType)
expect(block_t.param_types.types).to be_empty
expect(block_t.block_type).to be_nil
end
it 'the with_optional_block methods decorates a Callable with an optional block_type' do
b = TypeFactory.callable
t = TypeFactory.optional(b)
t2 = TypeFactory.callable(t)
opt_t = t2.block_type
expect(opt_t.class).to be(POptionalType)
block_t = opt_t.optional_type
# given t is returned after mutation
expect(opt_t).to be(t)
expect(block_t).to be(b)
expect(block_t.class).to be(PCallableType)
expect(block_t.param_types.class).to be(PTupleType)
expect(block_t.param_types.types).to be_empty
expect(block_t.block_type).to be_nil
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/task_spec.rb | spec/unit/pops/types/task_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
require 'puppet/parser/script_compiler'
module Puppet::Pops
module Types
describe 'The Task Type' do
include PuppetSpec::Compiler
include PuppetSpec::Files
context 'when loading' do
let(:testing_env) do
{
'testing' => {
'modules' => modules,
'manifests' => manifests
}
}
end
let(:manifests) { {} }
let(:environments_dir) { Puppet[:environmentpath] }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'testing')
PuppetSpec::Files.record_tmp(env_dir)
env_dir
end
let(:modules_dir) { File.join(testing_env_dir, 'modules') }
let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) }
let(:node) { Puppet::Node.new('test', :environment => env) }
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } }
let(:task_t) { TypeFactory.task }
before(:each) { Puppet[:tasks] = true }
context 'tasks' do
let(:compiler) { Puppet::Parser::ScriptCompiler.new(env, node.name) }
let(:modules) do
{ 'testmodule' => testmodule }
end
let(:module_loader) { Puppet.lookup(:loaders).find_loader('testmodule') }
def compile(code = nil)
Puppet[:code] = code
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
compiler.compile do |catalog|
yield if block_given?
catalog
end
end
end
context 'without metadata' do
let(:testmodule) {
{
'tasks' => {
'hello' => <<-RUBY
require 'json'
args = JSON.parse(STDIN.read)
puts({message: args['message']}.to_json)
exit 0
RUBY
}
}
}
it 'loads task without metadata as a generic Task' do
compile do
task = module_loader.load(:task, 'testmodule::hello')
expect(task_t.instance?(task)).to be_truthy
expect(task.name).to eq('testmodule::hello')
expect(task._pcore_type).to eq(task_t)
end
end
context 'without --tasks' do
before(:each) { Puppet[:tasks] = false }
it 'evaluator does not recognize generic tasks' do
compile do
expect(module_loader.load(:task, 'testmodule::hello')).to be_nil
end
end
end
end
context 'with metadata' do
let(:testmodule) {
{
'tasks' => {
'hello.rb' => <<-RUBY,
require 'json'
args = JSON.parse(STDIN.read)
puts({message: args['message']}.to_json)
exit 0
RUBY
'hello.json' => <<-JSON,
{
"puppet_task_version": 1,
"supports_noop": true,
"parameters": {
"message": {
"type": "String",
"description": "the message",
"sensitive": false
},
"font": {
"type": "Optional[String]"
}
}}
JSON
'non_data.rb' => <<-RUBY,
require 'json'
args = JSON.parse(STDIN.read)
puts({message: args['message']}.to_json)
exit 0
RUBY
'non_data.json' => <<-JSON
{
"puppet_task_version": 1,
"supports_noop": true,
"parameters": {
"arg": {
"type": "Hash",
"description": "the non data param"
}
}}
JSON
}
}
}
it 'loads a task with parameters' do
compile do
task = module_loader.load(:task, 'testmodule::hello')
expect(task_t.instance?(task)).to be_truthy
expect(task.name).to eq('testmodule::hello')
expect(task._pcore_type).to eq(task_t)
expect(task.metadata['supports_noop']).to eql(true)
expect(task.metadata['puppet_task_version']).to eql(1)
expect(task.files).to eql([{"name" => "hello.rb", "path" => "#{modules_dir}/testmodule/tasks/hello.rb"}])
expect(task.metadata['parameters']['message']['description']).to eql('the message')
expect(task.parameters['message']).to be_a(Puppet::Pops::Types::PStringType)
end
end
it 'loads a task with non-Data parameter' do
compile do
task = module_loader.load(:task, 'testmodule::non_data')
expect(task_t.instance?(task)).to be_truthy
expect(task.parameters['arg']).to be_a(Puppet::Pops::Types::PHashType)
end
end
context 'without an implementation file' do
let(:testmodule) {
{
'tasks' => {
'init.json' => '{}'
}
}
}
it 'fails to load the task' do
compile do
expect {
module_loader.load(:task, 'testmodule')
}.to raise_error(Puppet::Module::Task::InvalidTask, /No source besides task metadata was found/)
end
end
end
context 'with multiple implementation files' do
let(:metadata) { '{}' }
let(:testmodule) {
{
'tasks' => {
'init.sh' => '',
'init.ps1' => '',
'init.json' => metadata,
}
}
}
it "fails if metadata doesn't specify implementations" do
compile do
expect {
module_loader.load(:task, 'testmodule')
}.to raise_error(Puppet::Module::Task::InvalidTask, /Multiple executables were found .*/)
end
end
it "returns the implementations if metadata lists them all" do
impls = [{'name' => 'init.sh', 'requirements' => ['shell']},
{'name' => 'init.ps1', 'requirements' => ['powershell']}]
metadata.replace({'implementations' => impls}.to_json)
compile do
task = module_loader.load(:task, 'testmodule')
expect(task_t.instance?(task)).to be_truthy
expect(task.files).to eql([
{"name" => "init.sh", "path" => "#{modules_dir}/testmodule/tasks/init.sh"},
{"name" => "init.ps1", "path" => "#{modules_dir}/testmodule/tasks/init.ps1"}
])
expect(task.metadata['implementations']).to eql([
{"name" => "init.sh", "requirements" => ['shell']},
{"name" => "init.ps1", "requirements" => ['powershell']}
])
end
end
it "returns a single implementation if metadata only specifies one implementation" do
impls = [{'name' => 'init.ps1', 'requirements' => ['powershell']}]
metadata.replace({'implementations' => impls}.to_json)
compile do
task = module_loader.load(:task, 'testmodule')
expect(task_t.instance?(task)).to be_truthy
expect(task.files).to eql([
{"name" => "init.ps1", "path" => "#{modules_dir}/testmodule/tasks/init.ps1"}
])
expect(task.metadata['implementations']).to eql([
{"name" => "init.ps1", "requirements" => ['powershell']}
])
end
end
it "fails if a specified implementation doesn't exist" do
impls = [{'name' => 'init.sh', 'requirements' => ['shell']},
{'name' => 'init.ps1', 'requirements' => ['powershell']},
{'name' => 'init.rb', 'requirements' => ['puppet-agent']}]
metadata.replace({'implementations' => impls}.to_json)
compile do
expect {
module_loader.load(:task, 'testmodule')
}.to raise_error(Puppet::Module::Task::InvalidTask, /Task metadata for task testmodule specifies missing implementation init\.rb/)
end
end
it "fails if the implementations key isn't an array" do
metadata.replace({'implementations' => {'init.rb' => []}}.to_json)
compile do
expect {
module_loader.load(:task, 'testmodule')
}.to raise_error(Puppet::Module::Task::InvalidMetadata, /Task metadata for task testmodule does not specify implementations as an array/)
end
end
end
context 'with multiple tasks sharing executables' do
let(:foo_metadata) { '{}' }
let(:bar_metadata) { '{}' }
let(:testmodule) {
{
'tasks' => {
'foo.sh' => '',
'foo.ps1' => '',
'foo.json' => foo_metadata,
'bar.json' => bar_metadata,
'baz.json' => bar_metadata,
}
}
}
it 'loads a task that uses executables named after another task' do
metadata = {
implementations: [
{name: 'foo.sh', requirements: ['shell']},
{name: 'foo.ps1', requirements: ['powershell']},
]
}
bar_metadata.replace(metadata.to_json)
compile do
task = module_loader.load(:task, 'testmodule::bar')
expect(task.files).to eql([
{'name' => 'foo.sh', 'path' => "#{modules_dir}/testmodule/tasks/foo.sh"},
{'name' => 'foo.ps1', 'path' => "#{modules_dir}/testmodule/tasks/foo.ps1"},
])
end
end
it 'fails to load the task if it has no implementations section and no associated executables' do
compile do
expect {
module_loader.load(:task, 'testmodule::bar')
}.to raise_error(Puppet::Module::Task::InvalidTask, /No source besides task metadata was found/)
end
end
it 'fails to load the task if it has no files at all' do
compile do
expect(module_loader.load(:task, 'testmodule::qux')).to be_nil
end
end
end
context 'with adjacent directory for init task' do
let(:testmodule) {
{
'tasks' => {
'init' => {
'foo.sh' => 'echo hello'
},
'init.sh' => 'echo hello',
'init.json' => <<-JSON
{
"supports_noop": true,
"parameters": {
"message": { "type": "String" }
}
}
JSON
}
}
}
it 'loads the init task with parameters and implementations' do
compile do
task = module_loader.load(:task, 'testmodule')
expect(task_t.instance?(task)).to be_truthy
expect(task.files).to eql([{"name" => "init.sh", "path" => "#{modules_dir}/testmodule/tasks/init.sh"}])
expect(task.metadata['parameters']).to be_a(Hash)
expect(task.parameters['message']).to be_a(Puppet::Pops::Types::PStringType)
end
end
end
context 'with adjacent directory for named task' do
let(:testmodule) {
{
'tasks' => {
'hello' => {
'foo.sh' => 'echo hello'
},
'hello.sh' => 'echo hello',
'hello.json' => <<-JSON
{
"supports_noop": true,
"parameters": {
"message": { "type": "String" }
}
}
JSON
}
}
}
it 'loads a named task with parameters and implementations' do
compile do
task = module_loader.load(:task, 'testmodule::hello')
expect(task_t.instance?(task)).to be_truthy
expect(task.files).to eql([{"name" => "hello.sh", "path" => "#{modules_dir}/testmodule/tasks/hello.sh"}])
expect(task.metadata['parameters']).to be_a(Hash)
expect(task.parameters['message']).to be_a(Puppet::Pops::Types::PStringType)
end
end
end
context 'using more than two segments in the name' do
let(:testmodule) {
{
'tasks' => {
'hello' => {
'foo.sh' => 'echo hello'
}
}
}
}
it 'task is not found' do
compile do
expect(module_loader.load(:task, 'testmodule::hello::foo')).to be_nil
end
end
end
context 'that has no parameters' do
let(:testmodule) {
{
'tasks' => {
'hello' => 'echo hello',
'hello.json' => '{ "supports_noop": false }' }
}
}
it 'loads the task with parameters set to undef' do
compile do
task = module_loader.load(:task, 'testmodule::hello')
expect(task_t.instance?(task)).to be_truthy
expect(task.metadata['parameters']).to be_nil
end
end
end
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/deferred_spec.rb | spec/unit/pops/types/deferred_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Deferred type' do
context 'when used in Puppet expressions' do
include PuppetSpec::Compiler
it 'is equal to itself only' do
expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true false false))
$t = Deferred
notice(Deferred =~ Type[Deferred])
notice(Deferred == Deferred)
notice(Deferred < Deferred)
notice(Deferred > Deferred)
CODE
end
context 'a Deferred instance' do
it 'can be created using positional arguments' do
code = <<-CODE
$o = Deferred('michelangelo', [1,2,3])
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq([
"Deferred({'name' => 'michelangelo', 'arguments' => [1, 2, 3]})"
])
end
it 'can be created using named arguments' do
code = <<-CODE
$o = Deferred(name =>'michelangelo', arguments => [1,2,3])
notice($o)
CODE
expect(eval_and_collect_notices(code)).to eq([
"Deferred({'name' => 'michelangelo', 'arguments' => [1, 2, 3]})"
])
end
it 'is inferred to have the type Deferred' do
pending 'bug in type() function outputs the entire pcore definition'
code = <<-CODE
$o = Deferred('michelangelo', [1,2,3])
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq([
"Deferred"
])
end
it 'exposes name' do
code = <<-CODE
$o = Deferred(name =>'michelangelo', arguments => [1,2,3])
notice($o.name)
CODE
expect(eval_and_collect_notices(code)).to eq(["michelangelo"])
end
it 'exposes arguments' do
code = <<-CODE
$o = Deferred(name =>'michelangelo', arguments => [1,2,3])
notice($o.arguments)
CODE
expect(eval_and_collect_notices(code)).to eq(["[1, 2, 3]"])
end
it 'is an instance of its inferred type' do
code = <<-CODE
$o = Deferred(name =>'michelangelo', arguments => [1,2,3])
notice($o =~ type($o))
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'is an instance of Deferred' do
code = <<-CODE
$o = Deferred(name =>'michelangelo', arguments => [1,2,3])
notice($o =~ Deferred)
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/type_acceptor_spec.rb | spec/unit/pops/types/type_acceptor_spec.rb | require 'spec_helper'
require 'puppet/pops/types/type_acceptor'
class PuppetSpec::TestTypeAcceptor
include Puppet::Pops::Types::TypeAcceptor
attr_reader :visitors, :guard
def initialize
@visitors = []
@guard = nil
end
def visit(type, guard)
@visitors << type
@guard = guard
end
end
module Puppet::Pops::Types
describe 'the Puppet::Pops::Types::TypeAcceptor' do
let!(:acceptor_class) { PuppetSpec::TestTypeAcceptor }
let(:acceptor) { acceptor_class.new }
let(:guard) { RecursionGuard.new }
it "should get a visit from the type that accepts it" do
PAnyType::DEFAULT.accept(acceptor, nil)
expect(acceptor.visitors).to include(PAnyType::DEFAULT)
end
it "should receive the guard as an argument" do
PAnyType::DEFAULT.accept(acceptor, guard)
expect(acceptor.guard).to equal(guard)
end
it "should get a visit from the type of a Type that accepts it" do
t = PTypeType.new(PAnyType::DEFAULT)
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PAnyType::DEFAULT)
end
[
PTypeType,
PNotUndefType,
PIterableType,
PIteratorType,
POptionalType
].each do |tc|
it "should get a visit from the contained type of an #{tc.class.name} that accepts it" do
t = tc.new(PStringType::DEFAULT)
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PStringType::DEFAULT)
end
end
it "should get a visit from the size type of String type that accepts it" do
sz = PIntegerType.new(0,4)
t = PStringType.new(sz)
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, sz)
end
it "should get a visit from all contained types of an Array type that accepts it" do
sz = PIntegerType.new(0,4)
t = PArrayType.new(PAnyType::DEFAULT, sz)
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PAnyType::DEFAULT, sz)
end
it "should get a visit from all contained types of a Hash type that accepts it" do
sz = PIntegerType.new(0,4)
t = PHashType.new(PStringType::DEFAULT, PAnyType::DEFAULT, sz)
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PAnyType::DEFAULT, sz)
end
it "should get a visit from all contained types of a Tuple type that accepts it" do
sz = PIntegerType.new(0,4)
t = PTupleType.new([PStringType::DEFAULT, PIntegerType::DEFAULT], sz)
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT, sz)
end
it "should get a visit from all contained types of a Struct type that accepts it" do
t = PStructType.new([PStructElement.new(PStringType::DEFAULT, PIntegerType::DEFAULT)])
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT)
end
it "should get a visit from all contained types of a Callable type that accepts it" do
sz = PIntegerType.new(0,4)
args = PTupleType.new([PStringType::DEFAULT, PIntegerType::DEFAULT], sz)
block = PCallableType::DEFAULT
t = PCallableType.new(args, block)
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT, sz, args, block)
end
it "should get a visit from all contained types of a Variant type that accepts it" do
t = PVariantType.new([PStringType::DEFAULT, PIntegerType::DEFAULT])
t.accept(acceptor, nil)
expect(acceptor.visitors).to include(t, PStringType::DEFAULT, PIntegerType::DEFAULT)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_sensitive_type_spec.rb | spec/unit/pops/types/p_sensitive_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Sensitive Type' do
include PuppetSpec::Compiler
context 'as a type' do
it 'can be created without a parameter with the type factory' do
t = TypeFactory.sensitive
expect(t).to be_a(PSensitiveType)
expect(t).to eql(PSensitiveType::DEFAULT)
end
it 'can be created with a parameter with the type factory' do
t = TypeFactory.sensitive(PIntegerType::DEFAULT)
expect(t).to be_a(PSensitiveType)
expect(t.type).to eql(PIntegerType::DEFAULT)
end
it 'string representation of unparameterized instance is "Sensitive"' do
expect(PSensitiveType::DEFAULT.to_s).to eql('Sensitive')
end
context 'when used in Puppet expressions' do
it 'is equal to itself only' do
code = <<-CODE
$t = Sensitive
notice(Sensitive =~ Type[ Sensitive ])
notice(Sensitive == Sensitive)
notice(Sensitive < Sensitive)
notice(Sensitive > Sensitive)
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true', 'false', 'false'])
end
context "when parameterized" do
it 'is equal other types with the same parameterization' do
code = <<-CODE
notice(Sensitive[String] == Sensitive[String])
notice(Sensitive[Numeric] != Sensitive[Integer])
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'true'])
end
it 'orders parameterized types based on the type system hierarchy' do
code = <<-CODE
notice(Sensitive[Numeric] > Sensitive[Integer])
notice(Sensitive[Numeric] < Sensitive[Integer])
CODE
expect(eval_and_collect_notices(code)).to eq(['true', 'false'])
end
it 'does not order incomparable parameterized types' do
code = <<-CODE
notice(Sensitive[String] < Sensitive[Integer])
notice(Sensitive[String] > Sensitive[Integer])
CODE
expect(eval_and_collect_notices(code)).to eq(['false', 'false'])
end
it 'generalizes passed types to prevent information leakage' do
code =<<-CODE
$it = String[7, 7]
$st = Sensitive[$it]
notice(type($st))
CODE
expect(eval_and_collect_notices(code)).to eq(['Type[Sensitive[String]]'])
end
end
end
end
context 'a Sensitive instance' do
it 'can be created from a string and does not leak its contents' do
code =<<-CODE
$o = Sensitive("hunter2")
notice($o)
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]', 'Sensitive[String]'])
end
it 'matches the appropriate parameterized type' do
code =<<-CODE
$o = Sensitive("hunter2")
notice(assert_type(Sensitive[String], $o))
notice(assert_type(Sensitive[String[7, 7]], $o))
CODE
expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]', 'Sensitive [value redacted]'])
end
it 'verifies the constrains of the parameterized type' do
pending "the ability to enforce constraints without leaking information"
code =<<-CODE
$o = Sensitive("hunter2")
notice(assert_type(Sensitive[String[10, 20]], $o))
CODE
expect {
eval_and_collect_notices(code)
}.to raise_error(Puppet::Error, /expects a Sensitive\[String\[10, 20\]\] value, got Sensitive\[String\[7, 7\]\]/)
end
it 'does not match an inappropriate parameterized type' do
code =<<-CODE
$o = Sensitive("hunter2")
notice(assert_type(Sensitive[Integer], $o) |$expected, $actual| {
"$expected != $actual"
})
CODE
expect(eval_and_collect_notices(code)).to eq(['Sensitive[Integer] != Sensitive[String]'])
end
it 'equals another instance with the same value' do
code =<<-CODE
$i = Sensitive('secret')
$o = Sensitive('secret')
notice($i == $o)
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'has equal hash keys for same values' do
code =<<-CODE
$i = Sensitive('secret')
$o = Sensitive('secret')
notice({$i => 1} == {$o => 1})
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'can be created from another sensitive instance ' do
code =<<-CODE
$o = Sensitive("hunter2")
$x = Sensitive($o)
notice(assert_type(Sensitive[String], $x))
CODE
expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]'])
end
it 'can be given to a user defined resource as a parameter' do
code =<<-CODE
define keeper_of_secrets(Sensitive $x) {
notice(assert_type(Sensitive[String], $x))
}
keeper_of_secrets { 'test': x => Sensitive("long toe") }
CODE
expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]'])
end
it 'can be given to a class as a parameter' do
code =<<-CODE
class keeper_of_secrets(Sensitive $x) {
notice(assert_type(Sensitive[String], $x))
}
class { 'keeper_of_secrets': x => Sensitive("long toe") }
CODE
expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]'])
end
it 'can be given to a function as a parameter' do
code =<<-CODE
function keeper_of_secrets(Sensitive $x) {
notice(assert_type(Sensitive[String], $x))
}
keeper_of_secrets(Sensitive("long toe"))
CODE
expect(eval_and_collect_notices(code)).to eq(['Sensitive [value redacted]'])
end
end
it "enforces wrapped type constraints" do
pending "the ability to enforce constraints without leaking information"
code =<<-CODE
class secrets_handler(Sensitive[Array[String[4, 8]]] $pwlist) {
notice($pwlist)
}
class { "secrets_handler":
pwlist => Sensitive(['hi', 'longlonglong'])
}
CODE
expect {
expect(eval_and_collect_notices(code))
}.to raise_error(Puppet::Error, /expects a String\[4, 8\], got String/)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/error_spec.rb | spec/unit/pops/types/error_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Error type' do
context 'when used in Puppet expressions' do
include PuppetSpec::Compiler
it 'is equal to itself only' do
expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true false false))
$t = Error
notice(Error =~ Type[Error])
notice(Error == Error)
notice(Error < Error)
notice(Error > Error)
CODE
end
context "when parameterized" do
it 'is equal other types with the same parameterization' do
code = <<-CODE
notice(Error['puppet/error'] == Error['puppet/error', default])
notice(Error['puppet/error', 'ouch'] == Error['puppet/error', 'ouch'])
notice(Error['puppet/error', 'ouch'] != Error['puppet/error', 'ouch!'])
CODE
expect(eval_and_collect_notices(code)).to eq(%w(true true true))
end
it 'is assignable from more qualified types' do
expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true true true))
notice(Error > Error['puppet/error'])
notice(Error['puppet/error'] > Error['puppet/error', 'ouch'])
notice(Error['puppet/error', default] > Error['puppet/error', 'ouch'])
CODE
end
it 'is not assignable unless kind is assignable' do
expect(eval_and_collect_notices(<<-CODE)).to eq(%w(true false true false true false true))
notice(Error[/a/] > Error['hah'])
notice(Error[/a/] > Error['hbh'])
notice(Error[Enum[a,b,c]] > Error[a])
notice(Error[Enum[a,b,c]] > Error[d])
notice(Error[Pattern[/a/, /b/]] > Error[a])
notice(Error[Pattern[/a/, /b/]] > Error[c])
notice(Error[Pattern[/a/, /b/]] > Error[Enum[a, b]])
CODE
end
it 'presents parsable string form' do
code = <<-CODE
notice(Error['a'])
notice(Error[/a/])
notice(Error[Enum['a', 'b']])
notice(Error[Pattern[/a/, /b/]])
notice(Error['a', default])
notice(Error[/a/, default])
notice(Error[Enum['a', 'b'], default])
notice(Error[Pattern[/a/, /b/], default])
notice(Error[default,'a'])
notice(Error[default,/a/])
notice(Error[default,Enum['a', 'b']])
notice(Error[default,Pattern[/a/, /b/]])
notice(Error['a','a'])
notice(Error[/a/,/a/])
notice(Error[Enum['a', 'b'],Enum['a', 'b']])
notice(Error[Pattern[/a/, /b/],Pattern[/a/, /b/]])
CODE
expect(eval_and_collect_notices(code)).to eq([
"Error['a']",
'Error[/a/]',
"Error[Enum['a', 'b']]",
"Error[Pattern[/a/, /b/]]",
"Error['a']",
'Error[/a/]',
"Error[Enum['a', 'b']]",
"Error[Pattern[/a/, /b/]]",
"Error[default, 'a']",
'Error[default, /a/]',
"Error[default, Enum['a', 'b']]",
"Error[default, Pattern[/a/, /b/]]",
"Error['a', 'a']",
'Error[/a/, /a/]',
"Error[Enum['a', 'b'], Enum['a', 'b']]",
"Error[Pattern[/a/, /b/], Pattern[/a/, /b/]]",
])
end
end
context 'an Error instance' do
it 'can be created using positional arguments' do
code = <<-CODE
$o = Error('bad things happened', 'puppet/error', {'detail' => 'val'}, 'OOPS')
notice($o)
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq([
"Error({'msg' => 'bad things happened', 'kind' => 'puppet/error', 'details' => {'detail' => 'val'}, 'issue_code' => 'OOPS'})",
"Error['puppet/error', 'OOPS']"
])
end
it 'can be created using named arguments' do
code = <<-CODE
$o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED')
notice($o)
notice(type($o))
CODE
expect(eval_and_collect_notices(code)).to eq([
"Error({'msg' => 'Sorry, not implemented', 'kind' => 'puppet/error', 'issue_code' => 'NOT_IMPLEMENTED'})",
"Error['puppet/error', 'NOT_IMPLEMENTED']"
])
end
it 'exposes message' do
code = <<-CODE
$o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED')
notice($o.message)
CODE
expect(eval_and_collect_notices(code)).to eq(["Sorry, not implemented"])
end
it 'exposes kind' do
code = <<-CODE
$o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED')
notice($o.kind)
CODE
expect(eval_and_collect_notices(code)).to eq(["puppet/error"])
end
it 'exposes issue_code' do
code = <<-CODE
$o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', issue_code => 'NOT_IMPLEMENTED')
notice($o.issue_code)
CODE
expect(eval_and_collect_notices(code)).to eq(["NOT_IMPLEMENTED"])
end
it 'exposes details' do
code = <<-CODE
$o = Error(msg => 'Sorry, not implemented', kind => 'puppet/error', details => { 'detailk' => 'detailv' })
notice($o.details)
CODE
expect(eval_and_collect_notices(code)).to eq(["{detailk => detailv}"])
end
it 'is an instance of its inferred type' do
code = <<-CODE
$o = Error('bad things happened', 'puppet/error')
notice($o =~ type($o))
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'is an instance of Error with matching kind' do
code = <<-CODE
$o = Error('bad things happened', 'puppet/error')
notice($o =~ Error[/puppet\\/error/])
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'is an instance of Error with matching issue_code' do
code = <<-CODE
$o = Error('bad things happened', 'puppet/error', {}, 'FEE')
notice($o =~ Error[default, 'FEE'])
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'is an instance of Error with matching kind and issue_code' do
code = <<-CODE
$o = Error('bad things happened', 'puppet/error', {}, 'FEE')
notice($o =~ Error['puppet/error', 'FEE'])
CODE
expect(eval_and_collect_notices(code)).to eq(['true'])
end
it 'is not an instance of Error unless kind matches' do
code = <<-CODE
$o = Error('bad things happened', 'puppetlabs/error')
notice($o =~ Error[/puppet\\/error/])
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'is not an instance of Error unless issue_code matches' do
code = <<-CODE
$o = Error('bad things happened', 'puppetlabs/error', {}, 'BAR')
notice($o =~ Error[default, 'FOO'])
CODE
expect(eval_and_collect_notices(code)).to eq(['false'])
end
it 'is not an instance of Error unless both kind and issue is a match' do
code = <<-CODE
$o = Error('bad things happened', 'puppet/error', {}, 'FEE')
notice($o =~ Error['puppetlabs/error', 'FEE'])
notice($o =~ Error['puppet/error', 'FUM'])
CODE
expect(eval_and_collect_notices(code)).to eq(['false', 'false'])
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/class_loader_spec.rb | spec/unit/pops/types/class_loader_spec.rb | require 'spec_helper'
require 'puppet/pops'
describe 'the Puppet::Pops::Types::ClassLoader' do
it 'should produce path alternatives for CamelCase classes' do
expected_paths = ['puppet_x/some_thing', 'puppetx/something']
# path_for_name method is private
expect(Puppet::Pops::Types::ClassLoader.send(:paths_for_name, ['PuppetX', 'SomeThing'])).to include(*expected_paths)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/type_formatter_spec.rb | spec/unit/pops/types/type_formatter_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops::Types
describe 'The type formatter' do
let(:s) { TypeFormatter.new }
let(:f) { TypeFactory }
def drop_indent(str)
ld = str.index("\n")
if ld.nil?
str
else
str.gsub(Regexp.compile("^ {#{ld - 1}}"), '')
end
end
context 'when representing a literal as a string' do
{
'true' => true,
'false' => false,
'undef' => nil,
'23.4' => 23.4,
'145' => 145,
"'string'" => 'string',
'/expr/' => /expr/,
'[1, 2, 3]' => [1, 2, 3],
"{'a' => 32, 'b' => [1, 2, 3]}" => {'a' => 32,'b' => [1, 2, 3]}
}.each_pair do |str, value|
it "should yield '#{str}' for a value of #{str}" do
expect(s.string(value)).to eq(str)
end
end
end
context 'when using indent' do
it 'should put hash entries on new indented lines' do
expect(s.indented_string({'a' => 32,'b' => [1, 2, {'c' => 'd'}]})).to eq(<<-FORMATTED)
{
'a' => 32,
'b' => [
1,
2,
{
'c' => 'd'
}
]
}
FORMATTED
end
it 'should start on given indent level' do
expect(s.indented_string({'a' => 32,'b' => [1, 2, {'c' => 'd'}]}, 3)).to eq(<<-FORMATTED)
{
'a' => 32,
'b' => [
1,
2,
{
'c' => 'd'
}
]
}
FORMATTED
end
it 'should use given indent width' do
expect(s.indented_string({'a' => 32,'b' => [1, 2, {'c' => 'd'}]}, 2, 4)).to eq(<<-FORMATTED)
{
'a' => 32,
'b' => [
1,
2,
{
'c' => 'd'
}
]
}
FORMATTED
end
end
context 'when representing the type as string' do
include_context 'types_setup'
it "should yield 'Type' for PTypeType" do
expect(s.string(f.type_type)).to eq('Type')
end
it "should yield 'Any' for PAnyType" do
expect(s.string(f.any)).to eq('Any')
end
it "should yield 'Scalar' for PScalarType" do
expect(s.string(f.scalar)).to eq('Scalar')
end
it "should yield 'Boolean' for PBooleanType" do
expect(s.string(f.boolean)).to eq('Boolean')
end
it "should yield 'Boolean[true]' for PBooleanType parameterized with true" do
expect(s.string(f.boolean(true))).to eq('Boolean[true]')
end
it "should yield 'Boolean[false]' for PBooleanType parameterized with false" do
expect(s.string(f.boolean(false))).to eq('Boolean[false]')
end
it "should yield 'Data' for the Data type" do
expect(s.string(f.data)).to eq('Data')
end
it "should yield 'Numeric' for PNumericType" do
expect(s.string(f.numeric)).to eq('Numeric')
end
it "should yield 'Integer' and from/to for PIntegerType" do
expect(s.string(f.integer)).to eq('Integer')
expect(s.string(f.range(1,1))).to eq('Integer[1, 1]')
expect(s.string(f.range(1,2))).to eq('Integer[1, 2]')
expect(s.string(f.range(:default, 2))).to eq('Integer[default, 2]')
expect(s.string(f.range(2, :default))).to eq('Integer[2]')
end
it "should yield 'Float' for PFloatType" do
expect(s.string(f.float)).to eq('Float')
end
it "should yield 'Regexp' for PRegexpType" do
expect(s.string(f.regexp)).to eq('Regexp')
end
it "should yield 'Regexp[/pat/]' for parameterized PRegexpType" do
expect(s.string(f.regexp('a/b'))).to eq('Regexp[/a\/b/]')
end
it "should yield 'String' for PStringType" do
expect(s.string(f.string)).to eq('String')
end
it "should yield 'String' for PStringType with value" do
expect(s.string(f.string('a'))).to eq('String')
end
it "should yield 'String['a']' for PStringType with value if printed with debug_string" do
expect(s.debug_string(f.string('a'))).to eq("String['a']")
end
it "should yield 'String' and from/to for PStringType" do
expect(s.string(f.string(f.range(1,1)))).to eq('String[1, 1]')
expect(s.string(f.string(f.range(1,2)))).to eq('String[1, 2]')
expect(s.string(f.string(f.range(:default, 2)))).to eq('String[0, 2]')
expect(s.string(f.string(f.range(2, :default)))).to eq('String[2]')
end
it "should yield 'Array[Integer]' for PArrayType[PIntegerType]" do
expect(s.string(f.array_of(f.integer))).to eq('Array[Integer]')
end
it "should yield 'Array' for PArrayType::DEFAULT" do
expect(s.string(f.array_of_any)).to eq('Array')
end
it "should yield 'Array[0, 0]' for an empty array" do
t = f.array_of(PUnitType::DEFAULT, f.range(0,0))
expect(s.string(t)).to eq('Array[0, 0]')
end
it "should yield 'Hash[0, 0]' for an empty hash" do
t = f.hash_of(PUnitType::DEFAULT, PUnitType::DEFAULT, f.range(0,0))
expect(s.string(t)).to eq('Hash[0, 0]')
end
it "should yield 'Collection' and from/to for PCollectionType" do
expect(s.string(f.collection(f.range(1,1)))).to eq('Collection[1, 1]')
expect(s.string(f.collection(f.range(1,2)))).to eq('Collection[1, 2]')
expect(s.string(f.collection(f.range(:default, 2)))).to eq('Collection[0, 2]')
expect(s.string(f.collection(f.range(2, :default)))).to eq('Collection[2]')
end
it "should yield 'Array' and from/to for PArrayType" do
expect(s.string(f.array_of(f.string, f.range(1,1)))).to eq('Array[String, 1, 1]')
expect(s.string(f.array_of(f.string, f.range(1,2)))).to eq('Array[String, 1, 2]')
expect(s.string(f.array_of(f.string, f.range(:default, 2)))).to eq('Array[String, 0, 2]')
expect(s.string(f.array_of(f.string, f.range(2, :default)))).to eq('Array[String, 2]')
end
it "should yield 'Iterable' for PIterableType" do
expect(s.string(f.iterable)).to eq('Iterable')
end
it "should yield 'Iterable[Integer]' for PIterableType[PIntegerType]" do
expect(s.string(f.iterable(f.integer))).to eq('Iterable[Integer]')
end
it "should yield 'Iterator' for PIteratorType" do
expect(s.string(f.iterator)).to eq('Iterator')
end
it "should yield 'Iterator[Integer]' for PIteratorType[PIntegerType]" do
expect(s.string(f.iterator(f.integer))).to eq('Iterator[Integer]')
end
it "should yield 'Timespan' for PTimespanType" do
expect(s.string(f.timespan())).to eq('Timespan')
end
it "should yield 'Timespan[{hours => 1}] for PTimespanType[Timespan]" do
expect(s.string(f.timespan({'hours' => 1}))).to eq("Timespan['0-01:00:00.0']")
end
it "should yield 'Timespan[default, {hours => 2}] for PTimespanType[nil, Timespan]" do
expect(s.string(f.timespan(nil, {'hours' => 2}))).to eq("Timespan[default, '0-02:00:00.0']")
end
it "should yield 'Timespan[{hours => 1}, {hours => 2}] for PTimespanType[Timespan, Timespan]" do
expect(s.string(f.timespan({'hours' => 1}, {'hours' => 2}))).to eq("Timespan['0-01:00:00.0', '0-02:00:00.0']")
end
it "should yield 'Timestamp' for PTimestampType" do
expect(s.string(f.timestamp())).to eq('Timestamp')
end
it "should yield 'Timestamp['2016-09-05T13:00:00.000 UTC'] for PTimestampType[Timestamp]" do
expect(s.string(f.timestamp('2016-09-05T13:00:00.000 UTC'))).to eq("Timestamp['2016-09-05T13:00:00.000000000 UTC']")
end
it "should yield 'Timestamp[default, '2016-09-05T13:00:00.000 UTC'] for PTimestampType[nil, Timestamp]" do
expect(s.string(f.timestamp(nil, '2016-09-05T13:00:00.000 UTC'))).to eq("Timestamp[default, '2016-09-05T13:00:00.000000000 UTC']")
end
it "should yield 'Timestamp['2016-09-05T13:00:00.000 UTC', '2016-12-01T00:00:00.000 UTC'] for PTimestampType[Timestamp, Timestamp]" do
expect(s.string(f.timestamp('2016-09-05T13:00:00.000 UTC', '2016-12-01T00:00:00.000 UTC'))).to(
eq("Timestamp['2016-09-05T13:00:00.000000000 UTC', '2016-12-01T00:00:00.000000000 UTC']"))
end
it "should yield 'Tuple[Integer]' for PTupleType[PIntegerType]" do
expect(s.string(f.tuple([f.integer]))).to eq('Tuple[Integer]')
end
it "should yield 'Tuple[T, T,..]' for PTupleType[T, T, ...]" do
expect(s.string(f.tuple([f.integer, f.integer, f.string]))).to eq('Tuple[Integer, Integer, String]')
end
it "should yield 'Tuple' and from/to for PTupleType" do
types = [f.string]
expect(s.string(f.tuple(types, f.range(1,1)))).to eq('Tuple[String, 1, 1]')
expect(s.string(f.tuple(types, f.range(1,2)))).to eq('Tuple[String, 1, 2]')
expect(s.string(f.tuple(types, f.range(:default, 2)))).to eq('Tuple[String, 0, 2]')
expect(s.string(f.tuple(types, f.range(2, :default)))).to eq('Tuple[String, 2]')
end
it "should yield 'Struct' and details for PStructType" do
struct_t = f.struct({'a'=>Integer, 'b'=>String})
expect(s.string(struct_t)).to eq("Struct[{'a' => Integer, 'b' => String}]")
struct_t = f.struct({})
expect(s.string(struct_t)).to eq('Struct')
end
it "should yield 'Hash[String, Integer]' for PHashType[PStringType, PIntegerType]" do
expect(s.string(f.hash_of(f.integer, f.string))).to eq('Hash[String, Integer]')
end
it "should yield 'Hash' and from/to for PHashType" do
expect(s.string(f.hash_of(f.string, f.string, f.range(1,1)))).to eq('Hash[String, String, 1, 1]')
expect(s.string(f.hash_of(f.string, f.string, f.range(1,2)))).to eq('Hash[String, String, 1, 2]')
expect(s.string(f.hash_of(f.string, f.string, f.range(:default, 2)))).to eq('Hash[String, String, 0, 2]')
expect(s.string(f.hash_of(f.string, f.string, f.range(2, :default)))).to eq('Hash[String, String, 2]')
end
it "should yield 'Hash' for PHashType::DEFAULT" do
expect(s.string(f.hash_of_any)).to eq('Hash')
end
it "should yield 'Class' for a PClassType" do
expect(s.string(f.host_class)).to eq('Class')
end
it "should yield 'Class[x]' for a PClassType[x]" do
expect(s.string(f.host_class('x'))).to eq('Class[x]')
end
it "should yield 'Resource' for a PResourceType" do
expect(s.string(f.resource)).to eq('Resource')
end
it "should yield 'File' for a PResourceType['File']" do
expect(s.string(f.resource('File'))).to eq('File')
end
it "should yield 'File['/tmp/foo']' for a PResourceType['File', '/tmp/foo']" do
expect(s.string(f.resource('File', '/tmp/foo'))).to eq("File['/tmp/foo']")
end
it "should yield 'Enum[s,...]' for a PEnumType[s,...]" do
t = f.enum('a', 'b', 'c')
expect(s.string(t)).to eq("Enum['a', 'b', 'c']")
end
it "should yield 'Enum[s,...]' for a PEnumType[s,...,false]" do
t = f.enum('a', 'b', 'c', false)
expect(s.string(t)).to eq("Enum['a', 'b', 'c']")
end
it "should yield 'Enum[s,...,true]' for a PEnumType[s,...,true]" do
t = f.enum('a', 'b', 'c', true)
expect(s.string(t)).to eq("Enum['a', 'b', 'c', true]")
end
it "should yield 'Pattern[/pat/,...]' for a PPatternType['pat',...]" do
t = f.pattern('a')
t2 = f.pattern('a', 'b', 'c')
expect(s.string(t)).to eq('Pattern[/a/]')
expect(s.string(t2)).to eq('Pattern[/a/, /b/, /c/]')
end
it "should escape special characters in the string for a PPatternType['pat',...]" do
t = f.pattern('a/b')
expect(s.string(t)).to eq("Pattern[/a\\/b/]")
end
it "should yield 'Variant[t1,t2,...]' for a PVariantType[t1, t2,...]" do
t1 = f.string
t2 = f.integer
t3 = f.pattern('a')
t = f.variant(t1, t2, t3)
expect(s.string(t)).to eq('Variant[String, Integer, Pattern[/a/]]')
end
it "should yield 'Callable' for generic callable" do
expect(s.string(f.all_callables)).to eql('Callable')
end
it "should yield 'Callable[0,0]' for callable without params" do
expect(s.string(f.callable)).to eql('Callable[0, 0]')
end
it "should yield 'Callable[[0,0],rt]' for callable without params but with return type" do
expect(s.string(f.callable([], Float))).to eql('Callable[[0, 0], Float]')
end
it "should yield 'Callable[t,t]' for callable with typed parameters" do
expect(s.string(f.callable(String, Integer))).to eql('Callable[String, Integer]')
end
it "should yield 'Callable[[t,t],rt]' for callable with typed parameters and return type" do
expect(s.string(f.callable([String, Integer], Float))).to eql('Callable[[String, Integer], Float]')
end
it "should yield 'Callable[t,min,max]' for callable with size constraint (infinite max)" do
expect(s.string(f.callable(String, 0))).to eql('Callable[String, 0]')
end
it "should yield 'Callable[t,min,max]' for callable with size constraint (capped max)" do
expect(s.string(f.callable(String, 0, 3))).to eql('Callable[String, 0, 3]')
end
it "should yield 'Callable[min,max]' callable with size > 0" do
expect(s.string(f.callable(0, 0))).to eql('Callable[0, 0]')
expect(s.string(f.callable(0, 1))).to eql('Callable[0, 1]')
expect(s.string(f.callable(0, :default))).to eql('Callable[0]')
end
it "should yield 'Callable[Callable]' for callable with block" do
expect(s.string(f.callable(f.all_callables))).to eql('Callable[0, 0, Callable]')
expect(s.string(f.callable(f.string, f.all_callables))).to eql('Callable[String, Callable]')
expect(s.string(f.callable(f.string, 1,1, f.all_callables))).to eql('Callable[String, 1, 1, Callable]')
end
it 'should yield Unit for a Unit type' do
expect(s.string(PUnitType::DEFAULT)).to eql('Unit')
end
it "should yield 'NotUndef' for a PNotUndefType" do
t = f.not_undef
expect(s.string(t)).to eq('NotUndef')
end
it "should yield 'NotUndef[T]' for a PNotUndefType[T]" do
t = f.not_undef(f.data)
expect(s.string(t)).to eq('NotUndef[Data]')
end
it "should yield 'NotUndef['string']' for a PNotUndefType['string']" do
t = f.not_undef('hey')
expect(s.string(t)).to eq("NotUndef['hey']")
end
it "should yield the name of an unparameterized type reference" do
t = f.type_reference('What')
expect(s.string(t)).to eq("TypeReference['What']")
end
it "should yield the name and arguments of an parameterized type reference" do
t = f.type_reference('What[Undef, String]')
expect(s.string(t)).to eq("TypeReference['What[Undef, String]']")
end
it "should yield the name of a type alias" do
t = f.type_alias('Alias', 'Integer')
expect(s.string(t)).to eq('Alias')
end
it "should yield 'Type[Runtime[ruby, Puppet]]' for the Puppet module" do
expect(s.string(Puppet)).to eq("Runtime[ruby, 'Puppet']")
end
it "should yield 'Type[Runtime[ruby, Puppet::Pops]]' for the Puppet::Resource class" do
expect(s.string(Puppet::Resource)).to eq("Runtime[ruby, 'Puppet::Resource']")
end
it "should yield \"SemVer['1.x', '3.x']\" for the PSemVerType['1.x', '3.x']" do
expect(s.string(PSemVerType.new(['1.x', '3.x']))).to eq("SemVer['1.x', '3.x']")
end
it 'should present a valid simple name' do
(all_types - [PTypeType, PClassType]).each do |t|
name = t::DEFAULT.simple_name
expect(t.name).to match("^Puppet::Pops::Types::P#{name}Type$")
end
expect(PTypeType::DEFAULT.simple_name).to eql('Type')
expect(PClassType::DEFAULT.simple_name).to eql('Class')
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/ruby_generator_spec.rb | spec/unit/pops/types/ruby_generator_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
require 'puppet/pops/types/ruby_generator'
def root_binding
return binding
end
module Puppet::Pops
module Types
describe 'Puppet Ruby Generator' do
include PuppetSpec::Compiler
let!(:parser) { TypeParser.singleton }
let(:generator) { RubyGenerator.new }
context 'when generating classes for Objects having attribute names that are Ruby reserved words' do
let (:source) { <<-PUPPET }
type MyObject = Object[{
attributes => {
alias => String,
begin => String,
break => String,
def => String,
do => String,
end => String,
ensure => String,
for => String,
module => String,
next => String,
nil => String,
not => String,
redo => String,
rescue => String,
retry => String,
return => String,
self => String,
super => String,
then => String,
until => String,
when => String,
while => String,
yield => String,
},
}]
$x = MyObject({
alias => 'value of alias',
begin => 'value of begin',
break => 'value of break',
def => 'value of def',
do => 'value of do',
end => 'value of end',
ensure => 'value of ensure',
for => 'value of for',
module => 'value of module',
next => 'value of next',
nil => 'value of nil',
not => 'value of not',
redo => 'value of redo',
rescue => 'value of rescue',
retry => 'value of retry',
return => 'value of return',
self => 'value of self',
super => 'value of super',
then => 'value of then',
until => 'value of until',
when => 'value of when',
while => 'value of while',
yield => 'value of yield',
})
notice($x.alias)
notice($x.begin)
notice($x.break)
notice($x.def)
notice($x.do)
notice($x.end)
notice($x.ensure)
notice($x.for)
notice($x.module)
notice($x.next)
notice($x.nil)
notice($x.not)
notice($x.redo)
notice($x.rescue)
notice($x.retry)
notice($x.return)
notice($x.self)
notice($x.super)
notice($x.then)
notice($x.until)
notice($x.when)
notice($x.while)
notice($x.yield)
PUPPET
it 'can create an instance and access all attributes' do
expect(eval_and_collect_notices(source)).to eql([
'value of alias',
'value of begin',
'value of break',
'value of def',
'value of do',
'value of end',
'value of ensure',
'value of for',
'value of module',
'value of next',
'value of nil',
'value of not',
'value of redo',
'value of rescue',
'value of retry',
'value of return',
'value of self',
'value of super',
'value of then',
'value of until',
'value of when',
'value of while',
'value of yield',
])
end
end
context 'when generating classes for Objects having function names that are Ruby reserved words' do
let (:source) { <<-PUPPET }
type MyObject = Object[{
functions => {
alias => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of alias'" }}},
begin => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of begin'" }}},
break => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of break'" }}},
def => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of def'" }}},
do => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of do'" }}},
end => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of end'" }}},
ensure => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of ensure'" }}},
for => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of for'" }}},
module => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of module'" }}},
next => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of next'" }}},
nil => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of nil'" }}},
not => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of not'" }}},
redo => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of redo'" }}},
rescue => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of rescue'" }}},
retry => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of retry'" }}},
return => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of return'" }}},
self => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of self'" }}},
super => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of super'" }}},
then => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of then'" }}},
until => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of until'" }}},
when => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of when'" }}},
while => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of while'" }}},
yield => { type => Callable[[0,0],String], annotations => {RubyMethod => { 'body' => "'value of yield'" }}},
},
}]
$x = MyObject()
notice($x.alias)
notice($x.begin)
notice($x.break)
notice($x.def)
notice($x.do)
notice($x.end)
notice($x.ensure)
notice($x.for)
notice($x.module)
notice($x.next)
notice($x.nil)
notice($x.not)
notice($x.redo)
notice($x.rescue)
notice($x.retry)
notice($x.return)
notice($x.self)
notice($x.super)
notice($x.then)
notice($x.until)
notice($x.when)
notice($x.while)
notice($x.yield)
PUPPET
it 'can create an instance and call all functions' do
expect(eval_and_collect_notices(source)).to eql([
'value of alias',
'value of begin',
'value of break',
'value of def',
'value of do',
'value of end',
'value of ensure',
'value of for',
'value of module',
'value of next',
'value of nil',
'value of not',
'value of redo',
'value of rescue',
'value of retry',
'value of return',
'value of self',
'value of super',
'value of then',
'value of until',
'value of when',
'value of while',
'value of yield',
])
end
end
context 'when generating from Object types' do
let (:type_decls) { <<-CODE.unindent }
type MyModule::FirstGenerated = Object[{
attributes => {
name => String,
age => { type => Integer, value => 30 },
what => { type => String, value => 'what is this', kind => constant },
uc_name => {
type => String,
kind => derived,
annotations => {
RubyMethod => { body => '@name.upcase' }
}
},
other_name => {
type => String,
kind => derived
},
},
functions => {
some_other => {
type => Callable[1,1]
},
name_and_age => {
type => Callable[1,1],
annotations => {
RubyMethod => {
parameters => 'joiner',
body => '"\#{@name}\#{joiner}\#{@age}"'
}
}
},
'[]' => {
type => Callable[1,1],
annotations => {
RubyMethod => {
parameters => 'key',
body => @(EOF)
case key
when 'name'
name
when 'age'
age
else
nil
end
|-EOF
}
}
}
}
}]
type MyModule::SecondGenerated = Object[{
parent => MyModule::FirstGenerated,
attributes => {
address => String,
zipcode => String,
email => String,
another => { type => Optional[MyModule::FirstGenerated], value => undef },
number => Integer,
aref => { type => Optional[MyModule::FirstGenerated], value => undef, kind => reference }
}
}]
CODE
let(:type_usage) { '' }
let(:source) { type_decls + type_usage }
context 'when generating anonymous classes' do
loader = nil
let(:first_type) { parser.parse('MyModule::FirstGenerated', loader) }
let(:second_type) { parser.parse('MyModule::SecondGenerated', loader) }
let(:first) { generator.create_class(first_type) }
let(:second) { generator.create_class(second_type) }
let(:notices) { [] }
before(:each) do
notices.concat(eval_and_collect_notices(source) do |topscope|
loader = topscope.compiler.loaders.find_loader(nil)
end)
end
context 'the generated class' do
it 'inherits the PuppetObject module' do
expect(first < PuppetObject).to be_truthy
end
it 'is the superclass of a generated subclass' do
expect(second < first).to be_truthy
end
end
context 'the #create class method' do
it 'has an arity that reflects optional arguments' do
expect(first.method(:create).arity).to eql(-2)
expect(second.method(:create).arity).to eql(-6)
end
it 'creates an instance of the class' do
inst = first.create('Bob Builder', 52)
expect(inst).to be_a(first)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(52)
end
it 'created instance has a [] method' do
inst = first.create('Bob Builder', 52)
expect(inst['name']).to eq('Bob Builder')
expect(inst['age']).to eq(52)
end
it 'will perform type assertion of the arguments' do
expect { first.create('Bob Builder', '52') }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String')
)
end
it 'will not accept nil as given value for an optional parameter that does not accept nil' do
expect { first.create('Bob Builder', nil) }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef')
)
end
it 'reorders parameters to but the optional parameters last' do
inst = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst.name).to eq('Bob Builder')
expect(inst.address).to eq('42 Cool Street')
expect(inst.zipcode).to eq('12345')
expect(inst.email).to eq('bob@example.com')
expect(inst.number).to eq(23)
expect(inst.what).to eql('what is this')
expect(inst.age).to eql(30)
expect(inst.another).to be_nil
end
it 'generates a code body for derived attribute from a RubyMethod body attribute' do
inst = first.create('Bob Builder', 52)
expect(inst.uc_name).to eq('BOB BUILDER')
end
it "generates a code body with 'not implemented' in the absense of a RubyMethod body attribute" do
inst = first.create('Bob Builder', 52)
expect { inst.other_name }.to raise_error(/no method is implemented for derived attribute MyModule::FirstGenerated\[other_name\]/)
end
it 'generates parameter list and a code body for derived function from a RubyMethod body attribute' do
inst = first.create('Bob Builder', 52)
expect(inst.name_and_age(' of age ')).to eq('Bob Builder of age 52')
end
end
context 'the #from_hash class method' do
it 'has an arity of one' do
expect(first.method(:from_hash).arity).to eql(1)
expect(second.method(:from_hash).arity).to eql(1)
end
it 'creates an instance of the class' do
inst = first.from_hash('name' => 'Bob Builder', 'age' => 52)
expect(inst).to be_a(first)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(52)
end
it 'accepts an initializer where optional keys are missing' do
inst = first.from_hash('name' => 'Bob Builder')
expect(inst).to be_a(first)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(30)
end
it 'does not accept an initializer where optional values are nil and type does not accept nil' do
expect { first.from_hash('name' => 'Bob Builder', 'age' => nil) }.to(
raise_error(TypeAssertionError,
"MyModule::FirstGenerated initializer has wrong type, entry 'age' expects an Integer value, got Undef")
)
end
end
context 'creates an instance' do
it 'that the TypeCalculator infers to the Object type' do
expect(TypeCalculator.infer(first.from_hash('name' => 'Bob Builder'))).to eq(first_type)
end
it "where attributes of kind 'reference' are not considered part of #_pcore_all_contents" do
inst = first.from_hash('name' => 'Bob Builder')
wrinst = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23, 40, inst, inst)
results = []
wrinst._pcore_all_contents([]) { |v| results << v }
expect(results).to eq([inst])
end
end
context 'when used from Puppet' do
let(:type_usage) { <<-PUPPET.unindent }
$i = MyModule::FirstGenerated('Bob Builder', 52)
notice($i['name'])
notice($i['age'])
PUPPET
it 'The [] method is present on a created instance' do
expect(notices).to eql(['Bob Builder', '52'])
end
end
end
context 'when generating static code' do
module_def = nil
before(:each) do
# Ideally, this would be in a before(:all) but that is impossible since lots of Puppet
# environment specific settings are configured by the spec_helper in before(:each)
if module_def.nil?
first_type = nil
second_type = nil
eval_and_collect_notices(source) do
first_type = parser.parse('MyModule::FirstGenerated')
second_type = parser.parse('MyModule::SecondGenerated')
Loaders.implementation_registry.register_type_mapping(
PRuntimeType.new(:ruby, [/^PuppetSpec::RubyGenerator::(\w+)$/, 'MyModule::\1']),
[/^MyModule::(\w+)$/, 'PuppetSpec::RubyGenerator::\1'])
module_def = generator.module_definition([first_type, second_type], 'Generated stuff')
end
Loaders.clear
Puppet[:code] = nil
# Create the actual classes in the PuppetSpec::RubyGenerator module
Puppet.override(:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))) do
eval(module_def, root_binding)
end
end
end
after(:all) do
# Don't want generated module to leak outside this test
PuppetSpec.send(:remove_const, :RubyGenerator) if PuppetSpec.const_defined?(:RubyGenerator)
end
it 'the #_pcore_type class method returns a resolved Type' do
first_type = PuppetSpec::RubyGenerator::FirstGenerated._pcore_type
expect(first_type).to be_a(PObjectType)
second_type = PuppetSpec::RubyGenerator::SecondGenerated._pcore_type
expect(second_type).to be_a(PObjectType)
expect(second_type.parent).to eql(first_type)
end
context 'the #create class method' do
it 'has an arity that reflects optional arguments' do
expect(PuppetSpec::RubyGenerator::FirstGenerated.method(:create).arity).to eql(-2)
expect(PuppetSpec::RubyGenerator::SecondGenerated.method(:create).arity).to eql(-6)
end
it 'creates an instance of the class' do
inst = PuppetSpec::RubyGenerator::FirstGenerated.create('Bob Builder', 52)
expect(inst).to be_a(PuppetSpec::RubyGenerator::FirstGenerated)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(52)
end
it 'will perform type assertion of the arguments' do
expect { PuppetSpec::RubyGenerator::FirstGenerated.create('Bob Builder', '52') }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String')
)
end
it 'will not accept nil as given value for an optional parameter that does not accept nil' do
expect { PuppetSpec::RubyGenerator::FirstGenerated.create('Bob Builder', nil) }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef')
)
end
it 'reorders parameters to but the optional parameters last' do
inst = PuppetSpec::RubyGenerator::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst.name).to eq('Bob Builder')
expect(inst.address).to eq('42 Cool Street')
expect(inst.zipcode).to eq('12345')
expect(inst.email).to eq('bob@example.com')
expect(inst.number).to eq(23)
expect(inst.what).to eql('what is this')
expect(inst.age).to eql(30)
expect(inst.another).to be_nil
end
end
context 'the #from_hash class method' do
it 'has an arity of one' do
expect(PuppetSpec::RubyGenerator::FirstGenerated.method(:from_hash).arity).to eql(1)
expect(PuppetSpec::RubyGenerator::SecondGenerated.method(:from_hash).arity).to eql(1)
end
it 'creates an instance of the class' do
inst = PuppetSpec::RubyGenerator::FirstGenerated.from_hash('name' => 'Bob Builder', 'age' => 52)
expect(inst).to be_a(PuppetSpec::RubyGenerator::FirstGenerated)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(52)
end
it 'accepts an initializer where optional keys are missing' do
inst = PuppetSpec::RubyGenerator::FirstGenerated.from_hash('name' => 'Bob Builder')
expect(inst).to be_a(PuppetSpec::RubyGenerator::FirstGenerated)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(30)
end
it 'does not accept an initializer where optional values are nil and type does not accept nil' do
expect { PuppetSpec::RubyGenerator::FirstGenerated.from_hash('name' => 'Bob Builder', 'age' => nil) }.to(
raise_error(TypeAssertionError,
"MyModule::FirstGenerated initializer has wrong type, entry 'age' expects an Integer value, got Undef")
)
end
end
end
end
context 'when generating from TypeSets' do
def source
<<-CODE
type MyModule = TypeSet[{
pcore_version => '1.0.0',
version => '1.0.0',
types => {
MyInteger => Integer,
FirstGenerated => Object[{
attributes => {
name => String,
age => { type => Integer, value => 30 },
what => { type => String, value => 'what is this', kind => constant }
}
}],
SecondGenerated => Object[{
parent => FirstGenerated,
attributes => {
address => String,
zipcode => String,
email => String,
another => { type => Optional[FirstGenerated], value => undef },
number => MyInteger
}
}]
},
}]
type OtherModule = TypeSet[{
pcore_version => '1.0.0',
version => '1.0.0',
types => {
MyFloat => Float,
ThirdGenerated => Object[{
attributes => {
first => My::FirstGenerated
}
}],
FourthGenerated => Object[{
parent => My::SecondGenerated,
attributes => {
complex => { type => Optional[ThirdGenerated], value => undef },
n1 => My::MyInteger,
n2 => MyFloat
}
}]
},
references => {
My => { name => 'MyModule', version_range => '1.x' }
}
}]
CODE
end
context 'when generating anonymous classes' do
typeset = nil
let(:first_type) { typeset['My::FirstGenerated'] }
let(:second_type) { typeset['My::SecondGenerated'] }
let(:third_type) { typeset['ThirdGenerated'] }
let(:fourth_type) { typeset['FourthGenerated'] }
let(:first) { generator.create_class(first_type) }
let(:second) { generator.create_class(second_type) }
let(:third) { generator.create_class(third_type) }
let(:fourth) { generator.create_class(fourth_type) }
before(:each) do
eval_and_collect_notices(source) do
typeset = parser.parse('OtherModule')
end
end
after(:each) { typeset = nil }
context 'the typeset' do
it 'produces expected string representation' do
expect(typeset.to_s).to eq(
"TypeSet[{pcore_version => '1.0.0', name_authority => 'http://puppet.com/2016.1/runtime', name => 'OtherModule', version => '1.0.0', types => {"+
"MyFloat => Float, "+
"ThirdGenerated => Object[{attributes => {'first' => My::FirstGenerated}}], "+
"FourthGenerated => Object[{parent => My::SecondGenerated, attributes => {"+
"'complex' => {type => Optional[ThirdGenerated], value => undef}, "+
"'n1' => My::MyInteger, "+
"'n2' => MyFloat"+
"}}]}, references => {My => {'name' => 'MyModule', 'version_range' => '1.x'}}}]")
end
end
context 'the generated class' do
it 'inherits the PuppetObject module' do
expect(first < PuppetObject).to be_truthy
end
it 'is the superclass of a generated subclass' do
expect(second < first).to be_truthy
end
end
context 'the #create class method' do
it 'has an arity that reflects optional arguments' do
expect(first.method(:create).arity).to eql(-2)
expect(second.method(:create).arity).to eql(-6)
expect(third.method(:create).arity).to eql(1)
expect(fourth.method(:create).arity).to eql(-8)
end
it 'creates an instance of the class' do
inst = first.create('Bob Builder', 52)
expect(inst).to be_a(first)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(52)
end
it 'will perform type assertion of the arguments' do
expect { first.create('Bob Builder', '52') }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String')
)
end
it 'will not accept nil as given value for an optional parameter that does not accept nil' do
expect { first.create('Bob Builder', nil) }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef')
)
end
it 'reorders parameters to but the optional parameters last' do
inst = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst.name).to eq('Bob Builder')
expect(inst.address).to eq('42 Cool Street')
expect(inst.zipcode).to eq('12345')
expect(inst.email).to eq('bob@example.com')
expect(inst.number).to eq(23)
expect(inst.what).to eql('what is this')
expect(inst.age).to eql(30)
expect(inst.another).to be_nil
end
it 'two instances with the same attribute values are equal using #eql?' do
inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
inst2 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst1.eql?(inst2)).to be_truthy
end
it 'two instances with the same attribute values are equal using #==' do
inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
inst2 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst1 == inst2).to be_truthy
end
it 'two instances with the different attribute in super class values are different' do
inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
inst2 = second.create('Bob Engineer', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst1 == inst2).to be_falsey
end
it 'two instances with the different attribute in sub class values are different' do
inst1 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
inst2 = second.create('Bob Builder', '42 Cool Street', '12345', 'bob@other.com', 23)
expect(inst1 == inst2).to be_falsey
end
end
context 'the #from_hash class method' do
it 'has an arity of one' do
expect(first.method(:from_hash).arity).to eql(1)
expect(second.method(:from_hash).arity).to eql(1)
end
it 'creates an instance of the class' do
inst = first.from_hash('name' => 'Bob Builder', 'age' => 52)
expect(inst).to be_a(first)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(52)
end
it 'accepts an initializer where optional keys are missing' do
inst = first.from_hash('name' => 'Bob Builder')
expect(inst).to be_a(first)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(30)
end
it 'does not accept an initializer where optional values are nil and type does not accept nil' do
expect { first.from_hash('name' => 'Bob Builder', 'age' => nil) }.to(
raise_error(TypeAssertionError,
"MyModule::FirstGenerated initializer has wrong type, entry 'age' expects an Integer value, got Undef")
)
end
end
context 'creates an instance' do
it 'that the TypeCalculator infers to the Object type' do
expect(TypeCalculator.infer(first.from_hash('name' => 'Bob Builder'))).to eq(first_type)
end
end
end
context 'when generating static code' do
module_def = nil
module_def2 = nil
before(:each) do
# Ideally, this would be in a before(:all) but that is impossible since lots of Puppet
# environment specific settings are configured by the spec_helper in before(:each)
if module_def.nil?
eval_and_collect_notices(source) do
typeset1 = parser.parse('MyModule')
typeset2 = parser.parse('OtherModule')
Loaders.implementation_registry.register_type_mapping(
PRuntimeType.new(:ruby, [/^PuppetSpec::RubyGenerator::My::(\w+)$/, 'MyModule::\1']),
[/^MyModule::(\w+)$/, 'PuppetSpec::RubyGenerator::My::\1'])
Loaders.implementation_registry.register_type_mapping(
PRuntimeType.new(:ruby, [/^PuppetSpec::RubyGenerator::Other::(\w+)$/, 'OtherModule::\1']),
[/^OtherModule::(\w+)$/, 'PuppetSpec::RubyGenerator::Other::\1'])
module_def = generator.module_definition_from_typeset(typeset1)
module_def2 = generator.module_definition_from_typeset(typeset2)
end
Loaders.clear
Puppet[:code] = nil
# Create the actual classes in the PuppetSpec::RubyGenerator module
Puppet.override(:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))) do
eval(module_def, root_binding)
eval(module_def2, root_binding)
end
end
end
after(:all) do
# Don't want generated module to leak outside this test
PuppetSpec.send(:remove_const, :RubyGenerator) if PuppetSpec.const_defined?(:RubyGenerator)
end
it 'the #_pcore_type class method returns a resolved Type' do
first_type = PuppetSpec::RubyGenerator::My::FirstGenerated._pcore_type
expect(first_type).to be_a(PObjectType)
second_type = PuppetSpec::RubyGenerator::My::SecondGenerated._pcore_type
expect(second_type).to be_a(PObjectType)
expect(second_type.parent).to eql(first_type)
end
context 'the #create class method' do
it 'has an arity that reflects optional arguments' do
expect(PuppetSpec::RubyGenerator::My::FirstGenerated.method(:create).arity).to eql(-2)
expect(PuppetSpec::RubyGenerator::My::SecondGenerated.method(:create).arity).to eql(-6)
end
it 'creates an instance of the class' do
inst = PuppetSpec::RubyGenerator::My::FirstGenerated.create('Bob Builder', 52)
expect(inst).to be_a(PuppetSpec::RubyGenerator::My::FirstGenerated)
expect(inst.name).to eq('Bob Builder')
expect(inst.age).to eq(52)
end
it 'will perform type assertion of the arguments' do
expect { PuppetSpec::RubyGenerator::My::FirstGenerated.create('Bob Builder', '52') }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got String')
)
end
it 'will not accept nil as given value for an optional parameter that does not accept nil' do
expect { PuppetSpec::RubyGenerator::My::FirstGenerated.create('Bob Builder', nil) }.to(
raise_error(TypeAssertionError,
'MyModule::FirstGenerated[age] has wrong type, expects an Integer value, got Undef')
)
end
it 'reorders parameters to but the optional parameters last' do
inst = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst.name).to eq('Bob Builder')
expect(inst.address).to eq('42 Cool Street')
expect(inst.zipcode).to eq('12345')
expect(inst.email).to eq('bob@example.com')
expect(inst.number).to eq(23)
expect(inst.what).to eql('what is this')
expect(inst.age).to eql(30)
expect(inst.another).to be_nil
end
it 'two instances with the same attribute values are equal using #eql?' do
inst1 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
inst2 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
expect(inst1.eql?(inst2)).to be_truthy
end
it 'two instances with the same attribute values are equal using #==' do
inst1 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
inst2 = PuppetSpec::RubyGenerator::My::SecondGenerated.create('Bob Builder', '42 Cool Street', '12345', 'bob@example.com', 23)
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/p_binary_type_spec.rb | spec/unit/pops/types/p_binary_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
module Puppet::Pops
module Types
describe 'Binary Type' do
include PuppetSpec::Compiler
context 'as a type' do
it 'can be created with the type factory' do
t = TypeFactory.binary()
expect(t).to be_a(PBinaryType)
expect(t).to eql(PBinaryType::DEFAULT)
end
end
context 'a Binary instance' do
it 'can be created from a raw String using %r, raw string mode' do
str = [0xF1].pack("C*")
code = <<-CODE
$x = Binary($testing, '%r')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code, Puppet::Node.new('foonode'), { 'testing' => str })).to eql(['8Q=='])
end
it 'can be created from a String using %s, string mode' do
# the text 'binar' needs padding with '='
code = <<-CODE
$x = Binary('binary', '%s')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['YmluYXJ5'])
end
it 'format %s errors if encoding is bad in given string when using format %s and a broken UTF-8 string' do
str = [0xF1].pack("C*")
str.force_encoding('UTF-8')
code = <<-CODE
$x = Binary($testing, '%s')
notice(assert_type(Binary, $x))
CODE
expect {
eval_and_collect_notices(code, Puppet::Node.new('foonode'), { 'testing' => str })
}.to raise_error(/.*The given string in encoding 'UTF-8' is invalid\. Cannot create a Binary UTF-8 representation.*/)
end
it 'format %s errors if encoding is correct but string cannot be transcoded to UTF-8' do
str = [0xF1].pack("C*")
code = <<-CODE
$x = Binary($testing, '%s')
notice(assert_type(Binary, $x))
CODE
expect {
eval_and_collect_notices(code, Puppet::Node.new('foonode'), { 'testing' => str })
}.to raise_error(/.*"\\xF1" from ASCII-8BIT to UTF-8.*/)
end
it 'can be created from a strict Base64 encoded String using default format' do
code = <<-CODE
$x = Binary('YmluYXI=')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['YmluYXI='])
end
it 'will error creation in strict mode if padding is missing when using default format' do
# the text 'binar' needs padding with '=' (missing here to trigger error
code = <<-CODE
$x = Binary('YmluYXI')
notice(assert_type(Binary, $x))
CODE
expect{ eval_and_collect_notices(code) }.to raise_error(/invalid base64/)
end
it 'can be created from a Base64 encoded String using %B, strict mode' do
# the text 'binar' needs padding with '='
code = <<-CODE
$x = Binary('YmluYXI=', '%B')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['YmluYXI='])
end
it 'will error creation in strict mode if padding is missing' do
# the text 'binar' needs padding with '=' (missing here to trigger error
code = <<-CODE
$x = Binary('YmluYXI', '%B')
notice(assert_type(Binary, $x))
CODE
expect{ eval_and_collect_notices(code) }.to raise_error(/invalid base64/)
end
it 'will not error creation in base mode if padding is missing' do
# the text 'binar' needs padding with '=' (missing here to trigger possible error)
code = <<-CODE
$x = Binary('YmluYXI', '%b')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['YmluYXI='])
end
it 'will not error creation in base mode if padding is not required' do
# the text 'binary' does not need padding with '='
code = <<-CODE
$x = Binary('YmluYXJ5', '%b')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['YmluYXJ5'])
end
it 'can be compared to another instance for equality' do
code = <<-CODE
$x = Binary('YmluYXJ5')
$y = Binary('YmluYXJ5')
notice($x == $y)
notice($x != $y)
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'false'])
end
it 'can be created from an array of byte values' do
# the text 'binar' needs padding with '='
code = <<-CODE
$x = Binary([251, 239, 255])
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['++//'])
end
it "can be created from an hash with value and format" do
# the text 'binar' needs padding with '='
code = <<-CODE
$x = Binary({value => '--__', format => '%u'})
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['++//'])
end
it "can be created from an hash with value and default format" do
code = <<-CODE
$x = Binary({value => 'YmluYXI='})
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['YmluYXI='])
end
it 'can be created from a hash with value being an array' do
# the text 'binar' needs padding with '='
code = <<-CODE
$x = Binary({value => [251, 239, 255]})
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['++//'])
end
it "can be created from an Base64 using URL safe encoding by specifying '%u' format'" do
# the text 'binar' needs padding with '='
code = <<-CODE
$x = Binary('--__', '%u')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['++//'])
end
it "when created with URL safe encoding chars in '%b' format, these are skipped" do
code = <<-CODE
$x = Binary('--__YmluYXJ5', '%b')
notice(assert_type(Binary, $x))
CODE
expect(eval_and_collect_notices(code)).to eql(['YmluYXJ5'])
end
it "will error in strict format if string contains URL safe encoded chars" do
code = <<-CODE
$x = Binary('--__YmluYXJ5', '%B')
notice(assert_type(Binary, $x))
CODE
expect { eval_and_collect_notices(code) }.to raise_error(/invalid base64/)
end
[ '<',
'<=',
'>',
'>='
].each do |op|
it "cannot be compared to another instance for magnitude using #{op}" do
code = <<-"CODE"
$x = Binary('YmluYXJ5')
$y = Binary('YmluYXJ5')
$x #{op} $y
CODE
expect { eval_and_collect_notices(code)}.to raise_error(/Comparison of: Binary #{op} Binary, is not possible/)
end
end
it 'can be matched against a Binary in case expression' do
code = <<-CODE
case Binary('YmluYXJ5') {
Binary('YWxpZW4='): {
notice('nope')
}
Binary('YmluYXJ5'): {
notice('yay')
}
default: {
notice('nope')
}
}
CODE
expect(eval_and_collect_notices(code)).to eql(['yay'])
end
it "can be matched against a Binary subsequence using 'in' expression" do
# finding 'one' in 'one two three'
code = <<-CODE
notice(Binary("b25l") in Binary("b25lIHR3byB0aHJlZQ=="))
notice(Binary("c25l") in Binary("b25lIHR3byB0aHJlZQ=="))
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'false'])
end
it "can be matched against a byte value using 'in' expression" do
# finding 'e' (ascii 101) in 'one two three'
code = <<-CODE
notice(101 in Binary("b25lIHR3byB0aHJlZQ=="))
notice(101.0 in Binary("b25lIHR3byB0aHJlZQ=="))
notice(102 in Binary("b25lIHR3byB0aHJlZQ=="))
CODE
expect(eval_and_collect_notices(code)).to eql(['true', 'true', 'false'])
end
it "has a length method in ruby returning the length measured in bytes" do
# \u{1f452} is "woman's hat emoji - 4 bytes in UTF-8"
a_binary = PBinaryType::Binary.new("\u{1f452}")
expect(a_binary.length).to be(4)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/types/type_asserter_spec.rb | spec/unit/pops/types/type_asserter_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops::Types
describe 'the type asserter' do
let!(:asserter) { TypeAsserter }
context 'when deferring formatting of subject'
it 'can use an array' do
expect{ asserter.assert_instance_of(['The %s in the %s', 'gizmo', 'gadget'], PIntegerType::DEFAULT, 'lens') }.to(
raise_error(TypeAssertionError, 'The gizmo in the gadget has wrong type, expects an Integer value, got String'))
end
it 'can use an array obtained from block' do
expect do
asserter.assert_instance_of('gizmo', PIntegerType::DEFAULT, 'lens') { |s| ['The %s in the %s', s, 'gadget'] }
end.to(raise_error(TypeAssertionError, 'The gizmo in the gadget has wrong type, expects an Integer value, got String'))
end
it 'can use an subject obtained from zero argument block' do
expect do
asserter.assert_instance_of(nil, PIntegerType::DEFAULT, 'lens') { 'The gizmo in the gadget' }
end.to(raise_error(TypeAssertionError, 'The gizmo in the gadget has wrong type, expects an Integer value, got String'))
end
it 'does not produce a string unless the assertion fails' do
expect(TypeAsserter).not_to receive(:report_type_mismatch)
asserter.assert_instance_of(nil, PIntegerType::DEFAULT, 1)
end
it 'does not format string unless the assertion fails' do
fmt_string = 'The %s in the %s'
expect(fmt_string).not_to receive(:'%')
asserter.assert_instance_of([fmt_string, 'gizmo', 'gadget'], PIntegerType::DEFAULT, 1)
end
it 'does not call block unless the assertion fails' do
expect do
asserter.assert_instance_of(nil, PIntegerType::DEFAULT, 1) { |s| raise Error }
end.not_to raise_error
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/validator/validator_spec.rb | spec/unit/pops/validator/validator_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/pops'
require_relative '../parser/parser_rspec_helper'
describe "validating 4x" do
include ParserRspecHelper
include PuppetSpec::Pops
let(:acceptor) { Puppet::Pops::Validation::Acceptor.new() }
let(:validator) { Puppet::Pops::Validation::ValidatorFactory_4_0.new().validator(acceptor) }
let(:environment) { Puppet::Node::Environment.create(:bar, ['path']) }
def validate(factory)
validator.validate(factory.model)
acceptor
end
def deprecation_count(acceptor)
acceptor.diagnostics.select {|d| d.severity == :deprecation }.count
end
def with_environment(environment, env_params = {})
override_env = environment
override_env = environment.override_with({
modulepath: env_params[:modulepath] || environment.full_modulepath,
manifest: env_params[:manifest] || environment.manifest,
config_version: env_params[:config_version] || environment.config_version
}) if env_params.count > 0
Puppet.override(current_environment: override_env) do
yield
end
end
it 'should raise error for illegal class names' do
expect(validate(parse('class aaa::_bbb {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('class Aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('class ::aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal define names' do
expect(validate(parse('define aaa::_bbb {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('define Aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('define ::aaa {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal function names' do
expect(validate(parse('function aaa::_bbb() {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('function Aaa() {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
expect(validate(parse('function ::aaa() {}'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal definition locations' do
with_environment(environment) do
expect(validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('class bbb() {}', 'path/aaa/manifests/init.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('define aaa::bbb::ccc::eee() {}', 'path/aaa/manifests/bbb/ddd.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error for legal definition locations' do
with_environment(environment) do
expect(validate(parse('function aaa::bbb() {}', 'path/aaa/manifests/bbb.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('class aaa() {}', 'path/aaa/manifests/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('function aaa::bbB::ccc() {}', 'path/aaa/manifests/bBb.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('function aaa::bbb::ccc() {}', 'path/aaa/manifests/bbb/CCC.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error for class locations when not parsing a file' do
#nil/'' file means eval or some other way to get puppet language source code into the catalog
with_environment(environment) do
expect(validate(parse('function aaa::ccc() {}', nil))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('function aaa::ccc() {}', ''))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error for definitions inside initial --manifest file' do
with_environment(environment, :manifest => 'a/manifest/file.pp') do
expect(validate(parse('class aaa() {}', 'a/manifest/file.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error for definitions inside initial --manifest directory' do
with_environment(environment, :manifest => 'a/manifest/dir') do
expect(validate(parse('class aaa() {}', 'a/manifest/dir/file1.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('class bbb::ccc::ddd() {}', 'a/manifest/dir/and/more/stuff.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error for definitions not inside initial --manifest but also not in modulepath' do
with_environment(environment, :manifest => 'a/manifest/somewhere/else') do
expect(validate(parse('class aaa() {}', 'a/random/dir/file1.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error for empty files in modulepath' do
with_environment(environment) do
expect(validate(parse('', 'path/aaa/manifests/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION)
expect(validate(parse('#this is a comment', 'path/aaa/manifests/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION)
end
end
it 'should raise error if the file is in the modulepath but is not well formed' do
with_environment(environment) do
expect(validate(parse('class aaa::bbb::ccc() {}', 'path/manifest/aaa/bbb.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('class aaa::bbb::ccc() {}', 'path/aaa/bbb/manifest/ccc.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error for definitions not inside initial --manifest but also not in modulepath because of only a case difference' do
with_environment(environment) do
expect(validate(parse('class aaa::bb() {}', 'Path/aaa/manifests/ccc.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error when one modulepath is a substring of another' do
with_environment(environment, modulepath: ['path', 'pathplus']) do
expect(validate(parse('class aaa::ccc() {}', 'pathplus/aaa/manifests/ccc.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should not raise error when a modulepath ends with a file separator' do
with_environment(environment, modulepath: ['path/']) do
expect(validate(parse('class aaa::ccc() {}', 'pathplus/aaa/manifests/ccc.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'should raise error for illegal type names' do
expect(validate(parse('type ::Aaa = Any'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_NAME)
end
it 'should raise error for illegal variable names' do
expect(validate(fqn('Aaa').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('AAA').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('aaa::_aaa').var())).to have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
end
it 'should not raise error for variable name with underscore first in first name segment' do
expect(validate(fqn('_aa').var())).to_not have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
expect(validate(fqn('::_aa').var())).to_not have_issue(Puppet::Pops::Issues::ILLEGAL_VAR_NAME)
end
context 'with the default settings for --strict' do
it 'produces an error for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_KEY)
end
it 'produces an error for illegal function locations' do
with_environment(environment) do
acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'produces an error for illegal top level constructs' do
with_environment(environment) do
acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION)
end
end
end
context 'with --strict set to warning' do
before(:each) { Puppet[:strict] = :warning }
it 'produces a warning for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_KEY)
end
it 'produces an error for virtual class resource' do
acceptor = validate(parse('@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces an error for exported class resource' do
acceptor = validate(parse('@@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces an error for illegal function locations' do
with_environment(environment) do
acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'produces an error for illegal top level constructs' do
with_environment(environment) do
acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION)
end
end
end
context 'with --strict set to error' do
before(:each) { Puppet[:strict] = :error }
it 'produces an error for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_KEY)
end
it 'produces an error for virtual class resource' do
acceptor = validate(parse('@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'does not produce an error for regular class resource' do
acceptor = validate(parse('class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(0)
expect(acceptor).not_to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces an error for exported class resource' do
acceptor = validate(parse('@@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces an error for illegal function locations' do
with_environment(environment) do
acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'produces an error for illegal top level constructs' do
with_environment(environment) do
acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION)
end
end
end
context 'with --strict set to off' do
before(:each) { Puppet[:strict] = :off }
it 'does not produce an error or warning for duplicate keys in a literal hash' do
acceptor = validate(parse('{ a => 1, a => 2 }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to_not have_issue(Puppet::Pops::Issues::DUPLICATE_KEY)
end
it 'produces an error for illegal function locations' do
with_environment(environment) do
acceptor = validate(parse('function aaa::ccc() {}', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'produces an error for illegal top level constructs' do
with_environment(environment) do
acceptor = validate(parse('$foo = 1', 'path/aaa/manifests/bbb.pp'))
expect(deprecation_count(acceptor)).to eql(0)
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION)
end
end
end
context 'irrespective of --strict' do
it 'produces an error for duplicate default in a case expression' do
acceptor = validate(parse('case 1 { default: {1} default : {2} }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_DEFAULT)
end
it 'produces an error for duplicate default in a selector expression' do
acceptor = validate(parse(' 1 ? { default => 1, default => 2 }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::DUPLICATE_DEFAULT)
end
it 'produces an error for virtual class resource' do
acceptor = validate(parse('@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces an error for exported class resource' do
acceptor = validate(parse('@@class { test: }'))
expect(acceptor.warning_count).to eql(0)
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
it 'produces a deprecation warning for non-literal class parameters' do
acceptor = validate(parse('class test(Integer[2-1] $port) {}'))
expect(deprecation_count(acceptor)).to eql(1)
expect(acceptor.warning_count).to eql(1)
expect(acceptor.error_count).to eql(0)
expect(acceptor).to have_issue(Puppet::Pops::Issues::ILLEGAL_NONLITERAL_PARAMETER_TYPE)
end
end
context 'with --tasks set' do
before(:each) { Puppet[:tasks] = true }
it 'raises an error for illegal plan names' do
with_environment(environment) do
expect(validate(parse('plan aaa::ccc::eee() {}', 'path/aaa/plans/bbb/ccc/eee.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('plan aaa() {}', 'path/aaa/plans/aaa.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('plan aaa::bbb() {}', 'path/aaa/plans/bbb/bbb.pp'))).to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'accepts legal plan names' do
with_environment(environment) do
expect(validate(parse('plan aaa::ccc::eee() {}', 'path/aaa/plans/ccc/eee.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('plan aaa() {}', 'path/aaa/plans/init.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
expect(validate(parse('plan aaa::bbb() {}', 'path/aaa/plans/bbb.pp'))).not_to have_issue(Puppet::Pops::Issues::ILLEGAL_DEFINITION_LOCATION)
end
end
it 'produces an error for collect expressions with virtual query' do
acceptor = validate(parse("User <| title == 'admin' |>"))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for collect expressions with exported query' do
acceptor = validate(parse("User <<| title == 'admin' |>>"))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for class expressions' do
acceptor = validate(parse('class test {}'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for node expressions' do
acceptor = validate(parse('node default {}'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for relationship expressions' do
acceptor = validate(parse('$x -> $y'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for resource expressions' do
acceptor = validate(parse('notify { nope: }'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for resource default expressions' do
acceptor = validate(parse("File { mode => '0644' }"))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for resource override expressions' do
acceptor = validate(parse("File['/tmp/foo'] { mode => '0644' }"))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for resource definitions' do
acceptor = validate(parse('define foo($a) {}'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
context 'validating apply() blocks' do
it 'allows empty apply() blocks' do
acceptor = validate(parse('apply("foo.example.com") { }'))
expect(acceptor.error_count).to eql(0)
end
it 'allows apply() with a single expression' do
acceptor = validate(parse('apply("foo.example.com") { include foo }'))
expect(acceptor.error_count).to eql(0)
end
it 'allows apply() with multiple expressions' do
acceptor = validate(parse('apply("foo.example.com") { $message = "hello!"; notify { $message: } }'))
expect(acceptor.error_count).to eql(0)
end
it 'allows apply to be used as a resource attribute name' do
acceptor = validate(parse('apply("foo.example.com") { sometype { "resourcetitle": apply => "applyvalue" } }'))
expect(acceptor.error_count).to eql(0)
end
it 'accepts multiple arguments' do
acceptor = validate(parse('apply(["foo.example.com"], { "other" => "args" }) { }'))
expect(acceptor.error_count).to eql(0)
end
it 'allows virtual resource collectors' do
acceptor = validate(parse("apply('foo.example.com') { @user { 'foo': }; User <| title == 'foo' |> }"))
expect(acceptor.error_count).to eql(0)
end
it 'rejects exported resource collectors' do
acceptor = validate(parse("apply('foo.example.com') { @@user { 'foo': }; User <<| title == 'foo' |>> }"))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING)
end
it 'allows relationship expressions' do
acceptor = validate(parse('apply("foo.example.com") { $x -> $y }'))
expect(acceptor.error_count).to eql(0)
end
it 'allows resource default expressions' do
acceptor = validate(parse("apply('foo.example.com') { File { mode => '0644' } }"))
expect(acceptor.error_count).to eql(0)
end
it 'allows resource override expressions' do
acceptor = validate(parse("apply('foo.example.com') { File['/tmp/foo'] { mode => '0644' } }"))
expect(acceptor.error_count).to eql(0)
end
it 'can be assigned' do
acceptor = validate(parse('$result = apply("foo.example.com") { notify { "hello!": } }'))
expect(acceptor.error_count).to eql(0)
end
it 'produces an error for class expressions' do
acceptor = validate(parse('apply("foo.example.com") { class test {} }'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'allows node expressions' do
acceptor = validate(parse('apply("foo.example.com") { node default {} }'))
expect(acceptor.error_count).to eql(0)
end
it 'produces an error for node expressions nested in a block' do
acceptor = validate(parse('apply("foo.example.com") { if true { node default {} } }'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::NOT_TOP_LEVEL)
end
it 'produces an error for resource definitions' do
acceptor = validate(parse('apply("foo.example.com") { define foo($a) {} }'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING)
end
it 'produces an error for apply() inside apply()' do
acceptor = validate(parse('apply("foo.example.com") { apply("foo.example.com") { } }'))
expect(acceptor.error_count).to eql(1)
expect(acceptor).to have_issue(Puppet::Pops::Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING)
end
it 'allows multiple consecutive apply() blocks' do
acceptor = validate(parse('apply("foo.example.com") { } apply("foo.example.com") { }'))
expect(acceptor.error_count).to eql(0)
end
end
end
context 'for non productive expressions' do
[ '1',
'3.14',
"'a'",
'"a"',
'"${$a=10}"', # interpolation with side effect
'false',
'true',
'default',
'undef',
'[1,2,3]',
'{a=>10}',
'if 1 {2}',
'if 1 {2} else {3}',
'if 1 {2} elsif 3 {4}',
'unless 1 {2}',
'unless 1 {2} else {3}',
'1 ? 2 => 3',
'1 ? { 2 => 3}',
'-1',
'-foo()', # unary minus on productive
'1+2',
'1<2',
'(1<2)',
'!true',
'!foo()', # not on productive
'$a',
'$a[1]',
'name',
'Type',
'Type[foo]'
].each do |expr|
it "produces error for non productive: #{expr}" do
source = "#{expr}; $a = 10"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
it "does not produce error when last for non productive: #{expr}" do
source = " $a = 10; #{expr}"
expect(validate(parse(source))).to_not have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
end
[
'if 1 {$a = 1}',
'if 1 {2} else {$a=1}',
'if 1 {2} elsif 3 {$a=1}',
'unless 1 {$a=1}',
'unless 1 {2} else {$a=1}',
'$a = 1 ? 2 => 3',
'$a = 1 ? { 2 => 3}',
'Foo[a] -> Foo[b]',
'($a=1)',
'foo()',
'$a.foo()',
'"foo" =~ /foo/', # may produce or modify $n vars
'"foo" !~ /foo/', # may produce or modify $n vars
].each do |expr|
it "does not produce error when for productive: #{expr}" do
source = "#{expr}; $x = 1"
expect(validate(parse(source))).to_not have_issue(Puppet::Pops::Issues::IDEM_EXPRESSION_NOT_LAST)
end
end
['class', 'define', 'node'].each do |type|
it "flags non productive expression last in #{type}" do
source = <<-SOURCE
#{type} nope {
1
}
end
SOURCE
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::IDEM_NOT_ALLOWED_LAST)
end
it "detects a resource declared without title in #{type} when it is the only declaration present" do
source = <<-SOURCE
#{type} nope {
notify { message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
it "detects a resource declared without title in #{type} when it is in between other declarations" do
source = <<-SOURCE
#{type} nope {
notify { succ: message => 'Nope' }
notify { message => 'Nope' }
notify { pred: message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
it "detects a resource declared without title in #{type} when it is declarated first" do
source = <<-SOURCE
#{type} nope {
notify { message => 'Nope' }
notify { pred: message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
it "detects a resource declared without title in #{type} when it is declarated last" do
source = <<-SOURCE
#{type} nope {
notify { succ: message => 'Nope' }
notify { message => 'Nope' }
}
SOURCE
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESOURCE_WITHOUT_TITLE)
end
end
end
context 'for reserved words' do
['private', 'attr'].each do |word|
it "produces an error for the word '#{word}'" do
source = "$a = #{word}"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_WORD)
end
end
end
context 'for reserved type names' do
[# type/Type, is a reserved name but results in syntax error because it is a keyword in lower case form
'any',
'unit',
'scalar',
'boolean',
'numeric',
'integer',
'float',
'collection',
'array',
'hash',
'tuple',
'struct',
'variant',
'optional',
'enum',
'regexp',
'pattern',
'runtime',
'init',
'object',
'sensitive',
'semver',
'semverrange',
'string',
'timestamp',
'timespan',
'typeset',
].each do |name|
it "produces an error for 'class #{name}'" do
source = "class #{name} {}"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_TYPE_NAME)
end
it "produces an error for 'define #{name}'" do
source = "define #{name} {}"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_TYPE_NAME)
end
end
end
context 'for keywords' do
it "should allow using the 'type' as the name of a function with no parameters" do
source = "type()"
expect(validate(parse(source))).not_to have_any_issues
end
it "should allow using the keyword 'type' as the name of a function with parameters" do
source = "type('a', 'b')"
expect(validate(parse(source))).not_to have_any_issues
end
it "should allow using the 'type' as the name of a function with no parameters and a block" do
source = "type() |$x| { $x }"
expect(validate(parse(source))).not_to have_any_issues
end
it "should allow using the keyword 'type' as the name of a function with parameters and a block" do
source = "type('a', 'b') |$x| { $x }"
expect(validate(parse(source))).not_to have_any_issues
end
end
context 'for hash keys' do
it "should not allow reassignment of hash keys" do
source = "$my_hash = {'one' => '1', 'two' => '2' }; $my_hash['one']='1.5'"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::ILLEGAL_INDEXED_ASSIGNMENT)
end
end
context 'for parameter names' do
['class', 'define'].each do |word|
it "should require that #{word} parameter names are unique" do
expect(validate(parse("#{word} foo($a = 10, $a = 20) {}"))).to have_issue(Puppet::Pops::Issues::DUPLICATE_PARAMETER)
end
end
it "should require that template parameter names are unique" do
expect(validate(parse_epp("<%-| $a, $a |-%><%= $a == doh %>"))).to have_issue(Puppet::Pops::Issues::DUPLICATE_PARAMETER)
end
end
context 'for parameter defaults' do
['class', 'define'].each do |word|
it "should not permit assignments in #{word} parameter default expressions" do
expect { parse("#{word} foo($a = $x = 10) {}") }.to raise_error(Puppet::ParseErrorWithIssue, /Syntax error at '='/)
end
end
['class', 'define'].each do |word|
it "should not permit assignments in #{word} parameter default nested expressions" do
expect(validate(parse("#{word} foo($a = [$x = 10]) {}"))).to have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT)
end
it "should not permit assignments to subsequently declared parameters in #{word} parameter default nested expressions" do
expect(validate(parse("#{word} foo($a = ($b = 3), $b = 5) {}"))).to have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT)
end
it "should not permit assignments to previously declared parameters in #{word} parameter default nested expressions" do
expect(validate(parse("#{word} foo($a = 10, $b = ($a = 10)) {}"))).to have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT)
end
it "should permit assignments in #{word} parameter default inside nested lambda expressions" do
expect(validate(parse(
"#{word} foo($a = [1,2,3], $b = 0, $c = $a.map |$x| { $b = $x; $b * $a.reduce |$x, $y| {$x + $y}}) {}"))).not_to(
have_issue(Puppet::Pops::Issues::ILLEGAL_ASSIGNMENT_CONTEXT))
end
end
end
context 'for reserved parameter names' do
['name', 'title'].each do |word|
it "produces an error when $#{word} is used as a parameter in a class" do
source = "class x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_PARAMETER)
end
it "produces an error when $#{word} is used as a parameter in a define" do
source = "define x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::RESERVED_PARAMETER)
end
end
end
context 'for numeric parameter names' do
['1', '0x2', '03'].each do |word|
it "produces an error when $#{word} is used as a parameter in a class" do
source = "class x ($#{word}) {}"
expect(validate(parse(source))).to have_issue(Puppet::Pops::Issues::ILLEGAL_NUMERIC_PARAMETER)
end
end
end
context 'for badly formed non-numeric parameter names' do
['Ateam', 'a::team'].each do |word|
it "produces an error when $#{word} is used as a parameter in a class" do
source = "class x ($#{word}) {}"
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/loaders/static_loader_spec.rb | spec/unit/pops/loaders/static_loader_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
describe 'the static loader' do
let(:loader) do
loader = Puppet::Pops::Loader::StaticLoader.new()
loader.runtime_3_init
loader
end
it 'has no parent' do
expect(loader.parent).to be(nil)
end
it 'identifies itself in string form' do
expect(loader.to_s).to be_eql('(StaticLoader)')
end
it 'support the Loader API' do
# it may produce things later, this is just to test that calls work as they should - now all lookups are nil.
a_typed_name = typed_name(:function, 'foo')
expect(loader[a_typed_name]).to be(nil)
expect(loader.load_typed(a_typed_name)).to be(nil)
expect(loader.find(a_typed_name)).to be(nil)
end
context 'provides access to resource types built into puppet' do
%w{
Component
Exec
File
Filebucket
Group
Notify
Package
Resources
Schedule
Service
Stage
Tidy
User
Whit
}.each do |name |
it "such that #{name} is available" do
expect(loader.load(:type, name.downcase)).to be_the_type(resource_type(name))
end
end
end
context 'provides access to app-management specific resource types built into puppet' do
it "such that Node is available" do
expect(loader.load(:type, 'node')).to be_the_type(resource_type('Node'))
end
end
context 'without init_runtime3 initialization' do
let(:loader) { Puppet::Pops::Loader::StaticLoader.new() }
it 'does not provide access to resource types built into puppet' do
expect(loader.load(:type, 'file')).to be_nil
end
end
def typed_name(type, name)
Puppet::Pops::Loader::TypedName.new(type, name)
end
def resource_type(name)
Puppet::Pops::Types::TypeFactory.resource(name)
end
matcher :be_the_type do |type|
calc = Puppet::Pops::Types::TypeCalculator.new
match do |actual|
calc.assignable?(actual, type) && calc.assignable?(type, actual)
end
failure_message do |actual|
"expected #{type.to_s}, but was #{actual.to_s}"
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/loaders/dependency_loader_spec.rb | spec/unit/pops/loaders/dependency_loader_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/pops'
require 'puppet/loaders'
describe 'dependency loader' do
include PuppetSpec::Files
let(:static_loader) { Puppet::Pops::Loader::StaticLoader.new() }
let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) }
describe 'FileBased module loader' do
it 'prints a pretty name for itself when inspected' do
module_dir = dir_containing('testmodule', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule' => {
'foo.rb' => 'Puppet::Functions.create_function("foo") { def foo; end; }'
}}}}})
loader = loader_for('testmodule', module_dir)
expect(loader.inspect).to eq("(DependencyLoader 'test-dep' [(ModuleLoader::FileBased 'testmodule' 'testmodule')])")
expect(loader.to_s).to eq("(DependencyLoader 'test-dep' [(ModuleLoader::FileBased 'testmodule' 'testmodule')])")
end
it 'load something in global name space raises an error' do
module_dir = dir_containing('testmodule', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule' => {
'foo.rb' => 'Puppet::Functions.create_function("foo") { def foo; end; }'
}}}}})
loader = loader_for('testmodule', module_dir)
expect do
loader.load_typed(typed_name(:function, 'testmodule::foo')).value
end.to raise_error(ArgumentError, /produced mis-matched name, expected 'testmodule::foo', got foo/)
end
it 'can load something in a qualified name space' do
module_dir = dir_containing('testmodule', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule' => {
'foo.rb' => 'Puppet::Functions.create_function("testmodule::foo") { def foo; end; }'
}}}}})
loader = loader_for('testmodule', module_dir)
function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value
expect(function.class.name).to eq('testmodule::foo')
expect(function.is_a?(Puppet::Functions::Function)).to eq(true)
end
it 'can load something in a qualified name space more than once' do
module_dir = dir_containing('testmodule', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule' => {
'foo.rb' => 'Puppet::Functions.create_function("testmodule::foo") { def foo; end; }'
}}}}})
loader = loader_for('testmodule', module_dir)
function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value
expect(function.class.name).to eq('testmodule::foo')
expect(function.is_a?(Puppet::Functions::Function)).to eq(true)
function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value
expect(function.class.name).to eq('testmodule::foo')
expect(function.is_a?(Puppet::Functions::Function)).to eq(true)
end
describe "when parsing files from disk" do
# First line of Rune version of Rune poem at http://www.columbia.edu/~fdc/utf8/
# characters chosen since they will not parse on Windows with codepage 437 or 1252
# Section 3.2.1.3 of Ruby spec guarantees that \u strings are encoded as UTF-8
let (:node) { Puppet::Node.new('node') }
let (:rune_utf8) { "\u16A0\u16C7\u16BB" } # ᚠᛇᚻ
let (:code_utf8) do <<-CODE
Puppet::Functions.create_function('testmodule::foo') {
def foo
return \"#{rune_utf8}\"
end
}
CODE
end
context 'when loading files from disk' do
it 'should always read files as UTF-8' do
module_dir = dir_containing('testmodule', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule' => {
'foo.rb' => code_utf8
}}}}})
loader = loader_for('testmodule', module_dir)
function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value
expect(function.call({})).to eq(rune_utf8)
end
it 'currently ignores the UTF-8 BOM (Byte Order Mark) when loading module files' do
bom = "\uFEFF"
module_dir = dir_containing('testmodule', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule' => {
'foo.rb' => "#{bom}#{code_utf8}"
}}}}})
loader = loader_for('testmodule', module_dir)
function = loader.load_typed(typed_name(:function, 'testmodule::foo')).value
expect(function.call({})).to eq(rune_utf8)
end
end
end
end
def loader_for(name, dir)
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, name, dir)
Puppet::Pops::Loader::DependencyLoader.new(static_loader, 'test-dep', [module_loader], loaders.environment)
end
def typed_name(type, name)
Puppet::Pops::Loader::TypedName.new(type, name)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/loaders/loader_spec.rb | spec/unit/pops/loaders/loader_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/compiler'
require 'puppet/pops'
require 'puppet/loaders'
module Puppet::Pops
module Loader
describe 'The Loader' do
include PuppetSpec::Compiler
include PuppetSpec::Files
before(:each) do
Puppet[:tasks] = true
end
let(:testing_env) do
{
'testing' => {
'functions' => functions,
'lib' => { 'puppet' => lib_puppet },
'manifests' => manifests,
'modules' => modules,
'plans' => plans,
'tasks' => tasks,
'types' => types,
}
}
end
let(:functions) { {} }
let(:manifests) { {} }
let(:modules) { {} }
let(:plans) { {} }
let(:lib_puppet) { {} }
let(:tasks) { {} }
let(:types) { {} }
let(:environments_dir) { Puppet[:environmentpath] }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'testing')
PuppetSpec::Files.record_tmp(env_dir)
env_dir
end
let(:modules_dir) { File.join(testing_env_dir, 'modules') }
let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) }
let(:node) { Puppet::Node.new('test', :environment => env) }
let(:loader) { Loaders.find_loader(nil) }
let(:tasks_feature) { false }
before(:each) do
Puppet[:tasks] = tasks_feature
loaders = Loaders.new(env)
Puppet.push_context(:loaders => loaders)
loaders.pre_load
end
after(:each) { Puppet.pop_context }
context 'when doing discovery' do
context 'of things' do
it 'finds statically basic types' do
expect(loader.discover(:type)).to include(tn(:type, 'integer'))
end
it 'finds statically loaded types' do
expect(loader.discover(:type)).to include(tn(:type, 'file'))
end
it 'finds statically loaded Object types' do
expect(loader.discover(:type)).to include(tn(:type, 'puppet::ast::accessexpression'))
end
context 'in environment' do
let(:types) {
{
'global.pp' => <<-PUPPET.unindent,
type Global = Integer
PUPPET
'environment' => {
'env.pp' => <<-PUPPET.unindent,
type Environment::Env = String
PUPPET
}
}
}
let(:functions) {
{
'globfunc.pp' => 'function globfunc() {}',
'environment' => {
'envfunc.pp' => 'function environment::envfunc() {}'
}
}
}
let(:lib_puppet) {
{
'functions' => {
'globrubyfunc.rb' => 'Puppet::Functions.create_function(:globrubyfunc) { def globrubyfunc; end }',
'environment' => {
'envrubyfunc.rb' => "Puppet::Functions.create_function(:'environment::envrubyfunc') { def envrubyfunc; end }",
}
}
}
}
it 'finds global types in environment' do
expect(loader.discover(:type)).to include(tn(:type, 'global'))
end
it 'finds global functions in environment' do
expect(loader.discover(:function)).to include(tn(:function, 'lookup'))
end
it 'finds types prefixed with Environment in environment' do
expect(loader.discover(:type)).to include(tn(:type, 'environment::env'))
end
it 'finds global functions in environment' do
expect(loader.discover(:function)).to include(tn(:function, 'globfunc'))
end
it 'finds functions prefixed with Environment in environment' do
expect(loader.discover(:function)).to include(tn(:function, 'environment::envfunc'))
end
it 'finds global ruby functions in environment' do
expect(loader.discover(:function)).to include(tn(:function, 'globrubyfunc'))
end
it 'finds ruby functions prefixed with Environment in environment' do
expect(loader.discover(:function)).to include(tn(:function, 'environment::envrubyfunc'))
end
it 'can filter the list of discovered entries using a block' do
expect(loader.discover(:function) { |t| t.name =~ /rubyfunc\z/ }).to contain_exactly(
tn(:function, 'environment::envrubyfunc'),
tn(:function, 'globrubyfunc')
)
end
context 'with multiple modules' do
let(:metadata_json_a) {
{
'name' => 'example/a',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-a.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_b) {
{
'name' => 'example/b',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-b.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_c) {
{
'name' => 'example/c',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-c.git',
'dependencies' => [],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:modules) {
{
'a' => {
'functions' => a_functions,
'lib' => { 'puppet' => a_lib_puppet },
'plans' => a_plans,
'tasks' => a_tasks,
'types' => a_types,
'metadata.json' => metadata_json_a.to_json
},
'b' => {
'functions' => b_functions,
'lib' => { 'puppet' => b_lib_puppet },
'plans' => b_plans,
'tasks' => b_tasks,
'types' => b_types,
'metadata.json' => metadata_json_b.to_json
},
'c' => {
'types' => c_types,
'tasks' => c_tasks,
'metadata.json' => metadata_json_c.to_json
},
}
}
let(:a_plans) {
{
'aplan.pp' => <<-PUPPET.unindent,
plan a::aplan() {}
PUPPET
}
}
let(:a_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type A::Atype = Integer
PUPPET
}
}
let(:a_tasks) {
{
'atask' => '',
}
}
let(:a_functions) {
{
'afunc.pp' => 'function a::afunc() {}',
}
}
let(:a_lib_puppet) {
{
'functions' => {
'a' => {
'arubyfunc.rb' => "Puppet::Functions.create_function(:'a::arubyfunc') { def arubyfunc; end }",
}
}
}
}
let(:b_plans) {
{
'init.pp' => <<-PUPPET.unindent,
plan b() {}
PUPPET
'aplan.pp' => <<-PUPPET.unindent,
plan b::aplan() {}
PUPPET
'yamlplan.yaml' => '{}',
'conflict.yaml' => '{}',
'conflict.pp' => <<-PUPPET.unindent,
plan b::conflict() {}
PUPPET
}
}
let(:b_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type B::Atype = Integer
PUPPET
}
}
let(:b_tasks) {
{
'init.json' => <<-JSON.unindent,
{
"description": "test task b",
"parameters": {}
}
JSON
'init.sh' => "# doing exactly nothing\n",
'atask' => "# doing exactly nothing\n",
'atask.json' => <<-JSON.unindent,
{
"description": "test task b::atask",
"input_method": "stdin",
"parameters": {
"string_param": {
"description": "A string parameter",
"type": "String[1]"
},
"int_param": {
"description": "An integer parameter",
"type": "Integer"
}
}
}
JSON
}
}
let(:b_functions) {
{
'afunc.pp' => 'function b::afunc() {}',
}
}
let(:b_lib_puppet) {
{
'functions' => {
'b' => {
'arubyfunc.rb' => "Puppet::Functions.create_function(:'b::arubyfunc') { def arubyfunc; end }",
}
}
}
}
let(:c_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type C::Atype = Integer
PUPPET
}
}
let(:c_tasks) {
{
'foo.sh' => <<-SH.unindent,
# This is a task that does nothing
SH
'fee.md' => <<-MD.unindent,
This is not a task because it has .md extension
MD
'fum.conf' => <<-CONF.unindent,
text=This is not a task because it has .conf extension
CONF
'bad_syntax.sh' => '',
'bad_syntax.json' => <<-TXT.unindent,
text => This is not a task because JSON is unparsable
TXT
'missing_adjacent.json' => <<-JSON.unindent,
{
"description": "This is not a task because there is no adjacent file with the same base name",
"parameters": { "string_param": { "type": "String[1]" } }
}
JSON
}
}
it 'private loader finds types in all modules' do
expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:type, 'a::atype'), tn(:type, 'b::atype'), tn(:type, 'c::atype')))
end
it 'module loader finds types only in itself' do
expect(Loaders.find_loader('a').discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:type, 'a::atype')))
end
it 'private loader finds functions in all modules' do
expect(loader.private_loader.discover(:function) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:function, 'a::afunc'), tn(:function, 'b::afunc'), tn(:function, 'a::arubyfunc'), tn(:function, 'b::arubyfunc')))
end
it 'module loader finds functions only in itself' do
expect(Loaders.find_loader('a').discover(:function) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:function, 'a::afunc'), tn(:function, 'a::arubyfunc')))
end
it 'discover is only called once on dependent loader' do
times_called = 0
allow_any_instance_of(ModuleLoaders::FileBased).to receive(:discover).with(:type, nil, Pcore::RUNTIME_NAME_AUTHORITY) { times_called += 1 }.and_return([])
expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(contain_exactly())
expect(times_called).to eq(4)
end
context 'with tasks enabled' do
let(:tasks_feature) { true }
it 'private loader finds plans in all modules' do
expect(loader.private_loader.discover(:plan) { |t| t.name =~ /^.(?:::.*)?\z/ }).to(
contain_exactly(tn(:plan, 'b'), tn(:plan, 'a::aplan'), tn(:plan, 'b::aplan'), tn(:plan, 'b::conflict')))
end
it 'module loader finds plans only in itself' do
expect(Loaders.find_loader('a').discover(:plan)).to(
contain_exactly(tn(:plan, 'a::aplan')))
end
context 'with a yaml plan instantiator defined' do
before :each do
Puppet.push_context(:yaml_plan_instantiator => double(:create => double('plan')))
end
after :each do
Puppet.pop_context
end
it 'module loader finds yaml plans' do
expect(Loaders.find_loader('b').discover(:plan)).to(
include(tn(:plan, 'b::yamlplan')))
end
it 'module loader excludes plans with both .pp and .yaml versions' do
expect(Loaders.find_loader('b').discover(:plan)).not_to(
include(tn(:plan, 'b::conflict')))
end
end
it 'private loader finds types in all modules' do
expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:type, 'a::atype'), tn(:type, 'b::atype'), tn(:type, 'c::atype')))
end
it 'private loader finds tasks in all modules' do
expect(loader.private_loader.discover(:task) { |t| t.name =~ /^.(?:::.*)?\z/ }).to(
contain_exactly(tn(:task, 'a::atask'), tn(:task, 'b::atask'), tn(:task, 'b'), tn(:task, 'c::foo')))
end
it 'module loader finds types only in itself' do
expect(Loaders.find_loader('a').discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:type, 'a::atype')))
end
it 'module loader finds tasks only in itself' do
expect(Loaders.find_loader('a').discover(:task) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:task, 'a::atask')))
end
it 'module loader does not consider files with .md and .conf extension to be tasks' do
expect(Loaders.find_loader('c').discover(:task) { |t| t.name =~ /(?:foo|fee|fum)\z/ }).to(
contain_exactly(tn(:task, 'c::foo')))
end
it 'without error_collector, invalid task metadata results in warnings' do
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(Loaders.find_loader('c').discover(:task)).to(
contain_exactly(tn(:task, 'c::foo')))
end
expect(logs.select { |log| log.level == :warning }.map { |log| log.message }).to(
contain_exactly(/unexpected token/, /No source besides task metadata was found/)
)
end
it 'with error_collector, errors are collected and no warnings are logged' do
logs = []
error_collector = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(Loaders.find_loader('c').discover(:task, error_collector)).to(
contain_exactly(tn(:task, 'c::foo')))
end
expect(logs.select { |log| log.level == :warning }.map { |log| log.message }).to be_empty
expect(error_collector.size).to eql(2)
expect(error_collector.all? { |e| e.is_a?(Puppet::DataTypes::Error) })
expect(error_collector.all? { |e| e.issue_code == Puppet::Pops::Issues::LOADER_FAILURE.issue_code })
expect(error_collector.map { |e| e.details['original_error'] }).to(
contain_exactly(/unexpected token/, /No source besides task metadata was found/)
)
end
context 'and an environment without directory' do
let(:environments_dir) { tmpdir('loader_spec') }
let(:env) { Puppet::Node::Environment.create(:none_such, [modules_dir]) }
it 'an EmptyLoader is used and module loader finds types' do
expect_any_instance_of(Puppet::Pops::Loader::ModuleLoaders::EmptyLoader).to receive(:find).and_return(nil)
expect(Loaders.find_loader('a').discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:type, 'a::atype')))
end
it 'an EmptyLoader is used and module loader finds tasks' do
expect_any_instance_of(Puppet::Pops::Loader::ModuleLoaders::EmptyLoader).to receive(:find).and_return(nil)
expect(Loaders.find_loader('a').discover(:task) { |t| t.name =~ /^.::.*\z/ }).to(
contain_exactly(tn(:task, 'a::atask')))
end
end
end
context 'with no explicit dependencies' do
let(:modules) do
{
'a' => {
'functions' => a_functions,
'lib' => { 'puppet' => a_lib_puppet },
'plans' => a_plans,
'tasks' => a_tasks,
'types' => a_types,
},
'b' => {
'functions' => b_functions,
'lib' => { 'puppet' => b_lib_puppet },
'plans' => b_plans,
'tasks' => b_tasks,
'types' => b_types,
},
'c' => {
'types' => c_types,
},
}
end
it 'discover is only called once on dependent loader' do
times_called = 0
allow_any_instance_of(ModuleLoaders::FileBased).to receive(:discover).with(:type, nil, Pcore::RUNTIME_NAME_AUTHORITY) { times_called += 1 }.and_return([])
expect(loader.private_loader.discover(:type) { |t| t.name =~ /^.::.*\z/ }).to(contain_exactly())
expect(times_called).to eq(4)
end
end
end
end
end
end
def tn(type, name)
TypedName.new(type, name)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/loaders/module_loaders_spec.rb | spec/unit/pops/loaders/module_loaders_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/pops'
require 'puppet/loaders'
require 'puppet_spec/compiler'
describe 'FileBased module loader' do
include PuppetSpec::Files
let(:static_loader) { Puppet::Pops::Loader::StaticLoader.new() }
let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) }
it 'can load a 4x function API ruby function in global name space' do
module_dir = dir_containing('testmodule', {
'lib' => {
'puppet' => {
'functions' => {
'foo4x.rb' => <<-CODE
Puppet::Functions.create_function(:foo4x) do
def foo4x()
'yay'
end
end
CODE
}
}
}
})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
function = module_loader.load_typed(typed_name(:function, 'foo4x')).value
expect(function.class.name).to eq('foo4x')
expect(function.is_a?(Puppet::Functions::Function)).to eq(true)
end
it 'can load a 4x function API ruby function in qualified name space' do
module_dir = dir_containing('testmodule', {
'lib' => {
'puppet' => {
'functions' => {
'testmodule' => {
'foo4x.rb' => <<-CODE
Puppet::Functions.create_function('testmodule::foo4x') do
def foo4x()
'yay'
end
end
CODE
}
}
}
}})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
function = module_loader.load_typed(typed_name(:function, 'testmodule::foo4x')).value
expect(function.class.name).to eq('testmodule::foo4x')
expect(function.is_a?(Puppet::Functions::Function)).to eq(true)
end
it 'system loader has itself as private loader' do
module_loader = loaders.puppet_system_loader
expect(module_loader.private_loader).to be(module_loader)
end
it 'makes parent loader win over entries in child' do
module_dir = dir_containing('testmodule', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule' => {
'foo.rb' => <<-CODE
Puppet::Functions.create_function('testmodule::foo') do
def foo()
'yay'
end
end
CODE
}}}}})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
module_dir2 = dir_containing('testmodule2', {
'lib' => { 'puppet' => { 'functions' => { 'testmodule2' => {
'foo.rb' => <<-CODE
raise "should not get here"
CODE
}}}}})
module_loader2 = Puppet::Pops::Loader::ModuleLoaders::FileBased.new(module_loader, loaders, 'testmodule2', module_dir2, 'test2')
function = module_loader2.load_typed(typed_name(:function, 'testmodule::foo')).value
expect(function.class.name).to eq('testmodule::foo')
expect(function.is_a?(Puppet::Functions::Function)).to eq(true)
end
context 'loading tasks' do
before(:each) do
Puppet[:tasks] = true
Puppet.push_context(:loaders => loaders)
end
after(:each) { Puppet.pop_context }
it 'can load tasks with multiple files' do
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => '{}'})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
task = module_loader.load_typed(typed_name(:task, 'testmodule::foo')).value
expect(task.name).to eq('testmodule::foo')
expect(task.files.length).to eq(1)
expect(task.files[0]['name']).to eq('foo.py')
end
it 'can load tasks with multiple implementations' do
metadata = { 'implementations' => [{'name' => 'foo.py'}, {'name' => 'foo.ps1'}] }
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.ps1' => '', 'foo.json' => metadata.to_json})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
task = module_loader.load_typed(typed_name(:task, 'testmodule::foo')).value
expect(task.name).to eq('testmodule::foo')
expect(task.files.map {|impl| impl['name']}).to eq(['foo.py', 'foo.ps1'])
end
it 'can load multiple tasks with multiple files' do
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => '{}', 'foobar.py' => '', 'foobar.json' => '{}'})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
foo_task = module_loader.load_typed(typed_name(:task, 'testmodule::foo')).value
foobar_task = module_loader.load_typed(typed_name(:task, 'testmodule::foobar')).value
expect(foo_task.name).to eq('testmodule::foo')
expect(foo_task.files.length).to eq(1)
expect(foo_task.files[0]['name']).to eq('foo.py')
expect(foobar_task.name).to eq('testmodule::foobar')
expect(foobar_task.files.length).to eq(1)
expect(foobar_task.files[0]['name']).to eq('foobar.py')
end
it "won't load tasks with invalid names" do
module_dir = dir_containing('testmodule', 'tasks' => {'a-b.py' => '', 'foo.tar.gz' => ''})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
tasks = module_loader.discover(:task)
expect(tasks).to be_empty
expect(module_loader.load_typed(typed_name(:task, 'testmodule::foo'))).to be_nil
end
it "lists tasks without executables, if they specify implementations" do
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '',
'bar.rb' => '',
'baz.json' => {'implementations' => ['name' => 'foo.py']}.to_json,
'qux.json' => '{}'})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
tasks = module_loader.discover(:task)
expect(tasks.length).to eq(3)
expect(tasks.map(&:name).sort).to eq(['testmodule::bar', 'testmodule::baz', 'testmodule::foo'])
expect(module_loader.load_typed(typed_name(:task, 'testmodule::foo'))).not_to be_nil
expect(module_loader.load_typed(typed_name(:task, 'testmodule::bar'))).not_to be_nil
expect(module_loader.load_typed(typed_name(:task, 'testmodule::baz'))).not_to be_nil
expect { module_loader.load_typed(typed_name(:task, 'testmodule::qux')) }.to raise_error(/No source besides task metadata was found/)
end
it 'raises and error when `parameters` is not a hash' do
metadata = { 'parameters' => 'foo' }
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))}
.to raise_error(Puppet::ParseError, /Failed to load metadata for task testmodule::foo: 'parameters' must be a hash/)
end
it 'raises and error when `implementations` `requirements` key is not an array' do
metadata = { 'implementations' => { 'name' => 'foo.py', 'requirements' => 'foo'} }
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))}
.to raise_error(Puppet::Module::Task::InvalidMetadata,
/Task metadata for task testmodule::foo does not specify implementations as an array/)
end
it 'raises and error when top-level `files` is not an array' do
metadata = { 'files' => 'foo' }
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))}
.to raise_error(Puppet::Module::Task::InvalidMetadata, /The 'files' task metadata expects an array, got foo/)
end
it 'raises and error when `files` nested in `interpreters` is not an array' do
metadata = { 'implementations' => [{'name' => 'foo.py', 'files' => 'foo'}] }
module_dir = dir_containing('testmodule', 'tasks' => {'foo.py' => '', 'foo.json' => metadata.to_json})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, loaders, 'testmodule', module_dir)
expect{module_loader.load_typed(typed_name(:task, 'testmodule::foo'))}
.to raise_error(Puppet::Module::Task::InvalidMetadata, /The 'files' task metadata expects an array, got foo/)
end
end
def typed_name(type, name)
Puppet::Pops::Loader::TypedName.new(type, name)
end
context 'module function and class using a module type alias' do
include PuppetSpec::Compiler
let(:modules) do
{
'mod' => {
'functions' => {
'afunc.pp' => <<-PUPPET.unindent
function mod::afunc(Mod::Analias $v) {
notice($v)
}
PUPPET
},
'types' => {
'analias.pp' => <<-PUPPET.unindent
type Mod::Analias = Enum[a,b]
PUPPET
},
'manifests' => {
'init.pp' => <<-PUPPET.unindent
class mod(Mod::Analias $v) {
notify { $v: }
}
PUPPET
}
}
}
end
let(:testing_env) do
{
'testing' => {
'modules' => modules
}
}
end
let(:environments_dir) { Puppet[:environmentpath] }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'testing')
PuppetSpec::Files.record_tmp(env_dir)
env_dir
end
let(:env) { Puppet::Node::Environment.create(:testing, [File.join(testing_env_dir, 'modules')]) }
let(:node) { Puppet::Node.new('test', :environment => env) }
# The call to mod:afunc will load the function, and as a consequence, make an attempt to load
# the parameter type Mod::Analias. That load in turn, will trigger the Runtime3TypeLoader which
# will load the manifests in Mod. The init.pp manifest also references the Mod::Analias parameter
# which results in a recursive call to the same loader. This test asserts that this recursive
# call is handled OK.
# See PUP-7391 for more info.
it 'should handle a recursive load' do
expect(eval_and_collect_notices("mod::afunc('b')", node)).to eql(['b'])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/loaders/loaders_spec.rb | spec/unit/pops/loaders/loaders_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/compiler'
require 'puppet/pops'
require 'puppet/loaders'
describe 'loader helper classes' do
it 'NamedEntry holds values and is frozen' do
ne = Puppet::Pops::Loader::Loader::NamedEntry.new('name', 'value', 'origin')
expect(ne.frozen?).to be_truthy
expect(ne.typed_name).to eql('name')
expect(ne.origin).to eq('origin')
expect(ne.value).to eq('value')
end
it 'TypedName holds values and is frozen' do
tn = Puppet::Pops::Loader::TypedName.new(:function, '::foo::bar')
expect(tn.frozen?).to be_truthy
expect(tn.type).to eq(:function)
expect(tn.name_parts).to eq(['foo', 'bar'])
expect(tn.name).to eq('foo::bar')
expect(tn.qualified?).to be_truthy
end
it 'TypedName converts name to lower case' do
tn = Puppet::Pops::Loader::TypedName.new(:type, '::Foo::Bar')
expect(tn.name_parts).to eq(['foo', 'bar'])
expect(tn.name).to eq('foo::bar')
end
it 'TypedName is case insensitive' do
expect(Puppet::Pops::Loader::TypedName.new(:type, '::Foo::Bar')).to eq(Puppet::Pops::Loader::TypedName.new(:type, '::foo::bar'))
end
end
describe 'loaders' do
include PuppetSpec::Files
include PuppetSpec::Compiler
let(:module_without_metadata) { File.join(config_dir('wo_metadata_module'), 'modules') }
let(:module_without_lib) { File.join(config_dir('module_no_lib'), 'modules') }
let(:mix_4x_and_3x_functions) { config_dir('mix_4x_and_3x_functions') }
let(:module_with_metadata) { File.join(config_dir('single_module'), 'modules') }
let(:dependent_modules_with_metadata) { config_dir('dependent_modules_with_metadata') }
let(:no_modules) { config_dir('no_modules') }
let(:user_metadata_path) { File.join(dependent_modules_with_metadata, 'modules/user/metadata.json') }
let(:usee_metadata_path) { File.join(dependent_modules_with_metadata, 'modules/usee/metadata.json') }
let(:usee2_metadata_path) { File.join(dependent_modules_with_metadata, 'modules/usee2/metadata.json') }
let(:empty_test_env) { environment_for() }
# Loaders caches the puppet_system_loader, must reset between tests
before :each do
allow(File).to receive(:read).and_call_original
end
context 'when loading pp resource types using auto loading' do
let(:pp_resources) { config_dir('pp_resources') }
let(:environments) { Puppet::Environments::Directories.new(my_fixture_dir, []) }
let(:env) { Puppet::Node::Environment.create(:'pp_resources', [File.join(pp_resources, 'modules')]) }
let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) }
let(:loader) { Puppet::Pops::Loaders.loaders.find_loader(nil) }
before(:each) do
Puppet.push_context({ :environments => environments })
Puppet.push_context({ :loaders => compiler.loaders })
end
after(:each) do
Puppet.pop_context()
end
it 'finds a resource type that resides under <environment root>/.resource_types' do
rt = loader.load(:resource_type_pp, 'myresource')
expect(rt).to be_a(Puppet::Pops::Resource::ResourceTypeImpl)
end
it 'does not allow additional logic in the file' do
expect{loader.load(:resource_type_pp, 'addlogic')}.to raise_error(ArgumentError, /it has additional logic/)
end
it 'does not allow creation of classes other than Puppet::Resource::ResourceType3' do
expect{loader.load(:resource_type_pp, 'badcall')}.to raise_error(ArgumentError, /no call to Puppet::Resource::ResourceType3.new found/)
end
it 'does not allow creation of other types' do
expect{loader.load(:resource_type_pp, 'wrongname')}.to raise_error(ArgumentError, /produced resource type with the wrong name, expected 'wrongname', actual 'notwrongname'/)
end
it 'errors with message about empty file for files that contain no logic' do
expect{loader.load(:resource_type_pp, 'empty')}.to raise_error(ArgumentError, /it is empty/)
end
it 'creates a pcore resource type loader' do
pcore_loader = env.loaders.runtime3_type_loader.resource_3x_loader
expect(pcore_loader.loader_name).to eq('pcore_resource_types')
expect(pcore_loader).to be_a(Puppet::Pops::Loader::ModuleLoaders::FileBased)
end
it 'does not create a pcore resource type loader if requested not to' do
env.loaders = nil # clear cached loaders
loaders = Puppet::Pops::Loaders.new(env, false, false)
expect(loaders.runtime3_type_loader.resource_3x_loader).to be_nil
end
it 'does not create a pcore resource type loader for an empty environment' do
loaders = Puppet::Pops::Loaders.new(empty_test_env)
expect(loaders.runtime3_type_loader.resource_3x_loader).to be_nil
end
end
def expect_loader_hierarchy(loaders, expected_loaders)
actual_loaders = []
loader = loaders.private_environment_loader
while loader
actual_loaders << [loader.loader_name, loader]
loader = loader.parent
end
expect(actual_loaders).to contain_exactly(*expected_loaders)
end
it 'creates a puppet_system loader' do
loaders = Puppet::Pops::Loaders.new(empty_test_env)
expect(loaders.puppet_system_loader()).to be_a(Puppet::Pops::Loader::ModuleLoaders::FileBased)
end
it 'creates a cached_puppet loader when for_agent is set to true' do
loaders = Puppet::Pops::Loaders.new(empty_test_env, true)
expect(loaders.puppet_cache_loader()).to be_a(Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased)
end
it 'creates a cached_puppet loader that can load version 4 functions, version 3 functions, and data types, in that order' do
loaders = Puppet::Pops::Loaders.new(empty_test_env, true)
expect(loaders.puppet_cache_loader.loadables).to eq([:func_4x, :func_3x, :datatype])
end
it 'does not create a cached_puppet loader when for_agent is the default false value' do
loaders = Puppet::Pops::Loaders.new(empty_test_env)
expect(loaders.puppet_cache_loader()).to be(nil)
end
it 'creates an environment loader' do
loaders = Puppet::Pops::Loaders.new(empty_test_env)
expect(loaders.public_environment_loader()).to be_a(Puppet::Pops::Loader::SimpleEnvironmentLoader)
expect(loaders.public_environment_loader().to_s).to eql("(SimpleEnvironmentLoader 'environment')")
expect(loaders.private_environment_loader()).to be_a(Puppet::Pops::Loader::DependencyLoader)
expect(loaders.private_environment_loader().to_s).to eql("(DependencyLoader 'environment private' [])")
end
it 'creates a hierarchy of loaders' do
expect_loader_hierarchy(
Puppet::Pops::Loaders.new(empty_test_env),
[
[nil, Puppet::Pops::Loader::StaticLoader],
['puppet_system', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased],
[empty_test_env.name, Puppet::Pops::Loader::Runtime3TypeLoader],
['environment', Puppet::Pops::Loader::SimpleEnvironmentLoader],
['environment private', Puppet::Pops::Loader::DependencyLoader],
]
)
end
it 'excludes the Runtime3TypeLoader when tasks are enabled' do
Puppet[:tasks] = true
expect_loader_hierarchy(
Puppet::Pops::Loaders.new(empty_test_env),
[
[nil, Puppet::Pops::Loader::StaticLoader],
['puppet_system', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased],
['environment', Puppet::Pops::Loader::ModuleLoaders::EmptyLoader],
['environment private', Puppet::Pops::Loader::DependencyLoader],
]
)
end
it 'includes the agent cache loader when for_agent is true' do
expect_loader_hierarchy(
Puppet::Pops::Loaders.new(empty_test_env, true),
[
[nil, Puppet::Pops::Loader::StaticLoader],
['puppet_system', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased],
['cached_puppet_lib', Puppet::Pops::Loader::ModuleLoaders::LibRootedFileBased],
[empty_test_env.name, Puppet::Pops::Loader::Runtime3TypeLoader],
['environment', Puppet::Pops::Loader::SimpleEnvironmentLoader],
['environment private', Puppet::Pops::Loader::DependencyLoader],
],
)
end
context 'when loading from a module' do
it 'loads a ruby function using a qualified or unqualified name' do
loaders = Puppet::Pops::Loaders.new(environment_for(module_with_metadata))
modulea_loader = loaders.public_loader_for_module('modulea')
unqualified_function = modulea_loader.load_typed(typed_name(:function, 'rb_func_a')).value
qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::rb_func_a')).value
expect(unqualified_function).to be_a(Puppet::Functions::Function)
expect(qualified_function).to be_a(Puppet::Functions::Function)
expect(unqualified_function.class.name).to eq('rb_func_a')
expect(qualified_function.class.name).to eq('modulea::rb_func_a')
end
it 'loads a puppet function using a qualified name in module' do
loaders = Puppet::Pops::Loaders.new(environment_for(module_with_metadata))
modulea_loader = loaders.public_loader_for_module('modulea')
qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::hello')).value
expect(qualified_function).to be_a(Puppet::Functions::Function)
expect(qualified_function.class.name).to eq('modulea::hello')
end
it 'loads a puppet function from a module without a lib directory' do
loaders = Puppet::Pops::Loaders.new(environment_for(module_without_lib))
modulea_loader = loaders.public_loader_for_module('modulea')
qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::hello')).value
expect(qualified_function).to be_a(Puppet::Functions::Function)
expect(qualified_function.class.name).to eq('modulea::hello')
end
it 'loads a puppet function in a sub namespace of module' do
loaders = Puppet::Pops::Loaders.new(environment_for(module_with_metadata))
modulea_loader = loaders.public_loader_for_module('modulea')
qualified_function = modulea_loader.load_typed(typed_name(:function, 'modulea::subspace::hello')).value
expect(qualified_function).to be_a(Puppet::Functions::Function)
expect(qualified_function.class.name).to eq('modulea::subspace::hello')
end
it 'loader does not add namespace if not given' do
loaders = Puppet::Pops::Loaders.new(environment_for(module_without_metadata))
moduleb_loader = loaders.public_loader_for_module('moduleb')
expect(moduleb_loader.load_typed(typed_name(:function, 'rb_func_b'))).to be_nil
end
it 'loader allows loading a function more than once' do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return('')
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
env = environment_for(File.join(dependent_modules_with_metadata, 'modules'))
loaders = Puppet::Pops::Loaders.new(env)
moduleb_loader = loaders.private_loader_for_module('user')
function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value
expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()")
function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value
expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()")
end
end
context 'when loading from a module with metadata' do
let(:env) { environment_for(File.join(dependent_modules_with_metadata, 'modules')) }
let(:scope) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)).newscope(nil) }
let(:environmentpath) { my_fixture_dir }
let(:node) { Puppet::Node.new('test', :facts => Puppet::Node::Facts.new('facts', {}), :environment => 'dependent_modules_with_metadata') }
let(:compiler) { Puppet::Parser::Compiler.new(node) }
let(:user_metadata) {
{
'name' => 'test-user',
'author' => 'test',
'description' => '',
'license' => '',
'source' => '',
'version' => '1.0.0',
'dependencies' => []
}
}
def compile_and_get_notifications(code)
Puppet[:code] = code
catalog = block_given? ? compiler.compile { |c| yield(compiler.topscope); c } : compiler.compile
catalog.resources.map(&:ref).select { |r| r.start_with?('Notify[') }.map { |r| r[7..-2] }
end
around(:each) do |example|
# Initialize settings to get a full compile as close as possible to a real
# environment load
Puppet.settings.initialize_global_settings
# Initialize loaders based on the environmentpath. It does not work to
# just set the setting environmentpath for some reason - this achieves the same:
# - first a loader is created, loading directory environments from the fixture (there is
# one environment, 'sample', which will be loaded since the node references this
# environment by name).
# - secondly, the created env loader is set as 'environments' in the puppet context.
#
environments = Puppet::Environments::Directories.new(environmentpath, [])
Puppet.override(:environments => environments) do
example.run
end
end
it 'all dependent modules are visible' do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'}, { 'name' => 'test-usee2'} ]).to_json)
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
loaders = Puppet::Pops::Loaders.new(env)
moduleb_loader = loaders.private_loader_for_module('user')
function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value
expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()")
function = moduleb_loader.load_typed(typed_name(:function, 'user::caller2')).value
expect(function.call({})).to eql("usee2::callee() was told 'passed value' + I am user::caller2()")
end
it 'all other modules are visible when tasks are enabled' do
Puppet[:tasks] = true
env = environment_for(File.join(dependent_modules_with_metadata, 'modules'))
loaders = Puppet::Pops::Loaders.new(env)
moduleb_loader = loaders.private_loader_for_module('user')
function = moduleb_loader.load_typed(typed_name(:function, 'user::caller')).value
expect(function.call({})).to eql("usee::callee() was told 'passed value' + I am user::caller()")
end
[ 'outside a function', 'a puppet function declared under functions', 'a puppet function declared in init.pp', 'a ruby function'].each_with_index do |from, from_idx|
[ {:from => from, :called => 'a puppet function declared under functions', :expects => "I'm the function usee::usee_puppet()"},
{:from => from, :called => 'a puppet function declared in init.pp', :expects => "I'm the function usee::usee_puppet_init()"},
{:from => from, :called => 'a ruby function', :expects => "I'm the function usee::usee_ruby()"} ].each_with_index do |desc, called_idx|
case_number = from_idx * 3 + called_idx + 1
it "can call #{desc[:called]} from #{desc[:from]} when dependency is present in metadata.json" do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json)
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
Puppet[:code] = "$case_number = #{case_number}\ninclude ::user"
catalog = compiler.compile
resource = catalog.resource('Notify', "case_#{case_number}")
expect(resource).not_to be_nil
expect(resource['message']).to eq(desc[:expects])
end
it "can call #{desc[:called]} from #{desc[:from]} when no metadata is present" do
times_has_metadata_called = 0
allow_any_instance_of(Puppet::Module).to receive('has_metadata?') { times_has_metadata_called += 1 }.and_return(false)
Puppet[:code] = "$case_number = #{case_number}\ninclude ::user"
catalog = compiler.compile
resource = catalog.resource('Notify', "case_#{case_number}")
expect(resource).not_to be_nil
expect(resource['message']).to eq(desc[:expects])
expect(times_has_metadata_called).to be >= 1
end
it "can not call #{desc[:called]} from #{desc[:from]} if dependency is missing in existing metadata.json" do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => []).to_json)
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
Puppet[:code] = "$case_number = #{case_number}\ninclude ::user"
catalog = compiler.compile
resource = catalog.resource('Notify', "case_#{case_number}")
expect(resource).not_to be_nil
expect(resource['message']).to eq(desc[:expects])
end
end
end
it "a type can reference an autoloaded type alias from another module when dependency is present in metadata.json" do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json)
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok'])
assert_type(Usee::Zero, 0)
notice(ok)
CODE
end
it "a type can reference an autoloaded type alias from another module when no metadata is present" do
expect_any_instance_of(Puppet::Module).to receive('has_metadata?').at_least(:once).and_return(false)
expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok'])
assert_type(Usee::Zero, 0)
notice(ok)
CODE
end
it "a type can reference a type alias from another module when other module has it declared in init.pp" do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json)
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok'])
include 'usee'
assert_type(Usee::One, 1)
notice(ok)
CODE
end
it "an autoloaded type can reference an autoloaded type alias from another module when dependency is present in metadata.json" do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json)
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok'])
assert_type(User::WithUseeZero, [0])
notice(ok)
CODE
end
it "an autoloaded type can reference an autoloaded type alias from another module when other module has it declared in init.pp" do
allow(File).to receive(:read).with(user_metadata_path, {:encoding => 'utf-8'}).and_return(user_metadata.merge('dependencies' => [ { 'name' => 'test-usee'} ]).to_json)
allow(File).to receive(:read).with(usee_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
allow(File).to receive(:read).with(usee2_metadata_path, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
expect(eval_and_collect_notices(<<-CODE, node)).to eq(['ok'])
include 'usee'
assert_type(User::WithUseeOne, [1])
notice(ok)
CODE
end
end
context 'when loading from a module without metadata' do
it 'loads a ruby function with a qualified name' do
loaders = Puppet::Pops::Loaders.new(environment_for(module_without_metadata))
moduleb_loader = loaders.public_loader_for_module('moduleb')
function = moduleb_loader.load_typed(typed_name(:function, 'moduleb::rb_func_b')).value
expect(function).to be_a(Puppet::Functions::Function)
expect(function.class.name).to eq('moduleb::rb_func_b')
end
it 'all other modules are visible' do
env = environment_for(module_with_metadata, module_without_metadata)
loaders = Puppet::Pops::Loaders.new(env)
moduleb_loader = loaders.private_loader_for_module('moduleb')
function = moduleb_loader.load_typed(typed_name(:function, 'moduleb::rb_func_b')).value
expect(function.call({})).to eql("I am modulea::rb_func_a() + I am moduleb::rb_func_b()")
end
end
context 'when loading from an environment without modules' do
let(:node) { Puppet::Node.new('test', :facts => Puppet::Node::Facts.new('facts', {}), :environment => 'no_modules') }
it 'can load the same function twice with two different compilations and produce different values' do
Puppet.settings.initialize_global_settings
environments = Puppet::Environments::Directories.new(my_fixture_dir, [])
Puppet.override(:environments => environments) do
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['value_from_scope'] = 'first'
catalog = compiler.compile
expect(catalog.resource('Notify[first]')).to be_a(Puppet::Resource)
expect(Puppet::Pops::Loader::RubyFunctionInstantiator).not_to receive(:create)
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['value_from_scope'] = 'second'
catalog = compiler.compile
expect(catalog.resource('Notify[first]')).to be_nil
expect(catalog.resource('Notify[second]')).to be_a(Puppet::Resource)
end
end
end
context 'when calling' do
let(:env) { environment_for(mix_4x_and_3x_functions) }
let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) }
let(:scope) { compiler.topscope }
let(:loader) { compiler.loaders.private_loader_for_module('user') }
before(:each) do
Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders)
end
it 'a 3x function in dependent module can be called from a 4x function' do
function = loader.load_typed(typed_name(:function, 'user::caller')).value
expect(function.call(scope)).to eql("usee::callee() got 'first' - usee::callee() got 'second'")
end
it 'a 3x function in dependent module can be called from a puppet function' do
function = loader.load_typed(typed_name(:function, 'user::puppetcaller')).value
expect(function.call(scope)).to eql("usee::callee() got 'first' - usee::callee() got 'second'")
end
it 'a 4x function can be called from a puppet function' do
function = loader.load_typed(typed_name(:function, 'user::puppetcaller4')).value
expect(function.call(scope)).to eql("usee::callee() got 'first' - usee::callee() got 'second'")
end
it 'a puppet function can be called from a 4x function' do
function = loader.load_typed(typed_name(:function, 'user::callingpuppet')).value
expect(function.call(scope)).to eql("Did you call to say you love me?")
end
it 'a 3x function can be called with caller scope propagated from a 4x function' do
function = loader.load_typed(typed_name(:function, 'user::caller_ws')).value
expect(function.call(scope, 'passed in scope')).to eql("usee::callee_ws() got 'passed in scope'")
end
it 'calls can be made to a non core function via the call() function' do
call_function = loader.load_typed(typed_name(:function, 'call')).value
expect(call_function.call(scope, 'user::puppetcaller4')).to eql("usee::callee() got 'first' - usee::callee() got 'second'")
end
end
context 'when a 3x load takes place' do
let(:env) { environment_for(mix_4x_and_3x_functions) }
let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) }
let(:scope) { compiler.topscope }
let(:loader) { compiler.loaders.private_loader_for_module('user') }
before(:each) do
Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders)
end
after(:each) do
Puppet.pop_context
end
it "a function with no illegal constructs can be loaded" do
function = loader.load_typed(typed_name(:function, 'good_func_load')).value
expect(function.call(scope)).to eql(Float("3.14"))
end
it "a function with syntax error has helpful error message" do
expect {
loader.load_typed(typed_name(:function, 'func_with_syntax_error'))
}.to raise_error(/syntax error, unexpected (keyword_|`)?end/)
end
end
context 'when a 3x load has illegal method added' do
let(:env) { environment_for(mix_4x_and_3x_functions) }
let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) }
let(:scope) { compiler.topscope }
let(:loader) { compiler.loaders.private_loader_for_module('user') }
before(:each) do
Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders)
end
after(:each) do
Puppet.pop_context
end
it "outside function body is reported as an error" do
expect { loader.load_typed(typed_name(:function, 'bad_func_load')) }.to raise_error(/Illegal method definition/)
end
it "to self outside function body is reported as an error" do
expect { loader.load_typed(typed_name(:function, 'bad_func_load5')) }.to raise_error(/Illegal method definition.*'bad_func_load5_illegal_method'/)
end
it "outside body is reported as an error even if returning the right func_info" do
expect { loader.load_typed(typed_name(:function, 'bad_func_load2'))}.to raise_error(/Illegal method definition/)
end
it "inside function body is reported as an error" do
expect {
f = loader.load_typed(typed_name(:function, 'bad_func_load3')).value
f.call(scope)
}.to raise_error(/Illegal method definition.*'bad_func_load3_illegal_method'/)
end
it "to self inside function body is reported as an error" do
expect {
f = loader.load_typed(typed_name(:function, 'bad_func_load4')).value
f.call(scope)
}.to raise_error(/Illegal method definition.*'bad_func_load4_illegal_method'/)
end
end
context 'when causing a 3x load followed by a 4x load' do
let(:env) { environment_for(mix_4x_and_3x_functions) }
let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new("test", :environment => env)) }
let(:scope) { compiler.topscope }
let(:loader) { compiler.loaders.private_loader_for_module('user') }
before(:each) do
Puppet.push_context(:current_environment => scope.environment, :global_scope => scope, :loaders => compiler.loaders)
end
after(:each) do
Puppet.pop_context
end
it 'a 3x function is loaded once' do
# create a 3x function that when called will do a load of "callee_ws"
Puppet::Parser::Functions::newfunction(:callee, :type => :rvalue, :arity => 1) do |args|
function_callee_ws(['passed in scope'])
end
expect(Puppet).not_to receive(:warning)
scope['passed_in_scope'] = 'value'
function = loader.load_typed(typed_name(:function, 'callee')).value
expect(function.call(scope, 'passed in scope')).to eql("usee::callee_ws() got 'value'")
function = loader.load_typed(typed_name(:function, 'callee_ws')).value
expect(function.call(scope, 'passed in scope')).to eql("usee::callee_ws() got 'value'")
end
it "an illegal function is loaded" do
expect {
loader.load_typed(typed_name(:function, 'bad_func_load3')).value
}.to raise_error(SecurityError, /Illegal method definition of method 'bad_func_load3_illegal_method' in source .*bad_func_load3.rb on line 8 in legacy function/)
end
end
context 'loading' do
let(:env_name) { 'testenv' }
let(:environments_dir) { Puppet[:environmentpath] }
let(:env_dir) { File.join(environments_dir, env_name) }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')]) }
let(:node) { Puppet::Node.new("test", :environment => env) }
let(:env_dir_files) {}
let(:populated_env_dir) do
dir_contained_in(environments_dir, env_name => env_dir_files)
PuppetSpec::Files.record_tmp(env_dir)
env_dir
end
context 'non autoloaded types and functions' do
let(:env_dir_files) {
{
'modules' => {
'tstf' => {
'manifests' => {
'init.pp' => <<-PUPPET.unindent
class tstf {
notice(testfunc())
}
PUPPET
}
},
'tstt' => {
'manifests' => {
'init.pp' => <<-PUPPET.unindent
class tstt {
notice(assert_type(GlobalType, 23))
}
PUPPET
}
}
}
}
}
it 'finds the function from a module' do
expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eq(['hello from testfunc'])
function testfunc() {
'hello from testfunc'
}
include 'tstf'
PUPPET
end
it 'finds the type from a module' do
expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eq(['23'])
type GlobalType = Integer
include 'tstt'
PUPPET
end
end
context 'types' do
let(:env_name) { 'testenv' }
let(:environments_dir) { Puppet[:environmentpath] }
let(:env_dir) { File.join(environments_dir, env_name) }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')]) }
let(:metadata_json) {
<<-JSON
{
"name": "example/%1$s",
"version": "0.0.2",
"source": "git@github.com/example/example-%1$s.git",
"dependencies": [],
"author": "Bob the Builder",
"license": "Apache-2.0"%2$s
}
JSON
}
let(:env_dir_files) do
{
'types' => {
'c.pp' => 'type C = Integer'
},
'modules' => {
'a' => {
'manifests' => {
'init.pp' => 'class a { notice(A::A) }'
},
'types' => {
'a.pp' => 'type A::A = Variant[B::B, String]',
'n.pp' => 'type A::N = C::C'
},
'metadata.json' => sprintf(metadata_json, 'a', ', "dependencies": [{ "name": "example/b" }]')
},
'b' => {
'types' => {
'b.pp' => 'type B::B = Variant[C::C, Float]',
'x.pp' => 'type B::X = A::A'
},
'metadata.json' => sprintf(metadata_json, 'b', ', "dependencies": [{ "name": "example/c" }]')
},
'c' => {
'types' => {
'init_typeset.pp' => <<-PUPPET.unindent,
type C = TypeSet[{
pcore_version => '1.0.0',
types => {
C => Integer,
D => Float
}
}]
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/loaders/loader_paths_spec.rb | spec/unit/pops/loaders/loader_paths_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/pops'
require 'puppet/loaders'
describe 'loader paths' do
include PuppetSpec::Files
let(:static_loader) { Puppet::Pops::Loader::StaticLoader.new() }
let(:unused_loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:'*test*', [])) }
it 'module loader has smart-paths that prunes unavailable paths' do
module_dir = dir_containing('testmodule', {'lib' => {'puppet' => {'functions' =>
{'foo.rb' =>
'Puppet::Functions.create_function("testmodule::foo") {
def foo; end;
}'
}
}}})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, unused_loaders, 'testmodule', module_dir)
effective_paths = module_loader.smart_paths.effective_paths(:function)
expect(effective_paths.size).to be_eql(1)
expect(effective_paths[0].generic_path).to be_eql(File.join(module_dir, 'lib', 'puppet', 'functions'))
end
it 'all function smart-paths produces entries if they exist' do
module_dir = dir_containing('testmodule', {
'lib' => {
'puppet' => {
'functions' => {'foo4x.rb' => 'ignored in this test'},
}}})
module_loader = Puppet::Pops::Loader::ModuleLoaders.module_loader_from(static_loader, unused_loaders, 'testmodule', module_dir)
effective_paths = module_loader.smart_paths.effective_paths(:function)
expect(effective_paths.size).to eq(1)
expect(module_loader.path_index.size).to eq(1)
path_index = module_loader.path_index
expect(path_index).to include(File.join(module_dir, 'lib', 'puppet', 'functions', 'foo4x.rb'))
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/loaders/environment_loader_spec.rb | spec/unit/pops/loaders/environment_loader_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/pops'
require 'puppet/loaders'
describe 'Environment loader' do
include PuppetSpec::Files
let(:env_name) { 'spec' }
let(:code_dir) { Puppet[:environmentpath] }
let(:env_dir) { File.join(code_dir, env_name) }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_code_dir, env_name, 'modules')]) }
let(:populated_code_dir) do
dir_contained_in(code_dir, env_name => env_content)
PuppetSpec::Files.record_tmp(env_dir)
code_dir
end
let(:env_content) {
{
'lib' => {
'puppet' => {
'functions' => {
'ruby_foo.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:ruby_foo) do
def ruby_foo()
'ruby_foo'
end
end
RUBY
'environment' => {
'ruby_foo.rb' => <<-RUBY.unindent
Puppet::Functions.create_function(:'environment::ruby_foo') do
def ruby_foo()
'environment::ruby_foo'
end
end
RUBY
},
'someother' => {
'ruby_foo.rb' => <<-RUBY.unindent
Puppet::Functions.create_function(:'someother::ruby_foo') do
def ruby_foo()
'someother::ruby_foo'
end
end
RUBY
},
}
}
},
'functions' => {
'puppet_foo.pp' => <<-PUPPET.unindent,
function puppet_foo() {
'puppet_foo'
}
PUPPET
'environment' => {
'puppet_foo.pp' => <<-PUPPET.unindent,
function environment::puppet_foo() {
'environment::puppet_foo'
}
PUPPET
},
'someother' => {
'puppet_foo.pp' => <<-PUPPET.unindent,
function somether::puppet_foo() {
'someother::puppet_foo'
}
PUPPET
}
},
'types' => {
'footype.pp' => <<-PUPPET.unindent,
type FooType = Enum['foo', 'bar', 'baz']
PUPPET
'environment' => {
'footype.pp' => <<-PUPPET.unindent,
type Environment::FooType = Integer[0,9]
PUPPET
},
'someother' => {
'footype.pp' => <<-PUPPET.unindent,
type SomeOther::FooType = Float[0.0,9.0]
PUPPET
}
}
}
}
before(:each) do
Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env))
end
after(:each) do
Puppet.pop_context
end
def load_or_nil(type, name)
found = Puppet::Pops::Loaders.find_loader(nil).load_typed(Puppet::Pops::Loader::TypedName.new(type, name))
found.nil? ? nil : found.value
end
context 'loading a Ruby function' do
it 'loads from global name space' do
function = load_or_nil(:function, 'ruby_foo')
expect(function).not_to be_nil
expect(function.class.name).to eq('ruby_foo')
expect(function).to be_a(Puppet::Functions::Function)
end
it 'loads from environment name space' do
function = load_or_nil(:function, 'environment::ruby_foo')
expect(function).not_to be_nil
expect(function.class.name).to eq('environment::ruby_foo')
expect(function).to be_a(Puppet::Functions::Function)
end
it 'fails to load from namespaces other than global or environment' do
function = load_or_nil(:function, 'someother::ruby_foo')
expect(function).to be_nil
end
end
context 'loading a Puppet function' do
it 'loads from global name space' do
function = load_or_nil(:function, 'puppet_foo')
expect(function).not_to be_nil
expect(function.class.name).to eq('puppet_foo')
expect(function).to be_a(Puppet::Functions::PuppetFunction)
end
it 'loads from environment name space' do
function = load_or_nil(:function, 'environment::puppet_foo')
expect(function).not_to be_nil
expect(function.class.name).to eq('environment::puppet_foo')
expect(function).to be_a(Puppet::Functions::PuppetFunction)
end
it 'fails to load from namespaces other than global or environment' do
function = load_or_nil(:function, 'someother::puppet_foo')
expect(function).to be_nil
end
end
context 'loading a Puppet type' do
it 'loads from global name space' do
type = load_or_nil(:type, 'footype')
expect(type).not_to be_nil
expect(type).to be_a(Puppet::Pops::Types::PTypeAliasType)
expect(type.name).to eq('FooType')
end
it 'loads from environment name space' do
type = load_or_nil(:type, 'environment::footype')
expect(type).not_to be_nil
expect(type).to be_a(Puppet::Pops::Types::PTypeAliasType)
expect(type.name).to eq('Environment::FooType')
end
it 'fails to load from namespaces other than global or environment' do
type = load_or_nil(:type, 'someother::footype')
expect(type).to be_nil
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/locator_spec.rb | spec/unit/pops/parser/locator_spec.rb | require 'spec_helper'
require 'puppet/pops'
describe Puppet::Pops::Parser::Locator do
it "multi byte characters in a comment does not interfere with AST node text extraction" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("# \u{0400}comment\nabcdef#XXXXXXXXXX").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.offset).to eq(12)
expect(model.body.length).to eq(6)
expect(model.body.locator.extract_text(model.body.offset, model.body.length)).to eq('abcdef')
end
it "multi byte characters in a comment does not interfere with AST node text extraction" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("# \u{0400}comment\n1 + 2#XXXXXXXXXX").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.offset).to eq(14) # The '+'
expect(model.body.length).to eq(1)
expect(model.body.locator.extract_tree_text(model.body)).to eq('1 + 2')
end
it 'Locator caches last offset / line' do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("$a\n = 1\n + 1\n").model
expect(model.body.locator).to receive(:ary_bsearch_i).with(anything, 2).once.and_return(:special_value)
expect(model.body.locator.line_for_offset(2)).to eq(:special_value)
expect(model.body.locator.line_for_offset(2)).to eq(:special_value)
end
it 'Locator invalidates last offset / line cache if asked for different offset' do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("$a\n = 1\n + 1\n").model
expect(model.body.locator).to receive(:ary_bsearch_i).with(anything, 2).twice.and_return(:first_value, :third_value)
expect(model.body.locator).to receive(:ary_bsearch_i).with(anything, 3).once.and_return(:second_value)
expect(model.body.locator.line_for_offset(2)).to eq(:first_value)
expect(model.body.locator.line_for_offset(3)).to eq(:second_value) # invalidates cache as side effect
expect(model.body.locator.line_for_offset(2)).to eq(:third_value)
end
it 'A heredoc without margin and interpolated expression location has offset and length relative the source' do
parser = Puppet::Pops::Parser::Parser.new()
src = <<-CODE
# line one
# line two
@("END"/L)
Line four\\
Line five ${1 +
1}
END
CODE
model = parser.parse_string(src).model
interpolated_expr = model.body.text_expr.segments[1].expr
expect(interpolated_expr.left_expr.offset).to eq(84)
expect(interpolated_expr.left_expr.length).to eq(1)
expect(interpolated_expr.right_expr.offset).to eq(96)
expect(interpolated_expr.right_expr.length).to eq(1)
expect(interpolated_expr.offset).to eq(86) # the + sign
expect(interpolated_expr.length).to eq(1) # the + sign
expect(interpolated_expr.locator.extract_tree_text(interpolated_expr)).to eq("1 +\n 1")
end
it 'A heredoc with margin and interpolated expression location has offset and length relative the source' do
parser = Puppet::Pops::Parser::Parser.new()
src = <<-CODE
# line one
# line two
@("END"/L)
Line four\\
Line five ${1 +
1}
|- END
CODE
model = parser.parse_string(src).model
interpolated_expr = model.body.text_expr.segments[1].expr
expect(interpolated_expr.left_expr.offset).to eq(84)
expect(interpolated_expr.left_expr.length).to eq(1)
expect(interpolated_expr.right_expr.offset).to eq(96)
expect(interpolated_expr.right_expr.length).to eq(1)
expect(interpolated_expr.offset).to eq(86) # the + sign
expect(interpolated_expr.length).to eq(1) # the + sign
expect(interpolated_expr.locator.extract_tree_text(interpolated_expr)).to eq("1 +\n 1")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_heredoc_spec.rb | spec/unit/pops/parser/parse_heredoc_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing heredoc" do
include ParserRspecHelper
it "parses plain heredoc" do
expect(dump(parse("@(END)\nThis is\nheredoc text\nEND\n"))).to eq([
"(@()",
" 'This is\nheredoc text\n'",
")"
].join("\n"))
end
it "parses heredoc with margin" do
src = [
"@(END)",
" This is",
" heredoc text",
" | END",
""
].join("\n")
expect(dump(parse(src))).to eq([
"(@()",
" 'This is\nheredoc text\n'",
")"
].join("\n"))
end
it "parses heredoc with margin and right newline trim" do
src = [
"@(END)",
" This is",
" heredoc text",
" |- END",
""
].join("\n")
expect(dump(parse(src))).to eq([
"(@()",
" 'This is\nheredoc text'",
")"
].join("\n"))
end
it "parses syntax and escape specification" do
src = <<-CODE
@(END:syntax/t)
Tex\\tt\\n
|- END
CODE
expect(dump(parse(src))).to eq([
"(@(syntax)",
" 'Tex\tt\\n'",
")"
].join("\n"))
end
it "parses interpolated heredoc expression" do
src = <<-CODE
@("END")
Hello $name
|- END
CODE
expect(dump(parse(src))).to eq([
"(@()",
" (cat 'Hello ' (str $name))",
")"
].join("\n"))
end
it "parses interpolated heredoc expression containing escapes" do
src = <<-CODE
@("END")
Hello \\$name
|- END
CODE
expect(dump(parse(src))).to eq([
"(@()",
" (cat 'Hello \\' (str $name))",
")"
].join("\n"))
end
it "parses interpolated heredoc expression containing escapes when escaping other things than $" do
src = <<-CODE
@("END"/t)
Hello \\$name
|- END
CODE
expect(dump(parse(src))).to eq([
"(@()",
" (cat 'Hello \\' (str $name))",
")"
].join("\n"))
end
it "parses with escaped newlines without preceding whitespace" do
src = <<-CODE
@(END/L)
First Line\\
Second Line
|- END
CODE
parse(src)
expect(dump(parse(src))).to eq([
"(@()",
" 'First Line Second Line'",
")"
].join("\n"))
end
it "parses with escaped newlines with proper margin" do
src = <<-CODE
@(END/L)
First Line\\
Second Line
|- END
CODE
parse(src)
expect(dump(parse(src))).to eq([
"(@()",
" ' First Line Second Line'",
")"
].join("\n"))
end
it "parses interpolated heredoc expression with false start on $" do
src = <<-CODE
@("END")
Hello $name$%a
|- END
CODE
expect(dump(parse(src))).to eq([
"(@()",
" (cat 'Hello ' (str $name) '$%a')",
")"
].join("\n"))
end
it "parses interpolated [] expression by looking at the correct preceding char for space when there is no heredoc margin" do
# NOTE: Important not to use the left margin feature here
src = <<-CODE
$xxxxxxx = @("END")
${facts['os']['family']}
XXXXXXX XXX
END
CODE
expect(dump(parse(src))).to eq([
"(= $xxxxxxx (@()",
" (cat (str (slice (slice $facts 'os') 'family')) '",
"XXXXXXX XXX",
"')",
"))"].join("\n"))
end
it "parses interpolated [] expression by looking at the correct preceding char for space when there is a heredoc margin" do
# NOTE: Important not to use the left margin feature here - the problem in PUP 9303 is triggered by lines and text before
# an interpolation containing [].
src = <<-CODE
# comment
# comment
$xxxxxxx = @("END")
1
2
3
4
5
YYYYY${facts['fqdn']}
XXXXXXX XXX
| END
CODE
expect(dump(parse(src))).to eq([
"(= $xxxxxxx (@()",
" (cat '1", "2", "3", "4", "5",
"YYYYY' (str (slice $facts 'fqdn')) '",
"XXXXXXX XXX",
"')",
"))"].join("\n"))
end
it "correctly reports an error location in a nested heredoc with margin" do
# NOTE: Important not to use the left margin feature here - the problem in PUP 9303 is triggered by lines and text before
# an interpolation containing [].
src = <<-CODE
# comment
# comment
$xxxxxxx = @("END")
1
2
3
4
5
YYYYY${facts]}
XXXXXXX XXX
| END
CODE
expect{parse(src)}.to raise_error(/Syntax error at '\]' \(line: 9, column: 15\)/)
end
it "correctly reports an error location in a heredoc with line endings escaped" do
# DO NOT CHANGE INDENTATION OF THIS HEREDOC
src = <<-CODE
# line one
# line two
@("END"/L)
First Line\\
Second Line ${facts]}
|- END
CODE
expect{parse(src)}.to raise_error(/Syntax error at '\]' \(line: 5, column: 24\)/)
end
it "correctly reports an error location in a heredoc with line endings escaped when there is text in the margin" do
# DO NOT CHANGE INDENTATION OR SPACING OF THIS HEREDOC
src = <<-CODE
# line one
# line two
@("END"/L)
First Line\\
Second Line
x Third Line ${facts]}
|- END
# line 8
# line 9
CODE
expect{parse(src)}.to raise_error(/Syntax error at '\]' \(line: 6, column: 23\)/)
end
it "correctly reports an error location in a heredoc with line endings escaped when there is text in the margin" do
# DO NOT CHANGE INDENTATION OR SPACING OF THIS HEREDOC
src = <<-CODE
@(END)
AAA
BBB
CCC
DDD
EEE
FFF
|- END
CODE
expect(dump(parse(src))).to eq([
"(@()",
" 'AAA", # no left space trimmed
" BBB",
" CCC",
" DDD",
"EEE", # left space trimmed
" FFF'", # indented one because it is one in from margin marker
")"].join("\n"))
end
it 'parses multiple heredocs on the same line' do
src = <<-CODE
notice({ @(foo) => @(bar) })
hello
-foo
world
-bar
notice '!'
CODE
expect(dump(parse(src))).to eq([
'(block',
' (invoke notice ({} ((@()',
' \' hello\'',
' ) (@()',
' \' world\'',
' ))))',
' (invoke notice \'!\')',
')'
].join("\n"))
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/epp_parser_spec.rb | spec/unit/pops/parser/epp_parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
require File.join(File.dirname(__FILE__), '/../factory_rspec_helper')
module EppParserRspecHelper
include FactoryRspecHelper
def parse(code)
parser = Puppet::Pops::Parser::EppParser.new()
parser.parse_string(code)
end
end
describe "epp parser" do
include EppParserRspecHelper
it "should instantiate an epp parser" do
parser = Puppet::Pops::Parser::EppParser.new()
expect(parser.class).to eq(Puppet::Pops::Parser::EppParser)
end
it "should parse a code string and return a program with epp" do
parser = Puppet::Pops::Parser::EppParser.new()
model = parser.parse_string("Nothing to see here, move along...").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::LambdaExpression)
expect(model.body.body.class).to eq(Puppet::Pops::Model::EppExpression)
end
context "when facing bad input it reports" do
it "unbalanced tags" do
expect { dump(parse("<% missing end tag")) }.to raise_error(/Unbalanced/)
end
it "abrupt end" do
expect { dump(parse("dum di dum di dum <%")) }.to raise_error(/Unbalanced/)
end
it "nested epp tags" do
expect { dump(parse("<% $a = 10 <% $b = 20 %>%>")) }.to raise_error(/Syntax error/)
end
it "nested epp expression tags" do
expect { dump(parse("<%= 1+1 <%= 2+2 %>%>")) }.to raise_error(/Syntax error/)
end
it "rendering sequence of expressions" do
expect { dump(parse("<%= 1 2 3 %>")) }.to raise_error(/Syntax error/)
end
end
context "handles parsing of" do
it "text (and nothing else)" do
expect(dump(parse("Hello World"))).to eq([
"(lambda (epp (block",
" (render-s 'Hello World')",
")))"].join("\n"))
end
it "template parameters" do
expect(dump(parse("<%|$x|%>Hello World"))).to eq([
"(lambda (parameters x) (epp (block",
" (render-s 'Hello World')",
")))"].join("\n"))
end
it "template parameters with default" do
expect(dump(parse("<%|$x='cigar'|%>Hello World"))).to eq([
"(lambda (parameters (= x 'cigar')) (epp (block",
" (render-s 'Hello World')",
")))"].join("\n"))
end
it "template parameters with and without default" do
expect(dump(parse("<%|$x='cigar', $y|%>Hello World"))).to eq([
"(lambda (parameters (= x 'cigar') y) (epp (block",
" (render-s 'Hello World')",
")))"].join("\n"))
end
it "template parameters + additional setup" do
expect(dump(parse("<%|$x| $y = 10 %>Hello World"))).to eq([
"(lambda (parameters x) (epp (block",
" (= $y 10)",
" (render-s 'Hello World')",
")))"].join("\n"))
end
it "comments" do
expect(dump(parse("<%#($x='cigar', $y)%>Hello World"))).to eq([
"(lambda (epp (block",
" (render-s 'Hello World')",
")))"
].join("\n"))
end
it "verbatim epp tags" do
expect(dump(parse("<%% contemplating %%>Hello World"))).to eq([
"(lambda (epp (block",
" (render-s '<% contemplating %>Hello World')",
")))"
].join("\n"))
end
it "expressions" do
expect(dump(parse("We all live in <%= 3.14 - 2.14 %> world"))).to eq([
"(lambda (epp (block",
" (render-s 'We all live in ')",
" (render (- 3.14 2.14))",
" (render-s ' world')",
")))"
].join("\n"))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parser_rspec_helper.rb | spec/unit/pops/parser/parser_rspec_helper.rb | require 'puppet/pops'
require File.join(File.dirname(__FILE__), '/../factory_rspec_helper')
module ParserRspecHelper
include FactoryRspecHelper
def parse(code)
parser = Puppet::Pops::Parser::Parser.new()
parser.parse_string(code)
end
def parse_epp(code)
parser = Puppet::Pops::Parser::EppParser.new()
parser.parse_string(code)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/lexer2_spec.rb | spec/unit/pops/parser/lexer2_spec.rb | require 'spec_helper'
require 'matchers/match_tokens2'
require 'puppet/pops'
require 'puppet/pops/parser/lexer2'
module EgrammarLexer2Spec
def tokens_scanned_from(s)
lexer = Puppet::Pops::Parser::Lexer2.new
lexer.string = s
lexer.fullscan[0..-2]
end
def epp_tokens_scanned_from(s)
lexer = Puppet::Pops::Parser::Lexer2.new
lexer.string = s
lexer.fullscan_epp[0..-2]
end
end
describe 'Lexer2' do
include EgrammarLexer2Spec
{
:LISTSTART => '[',
:RBRACK => ']',
:LBRACE => '{',
:RBRACE => '}',
:WSLPAREN => '(', # since it is first on a line it is special (LPAREN handled separately)
:RPAREN => ')',
:EQUALS => '=',
:ISEQUAL => '==',
:GREATEREQUAL => '>=',
:GREATERTHAN => '>',
:LESSTHAN => '<',
:LESSEQUAL => '<=',
:NOTEQUAL => '!=',
:NOT => '!',
:COMMA => ',',
:DOT => '.',
:COLON => ':',
:AT => '@',
:LLCOLLECT => '<<|',
:RRCOLLECT => '|>>',
:LCOLLECT => '<|',
:RCOLLECT => '|>',
:SEMIC => ';',
:QMARK => '?',
:OTHER => '\\',
:FARROW => '=>',
:PARROW => '+>',
:APPENDS => '+=',
:DELETES => '-=',
:PLUS => '+',
:MINUS => '-',
:DIV => '/',
:TIMES => '*',
:LSHIFT => '<<',
:RSHIFT => '>>',
:MATCH => '=~',
:NOMATCH => '!~',
:IN_EDGE => '->',
:OUT_EDGE => '<-',
:IN_EDGE_SUB => '~>',
:OUT_EDGE_SUB => '<~',
:PIPE => '|',
}.each do |name, string|
it "should lex a token named #{name.to_s}" do
expect(tokens_scanned_from(string)).to match_tokens2(name)
end
end
it "should lex [ in position after non whitespace as LBRACK" do
expect(tokens_scanned_from("a[")).to match_tokens2(:NAME, :LBRACK)
end
{
"case" => :CASE,
"class" => :CLASS,
"default" => :DEFAULT,
"define" => :DEFINE,
# "import" => :IMPORT, # done as a function in egrammar
"if" => :IF,
"elsif" => :ELSIF,
"else" => :ELSE,
"inherits" => :INHERITS,
"node" => :NODE,
"and" => :AND,
"or" => :OR,
"undef" => :UNDEF,
"false" => :BOOLEAN,
"true" => :BOOLEAN,
"in" => :IN,
"unless" => :UNLESS,
"private" => :PRIVATE,
"type" => :TYPE,
"attr" => :ATTR,
}.each do |string, name|
it "should lex a keyword from '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2(name)
end
end
context 'when --no-tasks (the default)' do
it "should lex a NAME from 'plan'" do
expect(tokens_scanned_from('plan')).to match_tokens2(:NAME)
end
end
context 'when --tasks' do
before(:each) { Puppet[:tasks] = true }
after(:each) { Puppet[:tasks] = false }
it "should lex a keyword from 'plan'" do
expect(tokens_scanned_from('plan')).to match_tokens2(:PLAN)
end
end
# TODO: Complete with all edge cases
[ 'A', 'A::B', '::A', '::A::B',].each do |string|
it "should lex a CLASSREF on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:CLASSREF, string])
end
end
# TODO: Complete with all edge cases
[ 'a', 'a::b', '::a', '::a::b',].each do |string|
it "should lex a NAME on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:NAME, string])
end
end
[ 'a-b', 'a--b', 'a-b-c', '_x'].each do |string|
it "should lex a BARE WORD STRING on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:WORD, string])
end
end
[ '_x::y', 'x::_y'].each do |string|
it "should consider the bare word '#{string}' to be a WORD" do
expect(tokens_scanned_from(string)).to match_tokens2(:WORD)
end
end
{ '-a' => [:MINUS, :NAME],
'--a' => [:MINUS, :MINUS, :NAME],
'a-' => [:NAME, :MINUS],
'a- b' => [:NAME, :MINUS, :NAME],
'a--' => [:NAME, :MINUS, :MINUS],
'a-$3' => [:NAME, :MINUS, :VARIABLE],
}.each do |source, expected|
it "should lex leading and trailing hyphens from #{source}" do
expect(tokens_scanned_from(source)).to match_tokens2(*expected)
end
end
{ 'false'=>false, 'true'=>true}.each do |string, value|
it "should lex a BOOLEAN on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:BOOLEAN, value])
end
end
[ '0', '1', '2982383139'].each do |string|
it "should lex a decimal integer NUMBER on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string])
end
end
{ ' 1' => '1', '1 ' => '1', ' 1 ' => '1'}.each do |string, value|
it "should lex a NUMBER with surrounding space '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, value])
end
end
[ '0.0', '0.1', '0.2982383139', '29823.235', '10e23', '10e-23', '1.234e23'].each do |string|
it "should lex a decimal floating point NUMBER on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string])
end
end
[ '00', '01', '0123', '0777'].each do |string|
it "should lex an octal integer NUMBER on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string])
end
end
[ '0x0', '0x1', '0xa', '0xA', '0xabcdef', '0xABCDEF'].each do |string|
it "should lex an hex integer NUMBER on the form '#{string}'" do
expect(tokens_scanned_from(string)).to match_tokens2([:NUMBER, string])
end
end
{ "''" => '',
"'a'" => 'a',
"'a\\'b'" =>"a'b",
"'a\\rb'" =>"a\\rb",
"'a\\nb'" =>"a\\nb",
"'a\\tb'" =>"a\\tb",
"'a\\sb'" =>"a\\sb",
"'a\\$b'" =>"a\\$b",
"'a\\\"b'" =>"a\\\"b",
"'a\\\\b'" =>"a\\b",
"'a\\\\'" =>"a\\",
}.each do |source, expected|
it "should lex a single quoted STRING on the form #{source}" do
expect(tokens_scanned_from(source)).to match_tokens2([:STRING, expected])
end
end
{ "''" => [2, ""],
"'a'" => [3, "a"],
"'a\\'b'" => [6, "a'b"],
}.each do |source, expected|
it "should lex a single quoted STRING on the form #{source} as having length #{expected[0]}" do
length, value = expected
expect(tokens_scanned_from(source)).to match_tokens2([:STRING, value, {:line => 1, :pos=>1, :length=> length}])
end
end
{ '""' => '',
'"a"' => 'a',
'"a\'b"' => "a'b",
}.each do |source, expected|
it "should lex a double quoted STRING on the form #{source}" do
expect(tokens_scanned_from(source)).to match_tokens2([:STRING, expected])
end
end
{ '"a$x b"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>2 }],
[:VARIABLE, 'x', {:line => 1, :pos=>3, :length=>2 }],
[:DQPOST, ' b', {:line => 1, :pos=>5, :length=>3 }]],
'"a$x.b"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>2 }],
[:VARIABLE, 'x', {:line => 1, :pos=>3, :length=>2 }],
[:DQPOST, '.b', {:line => 1, :pos=>5, :length=>3 }]],
'"$x.b"' => [[:DQPRE, '', {:line => 1, :pos=>1, :length=>1 }],
[:VARIABLE, 'x', {:line => 1, :pos=>2, :length=>2 }],
[:DQPOST, '.b', {:line => 1, :pos=>4, :length=>3 }]],
'"a$x"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>2 }],
[:VARIABLE, 'x', {:line => 1, :pos=>3, :length=>2 }],
[:DQPOST, '', {:line => 1, :pos=>5, :length=>1 }]],
'"a${x}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }],
[:VARIABLE, 'x', {:line => 1, :pos=>5, :length=>1 }],
[:DQPOST, '', {:line => 1, :pos=>7, :length=>1 }]],
'"a${_x}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }],
[:VARIABLE, '_x', {:line => 1, :pos=>5, :length=>2 }],
[:DQPOST, '', {:line => 1, :pos=>8, :length=>1 }]],
'"a${y::_x}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }],
[:VARIABLE, 'y::_x', {:line => 1, :pos=>5, :length=>5 }],
[:DQPOST, '', {:line => 1, :pos=>11, :length=>1 }]],
'"a${_x[1]}"' => [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }],
[:VARIABLE, '_x', {:line => 1, :pos=>5, :length=>2 }],
[:LBRACK, '[', {:line => 1, :pos=>7, :length=>1 }],
[:NUMBER, '1', {:line => 1, :pos=>8, :length=>1 }],
[:RBRACK, ']', {:line => 1, :pos=>9, :length=>1 }],
[:DQPOST, '', {:line => 1, :pos=>11, :length=>1 }]],
'"a${_x.foo}"'=> [[:DQPRE, 'a', {:line => 1, :pos=>1, :length=>4 }],
[:VARIABLE, '_x', {:line => 1, :pos=>5, :length=>2 }],
[:DOT, '.', {:line => 1, :pos=>7, :length=>1 }],
[:NAME, 'foo', {:line => 1, :pos=>8, :length=>3 }],
[:DQPOST, '', {:line => 1, :pos=>12, :length=>1 }]],
}.each do |source, expected|
it "should lex an interpolated variable 'x' from #{source}" do
expect(tokens_scanned_from(source)).to match_tokens2(*expected)
end
end
{ '"$"' => '$',
'"a$"' => 'a$',
'"a$%b"' => "a$%b",
'"a$$"' => "a$$",
'"a$$%"' => "a$$%",
}.each do |source, expected|
it "should lex interpolation including false starts #{source}" do
expect(tokens_scanned_from(source)).to match_tokens2([:STRING, expected])
end
end
it "differentiates between foo[x] and foo [x] (whitespace)" do
expect(tokens_scanned_from("$a[1]")).to match_tokens2(:VARIABLE, :LBRACK, :NUMBER, :RBRACK)
expect(tokens_scanned_from("$a [1]")).to match_tokens2(:VARIABLE, :LISTSTART, :NUMBER, :RBRACK)
expect(tokens_scanned_from("a[1]")).to match_tokens2(:NAME, :LBRACK, :NUMBER, :RBRACK)
expect(tokens_scanned_from("a [1]")).to match_tokens2(:NAME, :LISTSTART, :NUMBER, :RBRACK)
end
it "differentiates between '(' first on line, and not first on line" do
expect(tokens_scanned_from("(")).to match_tokens2(:WSLPAREN)
expect(tokens_scanned_from("\n(")).to match_tokens2(:WSLPAREN)
expect(tokens_scanned_from("\n\r(")).to match_tokens2(:WSLPAREN)
expect(tokens_scanned_from("\n\t(")).to match_tokens2(:WSLPAREN)
expect(tokens_scanned_from("\n\r\t(")).to match_tokens2(:WSLPAREN)
expect(tokens_scanned_from("\n\u00a0(")).to match_tokens2(:WSLPAREN)
expect(tokens_scanned_from("x(")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("\nx(")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("\n\rx(")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("\n\tx(")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("\n\r\tx(")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("\n\u00a0x(")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("x (")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("x\t(")).to match_tokens2(:NAME, :LPAREN)
expect(tokens_scanned_from("x\u00a0(")).to match_tokens2(:NAME, :LPAREN)
end
it "skips whitepsace" do
expect(tokens_scanned_from(" if if if ")).to match_tokens2(:IF, :IF, :IF)
expect(tokens_scanned_from(" if \n\r\t\nif if ")).to match_tokens2(:IF, :IF, :IF)
expect(tokens_scanned_from(" if \n\r\t\n\u00a0if\u00a0 if ")).to match_tokens2(:IF, :IF, :IF)
end
it "skips single line comments" do
expect(tokens_scanned_from("if # comment\nif")).to match_tokens2(:IF, :IF)
end
["if /* comment */\nif",
"if /* comment\n */\nif",
"if /*\n comment\n */\nif",
].each do |source|
it "skips multi line comments" do
expect(tokens_scanned_from(source)).to match_tokens2(:IF, :IF)
end
end
it 'detects unterminated multiline comment' do
expect { tokens_scanned_from("/* not terminated\nmultiline\ncomment") }.to raise_error(Puppet::ParseErrorWithIssue) { |e|
expect(e.issue_code).to be(Puppet::Pops::Issues::UNCLOSED_MLCOMMENT.issue_code)
}
end
{ "=~" => [:MATCH, "=~ /./"],
"!~" => [:NOMATCH, "!~ /./"],
"," => [:COMMA, ", /./"],
"(" => [:WSLPAREN, "( /./"],
"x (" => [[:NAME, :LPAREN], "x ( /./"],
"x\\t (" => [[:NAME, :LPAREN], "x\t ( /./"],
"[ (liststart)" => [:LISTSTART, "[ /./"],
"[ (LBRACK)" => [[:NAME, :LBRACK], "a[ /./"],
"[ (liststart after name)" => [[:NAME, :LISTSTART], "a [ /./"],
"{" => [:LBRACE, "{ /./"],
"+" => [:PLUS, "+ /./"],
"-" => [:MINUS, "- /./"],
"*" => [:TIMES, "* /./"],
";" => [:SEMIC, "; /./"],
}.each do |token, entry|
it "should lex regexp after '#{token}'" do
expected = [entry[0], :REGEX].flatten
expect(tokens_scanned_from(entry[1])).to match_tokens2(*expected)
end
end
it "should lex a simple expression" do
expect(tokens_scanned_from('1 + 1')).to match_tokens2([:NUMBER, '1'], :PLUS, [:NUMBER, '1'])
end
{ "1" => ["1 /./", [:NUMBER, :DIV, :DOT, :DIV]],
"'a'" => ["'a' /./", [:STRING, :DIV, :DOT, :DIV]],
"true" => ["true /./", [:BOOLEAN, :DIV, :DOT, :DIV]],
"false" => ["false /./", [:BOOLEAN, :DIV, :DOT, :DIV]],
"/./" => ["/./ /./", [:REGEX, :DIV, :DOT, :DIV]],
"a" => ["a /./", [:NAME, :DIV, :DOT, :DIV]],
"A" => ["A /./", [:CLASSREF, :DIV, :DOT, :DIV]],
")" => [") /./", [:RPAREN, :DIV, :DOT, :DIV]],
"]" => ["] /./", [:RBRACK, :DIV, :DOT, :DIV]],
"|>" => ["|> /./", [:RCOLLECT, :DIV, :DOT, :DIV]],
"|>>" => ["|>> /./", [:RRCOLLECT, :DIV, :DOT, :DIV]],
"$x" => ["$x /1/", [:VARIABLE, :DIV, :NUMBER, :DIV]],
"a-b" => ["a-b /1/", [:WORD, :DIV, :NUMBER, :DIV]],
'"a$a"' => ['"a$a" /./', [:DQPRE, :VARIABLE, :DQPOST, :DIV, :DOT, :DIV]],
}.each do |token, entry|
it "should not lex regexp after '#{token}'" do
expect(tokens_scanned_from(entry[ 0 ])).to match_tokens2(*entry[ 1 ])
end
end
it 'should lex assignment' do
expect(tokens_scanned_from("$a = 10")).to match_tokens2([:VARIABLE, "a"], :EQUALS, [:NUMBER, '10'])
end
# TODO: Tricky, and heredoc not supported yet
# it "should not lex regexp after heredoc" do
# tokens_scanned_from("1 / /./").should match_tokens2(:NUMBER, :DIV, :REGEX)
# end
it "should lex regexp at beginning of input" do
expect(tokens_scanned_from(" /./")).to match_tokens2(:REGEX)
end
it "should lex regexp right of div" do
expect(tokens_scanned_from("1 / /./")).to match_tokens2(:NUMBER, :DIV, :REGEX)
end
it 'should lex regexp with escaped slash' do
scanned = tokens_scanned_from('/\//')
expect(scanned).to match_tokens2(:REGEX)
expect(scanned[0][1][:value]).to eql(Regexp.new('/'))
end
it 'should lex regexp with escaped backslash' do
scanned = tokens_scanned_from('/\\\\/')
expect(scanned).to match_tokens2(:REGEX)
expect(scanned[0][1][:value]).to eql(Regexp.new('\\\\'))
end
it 'should lex regexp with escaped backslash followed escaped slash ' do
scanned = tokens_scanned_from('/\\\\\\//')
expect(scanned).to match_tokens2(:REGEX)
expect(scanned[0][1][:value]).to eql(Regexp.new('\\\\/'))
end
it 'should lex regexp with escaped slash followed escaped backslash ' do
scanned = tokens_scanned_from('/\\/\\\\/')
expect(scanned).to match_tokens2(:REGEX)
expect(scanned[0][1][:value]).to eql(Regexp.new('/\\\\'))
end
it 'should not lex regexp with escaped ending slash' do
expect(tokens_scanned_from('/\\/')).to match_tokens2(:DIV, :OTHER, :DIV)
end
it "should accept newline in a regular expression" do
scanned = tokens_scanned_from("/\n.\n/")
# Note that strange formatting here is important
expect(scanned[0][1][:value]).to eql(/
.
/)
end
context 'when lexer lexes heredoc' do
it 'lexes tag, syntax and escapes, margin and right trim' do
code = <<-CODE
@(END:syntax/t)
Tex\\tt\\n
|- END
CODE
expect(tokens_scanned_from(code)).to match_tokens2([:HEREDOC, 'syntax'], :SUBLOCATE, [:STRING, "Tex\tt\\n"])
end
it 'lexes "tag", syntax and escapes, margin, right trim and interpolation' do
code = <<-CODE
@("END":syntax/t)
Tex\\tt\\n$var After
|- END
CODE
expect(tokens_scanned_from(code)).to match_tokens2(
[:HEREDOC, 'syntax'],
:SUBLOCATE,
[:DQPRE, "Tex\tt\\n"],
[:VARIABLE, "var"],
[:DQPOST, " After"]
)
end
it 'strips only last newline when using trim option' do
code = <<-CODE.unindent
@(END)
Line 1
Line 2
-END
CODE
expect(tokens_scanned_from(code)).to match_tokens2(
[:HEREDOC, ''],
[:SUBLOCATE, ["Line 1\n", "\n", "Line 2\n"]],
[:STRING, "Line 1\n\nLine 2"],
)
end
it 'strips only one newline at the end when using trim option' do
code = <<-CODE.unindent
@(END)
Line 1
Line 2
-END
CODE
expect(tokens_scanned_from(code)).to match_tokens2(
[:HEREDOC, ''],
[:SUBLOCATE, ["Line 1\n", "Line 2\n", "\n"]],
[:STRING, "Line 1\nLine 2\n"],
)
end
context 'with bad syntax' do
def expect_issue(code, issue)
expect { tokens_scanned_from(code) }.to raise_error(Puppet::ParseErrorWithIssue) { |e|
expect(e.issue_code).to be(issue.issue_code)
}
end
it 'detects and reports HEREDOC_UNCLOSED_PARENTHESIS' do
code = <<-CODE
@(END:syntax/t
Text
|- END
CODE
expect_issue(code, Puppet::Pops::Issues::HEREDOC_UNCLOSED_PARENTHESIS)
end
it 'detects and reports HEREDOC_WITHOUT_END_TAGGED_LINE' do
code = <<-CODE
@(END:syntax/t)
Text
CODE
expect_issue(code, Puppet::Pops::Issues::HEREDOC_WITHOUT_END_TAGGED_LINE)
end
it 'detects and reports HEREDOC_INVALID_ESCAPE' do
code = <<-CODE
@(END:syntax/x)
Text
|- END
CODE
expect_issue(code, Puppet::Pops::Issues::HEREDOC_INVALID_ESCAPE)
end
it 'detects and reports HEREDOC_INVALID_SYNTAX' do
code = <<-CODE
@(END:syntax/t/p)
Text
|- END
CODE
expect_issue(code, Puppet::Pops::Issues::HEREDOC_INVALID_SYNTAX)
end
it 'detects and reports HEREDOC_WITHOUT_TEXT' do
code = '@(END:syntax/t)'
expect_issue(code, Puppet::Pops::Issues::HEREDOC_WITHOUT_TEXT)
end
it 'detects and reports HEREDOC_EMPTY_ENDTAG' do
code = <<-CODE
@("")
Text
|-END
CODE
expect_issue(code, Puppet::Pops::Issues::HEREDOC_EMPTY_ENDTAG)
end
it 'detects and reports HEREDOC_MULTIPLE_AT_ESCAPES' do
code = <<-CODE
@(END:syntax/tst)
Tex\\tt\\n
|- END
CODE
expect_issue(code, Puppet::Pops::Issues::HEREDOC_MULTIPLE_AT_ESCAPES)
end
end
end
context 'when not given multi byte characters' do
it 'produces byte offsets for tokens' do
code = <<-"CODE"
1 2\n3
CODE
expect(tokens_scanned_from(code)).to match_tokens2(
[:NUMBER, '1', {:line => 1, :offset => 0, :length=>1}],
[:NUMBER, '2', {:line => 1, :offset => 2, :length=>1}],
[:NUMBER, '3', {:line => 2, :offset => 4, :length=>1}]
)
end
end
context 'when dealing with multi byte characters' do
it 'should support unicode characters' do
code = <<-CODE
"x\\u2713y"
CODE
expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\u2713y"])
end
it 'should support adjacent short form unicode characters' do
code = <<-CODE
"x\\u2713\\u2713y"
CODE
expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\u2713\u2713y"])
end
it 'should support unicode characters in long form' do
code = <<-CODE
"x\\u{1f452}y"
CODE
expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\u{1f452}y"])
end
it 'can escape the unicode escape' do
code = <<-"CODE"
"x\\\\u{1f452}y"
CODE
expect(tokens_scanned_from(code)).to match_tokens2([:STRING, "x\\u{1f452}y"])
end
it 'produces byte offsets that counts each byte in a comment' do
code = <<-"CODE"
# \u{0400}\na
CODE
expect(tokens_scanned_from(code.strip)).to match_tokens2([:NAME, 'a', {:line => 2, :offset => 5, :length=>1}])
end
it 'produces byte offsets that counts each byte in value token' do
code = <<-"CODE"
'\u{0400}'\na
CODE
expect(tokens_scanned_from(code.strip)).to match_tokens2(
[:STRING, "\u{400}", {:line => 1, :offset => 0, :length=>4}],
[:NAME, 'a', {:line => 2, :offset => 5, :length=>1}]
)
end
it 'should not select LISTSTART token when preceded by multibyte chars' do
# This test is sensitive to the number of multibyte characters and position of the expressions
# within the string - it is designed to fail if the position is calculated on the byte offset of the '['
# instead of the char offset.
#
code = "$a = '\u00f6\u00fc\u00fc\u00fc\u00fc\u00e4\u00e4\u00f6\u00e4'\nnotify {'x': message => B['dkda'] }\n"
expect(tokens_scanned_from(code)).to match_tokens2(
:VARIABLE, :EQUALS, :STRING,
[:NAME, 'notify'], :LBRACE,
[:STRING, 'x'], :COLON,
:NAME, :FARROW, :CLASSREF, :LBRACK, :STRING, :RBRACK,
:RBRACE)
end
end
context 'when lexing epp' do
it 'epp can contain just text' do
code = <<-CODE
This is just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(:EPP_START, [:RENDER_STRING, " This is just text\n"])
end
it 'epp can contain text with interpolated rendered expressions' do
code = <<-CODE
This is <%= $x %> just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, " This is "],
[:RENDER_EXPR, nil],
[:VARIABLE, "x"],
[:EPP_END, "%>"],
[:RENDER_STRING, " just text\n"]
)
end
it 'epp can contain text with trimmed interpolated rendered expressions' do
code = <<-CODE
This is <%= $x -%> just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, " This is "],
[:RENDER_EXPR, nil],
[:VARIABLE, "x"],
[:EPP_END_TRIM, "-%>"],
[:RENDER_STRING, "just text\n"]
)
end
it 'epp can contain text with expressions that are not rendered' do
code = <<-CODE
This is <% $x=10 %> just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, " This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, " just text\n"]
)
end
it 'epp can skip trailing space and newline in tail text' do
# note that trailing whitespace is significant on one of the lines
code = <<-CODE.unindent
This is <% $x=10 -%>
just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, "This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, "just text\n"]
)
end
it 'epp can skip comments' do
code = <<-CODE.unindent
This is <% $x=10 -%>
<%# This is an epp comment -%>
just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, "This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, "just text\n"]
)
end
it 'epp comments does not strip left whitespace when preceding is right trim' do
code = <<-CODE.unindent
This is <% $x=10 -%>
<%# This is an epp comment %>
just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, "This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, " \njust text\n"]
)
end
it 'epp comments does not strip left whitespace when preceding is not right trim' do
code = <<-CODE.unindent
This is <% $x=10 %>
<%# This is an epp comment -%>
just text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, "This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, "\n just text\n"]
)
end
it 'epp comments can trim left with <%#-' do
# test has 4 space before comment and 3 after it
# check that there is 3 spaces before the 'and'
#
code = <<-CODE.unindent
This is <% $x=10 -%>
no-space-after-me: <%#- This is an epp comment %> and
some text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, "This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, "no-space-after-me: and\nsome text\n"]
)
end
it 'puppet comment in left trimming epp tag works when containing a new line' do
# test has 4 space before comment and 3 after it
# check that there is 3 spaces before the 'and'
#
code = <<-CODE.unindent
This is <% $x=10 -%>
no-space-after-me: <%-# This is an puppet comment
%> and
some text
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, "This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, "no-space-after-me:"],
[:RENDER_STRING, " and\nsome text\n"]
)
end
it 'epp can escape epp tags' do
code = <<-CODE
This is <% $x=10 -%>
<%% this is escaped epp %%>
CODE
expect(epp_tokens_scanned_from(code)).to match_tokens2(
:EPP_START,
[:RENDER_STRING, " This is "],
[:VARIABLE, "x"],
:EQUALS,
[:NUMBER, "10"],
[:RENDER_STRING, " <% this is escaped epp %>\n"]
)
end
context 'with bad epp syntax' do
def expect_issue(code, issue)
expect { epp_tokens_scanned_from(code) }.to raise_error(Puppet::ParseErrorWithIssue) { |e|
expect(e.issue_code).to be(issue.issue_code)
}
end
it 'detects and reports EPP_UNBALANCED_TAG' do
expect_issue('<% asf', Puppet::Pops::Issues::EPP_UNBALANCED_TAG)
end
it 'detects and reports EPP_UNBALANCED_COMMENT' do
expect_issue('<%# asf', Puppet::Pops::Issues::EPP_UNBALANCED_COMMENT)
end
it 'detects and reports EPP_UNBALANCED_EXPRESSION' do
expect_issue('asf <%', Puppet::Pops::Issues::EPP_UNBALANCED_EXPRESSION)
end
end
end
context 'when parsing bad code' do
def expect_issue(code, issue)
expect { tokens_scanned_from(code) }.to raise_error(Puppet::ParseErrorWithIssue) do |e|
expect(e.issue_code).to be(issue.issue_code)
end
end
it 'detects and reports issue ILLEGAL_CLASS_REFERENCE' do
expect_issue('A::3', Puppet::Pops::Issues::ILLEGAL_CLASS_REFERENCE)
end
it 'detects and reports issue ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE' do
expect_issue('::A::3', Puppet::Pops::Issues::ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE)
end
it 'detects and reports issue ILLEGAL_FULLY_QUALIFIED_NAME' do
expect_issue('::a::3', Puppet::Pops::Issues::ILLEGAL_FULLY_QUALIFIED_NAME)
end
it 'detects and reports issue ILLEGAL_NUMBER' do
expect_issue('3g', Puppet::Pops::Issues::ILLEGAL_NUMBER)
end
it 'detects and reports issue INVALID_HEX_NUMBER' do
expect_issue('0x3g', Puppet::Pops::Issues::INVALID_HEX_NUMBER)
end
it 'detects and reports issue INVALID_OCTAL_NUMBER' do
expect_issue('038', Puppet::Pops::Issues::INVALID_OCTAL_NUMBER)
end
it 'detects and reports issue INVALID_DECIMAL_NUMBER' do
expect_issue('4.3g', Puppet::Pops::Issues::INVALID_DECIMAL_NUMBER)
end
it 'detects and reports issue NO_INPUT_TO_LEXER' do
expect { Puppet::Pops::Parser::Lexer2.new.fullscan }.to raise_error(Puppet::ParseErrorWithIssue) { |e|
expect(e.issue_code).to be(Puppet::Pops::Issues::NO_INPUT_TO_LEXER.issue_code)
}
end
it 'detects and reports issue UNCLOSED_QUOTE' do
expect_issue('"asd', Puppet::Pops::Issues::UNCLOSED_QUOTE)
end
end
context 'when dealing with non UTF-8 and Byte Order Marks (BOMs)' do
{
'UTF_8' => [0xEF, 0xBB, 0xBF],
'UTF_16_1' => [0xFE, 0xFF],
'UTF_16_2' => [0xFF, 0xFE],
'UTF_32_1' => [0x00, 0x00, 0xFE, 0xFF],
'UTF_32_2' => [0xFF, 0xFE, 0x00, 0x00],
'UTF_1' => [0xF7, 0x64, 0x4C],
'UTF_EBCDIC' => [0xDD, 0x73, 0x66, 0x73],
'SCSU' => [0x0E, 0xFE, 0xFF],
'BOCU' => [0xFB, 0xEE, 0x28],
'GB_18030' => [0x84, 0x31, 0x95, 0x33]
}.each do |key, bytes|
it "errors on the byte order mark for #{key} '[#{bytes.map() {|b| '%X' % b}.join(' ')}]'" do
format_name = key.split('_')[0,2].join('-')
bytes_str = "\\[#{bytes.map {|b| '%X' % b}.join(' ')}\\]"
fix = " - remove these from the puppet source"
expect {
tokens_scanned_from(bytes.pack('C*'))
}.to raise_error(Puppet::ParseErrorWithIssue,
/Illegal #{format_name} .* at beginning of input: #{bytes_str}#{fix}/)
end
it "can use a possibly 'broken' UTF-16 string without problems for #{key}" do
format_name = key.split('_')[0,2].join('-')
string = bytes.pack('C*').force_encoding('UTF-16')
bytes_str = "\\[#{string.bytes.map {|b| '%X' % b}.join(' ')}\\]"
fix = " - remove these from the puppet source"
expect {
tokens_scanned_from(string)
}.to raise_error(Puppet::ParseErrorWithIssue,
/Illegal #{format_name} .* at beginning of input: #{bytes_str}#{fix}/)
end
end
end
end
describe Puppet::Pops::Parser::Lexer2 do
include PuppetSpec::Files
# First line of Rune version of Rune poem at http://www.columbia.edu/~fdc/utf8/
# characters chosen since they will not parse on Windows with codepage 437 or 1252
# Section 3.2.1.3 of Ruby spec guarantees that \u strings are encoded as UTF-8
# Runes (may show up as garbage if font is not available): ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ
let (:rune_utf8) {
"\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2" +
"\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA" +
"\u16B3\u16A2\u16D7"
}
context 'when lexing files from disk' do
it 'should always read files as UTF-8' do
manifest_code = "notify { '#{rune_utf8}': }"
manifest = file_containing('manifest.pp', manifest_code)
lexed_file = described_class.new.lex_file(manifest)
expect(lexed_file.string.encoding).to eq(Encoding::UTF_8)
expect(lexed_file.string).to eq(manifest_code)
end
it 'currently errors when the UTF-8 BOM (Byte Order Mark) is present when lexing files' do
bom = "\uFEFF"
manifest_code = "#{bom}notify { '#{rune_utf8}': }"
manifest = file_containing('manifest.pp', manifest_code)
expect {
described_class.new.lex_file(manifest)
}.to raise_error(Puppet::ParseErrorWithIssue,
'Illegal UTF-8 Byte Order mark at beginning of input: [EF BB BF] - remove these from the puppet source')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_plan_spec.rb | spec/unit/pops/parser/parse_plan_spec.rb | require 'spec_helper'
require 'puppet/pops'
require_relative 'parser_rspec_helper'
describe "egrammar parsing of 'plan'" do
include ParserRspecHelper
context 'with --tasks' do
before(:each) do
Puppet[:tasks] = true
end
it "an empty body" do
expect(dump(parse("plan foo { }"))).to eq("(plan foo ())")
end
it "a non empty body" do
prog = <<-EPROG
plan foo {
$a = 10
$b = 20
}
EPROG
expect(dump(parse(prog))).to eq( [
"(plan foo (block",
" (= $a 10)",
" (= $b 20)",
"))",
].join("\n"))
end
it "accepts parameters" do
s = "plan foo($p1 = 'yo', $p2) { }"
expect(dump(parse(s))).to eq("(plan foo (parameters (= p1 'yo') p2) ())")
end
end
context 'with --no-tasks' do
before(:each) do
Puppet[:tasks] = false
end
it "the keyword 'plan' is a name" do
expect(dump(parse("$a = plan"))).to eq("(= $a plan)")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_calls_spec.rb | spec/unit/pops/parser/parse_calls_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing function calls" do
include ParserRspecHelper
context "When parsing calls as statements" do
context "in top level scope" do
it "foo()" do
expect(dump(parse("foo()"))).to eq("(invoke foo)")
end
it "notice bar" do
expect(dump(parse("notice bar"))).to eq("(invoke notice bar)")
end
it "notice(bar)" do
expect(dump(parse("notice bar"))).to eq("(invoke notice bar)")
end
it "foo(bar)" do
expect(dump(parse("foo(bar)"))).to eq("(invoke foo bar)")
end
it "notice {a=>2}" do
expect(dump(parse("notice {a => 2}"))).to eq("(invoke notice ({} ('a' 2)))")
end
it 'notice a=>2' do
expect{parse('notice a => 2')}.to raise_error(/Syntax error at '=>'/)
end
it "foo(bar,)" do
expect(dump(parse("foo(bar,)"))).to eq("(invoke foo bar)")
end
it "foo(bar, fum,)" do
expect(dump(parse("foo(bar,fum,)"))).to eq("(invoke foo bar fum)")
end
it 'foo(a=>1)' do
expect(dump(parse('foo(a=>1)'))).to eq('(invoke foo ({} (a 1)))')
end
it 'foo(a=>1, b=>2)' do
expect(dump(parse('foo(a=>1, b=>2)'))).to eq('(invoke foo ({} (a 1) (b 2)))')
end
it 'foo({a=>1, b=>2})' do
expect(dump(parse('foo({a=>1, b=>2})'))).to eq('(invoke foo ({} (a 1) (b 2)))')
end
it 'foo({a=>1}, b=>2)' do
expect(dump(parse('foo({a=>1}, b=>2)'))).to eq('(invoke foo ({} (a 1)) ({} (b 2)))')
end
it 'foo(a=>1, {b=>2})' do
expect(dump(parse('foo(a=>1, {b=>2})'))).to eq('(invoke foo ({} (a 1)) ({} (b 2)))')
end
it "notice fqdn_rand(30)" do
expect(dump(parse("notice fqdn_rand(30)"))).to eq('(invoke notice (call fqdn_rand 30))')
end
it "notice type(42)" do
expect(dump(parse("notice type(42)"))).to eq('(invoke notice (call type 42))')
end
it "is required to place the '(' on the same line as the name of the function to recognize it as arguments in call" do
expect(dump(parse("notice foo\n(42)"))).to eq("(block\n (invoke notice foo)\n 42\n)")
end
end
context "in nested scopes" do
it "if true { foo() }" do
expect(dump(parse("if true {foo()}"))).to eq("(if true\n (then (invoke foo)))")
end
it "if true { notice bar}" do
expect(dump(parse("if true {notice bar}"))).to eq("(if true\n (then (invoke notice bar)))")
end
end
end
context "When parsing calls as expressions" do
it "$a = foo()" do
expect(dump(parse("$a = foo()"))).to eq("(= $a (call foo))")
end
it "$a = foo(bar)" do
expect(dump(parse("$a = foo()"))).to eq("(= $a (call foo))")
end
# For egrammar where a bare word can be a "statement"
it "$a = foo bar # illegal, must have parentheses" do
expect(dump(parse("$a = foo bar"))).to eq("(block\n (= $a foo)\n bar\n)")
end
context "in nested scopes" do
it "if true { $a = foo() }" do
expect(dump(parse("if true { $a = foo()}"))).to eq("(if true\n (then (= $a (call foo))))")
end
it "if true { $a= foo(bar)}" do
expect(dump(parse("if true {$a = foo(bar)}"))).to eq("(if true\n (then (= $a (call foo bar))))")
end
end
end
context "When parsing method calls" do
it "$a.foo" do
expect(dump(parse("$a.foo"))).to eq("(call-method (. $a foo))")
end
it "$a.foo || { }" do
expect(dump(parse("$a.foo || { }"))).to eq("(call-method (. $a foo) (lambda ()))")
end
it "$a.foo |$x| { }" do
expect(dump(parse("$a.foo |$x|{ }"))).to eq("(call-method (. $a foo) (lambda (parameters x) ()))")
end
it "$a.foo |$x|{ }" do
expect(dump(parse("$a.foo |$x|{ $b = $x}"))).to eq([
"(call-method (. $a foo) (lambda (parameters x) (block",
" (= $b $x)",
")))"
].join("\n"))
end
it "notice 42.type()" do
expect(dump(parse("notice 42.type()"))).to eq('(invoke notice (call-method (. 42 type)))')
end
it 'notice Hash.assert_type(a => 42)' do
expect(dump(parse('notice Hash.assert_type(a => 42)'))).to eq('(invoke notice (call-method (. Hash assert_type) ({} (a 42))))')
end
it "notice 42.type(detailed)" do
expect(dump(parse("notice 42.type(detailed)"))).to eq('(invoke notice (call-method (. 42 type) detailed))')
end
it "is required to place the '(' on the same line as the name of the method to recognize it as arguments in call" do
expect(dump(parse("notice 42.type\n(detailed)"))).to eq("(block\n (invoke notice (call-method (. 42 type)))\n detailed\n)")
end
end
context "When parsing an illegal argument list" do
it "raises an error if argument list is not for a call" do
expect do
parse("$a = 10, 3")
end.to raise_error(/illegal comma/)
end
it "raises an error if argument list is for a potential call not allowed without parentheses" do
expect do
parse("foo 10, 3")
end.to raise_error(/attempt to pass argument list to the function 'foo' which cannot be called without parentheses/)
end
it "does no raise an error for an argument list to an allowed call" do
expect do
parse("notice 10, 3")
end.to_not raise_error()
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/evaluating_parser_spec.rb | spec/unit/pops/parser/evaluating_parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
describe 'The Evaluating Parser' do
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:acceptor) { Puppet::Pops::Validation::Acceptor.new() }
let(:scope) { s = create_test_scope_for_node(node); s }
let(:node) { 'node.example.com' }
def quote(x)
Puppet::Pops::Parser::EvaluatingParser.quote(x)
end
def evaluator()
Puppet::Pops::Parser::EvaluatingParser.new()
end
def evaluate(s)
evaluator.evaluate(scope, quote(s))
end
def test(x)
expect(evaluator.evaluate_string(scope, quote(x))).to eq(x)
end
def test_interpolate(x, y)
scope['a'] = 'expansion'
expect(evaluator.evaluate_string(scope, quote(x))).to eq(y)
end
context 'when evaluating' do
it 'should produce an empty string with no change' do
test('')
end
it 'should produce a normal string with no change' do
test('A normal string')
end
it 'should produce a string with newlines with no change' do
test("A\nnormal\nstring")
end
it 'should produce a string with escaped newlines with no change' do
test("A\\nnormal\\nstring")
end
it 'should produce a string containing quotes without change' do
test('This " should remain untouched')
end
it 'should produce a string containing escaped quotes without change' do
test('This \" should remain untouched')
end
it 'should expand ${a} variables' do
test_interpolate('This ${a} was expanded', 'This expansion was expanded')
end
it 'should expand quoted ${a} variables' do
test_interpolate('This "${a}" was expanded', 'This "expansion" was expanded')
end
it 'should not expand escaped ${a}' do
test_interpolate('This \${a} was not expanded', 'This ${a} was not expanded')
end
it 'should expand $a variables' do
test_interpolate('This $a was expanded', 'This expansion was expanded')
end
it 'should expand quoted $a variables' do
test_interpolate('This "$a" was expanded', 'This "expansion" was expanded')
end
it 'should not expand escaped $a' do
test_interpolate('This \$a was not expanded', 'This $a was not expanded')
end
it 'should produce an single space from a \s' do
test_interpolate("\\s", ' ')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_containers_spec.rb | spec/unit/pops/parser/parse_containers_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing containers" do
include ParserRspecHelper
context "When parsing file scope" do
it "$a = 10 $b = 20" do
expect(dump(parse("$a = 10 $b = 20"))).to eq([
"(block",
" (= $a 10)",
" (= $b 20)",
")"
].join("\n"))
end
it "$a = 10" do
expect(dump(parse("$a = 10"))).to eq("(= $a 10)")
end
end
context "When parsing class" do
it "class foo {}" do
expect(dump(parse("class foo {}"))).to eq("(class foo ())")
end
it "class foo { class bar {} }" do
expect(dump(parse("class foo { class bar {}}"))).to eq([
"(class foo (block",
" (class foo::bar ())",
"))"
].join("\n"))
end
it "class foo::bar {}" do
expect(dump(parse("class foo::bar {}"))).to eq("(class foo::bar ())")
end
it "class foo inherits bar {}" do
expect(dump(parse("class foo inherits bar {}"))).to eq("(class foo (inherits bar) ())")
end
it "class foo($a) {}" do
expect(dump(parse("class foo($a) {}"))).to eq("(class foo (parameters a) ())")
end
it "class foo($a, $b) {}" do
expect(dump(parse("class foo($a, $b) {}"))).to eq("(class foo (parameters a b) ())")
end
it "class foo($a, $b=10) {}" do
expect(dump(parse("class foo($a, $b=10) {}"))).to eq("(class foo (parameters a (= b 10)) ())")
end
it "class foo($a, $b) inherits belgo::bar {}" do
expect(dump(parse("class foo($a, $b) inherits belgo::bar{}"))).to eq("(class foo (inherits belgo::bar) (parameters a b) ())")
end
it "class foo {$a = 10 $b = 20}" do
expect(dump(parse("class foo {$a = 10 $b = 20}"))).to eq([
"(class foo (block",
" (= $a 10)",
" (= $b 20)",
"))"
].join("\n"))
end
context "it should handle '3x weirdness'" do
it "class class {} # a class named 'class'" do
# Not as much weird as confusing that it is possible to name a class 'class'. Can have
# a very confusing effect when resolving relative names, getting the global hardwired "Class"
# instead of some foo::class etc.
# This was allowed in 3.x.
expect { parse("class class {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
it "class default {} # a class named 'default'" do
# The weirdness here is that a class can inherit 'default' but not declare a class called default.
# (It will work with relative names i.e. foo::default though). The whole idea with keywords as
# names is flawed to begin with - it generally just a very bad idea.
expect { parse("class default {}") }.to raise_error(Puppet::ParseError)
end
it "class 'foo' {} # a string as class name" do
# A common error is to put quotes around the class name, the parser should provide the error message at the right location
# See PUP-7471
expect { parse("class 'foo' {}") }.to raise_error(/A quoted string is not valid as a name here \(line: 1, column: 7\)/)
end
it "class foo::default {} # a nested name 'default'" do
expect(dump(parse("class foo::default {}"))).to eq("(class foo::default ())")
end
it "class class inherits default {} # inherits default" do
expect { parse("class class inherits default {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
it "class foo inherits class" do
expect { parse("class foo inherits class {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
end
context 'it should allow keywords as attribute names' do
['and', 'case', 'class', 'default', 'define', 'else', 'elsif', 'if', 'in', 'inherits', 'node', 'or',
'undef', 'unless', 'type', 'attr', 'function', 'private', 'plan', 'apply'].each do |keyword|
it "such as #{keyword}" do
expect { parse("class x ($#{keyword}){} class { x: #{keyword} => 1 }") }.to_not raise_error
end
end
end
end
context "When the parser parses define" do
it "define foo {}" do
expect(dump(parse("define foo {}"))).to eq("(define foo ())")
end
it "class foo { define bar {}}" do
expect(dump(parse("class foo {define bar {}}"))).to eq([
"(class foo (block",
" (define foo::bar ())",
"))"
].join("\n"))
end
it "define foo { define bar {}}" do
# This is illegal, but handled as part of validation
expect(dump(parse("define foo { define bar {}}"))).to eq([
"(define foo (block",
" (define bar ())",
"))"
].join("\n"))
end
it "define foo::bar {}" do
expect(dump(parse("define foo::bar {}"))).to eq("(define foo::bar ())")
end
it "define foo($a) {}" do
expect(dump(parse("define foo($a) {}"))).to eq("(define foo (parameters a) ())")
end
it "define foo($a, $b) {}" do
expect(dump(parse("define foo($a, $b) {}"))).to eq("(define foo (parameters a b) ())")
end
it "define foo($a, $b=10) {}" do
expect(dump(parse("define foo($a, $b=10) {}"))).to eq("(define foo (parameters a (= b 10)) ())")
end
it "define foo {$a = 10 $b = 20}" do
expect(dump(parse("define foo {$a = 10 $b = 20}"))).to eq([
"(define foo (block",
" (= $a 10)",
" (= $b 20)",
"))"
].join("\n"))
end
context "it should handle '3x weirdness'" do
it "define class {} # a define named 'class'" do
# This is weird because Class already exists, and instantiating this define will probably not
# work
expect { parse("define class {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
it "define default {} # a define named 'default'" do
# Check unwanted ability to define 'default'.
# The expression below is not allowed (which is good).
expect { parse("define default {}") }.to raise_error(Puppet::ParseError)
end
end
context 'it should allow keywords as attribute names' do
['and', 'case', 'class', 'default', 'define', 'else', 'elsif', 'if', 'in', 'inherits', 'node', 'or',
'undef', 'unless', 'type', 'attr', 'function', 'private', 'plan', 'apply'].each do |keyword|
it "such as #{keyword}" do
expect {parse("define x ($#{keyword}){} x { y: #{keyword} => 1 }")}.to_not raise_error
end
end
end
end
context "When parsing node" do
it "node foo {}" do
expect(dump(parse("node foo {}"))).to eq("(node (matches 'foo') ())")
end
it "node foo, {} # trailing comma" do
expect(dump(parse("node foo, {}"))).to eq("(node (matches 'foo') ())")
end
it "node kermit.example.com {}" do
expect(dump(parse("node kermit.example.com {}"))).to eq("(node (matches 'kermit.example.com') ())")
end
it "node kermit . example . com {}" do
expect(dump(parse("node kermit . example . com {}"))).to eq("(node (matches 'kermit.example.com') ())")
end
it "node foo, x::bar, default {}" do
expect(dump(parse("node foo, x::bar, default {}"))).to eq("(node (matches 'foo' 'x::bar' :default) ())")
end
it "node 'foo' {}" do
expect(dump(parse("node 'foo' {}"))).to eq("(node (matches 'foo') ())")
end
it "node foo inherits x::bar {}" do
expect(dump(parse("node foo inherits x::bar {}"))).to eq("(node (matches 'foo') (parent 'x::bar') ())")
end
it "node foo inherits 'bar' {}" do
expect(dump(parse("node foo inherits 'bar' {}"))).to eq("(node (matches 'foo') (parent 'bar') ())")
end
it "node foo inherits default {}" do
expect(dump(parse("node foo inherits default {}"))).to eq("(node (matches 'foo') (parent :default) ())")
end
it "node /web.*/ {}" do
expect(dump(parse("node /web.*/ {}"))).to eq("(node (matches /web.*/) ())")
end
it "node /web.*/, /do\.wop.*/, and.so.on {}" do
expect(dump(parse("node /web.*/, /do\.wop.*/, 'and.so.on' {}"))).to eq("(node (matches /web.*/ /do\.wop.*/ 'and.so.on') ())")
end
it "node wat inherits /apache.*/ {}" do
expect(dump(parse("node wat inherits /apache.*/ {}"))).to eq("(node (matches 'wat') (parent /apache.*/) ())")
end
it "node foo inherits bar {$a = 10 $b = 20}" do
expect(dump(parse("node foo inherits bar {$a = 10 $b = 20}"))).to eq([
"(node (matches 'foo') (parent 'bar') (block",
" (= $a 10)",
" (= $b 20)",
"))"
].join("\n"))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_lambda_spec.rb | spec/unit/pops/parser/parse_lambda_spec.rb | require 'spec_helper'
require 'puppet/pops'
require_relative 'parser_rspec_helper'
describe 'egrammar parsing lambda definitions' do
include ParserRspecHelper
context 'without return type' do
it 'f() |$x| { 1 }' do
expect(dump(parse('f() |$x| { 1 }'))).to eq("(invoke f (lambda (parameters x) (block\n 1\n)))")
end
end
context 'with return type' do
it 'f() |$x| >> Integer { 1 }' do
expect(dump(parse('f() |$x| >> Integer { 1 }'))).to eq("(invoke f (lambda (parameters x) (return_type Integer) (block\n 1\n)))")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_conditionals_spec.rb | spec/unit/pops/parser/parse_conditionals_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing conditionals" do
include ParserRspecHelper
context "When parsing if statements" do
it "if true { $a = 10 }" do
expect(dump(parse("if true { $a = 10 }"))).to eq("(if true\n (then (= $a 10)))")
end
it "if true { $a = 10 } else {$a = 20}" do
expect(dump(parse("if true { $a = 10 } else {$a = 20}"))).to eq(
["(if true",
" (then (= $a 10))",
" (else (= $a 20)))"].join("\n")
)
end
it "if true { $a = 10 } elsif false { $a = 15} else {$a = 20}" do
expect(dump(parse("if true { $a = 10 } elsif false { $a = 15} else {$a = 20}"))).to eq(
["(if true",
" (then (= $a 10))",
" (else (if false",
" (then (= $a 15))",
" (else (= $a 20)))))"].join("\n")
)
end
it "if true { $a = 10 $b = 10 } else {$a = 20}" do
expect(dump(parse("if true { $a = 10 $b = 20} else {$a = 20}"))).to eq([
"(if true",
" (then (block",
" (= $a 10)",
" (= $b 20)",
" ))",
" (else (= $a 20)))"
].join("\n"))
end
it "allows a parenthesized conditional expression" do
expect(dump(parse("if (true) { 10 }"))).to eq("(if true\n (then 10))")
end
it "allows a parenthesized elsif conditional expression" do
expect(dump(parse("if true { 10 } elsif (false) { 20 }"))).to eq(
["(if true",
" (then 10)",
" (else (if false",
" (then 20))))"].join("\n")
)
end
end
context "When parsing unless statements" do
it "unless true { $a = 10 }" do
expect(dump(parse("unless true { $a = 10 }"))).to eq("(unless true\n (then (= $a 10)))")
end
it "unless true { $a = 10 } else {$a = 20}" do
expect(dump(parse("unless true { $a = 10 } else {$a = 20}"))).to eq(
["(unless true",
" (then (= $a 10))",
" (else (= $a 20)))"].join("\n")
)
end
it "allows a parenthesized conditional expression" do
expect(dump(parse("unless (true) { 10 }"))).to eq("(unless true\n (then 10))")
end
it "unless true { $a = 10 } elsif false { $a = 15} else {$a = 20} # is illegal" do
expect { parse("unless true { $a = 10 } elsif false { $a = 15} else {$a = 20}")}.to raise_error(Puppet::ParseError)
end
end
context "When parsing selector expressions" do
it "$a = $b ? banana => fruit " do
expect(dump(parse("$a = $b ? banana => fruit"))).to eq(
"(= $a (? $b (banana => fruit)))"
)
end
it "$a = $b ? { banana => fruit}" do
expect(dump(parse("$a = $b ? { banana => fruit }"))).to eq(
"(= $a (? $b (banana => fruit)))"
)
end
it "does not fail on a trailing blank line" do
expect(dump(parse("$a = $b ? { banana => fruit }\n\n"))).to eq(
"(= $a (? $b (banana => fruit)))"
)
end
it "$a = $b ? { banana => fruit, grape => berry }" do
expect(dump(parse("$a = $b ? {banana => fruit, grape => berry}"))).to eq(
"(= $a (? $b (banana => fruit) (grape => berry)))"
)
end
it "$a = $b ? { banana => fruit, grape => berry, default => wat }" do
expect(dump(parse("$a = $b ? {banana => fruit, grape => berry, default => wat}"))).to eq(
"(= $a (? $b (banana => fruit) (grape => berry) (:default => wat)))"
)
end
it "$a = $b ? { default => wat, banana => fruit, grape => berry, }" do
expect(dump(parse("$a = $b ? {default => wat, banana => fruit, grape => berry}"))).to eq(
"(= $a (? $b (:default => wat) (banana => fruit) (grape => berry)))"
)
end
it '1+2 ? 3 => yes' do
expect(dump(parse("1+2 ? 3 => yes"))).to eq(
"(? (+ 1 2) (3 => yes))"
)
end
it 'true and 1+2 ? 3 => yes' do
expect(dump(parse("true and 1+2 ? 3 => yes"))).to eq(
"(&& true (? (+ 1 2) (3 => yes)))"
)
end
end
context "When parsing case statements" do
it "case $a { a : {}}" do
expect(dump(parse("case $a { a : {}}"))).to eq(
["(case $a",
" (when (a) (then ())))"
].join("\n")
)
end
it "allows a parenthesized value expression" do
expect(dump(parse("case ($a) { a : {}}"))).to eq(
["(case $a",
" (when (a) (then ())))"
].join("\n")
)
end
it "case $a { /.*/ : {}}" do
expect(dump(parse("case $a { /.*/ : {}}"))).to eq(
["(case $a",
" (when (/.*/) (then ())))"
].join("\n")
)
end
it "case $a { a, b : {}}" do
expect(dump(parse("case $a { a, b : {}}"))).to eq(
["(case $a",
" (when (a b) (then ())))"
].join("\n")
)
end
it "case $a { a, b : {} default : {}}" do
expect(dump(parse("case $a { a, b : {} default : {}}"))).to eq(
["(case $a",
" (when (a b) (then ()))",
" (when (:default) (then ())))"
].join("\n")
)
end
it "case $a { a : {$b = 10 $c = 20}}" do
expect(dump(parse("case $a { a : {$b = 10 $c = 20}}"))).to eq(
["(case $a",
" (when (a) (then (block",
" (= $b 10)",
" (= $c 20)",
" ))))"
].join("\n")
)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parsing_typed_parameters_spec.rb | spec/unit/pops/parser/parsing_typed_parameters_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
require 'puppet/parser/e4_parser_adapter'
# relative to this spec file (./) does not work as this file is loaded by rspec
#require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
context "captures-rest parameter" do
it 'is allowed in lambda when placed last' do
source = <<-CODE
foo() |$a, *$b| { $a + $b[0] }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to_not raise_error()
end
it 'allows a type annotation' do
source = <<-CODE
foo() |$a, Integer *$b| { $a + $b[0] }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to_not raise_error()
end
it 'is not allowed in lambda except last' do
source = <<-CODE
foo() |*$a, $b| { $a + $b[0] }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to raise_error(Puppet::ParseError, /Parameter \$a is not last, and has 'captures rest'/)
end
it 'is not allowed in define' do
source = <<-CODE
define foo(*$a) { }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to raise_error(Puppet::ParseError, /Parameter \$a has 'captures rest' - not supported in a 'define'/)
end
it 'is not allowed in class' do
source = <<-CODE
class foo(*$a) { }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to raise_error(Puppet::ParseError, /Parameter \$a has 'captures rest' - not supported in a Host Class Definition/)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_resource_spec.rb | spec/unit/pops/parser/parse_resource_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing resource declarations" do
include ParserRspecHelper
context "When parsing regular resource" do
["File", "file"].each do |word|
it "#{word} { 'title': }" do
expect(dump(parse("#{word} { 'title': }"))).to eq([
"(resource #{word}",
" ('title'))"
].join("\n"))
end
it "#{word} { 'title': path => '/somewhere', mode => '0777'}" do
expect(dump(parse("#{word} { 'title': path => '/somewhere', mode => '0777'}"))).to eq([
"(resource #{word}",
" ('title'",
" (path => '/somewhere')",
" (mode => '0777')))"
].join("\n"))
end
it "#{word} { 'title': path => '/somewhere', }" do
expect(dump(parse("#{word} { 'title': path => '/somewhere', }"))).to eq([
"(resource #{word}",
" ('title'",
" (path => '/somewhere')))"
].join("\n"))
end
it "#{word} { 'title': , }" do
expect(dump(parse("#{word} { 'title': , }"))).to eq([
"(resource #{word}",
" ('title'))"
].join("\n"))
end
it "#{word} { 'title': ; }" do
expect(dump(parse("#{word} { 'title': ; }"))).to eq([
"(resource #{word}",
" ('title'))"
].join("\n"))
end
it "#{word} { 'title': ; 'other_title': }" do
expect(dump(parse("#{word} { 'title': ; 'other_title': }"))).to eq([
"(resource #{word}",
" ('title')",
" ('other_title'))"
].join("\n"))
end
# PUP-2898, trailing ';'
it "#{word} { 'title': ; 'other_title': ; }" do
expect(dump(parse("#{word} { 'title': ; 'other_title': ; }"))).to eq([
"(resource #{word}",
" ('title')",
" ('other_title'))"
].join("\n"))
end
it "#{word} { 'title1': path => 'x'; 'title2': path => 'y'}" do
expect(dump(parse("#{word} { 'title1': path => 'x'; 'title2': path => 'y'}"))).to eq([
"(resource #{word}",
" ('title1'",
" (path => 'x'))",
" ('title2'",
" (path => 'y')))",
].join("\n"))
end
it "#{word} { title: * => {mode => '0777'} }" do
expect(dump(parse("#{word} { title: * => {mode => '0777'}}"))).to eq([
"(resource #{word}",
" (title",
" (* => ({} (mode '0777')))))"
].join("\n"))
end
end
end
context "When parsing (type based) resource defaults" do
it "File { }" do
expect(dump(parse("File { }"))).to eq("(resource-defaults File)")
end
it "File { mode => '0777' }" do
expect(dump(parse("File { mode => '0777'}"))).to eq([
"(resource-defaults File",
" (mode => '0777'))"
].join("\n"))
end
it "File { * => {mode => '0777'} } (even if validated to be illegal)" do
expect(dump(parse("File { * => {mode => '0777'}}"))).to eq([
"(resource-defaults File",
" (* => ({} (mode '0777'))))"
].join("\n"))
end
end
context "When parsing resource override" do
it "File['x'] { }" do
expect(dump(parse("File['x'] { }"))).to eq("(override (slice File 'x'))")
end
it "File['x'] { x => 1 }" do
expect(dump(parse("File['x'] { x => 1}"))).to eq([
"(override (slice File 'x')",
" (x => 1))"
].join("\n"))
end
it "File['x', 'y'] { x => 1 }" do
expect(dump(parse("File['x', 'y'] { x => 1}"))).to eq([
"(override (slice File ('x' 'y'))",
" (x => 1))"
].join("\n"))
end
it "File['x'] { x => 1, y => 2 }" do
expect(dump(parse("File['x'] { x => 1, y=> 2}"))).to eq([
"(override (slice File 'x')",
" (x => 1)",
" (y => 2))"
].join("\n"))
end
it "File['x'] { x +> 1 }" do
expect(dump(parse("File['x'] { x +> 1}"))).to eq([
"(override (slice File 'x')",
" (x +> 1))"
].join("\n"))
end
it "File['x'] { * => {mode => '0777'} } (even if validated to be illegal)" do
expect(dump(parse("File['x'] { * => {mode => '0777'}}"))).to eq([
"(override (slice File 'x')",
" (* => ({} (mode '0777'))))"
].join("\n"))
end
end
context "When parsing virtual and exported resources" do
it "parses exported @@file { 'title': }" do
expect(dump(parse("@@file { 'title': }"))).to eq("(exported-resource file\n ('title'))")
end
it "parses virtual @file { 'title': }" do
expect(dump(parse("@file { 'title': }"))).to eq("(virtual-resource file\n ('title'))")
end
it "nothing before the title colon is a syntax error" do
expect do
parse("@file {: mode => '0777' }")
end.to raise_error(/Syntax error/)
end
it "raises error for user error; not a resource" do
# The expression results in VIRTUAL, CALL FUNCTION('file', HASH) since the resource body has
# no title.
expect do
parse("@file { mode => '0777' }")
end.to raise_error(/Virtual \(@\) can only be applied to a Resource Expression/)
end
it "parses global defaults with @ (even if validated to be illegal)" do
expect(dump(parse("@File { mode => '0777' }"))).to eq([
"(virtual-resource-defaults File",
" (mode => '0777'))"
].join("\n"))
end
it "parses global defaults with @@ (even if validated to be illegal)" do
expect(dump(parse("@@File { mode => '0777' }"))).to eq([
"(exported-resource-defaults File",
" (mode => '0777'))"
].join("\n"))
end
it "parses override with @ (even if validated to be illegal)" do
expect(dump(parse("@File[foo] { mode => '0777' }"))).to eq([
"(virtual-override (slice File foo)",
" (mode => '0777'))"
].join("\n"))
end
it "parses override combined with @@ (even if validated to be illegal)" do
expect(dump(parse("@@File[foo] { mode => '0777' }"))).to eq([
"(exported-override (slice File foo)",
" (mode => '0777'))"
].join("\n"))
end
end
context "When parsing class resource" do
it "class { 'cname': }" do
expect(dump(parse("class { 'cname': }"))).to eq([
"(resource class",
" ('cname'))"
].join("\n"))
end
it "@class { 'cname': }" do
expect(dump(parse("@class { 'cname': }"))).to eq([
"(virtual-resource class",
" ('cname'))"
].join("\n"))
end
it "@@class { 'cname': }" do
expect(dump(parse("@@class { 'cname': }"))).to eq([
"(exported-resource class",
" ('cname'))"
].join("\n"))
end
it "class { 'cname': x => 1, y => 2}" do
expect(dump(parse("class { 'cname': x => 1, y => 2}"))).to eq([
"(resource class",
" ('cname'",
" (x => 1)",
" (y => 2)))"
].join("\n"))
end
it "class { 'cname1': x => 1; 'cname2': y => 2}" do
expect(dump(parse("class { 'cname1': x => 1; 'cname2': y => 2}"))).to eq([
"(resource class",
" ('cname1'",
" (x => 1))",
" ('cname2'",
" (y => 2)))",
].join("\n"))
end
end
context "reported issues in 3.x" do
it "should not screw up on brackets in title of resource #19632" do
expect(dump(parse('notify { "thisisa[bug]": }'))).to eq([
"(resource notify",
" ('thisisa[bug]'))",
].join("\n"))
end
end
context "When parsing Relationships" do
it "File[a] -> File[b]" do
expect(dump(parse("File[a] -> File[b]"))).to eq("(-> (slice File a) (slice File b))")
end
it "File[a] <- File[b]" do
expect(dump(parse("File[a] <- File[b]"))).to eq("(<- (slice File a) (slice File b))")
end
it "File[a] ~> File[b]" do
expect(dump(parse("File[a] ~> File[b]"))).to eq("(~> (slice File a) (slice File b))")
end
it "File[a] <~ File[b]" do
expect(dump(parse("File[a] <~ File[b]"))).to eq("(<~ (slice File a) (slice File b))")
end
it "Should chain relationships" do
expect(dump(parse("a -> b -> c"))).to eq(
"(-> (-> a b) c)"
)
end
it "Should chain relationships" do
expect(dump(parse("File[a] -> File[b] ~> File[c] <- File[d] <~ File[e]"))).to eq(
"(<~ (<- (~> (-> (slice File a) (slice File b)) (slice File c)) (slice File d)) (slice File e))"
)
end
it "should create relationships between collects" do
expect(dump(parse("File <| mode == 0644 |> -> File <| mode == 0755 |>"))).to eq(
"(-> (collect File\n (<| |> (== mode 0644))) (collect File\n (<| |> (== mode 0755))))"
)
end
end
context "When parsing collection" do
context "of virtual resources" do
it "File <| |>" do
expect(dump(parse("File <| |>"))).to eq("(collect File\n (<| |>))")
end
end
context "of exported resources" do
it "File <<| |>>" do
expect(dump(parse("File <<| |>>"))).to eq("(collect File\n (<<| |>>))")
end
end
context "queries are parsed with correct precedence" do
it "File <| tag == 'foo' |>" do
expect(dump(parse("File <| tag == 'foo' |>"))).to eq("(collect File\n (<| |> (== tag 'foo')))")
end
it "File <| tag == 'foo' and mode != '0777' |>" do
expect(dump(parse("File <| tag == 'foo' and mode != '0777' |>"))).to eq("(collect File\n (<| |> (&& (== tag 'foo') (!= mode '0777'))))")
end
it "File <| tag == 'foo' or mode != '0777' |>" do
expect(dump(parse("File <| tag == 'foo' or mode != '0777' |>"))).to eq("(collect File\n (<| |> (|| (== tag 'foo') (!= mode '0777'))))")
end
it "File <| tag == 'foo' or tag == 'bar' and mode != '0777' |>" do
expect(dump(parse("File <| tag == 'foo' or tag == 'bar' and mode != '0777' |>"))).to eq(
"(collect File\n (<| |> (|| (== tag 'foo') (&& (== tag 'bar') (!= mode '0777')))))"
)
end
it "File <| (tag == 'foo' or tag == 'bar') and mode != '0777' |>" do
expect(dump(parse("File <| (tag == 'foo' or tag == 'bar') and mode != '0777' |>"))).to eq(
"(collect File\n (<| |> (&& (|| (== tag 'foo') (== tag 'bar')) (!= mode '0777'))))"
)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_basic_expressions_spec.rb | spec/unit/pops/parser/parse_basic_expressions_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing basic expressions" do
include ParserRspecHelper
context "When the parser parses arithmetic" do
context "with Integers" do
it "$a = 2 + 2" do; expect(dump(parse("$a = 2 + 2"))).to eq("(= $a (+ 2 2))") ; end
it "$a = 7 - 3" do; expect(dump(parse("$a = 7 - 3"))).to eq("(= $a (- 7 3))") ; end
it "$a = 6 * 3" do; expect(dump(parse("$a = 6 * 3"))).to eq("(= $a (* 6 3))") ; end
it "$a = 6 / 3" do; expect(dump(parse("$a = 6 / 3"))).to eq("(= $a (/ 6 3))") ; end
it "$a = 6 % 3" do; expect(dump(parse("$a = 6 % 3"))).to eq("(= $a (% 6 3))") ; end
it "$a = -(6/3)" do; expect(dump(parse("$a = -(6/3)"))).to eq("(= $a (- (/ 6 3)))") ; end
it "$a = -6/3" do; expect(dump(parse("$a = -6/3"))).to eq("(= $a (/ (- 6) 3))") ; end
it "$a = 8 >> 1 " do; expect(dump(parse("$a = 8 >> 1"))).to eq("(= $a (>> 8 1))") ; end
it "$a = 8 << 1 " do; expect(dump(parse("$a = 8 << 1"))).to eq("(= $a (<< 8 1))") ; end
end
context "with Floats" do
it "$a = 2.2 + 2.2" do; expect(dump(parse("$a = 2.2 + 2.2"))).to eq("(= $a (+ 2.2 2.2))") ; end
it "$a = 7.7 - 3.3" do; expect(dump(parse("$a = 7.7 - 3.3"))).to eq("(= $a (- 7.7 3.3))") ; end
it "$a = 6.1 * 3.1" do; expect(dump(parse("$a = 6.1 - 3.1"))).to eq("(= $a (- 6.1 3.1))") ; end
it "$a = 6.6 / 3.3" do; expect(dump(parse("$a = 6.6 / 3.3"))).to eq("(= $a (/ 6.6 3.3))") ; end
it "$a = -(6.0/3.0)" do; expect(dump(parse("$a = -(6.0/3.0)"))).to eq("(= $a (- (/ 6.0 3.0)))") ; end
it "$a = -6.0/3.0" do; expect(dump(parse("$a = -6.0/3.0"))).to eq("(= $a (/ (- 6.0) 3.0))") ; end
it "$a = 3.14 << 2" do; expect(dump(parse("$a = 3.14 << 2"))).to eq("(= $a (<< 3.14 2))") ; end
it "$a = 3.14 >> 2" do; expect(dump(parse("$a = 3.14 >> 2"))).to eq("(= $a (>> 3.14 2))") ; end
end
context "with hex and octal Integer values" do
it "$a = 0xAB + 0xCD" do; expect(dump(parse("$a = 0xAB + 0xCD"))).to eq("(= $a (+ 0xAB 0xCD))") ; end
it "$a = 0777 - 0333" do; expect(dump(parse("$a = 0777 - 0333"))).to eq("(= $a (- 0777 0333))") ; end
end
context "with strings requiring boxing to Numeric" do
# Test that numbers in string form does not turn into numbers
it "$a = '2' + '2'" do; expect(dump(parse("$a = '2' + '2'"))).to eq("(= $a (+ '2' '2'))") ; end
it "$a = '2.2' + '0.2'" do; expect(dump(parse("$a = '2.2' + '0.2'"))).to eq("(= $a (+ '2.2' '0.2'))") ; end
it "$a = '0xab' + '0xcd'" do; expect(dump(parse("$a = '0xab' + '0xcd'"))).to eq("(= $a (+ '0xab' '0xcd'))") ; end
it "$a = '0777' + '0333'" do; expect(dump(parse("$a = '0777' + '0333'"))).to eq("(= $a (+ '0777' '0333'))") ; end
end
context "precedence should be correct" do
it "$a = 1 + 2 * 3" do; expect(dump(parse("$a = 1 + 2 * 3"))).to eq("(= $a (+ 1 (* 2 3)))"); end
it "$a = 1 + 2 % 3" do; expect(dump(parse("$a = 1 + 2 % 3"))).to eq("(= $a (+ 1 (% 2 3)))"); end
it "$a = 1 + 2 / 3" do; expect(dump(parse("$a = 1 + 2 / 3"))).to eq("(= $a (+ 1 (/ 2 3)))"); end
it "$a = 1 + 2 << 3" do; expect(dump(parse("$a = 1 + 2 << 3"))).to eq("(= $a (<< (+ 1 2) 3))"); end
it "$a = 1 + 2 >> 3" do; expect(dump(parse("$a = 1 + 2 >> 3"))).to eq("(= $a (>> (+ 1 2) 3))"); end
end
context "parentheses alter precedence" do
it "$a = (1 + 2) * 3" do; expect(dump(parse("$a = (1 + 2) * 3"))).to eq("(= $a (* (+ 1 2) 3))"); end
it "$a = (1 + 2) / 3" do; expect(dump(parse("$a = (1 + 2) / 3"))).to eq("(= $a (/ (+ 1 2) 3))"); end
end
end
context "When the evaluator performs boolean operations" do
context "using operators AND OR NOT" do
it "$a = true and true" do; expect(dump(parse("$a = true and true"))).to eq("(= $a (&& true true))"); end
it "$a = true or true" do; expect(dump(parse("$a = true or true"))).to eq("(= $a (|| true true))") ; end
it "$a = !true" do; expect(dump(parse("$a = !true"))).to eq("(= $a (! true))") ; end
end
context "precedence should be correct" do
it "$a = false or true and true" do
expect(dump(parse("$a = false or true and true"))).to eq("(= $a (|| false (&& true true)))")
end
it "$a = (false or true) and true" do
expect(dump(parse("$a = (false or true) and true"))).to eq("(= $a (&& (|| false true) true))")
end
it "$a = !true or true and true" do
expect(dump(parse("$a = !false or true and true"))).to eq("(= $a (|| (! false) (&& true true)))")
end
end
# Possibly change to check of literal expressions
context "on values requiring boxing to Boolean" do
it "'x' == true" do
expect(dump(parse("! 'x'"))).to eq("(! 'x')")
end
it "'' == false" do
expect(dump(parse("! ''"))).to eq("(! '')")
end
it ":undef == false" do
expect(dump(parse("! undef"))).to eq("(! :undef)")
end
end
end
context "When parsing comparisons" do
context "of string values" do
it "$a = 'a' == 'a'" do; expect(dump(parse("$a = 'a' == 'a'"))).to eq("(= $a (== 'a' 'a'))") ; end
it "$a = 'a' != 'a'" do; expect(dump(parse("$a = 'a' != 'a'"))).to eq("(= $a (!= 'a' 'a'))") ; end
it "$a = 'a' < 'b'" do; expect(dump(parse("$a = 'a' < 'b'"))).to eq("(= $a (< 'a' 'b'))") ; end
it "$a = 'a' > 'b'" do; expect(dump(parse("$a = 'a' > 'b'"))).to eq("(= $a (> 'a' 'b'))") ; end
it "$a = 'a' <= 'b'" do; expect(dump(parse("$a = 'a' <= 'b'"))).to eq("(= $a (<= 'a' 'b'))") ; end
it "$a = 'a' >= 'b'" do; expect(dump(parse("$a = 'a' >= 'b'"))).to eq("(= $a (>= 'a' 'b'))") ; end
end
context "of integer values" do
it "$a = 1 == 1" do; expect(dump(parse("$a = 1 == 1"))).to eq("(= $a (== 1 1))") ; end
it "$a = 1 != 1" do; expect(dump(parse("$a = 1 != 1"))).to eq("(= $a (!= 1 1))") ; end
it "$a = 1 < 2" do; expect(dump(parse("$a = 1 < 2"))).to eq("(= $a (< 1 2))") ; end
it "$a = 1 > 2" do; expect(dump(parse("$a = 1 > 2"))).to eq("(= $a (> 1 2))") ; end
it "$a = 1 <= 2" do; expect(dump(parse("$a = 1 <= 2"))).to eq("(= $a (<= 1 2))") ; end
it "$a = 1 >= 2" do; expect(dump(parse("$a = 1 >= 2"))).to eq("(= $a (>= 1 2))") ; end
end
context "of regular expressions (parse errors)" do
# Not supported in concrete syntax
it "$a = /.*/ == /.*/" do
expect(dump(parse("$a = /.*/ == /.*/"))).to eq("(= $a (== /.*/ /.*/))")
end
it "$a = /.*/ != /a.*/" do
expect(dump(parse("$a = /.*/ != /.*/"))).to eq("(= $a (!= /.*/ /.*/))")
end
end
end
context "When parsing Regular Expression matching" do
it "$a = 'a' =~ /.*/" do; expect(dump(parse("$a = 'a' =~ /.*/"))).to eq("(= $a (=~ 'a' /.*/))") ; end
it "$a = 'a' =~ '.*'" do; expect(dump(parse("$a = 'a' =~ '.*'"))).to eq("(= $a (=~ 'a' '.*'))") ; end
it "$a = 'a' !~ /b.*/" do; expect(dump(parse("$a = 'a' !~ /b.*/"))).to eq("(= $a (!~ 'a' /b.*/))") ; end
it "$a = 'a' !~ 'b.*'" do; expect(dump(parse("$a = 'a' !~ 'b.*'"))).to eq("(= $a (!~ 'a' 'b.*'))") ; end
end
context "When parsing unfold" do
it "$a = *[1,2]" do; expect(dump(parse("$a = *[1,2]"))).to eq("(= $a (unfold ([] 1 2)))") ; end
it "$a = *1" do; expect(dump(parse("$a = *1"))).to eq("(= $a (unfold 1))") ; end
it "$a = *[1,a => 2]" do; expect(dump(parse("$a = *[1,a => 2]"))).to eq("(= $a (unfold ([] 1 ({} (a 2)))))") ; end
end
context "When parsing Lists" do
it "$a = []" do
expect(dump(parse("$a = []"))).to eq("(= $a ([]))")
end
it "$a = [1]" do
expect(dump(parse("$a = [1]"))).to eq("(= $a ([] 1))")
end
it "$a = [1,2,3]" do
expect(dump(parse("$a = [1,2,3]"))).to eq("(= $a ([] 1 2 3))")
end
it "$a = [1,a => 2]" do
expect(dump(parse("$a = [1,a => 2]"))).to eq('(= $a ([] 1 ({} (a 2))))')
end
it "$a = [1,a => 2, 3]" do
expect(dump(parse("$a = [1,a => 2, 3]"))).to eq('(= $a ([] 1 ({} (a 2)) 3))')
end
it "$a = [1,a => 2, b => 3]" do
expect(dump(parse("$a = [1,a => 2, b => 3]"))).to eq('(= $a ([] 1 ({} (a 2) (b 3))))')
end
it "$a = [1,a => 2, b => 3, 4]" do
expect(dump(parse("$a = [1,a => 2, b => 3, 4]"))).to eq('(= $a ([] 1 ({} (a 2) (b 3)) 4))')
end
it "$a = [{ x => y }, a => 2, b => 3, { z => p }]" do
expect(dump(parse("$a = [{ x => y }, a => 2, b => 3, { z => p }]"))).to eq('(= $a ([] ({} (x y)) ({} (a 2) (b 3)) ({} (z p))))')
end
it "[...[...[]]] should create nested arrays without trouble" do
expect(dump(parse("$a = [1,[2.0, 2.1, [2.2]],[3.0, 3.1]]"))).to eq("(= $a ([] 1 ([] 2.0 2.1 ([] 2.2)) ([] 3.0 3.1)))")
end
it "$a = [2 + 2]" do
expect(dump(parse("$a = [2+2]"))).to eq("(= $a ([] (+ 2 2)))")
end
it "$a [1,2,3] == [1,2,3]" do
expect(dump(parse("$a = [1,2,3] == [1,2,3]"))).to eq("(= $a (== ([] 1 2 3) ([] 1 2 3)))")
end
it "calculates the text length of an empty array" do
expect(parse("[]").model.body.length).to eq(2)
expect(parse("[ ]").model.body.length).to eq(3)
end
{
'keyword' => %w(type function),
}.each_pair do |word_type, words|
words.each do |word|
it "allows the #{word_type} '#{word}' in a list" do
expect(dump(parse("$a = [#{word}]"))).to(eq("(= $a ([] '#{word}'))"))
end
it "allows the #{word_type} '#{word}' as a key in a hash" do
expect(dump(parse("$a = {#{word}=>'x'}"))).to(eq("(= $a ({} ('#{word}' 'x')))"))
end
it "allows the #{word_type} '#{word}' as a value in a hash" do
expect(dump(parse("$a = {'x'=>#{word}}"))).to(eq("(= $a ({} ('x' '#{word}')))"))
end
end
end
end
context "When parsing indexed access" do
it "$a = $b[2]" do
expect(dump(parse("$a = $b[2]"))).to eq("(= $a (slice $b 2))")
end
it "$a = $b[2,]" do
expect(dump(parse("$a = $b[2,]"))).to eq("(= $a (slice $b 2))")
end
it "$a = [1, 2, 3][2]" do
expect(dump(parse("$a = [1,2,3][2]"))).to eq("(= $a (slice ([] 1 2 3) 2))")
end
it '$a = [1, 2, 3][a => 2]' do
expect(dump(parse('$a = [1,2,3][a => 2]'))).to eq('(= $a (slice ([] 1 2 3) ({} (a 2))))')
end
it "$a = {'a' => 1, 'b' => 2}['b']" do
expect(dump(parse("$a = {'a'=>1,'b' =>2}[b]"))).to eq("(= $a (slice ({} ('a' 1) ('b' 2)) b))")
end
end
context 'When parsing type aliases' do
it 'type A = B' do
expect(dump(parse('type A = B'))).to eq('(type-alias A B)')
end
it 'type A = B[]' do
expect{parse('type A = B[]')}.to raise_error(/Syntax error at '\]'/)
end
it 'type A = B[,]' do
expect{parse('type A = B[,]')}.to raise_error(/Syntax error at ','/)
end
it 'type A = B[C]' do
expect(dump(parse('type A = B[C]'))).to eq('(type-alias A (slice B C))')
end
it 'type A = B[C,]' do
expect(dump(parse('type A = B[C,]'))).to eq('(type-alias A (slice B C))')
end
it 'type A = B[C,D]' do
expect(dump(parse('type A = B[C,D]'))).to eq('(type-alias A (slice B (C D)))')
end
it 'type A = B[C,D,]' do
expect(dump(parse('type A = B[C,D,]'))).to eq('(type-alias A (slice B (C D)))')
end
end
context "When parsing assignments" do
it "Should allow simple assignment" do
expect(dump(parse("$a = 10"))).to eq("(= $a 10)")
end
it "Should allow append assignment" do
expect(dump(parse("$a += 10"))).to eq("(+= $a 10)")
end
it "Should allow without assignment" do
expect(dump(parse("$a -= 10"))).to eq("(-= $a 10)")
end
it "Should allow chained assignment" do
expect(dump(parse("$a = $b = 10"))).to eq("(= $a (= $b 10))")
end
it "Should allow chained assignment with expressions" do
expect(dump(parse("$a = 1 + ($b = 10)"))).to eq("(= $a (+ 1 (= $b 10)))")
end
end
context "When parsing Hashes" do
it "should create a Hash when evaluating a LiteralHash" do
expect(dump(parse("$a = {'a'=>1,'b'=>2}"))).to eq("(= $a ({} ('a' 1) ('b' 2)))")
end
it "$a = {...{...{}}} should create nested hashes without trouble" do
expect(dump(parse("$a = {'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}"))).to eq("(= $a ({} ('a' 1) ('b' ({} ('x' 2.1) ('y' 2.2)))))")
end
it "$a = {'a'=> 2 + 2} should evaluate values in entries" do
expect(dump(parse("$a = {'a'=>2+2}"))).to eq("(= $a ({} ('a' (+ 2 2))))")
end
it "$a = {'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2}" do
expect(dump(parse("$a = {'a'=>1,'b'=>2} == {'a'=>1,'b'=>2}"))).to eq("(= $a (== ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))")
end
it "$a = {'a'=> 1, 'b'=>2} != {'x'=> 1, 'y'=>3}" do
expect(dump(parse("$a = {'a'=>1,'b'=>2} != {'a'=>1,'b'=>2}"))).to eq("(= $a (!= ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))")
end
it "$a = 'a' => 1" do
expect{parse("$a = 'a' => 1")}.to raise_error(/Syntax error at '=>'/)
end
it "$a = { 'a' => 'b' => 1 }" do
expect{parse("$a = { 'a' => 'b' => 1 }")}.to raise_error(/Syntax error at '=>'/)
end
it "calculates the text length of an empty hash" do
expect(parse("{}").model.body.length).to eq(2)
expect(parse("{ }").model.body.length).to eq(3)
end
end
context "When parsing the 'in' operator" do
it "with integer in a list" do
expect(dump(parse("$a = 1 in [1,2,3]"))).to eq("(= $a (in 1 ([] 1 2 3)))")
end
it "with string key in a hash" do
expect(dump(parse("$a = 'a' in {'x'=>1, 'a'=>2, 'y'=> 3}"))).to eq("(= $a (in 'a' ({} ('x' 1) ('a' 2) ('y' 3))))")
end
it "with substrings of a string" do
expect(dump(parse("$a = 'ana' in 'bananas'"))).to eq("(= $a (in 'ana' 'bananas'))")
end
it "with sublist in a list" do
expect(dump(parse("$a = [2,3] in [1,2,3]"))).to eq("(= $a (in ([] 2 3) ([] 1 2 3)))")
end
end
context "When parsing string interpolation" do
it "should interpolate a bare word as a variable name, \"${var}\"" do
expect(dump(parse("$a = \"$var\""))).to eq("(= $a (cat (str $var)))")
end
it "should interpolate a variable in a text expression, \"${$var}\"" do
expect(dump(parse("$a = \"${$var}\""))).to eq("(= $a (cat (str $var)))")
end
it "should interpolate a variable, \"yo${var}yo\"" do
expect(dump(parse("$a = \"yo${var}yo\""))).to eq("(= $a (cat 'yo' (str $var) 'yo'))")
end
it "should interpolate any expression in a text expression, \"${$var*2}\"" do
expect(dump(parse("$a = \"yo${$var+2}yo\""))).to eq("(= $a (cat 'yo' (str (+ $var 2)) 'yo'))")
end
it "should not interpolate names as variable in expression, \"${notvar*2}\"" do
expect(dump(parse("$a = \"yo${notvar+2}yo\""))).to eq("(= $a (cat 'yo' (str (+ notvar 2)) 'yo'))")
end
it "should interpolate name as variable in access expression, \"${var[0]}\"" do
expect(dump(parse("$a = \"yo${var[0]}yo\""))).to eq("(= $a (cat 'yo' (str (slice $var 0)) 'yo'))")
end
it "should interpolate name as variable in method call, \"${var.foo}\"" do
expect(dump(parse("$a = \"yo${$var.foo}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))")
end
it "should interpolate name as variable in method call, \"${var.foo}\"" do
expect(dump(parse("$a = \"yo${var.foo}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))")
expect(dump(parse("$a = \"yo${var.foo.bar}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. (call-method (. $var foo)) bar))) 'yo'))")
end
it "should interpolate interpolated expressions with a variable, \"yo${\"$var\"}yo\"" do
expect(dump(parse("$a = \"yo${\"$var\"}yo\""))).to eq("(= $a (cat 'yo' (str (cat (str $var))) 'yo'))")
end
it "should interpolate interpolated expressions with an expression, \"yo${\"${$var+2}\"}yo\"" do
expect(dump(parse("$a = \"yo${\"${$var+2}\"}yo\""))).to eq("(= $a (cat 'yo' (str (cat (str (+ $var 2)))) 'yo'))")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parser_spec.rb | spec/unit/pops/parser/parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
describe Puppet::Pops::Parser::Parser do
it "should instantiate a parser" do
parser = Puppet::Pops::Parser::Parser.new()
expect(parser.class).to eq(Puppet::Pops::Parser::Parser)
end
it "should parse a code string and return a model" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("$a = 10").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::AssignmentExpression)
end
it "should accept empty input and return a model" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
end
it "should accept empty input containing only comments and report location at end of input" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("# comment\n").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
expect(model.body.offset).to eq(10)
expect(model.body.length).to eq(0)
end
it "should give single resource expressions the correct offset inside an if/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
if(true) {
service { 'if service':
ensure => stopped
}
} else {
service { 'else service':
ensure => running
}
}
}
EOF
then_service = model.body.body.statements[0].then_expr
expect(then_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(then_service.offset).to eq(34)
else_service = model.body.body.statements[0].else_expr
expect(else_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(else_service.offset).to eq(106)
end
it "should give block expressions and their contained resources the correct offset inside an if/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
if(true) {
service { 'if service 1':
ensure => running
}
service { 'if service 2':
ensure => stopped
}
} else {
service { 'else service 1':
ensure => running
}
service { 'else service 2':
ensure => stopped
}
}
}
EOF
if_expr = model.body.body.statements[0]
block_expr = model.body.body.statements[0].then_expr
expect(if_expr.class).to eq(Puppet::Pops::Model::IfExpression)
expect(if_expr.offset).to eq(19)
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(28)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(34)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(98)
block_expr = model.body.body.statements[0].else_expr
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(166)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(172)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(238)
end
it "should give single resource expressions the correct offset inside an unless/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
unless(true) {
service { 'if service':
ensure => stopped
}
} else {
service { 'else service':
ensure => running
}
}
}
EOF
then_service = model.body.body.statements[0].then_expr
expect(then_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(then_service.offset).to eq(38)
else_service = model.body.body.statements[0].else_expr
expect(else_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(else_service.offset).to eq(110)
end
it "should give block expressions and their contained resources the correct offset inside an unless/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
unless(true) {
service { 'if service 1':
ensure => running
}
service { 'if service 2':
ensure => stopped
}
} else {
service { 'else service 1':
ensure => running
}
service { 'else service 2':
ensure => stopped
}
}
}
EOF
if_expr = model.body.body.statements[0]
block_expr = model.body.body.statements[0].then_expr
expect(if_expr.class).to eq(Puppet::Pops::Model::UnlessExpression)
expect(if_expr.offset).to eq(19)
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(32)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(38)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(102)
block_expr = model.body.body.statements[0].else_expr
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(170)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(176)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(242)
end
it "multi byte characters in a comment are counted as individual bytes" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("# \u{0400}comment\n").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
expect(model.body.offset).to eq(12)
expect(model.body.length).to eq(0)
end
it "should raise an error with position information when error is raised from within parser" do
parser = Puppet::Pops::Parser::Parser.new()
the_error = nil
begin
parser.parse_string("File [1] { }", 'fakefile.pp')
rescue Puppet::ParseError => e
the_error = e
end
expect(the_error).to be_a(Puppet::ParseError)
expect(the_error.file).to eq('fakefile.pp')
expect(the_error.line).to eq(1)
expect(the_error.pos).to eq(6)
end
it "should raise an error with position information when error is raised on token" do
parser = Puppet::Pops::Parser::Parser.new()
the_error = nil
begin
parser.parse_string(<<-EOF, 'fakefile.pp')
class whoops($a,$b,$c) {
$d = "oh noes", "b"
}
EOF
rescue Puppet::ParseError => e
the_error = e
end
expect(the_error).to be_a(Puppet::ParseError)
expect(the_error.file).to eq('fakefile.pp')
expect(the_error.line).to eq(2)
expect(the_error.pos).to eq(17)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/parse_functions_spec.rb | spec/unit/pops/parser/parse_functions_spec.rb | require 'spec_helper'
require 'puppet/pops'
require_relative 'parser_rspec_helper'
describe 'egrammar parsing function definitions' do
include ParserRspecHelper
context 'without return type' do
it 'function foo() { 1 }' do
expect(dump(parse('function foo() { 1 }'))).to eq("(function foo (block\n 1\n))")
end
end
context 'with return type' do
it 'function foo() >> Integer { 1 }' do
expect(dump(parse('function foo() >> Integer { 1 }'))).to eq("(function foo (return_type Integer) (block\n 1\n))")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/parser/pn_parser_spec.rb | spec/unit/pops/parser/pn_parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/pn'
module Puppet::Pops
module Parser
describe 'Puppet::Pops::Parser::PNParser' do
context 'parses the text' do
it '"true" to PN::Literal(true)' do
expect(PNParser.new.parse('true')).to eql(lit(true))
end
it '"false" to PN::Literal(false)' do
expect(PNParser.new.parse('false')).to eql(lit(false))
end
it '"nil" to PN::Literal(nil)' do
expect(PNParser.new.parse('nil')).to eql(lit(nil))
end
it '"123" to PN::Literal(123)' do
expect(PNParser.new.parse('123')).to eql(lit(123))
end
it '"-123" to PN::Literal(-123)' do
expect(PNParser.new.parse('-123')).to eql(lit(-123))
end
it '"123.45" to PN::Literal(123.45)' do
expect(PNParser.new.parse('123.45')).to eql(lit(123.45))
end
it '"-123.45" to PN::Literal(-123.45)' do
expect(PNParser.new.parse('-123.45')).to eql(lit(-123.45))
end
it '"123.45e12" to PN::Literal(123.45e12)' do
expect(PNParser.new.parse('123.45e12')).to eql(lit(123.45e12))
end
it '"123.45e+12" to PN::Literal(123.45e+12)' do
expect(PNParser.new.parse('123.45e+12')).to eql(lit(123.45e+12))
end
it '"123.45e-12" to PN::Literal(123.45e-12)' do
expect(PNParser.new.parse('123.45e-12')).to eql(lit(123.45e-12))
end
it '"hello" to PN::Literal("hello")' do
expect(PNParser.new.parse('"hello"')).to eql(lit('hello'))
end
it '"\t" to PN::Literal("\t")' do
expect(PNParser.new.parse('"\t"')).to eql(lit("\t"))
end
it '"\r" to PN::Literal("\r")' do
expect(PNParser.new.parse('"\r"')).to eql(lit("\r"))
end
it '"\n" to PN::Literal("\n")' do
expect(PNParser.new.parse('"\n"')).to eql(lit("\n"))
end
it '"\"" to PN::Literal("\"")' do
expect(PNParser.new.parse('"\""')).to eql(lit('"'))
end
it '"\\\\" to PN::Literal("\\")' do
expect(PNParser.new.parse('"\\\\"')).to eql(lit("\\"))
end
it '"\o024" to PN::Literal("\u{14}")' do
expect(PNParser.new.parse('"\o024"')).to eql(lit("\u{14}"))
end
end
it 'parses elements enclosed in brackets to a PN::List' do
expect(PNParser.new.parse('[1 "2" true false nil]')).to eql(PN::List.new([lit(1), lit('2'), lit(true), lit(false), lit(nil)]))
end
it 'parses elements enclosed in parenthesis to a PN::Call' do
expect(PNParser.new.parse('(+ 1 2)')).to eql(PN::Call.new('+', lit(1), lit(2)))
end
it 'parses entries enclosed in curly braces to a PN::Map' do
expect(PNParser.new.parse('{:a 1 :b "2" :c true}')).to eql(PN::Map.new([entry('a', 1), entry('b', '2'), entry('c', true)]))
end
def entry(k, v)
PN::Entry.new(k, lit(v))
end
def lit(v)
PN::Literal.new(v)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/serialization/to_stringified_spec.rb | spec/unit/pops/serialization/to_stringified_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe 'ToStringifiedConverter' do
include PuppetSpec::Compiler
after(:all) { Puppet::Pops::Loaders.clear }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:loaders) { Puppet::Pops::Loaders.new(env) }
let(:node) { Puppet::Node.new(env, environment: env) }
def transform(v)
Puppet::Pops::Serialization::ToStringifiedConverter.convert(v)
end
def eval_transform(source)
Puppet.override(:current_environment => env, :loaders => loaders) do
transform(evaluate(source: source, node: node))
end
end
it 'converts undef to to nil' do
expect(transform(nil)).to be_nil
expect(eval_transform('undef')).to be_nil
end
it "converts literal default to the string 'default'" do
expect(transform(:default)).to eq('default')
expect(eval_transform('default')).to eq('default')
end
it "does not convert an integer" do
expect(transform(42)).to eq(42)
end
it "does not convert a float" do
expect(transform(3.14)).to eq(3.14)
end
it "does not convert a boolean" do
expect(transform(true)).to be(true)
expect(transform(false)).to be(false)
end
it "does not convert a string (that is free from encoding issues)" do
expect(transform("hello")).to eq("hello")
end
it "converts a regexp to a string" do
expect(transform(/this|that.*/)).to eq("/this|that.*/")
expect(eval_transform('/this|that.*/')).to eq("/this|that.*/")
end
it 'handles a string with an embedded single quote' do
expect(transform("ta'phoenix")).to eq("ta'phoenix")
end
it 'handles a string with embedded double quotes' do
expect(transform('he said "hi"')).to eq("he said \"hi\"")
end
it 'converts a user defined object to its string representation including attributes' do
result = evaluate(code: "type Car = Object[attributes=>{regnbr => String}]", source: "Car(abc123)")
expect(transform(result)).to eq("Car({'regnbr' => 'abc123'})")
end
it 'converts a Deferred object to its string representation including attributes' do
expect(eval_transform("Deferred(func, [1,2,3])")).to eq("Deferred({'name' => 'func', 'arguments' => [1, 2, 3]})")
end
it 'converts a Sensitive to type + redacted plus id' do
sensitive = evaluate(source: "Sensitive('hush')")
id = sensitive.object_id
expect(transform(sensitive)).to eq("#<Sensitive [value redacted]:#{id}>")
end
it 'converts a Timestamp to String' do
expect(eval_transform("Timestamp('2018-09-03T19:45:33.697066000 UTC')")).to eq("2018-09-03T19:45:33.697066000 UTC")
end
it 'does not convert an array' do
expect(transform([1,2,3])).to eq([1,2,3])
end
it 'converts the content of an array - for example a Sensitive value' do
sensitive = evaluate(source: "Sensitive('hush')")
id = sensitive.object_id
expect(transform([sensitive])).to eq(["#<Sensitive [value redacted]:#{id}>"])
end
it 'converts the content of a hash - for example a Sensitive value' do
sensitive = evaluate(source: "Sensitive('hush')")
id = sensitive.object_id
expect(transform({'x' => sensitive})).to eq({'x' => "#<Sensitive [value redacted]:#{id}>"})
end
it 'does not convert a hash' do
expect(transform({'a' => 10, 'b' => 20})).to eq({'a' => 10, 'b' => 20})
end
it 'converts non Data compliant hash key to string' do
expect(transform({['funky', 'key'] => 10})).to eq({'["funky", "key"]' => 10})
end
it 'converts reserved __ptype hash key to different string' do
expect(transform({'__ptype' => 10})).to eq({'reserved key: __ptype' => 10})
end
it 'converts reserved __pvalue hash key to different string' do
expect(transform({'__pvalue' => 10})).to eq({'reserved key: __pvalue' => 10})
end
it 'converts a Binary to Base64 string' do
expect(eval_transform("Binary('hello', '%s')")).to eq("aGVsbG8=")
end
it 'converts an ASCII-8BIT String to Base64 String' do
binary_string = "\x02\x03\x04hello".force_encoding('ascii-8bit')
expect(transform(binary_string)).to eq("AgMEaGVsbG8=")
end
it 'converts Runtime (alien) object to its to_s' do
class Alien
end
an_alien = Alien.new
expect(transform(an_alien)).to eq(an_alien.to_s)
end
it 'converts a runtime Symbol to String' do
expect(transform(:symbolic)).to eq("symbolic")
end
it 'converts a datatype (such as Integer[0,10]) to its puppet source string form' do
expect(eval_transform("Integer[0,100]")).to eq("Integer[0, 100]")
end
it 'converts a user defined datatype (such as Car) to its puppet source string form' do
result = evaluate(code: "type Car = Object[attributes=>{regnbr => String}]", source: "Car")
expect(transform(result)).to eq("Car")
end
it 'converts a self referencing user defined datatype by using named references for cyclic entries' do
result = evaluate(code: "type Tree = Array[Variant[String, Tree]]", source: "Tree")
expect(transform(result)).to eq("Tree = Array[Variant[String, Tree]]")
end
it 'converts illegal char sequence in an encoding to Unicode Illegal' do
invalid_sequence = [0xc2, 0xc2].pack("c*").force_encoding(Encoding::UTF_8)
expect(transform(invalid_sequence)).to eq("��")
end
it 'does not convert unassigned char - glyph is same for all unassigned' do
unassigned = [243, 176, 128, 128].pack("C*").force_encoding(Encoding::UTF_8)
expect(transform(unassigned)).to eq("")
end
it 'converts ProcessOutput objects to string' do
object = Puppet::Util::Execution::ProcessOutput.new('object', 0)
expect(transform(object)).to be_instance_of(String)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/serialization/to_from_hr_spec.rb | spec/unit/pops/serialization/to_from_hr_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Serialization
describe 'Passing values through ToDataConverter/FromDataConverter' do
let(:dumper) { Model::ModelTreeDumper.new }
let(:io) { StringIO.new }
let(:parser) { Parser::EvaluatingParser.new }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:loaders) { Puppet::Pops::Loaders.new(env) }
let(:loader) { loaders.find_loader(nil) }
let(:to_converter) { ToDataConverter.new(:rich_data => true) }
let(:from_converter) { FromDataConverter.new(:loader => loader) }
before(:each) do
Puppet.lookup(:environments).clear_all
Puppet.push_context(:loaders => loaders, :current_environment => env)
end
after(:each) do
Puppet.pop_context
end
def write(value)
io.reopen
value = to_converter.convert(value)
expect(Types::TypeFactory.data).to be_instance(value)
io << [value].to_json
io.rewind
end
def write_raw(value)
io.reopen
expect(Types::TypeFactory.data).to be_instance(value)
io << [value].to_json
io.rewind
end
def read
from_converter.convert(::JSON.parse(io.read)[0])
end
def parse(string)
parser.parse_string(string, '/home/tester/experiments/manifests/init.pp')
end
context 'can write and read a' do
it 'String' do
val = 'the value'
write(val)
val2 = read
expect(val2).to be_a(String)
expect(val2).to eql(val)
end
it 'Integer' do
val = 32
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'Float' do
val = 32.45
write(val)
val2 = read
expect(val2).to be_a(Float)
expect(val2).to eql(val)
end
it 'true' do
val = true
write(val)
val2 = read
expect(val2).to be_a(TrueClass)
expect(val2).to eql(val)
end
it 'false' do
val = false
write(val)
val2 = read
expect(val2).to be_a(FalseClass)
expect(val2).to eql(val)
end
it 'nil' do
val = nil
write(val)
val2 = read
expect(val2).to be_a(NilClass)
expect(val2).to eql(val)
end
it 'Regexp' do
val = /match me/
write(val)
val2 = read
expect(val2).to be_a(Regexp)
expect(val2).to eql(val)
end
it 'Sensitive' do
sval = 'the sensitive value'
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to eql(sval)
end
it 'Timespan' do
val = Time::Timespan.from_fields(false, 3, 12, 40, 31, 123)
write(val)
val2 = read
expect(val2).to be_a(Time::Timespan)
expect(val2).to eql(val)
end
it 'Timestamp' do
val = Time::Timestamp.now
write(val)
val2 = read
expect(val2).to be_a(Time::Timestamp)
expect(val2).to eql(val)
end
it 'Version' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::Version.parse('1.2.3-alpha2')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::Version)
expect(val2).to eql(val)
end
it 'VersionRange' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::VersionRange)
expect(val2).to eql(val)
end
it 'Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
write(val)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'ACII_8BIT String as Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
strval = val.binary_buffer
write(strval)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'URI' do
val = URI('http://bob:ewing@dallas.example.com:8080/oil/baron?crude=cash#leftovers')
write(val)
val2 = read
expect(val2).to be_a(URI)
expect(val2).to eql(val)
end
it 'Sensitive with rich data' do
sval = Time::Timestamp.now
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to be_a(Time::Timestamp)
expect(val2.unwrap).to eql(sval)
end
it 'Hash with Symbol keys' do
val = { :one => 'one', :two => 'two' }
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql(val)
end
it 'Hash with Integer keys' do
val = { 1 => 'one', 2 => 'two' }
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql(val)
end
it 'A Hash that references itself' do
val = {}
val['myself'] = val
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2['myself']).to equal(val2)
end
end
context 'can write and read' do
include_context 'types_setup'
all_types.each do |t|
it "the default for type #{t.name}" do
val = t::DEFAULT
write(val)
val2 = read
expect(val2).to be_a(t)
expect(val2).to eql(val)
end
end
context 'a parameterized' do
it 'String' do
val = Types::TypeFactory.string(Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PStringType)
expect(val2).to eql(val)
end
it 'Regex' do
val = Types::TypeFactory.regexp(/foo/)
write(val)
val2 = read
expect(val2).to be_a(Types::PRegexpType)
expect(val2).to eql(val)
end
it 'Collection' do
val = Types::TypeFactory.collection(Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PCollectionType)
expect(val2).to eql(val)
end
it 'Array' do
val = Types::TypeFactory.array_of(Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PArrayType)
expect(val2).to eql(val)
end
it 'Hash' do
val = Types::TypeFactory.hash_kv(Types::TypeFactory.string, Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PHashType)
expect(val2).to eql(val)
end
it 'Variant' do
val = Types::TypeFactory.variant(Types::TypeFactory.string, Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PVariantType)
expect(val2).to eql(val)
end
it 'Object' do
val = Types::TypeParser.singleton.parse('Pcore::StringType', loader)
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectType)
expect(val2).to eql(val)
end
context 'ObjectType' do
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'type_parameters' => {
'x' => Types::PIntegerType::DEFAULT
},
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
it 'with preserved parameters' do
val = type.create(34)._pcore_type
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectTypeExtension)
expect(val2).to eql(val)
end
it 'with POjbectTypeExtension type being converted' do
val = { 'ObjectExtension' => type.create(34) }
expect(to_converter.convert(val))
.to eq({"ObjectExtension"=>{"__ptype"=>"MyType", "x"=>34}})
end
end
end
it 'Array of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = [
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
]
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'Hash of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = {
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
}
write(val)
val2 = read
expect(val2).to eql(val)
end
context 'an AST model' do
it "Locator" do
val = Parser::Locator::Locator19.new('here is some text', '/tmp/foo', [5])
write(val)
val2 = read
expect(val2).to be_a(Parser::Locator::Locator19)
expect(val2).to eql(val)
end
it 'nested Expression' do
expr = parse(<<-CODE)
$rootgroup = $os['family'] ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
CODE
write(expr)
expr2 = read
expect(dumper.dump(expr)).to eq(dumper.dump(expr2))
end
end
context 'PuppetObject' do
before(:each) do
class DerivedArray < Array
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedArray, 'DerivedArray', nil, 'values' => Types::PArrayType::DEFAULT)
.resolve(loader)
end
def initialize(values)
concat(values)
end
def values
Array.new(self)
end
end
class DerivedHash < Hash
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedHash, 'DerivedHash', nil, '_pcore_init_hash' => Types::PHashType::DEFAULT)
.resolve(loader)
end
def initialize(_pcore_init_hash)
merge!(_pcore_init_hash)
end
def _pcore_init_hash
result = {}
result.merge!(self)
result
end
end
end
after(:each) do
x = Puppet::Pops::Serialization
x.send(:remove_const, :DerivedArray) if x.const_defined?(:DerivedArray)
x.send(:remove_const, :DerivedHash) if x.const_defined?(:DerivedHash)
end
it 'derived from Array' do
DerivedArray.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedArray.new([
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
])
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'derived from Hash' do
DerivedHash.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedHash.new({
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
})
write(val)
val2 = read
expect(val2).to eql(val)
end
end
end
context 'deserializing an instance whose Object type was serialized by reference' do
let(:to_converter) { ToDataConverter.new(:type_by_reference => true, :rich_data => true) }
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
context 'fails when deserializer is unaware of the referenced type' do
it 'fails by default' do
write(type.create(32))
# Should fail since no loader knows about 'MyType'
expect{ read }.to raise_error(Puppet::Error, 'No implementation mapping found for Puppet Type MyType')
end
it 'succeeds and produces a hash when a read __ptype key is something other than a string or a hash' do
# i.e. this is for content that is not produced by ToDataHash - writing on-the-wire-format directly
# to test that it does not crash.
write_raw({'__ptype' => 10, 'x'=> 32})
expect(read).to eql({'__ptype'=>10, 'x'=>32})
end
context "succeeds but produces an rich_type hash when deserializer has 'allow_unresolved' set to true" do
let(:from_converter) { FromDataConverter.new(:allow_unresolved => true) }
it do
write(type.create(32))
expect(read).to eql({'__ptype'=>'MyType', 'x'=>32})
end
end
end
it 'succeeds when deserializer is aware of the referenced type' do
obj = type.create(32)
write(obj)
expect(loaders.find_loader(nil)).to receive(:load).with(:type, 'mytype').and_return(type)
expect(read).to eql(obj)
end
end
context 'with rich_data set to false' do
before :each do
# strict mode off so behavior is not stubbed
Puppet[:strict] = :warning
end
let(:to_converter) { ToDataConverter.new(:message_prefix => 'Test Hash', :rich_data => false) }
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
it 'A Hash with Symbol keys is converted to hash with String keys with warning' do
val = { :one => 'one', :two => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to eql([
"Test Hash contains a hash with a Symbol key. It will be converted to the String 'one'",
"Test Hash contains a hash with a Symbol key. It will be converted to the String 'two'"])
end
it 'A Hash with Version keys is converted to hash with String keys with warning' do
val = { SemanticPuppet::Version.parse('1.0.0') => 'one', SemanticPuppet::Version.parse('2.0.0') => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ '1.0.0' => 'one', '2.0.0' => 'two' })
end
expect(warnings).to eql([
"Test Hash contains a hash with a SemanticPuppet::Version key. It will be converted to the String '1.0.0'",
"Test Hash contains a hash with a SemanticPuppet::Version key. It will be converted to the String '2.0.0'"])
end
it 'A Hash with rich data is not converted and raises error by default' do
Puppet[:strict] = :error
expect do
val = { SemanticPuppet::Version.parse('1.0.0') => 'one', SemanticPuppet::Version.parse('2.0.0') => 'two' }
write(val)
end.to raise_error(/Evaluation Error: Test Hash contains a hash with a SemanticPuppet::Version key. It will be converted to the String '1.0.0'/)
end
context 'and symbol_as_string is set to true' do
let(:to_converter) { ToDataConverter.new(:rich_data => false, :symbol_as_string => true) }
it 'A Hash with Symbol keys is silently converted to hash with String keys' do
val = { :one => 'one', :two => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with Symbol values is silently converted to hash with String values' do
val = { 'one' => :one, 'two' => :two }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with default values will have the values converted to string with a warning' do
val = { 'key' => :default }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'key' => 'default' })
end
expect(warnings).to eql(["['key'] contains the special value default. It will be converted to the String 'default'"])
end
end
end
context 'with rich_data is set to true' do
let(:to_converter) { ToDataConverter.new(:message_prefix => 'Test Hash', :rich_data => true) }
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
context 'and symbol_as_string is set to true' do
let(:to_converter) { ToDataConverter.new(:rich_data => true, :symbol_as_string => true) }
it 'A Hash with Symbol keys is silently converted to hash with String keys' do
val = { :one => 'one', :two => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with Symbol values is silently converted to hash with String values' do
val = { 'one' => :one, 'two' => :two }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with __ptype, __pvalue keys will not be taken as a pcore meta tag' do
val = { '__ptype' => 42, '__pvalue' => 43 }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ '__ptype' => 42, '__pvalue' => 43 })
end
expect(warnings).to be_empty
end
it 'A Hash with default values will not loose type information' do
val = { 'key' => :default }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'key' => :default })
end
expect(warnings).to be_empty
end
end
end
context 'with local_reference set to false' do
let(:to_converter) { ToDataConverter.new(:local_reference => false) }
it 'A self referencing value will trigger an endless recursion error' do
val = {}
val['myself'] = val
expect { write(val) }.to raise_error(/Endless recursion detected when attempting to serialize value of class Hash/)
end
end
context 'will fail when' do
it 'the value of a type description is something other than a String or a Hash' do
expect do
from_converter.convert({ '__ptype' => { '__ptype' => 'Pcore::TimestampType', '__pvalue' => 12345 }})
end.to raise_error(/Cannot create a Pcore::TimestampType from a Integer/)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/serialization/packer_spec.rb | spec/unit/pops/serialization/packer_spec.rb | require 'spec_helper'
require 'puppet/pops/serialization'
module Puppet::Pops
module Serialization
[JSON].each do |packer_module|
describe "the Puppet::Pops::Serialization when using #{packer_module.name}" do
let(:io) { StringIO.new }
let(:reader_class) { packer_module::Reader }
let(:writer_class) { packer_module::Writer }
def write(*values)
io.reopen
serializer = writer_class.new(io)
values.each { |val| serializer.write(val) }
serializer.finish
io.rewind
end
def read(count = nil)
@deserializer = reader_class.new(io)
count.nil? ? @deserializer.read : Array.new(count) { @deserializer.read }
end
context 'can write and read a' do
it 'String' do
val = 'the value'
write(val)
val2 = read
expect(val2).to be_a(String)
expect(val2).to eql(val)
end
it 'positive Integer' do
val = 2**63-1
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'negative Integer' do
val = -2**63
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'Float' do
val = 32.45
write(val)
val2 = read
expect(val2).to be_a(Float)
expect(val2).to eql(val)
end
it 'true' do
val = true
write(val)
val2 = read
expect(val2).to be_a(TrueClass)
expect(val2).to eql(val)
end
it 'false' do
val = false
write(val)
val2 = read
expect(val2).to be_a(FalseClass)
expect(val2).to eql(val)
end
it 'nil' do
val = nil
write(val)
val2 = read
expect(val2).to be_a(NilClass)
expect(val2).to eql(val)
end
it 'Regexp' do
val = /match me/
write(val)
val2 = read
expect(val2).to be_a(Regexp)
expect(val2).to eql(val)
end
it 'Timespan' do
val = Time::Timespan.from_fields(false, 3, 12, 40, 31, 123)
write(val)
val2 = read
expect(val2).to be_a(Time::Timespan)
expect(val2).to eql(val)
end
it 'Timestamp' do
val = Time::Timestamp.now
write(val)
val2 = read
expect(val2).to be_a(Time::Timestamp)
expect(val2).to eql(val)
end
it 'Version' do
val = SemanticPuppet::Version.parse('1.2.3-alpha2')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::Version)
expect(val2).to eql(val)
end
it 'VersionRange' do
val = SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::VersionRange)
expect(val2).to eql(val)
end
it 'Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
write(val)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'URI' do
val = URI('http://bob:ewing@dallas.example.com:8080/oil/baron?crude=cash#leftovers')
write(val)
val2 = read
expect(val2).to be_a(URI)
expect(val2).to eql(val)
end
end
context 'will fail on attempts to write' do
it 'Integer larger than 2**63-1' do
expect { write(2**63) }.to raise_error(SerializationError, 'Integer out of bounds')
end
it 'Integer smaller than -2**63' do
expect { write(-2**63-1) }.to raise_error(SerializationError, 'Integer out of bounds')
end
it 'objects unknown to Puppet serialization' do
expect { write("".class) }.to raise_error(SerializationError, 'Unable to serialize a Class')
end
end
it 'should be able to write and read primitives using tabulation' do
val = 'the value'
write(val, val)
expect(read(2)).to eql([val, val])
expect(@deserializer.primitive_count).to eql(1)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/serialization/serialization_spec.rb | spec/unit/pops/serialization/serialization_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Serialization
[JSON].each do |packer_module|
describe "the Puppet::Pops::Serialization over #{packer_module.name}" do
let!(:dumper) { Model::ModelTreeDumper.new }
let(:io) { StringIO.new }
let(:parser) { Parser::EvaluatingParser.new }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:loaders) { Puppet::Pops::Loaders.new(env) }
let(:loader) { loaders.find_loader(nil) }
let(:reader_class) { packer_module::Reader }
let(:writer_class) { packer_module::Writer }
let(:serializer) { Serializer.new(writer_class.new(io)) }
let(:deserializer) { Deserializer.new(reader_class.new(io), loaders.find_loader(nil)) }
before(:each) do
Puppet.push_context(:loaders => loaders, :current_environment => env)
end
after(:each) do
Puppet.pop_context()
end
def write(*values)
io.reopen
values.each { |val| serializer.write(val) }
serializer.finish
io.rewind
end
def read
deserializer.read
end
def parse(string)
parser.parse_string(string, '/home/tester/experiments/manifests/init.pp')
end
context 'can write and read a' do
it 'String' do
val = 'the value'
write(val)
val2 = read
expect(val2).to be_a(String)
expect(val2).to eql(val)
end
it 'Integer' do
val = 32
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'Float' do
val = 32.45
write(val)
val2 = read
expect(val2).to be_a(Float)
expect(val2).to eql(val)
end
it 'true' do
val = true
write(val)
val2 = read
expect(val2).to be_a(TrueClass)
expect(val2).to eql(val)
end
it 'false' do
val = false
write(val)
val2 = read
expect(val2).to be_a(FalseClass)
expect(val2).to eql(val)
end
it 'nil' do
val = nil
write(val)
val2 = read
expect(val2).to be_a(NilClass)
expect(val2).to eql(val)
end
it 'Regexp' do
val = /match me/
write(val)
val2 = read
expect(val2).to be_a(Regexp)
expect(val2).to eql(val)
end
it 'Sensitive' do
sval = 'the sensitive value'
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to eql(sval)
end
it 'Timespan' do
val = Time::Timespan.from_fields(false, 3, 12, 40, 31, 123)
write(val)
val2 = read
expect(val2).to be_a(Time::Timespan)
expect(val2).to eql(val)
end
it 'Timestamp' do
val = Time::Timestamp.now
write(val)
val2 = read
expect(val2).to be_a(Time::Timestamp)
expect(val2).to eql(val)
end
it 'Version' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::Version.parse('1.2.3-alpha2')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::Version)
expect(val2).to eql(val)
end
it 'VersionRange' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::VersionRange)
expect(val2).to eql(val)
end
it 'Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
write(val)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'URI' do
val = URI('http://bob:ewing@dallas.example.com:8080/oil/baron?crude=cash#leftovers')
write(val)
val2 = read
expect(val2).to be_a(URI)
expect(val2).to eql(val)
end
it 'Sensitive with rich data' do
sval = Time::Timestamp.now
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to be_a(Time::Timestamp)
expect(val2.unwrap).to eql(sval)
end
end
context 'can write and read' do
include_context 'types_setup'
all_types.each do |t|
it "the default for type #{t.name}" do
val = t::DEFAULT
write(val)
val2 = read
expect(val2).to be_a(t)
expect(val2).to eql(val)
end
end
context 'a parameterized' do
it 'String' do
val = Types::TypeFactory.string(Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PStringType)
expect(val2).to eql(val)
end
it 'Regex' do
val = Types::TypeFactory.regexp(/foo/)
write(val)
val2 = read
expect(val2).to be_a(Types::PRegexpType)
expect(val2).to eql(val)
end
it 'Collection' do
val = Types::TypeFactory.collection(Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PCollectionType)
expect(val2).to eql(val)
end
it 'Array' do
val = Types::TypeFactory.array_of(Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PArrayType)
expect(val2).to eql(val)
end
it 'Hash' do
val = Types::TypeFactory.hash_kv(Types::TypeFactory.string, Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PHashType)
expect(val2).to eql(val)
end
it 'Variant' do
val = Types::TypeFactory.variant(Types::TypeFactory.string, Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PVariantType)
expect(val2).to eql(val)
end
it 'Object' do
val = Types::TypeParser.singleton.parse('Pcore::StringType', loader)
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectType)
expect(val2).to eql(val)
end
context 'ObjectType' do
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'type_parameters' => {
'x' => Types::PIntegerType::DEFAULT
},
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
it 'with preserved parameters' do
val = type.create(34)._pcore_type
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectTypeExtension)
expect(val2).to eql(val)
end
end
end
it 'Array of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = [
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
]
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'Hash of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = {
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
}
write(val)
val2 = read
expect(val2).to eql(val)
end
context 'an AST model' do
it "Locator" do
val = Parser::Locator::Locator19.new('here is some text', '/tmp/foo', [5])
write(val)
val2 = read
expect(val2).to be_a(Parser::Locator::Locator19)
expect(val2).to eql(val)
end
it 'nested Expression' do
expr = parse(<<-CODE)
$rootgroup = $os['family'] ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
CODE
write(expr)
expr2 = read
expect(dumper.dump(expr)).to eq(dumper.dump(expr2))
end
end
context 'PuppetObject' do
before(:each) do
class DerivedArray < Array
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedArray, 'DerivedArray', nil, 'values' => Types::PArrayType::DEFAULT)
.resolve(loader)
end
def initialize(values)
concat(values)
end
def values
Array.new(self)
end
end
class DerivedHash < Hash
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedHash, 'DerivedHash', nil, '_pcore_init_hash' => Types::PHashType::DEFAULT)
.resolve(loader)
end
def initialize(_pcore_init_hash)
merge!(_pcore_init_hash)
end
def _pcore_init_hash
result = {}
result.merge!(self)
result
end
end
end
after(:each) do
x = Puppet::Pops::Serialization
x.send(:remove_const, :DerivedArray) if x.const_defined?(:DerivedArray)
x.send(:remove_const, :DerivedHash) if x.const_defined?(:DerivedHash)
end
it 'derived from Array' do
DerivedArray.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedArray.new([
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
])
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'derived from Hash' do
DerivedHash.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedHash.new({
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
})
write(val)
val2 = read
expect(val2).to eql(val)
end
end
end
context 'deserializing an instance whose Object type was serialized by reference' do
let(:serializer) { Serializer.new(writer_class.new(io), :type_by_reference => true) }
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
it 'fails when deserializer is unaware of the referenced type' do
write(type.create(32))
# Should fail since no loader knows about 'MyType'
expect{ read }.to raise_error(Puppet::Error, 'No implementation mapping found for Puppet Type MyType')
end
it 'succeeds when deserializer is aware of the referenced type' do
obj = type.create(32)
write(obj)
expect(loaders.find_loader(nil)).to receive(:load).with(:type, 'mytype').and_return(type)
expect(read).to eql(obj)
end
end
context 'When debugging' do
let(:debug_io) { StringIO.new }
let(:writer) { reader_class.new(io, { :debug_io => debug_io, :tabulate => false, :verbose => true }) }
it 'can write and read an AST expression' do
expr = parse(<<-CODE)
$rootgroup = $os['family'] ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
CODE
write(expr)
expr2 = read
expect(dumper.dump(expr)).to eq(dumper.dump(expr2))
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/external/pson_spec.rb | spec/unit/external/pson_spec.rb | # Encoding: UTF-8
require 'spec_helper'
describe 'PSON', if: Puppet.features.pson? do
{
'foo' => '"foo"',
1 => '1',
"\x80" => "\"\x80\"",
[] => '[]'
}.each do |str, expect|
it "should be able to encode #{str.inspect}" do
got = str.to_pson
if got.respond_to? :force_encoding
expect(got.force_encoding('binary')).to eq(expect.force_encoding('binary'))
else
expect(got).to eq(expect)
end
end
end
it "should be able to handle arbitrary binary data" do
bin_string = (1..20000).collect { |i| ((17*i+13*i*i) % 255).chr }.join
parsed = PSON.parse(%Q{{ "type": "foo", "data": #{bin_string.to_pson} }})["data"]
if parsed.respond_to? :force_encoding
parsed.force_encoding('binary')
bin_string.force_encoding('binary')
end
expect(parsed).to eq(bin_string)
end
it "should be able to handle UTF8 that isn't a real unicode character" do
s = ["\355\274\267"]
expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to handle UTF8 for \\xFF" do
s = ["\xc3\xbf"]
expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to handle invalid UTF8 bytes" do
s = ["\xc3\xc3"]
expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to parse JSON containing UTF-8 characters in strings" do
s = '{ "foö": "bár" }'
expect { PSON.parse s }.not_to raise_error
end
it 'ignores "document_type" during parsing' do
text = '{"data":{},"document_type":"Node"}'
expect(PSON.parse(text)).to eq({"data" => {}, "document_type" => "Node"})
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/face_base_spec.rb | spec/unit/application/face_base_spec.rb | require 'spec_helper'
require 'puppet/application/face_base'
require 'tmpdir'
class Puppet::Application::FaceBase::Basetest < Puppet::Application::FaceBase
end
describe Puppet::Application::FaceBase do
let :app do
app = Puppet::Application::FaceBase::Basetest.new
allow(app.command_line).to receive(:subcommand_name).and_return('subcommand')
allow(Puppet::Util::Log).to receive(:newdestination)
app
end
after :each do
app.class.clear_everything_for_tests
end
describe "#find_global_settings_argument" do
it "should not match --ca to --ca-location" do
option = double('ca option', :optparse_args => ["--ca"])
expect(Puppet.settings).to receive(:each).and_yield(:ca, option)
expect(app.find_global_settings_argument("--ca-location")).to be_nil
end
end
describe "#parse_options" do
before :each do
allow(app.command_line).to receive(:args).and_return(%w{})
end
describe "with just an action" do
before(:each) do
# We have to stub Signal.trap to avoid a crazy mess where we take
# over signal handling and make it impossible to cancel the test
# suite run.
#
# It would be nice to fix this elsewhere, but it is actually hard to
# capture this in rspec 2.5 and all. :( --daniel 2011-04-08
allow(Signal).to receive(:trap)
allow(app.command_line).to receive(:args).and_return(%w{foo})
app.preinit
app.parse_options
end
it "should set the face based on the type" do
expect(app.face.name).to eq(:basetest)
end
it "should find the action" do
expect(app.action).to be
expect(app.action.name).to eq(:foo)
end
end
it "should stop if the first thing found is not an action" do
allow(app.command_line).to receive(:args).and_return(%w{banana count_args})
expect { app.run }.to exit_with(1)
expect(@logs.map(&:message)).to eq(["'basetest' has no 'banana' action. See `puppet help basetest`."])
end
it "should use the default action if not given any arguments" do
allow(app.command_line).to receive(:args).and_return([])
action = double(:options => [], :render_as => nil)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(action)
allow(app).to receive(:main)
app.run
expect(app.action).to eq(action)
expect(app.arguments).to eq([ { } ])
end
it "should use the default action if not given a valid one" do
allow(app.command_line).to receive(:args).and_return(%w{bar})
action = double(:options => [], :render_as => nil)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(action)
allow(app).to receive(:main)
app.run
expect(app.action).to eq(action)
expect(app.arguments).to eq([ 'bar', { } ])
end
it "should have no action if not given a valid one and there is no default action" do
allow(app.command_line).to receive(:args).and_return(%w{bar})
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(nil)
allow(app).to receive(:main)
expect { app.run }.to exit_with(1)
expect(@logs.first.message).to match(/has no 'bar' action./)
end
[%w{something_I_cannot_do},
%w{something_I_cannot_do argument}].each do |input|
it "should report unknown actions nicely" do
allow(app.command_line).to receive(:args).and_return(input)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(nil)
allow(app).to receive(:main)
expect { app.run }.to exit_with(1)
expect(@logs.first.message).to match(/has no 'something_I_cannot_do' action/)
end
end
[%w{something_I_cannot_do --unknown-option},
%w{something_I_cannot_do argument --unknown-option}].each do |input|
it "should report unknown actions even if there are unknown options" do
allow(app.command_line).to receive(:args).and_return(input)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(nil)
allow(app).to receive(:main)
expect { app.run }.to exit_with(1)
expect(@logs.first.message).to match(/has no 'something_I_cannot_do' action/)
end
end
it "should report a sensible error when options with = fail" do
allow(app.command_line).to receive(:args).and_return(%w{--action=bar foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --action/)
end
it "should fail if an action option is before the action" do
allow(app.command_line).to receive(:args).and_return(%w{--action foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --action/)
end
it "should fail if an unknown option is before the action" do
allow(app.command_line).to receive(:args).and_return(%w{--bar foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "should fail if an unknown option is after the action" do
allow(app.command_line).to receive(:args).and_return(%w{foo --bar})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "should accept --bar as an argument to a mandatory option after action" do
allow(app.command_line).to receive(:args).and_return(%w{foo --mandatory --bar})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({ :mandatory => "--bar" })
end
it "should accept --bar as an argument to a mandatory option before action" do
allow(app.command_line).to receive(:args).and_return(%w{--mandatory --bar foo})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({ :mandatory => "--bar" })
end
it "should not skip when --foo=bar is given" do
allow(app.command_line).to receive(:args).and_return(%w{--mandatory=bar --bar foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "does not skip when a puppet global setting is given as one item" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir=/tmp/puppet foo})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
it "does not skip when a puppet global setting is given as two items" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir /tmp/puppet foo})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
it "should not add :debug to the application-level options" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir /tmp/puppet foo --debug})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
it "should not add :verbose to the application-level options" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir /tmp/puppet foo --verbose})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
{ "boolean options before" => %w{--trace foo},
"boolean options after" => %w{foo --trace}
}.each do |name, args|
it "should accept global boolean settings #{name} the action" do
allow(app.command_line).to receive(:args).and_return(args)
Puppet.settings.initialize_global_settings(args)
app.preinit
app.parse_options
expect(Puppet[:trace]).to be_truthy
end
end
{ "before" => %w{--syslogfacility user1 foo},
" after" => %w{foo --syslogfacility user1}
}.each do |name, args|
it "should accept global settings with arguments #{name} the action" do
allow(app.command_line).to receive(:args).and_return(args)
Puppet.settings.initialize_global_settings(args)
app.preinit
app.parse_options
expect(Puppet[:syslogfacility]).to eq("user1")
end
end
it "should handle application-level options" do
allow(app.command_line).to receive(:args).and_return(%w{--verbose return_true})
app.preinit
app.parse_options
expect(app.face.name).to eq(:basetest)
end
end
describe "#setup" do
it "should remove the action name from the arguments" do
allow(app.command_line).to receive(:args).and_return(%w{--mandatory --bar foo})
app.preinit
app.parse_options
app.setup
expect(app.arguments).to eq([{ :mandatory => "--bar" }])
end
it "should pass positional arguments" do
myargs = %w{--mandatory --bar foo bar baz quux}
allow(app.command_line).to receive(:args).and_return(myargs)
app.preinit
app.parse_options
app.setup
expect(app.arguments).to eq(['bar', 'baz', 'quux', { :mandatory => "--bar" }])
end
end
describe "#main" do
before :each do
allow(app).to receive(:puts) # don't dump text to screen.
app.face = Puppet::Face[:basetest, '0.0.1']
app.action = app.face.get_action(:foo)
app.arguments = ["myname", "myarg"]
end
it "should send the specified verb and name to the face" do
expect(app.face).to receive(:foo).with(*app.arguments)
expect { app.main }.to exit_with(0)
end
it "should lookup help when it cannot do anything else" do
app.action = nil
expect(Puppet::Face[:help, :current]).to receive(:help).with(:basetest)
expect { app.main }.to exit_with(1)
end
it "should use its render method to render any result" do
expect(app).to receive(:render).with(app.arguments.length + 1, ["myname", "myarg"])
expect { app.main }.to exit_with(0)
end
it "should issue a deprecation warning if the face is deprecated" do
# since app is shared across examples, stub to avoid affecting shared context
allow(app.face).to receive(:deprecated?).and_return(true)
expect(app.face).to receive(:foo).with(*app.arguments)
expect(Puppet).to receive(:deprecation_warning).with(/'puppet basetest' is deprecated/)
expect { app.main }.to exit_with(0)
end
it "should not issue a deprecation warning if the face is not deprecated" do
expect(Puppet).not_to receive(:deprecation_warning)
# since app is shared across examples, stub to avoid affecting shared context
allow(app.face).to receive(:deprecated?).and_return(false)
expect(app.face).to receive(:foo).with(*app.arguments)
expect { app.main }.to exit_with(0)
end
end
describe "error reporting" do
before :each do
allow(app).to receive(:puts) # don't dump text to screen.
app.render_as = :json
app.face = Puppet::Face[:basetest, '0.0.1']
app.arguments = [{}] # we always have options in there...
end
it "should exit 0 when the action returns true" do
app.action = app.face.get_action :return_true
expect { app.main }.to exit_with(0)
end
it "should exit 0 when the action returns false" do
app.action = app.face.get_action :return_false
expect { app.main }.to exit_with(0)
end
it "should exit 0 when the action returns nil" do
app.action = app.face.get_action :return_nil
expect { app.main }.to exit_with(0)
end
it "should exit non-0 when the action raises" do
app.action = app.face.get_action :return_raise
expect { app.main }.not_to exit_with(0)
end
it "should use the exit code set by the action" do
app.action = app.face.get_action :with_specific_exit_code
expect { app.main }.to exit_with(5)
end
end
describe "#render" do
before :each do
app.face = Puppet::Interface.new('basetest', '0.0.1')
app.action = Puppet::Interface::Action.new(app.face, :foo)
end
context "default rendering" do
before :each do app.setup end
["hello", 1, 1.0].each do |input|
it "should just return a #{input.class.name}" do
expect(app.render(input, {})).to eq(input)
end
end
[[1, 2], ["one"], [{ 1 => 1 }]].each do |input|
it "should render Array as one item per line" do
expect(app.render(input, {})).to eq(input.collect { |item| item.to_s + "\n" }.join(''))
end
end
it "should render a non-trivially-keyed Hash with using pretty printed JSON" do
hash = { [1,2] => 3, [2,3] => 5, [3,4] => 7 }
expect(app.render(hash, {})).to eq(Puppet::Util::Json.dump(hash, :pretty => true).chomp)
end
it "should render a {String,Numeric}-keyed Hash into a table" do
object = Object.new
hash = { "one" => 1, "two" => [], "three" => {}, "four" => object,
5 => 5, 6.0 => 6 }
# Gotta love ASCII-betical sort order. Hope your objects are better
# structured for display than my test one is. --daniel 2011-04-18
expect(app.render(hash, {})).to eq <<EOT
5 5
6.0 6
four #{Puppet::Util::Json.dump(object).chomp}
one 1
three {}
two []
EOT
end
it "should render a hash nicely with a multi-line value" do
pending "Moving to PSON rather than PP makes this unsupportable."
hash = {
"number" => { "1" => '1' * 40, "2" => '2' * 40, '3' => '3' * 40 },
"text" => { "a" => 'a' * 40, 'b' => 'b' * 40, 'c' => 'c' * 40 }
}
expect(app.render(hash, {})).to eq <<EOT
number {"1"=>"1111111111111111111111111111111111111111",
"2"=>"2222222222222222222222222222222222222222",
"3"=>"3333333333333333333333333333333333333333"}
text {"a"=>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"b"=>"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"c"=>"cccccccccccccccccccccccccccccccccccccccc"}
EOT
end
describe "when setting the rendering method" do
after do
# need to reset the when_rendering block so that other tests can set it later
app.action.instance_variable_set("@when_rendering", {})
end
it "should invoke the action rendering hook while rendering" do
app.action.set_rendering_method_for(:console, proc { |value| "bi-winning!" })
expect(app.render("bi-polar?", {})).to eq("bi-winning!")
end
it "should invoke the action rendering hook with args and options while rendering" do
app.action.instance_variable_set("@when_rendering", {})
app.action.when_invoked = proc { |name, options| 'just need to match arity for rendering' }
app.action.set_rendering_method_for(
:console,
proc { |value, name, options| "I'm #{name}, no wait, I'm #{options[:altername]}" }
)
expect(app.render("bi-polar?", ['bob', {:altername => 'sue'}])).to eq("I'm bob, no wait, I'm sue")
end
end
it "should render JSON when asked for json" do
app.render_as = :json
json = app.render({ :one => 1, :two => 2 }, {})
expect(json).to match(/"one":\s*1\b/)
expect(json).to match(/"two":\s*2\b/)
expect(JSON.parse(json)).to eq({ "one" => 1, "two" => 2 })
end
end
it "should fail early if asked to render an invalid format" do
allow(app.command_line).to receive(:args).and_return(%w{--render-as interpretive-dance return_true})
# We shouldn't get here, thanks to the exception, and our expectation on
# it, but this helps us fail if that slips up and all. --daniel 2011-04-27
expect(Puppet::Face[:help, :current]).not_to receive(:help)
expect(Puppet).to receive(:send_log).with(:err, "Could not parse application options: I don't know how to render 'interpretive-dance'")
expect { app.run }.to exit_with(1)
end
it "should work if asked to render json" do
allow(app.command_line).to receive(:args).and_return(%w{count_args a b c --render-as json})
expect {
app.run
}.to exit_with(0)
.and output(/3/).to_stdout
end
it "should invoke when_rendering hook 's' when asked to render-as 's'" do
allow(app.command_line).to receive(:args).and_return(%w{with_s_rendering_hook --render-as s})
app.action = app.face.get_action(:with_s_rendering_hook)
expect {
app.run
}.to exit_with(0)
.and output(/you invoked the 's' rendering hook/).to_stdout
end
end
describe "#help" do
it "should generate help for --help" do
allow(app.command_line).to receive(:args).and_return(%w{--help})
expect(Puppet::Face[:help, :current]).to receive(:help)
expect { app.run }.to exit_with(0)
end
it "should generate help for -h" do
allow(app.command_line).to receive(:args).and_return(%w{-h})
expect(Puppet::Face[:help, :current]).to receive(:help)
expect { app.run }.to exit_with(0)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/agent_spec.rb | spec/unit/application/agent_spec.rb | require 'spec_helper'
require 'puppet/agent'
require 'puppet/application/agent'
require 'puppet/daemon'
class TestAgentClientClass
def initialize(transaction_uuid = nil, job_id = nil); end
def run(options = {}); end
end
describe Puppet::Application::Agent do
include PuppetSpec::Files
let(:machine) { double(ensure_client_certificate: nil) }
before :each do
@puppetd = Puppet::Application[:agent]
@client = TestAgentClientClass.new
allow(TestAgentClientClass).to receive(:new).and_return(@client)
@agent = Puppet::Agent.new(TestAgentClientClass, false)
allow(Puppet::Agent).to receive(:new).and_return(@agent)
Puppet[:pidfile] = tmpfile('pidfile')
@daemon = Puppet::Daemon.new(@agent, Puppet::Util::Pidlock.new(Puppet[:pidfile]))
allow(@daemon).to receive(:daemonize)
allow(@daemon).to receive(:stop)
# simulate one run so we don't infinite looptwo runs of the agent, then return so we don't infinite loop
allow(@daemon).to receive(:run_event_loop) do
@agent.run(splay: false)
end
allow(Puppet::Daemon).to receive(:new).and_return(@daemon)
Puppet[:daemonize] = false
@puppetd.preinit
allow(Puppet::Util::Log).to receive(:newdestination)
allow(Puppet::Node.indirection).to receive(:terminus_class=)
allow(Puppet::Node.indirection).to receive(:cache_class=)
allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=)
allow(Puppet.settings).to receive(:use)
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(machine)
end
it "should operate in agent run_mode" do
expect(@puppetd.class.run_mode.name).to eq(:agent)
end
it "should declare a main command" do
expect(@puppetd).to respond_to(:main)
end
it "should declare a onetime command" do
expect(@puppetd).to respond_to(:onetime)
end
it "should declare a fingerprint command" do
expect(@puppetd).to respond_to(:fingerprint)
end
it "should declare a preinit block" do
expect(@puppetd).to respond_to(:preinit)
end
describe "in preinit" do
it "should catch INT" do
expect(Signal).to receive(:trap).with(:INT)
@puppetd.preinit
end
it "should init fqdn to nil" do
@puppetd.preinit
expect(@puppetd.options[:fqdn]).to be_nil
end
it "should init serve to []" do
@puppetd.preinit
expect(@puppetd.options[:serve]).to eq([])
end
it "should use SHA256 as default digest algorithm" do
@puppetd.preinit
expect(@puppetd.options[:digest]).to eq('SHA256')
end
it "should not fingerprint by default" do
@puppetd.preinit
expect(@puppetd.options[:fingerprint]).to be_falsey
end
it "should init waitforcert to nil" do
@puppetd.preinit
expect(@puppetd.options[:waitforcert]).to be_nil
end
end
describe "when handling options" do
[:enable, :debug, :fqdn, :test, :verbose, :digest].each do |option|
it "should declare handle_#{option} method" do
expect(@puppetd).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@puppetd.send("handle_#{option}".to_sym, 'arg')
expect(@puppetd.options[option]).to eq('arg')
end
end
describe "when handling --disable" do
it "should set disable to true" do
@puppetd.handle_disable('')
expect(@puppetd.options[:disable]).to eq(true)
end
it "should store disable message" do
@puppetd.handle_disable('message')
expect(@puppetd.options[:disable_message]).to eq('message')
end
end
it "should log the agent start time" do
expect(@puppetd.options[:start_time]).to be_a(Time)
end
it "should set waitforcert to 0 with --onetime and if --waitforcert wasn't given" do
allow(@client).to receive(:run).and_return(2)
Puppet[:onetime] = true
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 0)).and_return(machine)
expect { execute_agent }.to exit_with 0
end
it "should use supplied waitforcert when --onetime is specified" do
allow(@client).to receive(:run).and_return(2)
Puppet[:onetime] = true
@puppetd.handle_waitforcert(60)
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 60)).and_return(machine)
expect { execute_agent }.to exit_with 0
end
it "should use a default value for waitforcert when --onetime and --waitforcert are not specified" do
allow(@client).to receive(:run).and_return(2)
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 120)).and_return(machine)
execute_agent
end
it "should register ssl OIDs" do
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 120)).and_return(machine)
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
execute_agent
end
it "should use the waitforcert setting when checking for a signed certificate" do
Puppet[:waitforcert] = 10
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 10)).and_return(machine)
execute_agent
end
it "should set the log destination with --logdest" do
expect(Puppet::Log).to receive(:newdestination).with("console")
@puppetd.handle_logdest("console")
end
it "should put the setdest options to true" do
@puppetd.handle_logdest("console")
expect(@puppetd.options[:setdest]).to eq(true)
end
it "should parse the log destination from the command line" do
allow(@puppetd.command_line).to receive(:args).and_return(%w{--logdest /my/file})
expect(Puppet::Util::Log).to receive(:newdestination).with("/my/file")
@puppetd.parse_options
end
it "should store the waitforcert options with --waitforcert" do
@puppetd.handle_waitforcert("42")
expect(@puppetd.options[:waitforcert]).to eq(42)
end
end
describe "during setup" do
before :each do
allow(Puppet).to receive(:info)
Puppet[:libdir] = "/dev/null/lib"
allow(Puppet::Transaction::Report.indirection).to receive(:terminus_class=)
allow(Puppet::Transaction::Report.indirection).to receive(:cache_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:cache_class=)
allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=)
end
it "should not run with extra arguments" do
allow(@puppetd.command_line).to receive(:args).and_return(%w{disable})
expect{@puppetd.setup}.to raise_error ArgumentError, /does not take parameters/
end
describe "with --test" do
it "should call setup_test" do
@puppetd.options[:test] = true
expect(@puppetd).to receive(:setup_test)
@puppetd.setup
end
it "should set options[:verbose] to true" do
@puppetd.setup_test
expect(@puppetd.options[:verbose]).to eq(true)
end
it "should set options[:onetime] to true" do
Puppet[:onetime] = false
@puppetd.setup_test
expect(Puppet[:onetime]).to eq(true)
end
it "should set options[:detailed_exitcodes] to true" do
@puppetd.setup_test
expect(@puppetd.options[:detailed_exitcodes]).to eq(true)
end
end
it "should call setup_logs" do
expect(@puppetd).to receive(:setup_logs)
@puppetd.setup
end
describe "when setting up logs" do
before :each do
allow(Puppet::Util::Log).to receive(:newdestination)
end
it "should set log level to debug if --debug was passed" do
@puppetd.options[:debug] = true
@puppetd.setup_logs
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@puppetd.options[:verbose] = true
@puppetd.setup_logs
expect(Puppet::Util::Log.level).to eq(:info)
end
[:verbose, :debug].each do |level|
it "should set console as the log destination with level #{level}" do
@puppetd.options[level] = true
allow(Puppet::Util::Log).to receive(:newdestination)
expect(Puppet::Util::Log).to receive(:newdestination).with(:console).exactly(:once)
@puppetd.setup_logs
end
end
it "should set a default log destination if no --logdest" do
@puppetd.options[:setdest] = false
expect(Puppet::Util::Log).to receive(:setup_default)
@puppetd.setup_logs
end
end
it "should print puppet config if asked to in Puppet config" do
Puppet[:configprint] = "plugindest"
expect(Puppet.settings).to receive(:print_configs).and_return(true)
expect { execute_agent }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
path = make_absolute('/my/path')
Puppet[:modulepath] = path
Puppet[:configprint] = "modulepath"
expect_any_instance_of(Puppet::Settings).to receive(:puts).with(path)
expect { execute_agent }.to exit_with 0
end
it "should use :main, :puppetd, and :ssl" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :ssl)
@puppetd.setup
end
it "should setup an agent in fingerprint mode" do
@puppetd.options[:fingerprint] = true
expect(@puppetd).not_to receive(:setup_agent)
@puppetd.setup
end
it "should tell the report handler to use REST" do
expect(Puppet::Transaction::Report.indirection).to receive(:terminus_class=).with(:rest)
@puppetd.setup
end
it "should tell the report handler to cache locally as yaml" do
expect(Puppet::Transaction::Report.indirection).to receive(:cache_class=).with(:yaml)
@puppetd.setup
end
it "should default catalog_terminus setting to 'rest'" do
@puppetd.initialize_app_defaults
expect(Puppet[:catalog_terminus]).to eq(:rest)
end
it "should default node_terminus setting to 'rest'" do
@puppetd.initialize_app_defaults
expect(Puppet[:node_terminus]).to eq(:rest)
end
it "has an application default :catalog_cache_terminus setting of 'json'" do
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:json)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should tell the catalog cache class based on the :catalog_cache_terminus setting" do
Puppet[:catalog_cache_terminus] = "yaml"
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:yaml)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should not set catalog cache class if :catalog_cache_terminus is explicitly nil" do
Puppet[:catalog_cache_terminus] = nil
expect(Puppet::Resource::Catalog.indirection).not_to receive(:cache_class=)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should default facts_terminus setting to 'facter'" do
@puppetd.initialize_app_defaults
expect(Puppet[:facts_terminus]).to eq(:facter)
end
it "should create an agent" do
allow(Puppet::Agent).to receive(:new).with(Puppet::Configurer)
@puppetd.setup
end
[:enable, :disable].each do |action|
it "should delegate to enable_disable_client if we #{action} the agent" do
@puppetd.options[action] = true
expect(@puppetd).to receive(:enable_disable_client).with(@agent)
@puppetd.setup
end
end
describe "when enabling or disabling agent" do
[:enable, :disable].each do |action|
it "should call client.#{action}" do
@puppetd.options[action] = true
expect(@agent).to receive(action)
expect { execute_agent }.to exit_with 0
end
end
it "should pass the disable message when disabling" do
@puppetd.options[:disable] = true
@puppetd.options[:disable_message] = "message"
expect(@agent).to receive(:disable).with("message")
expect { execute_agent }.to exit_with 0
end
it "should pass the default disable message when disabling without a message" do
@puppetd.options[:disable] = true
@puppetd.options[:disable_message] = nil
expect(@agent).to receive(:disable).with("reason not specified")
expect { execute_agent }.to exit_with 0
end
end
it "should inform the daemon about our agent if :client is set to 'true'" do
@puppetd.options[:client] = true
execute_agent
expect(@daemon.agent).to eq(@agent)
end
it "should daemonize if needed" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
Puppet[:daemonize] = true
allow(Signal).to receive(:trap)
expect(@daemon).to receive(:daemonize)
execute_agent
end
it "should wait for a certificate" do
Puppet[:waitforcert] = 123
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 123)).and_return(machine)
execute_agent
end
describe "when setting up for fingerprint" do
before(:each) do
@puppetd.options[:fingerprint] = true
end
it "should not setup as an agent" do
expect(@puppetd).not_to receive(:setup_agent)
@puppetd.setup
end
it "should not create an agent" do
expect(Puppet::Agent).not_to receive(:new).with(Puppet::Configurer)
@puppetd.setup
end
it "should not daemonize" do
expect(@daemon).not_to receive(:daemonize)
@puppetd.setup
end
end
describe "when configuring agent for catalog run" do
it "should set should_fork as true when running normally" do
expect(Puppet::Agent).to receive(:new).with(anything, true)
@puppetd.setup
end
it "should not set should_fork as false for --onetime" do
Puppet[:onetime] = true
expect(Puppet::Agent).to receive(:new).with(anything, false)
@puppetd.setup
end
end
end
describe "when running" do
before :each do
@puppetd.options[:fingerprint] = false
end
it "should dispatch to fingerprint if --fingerprint is used" do
@puppetd.options[:fingerprint] = true
expect(@puppetd).to receive(:fingerprint)
execute_agent
end
it "should dispatch to onetime if --onetime is used" do
Puppet[:onetime] = true
expect(@puppetd).to receive(:onetime)
execute_agent
end
it "should dispatch to main if --onetime and --fingerprint are not used" do
Puppet[:onetime] = false
expect(@puppetd).to receive(:main)
execute_agent
end
describe "with --onetime" do
before :each do
allow(@agent).to receive(:run).and_return(:report)
Puppet[:onetime] = true
@puppetd.options[:client] = :client
@puppetd.options[:detailed_exitcodes] = false
end
it "should setup traps" do
expect(@daemon).to receive(:set_signal_traps)
expect { execute_agent }.to exit_with 0
end
it "should let the agent run" do
expect(@agent).to receive(:run).and_return(:report)
expect { execute_agent }.to exit_with 0
end
it "should run the agent with the supplied job_id" do
@puppetd.options[:job_id] = 'special id'
expect(@agent).to receive(:run).with(hash_including(:job_id => 'special id')).and_return(:report)
expect { execute_agent }.to exit_with 0
end
it "should stop the daemon" do
expect(@daemon).to receive(:stop).with({:exit => false})
expect { execute_agent }.to exit_with 0
end
describe "and --detailed-exitcodes" do
before :each do
@puppetd.options[:detailed_exitcodes] = true
end
it "should exit with agent computed exit status" do
Puppet[:noop] = false
allow(@agent).to receive(:run).and_return(666)
expect { execute_agent }.to exit_with 666
end
it "should exit with the agent's exit status, even if --noop is set." do
Puppet[:noop] = true
allow(@agent).to receive(:run).and_return(666)
expect { execute_agent }.to exit_with 666
end
end
end
describe "with --fingerprint" do
before :each do
@puppetd.options[:fingerprint] = true
@puppetd.options[:digest] = :MD5
end
def expected_fingerprint(name, x509)
digest = OpenSSL::Digest.new(name).hexdigest(x509.to_der)
digest.scan(/../).join(':').upcase
end
it "should fingerprint the certificate if it exists" do
cert = cert_fixture('signed.pem')
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_return(cert)
expect(@puppetd).to receive(:puts).with("(MD5) #{expected_fingerprint('md5', cert)}")
@puppetd.fingerprint
end
it "should fingerprint the request if it exists" do
request = request_fixture('request.pem')
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_return(nil)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_request).and_return(request)
expect(@puppetd).to receive(:puts).with("(MD5) #{expected_fingerprint('md5', request)}")
@puppetd.fingerprint
end
it "should print an error to stderr if neither exist" do
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_return(nil)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_request).and_return(nil)
expect {
@puppetd.fingerprint
}.to exit_with(1)
.and output(/Fingerprint asked but neither the certificate, nor the certificate request have been issued/).to_stderr
end
it "should log an error if an exception occurs" do
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_raise(Puppet::Error, "Invalid PEM")
expect {
@puppetd.fingerprint
}.to exit_with(1)
expect(@logs).to include(an_object_having_attributes(message: /Failed to generate fingerprint: Invalid PEM/))
end
end
describe "without --onetime and --fingerprint" do
before :each do
allow(Puppet).to receive(:notice)
end
it "should start our daemon" do
expect(@daemon).to receive(:start)
execute_agent
end
end
end
describe "when starting in daemon mode on non-windows", :unless => Puppet.features.microsoft_windows? do
before :each do
allow(Puppet).to receive(:notice)
Puppet[:daemonize] = true
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(machine)
end
it "should not print config in default mode" do
execute_agent
expect(@logs).to be_empty
end
it "should print config in debug mode" do
@puppetd.options[:debug] = true
execute_agent
expect(@logs).to include(an_object_having_attributes(level: :debug, message: /agent_catalog_run_lockfile=/))
end
end
def execute_agent
@puppetd.setup
@puppetd.run_command
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/device_spec.rb | spec/unit/application/device_spec.rb | require 'spec_helper'
require 'ostruct'
require 'puppet/application/apply'
require 'puppet/application/device'
require 'puppet/configurer'
require 'puppet/util/network_device/config'
describe Puppet::Application::Device do
include PuppetSpec::Files
let(:device) do
dev = Puppet::Application[:device]
allow(dev).to receive(:trap)
allow(Signal).to receive(:trap)
dev.preinit
dev
end
let(:ssl_context) { instance_double(Puppet::SSL::SSLContext, 'ssl_context') }
let(:state_machine) { instance_double(Puppet::SSL::StateMachine, 'state machine') }
before do
allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=)
allow(Puppet::Node.indirection).to receive(:cache_class=)
allow(Puppet::Node.indirection).to receive(:terminus_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:cache_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class=)
allow(Puppet::Transaction::Report.indirection).to receive(:terminus_class=)
allow(Puppet::Util::Log).to receive(:newdestination)
allow(state_machine).to receive(:ensure_client_certificate).and_return(ssl_context)
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(state_machine)
end
it "operates in agent run_mode" do
expect(device.class.run_mode.name).to eq(:agent)
end
it "declares a main command" do
expect(device).to respond_to(:main)
end
it "declares a preinit block" do
expect(device).to respond_to(:preinit)
end
describe "in preinit" do
before do
end
it "catches INT" do
device
expect(Signal).to have_received(:trap).with(:INT)
end
it "inits waitforcert to nil" do
expect(device.options[:waitforcert]).to be_nil
end
it "inits target to nil" do
expect(device.options[:target]).to be_nil
end
end
describe "when handling options" do
before do
Puppet[:certname] = 'device.example.com'
allow(device.command_line).to receive(:args).and_return([])
end
[:centrallogging, :debug, :verbose,].each do |option|
it "should declare handle_#{option} method" do
expect(device).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
allow(device.options).to receive(:[]=).with(option, 'arg')
device.send("handle_#{option}".to_sym, 'arg')
end
end
context 'when setting --onetime' do
before do
Puppet[:onetime] = true
end
context 'without --waitforcert' do
it "defaults waitforcert to 0" do
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 0))
end
end
context 'with --waitforcert=60' do
it "uses supplied waitforcert" do
device.handle_waitforcert(60)
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 60))
end
end
end
context 'without setting --onetime' do
before do
Puppet[:onetime] = false
end
it "uses a default value for waitforcert when --onetime and --waitforcert are not specified" do
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 120))
end
it "uses the waitforcert setting when checking for a signed certificate" do
Puppet[:waitforcert] = 10
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 10))
end
end
it "sets the log destination with --logdest" do
allow(device.options).to receive(:[]=).with(:setdest, anything)
expect(Puppet::Log).to receive(:newdestination).with("console")
device.handle_logdest("console")
end
it "puts the setdest options to true" do
expect(device.options).to receive(:[]=).with(:setdest, true)
device.handle_logdest("console")
end
it "parses the log destination from the command line" do
allow(device.command_line).to receive(:args).and_return(%w{--logdest /my/file})
expect(Puppet::Util::Log).to receive(:newdestination).with("/my/file")
device.parse_options
end
it "stores the waitforcert options with --waitforcert" do
expect(device.options).to receive(:[]=).with(:waitforcert,42)
device.handle_waitforcert("42")
end
it "sets args[:Port] with --port" do
device.handle_port("42")
expect(device.args[:Port]).to eq("42")
end
it "stores the target options with --target" do
expect(device.options).to receive(:[]=).with(:target,'test123')
device.handle_target('test123')
end
it "stores the resource options with --resource" do
expect(device.options).to receive(:[]=).with(:resource,true)
device.handle_resource(true)
end
it "stores the facts options with --facts" do
expect(device.options).to receive(:[]=).with(:facts,true)
device.handle_facts(true)
end
it "should register ssl OIDs" do
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
device.setup
end
end
describe "during setup" do
before do
allow(device.options).to receive(:[])
Puppet[:libdir] = "/dev/null/lib"
end
it "calls setup_logs" do
expect(device).to receive(:setup_logs)
device.setup
end
describe "when setting up logs" do
before do
allow(Puppet::Util::Log).to receive(:newdestination)
end
it "sets log level to debug if --debug was passed" do
allow(device.options).to receive(:[]).with(:debug).and_return(true)
device.setup_logs
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "sets log level to info if --verbose was passed" do
allow(device.options).to receive(:[]).with(:verbose).and_return(true)
device.setup_logs
expect(Puppet::Util::Log.level).to eq(:info)
end
[:verbose, :debug].each do |level|
it "should set console as the log destination with level #{level}" do
allow(device.options).to receive(:[]).with(level).and_return(true)
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
device.setup_logs
end
end
it "sets a default log destination if no --logdest" do
allow(device.options).to receive(:[]).with(:setdest).and_return(false)
expect(Puppet::Util::Log).to receive(:setup_default)
device.setup_logs
end
end
it "sets a central log destination with --centrallogs" do
allow(device.options).to receive(:[]).with(:centrallogs).and_return(true)
Puppet[:server] = "puppet.example.com"
allow(Puppet::Util::Log).to receive(:newdestination).with(:syslog)
expect(Puppet::Util::Log).to receive(:newdestination).with("puppet.example.com")
device.setup
end
it "uses :main, :agent, :device and :ssl config" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :device, :ssl)
device.setup
end
it "tells the report handler to use REST" do
device.setup
expect(Puppet::Transaction::Report.indirection).to have_received(:terminus_class=).with(:rest)
end
it "defaults the catalog_terminus setting to 'rest'" do
device.initialize_app_defaults
expect(Puppet[:catalog_terminus]).to eq(:rest)
end
it "defaults the node_terminus setting to 'rest'" do
device.initialize_app_defaults
expect(Puppet[:node_terminus]).to eq(:rest)
end
it "has an application default :catalog_cache_terminus setting of 'json'" do
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:json)
device.initialize_app_defaults
device.setup
end
it "tells the catalog cache class based on the :catalog_cache_terminus setting" do
Puppet[:catalog_cache_terminus] = "yaml"
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:yaml)
device.initialize_app_defaults
device.setup
end
it "does not set catalog cache class if :catalog_cache_terminus is explicitly nil" do
Puppet[:catalog_cache_terminus] = nil
expect(Puppet::Resource::Catalog.indirection).not_to receive(:cache_class=)
device.initialize_app_defaults
device.setup
end
it "defaults the facts_terminus setting to 'network_device'" do
device.initialize_app_defaults
expect(Puppet[:facts_terminus]).to eq(:network_device)
end
end
describe "when initializing SSL" do
it "creates a new ssl host" do
allow(device.options).to receive(:[]).with(:waitforcert).and_return(123)
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 123))
end
end
describe "when running" do
let(:device_hash) { {} }
let(:plugin_handler) { instance_double(Puppet::Configurer::PluginHandler, 'plugin_handler') }
before do
allow(device.options).to receive(:[]).with(:fingerprint).and_return(false)
allow(Puppet).to receive(:notice)
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(false)
allow(device.options).to receive(:[]).with(:target).and_return(nil)
allow(device.options).to receive(:[]).with(:apply).and_return(nil)
allow(device.options).to receive(:[]).with(:facts).and_return(false)
allow(device.options).to receive(:[]).with(:resource).and_return(false)
allow(device.options).to receive(:[]).with(:to_yaml).and_return(false)
allow(device.options).to receive(:[]).with(:libdir).and_return(nil)
allow(device.options).to receive(:[]).with(:client)
allow(device.command_line).to receive(:args).and_return([])
allow(Puppet::Util::NetworkDevice::Config).to receive(:devices).and_return(device_hash)
allow(Puppet::Configurer::PluginHandler).to receive(:new).and_return(plugin_handler)
end
it "dispatches to main" do
allow(device).to receive(:main)
device.run_command
end
it "errors if resource is requested without target" do
allow(device.options).to receive(:[]).with(:resource).and_return(true)
expect { device.main }.to raise_error(RuntimeError, "resource command requires target")
end
it "errors if facts is requested without target" do
allow(device.options).to receive(:[]).with(:facts).and_return(true)
expect { device.main }.to raise_error(RuntimeError, "facts command requires target")
end
it "gets the device list" do
expect(Puppet::Util::NetworkDevice::Config).to receive(:devices).and_return(device_hash)
expect { device.main }.to exit_with 1
end
it "errors when an invalid target parameter is passed" do
allow(device.options).to receive(:[]).with(:target).and_return('bla')
expect(Puppet).not_to receive(:info).with(/starting applying configuration to/)
expect { device.main }.to raise_error(RuntimeError, /Target device \/ certificate 'bla' not found in .*\.conf/)
end
it "errors if target is passed and the apply path is incorrect" do
allow(device.options).to receive(:[]).with(:apply).and_return('file.pp')
allow(device.options).to receive(:[]).with(:target).and_return('device1')
expect(File).to receive(:file?).and_return(false)
expect { device.main }.to raise_error(RuntimeError, /does not exist, cannot apply/)
end
it "exits if the device list is empty" do
expect { device.main }.to exit_with 1
end
context 'with some devices configured' do
let(:configurer) { instance_double(Puppet::Configurer, 'configurer') }
let(:device_hash) {
{
"device1" => OpenStruct.new(:name => "device1", :url => "ssh://user:pass@testhost", :provider => "cisco"),
"device2" => OpenStruct.new(:name => "device2", :url => "https://user:pass@testhost/some/path", :provider => "rest"),
}
}
before do
Puppet[:vardir] = make_absolute("/dummy")
Puppet[:confdir] = make_absolute("/dummy")
Puppet[:certname] = "certname"
allow(Puppet).to receive(:[]=)
allow(Puppet.settings).to receive(:use)
allow(device).to receive(:setup_context)
allow(Puppet::Util::NetworkDevice).to receive(:init)
allow(configurer).to receive(:run)
allow(Puppet::Configurer).to receive(:new).and_return(configurer)
allow(Puppet::FileSystem).to receive(:exist?)
allow(Puppet::FileSystem).to receive(:symlink)
allow(Puppet::FileSystem).to receive(:dir_mkpath).and_return(true)
allow(Puppet::FileSystem).to receive(:dir_exist?).and_return(true)
allow(plugin_handler).to receive(:download_plugins)
end
it "sets ssldir relative to the global confdir" do
expect(Puppet).to receive(:[]=).with(:ssldir, make_absolute("/dummy/devices/device1/ssl"))
expect { device.main }.to exit_with 1
end
it "sets vardir to the device vardir" do
expect(Puppet).to receive(:[]=).with(:vardir, make_absolute("/dummy/devices/device1"))
expect { device.main }.to exit_with 1
end
it "sets confdir to the device confdir" do
expect(Puppet).to receive(:[]=).with(:confdir, make_absolute("/dummy/devices/device1"))
expect { device.main }.to exit_with 1
end
it "sets certname to the device certname" do
expect(Puppet).to receive(:[]=).with(:certname, "device1")
expect(Puppet).to receive(:[]=).with(:certname, "device2")
expect { device.main }.to exit_with 1
end
context 'with --target=device1' do
it "symlinks the ssl directory if it doesn't exist" do
allow(device.options).to receive(:[]).with(:target).and_return('device1')
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(Puppet::FileSystem).to receive(:symlink).with(Puppet[:ssldir], File.join(Puppet[:confdir], 'ssl')).and_return(true)
expect { device.main }.to exit_with 1
end
it "creates the device confdir under the global confdir" do
allow(device.options).to receive(:[]).with(:target).and_return('device1')
allow(Puppet::FileSystem).to receive(:dir_exist?).and_return(false)
expect(Puppet::FileSystem).to receive(:dir_mkpath).with(Puppet[:ssldir]).and_return(true)
expect { device.main }.to exit_with 1
end
it "manages the specified target" do
allow(device.options).to receive(:[]).with(:target).and_return('device1')
expect(URI).to receive(:parse).with("ssh://user:pass@testhost")
expect(URI).not_to receive(:parse).with("https://user:pass@testhost/some/path")
expect { device.main }.to exit_with 1
end
end
context 'when running --resource' do
before do
allow(device.options).to receive(:[]).with(:resource).and_return(true)
allow(device.options).to receive(:[]).with(:target).and_return('device1')
end
it "raises an error if no type is given" do
allow(device.command_line).to receive(:args).and_return([])
expect(Puppet).to receive(:log_exception) { |e| expect(e.message).to eq("You must specify the type to display") }
expect { device.main }.to exit_with 1
end
it "raises an error if the type is not found" do
allow(device.command_line).to receive(:args).and_return(['nope'])
expect(Puppet).to receive(:log_exception) { |e| expect(e.message).to eq("Could not find type nope") }
expect { device.main }.to exit_with 1
end
it "retrieves all resources of a type" do
allow(device.command_line).to receive(:args).and_return(['user'])
expect(Puppet::Resource.indirection).to receive(:search).with('user/', {}).and_return([])
expect { device.main }.to exit_with 0
end
it "retrieves named resources of a type" do
resource = Puppet::Type.type(:user).new(:name => "jim").to_resource
allow(device.command_line).to receive(:args).and_return(['user', 'jim'])
expect(Puppet::Resource.indirection).to receive(:find).with('user/jim').and_return(resource)
expect(device).to receive(:puts).with("user { 'jim':\n ensure => 'absent',\n}")
expect { device.main }.to exit_with 0
end
it "outputs resources as YAML" do
resources = [
Puppet::Type.type(:user).new(:name => "title").to_resource,
]
allow(device.options).to receive(:[]).with(:to_yaml).and_return(true)
allow(device.command_line).to receive(:args).and_return(['user'])
expect(Puppet::Resource.indirection).to receive(:search).with('user/', {}).and_return(resources)
expect(device).to receive(:puts).with("---\nuser:\n title:\n ensure: absent\n")
expect { device.main }.to exit_with 0
end
end
context 'when running --facts' do
before do
allow(device.options).to receive(:[]).with(:facts).and_return(true)
allow(device.options).to receive(:[]).with(:target).and_return('device1')
end
it "retrieves facts" do
indirection_fact_values = {"os"=> {"name" => "cisco_ios"},"clientcert"=>"3750"}
indirection_facts = Puppet::Node::Facts.new("nil", indirection_fact_values)
expect(Puppet::Node::Facts.indirection).to receive(:find).with(nil, anything()).and_return(indirection_facts)
expect(device).to receive(:puts).with(/name.*3750.*\n.*values.*\n.*os.*\n.*name.*cisco_ios/)
expect { device.main }.to exit_with 0
end
end
context 'when running in agent mode' do
it "makes sure all the required folders and files are created" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :ssl).twice
expect { device.main }.to exit_with 1
end
it "initializes the device singleton" do
expect(Puppet::Util::NetworkDevice).to receive(:init).with(device_hash["device1"]).ordered
expect(Puppet::Util::NetworkDevice).to receive(:init).with(device_hash["device2"]).ordered
expect { device.main }.to exit_with 1
end
it "retrieves plugins and print the device url scheme, host, and port" do
allow(Puppet).to receive(:info)
expect(plugin_handler).to receive(:download_plugins).twice
expect(Puppet).to receive(:info).with("starting applying configuration to device1 at ssh://testhost")
expect(Puppet).to receive(:info).with("starting applying configuration to device2 at https://testhost:443/some/path")
expect { device.main }.to exit_with 1
end
it "setups the SSL context before pluginsync" do
expect(device).to receive(:setup_context).ordered
expect(plugin_handler).to receive(:download_plugins).ordered
expect(device).to receive(:setup_context).ordered
expect(plugin_handler).to receive(:download_plugins).ordered
expect { device.main }.to exit_with 1
end
it "launches a configurer for this device" do
expect(configurer).to receive(:run).twice
expect { device.main }.to exit_with 1
end
it "exits 1 when configurer raises error" do
expect(configurer).to receive(:run).and_raise(Puppet::Error).ordered
expect(configurer).to receive(:run).and_return(0).ordered
expect { device.main }.to exit_with 1
end
it "exits 0 when run happens without puppet errors but with failed run" do
allow(configurer).to receive(:run).and_return(6, 2)
expect { device.main }.to exit_with 0
end
it "makes the Puppet::Pops::Loaders available" do
expect(configurer).to receive(:run).with({:network_device => true, :pluginsync => false}) do
fail('Loaders not available') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end.and_return(6, 2)
expect { device.main }.to exit_with 0
end
it "exits 2 when --detailed-exitcodes and successful runs" do
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(true)
allow(configurer).to receive(:run).and_return(0, 2)
expect { device.main }.to exit_with 2
end
it "exits 1 when --detailed-exitcodes and failed parse" do
allow(Puppet::Configurer).to receive(:new).and_return(configurer)
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(true)
allow(configurer).to receive(:run).and_return(6, 1)
expect { device.main }.to exit_with 7
end
it "exits 6 when --detailed-exitcodes and failed run" do
allow(Puppet::Configurer).to receive(:new).and_return(configurer)
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(true)
allow(configurer).to receive(:run).and_return(6, 2)
expect { device.main }.to exit_with 6
end
[:vardir, :confdir].each do |setting|
it "resets the #{setting} setting after the run" do
all_devices = Set.new(device_hash.keys.map do |device_name| make_absolute("/dummy/devices/#{device_name}") end)
found_devices = Set.new()
# a block to use in a few places later to validate the updated settings
p = Proc.new do |my_setting, my_value|
expect(all_devices).to include(my_value)
found_devices.add(my_value)
end
all_devices.size.times do
## one occurrence of set / run / set("/dummy") for each device
expect(Puppet).to receive(:[]=, &p).with(setting, anything).ordered
expect(configurer).to receive(:run).ordered
expect(Puppet).to receive(:[]=).with(setting, make_absolute("/dummy")).ordered
end
expect { device.main }.to exit_with 1
expect(found_devices).to eq(all_devices)
end
end
it "resets the certname setting after the run" do
all_devices = Set.new(device_hash.keys)
found_devices = Set.new()
# a block to use in a few places later to validate the updated settings
p = Proc.new do |my_setting, my_value|
expect(all_devices).to include(my_value)
found_devices.add(my_value)
end
allow(Puppet).to receive(:[]=)
all_devices.size.times do
## one occurrence of set / run / set("certname") for each device
expect(Puppet).to receive(:[]=, &p).with(:certname, anything).ordered
expect(configurer).to receive(:run).ordered
expect(Puppet).to receive(:[]=).with(:certname, "certname").ordered
end
expect { device.main }.to exit_with 1
# make sure that we were called with each of the defined devices
expect(found_devices).to eq(all_devices)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/apply_spec.rb | spec/unit/application/apply_spec.rb | require 'spec_helper'
require 'puppet/application/apply'
require 'puppet/file_bucket/dipper'
require 'puppet/configurer'
require 'fileutils'
describe Puppet::Application::Apply do
include PuppetSpec::Files
before :each do
@apply = Puppet::Application[:apply]
Puppet[:reports] = "none"
end
[:debug,:loadclasses,:test,:verbose,:use_nodes,:detailed_exitcodes,:catalog].each do |option|
it "should store argument value when calling handle_#{option}" do
expect(@apply.options).to receive(:[]=).with(option, 'arg')
@apply.send("handle_#{option}".to_sym, 'arg')
end
end
it "should handle write_catalog_summary" do
@apply.send(:handle_write_catalog_summary, true)
expect(Puppet[:write_catalog_summary]).to eq(true)
end
it "should set the code to the provided code when :execute is used" do
expect(@apply.options).to receive(:[]=).with(:code, 'arg')
@apply.send("handle_execute".to_sym, 'arg')
end
describe "when applying options" do
it "should set the log destination with --logdest" do
expect(Puppet::Log).to receive(:newdestination).with("console")
@apply.handle_logdest("console")
end
it "should set the setdest options to true" do
expect(@apply.options).to receive(:[]=).with(:setdest,true)
@apply.handle_logdest("console")
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(Puppet::FileBucket::Dipper).to receive(:new)
allow(STDIN).to receive(:read)
allow(Puppet::Transaction::Report.indirection).to receive(:cache_class=)
end
describe "with --test" do
it "should set options[:verbose] to true" do
@apply.setup_test
expect(@apply.options[:verbose]).to eq(true)
end
it "should set options[:show_diff] to true" do
Puppet.settings.override_default(:show_diff, false)
@apply.setup_test
expect(Puppet[:show_diff]).to eq(true)
end
it "should set options[:detailed_exitcodes] to true" do
@apply.setup_test
expect(@apply.options[:detailed_exitcodes]).to eq(true)
end
end
it "should set console as the log destination if logdest option wasn't provided" do
expect(Puppet::Log).to receive(:newdestination).with(:console)
@apply.setup
end
it "sets the log destination if logdest is provided via settings" do
expect(Puppet::Log).to receive(:newdestination).with("set_via_config")
Puppet[:logdest] = "set_via_config"
@apply.setup
end
it "should set INT trap" do
expect(Signal).to receive(:trap).with(:INT)
@apply.setup
end
it "should set log level to debug if --debug was passed" do
@apply.options[:debug] = true
@apply.setup
expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@apply.options[:verbose] = true
@apply.setup
expect(Puppet::Log.level).to eq(:info)
end
it "should print puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect(Puppet.settings).to receive(:print_configs).and_return(true)
expect { @apply.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect { @apply.setup }.to exit_with 1
end
it "should use :main, :puppetd, and :ssl" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :ssl)
@apply.setup
end
it "should tell the report handler to cache locally as yaml" do
expect(Puppet::Transaction::Report.indirection).to receive(:cache_class=).with(:yaml)
@apply.setup
end
it "configures a profiler when profiling is enabled" do
Puppet[:profile] = true
@apply.setup
expect(Puppet::Util::Profiler.current).to satisfy do |ps|
ps.any? {|p| p.is_a? Puppet::Util::Profiler::WallClock }
end
end
it "does not have a profiler if profiling is disabled" do
Puppet[:profile] = false
@apply.setup
expect(Puppet::Util::Profiler.current.length).to be 0
end
it "should set default_file_terminus to `file_server` to be local" do
expect(@apply.app_defaults[:default_file_terminus]).to eq(:file_server)
end
end
describe "when executing" do
it "should dispatch to 'apply' if it was called with a catalog" do
@apply.options[:catalog] = "foo"
expect(@apply).to receive(:apply)
@apply.run_command
end
it "should dispatch to main otherwise" do
allow(@apply).to receive(:options).and_return({})
expect(@apply).to receive(:main)
@apply.run_command
end
describe "the main command" do
before :each do
Puppet[:prerun_command] = ''
Puppet[:postrun_command] = ''
Puppet::Node.indirection.terminus_class = :memory
Puppet::Node.indirection.cache_class = :memory
facts = Puppet::Node::Facts.new(Puppet[:node_name_value])
Puppet::Node::Facts.indirection.save(facts)
@node = Puppet::Node.new(Puppet[:node_name_value])
Puppet::Node.indirection.save(@node)
@catalog = Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment]))
allow(@catalog).to receive(:to_ral).and_return(@catalog)
allow(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog)
allow(STDIN).to receive(:read)
@transaction = double('transaction')
allow(@catalog).to receive(:apply).and_return(@transaction)
allow(Puppet::Util::Storage).to receive(:load)
allow_any_instance_of(Puppet::Configurer).to receive(:save_last_run_summary) # to prevent it from trying to write files
end
after :each do
Puppet::Node::Facts.indirection.reset_terminus_class
Puppet::Node::Facts.indirection.cache_class = nil
end
around :each do |example|
Puppet.override(:current_environment =>
Puppet::Node::Environment.create(:production, [])) do
example.run
end
end
it "should set the code to run from --code" do
@apply.options[:code] = "code to run"
expect(Puppet).to receive(:[]=).with(:code,"code to run")
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should set the code to run from STDIN if no arguments" do
@apply.command_line.args = []
allow(STDIN).to receive(:read).and_return("code to run")
expect(Puppet).to receive(:[]=).with(:code,"code to run")
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should raise an error if a file is passed on command line and the file does not exist" do
noexist = tmpfile('noexist.pp')
@apply.command_line.args << noexist
expect {
@apply.run
}.to exit_with(1)
.and output(anything).to_stdout
.and output(/Could not find file #{noexist}/).to_stderr
end
it "should set the manifest to the first file and warn other files will be skipped" do
manifest = tmpfile('starwarsIV')
FileUtils.touch(manifest)
@apply.command_line.args << manifest << 'starwarsI' << 'starwarsII'
expect {
@apply.run
}.to exit_with(0)
.and output(anything).to_stdout
.and output(/Warning: Only one file can be applied per run. Skipping starwarsI, starwarsII/).to_stderr
end
it "should splay" do
expect(@apply).to receive(:splay)
expect {
@apply.run
}.to exit_with(0).and output(anything).to_stdout
end
it "should exit with 1 if we can't find the node" do
expect(Puppet::Node.indirection).to receive(:find).and_return(nil)
expect { @apply.run }.to exit_with(1).and output(/Could not find node/).to_stderr
end
it "should load custom classes if loadclasses" do
@apply.options[:loadclasses] = true
classfile = tmpfile('classfile')
File.open(classfile, 'w') { |c| c.puts 'class' }
Puppet[:classfile] = classfile
expect(@node).to receive(:classes=).with(['class'])
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should compile the catalog" do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it 'should called the DeferredResolver to resolve any Deferred values' do
expect(Puppet::Pops::Evaluator::DeferredResolver).to receive(:resolve_and_replace).with(any_args)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it 'should make the Puppet::Pops::Loaders available when applying the compiled catalog' do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog)
expect(@apply).to receive(:apply_catalog) do |catalog|
expect(@catalog).to eq(@catalog)
fail('Loaders not found') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end.and_return(0)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should transform the catalog to ral" do
expect(@catalog).to receive(:to_ral).and_return(@catalog)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should finalize the catalog" do
expect(@catalog).to receive(:finalize)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should not save the classes or resource file by default" do
expect(@catalog).not_to receive(:write_class_file)
expect(@catalog).not_to receive(:write_resource_file)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the classes and resources files when requested on the command line using dashes" do
expect(@catalog).to receive(:write_class_file).once
expect(@catalog).to receive(:write_resource_file).once
# dashes are parsed by the application's OptionParser
@apply.command_line.args = ['--write-catalog-summary']
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the classes and resources files when requested on the command line using underscores" do
expect(@catalog).to receive(:write_class_file).once
expect(@catalog).to receive(:write_resource_file).once
# underscores are parsed by the settings PuppetOptionParser
@apply.command_line.args = ['--write_catalog_summary']
Puppet.initialize_settings(['--write_catalog_summary'])
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the classes and resources files when specified as a setting" do
Puppet[:write_catalog_summary] = true
expect(@catalog).to receive(:write_class_file).once
expect(@catalog).to receive(:write_resource_file).once
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should call the prerun and postrun commands on a Configurer instance" do
expect_any_instance_of(Puppet::Configurer).to receive(:execute_prerun_command).and_return(true)
expect_any_instance_of(Puppet::Configurer).to receive(:execute_postrun_command).and_return(true)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should apply the catalog" do
expect(@catalog).to receive(:apply).and_return(double('transaction'))
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the last run summary" do
Puppet[:noop] = false
report = Puppet::Transaction::Report.new
allow(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect_any_instance_of(Puppet::Configurer).to receive(:save_last_run_summary).with(report)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
describe "when using node_name_fact" do
before :each do
@facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(@facts)
@node = Puppet::Node.new('other_node_name')
Puppet::Node.indirection.save(@node)
Puppet[:node_name_fact] = 'my_name_fact'
end
it "should set the facts name based on the node_name_fact" do
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
expect(@facts.name).to eq('other_node_name')
end
it "should set the node_name_value based on the node_name_fact" do
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
expect(Puppet[:node_name_value]).to eq('other_node_name')
end
it "should merge in our node the loaded facts" do
@facts.values.merge!('key' => 'value')
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
expect(@node.parameters['key']).to eq('value')
end
it "should exit if we can't find the facts" do
expect(Puppet::Node::Facts.indirection).to receive(:find).and_return(nil)
expect { @apply.run }.to exit_with(1).and output(/Could not find facts/).to_stderr
end
end
describe "with detailed_exitcodes" do
before :each do
@apply.options[:detailed_exitcodes] = true
end
it "should exit with report's computed exit status" do
Puppet[:noop] = false
allow_any_instance_of(Puppet::Transaction::Report).to receive(:exit_status).and_return(666)
expect { @apply.run }.to exit_with(666).and output(anything).to_stdout
end
it "should exit with report's computed exit status, even if --noop is set" do
Puppet[:noop] = true
allow_any_instance_of(Puppet::Transaction::Report).to receive(:exit_status).and_return(666)
expect { @apply.run }.to exit_with(666).and output(anything).to_stdout
end
it "should always exit with 0 if option is disabled" do
Puppet[:noop] = false
report = double('report', :exit_status => 666)
allow(@transaction).to receive(:report).and_return(report)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should always exit with 0 if --noop" do
Puppet[:noop] = true
report = double('report', :exit_status => 666)
allow(@transaction).to receive(:report).and_return(report)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
end
end
describe "the 'apply' command" do
# We want this memoized, and to be able to adjust the content, so we
# have to do it ourselves.
def temporary_catalog(content = '"something"')
@tempfile = Tempfile.new('catalog.json')
@tempfile.write(content)
@tempfile.close
@tempfile.path
end
let(:default_format) { Puppet::Resource::Catalog.default_format }
it "should read the catalog in from disk if a file name is provided" do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(default_format, '"something"').and_return(catalog)
@apply.apply
end
it "should read the catalog in from stdin if '-' is provided" do
@apply.options[:catalog] = "-"
expect($stdin).to receive(:read).and_return('"something"')
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(default_format, '"something"').and_return(catalog)
@apply.apply
end
it "should deserialize the catalog from the default format" do
@apply.options[:catalog] = temporary_catalog
allow(Puppet::Resource::Catalog).to receive(:default_format).and_return(:rot13_piglatin)
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(:rot13_piglatin,'"something"').and_return(catalog)
@apply.apply
end
it "should fail helpfully if deserializing fails" do
@apply.options[:catalog] = temporary_catalog('something syntactically invalid')
expect { @apply.apply }.to raise_error(Puppet::Error)
end
it "should convert the catalog to a RAL catalog and use a Configurer instance to apply it" do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(default_format, '"something"').and_return(catalog)
expect(catalog).to receive(:to_ral).and_return("mycatalog")
configurer = double('configurer')
expect(Puppet::Configurer).to receive(:new).and_return(configurer)
expect(configurer).to receive(:run).
with(:catalog => "mycatalog", :pluginsync => false)
@apply.apply
end
it 'should make the Puppet::Pops::Loaders available when applying a catalog' do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
expect(@apply).to receive(:read_catalog) do |arg|
expect(arg).to eq('"something"')
fail('Loaders not found') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end.and_return(catalog)
expect(@apply).to receive(:apply_catalog) do |cat|
expect(cat).to eq(catalog)
fail('Loaders not found') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end
expect { @apply.apply }.not_to raise_error
end
it "should call the DeferredResolver to resolve Deferred values" do
@apply.options[:catalog] = temporary_catalog
allow(Puppet::Resource::Catalog).to receive(:default_format).and_return(:rot13_piglatin)
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(:rot13_piglatin, '"something"').and_return(catalog)
expect(Puppet::Pops::Evaluator::DeferredResolver).to receive(:resolve_and_replace).with(any_args)
@apply.apply
end
end
end
describe "when really executing" do
let(:testfile) { tmpfile('secret_file_name') }
let(:resourcefile) { tmpfile('resourcefile') }
let(:classfile) { tmpfile('classfile') }
it "should not expose sensitive data in the relationship file" do
@apply.options[:code] = <<-CODE
$secret = Sensitive('cat #{testfile}')
exec { 'do it':
command => $secret,
path => '/bin/'
}
CODE
Puppet.settings[:write_catalog_summary] = true
Puppet.settings[:resourcefile] = resourcefile
Puppet.settings[:classfile] = classfile
#We don't actually need the resource to do anything, we are using it's properties in other parts of the workflow.
allow_any_instance_of(Puppet::Type.type(:exec).defaultprovider).to receive(:which).and_return('cat')
allow(Puppet::Util::Execution).to receive(:execute).and_return(double(exitstatus: 0, output: ''))
expect { @apply.run }.to exit_with(0).and output(%r{Exec\[do it\]/returns: executed successfully}).to_stdout
result = File.read(resourcefile)
expect(result).not_to match(/secret_file_name/)
expect(result).to match(/do it/)
end
end
describe "apply_catalog" do
it "should call the configurer with the catalog" do
catalog = "I am a catalog"
expect_any_instance_of(Puppet::Configurer).to receive(:run).
with(:catalog => catalog, :pluginsync => false)
@apply.send(:apply_catalog, catalog)
end
end
it "should honor the catalog_cache_terminus setting" do
Puppet.settings[:catalog_cache_terminus] = "json"
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:json)
@apply.initialize_app_defaults
@apply.setup
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/filebucket_spec.rb | spec/unit/application/filebucket_spec.rb | require 'spec_helper'
require 'puppet/application/filebucket'
require 'puppet/file_bucket/dipper'
describe Puppet::Application::Filebucket do
before :each do
@filebucket = Puppet::Application[:filebucket]
end
it "should declare a get command" do
expect(@filebucket).to respond_to(:get)
end
it "should declare a backup command" do
expect(@filebucket).to respond_to(:backup)
end
it "should declare a restore command" do
expect(@filebucket).to respond_to(:restore)
end
it "should declare a diff command" do
expect(@filebucket).to respond_to(:diff)
end
it "should declare a list command" do
expect(@filebucket).to respond_to(:list)
end
[:bucket, :debug, :local, :remote, :verbose, :fromdate, :todate].each do |option|
it "should declare handle_#{option} method" do
expect(@filebucket).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
expect(@filebucket.options).to receive(:[]=).with("#{option}".to_sym, 'arg')
@filebucket.send("handle_#{option}".to_sym, 'arg')
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(Puppet::FileBucket::Dipper).to receive(:new)
allow(@filebucket.options).to receive(:[])
end
it "should set console as the log destination" do
expect(Puppet::Log).to receive(:newdestination).with(:console)
@filebucket.setup
end
it "should trap INT" do
expect(Signal).to receive(:trap).with(:INT)
@filebucket.setup
end
it "should set log level to debug if --debug was passed" do
allow(@filebucket.options).to receive(:[]).with(:debug).and_return(true)
@filebucket.setup
expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
allow(@filebucket.options).to receive(:[]).with(:verbose).and_return(true)
@filebucket.setup
expect(Puppet::Log.level).to eq(:info)
end
it "should print puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect(Puppet.settings).to receive(:print_configs).and_return(true)
expect { @filebucket.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect { @filebucket.setup }.to exit_with 1
end
describe "with local bucket" do
let(:path) { File.expand_path("path") }
before :each do
allow(@filebucket.options).to receive(:[]).with(:local).and_return(true)
end
it "should create a client with the default bucket if none passed" do
Puppet[:clientbucketdir] = path
Puppet[:bucketdir] = path + "2"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Path: path))
@filebucket.setup
end
it "should create a local Dipper with the given bucket" do
allow(@filebucket.options).to receive(:[]).with(:bucket).and_return(path)
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Path: path))
@filebucket.setup
end
end
describe "with remote bucket" do
it "should create a remote Client to the configured server" do
Puppet[:server] = "puppet.reductivelabs.com"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "puppet.reductivelabs.com"))
@filebucket.setup
end
it "should default to the first good server_list entry if server_list is set" do
stub_request(:get, "https://foo:8140/status/v1/simple/server").to_return(status: 200)
Puppet[:server_list] = "foo,bar,baz"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "foo"))
@filebucket.setup
end
it "should walk server_list until it finds a good entry" do
stub_request(:get, "https://foo:8140/status/v1/simple/server").to_return(status: 502)
stub_request(:get, "https://bar:8140/status/v1/simple/server").to_return(status: 200)
Puppet[:server_list] = "foo,bar,baz"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "bar"))
@filebucket.setup
end
# FileBucket catches any exceptions raised, logs them, then just exits
it "raises an error if there are no functional servers in server_list" do
stub_request(:get, "https://foo:8140/status/v1/simple/server").to_return(status: 404)
stub_request(:get, "https://bar:8140/status/v1/simple/server").to_return(status: 404)
stub_request(:get, "https://foo:8140/status/v1/simple/master").to_return(status: 404)
stub_request(:get, "https://bar:8140/status/v1/simple/master").to_return(status: 404)
Puppet[:server] = 'horacio'
Puppet[:server_list] = "foo,bar"
expect{@filebucket.setup}.to exit_with(1)
end
it "should fall back to server if server_list is empty" do
Puppet[:server_list] = ""
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "puppet"))
@filebucket.setup
end
it "should take both the server and port specified in server_list" do
stub_request(:get, "https://foo:632/status/v1/simple/server").to_return(status: 200)
Puppet[:server_list] = "foo:632,bar:6215,baz:351"
expect(Puppet::FileBucket::Dipper).to receive(:new).with({ :Server => "foo", :Port => 632 })
@filebucket.setup
end
end
end
describe "when running" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(Puppet::FileBucket::Dipper).to receive(:new)
allow(@filebucket.options).to receive(:[])
@client = double('client')
allow(Puppet::FileBucket::Dipper).to receive(:new).and_return(@client)
@filebucket.setup
end
it "should use the first non-option parameter as the dispatch" do
allow(@filebucket.command_line).to receive(:args).and_return(['get'])
expect(@filebucket).to receive(:get)
@filebucket.run_command
end
describe "the command get" do
before :each do
allow(@filebucket).to receive(:print)
allow(@filebucket).to receive(:args).and_return([])
end
it "should call the client getfile method" do
expect(@client).to receive(:getfile)
@filebucket.get
end
it "should call the client getfile method with the given digest" do
digest = 'DEADBEEF'
allow(@filebucket).to receive(:args).and_return([digest])
expect(@client).to receive(:getfile).with(digest)
@filebucket.get
end
it "should print the file content" do
allow(@client).to receive(:getfile).and_return("content")
expect(@filebucket).to receive(:print).and_return("content")
@filebucket.get
end
end
describe "the command backup" do
it "should fail if no arguments are specified" do
allow(@filebucket).to receive(:args).and_return([])
expect { @filebucket.backup }.to raise_error(RuntimeError, /You must specify a file to back up/)
end
it "should call the client backup method for each given parameter" do
allow(@filebucket).to receive(:puts)
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(FileTest).to receive(:readable?).and_return(true)
allow(@filebucket).to receive(:args).and_return(["file1", "file2"])
expect(@client).to receive(:backup).with("file1")
expect(@client).to receive(:backup).with("file2")
@filebucket.backup
end
end
describe "the command restore" do
it "should call the client getfile method with the given digest" do
digest = 'DEADBEEF'
file = 'testfile'
allow(@filebucket).to receive(:args).and_return([file, digest])
expect(@client).to receive(:restore).with(file, digest)
@filebucket.restore
end
end
describe "the command diff" do
it "should call the client diff method with 2 given checksums" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(digest_a, digest_b, nil, nil)
@filebucket.diff
end
it "should call the client diff with a path if the second argument is a file" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).with(digest_a).and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with(digest_b).and_return(true)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(digest_a, nil, nil, digest_b)
@filebucket.diff
end
it "should call the client diff with a path if the first argument is a file" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).with(digest_a).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(digest_b).and_return(false)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(nil, digest_b, digest_a, nil)
@filebucket.diff
end
it "should call the clien diff with paths if the both arguments are files" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).with(digest_a).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(digest_b).and_return(true)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(nil, nil, digest_a, digest_b)
@filebucket.diff
end
it "should fail if only one checksum is given" do
digest_a = 'DEADBEEF'
allow(@filebucket).to receive(:args).and_return([digest_a])
expect { @filebucket.diff }.to raise_error Puppet::Error
end
end
describe "the command list" do
it "should call the client list method with nil dates" do
expect(@client).to receive(:list).with(nil, nil)
@filebucket.list
end
it "should call the client list method with the given dates" do
# 3 Hours ago
threehours = 60*60*3
fromdate = (Time.now - threehours).strftime("%F %T")
# 1 Hour ago
onehour = 60*60
todate = (Time.now - onehour).strftime("%F %T")
allow(@filebucket.options).to receive(:[]).with(:fromdate).and_return(fromdate)
allow(@filebucket.options).to receive(:[]).with(:todate).and_return(todate)
expect(@client).to receive(:list).with(fromdate, todate)
@filebucket.list
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/indirection_base_spec.rb | spec/unit/application/indirection_base_spec.rb | require 'spec_helper'
require 'puppet/util/command_line'
require 'puppet/application/indirection_base'
require 'puppet/indirector/face'
########################################################################
# Stub for testing; the names are critical, sadly. --daniel 2011-03-30
class Puppet::Application::TestIndirection < Puppet::Application::IndirectionBase
end
########################################################################
describe Puppet::Application::IndirectionBase do
before :all do
@face = Puppet::Indirector::Face.define(:test_indirection, '0.0.1') do
summary "fake summary"
copyright "Puppet Labs", 2011
license "Apache 2 license; see COPYING"
end
# REVISIT: This horror is required because we don't allow anything to be
# :current except for if it lives on, and is loaded from, disk. --daniel 2011-03-29
@face.instance_variable_set('@version', :current)
Puppet::Face.register(@face)
end
after :all do
# Delete the face so that it doesn't interfere with other specs
Puppet::Interface::FaceCollection.instance_variable_get(:@faces).delete Puppet::Interface::FaceCollection.underscorize(@face.name)
end
it "should accept a terminus command line option" do
# It would be nice not to have to stub this, but whatever... writing an
# entire indirection stack would cause us more grief. --daniel 2011-03-31
terminus = double("test indirection terminus")
allow(terminus).to receive(:name).and_return(:test_indirection)
allow(terminus).to receive(:terminus_class=)
allow(terminus).to receive(:save)
allow(terminus).to receive(:reset_terminus_class)
expect(Puppet::Indirector::Indirection).to receive(:instance).
with(:test_indirection).and_return(terminus)
command_line = Puppet::Util::CommandLine.new("puppet", %w{test_indirection --terminus foo save bar})
application = Puppet::Application::TestIndirection.new(command_line)
expect {
application.run
}.to exit_with 0
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/describe_spec.rb | spec/unit/application/describe_spec.rb | require 'spec_helper'
require 'puppet/application/describe'
describe Puppet::Application::Describe do
let(:describe) { Puppet::Application[:describe] }
it "lists all types" do
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/These are the types known to puppet:/).to_stdout
end
it "describes a single type" do
describe.command_line.args << 'exec'
expect {
describe.run
}.to output(/exec.*====.*Executes external commands/m).to_stdout
end
it "describes multiple types" do
describe.command_line.args.concat(['exec', 'file'])
expect {
describe.run
}.to output(/Executes external commands.*Manages files, including their content, ownership, and permissions./m).to_stdout
end
it "describes parameters for the type by default" do
describe.command_line.args << 'exec'
expect {
describe.run
}.to output(/Parameters\n----------/m).to_stdout
end
it "lists parameter names, but excludes description in short mode" do
describe.command_line.args.concat(['exec', '-s'])
expect {
describe.run
}.to output(/Parameters.*command, creates, cwd/m).to_stdout
end
it "outputs providers for the type" do
describe.command_line.args.concat(['exec', '--providers'])
expect {
describe.run
}.to output(/Providers.*#{Regexp.escape('**posix**')}.*#{Regexp.escape('**windows**')}/m).to_stdout
end
it "lists metaparameters for a type" do
describe.command_line.args.concat(['exec', '--meta'])
expect {
describe.run
}.to output(/Meta Parameters.*#{Regexp.escape('**notify**')}/m).to_stdout
end
it "outputs no documentation if the summary is missing" do
Puppet::Type.newtype(:describe_test) {}
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - .. no documentation ..")}/).to_stdout
end
it "outputs the first short sentence ending in a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "ends in a dot."
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - ends in a dot\n")}/).to_stdout
end
it "outputs the first short sentence missing a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "missing a dot"
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/describe_test - missing a dot\n/).to_stdout
end
it "truncates long summaries ending in a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "This sentence is more than 45 characters and ends in a dot."
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - This sentence is more than 45 characters and ...")}/).to_stdout
end
it "truncates long summaries missing a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "This sentence is more than 45 characters and is missing a dot"
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - This sentence is more than 45 characters and ...")}/).to_stdout
end
it "formats text with long non-space runs without garbling" do
f = Formatter.new(76)
teststring = <<TESTSTRING
. 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 nick@magpie.puppetlabs.lan
**this part should not repeat!**
TESTSTRING
expected_result = <<EXPECTED
.
1234567890123456789012345678901234567890123456789012345678901234567890123456
7890123456789012345678901234567890 nick@magpie.puppetlabs.lan
**this part should not repeat!**
EXPECTED
result = f.wrap(teststring, {:indent => 0, :scrub => true})
expect(result).to eql(expected_result)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/facts_spec.rb | spec/unit/application/facts_spec.rb | require 'spec_helper'
require 'puppet/application/facts'
describe Puppet::Application::Facts do
let(:app) { Puppet::Application[:facts] }
let(:values) { {"filesystems" => "apfs,autofs,devfs", "macaddress" => "64:52:11:22:03:2e"} }
before :each do
Puppet::Node::Facts.indirection.terminus_class = :memory
end
it "returns facts for a given node" do
facts = Puppet::Node::Facts.new('whatever', values)
Puppet::Node::Facts.indirection.save(facts)
app.command_line.args = %w{find whatever --render-as yaml}
# due to PUP-10105 we emit the class tag when we shouldn't
expected = Regexp.new(<<~END)
--- !ruby/object:Puppet::Node::Facts
name: whatever
values:
filesystems: apfs,autofs,devfs
macaddress: "64:52:11:22:03:2e"
END
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
end
it "returns facts for the current node when the name is omitted" do
facts = Puppet::Node::Facts.new(Puppet[:certname], values)
Puppet::Node::Facts.indirection.save(facts)
app.command_line.args = %w{find --render-as yaml}
# due to PUP-10105 we emit the class tag when we shouldn't
expected = Regexp.new(<<~END)
--- !ruby/object:Puppet::Node::Facts
name: #{Puppet[:certname]}
values:
filesystems: apfs,autofs,devfs
macaddress: "64:52:11:22:03:2e"
END
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
end
context 'when show action is called' do
let(:expected) { <<~END }
{
"filesystems": "apfs,autofs,devfs",
"macaddress": "64:52:11:22:03:2e"
}
END
before :each do
Puppet::Node::Facts.indirection.terminus_class = :facter
allow(Facter).to receive(:resolve).and_return(values)
app.command_line.args = %w{show}
end
it 'correctly displays facts with default formatting' do
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
end
it 'displays a single fact value' do
app.command_line.args << 'filesystems' << '--value-only'
expect {
app.run
}.to exit_with(0)
.and output("apfs,autofs,devfs\n").to_stdout
end
it "warns and ignores value-only when multiple fact names are specified" do
app.command_line.args << 'filesystems' << 'macaddress' << '--value-only'
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
.and output(/it can only be used when querying for a single fact/).to_stderr
end
{
"type_hash" => [{'a' => 2}, "{\n \"a\": 2\n}"],
"type_empty_hash" => [{}, "{\n}"],
"type_array" => [[], "[\n\n]"],
"type_string" => ["str", "str"],
"type_int" => [1, "1"],
"type_float" => [1.0, "1.0"],
"type_true" => [true, "true"],
"type_false" => [false, "false"],
"type_nil" => [nil, ""],
"type_sym" => [:sym, "sym"]
}.each_pair do |name, values|
it "renders '#{name}' as '#{values.last}'" do
fact_value = values.first
fact_output = values.last
allow(Facter).to receive(:resolve).and_return({name => fact_value})
app.command_line.args << name << '--value-only'
expect {
app.run
}.to exit_with(0)
.and output("#{fact_output}\n").to_stdout
end
end
end
context 'when default action is called' do
let(:expected) { <<~END }
---
filesystems: apfs,autofs,devfs
macaddress: 64:52:11:22:03:2e
END
before :each do
Puppet::Node::Facts.indirection.terminus_class = :facter
allow(Facter).to receive(:resolve).and_return(values)
app.command_line.args = %w{--render-as yaml}
end
it 'calls show action' do
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
expect(app.action.name).to eq(:show)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/ssl_spec.rb | spec/unit/application/ssl_spec.rb | require 'spec_helper'
require 'puppet/application/ssl'
require 'openssl'
require 'puppet/test_ca'
describe Puppet::Application::Ssl, unless: Puppet::Util::Platform.jruby? do
include PuppetSpec::Files
let(:ssl) do
app = Puppet::Application[:ssl]
app.options[:verbose] = true
app.setup_logs
app
end
let(:name) { 'ssl-client' }
before :all do
@ca = Puppet::TestCa.new
@ca_cert = @ca.ca_cert
@crl = @ca.ca_crl
@host = @ca.generate('ssl-client', {})
end
before do
Puppet.settings.use(:main)
Puppet[:certname] = name
Puppet[:vardir] = tmpdir("ssl_testing")
# Host assumes ca cert and crl are present
File.write(Puppet[:localcacert], @ca_cert.to_pem)
File.write(Puppet[:hostcrl], @crl.to_pem)
# Setup our ssl client
File.write(Puppet[:hostprivkey], @host[:private_key].to_pem)
File.write(Puppet[:hostpubkey], @host[:private_key].public_key.to_pem)
end
def expects_command_to_pass(expected_output = nil)
expect {
ssl.run_command
}.to output(expected_output).to_stdout
end
def expects_command_to_fail(message)
expect {
expect {
ssl.run_command
}.to raise_error(Puppet::Error, message)
}.to output(/.*/).to_stdout
end
shared_examples_for 'an ssl action' do
it 'downloads the CA bundle first when missing' do
File.delete(Puppet[:localcacert])
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: @ca.ca_cert.to_pem)
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass
expect(File.read(Puppet[:localcacert])).to eq(@ca.ca_cert.to_pem)
end
it 'downloads the CRL bundle first when missing' do
File.delete(Puppet[:hostcrl])
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: @crl.to_pem)
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass
expect(File.read(Puppet[:hostcrl])).to eq(@crl.to_pem)
end
end
it 'uses the agent run mode' do
# make sure the ssl app resolves certname, server, etc
# the same way the agent application does
expect(ssl.class.run_mode.name).to eq(:agent)
end
context 'when generating help' do
it 'prints a message when an unknown action is specified' do
ssl.command_line.args << 'whoops'
expects_command_to_fail(/Unknown action 'whoops'/)
end
it 'prints a message requiring an action to be specified' do
expects_command_to_fail(/An action must be specified/)
end
end
context 'when submitting a CSR' do
let(:csr_path) { Puppet[:hostcsr] }
before do
ssl.command_line.args << 'submit_request'
end
it_behaves_like 'an ssl action'
it 'generates an RSA private key' do
File.unlink(Puppet[:hostprivkey])
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
end
it 'generates an EC private key' do
Puppet[:key_type] = 'ec'
File.unlink(Puppet[:hostprivkey])
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
end
it 'registers OIDs' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
end
it 'submits the CSR and saves it locally' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
expect(Puppet::FileSystem).to be_exist(csr_path)
end
it 'detects when a CSR with the same public key has already been submitted' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass
end
it 'downloads the certificate when autosigning is enabled' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
expect(Puppet::FileSystem).to be_exist(Puppet[:hostcert])
expect(Puppet::FileSystem).to_not be_exist(csr_path)
end
it 'accepts dns alt names' do
Puppet[:dns_alt_names] = 'majortom'
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass
csr = Puppet::SSL::CertificateRequest.new(name)
csr.read(csr_path)
expect(csr.subject_alt_names).to include('DNS:majortom')
end
end
context 'when generating a CSR' do
let(:csr_path) { Puppet[:hostcsr] }
let(:requestdir) { Puppet[:requestdir] }
before do
ssl.command_line.args << 'generate_request'
end
it 'generates an RSA private key' do
File.unlink(Puppet[:hostprivkey])
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
end
it 'generates an EC private key' do
Puppet[:key_type] = 'ec'
File.unlink(Puppet[:hostprivkey])
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
end
it 'registers OIDs' do
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
end
it 'saves the CSR locally' do
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
expect(Puppet::FileSystem).to be_exist(csr_path)
end
it 'accepts dns alt names' do
Puppet[:dns_alt_names] = 'majortom'
expects_command_to_pass
csr = Puppet::SSL::CertificateRequest.new(name)
csr.read(csr_path)
expect(csr.subject_alt_names).to include('DNS:majortom')
end
end
context 'when downloading a certificate' do
before do
ssl.command_line.args << 'download_cert'
end
it_behaves_like 'an ssl action'
it 'downloads a new cert' do
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass(%r{Downloaded certificate '#{name}' with fingerprint .*})
expect(File.read(Puppet[:hostcert])).to eq(@host[:cert].to_pem)
end
it 'overwrites an existing cert' do
File.write(Puppet[:hostcert], "existing certificate")
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass(%r{Downloaded certificate '#{name}' with fingerprint .*})
expect(File.read(Puppet[:hostcert])).to eq(@host[:cert].to_pem)
end
it "reports an error if the downloaded cert's public key doesn't match our private key" do
File.write(Puppet[:hostcert], "existing cert")
# generate a new host key, whose public key doesn't match the cert
private_key = OpenSSL::PKey::RSA.new(512)
File.write(Puppet[:hostprivkey], private_key.to_pem)
File.write(Puppet[:hostpubkey], private_key.public_key.to_pem)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_fail(
%r{^Failed to download certificate: The certificate for 'CN=ssl-client' does not match its private key}
)
end
it "prints a message if there isn't a cert to download" do
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_fail(/The certificate for '#{name}' has not yet been signed/)
end
end
context 'when verifying' do
before do
ssl.command_line.args << 'verify'
File.write(Puppet[:hostcert], @host[:cert].to_pem)
end
it 'reports if the key is missing' do
File.delete(Puppet[:hostprivkey])
expects_command_to_fail(/The private key is missing from/)
end
it 'reports if the cert is missing' do
File.delete(Puppet[:hostcert])
expects_command_to_fail(/The client certificate is missing from/)
end
it 'reports if the key and cert are mismatched' do
# generate new keys
private_key = OpenSSL::PKey::RSA.new(512)
public_key = private_key.public_key
File.write(Puppet[:hostprivkey], private_key.to_pem)
File.write(Puppet[:hostpubkey], public_key.to_pem)
expects_command_to_fail(%r{The certificate for 'CN=ssl-client' does not match its private key})
end
it 'reports if the cert verification fails' do
# generate a new CA to force an error
new_ca = Puppet::TestCa.new
File.write(Puppet[:localcacert], new_ca.ca_cert.to_pem)
# and CRL for that CA
File.write(Puppet[:hostcrl], new_ca.ca_crl.to_pem)
expects_command_to_fail(%r{Invalid signature for certificate 'CN=ssl-client'})
end
it 'reports when verification succeeds' do
expects_command_to_pass(%r{Verified client certificate 'CN=ssl-client' fingerprint})
end
it 'reports when verification succeeds with a password protected private key' do
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), Puppet[:hostprivkey])
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'signed.pem'), Puppet[:hostcert])
# To verify the client cert we need the root and intermediate certs and crls.
# We don't need to do this with `ssl-client` cert above, because it is issued
# directly from the generated TestCa above.
File.open(Puppet[:localcacert], 'w') do |f|
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'ca.pem')))
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'intermediate.pem')))
end
File.open(Puppet[:hostcrl], 'w') do |f|
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'crl.pem')))
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'intermediate-crl.pem')))
end
Puppet[:passfile] = file_containing('passfile', '74695716c8b6')
expects_command_to_pass(%r{Verified client certificate 'CN=signed' fingerprint})
end
it 'reports if the private key password is incorrect' do
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), Puppet[:hostprivkey])
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'signed.pem'), Puppet[:hostcert])
Puppet[:passfile] = file_containing('passfile', 'wrongpassword')
expects_command_to_fail(/Failed to load private key for host 'ssl-client'/)
end
end
context 'when cleaning' do
before do
ssl.command_line.args << 'clean'
end
it 'deletes the hostcert' do
File.write(Puppet[:hostcert], @host[:cert].to_pem)
expects_command_to_pass(%r{Removed certificate #{Puppet[:cert]}})
end
it 'deletes the private key' do
File.write(Puppet[:hostprivkey], @host[:private_key].to_pem)
expects_command_to_pass(%r{Removed private key #{Puppet[:hostprivkey]}})
end
it 'deletes the public key' do
File.write(Puppet[:hostpubkey], @host[:private_key].public_key.to_pem)
expects_command_to_pass(%r{Removed public key #{Puppet[:hostpubkey]}})
end
it 'deletes the request' do
path = Puppet[:hostcsr]
File.write(path, @host[:csr].to_pem)
expects_command_to_pass(%r{Removed certificate request #{path}})
end
it 'deletes the passfile' do
FileUtils.touch(Puppet[:passfile])
expects_command_to_pass(%r{Removed private key password file #{Puppet[:passfile]}})
end
it 'skips files that do not exist' do
File.delete(Puppet[:hostprivkey])
expect {
ssl.run_command
}.to_not output(%r{Removed private key #{Puppet[:hostprivkey]}}).to_stdout
end
it "raises if we fail to retrieve server's cert that we're about to clean" do
Puppet[:certname] = name
Puppet[:server] = name
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_raise(Errno::ECONNREFUSED)
expects_command_to_fail(%r{Failed to connect to the CA to determine if certificate #{name} has been cleaned})
end
it 'raises if we have extra args' do
ssl.command_line.args << 'hostname.example.biz'
expects_command_to_fail(/Extra arguments detected: hostname.example.biz/)
end
context 'when deleting local CA' do
before do
ssl.command_line.args << '--localca'
ssl.parse_options
end
it 'deletes the local CA cert' do
File.write(Puppet[:localcacert], @ca_cert.to_pem)
expects_command_to_pass(%r{Removed local CA certificate #{Puppet[:localcacert]}})
end
it 'deletes the local CRL' do
File.write(Puppet[:hostcrl], @crl.to_pem)
expects_command_to_pass(%r{Removed local CRL #{Puppet[:hostcrl]}})
end
end
context 'on the puppetserver host' do
before :each do
Puppet[:certname] = 'puppetserver'
Puppet[:server] = 'puppetserver'
end
it "prints an error when the CA is local and the CA has not cleaned its cert" do
stub_request(:get, %r{puppet-ca/v1/certificate/puppetserver}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_fail(%r{The certificate puppetserver must be cleaned from the CA first})
end
it "cleans the cert when the CA is local and the CA has already cleaned its cert" do
File.write(Puppet[:hostcert], @host[:cert].to_pem)
stub_request(:get, %r{puppet-ca/v1/certificate/puppetserver}).to_return(status: 404)
expects_command_to_pass(%r{Removed certificate .*puppetserver.pem})
end
it "cleans the cert when run on a puppetserver that isn't the CA" do
File.write(Puppet[:hostcert], @host[:cert].to_pem)
Puppet[:ca_server] = 'caserver'
expects_command_to_pass(%r{Removed certificate .*puppetserver.pem})
end
end
context 'when cleaning a device' do
before do
ssl.command_line.args = ['clean', '--target', 'device.example.com']
ssl.parse_options
end
it 'deletes the device certificate' do
device_cert_path = File.join(Puppet[:devicedir], 'device.example.com', 'ssl', 'certs')
device_cert_file = File.join(device_cert_path, 'device.example.com.pem')
FileUtils.mkdir_p(device_cert_path)
File.write(device_cert_file, 'device.example.com')
expects_command_to_pass(%r{Removed certificate #{device_cert_file}})
end
end
end
context 'when bootstrapping' do
before do
ssl.command_line.args << 'bootstrap'
end
it 'registers the OIDs' do
expect_any_instance_of(Puppet::SSL::StateMachine).to receive(:ensure_client_certificate).and_return(
double('ssl_context')
)
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
expects_command_to_pass
end
it 'returns an SSLContext with the loaded CA certs, CRLs, private key and client cert' do
expect_any_instance_of(Puppet::SSL::StateMachine).to receive(:ensure_client_certificate).and_return(
double('ssl_context')
)
expects_command_to_pass
end
end
context 'when showing' do
before do
ssl.command_line.args << 'show'
File.write(Puppet[:hostcert], @host[:cert].to_pem)
end
it 'reports if the key is missing' do
File.delete(Puppet[:hostprivkey])
expects_command_to_fail(/The private key is missing from/)
end
it 'reports if the cert is missing' do
File.delete(Puppet[:hostcert])
expects_command_to_fail(/The client certificate is missing from/)
end
it 'prints certificate information' do
expects_command_to_pass(@host[:cert].to_text)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/lookup_spec.rb | spec/unit/application/lookup_spec.rb | require 'spec_helper'
require 'puppet/application/lookup'
require 'puppet/pops/lookup'
describe Puppet::Application::Lookup do
def run_lookup(lookup)
capture = StringIO.new
saved_stdout = $stdout
begin
$stdout = capture
expect { lookup.run_command }.to exit_with(0)
ensure
$stdout = saved_stdout
end
# Drop end of line and an optional yaml end of document
capture.string.gsub(/\n(\.\.\.\n)?\Z/m, '')
end
context "when running with incorrect command line options" do
let (:lookup) { Puppet::Application[:lookup] }
it "errors if no keys are given via the command line" do
lookup.options[:node] = 'dantooine.local'
expected_error = "No keys were given to lookup."
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
it "does not allow invalid arguments for '--merge'" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:merge] = 'something_bad'
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
expected_error = "The --merge option only accepts 'first', 'hash', 'unique', or 'deep'\nRun 'puppet lookup --help' for more details"
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
it "does not allow deep merge options if '--merge' was not set to deep" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:merge_hash_arrays] = true
lookup.options[:merge] = 'hash'
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
expected_error = "The options --knock-out-prefix, --sort-merged-arrays, and --merge-hash-arrays are only available with '--merge deep'\nRun 'puppet lookup --help' for more details"
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
end
context "when running with correct command line options" do
let (:lookup) { Puppet::Application[:lookup] }
it "calls the lookup method with the correct arguments" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:render_as] = :s;
lookup.options[:merge_hash_arrays] = true
lookup.options[:merge] = 'deep'
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
allow(lookup).to receive(:generate_scope).and_yield('scope')
expected_merge = { "strategy" => "deep", "sort_merged_arrays" => false, "merge_hash_arrays" => true }
expect(Puppet::Pops::Lookup).to receive(:lookup).with(['atton', 'kreia'], nil, nil, false, expected_merge, anything).and_return('rand')
expect(run_lookup(lookup)).to eql("rand")
end
%w(first unique hash deep).each do |opt|
it "accepts --merge #{opt}" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:merge] = opt
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
allow(lookup).to receive(:generate_scope).and_yield('scope')
allow(Puppet::Pops::Lookup).to receive(:lookup).and_return('rand')
expect(run_lookup(lookup)).to eql("rand")
end
end
it "prints the value found by lookup" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
allow(lookup).to receive(:generate_scope).and_yield('scope')
allow(Puppet::Pops::Lookup).to receive(:lookup).and_return('rand')
expect(run_lookup(lookup)).to eql("rand")
end
end
context 'when given a valid configuration' do
let (:lookup) { Puppet::Application[:lookup] }
# There is a fully configured 'sample' environment in fixtures at this location
let(:environmentpath) { File.absolute_path(File.join(my_fixture_dir(), '../environments')) }
let(:facts) { Puppet::Node::Facts.new("facts", {}) }
let(:node) { Puppet::Node.new("testnode", :facts => facts, :environment => 'production') }
let(:expected_json_hash) {
{
'branches' =>
[
{
'branches'=>
[
{
'key'=>'lookup_options',
'event'=>'not_found',
'type'=>'data_provider',
'name'=>'Global Data Provider (hiera configuration version 5)'
},
{
'branches'=>
[
{
'branches'=>
[
{
'key' => 'lookup_options',
'value' => {'a'=>'first'},
'event'=>'found',
'type'=>'path',
'original_path'=>'common.yaml',
'path'=>"#{environmentpath}/production/data/common.yaml"
}
],
'type'=>'data_provider',
'name'=>'Hierarchy entry "Common"'
}
],
'type'=>'data_provider',
'name'=>'Environment Data Provider (hiera configuration version 5)'
}
],
'key'=>'lookup_options',
'type'=>'root'
},
{
'branches'=>
[
{
'key'=>'a',
'event'=>'not_found',
'type'=>'data_provider',
'name'=>'Global Data Provider (hiera configuration version 5)'
},
{
'branches'=>
[
{
'branches'=>
[
{
'key'=>'a',
'value'=>'This is A',
'event'=>'found',
'type'=>'path',
'original_path'=>'common.yaml',
'path'=>"#{environmentpath}/production/data/common.yaml"
}
],
'type'=>'data_provider',
'name'=>'Hierarchy entry "Common"'
}
],
'type'=>'data_provider',
'name'=>'Environment Data Provider (hiera configuration version 5)'
}
],
'key'=>'a',
'type'=>'root'
}
]
}
}
let(:expected_yaml_hash) {
{
:branches =>
[
{
:branches=>
[
{
:key=>'lookup_options',
:event=>:not_found,
:type=>:data_provider,
:name=>'Global Data Provider (hiera configuration version 5)'
},
{
:branches=>
[
{
:branches=>
[
{
:key => 'lookup_options',
:value => {'a'=>'first'},
:event=>:found,
:type=>:path,
:original_path=>'common.yaml',
:path=>"#{environmentpath}/production/data/common.yaml"
}
],
:type=>:data_provider,
:name=>'Hierarchy entry "Common"'
}
],
:type=>:data_provider,
:name=>'Environment Data Provider (hiera configuration version 5)'
}
],
:key=>'lookup_options',
:type=>:root
},
{
:branches=>
[
{
:key=>'a',
:event=>:not_found,
:type=>:data_provider,
:name=>'Global Data Provider (hiera configuration version 5)'
},
{
:branches=>
[
{
:branches=>
[
{
:key=>'a',
:value=>'This is A',
:event=>:found,
:type=>:path,
:original_path=>'common.yaml',
:path=>"#{environmentpath}/production/data/common.yaml"
}
],
:type=>:data_provider,
:name=>'Hierarchy entry "Common"'
}
],
:type=>:data_provider,
:name=>'Environment Data Provider (hiera configuration version 5)'
}
],
:key=>'a',
:type=>:root
}
]
}
}
around(:each) do |example|
# Initialize settings to get a full compile as close as possible to a real
# environment load
Puppet.settings.initialize_global_settings
loader = Puppet::Environments::Directories.new(environmentpath, [])
Puppet.override(:environments => loader) do
example.run
end
end
it '--explain produces human readable text by default and does not produce output to debug logger' do
lookup.options[:node] = node
lookup.options[:explain] = true
allow(lookup.command_line).to receive(:args).and_return(['a'])
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
expect(logs.any? { |log| log.level == :debug }).to be_falsey
end
it '--debug using multiple interpolation functions produces output to the logger' do
lookup.options[:node] = node
allow(lookup.command_line).to receive(:args).and_return(['ab'])
Puppet.debug = true
logs = []
begin
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect { lookup.run_command }.to output(<<-VALUE.unindent).to_stdout
--- This is A and This is B
...
VALUE
end
rescue SystemExit => e
expect(e.status).to eq(0)
end
logs = logs.select { |log| log.level == :debug }.map { |log| log.message }
expect(logs).to include(/Found key: "ab" value: "This is A and This is B"/)
end
it '--explain produces human readable text by default and --debug produces the same output to debug logger' do
lookup.options[:node] = node
lookup.options[:explain] = true
allow(lookup.command_line).to receive(:args).and_return(['a'])
Puppet.debug = true
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
logs = logs.select { |log| log.level == :debug }.map { |log| log.message }
expect(logs).to include(<<-EXPLANATION.chomp)
Lookup of 'a'
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
it '--explain-options produces human readable text of a hash merge' do
lookup.options[:node] = node
lookup.options[:explain_options] = true
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Merged result: {
"a" => "first"
}
EXPLANATION
end
it '--explain-options produces human readable text of a hash merge and --debug produces the same output to debug logger' do
lookup.options[:node] = node
lookup.options[:explain_options] = true
Puppet.debug = true
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Merged result: {
"a" => "first"
}
EXPLANATION
logs = logs.select { |log| log.level == :debug }.map { |log| log.message }
expect(logs).to include(<<-EXPLANATION.chomp)
Lookup of '__global__'
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Merged result: {
"a" => "first"
}
EXPLANATION
end
end
it '--explain produces human readable text of a hash merge when using both --explain and --explain-options' do
lookup.options[:node] = node
lookup.options[:explain] = true
lookup.options[:explain_options] = true
allow(lookup.command_line).to receive(:args).and_return(['a'])
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
it 'can produce a yaml explanation' do
lookup.options[:node] = node
lookup.options[:explain] = true
lookup.options[:render_as] = :yaml
allow(lookup.command_line).to receive(:args).and_return(['a'])
output = run_lookup(lookup)
expect(Puppet::Util::Yaml.safe_load(output, [Symbol])).to eq(expected_yaml_hash)
end
it 'can produce a json explanation' do
lookup.options[:node] = node
lookup.options[:explain] = true
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['a'])
output = run_lookup(lookup)
expect(JSON.parse(output)).to eq(expected_json_hash)
end
it 'can access values using dotted keys' do
lookup.options[:node] = node
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['d.one.two.three'])
output = run_lookup(lookup)
expect(JSON.parse("[#{output}]")).to eq(['the value'])
end
it 'can access values using quoted dotted keys' do
lookup.options[:node] = node
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['"e.one.two.three"'])
output = run_lookup(lookup)
expect(JSON.parse("[#{output}]")).to eq(['the value'])
end
it 'can access values using mix of dotted keys and quoted dotted keys' do
lookup.options[:node] = node
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['"f.one"."two.three".1'])
output = run_lookup(lookup)
expect(JSON.parse("[#{output}]")).to eq(['second value'])
end
context 'the global scope' do
include PuppetSpec::Files
it "is unaffected by global variables unless '--compile' is used" do
# strict mode is off so behavior this test is trying to check isn't stubbed out
Puppet[:strict_variables] = false
Puppet[:strict] = :warning
lookup.options[:node] = node
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is")
end
it "is affected by global variables when '--compile' is used" do
lookup.options[:node] = node
lookup.options[:compile] = true
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is C from site.pp")
end
it 'receives extra facts in top scope' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
cx: ' C from facts'
CONTENT
lookup.options[:node] = node
lookup.options[:fact_file] = file_path
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is C from facts")
end
it 'receives extra facts in the facts hash' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:node] = node
lookup.options[:fact_file] = file_path
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['g'])
expect(run_lookup(lookup)).to eql("This is G from facts in facts hash")
end
it 'looks up server facts' do
lookup.options[:node] = node
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['h'])
expect(run_lookup(lookup)).to eql("server version is #{Puppet.version}")
end
describe 'when retrieving given facts' do
before do
lookup.options[:node] = node
allow(lookup.command_line).to receive(:args).and_return(['g'])
end
it 'loads files with yaml extension as yaml on first try' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Yaml).to receive(:safe_load_file).with(file_path, []).and_call_original
run_lookup(lookup)
end
it 'loads files with yml extension as yaml on first try' do
file_path = file_containing('facts.yml', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Yaml).to receive(:safe_load_file).with(file_path, []).and_call_original
run_lookup(lookup)
end
it 'loads files with json extension as json on first try' do
file_path = file_containing('facts.json', <<~CONTENT)
{
"cx": " G from facts"
}
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json).to receive(:load_file).with(file_path, {}).and_call_original
run_lookup(lookup)
end
it 'detects file format accordingly even with random file extension' do
file_path = file_containing('facts.txt', <<~CONTENT)
{
"cx": " G from facts"
}
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json).to receive(:load_file_if_valid).with(file_path).and_call_original
expect(Puppet::Util::Yaml).not_to receive(:safe_load_file_if_valid).with(file_path)
run_lookup(lookup)
end
it 'detects file without extension as json due to valid contents' do
file_path = file_containing('facts', <<~CONTENT)
{
"cx": " G from facts"
}
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json).to receive(:load_file_if_valid).with(file_path).and_call_original
expect(Puppet::Util::Yaml).not_to receive(:safe_load_file_if_valid).with(file_path)
run_lookup(lookup)
end
it 'detects file without extension as yaml due to valid contents' do
file_path = file_containing('facts', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json.load_file_if_valid(file_path)).to be_nil
expect(Puppet::Util::Yaml).to receive(:safe_load_file_if_valid).with(file_path).and_call_original
run_lookup(lookup)
end
it 'raises error due to invalid contents' do
file_path = file_containing('facts.yml', <<~CONTENT)
INVALID CONTENT
CONTENT
lookup.options[:fact_file] = file_path
expect {
lookup.run_command
}.to raise_error(/Incorrectly formatted data in .+ given via the --facts flag \(only accepts yaml and json files\)/)
end
it "fails when a node doesn't have facts" do
lookup.options[:node] = "bad.node"
allow(lookup.command_line).to receive(:args).and_return(['c'])
expected_error = "No facts available for target node: #{lookup.options[:node]}"
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
it 'raises error due to missing trusted information facts in --facts file' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
fqdn: some.fqdn.com
CONTENT
lookup.options[:fact_file] = file_path
expect {
lookup.run_command
}.to raise_error(/When overriding any of the hostname,domain,fqdn,clientcert facts with #{file_path} given via the --facts flag, they must all be overridden./)
end
it 'does not fail when all trusted information facts are provided via --facts file' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
fqdn: some.fqdn.com
hostname: some.hostname
domain: some.domain
clientcert: some.clientcert
CONTENT
lookup.options[:fact_file] = file_path
expect {
lookup.run_command
}.to exit_with(0)
.and output(/This is in facts hash/).to_stdout
end
end
end
context 'using a puppet function as data provider' do
let(:node) { Puppet::Node.new("testnode", :facts => facts, :environment => 'puppet_func_provider') }
it "works OK in the absense of '--compile'" do
# strict mode is off so behavior this test is trying to check isn't stubbed out
Puppet[:strict_variables] = false
Puppet[:strict] = :warning
lookup.options[:node] = node
allow(lookup.command_line).to receive(:args).and_return(['c'])
lookup.options[:render_as] = :s
expect(run_lookup(lookup)).to eql("This is C from data.pp")
end
it "global scope is affected by global variables when '--compile' is used" do
lookup.options[:node] = node
lookup.options[:compile] = true
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is C from site.pp")
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/config_spec.rb | spec/unit/application/config_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/application/config'
describe Puppet::Application::Config do
include PuppetSpec::Files
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
MIXED_UTF8 = "A\u06FF\u16A0\u{2070E}" # Aۿᚠ𠜎
let(:app) { Puppet::Application[:config] }
before :each do
Puppet[:config] = tmpfile('config')
end
def initialize_app(args)
app.command_line.args = args
# ensure global defaults are initialized prior to app defaults
Puppet.initialize_settings(args)
end
def read_utf8(path)
File.read(path, :encoding => 'UTF-8')
end
def write_utf8(path, content)
File.write(path, content, 0, :encoding => 'UTF-8')
end
context "when printing" do
it "prints a value" do
initialize_app(%w[print certname])
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching(Puppet[:certname])).to_stdout
end
it "prints a value from a section" do
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
[server]
external_nodes=exec
END
initialize_app(%w[print external_nodes --section server])
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching('exec')).to_stdout
end
it "doesn't require the environment to exist" do
initialize_app(%w[print certname --environment doesntexist])
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching(Puppet[:certname])).to_stdout
end
end
context "when setting" do
it "sets a value in its config file" do
initialize_app(%w[set certname www.example.com])
expect {
app.run
}.to exit_with(0)
expect(File.read(Puppet[:config])).to eq("[main]\ncertname = www.example.com\n")
end
it "sets a value in the server section" do
initialize_app(%w[set external_nodes exec --section server])
expect {
app.run
}.to exit_with(0)
expect(File.read(Puppet[:config])).to eq("[server]\nexternal_nodes = exec\n")
end
{
%w[certname WWW.EXAMPLE.COM] => /Certificate names must be lower case/,
%w[log_level all] => /Invalid loglevel all/,
%w[disable_warnings true] => /Cannot disable unrecognized warning types 'true'/,
%w[strict on] => /Invalid value 'on' for parameter strict/,
%w[digest_algorithm rot13] => /Invalid value 'rot13' for parameter digest_algorithm/,
%w[http_proxy_password a#b] => /Passwords set in the http_proxy_password setting must be valid as part of a URL/,
}.each_pair do |args, message|
it "rejects #{args.join(' ')}" do
initialize_app(['set', *args])
expect {
app.run
}.to exit_with(1)
.and output(message).to_stderr
end
end
it 'sets unknown settings' do
initialize_app(['set', 'notarealsetting', 'true'])
expect {
app.run
}.to exit_with(0)
expect(File.read(Puppet[:config])).to eq("[main]\nnotarealsetting = true\n")
end
end
context "when deleting" do
it "deletes a value" do
initialize_app(%w[delete external_nodes])
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
END
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'main': 'external_nodes=none'/).to_stdout
expect(File.read(Puppet[:config])).to eq("[main]\n")
end
it "warns when deleting a value that isn't set" do
initialize_app(%w[delete external_nodes])
File.write(Puppet[:config], "")
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching("Warning: No setting found in configuration file for section 'main' setting name 'external_nodes'")).to_stderr
expect(File.read(Puppet[:config])).to eq("")
end
it "deletes a value from main" do
initialize_app(%w[delete external_nodes])
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
END
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'main': 'external_nodes=none'/).to_stdout
expect(File.read(Puppet[:config])).to eq("[main]\n")
end
it "deletes a value from main a section" do
initialize_app(%w[delete external_nodes --section server])
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
[server]
external_nodes=exec
END
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'server': 'external_nodes'/).to_stdout
expect(File.read(Puppet[:config])).to eq("[main]\nexternal_nodes=none\n[server]\n")
end
end
context "when managing UTF-8 values" do
it "reads a UTF-8 value" do
write_utf8(Puppet[:config], <<~EOF)
[main]
tags=#{MIXED_UTF8}
EOF
initialize_app(%w[print tags])
expect {
app.run
}.to exit_with(0)
.and output("#{MIXED_UTF8}\n").to_stdout
end
it "sets a UTF-8 value" do
initialize_app(['set', 'tags', MIXED_UTF8])
expect {
app.run
}.to exit_with(0)
expect(read_utf8(Puppet[:config])).to eq(<<~EOF)
[main]
tags = #{MIXED_UTF8}
EOF
end
it "deletes a UTF-8 value" do
initialize_app(%w[delete tags])
write_utf8(Puppet[:config], <<~EOF)
[main]
tags=#{MIXED_UTF8}
EOF
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'main': 'tags=#{MIXED_UTF8}'/).to_stdout
expect(read_utf8(Puppet[:config])).to eq(<<~EOF)
[main]
EOF
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/doc_spec.rb | spec/unit/application/doc_spec.rb | require 'spec_helper'
require 'puppet/application/doc'
require 'puppet/util/reference'
require 'puppet/util/rdoc'
describe Puppet::Application::Doc do
before :each do
@doc = Puppet::Application[:doc]
allow(@doc).to receive(:puts)
@doc.preinit
allow(Puppet::Util::Log).to receive(:newdestination)
end
it "should declare an other command" do
expect(@doc).to respond_to(:other)
end
it "should declare a rdoc command" do
expect(@doc).to respond_to(:rdoc)
end
it "should declare a fallback for unknown options" do
expect(@doc).to respond_to(:handle_unknown)
end
it "should declare a preinit block" do
expect(@doc).to respond_to(:preinit)
end
describe "in preinit" do
it "should set references to []" do
@doc.preinit
expect(@doc.options[:references]).to eq([])
end
it "should init mode to text" do
@doc.preinit
expect(@doc.options[:mode]).to eq(:text)
end
it "should init format to to_markdown" do
@doc.preinit
expect(@doc.options[:format]).to eq(:to_markdown)
end
end
describe "when handling options" do
[:all, :outputdir, :verbose, :debug, :charset].each do |option|
it "should declare handle_#{option} method" do
expect(@doc).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
expect(@doc.options).to receive(:[]=).with(option, 'arg')
@doc.send("handle_#{option}".to_sym, 'arg')
end
end
it "should store the format if valid" do
allow(Puppet::Util::Reference).to receive(:method_defined?).with('to_format').and_return(true)
@doc.handle_format('format')
expect(@doc.options[:format]).to eq('to_format')
end
it "should raise an error if the format is not valid" do
allow(Puppet::Util::Reference).to receive(:method_defined?).with('to_format').and_return(false)
expect { @doc.handle_format('format') }.to raise_error(RuntimeError, /Invalid output format/)
end
it "should store the mode if valid" do
allow(Puppet::Util::Reference).to receive(:modes).and_return(double('mode', :include? => true))
@doc.handle_mode('mode')
expect(@doc.options[:mode]).to eq(:mode)
end
it "should store the mode if :rdoc" do
allow(Puppet::Util::Reference.modes).to receive(:include?).with('rdoc').and_return(false)
@doc.handle_mode('rdoc')
expect(@doc.options[:mode]).to eq(:rdoc)
end
it "should raise an error if the mode is not valid" do
allow(Puppet::Util::Reference.modes).to receive(:include?).with('unknown').and_return(false)
expect { @doc.handle_mode('unknown') }.to raise_error(RuntimeError, /Invalid output mode/)
end
it "should list all references on list and exit" do
reference = double('reference')
ref = double('ref')
allow(Puppet::Util::Reference).to receive(:references).and_return([reference])
expect(Puppet::Util::Reference).to receive(:reference).with(reference).and_return(ref)
expect(ref).to receive(:doc)
expect { @doc.handle_list(nil) }.to exit_with 0
end
it "should add reference to references list with --reference" do
@doc.options[:references] = [:ref1]
@doc.handle_reference('ref2')
expect(@doc.options[:references]).to eq([:ref1,:ref2])
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(@doc.command_line).to receive(:args).and_return([])
end
it "should default to rdoc mode if there are command line arguments" do
allow(@doc.command_line).to receive(:args).and_return(["1"])
allow(@doc).to receive(:setup_rdoc)
@doc.setup
expect(@doc.options[:mode]).to eq(:rdoc)
end
it "should call setup_rdoc in rdoc mode" do
@doc.options[:mode] = :rdoc
expect(@doc).to receive(:setup_rdoc)
@doc.setup
end
it "should call setup_reference if not rdoc" do
@doc.options[:mode] = :test
expect(@doc).to receive(:setup_reference)
@doc.setup
end
describe "configuring logging" do
before :each do
allow(Puppet::Util::Log).to receive(:newdestination)
end
describe "with --debug" do
before do
@doc.options[:debug] = true
end
it "should set log level to debug" do
@doc.setup
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "should set log destination to console" do
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
@doc.setup
end
end
describe "with --verbose" do
before do
@doc.options[:verbose] = true
end
it "should set log level to info" do
@doc.setup
expect(Puppet::Util::Log.level).to eq(:info)
end
it "should set log destination to console" do
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
@doc.setup
end
end
describe "without --debug or --verbose" do
before do
@doc.options[:debug] = false
@doc.options[:verbose] = false
end
it "should set log level to warning" do
@doc.setup
expect(Puppet::Util::Log.level).to eq(:warning)
end
it "should set log destination to console" do
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
@doc.setup
end
end
end
describe "in non-rdoc mode" do
it "should get all non-dynamic reference if --all" do
@doc.options[:all] = true
static = double('static', :dynamic? => false)
dynamic = double('dynamic', :dynamic? => true)
allow(Puppet::Util::Reference).to receive(:reference).with(:static).and_return(static)
allow(Puppet::Util::Reference).to receive(:reference).with(:dynamic).and_return(dynamic)
allow(Puppet::Util::Reference).to receive(:references).and_return([:static,:dynamic])
@doc.setup_reference
expect(@doc.options[:references]).to eq([:static])
end
it "should default to :type if no references" do
@doc.setup_reference
expect(@doc.options[:references]).to eq([:type])
end
end
describe "in rdoc mode" do
describe "when there are unknown args" do
it "should expand --modulepath if any" do
@doc.unknown_args = [ { :opt => "--modulepath", :arg => "path" } ]
allow(Puppet.settings).to receive(:handlearg)
@doc.setup_rdoc
expect(@doc.unknown_args[0][:arg]).to eq(File.expand_path('path'))
end
it "should give them to Puppet.settings" do
@doc.unknown_args = [ { :opt => :option, :arg => :argument } ]
expect(Puppet.settings).to receive(:handlearg).with(:option,:argument)
@doc.setup_rdoc
end
end
it "should operate in server run_mode" do
expect(@doc.class.run_mode.name).to eq(:server)
@doc.setup_rdoc
end
end
end
describe "when running" do
describe "in rdoc mode" do
include PuppetSpec::Files
let(:envdir) { tmpdir('env') }
let(:modules) { File.join(envdir, "modules") }
let(:modules2) { File.join(envdir, "modules2") }
let(:manifests) { File.join(envdir, "manifests") }
before :each do
@doc.manifest = false
allow(Puppet).to receive(:info)
Puppet[:trace] = false
Puppet[:modulepath] = modules
Puppet[:manifest] = manifests
@doc.options[:all] = false
@doc.options[:outputdir] = 'doc'
@doc.options[:charset] = nil
allow(Puppet.settings).to receive(:define_settings)
allow(Puppet::Util::RDoc).to receive(:rdoc)
allow(@doc.command_line).to receive(:args).and_return([])
end
around(:each) do |example|
FileUtils.mkdir_p(modules)
env = Puppet::Node::Environment.create(Puppet[:environment].to_sym, [modules], "#{manifests}/site.pp")
Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do
example.run
end
end
it "should set document_all on --all" do
@doc.options[:all] = true
expect(Puppet.settings).to receive(:[]=).with(:document_all, true)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc in full mode" do
expect(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules, manifests], nil)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc with a charset if --charset has been provided" do
@doc.options[:charset] = 'utf-8'
expect(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules, manifests], "utf-8")
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc in full mode with outputdir set to doc if no --outputdir" do
@doc.options[:outputdir] = false
expect(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules, manifests], nil)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.manifestdoc in manifest mode" do
@doc.manifest = true
expect(Puppet::Util::RDoc).to receive(:manifestdoc)
expect { @doc.rdoc }.to exit_with(0)
end
it "should get modulepath and manifest values from the environment" do
FileUtils.mkdir_p(modules)
FileUtils.mkdir_p(modules2)
env = Puppet::Node::Environment.create(Puppet[:environment].to_sym,
[modules, modules2],
"envmanifests/site.pp")
Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do
allow(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules.to_s, modules2.to_s, env.manifest.to_s], nil)
expect { @doc.rdoc }.to exit_with(0)
end
end
end
describe "in the other modes" do
it "should get reference in given format" do
reference = double('reference')
@doc.options[:mode] = :none
@doc.options[:references] = [:ref]
expect(Puppet::Util::Reference).to receive(:reference).with(:ref).and_return(reference)
@doc.options[:format] = :format
allow(@doc).to receive(:exit)
expect(reference).to receive(:send).with(:format, anything).and_return('doc')
@doc.other
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application/resource_spec.rb | spec/unit/application/resource_spec.rb | require 'spec_helper'
require 'puppet/application/resource'
require 'puppet_spec/character_encoding'
describe Puppet::Application::Resource do
include PuppetSpec::Files
before :each do
@resource_app = Puppet::Application[:resource]
allow(Puppet::Util::Log).to receive(:newdestination)
end
describe "in preinit" do
it "should include provider parameter by default" do
@resource_app.preinit
expect(@resource_app.extra_params).to eq([:provider])
end
end
describe "when handling options" do
[:debug, :verbose, :edit].each do |option|
it "should store argument value when calling handle_#{option}" do
expect(@resource_app.options).to receive(:[]=).with(option, 'arg')
@resource_app.send("handle_#{option}".to_sym, 'arg')
end
end
it "should load a display all types with types option" do
type1 = double('type1', :name => :type1)
type2 = double('type2', :name => :type2)
allow(Puppet::Type).to receive(:loadall)
allow(Puppet::Type).to receive(:eachtype).and_yield(type1).and_yield(type2)
expect(@resource_app).to receive(:puts).with(['type1','type2'])
expect { @resource_app.handle_types(nil) }.to exit_with 0
end
it "should add param to extra_params list" do
@resource_app.extra_params = [ :param1 ]
@resource_app.handle_param("whatever")
expect(@resource_app.extra_params).to eq([ :param1, :whatever ])
end
it "should get a parameter in the printed data if extra_params are passed" do
tty = double("tty", :tty? => true )
path = tmpfile('testfile')
command_line = Puppet::Util::CommandLine.new("puppet", [ 'resource', 'file', path ], tty )
allow(@resource_app).to receive(:command_line).and_return(command_line)
# provider is a parameter that should always be available
@resource_app.extra_params = [ :provider ]
expect {
@resource_app.main
}.to output(/provider\s+=>/).to_stdout
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
end
it "should set console as the log destination" do
expect(Puppet::Log).to receive(:newdestination).with(:console)
@resource_app.setup
end
it "should set log level to debug if --debug was passed" do
allow(@resource_app.options).to receive(:[]).with(:debug).and_return(true)
@resource_app.setup
expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
allow(@resource_app.options).to receive(:[]).with(:debug).and_return(false)
allow(@resource_app.options).to receive(:[]).with(:verbose).and_return(true)
@resource_app.setup
expect(Puppet::Log.level).to eq(:info)
end
end
describe "when running" do
before :each do
@type = double('type', :properties => [])
allow(@resource_app.command_line).to receive(:args).and_return(['mytype'])
allow(Puppet::Type).to receive(:type).and_return(@type)
@res = double("resource")
allow(@res).to receive(:prune_parameters).and_return(@res)
allow(@res).to receive(:to_manifest).and_return("resource")
@report = double("report")
allow(@resource_app).to receive(:puts)
end
it "should raise an error if no type is given" do
allow(@resource_app.command_line).to receive(:args).and_return([])
expect { @resource_app.main }.to raise_error(RuntimeError, "You must specify the type to display")
end
it "should raise an error if the type is not found" do
allow(Puppet::Type).to receive(:type).and_return(nil)
expect { @resource_app.main }.to raise_error(RuntimeError, 'Could not find type mytype')
end
it "should search for resources" do
expect(Puppet::Resource.indirection).to receive(:search).with('mytype/', {}).and_return([])
@resource_app.main
end
it "should describe the given resource" do
allow(@resource_app.command_line).to receive(:args).and_return(['type','name'])
expect(Puppet::Resource.indirection).to receive(:find).with('type/name').and_return(@res)
@resource_app.main
end
before :each do
allow(@res).to receive(:ref).and_return("type/name")
end
it "should add given parameters to the object" do
allow(@resource_app.command_line).to receive(:args).and_return(['type','name','param=temp'])
expect(Puppet::Resource.indirection).to receive(:save).with(@res, 'type/name').and_return([@res, @report])
expect(Puppet::Resource).to receive(:new).with('type', 'name', {:parameters => {'param' => 'temp'}}).and_return(@res)
resource_status = instance_double('Puppet::Resource::Status')
allow(@report).to receive(:resource_statuses).and_return({'type/name' => resource_status})
allow(resource_status).to receive(:failed?).and_return(false)
@resource_app.main
end
end
describe "when printing output" do
Puppet::Type.newtype(:stringify) do
ensurable
newparam(:name, isnamevar: true)
newproperty(:string)
end
Puppet::Type.type(:stringify).provide(:stringify) do
def exists?
true
end
def string=(value)
end
def string
Puppet::Util::Execution::ProcessOutput.new('test', 0)
end
end
it "should not emit puppet class tags when printing yaml when strict mode is off" do
Puppet[:strict] = :warning
@resource_app.options[:to_yaml] = true
allow(@resource_app.command_line).to receive(:args).and_return(['stringify', 'hello', 'ensure=present', 'string=asd'])
expect(@resource_app).to receive(:puts).with(<<~YAML)
---
stringify:
hello:
ensure: present
string: test
YAML
expect { @resource_app.main }.not_to raise_error
end
it "should ensure all values to be printed are in the external encoding" do
resources = [
Puppet::Type.type(:user).new(:name => "\u2603".force_encoding(Encoding::UTF_8)).to_resource,
Puppet::Type.type(:user).new(:name => "Jos\xE9".force_encoding(Encoding::ISO_8859_1)).to_resource
]
expect(Puppet::Resource.indirection).to receive(:search).with('user/', {}).and_return(resources)
allow(@resource_app.command_line).to receive(:args).and_return(['user'])
# All of our output should be in external encoding
expect(@resource_app).to receive(:puts) { |args| expect(args.encoding).to eq(Encoding::ISO_8859_1) }
# This would raise an error if we weren't handling it
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ISO_8859_1) do
expect { @resource_app.main }.not_to raise_error
end
end
end
describe "when handling file type" do
before :each do
allow(Facter).to receive(:loadfacts)
@resource_app.preinit
end
it "should raise an exception if no file specified" do
allow(@resource_app.command_line).to receive(:args).and_return(['file'])
expect { @resource_app.main }.to raise_error(RuntimeError, /Listing all file instances is not supported/)
end
it "should output a file resource when given a file path" do
path = File.expand_path('/etc')
res = Puppet::Type.type(:file).new(:path => path).to_resource
expect(Puppet::Resource.indirection).to receive(:find).and_return(res)
allow(@resource_app.command_line).to receive(:args).and_return(['file', path])
expect(@resource_app).to receive(:puts).with(/file \{ '#{Regexp.escape(path)}'/m)
@resource_app.main
end
end
describe 'when handling a custom type' do
it 'the Puppet::Pops::Loaders instance is available' do
Puppet::Type.newtype(:testing) do
newparam(:name) do
isnamevar
end
def self.instances
fail('Loader not found') unless Puppet::Pops::Loaders.find_loader(nil).is_a?(Puppet::Pops::Loader::Loader)
@instances ||= [new(:name => name)]
end
end
allow(@resource_app.command_line).to receive(:args).and_return(['testing', 'hello'])
expect(@resource_app).to receive(:puts).with("testing { 'hello':\n}")
expect { @resource_app.main }.not_to raise_error
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/data_providers/hiera_data_provider_spec.rb | spec/unit/data_providers/hiera_data_provider_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe "when using a hiera data provider" do
include PuppetSpec::Compiler
# There is a fully configured 'sample' environment in fixtures at this location
let(:environmentpath) { parent_fixture('environments') }
let(:facts) { Puppet::Node::Facts.new("facts", {}) }
around(:each) do |example|
# Initialize settings to get a full compile as close as possible to a real
# environment load
Puppet.settings.initialize_global_settings
# Initialize loaders based on the environmentpath. It does not work to
# just set the setting environmentpath for some reason - this achieves the same:
# - first a loader is created, loading directory environments from the fixture (there is
# one environment, 'sample', which will be loaded since the node references this
# environment by name).
# - secondly, the created env loader is set as 'environments' in the puppet context.
#
loader = Puppet::Environments::Directories.new(environmentpath, [])
Puppet.override(:environments => loader) do
example.run
end
end
def compile_and_get_notifications(environment, code = nil)
extract_notifications(compile(environment, code))
end
def compile(environment, code = nil)
Puppet[:code] = code if code
node = Puppet::Node.new("testnode", :facts => facts, :environment => environment)
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['domain'] = 'example.com'
compiler.topscope['my_fact'] = 'server3'
block_given? ? compiler.compile { |catalog| yield(compiler); catalog } : compiler.compile
end
def extract_notifications(catalog)
catalog.resources.map(&:ref).select { |r| r.start_with?('Notify[') }.map { |r| r[7..-2] }
end
it 'uses default configuration for environment and module data' do
resources = compile_and_get_notifications('hiera_defaults')
expect(resources).to include('module data param_a is 100, param default is 200, env data param_c is 300')
end
it 'reads hiera.yaml in environment root and configures multiple json and yaml providers' do
resources = compile_and_get_notifications('hiera_env_config')
expect(resources).to include("env data param_a is 10, env data param_b is 20, env data param_c is 30, env data param_d is 40, env data param_e is 50, env data param_yaml_utf8 is \u16EB\u16D2\u16E6, env data param_json_utf8 is \u16A0\u16C7\u16BB")
end
it 'reads hiera.yaml in module root and configures multiple json and yaml providers' do
resources = compile_and_get_notifications('hiera_module_config')
expect(resources).to include('module data param_a is 100, module data param_b is 200, module data param_c is 300, module data param_d is 400, module data param_e is 500')
end
it 'keeps lookup_options in one module separate from lookup_options in another' do
resources1 = compile('hiera_modules', 'include one').resources.select {|r| r.ref.start_with?('Class[One]')}
resources2 = compile('hiera_modules', 'include two').resources.select {|r| r.ref.start_with?('Class[One]')}
expect(resources1).to eq(resources2)
end
it 'does not perform merge of values declared in environment and module when resolving parameters' do
resources = compile_and_get_notifications('hiera_misc')
expect(resources).to include('env 1, ')
end
it 'performs hash merge of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', '$r = lookup(one::test::param, Hash[String,String], hash) notify{"${r[key1]}, ${r[key2]}":}')
expect(resources).to include('env 1, module 2')
end
it 'performs unique merge of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', '$r = lookup(one::array, Array[String], unique) notify{"${r}":}')
expect(resources.size).to eq(1)
expect(resources[0][1..-2].split(', ')).to contain_exactly('first', 'second', 'third', 'fourth')
end
it 'performs merge found in lookup_options in environment of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', 'include one::lopts_test')
expect(resources.size).to eq(1)
expect(resources[0]).to eq('A, B, C, MA, MB, MC')
end
it 'performs merge found in lookup_options in module of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', 'include one::loptsm_test')
expect(resources.size).to eq(1)
expect(resources[0]).to eq('A, B, C, MA, MB, MC')
end
it "will not find 'lookup_options' as a regular value" do
expect { compile_and_get_notifications('hiera_misc', '$r = lookup("lookup_options")') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value/)
end
it 'does find unqualified keys in the environment' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(ukey1):}')
expect(resources).to include('Some value')
end
it 'does not find unqualified keys in the module' do
expect do
compile_and_get_notifications('hiera_misc', 'notify{lookup(ukey2):}')
end.to raise_error(Puppet::ParseError, /did not find a value for the name 'ukey2'/)
end
it 'can use interpolation lookup method "alias"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_alias):}')
expect(resources).to include('Value from interpolation with alias')
end
it 'can use interpolation lookup method "lookup"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_lookup):}')
expect(resources).to include('Value from interpolation with lookup')
end
it 'can use interpolation lookup method "hiera"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_hiera):}')
expect(resources).to include('Value from interpolation with hiera')
end
it 'can use interpolation lookup method "literal"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_literal):}')
expect(resources).to include('Value from interpolation with literal')
end
it 'can use interpolation lookup method "scope"' do
resources = compile_and_get_notifications('hiera_misc', '$target_scope = "with scope" notify{lookup(km_scope):}')
expect(resources).to include('Value from interpolation with scope')
end
it 'can use interpolation using default lookup method (scope)' do
resources = compile_and_get_notifications('hiera_misc', '$target_default = "with default" notify{lookup(km_default):}')
expect(resources).to include('Value from interpolation with default')
end
it 'performs lookup using qualified expressions in interpolation' do
resources = compile_and_get_notifications('hiera_misc', "$os = { name => 'Fedora' } notify{lookup(km_qualified):}")
expect(resources).to include('Value from qualified interpolation OS = Fedora')
end
it 'can have multiple interpolate expressions in one value' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_multi):}')
expect(resources).to include('cluster/%{::cluster}/%{role}')
end
it 'performs single quoted interpolation' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_sqalias):}')
expect(resources).to include('Value from interpolation with alias')
end
it 'uses compiler lifecycle for caching' do
Puppet[:code] = 'notify{lookup(one::my_var):}'
node = Puppet::Node.new('testnode', :facts => facts, :environment => 'hiera_module_config')
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['my_fact'] = 'server1'
expect(extract_notifications(compiler.compile)).to include('server1')
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['my_fact'] = 'server2'
expect(extract_notifications(compiler.compile)).to include('server2')
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['my_fact'] = 'server3'
expect(extract_notifications(compiler.compile)).to include('In name.yaml')
end
it 'traps endless interpolate recursion' do
expect do
compile_and_get_notifications('hiera_misc', '$r1 = "%{r2}" $r2 = "%{r1}" notify{lookup(recursive):}')
end.to raise_error(Puppet::DataBinding::RecursiveLookupError, /detected in \[recursive, scope:r1, scope:r2\]/)
end
it 'does not consider use of same key in the lookup and scope namespaces as recursion' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(domain):}')
expect(resources).to include('-- example.com --')
end
it 'traps bad alias declarations' do
expect do
compile_and_get_notifications('hiera_misc', "$r1 = 'Alias within string %{alias(\"r2\")}' $r2 = '%{r1}' notify{lookup(recursive):}")
end.to raise_error(Puppet::DataBinding::LookupError, /'alias' interpolation is only permitted if the expression is equal to the entire string/)
end
it 'reports syntax errors for JSON files' do
expect do
compile_and_get_notifications('hiera_bad_syntax_json')
end.to raise_error(Puppet::DataBinding::LookupError, /Unable to parse \(#{environmentpath}[^)]+\):/)
end
it 'reports syntax errors for YAML files' do
expect do
compile_and_get_notifications('hiera_bad_syntax_yaml')
end.to raise_error(Puppet::DataBinding::LookupError, /Unable to parse \(#{environmentpath}[^)]+\):/)
end
describe 'when using explain' do
it 'will report config path (original and resolved), data path (original and resolved), and interpolation (before and after)' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true)
Puppet::Pops::Lookup.lookup('km_scope', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to include(<<-EOS)
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Interpolation on "Value from interpolation %{scope("target_scope")}"
Global Scope
Found key: "target_scope" value: "with scope"
Found key: "km_scope" value: "Value from interpolation with scope"
EOS
end
end
it 'will report that merge options was found in the lookup_options hash' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true)
Puppet::Pops::Lookup.lookup('one::loptsm_test::hash', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to include("Using merge options from \"lookup_options\" hash")
end
end
it 'will report lookup_options details in combination with details of found value' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, Puppet::Pops::Lookup::Explainer.new(true))
Puppet::Pops::Lookup.lookup('one::loptsm_test::hash', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to eq(<<EOS)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Module "one" Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/modules/one/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::loptsm_test::hash" => {
"merge" => "deep"
}
}
Merge strategy hash
Global and Environment
Found key: "lookup_options" value: {
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Module one
Found key: "lookup_options" value: {
"one::loptsm_test::hash" => {
"merge" => "deep"
}
}
Merged result: {
"one::loptsm_test::hash" => {
"merge" => "deep"
},
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Using merge options from "lookup_options" hash
Searching for "one::loptsm_test::hash"
Merge strategy deep
Global Data Provider (hiera configuration version 5)
No such key: "one::loptsm_test::hash"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Found key: "one::loptsm_test::hash" value: {
"a" => "A",
"b" => "B",
"m" => {
"ma" => "MA",
"mb" => "MB"
}
}
Module "one" Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/modules/one/data/common.yaml"
Original path: "common.yaml"
Found key: "one::loptsm_test::hash" value: {
"a" => "A",
"c" => "C",
"m" => {
"ma" => "MA",
"mc" => "MC"
}
}
Merged result: {
"a" => "A",
"c" => "C",
"m" => {
"ma" => "MA",
"mc" => "MC",
"mb" => "MB"
},
"b" => "B"
}
EOS
end
end
it 'will report config path (original and resolved), data path (original and resolved), and interpolation (before and after)' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, Puppet::Pops::Lookup::Explainer.new(true, true))
Puppet::Pops::Lookup.lookup('one::loptsm_test::hash', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to eq(<<EOS)
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Module "one" Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/modules/one/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::loptsm_test::hash" => {
"merge" => "deep"
}
}
Merged result: {
"one::loptsm_test::hash" => {
"merge" => "deep"
},
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
EOS
end
end
end
def parent_fixture(dir_name)
File.absolute_path(File.join(my_fixture_dir(), "../#{dir_name}"))
end
def resources_in(catalog)
catalog.resources.map(&:ref)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/data_providers/function_data_provider_spec.rb | spec/unit/data_providers/function_data_provider_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe "when using function data provider" do
include PuppetSpec::Compiler
# There is a fully configured environment in fixtures in this location
let(:environmentpath) { parent_fixture('environments') }
around(:each) do |example|
# Initialize settings to get a full compile as close as possible to a real
# environment load
Puppet.settings.initialize_global_settings
# Initialize loaders based on the environmentpath. It does not work to
# just set the setting environmentpath for some reason - this achieves the same:
# - first a loader is created, loading directory environments from the fixture (there is
# one such environment, 'production', which will be loaded since the node references this
# environment by name).
# - secondly, the created env loader is set as 'environments' in the puppet context.
#
loader = Puppet::Environments::Directories.new(environmentpath, [])
Puppet.override(:environments => loader) do
example.run
end
end
# The environment configured in the fixture has one module called 'abc'. Its class abc, includes
# a class called 'def'. This class has three parameters test1, test2, and test3 and it creates
# three notify with name set to the value of the three parameters.
#
# Since the abc class does not provide any parameter values to its def class, it attempts to
# get them from data lookup. The fixture has an environment that is configured to load data from
# a function called environment::data, this data sets test1, and test2.
# The module 'abc' is configured to get data by calling the function abc::data(), this function
# returns data for all three parameters test1-test3, now with the prefix 'module'.
#
# The result should be that the data set in the environment wins over those set in the
# module.
#
it 'gets data from module and environment functions and combines them with env having higher precedence' do
Puppet[:code] = 'include abc'
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
catalog = compiler.compile()
resources_created_in_fixture = ["Notify[env_test1]", "Notify[env_test2]", "Notify[module_test3]", "Notify[env_test2-ipl]"]
expect(resources_in(catalog)).to include(*resources_created_in_fixture)
end
it 'gets data from module having a puppet function delivering module data' do
Puppet[:code] = 'include xyz'
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
catalog = compiler.compile()
resources_created_in_fixture = ["Notify[env_test1]", "Notify[env_test2]", "Notify[module_test3]"]
expect(resources_in(catalog)).to include(*resources_created_in_fixture)
end
it 'gets data from puppet function delivering environment data' do
Puppet[:code] = <<-CODE
function environment::data() {
{ 'cls::test1' => 'env_puppet1',
'cls::test2' => 'env_puppet2'
}
}
class cls ($test1, $test2) {
notify { $test1: }
notify { $test2: }
}
include cls
CODE
node = Puppet::Node.new('testnode', :facts => Puppet::Node::Facts.new('facts', {}), :environment => 'production')
catalog = Puppet::Parser::Compiler.new(node).compile
expect(resources_in(catalog)).to include('Notify[env_puppet1]', 'Notify[env_puppet2]')
end
it 'raises an error if the environment data function does not return a hash' do
Puppet[:code] = 'include abc'
# find the loaders to patch with faulty function
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
loaders = compiler.loaders()
env_loader = loaders.private_environment_loader()
f = Puppet::Functions.create_function('environment::data') do
def data()
'this is not a hash'
end
end
env_loader.add_entry(:function, 'environment::data', f.new(compiler.topscope, env_loader), nil)
expect do
compiler.compile()
end.to raise_error(/Value returned from deprecated API function 'environment::data' has wrong type/)
end
it 'raises an error if the module data function does not return a hash' do
Puppet[:code] = 'include abc'
# find the loaders to patch with faulty function
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
loaders = compiler.loaders()
module_loader = loaders.public_loader_for_module('abc')
f = Puppet::Functions.create_function('abc::data') do
def data()
'this is not a hash'
end
end
module_loader.add_entry(:function, 'abc::data', f.new(compiler.topscope, module_loader), nil)
expect do
compiler.compile()
end.to raise_error(/Value returned from deprecated API function 'abc::data' has wrong type/)
end
def parent_fixture(dir_name)
File.absolute_path(File.join(my_fixture_dir(), "../#{dir_name}"))
end
def resources_in(catalog)
catalog.resources.map(&:ref)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/concurrent/thread_local_singleton_spec.rb | spec/unit/concurrent/thread_local_singleton_spec.rb | require 'spec_helper'
require 'puppet/concurrent/thread_local_singleton'
class PuppetSpec::Singleton
extend Puppet::Concurrent::ThreadLocalSingleton
end
# Use the `equal?` matcher to ensure we get the same object
describe Puppet::Concurrent::ThreadLocalSingleton do
it 'returns the same object for a single thread' do
expect(PuppetSpec::Singleton.singleton).to equal(PuppetSpec::Singleton.singleton)
end
it 'is not inherited for a newly created thread' do
main_thread_local = PuppetSpec::Singleton.singleton
Thread.new do
expect(main_thread_local).to_not equal(PuppetSpec::Singleton.singleton)
end.join
end
it 'does not leak outside a thread' do
thread_local = nil
Thread.new do
thread_local = PuppetSpec::Singleton.singleton
end.join
expect(thread_local).to_not equal(PuppetSpec::Singleton.singleton)
end
it 'is different for each thread' do
locals = []
Thread.new do
locals << PuppetSpec::Singleton.singleton
end.join
Thread.new do
locals << PuppetSpec::Singleton.singleton
end.join
expect(locals.first).to_not equal(locals.last)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/concurrent/lock_spec.rb | spec/unit/concurrent/lock_spec.rb | require 'spec_helper'
require 'puppet/concurrent/lock'
describe Puppet::Concurrent::Lock do
if Puppet::Util::Platform.jruby?
context 'on jruby' do
it 'synchronizes a block on itself' do
iterations = 100
value = 0
lock = Puppet::Concurrent::Lock.new
threads = iterations.times.collect do
Thread.new do
lock.synchronize do
tmp = (value += 1)
sleep(0.001)
# This update using tmp is designed to lose increments if threads overlap
value = tmp + 1
end
end
end
threads.each(&:join)
# In my testing this always fails by quite a lot when not synchronized (ie on mri)
expect(value).to eq(iterations * 2)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/scheduler/splay_job_spec.rb | spec/unit/scheduler/splay_job_spec.rb | require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::SplayJob do
let(:run_interval) { 10 }
let(:last_run) { 50 }
let(:splay_limit) { 5 }
let(:start_time) { 23 }
let(:job) { described_class.new(run_interval, splay_limit) }
it "does not apply a splay after the first run" do
job.run(last_run)
expect(job.interval_to_next_from(last_run)).to eq(run_interval)
end
it "calculates the first run splayed from the start time" do
job.start_time = start_time
expect(job.interval_to_next_from(start_time)).to eq(job.splay)
end
it "interval to the next run decreases as time advances" do
time_passed = 3
job.start_time = start_time
expect(job.interval_to_next_from(start_time + time_passed)).to eq(job.splay - time_passed)
end
it "is not immediately ready if splayed" do
job.start_time = start_time
expect(job).to receive(:splay).and_return(6)
expect(job.ready?(start_time)).not_to be
end
it "does not apply a splay if the splaylimit is unchanged" do
old_splay = job.splay
job.splay_limit = splay_limit
expect(job.splay).to eq(old_splay)
end
it "applies a splay if the splaylimit is changed" do
new_splay = 999
allow(job).to receive(:rand).and_return(new_splay)
job.splay_limit = splay_limit + 1
expect(job.splay).to eq(new_splay)
end
it "returns the splay_limit" do
expect(job.splay_limit).to eq(splay_limit)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/scheduler/scheduler_spec.rb | spec/unit/scheduler/scheduler_spec.rb | require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::Scheduler do
let(:now) { 183550 }
let(:timer) { MockTimer.new(now) }
class MockTimer
attr_reader :wait_for_calls
def initialize(start=1729)
@now = start
@wait_for_calls = []
end
def wait_for(seconds)
@wait_for_calls << seconds
@now += seconds
end
def now
@now
end
end
def one_time_job(interval)
Puppet::Scheduler::Job.new(interval) { |j| j.disable }
end
def disabled_job(interval)
job = Puppet::Scheduler::Job.new(interval) { |j| j.disable }
job.disable
job
end
let(:scheduler) { Puppet::Scheduler::Scheduler.new(timer) }
it "uses the minimum interval" do
later_job = one_time_job(7)
earlier_job = one_time_job(2)
later_job.last_run = now
earlier_job.last_run = now
scheduler.run_loop([later_job, earlier_job])
expect(timer.wait_for_calls).to eq([2, 5])
end
it "ignores disabled jobs when calculating intervals" do
enabled = one_time_job(7)
enabled.last_run = now
disabled = disabled_job(2)
scheduler.run_loop([enabled, disabled])
expect(timer.wait_for_calls).to eq([7])
end
it "asks the timer to wait for the job interval" do
job = one_time_job(5)
job.last_run = now
scheduler.run_loop([job])
expect(timer.wait_for_calls).to eq([5])
end
it "does not run when there are no jobs" do
scheduler.run_loop([])
expect(timer.wait_for_calls).to be_empty
end
it "does not run when there are only disabled jobs" do
disabled_job = Puppet::Scheduler::Job.new(0)
disabled_job.disable
scheduler.run_loop([disabled_job])
expect(timer.wait_for_calls).to be_empty
end
it "stops running when there are no more enabled jobs" do
disabling_job = Puppet::Scheduler::Job.new(0) do |j|
j.disable
end
scheduler.run_loop([disabling_job])
expect(timer.wait_for_calls.size).to eq(1)
end
it "marks the start of the run loop" do
disabled_job = Puppet::Scheduler::Job.new(0)
disabled_job.disable
scheduler.run_loop([disabled_job])
expect(disabled_job.start_time).to eq(now)
end
it "calculates the next interval from the start of a job" do
countdown = 2
slow_job = Puppet::Scheduler::Job.new(10) do |job|
timer.wait_for(3)
countdown -= 1
job.disable if countdown == 0
end
scheduler.run_loop([slow_job])
expect(timer.wait_for_calls).to eq([0, 3, 7, 3])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/scheduler/job_spec.rb | spec/unit/scheduler/job_spec.rb | require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::Job do
let(:run_interval) { 10 }
let(:job) { described_class.new(run_interval) }
it "has a minimum run interval of 0" do
expect(Puppet::Scheduler::Job.new(-1).run_interval).to eq(0)
end
describe "when not run yet" do
it "is ready" do
expect(job.ready?(2)).to be
end
it "gives the time to next run as 0" do
expect(job.interval_to_next_from(2)).to eq(0)
end
end
describe "when run at least once" do
let(:last_run) { 50 }
before(:each) do
job.run(last_run)
end
it "is ready when the time is greater than the last run plus the interval" do
expect(job.ready?(last_run + run_interval + 1)).to be
end
it "is ready when the time is equal to the last run plus the interval" do
expect(job.ready?(last_run + run_interval)).to be
end
it "is not ready when the time is less than the last run plus the interval" do
expect(job.ready?(last_run + run_interval - 1)).not_to be
end
context "when calculating the next run" do
it "returns the run interval if now == last run" do
expect(job.interval_to_next_from(last_run)).to eq(run_interval)
end
it "when time is between the last and next runs gives the remaining portion of the run_interval" do
time_since_last_run = 2
now = last_run + time_since_last_run
expect(job.interval_to_next_from(now)).to eq(run_interval - time_since_last_run)
end
it "when time is later than last+interval returns 0" do
time_since_last_run = run_interval + 5
now = last_run + time_since_last_run
expect(job.interval_to_next_from(now)).to eq(0)
end
end
end
it "starts enabled" do
expect(job.enabled?).to be
end
it "can be disabled" do
job.disable
expect(job.enabled?).not_to be
end
it "has the job instance as a parameter" do
passed_job = nil
job = Puppet::Scheduler::Job.new(run_interval) do |j|
passed_job = j
end
job.run(5)
expect(passed_job).to eql(job)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/reports/store_spec.rb | spec/unit/reports/store_spec.rb | require 'spec_helper'
require 'puppet/reports'
require 'time'
require 'pathname'
require 'tempfile'
require 'fileutils'
describe Puppet::Reports.report(:store) do
describe "#process" do
include PuppetSpec::Files
before :each do
Puppet[:reportdir] = File.join(tmpdir('reports'), 'reports')
end
let(:report) do
# It's possible to install Psych 5 with Ruby 2.7, so check whether underlying YAML supports
# unsafe_load_file. This check can be removed in PUP-11718
if YAML.respond_to?(:unsafe_load_file)
report = YAML.unsafe_load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report2.6.x.yaml'))
else
report = YAML.load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report2.6.x.yaml'))
end
report.extend(described_class)
report
end
it "should create a report directory for the client if one doesn't exist" do
report.process
expect(File).to be_directory(File.join(Puppet[:reportdir], report.host))
end
it "should write the report to the file in YAML" do
allow(Time).to receive(:now).and_return(Time.utc(2011,01,06,12,00,00))
report.process
expect(File.read(File.join(Puppet[:reportdir], report.host, "201101061200.yaml"))).to eq(report.to_yaml)
end
it "rejects invalid hostnames" do
report.host = ".."
expect(Puppet::FileSystem).not_to receive(:exist?)
expect { report.process }.to raise_error(ArgumentError, /Invalid node/)
end
end
describe "::destroy" do
it "rejects invalid hostnames" do
expect(Puppet::FileSystem).not_to receive(:unlink)
expect { described_class.destroy("..") }.to raise_error(ArgumentError, /Invalid node/)
end
end
describe "::validate_host" do
['..', 'hello/', '/hello', 'he/llo', 'hello/..', '.'].each do |node|
it "rejects #{node.inspect}" do
expect { described_class.validate_host(node) }.to raise_error(ArgumentError, /Invalid node/)
end
end
['.hello', 'hello.', '..hi', 'hi..'].each do |node|
it "accepts #{node.inspect}" do
described_class.validate_host(node)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/reports/http_spec.rb | spec/unit/reports/http_spec.rb | require 'spec_helper'
require 'puppet/reports'
describe Puppet::Reports.report(:http) do
subject { Puppet::Transaction::Report.new.extend(described_class) }
let(:url) { "https://puppet.example.com/report/upload" }
before :each do
Puppet[:reporturl] = url
end
describe "when setting up the connection" do
it "raises if the connection fails" do
stub_request(:post, url).to_raise(Errno::ECONNREFUSED.new('Connection refused - connect(2)'))
expect {
subject.process
}.to raise_error(Puppet::HTTP::HTTPError, /Request to #{url} failed after .* seconds: .*Connection refused/)
end
it "configures the connection for ssl when using https" do
stub_request(:post, url)
expect_any_instance_of(Net::HTTP).to receive(:start) do |http|
expect(http).to be_use_ssl
expect(http.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER)
end
subject.process
end
it "does not configure the connection for ssl when using http" do
Puppet[:reporturl] = 'http://puppet.example.com:8080/the/path'
stub_request(:post, Puppet[:reporturl])
expect_any_instance_of(Net::HTTP).to receive(:start) do |http|
expect(http).to_not be_use_ssl
end
subject.process
end
end
describe "when making a request" do
it "uses the path specified by the 'reporturl' setting" do
req = stub_request(:post, url)
subject.process
expect(req).to have_been_requested
end
it "uses the username and password specified by the 'reporturl' setting" do
Puppet[:reporturl] = "https://user:pass@puppet.example.com/report/upload"
req = stub_request(:post, %r{/report/upload}).with(basic_auth: ['user', 'pass'])
subject.process
expect(req).to have_been_requested
end
it "passes metric_id options" do
stub_request(:post, url)
expect(Puppet.runtime[:http]).to receive(:post).with(anything, anything, hash_including(options: hash_including(metric_id: [:puppet, :report, :http]))).and_call_original
subject.process
end
it "passes the report as YAML" do
req = stub_request(:post, url).with(body: subject.to_yaml)
subject.process
expect(req).to have_been_requested
end
it "sets content-type to 'application/x-yaml'" do
req = stub_request(:post, url).with(headers: {'Content-Type' => 'application/x-yaml'})
subject.process
expect(req).to have_been_requested
end
it "doesn't log anything if the request succeeds" do
req = stub_request(:post, url).to_return(status: [200, "OK"])
subject.process
expect(req).to have_been_requested
expect(@logs).to eq([])
end
it "follows redirects" do
location = {headers: {'Location' => url}}
req = stub_request(:post, url)
.to_return(**location, status: [301, "Moved Permanently"]).then
.to_return(**location, status: [302, "Found"]).then
.to_return(**location, status: [307, "Temporary Redirect"]).then
.to_return(status: [200, "OK"])
subject.process
expect(req).to have_been_requested.times(4)
end
it "logs an error if the request fails" do
stub_request(:post, url).to_return(status: [500, "Internal Server Error"])
subject.process
expect(@logs).to include(having_attributes(level: :err, message: "Unable to submit report to #{url} [500] Internal Server Error"))
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/property/ensure_spec.rb | spec/unit/property/ensure_spec.rb | require 'spec_helper'
require 'puppet/property/ensure'
klass = Puppet::Property::Ensure
describe klass do
it "should be a subclass of Property" do
expect(klass.superclass).to eq(Puppet::Property)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/property/list_spec.rb | spec/unit/property/list_spec.rb | require 'spec_helper'
require 'puppet/property/list'
list_class = Puppet::Property::List
describe list_class do
it "should be a subclass of Property" do
expect(list_class.superclass).to eq(Puppet::Property)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
list_class.initvars
@resource = double('resource', :[]= => nil, :property => nil)
@property = list_class.new(:resource => @resource)
end
it "should have a , as default delimiter" do
expect(@property.delimiter).to eq(",")
end
it "should have a :membership as default membership" do
expect(@property.membership).to eq(:membership)
end
it "should return the same value passed into should_to_s" do
@property.should_to_s("foo") == "foo"
end
it "should return the passed in array values joined with the delimiter from is_to_s" do
expect(@property.is_to_s(["foo","bar"])).to eq("foo,bar")
end
it "should be able to correctly convert ':absent' to a quoted string" do
expect(@property.is_to_s(:absent)).to eq("'absent'")
end
describe "when adding should to current" do
it "should add the arrays when current is an array" do
expect(@property.add_should_with_current(["foo"], ["bar"])).to eq(["foo", "bar"])
end
it "should return should if current is not an array" do
expect(@property.add_should_with_current(["foo"], :absent)).to eq(["foo"])
end
it "should return only the uniq elements" do
expect(@property.add_should_with_current(["foo", "bar"], ["foo", "baz"])).to eq(["foo", "bar", "baz"])
end
end
describe "when calling inclusive?" do
it "should use the membership method to look up on the @resource" do
expect(@property).to receive(:membership).and_return(:membership)
expect(@resource).to receive(:[]).with(:membership)
@property.inclusive?
end
it "should return true when @resource[membership] == inclusive" do
allow(@property).to receive(:membership).and_return(:membership)
allow(@resource).to receive(:[]).with(:membership).and_return(:inclusive)
expect(@property.inclusive?).to eq(true)
end
it "should return false when @resource[membership] != inclusive" do
allow(@property).to receive(:membership).and_return(:membership)
allow(@resource).to receive(:[]).with(:membership).and_return(:minimum)
expect(@property.inclusive?).to eq(false)
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
expect(@property.should).to eq(nil)
end
it "should return the sorted values of @should as a string if inclusive" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.should).to eq("bar,foo")
end
it "should return the uniq sorted values of @should + retrieve as a string if !inclusive" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(false)
expect(@property).to receive(:retrieve).and_return(["foo","baz"])
expect(@property.should).to eq("bar,baz,foo")
end
end
describe "when calling retrieve" do
let(:provider) { @provider }
before do
@provider = double("provider")
allow(@property).to receive(:provider).and_return(provider)
end
it "should send 'name' to the provider" do
expect(@provider).to receive(:send).with(:group)
expect(@property).to receive(:name).and_return(:group)
@property.retrieve
end
it "should return an array with the provider returned info" do
allow(@provider).to receive(:send).with(:group).and_return("foo,bar,baz")
allow(@property).to receive(:name).and_return(:group)
@property.retrieve == ["foo", "bar", "baz"]
end
it "should return :absent when the provider returns :absent" do
allow(@provider).to receive(:send).with(:group).and_return(:absent)
allow(@property).to receive(:name).and_return(:group)
@property.retrieve == :absent
end
context "and provider is nil" do
let(:provider) { nil }
it "should return :absent" do
@property.retrieve == :absent
end
end
end
describe "when calling safe_insync?" do
it "should return true unless @should is defined and not nil" do
expect(@property).to be_safe_insync("foo")
end
it "should return true unless the passed in values is not nil" do
@property.should = "foo"
expect(@property).to be_safe_insync(nil)
end
it "should call prepare_is_for_comparison with value passed in and should" do
@property.should = "foo"
expect(@property).to receive(:prepare_is_for_comparison).with("bar")
expect(@property).to receive(:should)
@property.safe_insync?("bar")
end
it "should return true if 'is' value is array of comma delimited should values" do
@property.should = "bar,foo"
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property).to be_safe_insync(["bar","foo"])
end
it "should return true if 'is' value is :absent and should value is empty string" do
@property.should = ""
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property).to be_safe_insync([])
end
it "should return false if prepared value != should value" do
@property.should = "bar,baz,foo"
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property).to_not be_safe_insync(["bar","foo"])
end
end
describe "when calling dearrayify" do
it "should sort and join the array with 'delimiter'" do
array = double("array")
expect(array).to receive(:sort).and_return(array)
expect(array).to receive(:join).with(@property.delimiter)
@property.dearrayify(array)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/property/boolean_spec.rb | spec/unit/property/boolean_spec.rb | require 'spec_helper'
require 'puppet/property/boolean'
describe Puppet::Property::Boolean do
let (:resource) { double('resource') }
subject { described_class.new(:resource => resource) }
[ true, :true, 'true', :yes, 'yes', 'TrUe', 'yEs' ].each do |arg|
it "should munge #{arg.inspect} as true" do
expect(subject.munge(arg)).to eq(true)
end
end
[ false, :false, 'false', :no, 'no', 'FaLSE', 'nO' ].each do |arg|
it "should munge #{arg.inspect} as false" do
expect(subject.munge(arg)).to eq(false)
end
end
[ nil, :undef, 'undef', '0', 0, '1', 1, 9284 ].each do |arg|
it "should fail to munge #{arg.inspect}" do
expect { subject.munge(arg) }.to raise_error Puppet::Error
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/property/keyvalue_spec.rb | spec/unit/property/keyvalue_spec.rb | require 'spec_helper'
require 'puppet/property/keyvalue'
describe 'Puppet::Property::KeyValue' do
let(:klass) { Puppet::Property::KeyValue }
it "should be a subclass of Property" do
expect(klass.superclass).to eq(Puppet::Property)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
klass.initvars
@resource = double('resource', :[]= => nil, :property => nil)
@property = klass.new(:resource => @resource)
klass.log_only_changed_or_new_keys = false
end
it "should have a , as default delimiter" do
expect(@property.delimiter).to eq(";")
end
it "should have a = as default separator" do
expect(@property.separator).to eq("=")
end
it "should have a :membership as default membership" do
expect(@property.membership).to eq(:key_value_membership)
end
it "should return the same value passed into should_to_s" do
@property.should_to_s({:foo => "baz", :bar => "boo"}) == "foo=baz;bar=boo"
end
it "should return the passed in hash values joined with the delimiter from is_to_s" do
s = @property.is_to_s({"foo" => "baz" , "bar" => "boo"})
# We can't predict the order the hash is processed in...
expect(["foo=baz;bar=boo", "bar=boo;foo=baz"]).to be_include s
end
describe "when calling hash_to_key_value_s" do
let(:input) do
{
:key1 => "value1",
:key2 => "value2",
:key3 => "value3"
}
end
before(:each) do
@property.instance_variable_set(:@changed_or_new_keys, [:key1, :key2])
end
it "returns only the changed or new keys if log_only_changed_or_new_keys is set" do
klass.log_only_changed_or_new_keys = true
expect(@property.hash_to_key_value_s(input)).to eql("key1=value1;key2=value2")
end
end
describe "when calling inclusive?" do
it "should use the membership method to look up on the @resource" do
expect(@property).to receive(:membership).and_return(:key_value_membership)
expect(@resource).to receive(:[]).with(:key_value_membership)
@property.inclusive?
end
it "should return true when @resource[membership] == inclusive" do
allow(@property).to receive(:membership).and_return(:key_value_membership)
allow(@resource).to receive(:[]).with(:key_value_membership).and_return(:inclusive)
expect(@property.inclusive?).to eq(true)
end
it "should return false when @resource[membership] != inclusive" do
allow(@property).to receive(:membership).and_return(:key_value_membership)
allow(@resource).to receive(:[]).with(:key_value_membership).and_return(:minimum)
expect(@property.inclusive?).to eq(false)
end
end
describe "when calling process_current_hash" do
it "should return {} if hash is :absent" do
expect(@property.process_current_hash(:absent)).to eq({})
end
it "should set every key to nil if inclusive?" do
allow(@property).to receive(:inclusive?).and_return(true)
expect(@property.process_current_hash({:foo => "bar", :do => "re"})).to eq({ :foo => nil, :do => nil })
end
it "should return the hash if !inclusive?" do
allow(@property).to receive(:inclusive?).and_return(false)
expect(@property.process_current_hash({:foo => "bar", :do => "re"})).to eq({:foo => "bar", :do => "re"})
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
expect(@property.should).to eq(nil)
end
it "should call process_current_hash" do
@property.should = ["foo=baz", "bar=boo"]
allow(@property).to receive(:retrieve).and_return({:do => "re", :mi => "fa" })
expect(@property).to receive(:process_current_hash).and_return({})
@property.should
end
it "should return the hashed values of @should and the nilled values of retrieve if inclusive" do
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:retrieve).and_return({:do => "re", :mi => "fa" })
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.should).to eq({ :foo => "baz", :bar => "boo", :do => nil, :mi => nil })
end
it "should return the hashed @should + the unique values of retrieve if !inclusive" do
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:retrieve).and_return({:foo => "diff", :do => "re", :mi => "fa"})
expect(@property).to receive(:inclusive?).and_return(false)
expect(@property.should).to eq({ :foo => "baz", :bar => "boo", :do => "re", :mi => "fa" })
end
it "should mark the keys that will change or be added as a result of our Puppet run" do
@property.should = {
:key1 => "new_value1",
:key2 => "value2",
:key3 => "new_value3",
:key4 => "value4"
}
allow(@property).to receive(:retrieve).and_return(
{
:key1 => "value1",
:key2 => "value2",
:key3 => "value3"
}
)
allow(@property).to receive(:inclusive?).and_return(false)
@property.should
expect(@property.instance_variable_get(:@changed_or_new_keys)).to eql([:key1, :key3, :key4])
end
end
describe "when calling retrieve" do
before do
@provider = double("provider")
allow(@property).to receive(:provider).and_return(@provider)
end
it "should send 'name' to the provider" do
expect(@provider).to receive(:send).with(:keys)
expect(@property).to receive(:name).and_return(:keys)
@property.retrieve
end
it "should return a hash with the provider returned info" do
allow(@provider).to receive(:send).with(:keys).and_return({"do" => "re", "mi" => "fa" })
allow(@property).to receive(:name).and_return(:keys)
@property.retrieve == {"do" => "re", "mi" => "fa" }
end
it "should return :absent when the provider returns :absent" do
allow(@provider).to receive(:send).with(:keys).and_return(:absent)
allow(@property).to receive(:name).and_return(:keys)
@property.retrieve == :absent
end
end
describe "when calling hashify_should" do
it "should return the underlying hash if the user passed in a hash" do
@property.should = { "foo" => "bar" }
expect(@property.hashify_should).to eql({ :foo => "bar" })
end
it "should hashify the array of key/value pairs if that is what our user passed in" do
@property.should = [ "foo=baz", "bar=boo" ]
expect(@property.hashify_should).to eq({ :foo => "baz", :bar => "boo" })
end
end
describe "when calling safe_insync?" do
before do
@provider = double("provider")
allow(@property).to receive(:provider).and_return(@provider)
allow(@property).to receive(:name).and_return(:prop_name)
end
it "should return true unless @should is defined and not nil" do
@property.safe_insync?("foo") == true
end
it "should return true if the passed in values is nil" do
@property.safe_insync?(nil) == true
end
it "should return true if hashified should value == (retrieved) value passed in" do
allow(@provider).to receive(:prop_name).and_return({ :foo => "baz", :bar => "boo" })
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.safe_insync?({ :foo => "baz", :bar => "boo" })).to eq(true)
end
it "should return false if prepared value != should value" do
allow(@provider).to receive(:prop_name).and_return({ "foo" => "bee", "bar" => "boo" })
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.safe_insync?({ "foo" => "bee", "bar" => "boo" })).to eq(false)
end
end
describe 'when validating a passed-in property value' do
it 'should raise a Puppet::Error if the property value is anything but a Hash or a String' do
expect { @property.validate(5) }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("specified as a hash or an array")
end
end
it 'should accept a Hash property value' do
@property.validate({ 'foo' => 'bar' })
end
it "should raise a Puppet::Error if the property value isn't a key/value pair" do
expect { @property.validate('foo') }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("separated by '='")
end
end
it 'should accept a valid key/value pair property value' do
@property.validate('foo=bar')
end
end
describe 'when munging a passed-in property value' do
it 'should return the value as-is if it is a string' do
expect(@property.munge('foo=bar')).to eql('foo=bar')
end
it 'should stringify + symbolize the keys and stringify the values if it is a hash' do
input = {
1 => 2,
true => false,
' foo ' => 'bar'
}
expected_output = {
:'1' => '2',
:true => 'false',
:foo => 'bar'
}
expect(@property.munge(input)).to eql(expected_output)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/property/ordered_list_spec.rb | spec/unit/property/ordered_list_spec.rb | require 'spec_helper'
require 'puppet/property/ordered_list'
describe Puppet::Property::OrderedList do
it "should be a subclass of List" do
expect(described_class.superclass).to eq(Puppet::Property::List)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
described_class.initvars
@resource = double('resource', :[]= => nil, :property => nil)
@property = described_class.new(:resource => @resource)
end
describe "when adding should to current" do
it "should add the arrays when current is an array" do
expect(@property.add_should_with_current(["should"], ["current"])).to eq(["should", "current"])
end
it "should return 'should' if current is not an array" do
expect(@property.add_should_with_current(["should"], :absent)).to eq(["should"])
end
it "should return only the uniq elements leading with the order of 'should'" do
expect(@property.add_should_with_current(["this", "is", "should"], ["is", "this", "current"])).to eq(["this", "is", "should", "current"])
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
expect(@property.should).to eq(nil)
end
it "should return the values of @should (without sorting) as a string if inclusive" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.should).to eq("foo,bar")
end
it "should return the uniq values of @should + retrieve as a string if !inclusive with the @ values leading" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(false)
expect(@property).to receive(:retrieve).and_return(["foo","baz"])
expect(@property.should).to eq("foo,bar,baz")
end
end
describe "when calling dearrayify" do
it "should join the array with the delimiter" do
array = double("array")
expect(array).to receive(:join).with(@property.delimiter)
@property.dearrayify(array)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_system/uniquefile_spec.rb | spec/unit/file_system/uniquefile_spec.rb | require 'spec_helper'
describe Puppet::FileSystem::Uniquefile do
include PuppetSpec::Files
it "makes the name of the file available" do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
expect(file.path).to match(/foo/)
end
end
it "ensures the file has permissions 0600", unless: Puppet::Util::Platform.windows? do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
expect(Puppet::FileSystem.stat(file.path).mode & 07777).to eq(0600)
end
end
it "provides a writeable file" do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
file.write("stuff")
file.flush
expect(Puppet::FileSystem.read(file.path)).to eq("stuff")
end
end
it "returns the value of the block" do
the_value = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
"my value"
end
expect(the_value).to eq("my value")
end
it "unlinks the temporary file" do
filename = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
file.path
end
expect(Puppet::FileSystem.exist?(filename)).to be_falsey
end
it "unlinks the temporary file even if the block raises an error" do
filename = nil
begin
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
filename = file.path
raise "error!"
end
rescue
end
expect(Puppet::FileSystem.exist?(filename)).to be_falsey
end
it "propagates lock creation failures" do
# use an arbitrary exception so as not accidentally collide
# with the ENOENT that occurs when trying to call rmdir
allow(Puppet::FileSystem::Uniquefile).to receive(:mkdir).and_raise('arbitrary failure')
expect(Puppet::FileSystem::Uniquefile).not_to receive(:rmdir)
expect {
Puppet::FileSystem::Uniquefile.open_tmp('foo') { |tmp| }
}.to raise_error('arbitrary failure')
end
it "only removes lock files that exist" do
# prevent the .lock directory from being created
allow(Puppet::FileSystem::Uniquefile).to receive(:mkdir)
# and expect cleanup to be skipped
expect(Puppet::FileSystem::Uniquefile).not_to receive(:rmdir)
Puppet::FileSystem::Uniquefile.open_tmp('foo') { |tmp| }
end
it "reports when a parent directory does not exist" do
dir = tmpdir('uniquefile')
lock = File.join(dir, 'path', 'to', 'lock')
expect {
Puppet::FileSystem::Uniquefile.new('foo', lock) { |tmp| }
}.to raise_error(Errno::ENOENT, %r{No such file or directory - A directory component in .* does not exist or is a dangling symbolic link})
end
it "should use UTF8 characters in TMP,TEMP,TMPDIR environment variable", :if => Puppet::Util::Platform.windows? do
rune_utf8 = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7"
temp_rune_utf8 = File.join(Dir.tmpdir, rune_utf8)
Puppet::FileSystem.mkpath(temp_rune_utf8)
# Set the temporary environment variables to the UTF8 temp path
Puppet::Util::Windows::Process.set_environment_variable('TMPDIR', temp_rune_utf8)
Puppet::Util::Windows::Process.set_environment_variable('TMP', temp_rune_utf8)
Puppet::Util::Windows::Process.set_environment_variable('TEMP', temp_rune_utf8)
# Create a unique file
filename = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
File.dirname(file.path)
end
expect(filename).to eq(temp_rune_utf8)
end
it "preserves tilde characters" do
Puppet::FileSystem::Uniquefile.open_tmp('~foo') do |file|
expect(File.basename(file.path)).to start_with('~foo')
end
end
context "Ruby 1.9.3 Tempfile tests" do
# the remaining tests in this file are ported directly from the ruby 1.9.3 source,
# since most of this file was ported from there
# see: https://github.com/ruby/ruby/blob/v1_9_3_547/test/test_tempfile.rb
def tempfile(*args, &block)
t = Puppet::FileSystem::Uniquefile.new(*args, &block)
@tempfile = (t unless block)
end
after(:each) do
if @tempfile
@tempfile.close!
end
end
it "creates tempfiles" do
t = tempfile("foo")
path = t.path
t.write("hello world")
t.close
expect(File.read(path)).to eq("hello world")
end
it "saves in tmpdir by default" do
t = tempfile("foo")
expect(Dir.tmpdir).to eq(File.dirname(t.path))
end
it "saves in given directory" do
subdir = File.join(Dir.tmpdir, "tempfile-test-#{rand}")
Dir.mkdir(subdir)
begin
tempfile = Tempfile.new("foo", subdir)
tempfile.close
begin
expect(subdir).to eq(File.dirname(tempfile.path))
ensure
tempfile.unlink
end
ensure
Dir.rmdir(subdir)
end
end
it "supports basename" do
t = tempfile("foo")
expect(File.basename(t.path)).to match(/^foo/)
end
it "supports basename with suffix" do
t = tempfile(["foo", ".txt"])
expect(File.basename(t.path)).to match(/^foo/)
expect(File.basename(t.path)).to match(/\.txt$/)
end
it "supports unlink" do
t = tempfile("foo")
path = t.path
t.close
expect(File.exist?(path)).to eq(true)
t.unlink
expect(File.exist?(path)).to eq(false)
expect(t.path).to eq(nil)
end
it "supports closing" do
t = tempfile("foo")
expect(t.closed?).to eq(false)
t.close
expect(t.closed?).to eq(true)
end
it "supports closing and unlinking via boolean argument" do
t = tempfile("foo")
path = t.path
t.close(true)
expect(t.closed?).to eq(true)
expect(t.path).to eq(nil)
expect(File.exist?(path)).to eq(false)
end
context "on unix platforms", :unless => Puppet::Util::Platform.windows? do
it "close doesn't unlink if already unlinked" do
t = tempfile("foo")
path = t.path
t.unlink
File.open(path, "w").close
begin
t.close(true)
expect(File.exist?(path)).to eq(true)
ensure
File.unlink(path) rescue nil
end
end
end
it "supports close!" do
t = tempfile("foo")
path = t.path
t.close!
expect(t.closed?).to eq(true)
expect(t.path).to eq(nil)
expect(File.exist?(path)).to eq(false)
end
context "on unix platforms", :unless => Puppet::Util::Platform.windows? do
it "close! doesn't unlink if already unlinked" do
t = tempfile("foo")
path = t.path
t.unlink
File.open(path, "w").close
begin
t.close!
expect(File.exist?(path)).to eq(true)
ensure
File.unlink(path) rescue nil
end
end
end
it "close does not make path nil" do
t = tempfile("foo")
t.close
expect(t.path.nil?).to eq(false)
end
it "close flushes buffer" do
t = tempfile("foo")
t.write("hello")
t.close
expect(File.size(t.path)).to eq(5)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_system/path_pattern_spec.rb | spec/unit/file_system/path_pattern_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/file_system'
require 'puppet/util'
describe Puppet::FileSystem::PathPattern do
include PuppetSpec::Files
InvalidPattern = Puppet::FileSystem::PathPattern::InvalidPattern
describe 'relative' do
it "can not be created with a traversal up the directory tree" do
expect do
Puppet::FileSystem::PathPattern.relative("my/../other")
end.to raise_error(InvalidPattern, "PathPatterns cannot be created with directory traversals.")
end
it "can be created with a '..' prefixing a filename" do
expect(Puppet::FileSystem::PathPattern.relative("my/..other").to_s).to eq("my/..other")
end
it "can be created with a '..' suffixing a filename" do
expect(Puppet::FileSystem::PathPattern.relative("my/other..").to_s).to eq("my/other..")
end
it "can be created with a '..' embedded in a filename" do
expect(Puppet::FileSystem::PathPattern.relative("my/ot..her").to_s).to eq("my/ot..her")
end
it "can not be created with a \\0 byte embedded" do
expect do
Puppet::FileSystem::PathPattern.relative("my/\0/other")
end.to raise_error(InvalidPattern, "PathPatterns cannot be created with a zero byte.")
end
it "can not be created with a windows drive" do
expect do
Puppet::FileSystem::PathPattern.relative("c:\\relative\\path")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be prefixed with a drive.")
end
it "can not be created with a windows drive (with space)" do
expect do
Puppet::FileSystem::PathPattern.relative(" c:\\relative\\path")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be prefixed with a drive.")
end
it "can not create an absolute relative path" do
expect do
Puppet::FileSystem::PathPattern.relative("/no/absolutes")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be an absolute path.")
end
it "can not create an absolute relative path (with space)" do
expect do
Puppet::FileSystem::PathPattern.relative("\t/no/absolutes")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be an absolute path.")
end
it "can not create a relative path that is a windows path relative to the current drive" do
expect do
Puppet::FileSystem::PathPattern.relative("\\no\relatives")
end.to raise_error(InvalidPattern, "A PathPattern cannot be a Windows current drive relative path.")
end
it "creates a relative PathPattern from a valid relative path" do
expect(Puppet::FileSystem::PathPattern.relative("a/relative/path").to_s).to eq("a/relative/path")
end
it "is not absolute" do
expect(Puppet::FileSystem::PathPattern.relative("a/relative/path")).to_not be_absolute
end
end
describe 'absolute' do
it "can not create a relative absolute path" do
expect do
Puppet::FileSystem::PathPattern.absolute("no/relatives")
end.to raise_error(InvalidPattern, "An absolute PathPattern cannot be a relative path.")
end
it "can not create an absolute path that is a windows path relative to the current drive" do
expect do
Puppet::FileSystem::PathPattern.absolute("\\no\\relatives")
end.to raise_error(InvalidPattern, "A PathPattern cannot be a Windows current drive relative path.")
end
it "creates an absolute PathPattern from a valid absolute path" do
expect(Puppet::FileSystem::PathPattern.absolute("/an/absolute/path").to_s).to eq("/an/absolute/path")
end
it "creates an absolute PathPattern from a valid Windows absolute path" do
expect(Puppet::FileSystem::PathPattern.absolute("c:/absolute/windows/path").to_s).to eq("c:/absolute/windows/path")
end
it "can be created with a '..' embedded in a filename on windows", :if => Puppet::Util::Platform.windows? do
expect(Puppet::FileSystem::PathPattern.absolute(%q{c:\..my\ot..her\one..}).to_s).to eq(%q{c:\..my\ot..her\one..})
end
it "is absolute" do
expect(Puppet::FileSystem::PathPattern.absolute("c:/absolute/windows/path")).to be_absolute
end
end
it "prefixes the relative path pattern with another path" do
pattern = Puppet::FileSystem::PathPattern.relative("docs/*_thoughts.txt")
prefix = Puppet::FileSystem::PathPattern.absolute("/prefix")
absolute_pattern = pattern.prefix_with(prefix)
expect(absolute_pattern).to be_absolute
expect(absolute_pattern.to_s).to eq(File.join("/prefix", "docs/*_thoughts.txt"))
end
it "refuses to prefix with a relative pattern" do
pattern = Puppet::FileSystem::PathPattern.relative("docs/*_thoughts.txt")
prefix = Puppet::FileSystem::PathPattern.relative("prefix")
expect do
pattern.prefix_with(prefix)
end.to raise_error(InvalidPattern, "An absolute PathPattern cannot be a relative path.")
end
it "applies the pattern to the filesystem as a glob" do
dir = tmpdir('globtest')
create_file_in(dir, "found_one")
create_file_in(dir, "found_two")
create_file_in(dir, "third_not_found")
pattern = Puppet::FileSystem::PathPattern.relative("found_*").prefix_with(
Puppet::FileSystem::PathPattern.absolute(dir))
expect(pattern.glob).to match_array([File.join(dir, "found_one"),
File.join(dir, "found_two")])
end
it 'globs wildcard patterns properly' do
# See PUP-11788 and https://github.com/jruby/jruby/issues/7836.
pending 'JRuby does not properly handle Dir.glob' if Puppet::Util::Platform.jruby?
dir = tmpdir('globtest')
create_file_in(dir, 'foo.pp')
create_file_in(dir, 'foo.pp.pp')
pattern = Puppet::FileSystem::PathPattern.absolute(File.join(dir, '**/*.pp'))
expect(pattern.glob).to match_array([File.join(dir, 'foo.pp'),
File.join(dir, 'foo.pp.pp')])
end
def create_file_in(dir, name)
File.open(File.join(dir, name), "w") { |f| f.puts "data" }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.