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
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/get_spec.rb
spec/unit/functions/get_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the get function' do include PuppetSpec::Compiler include Matchers::Resource context 'returns undef value' do it 'when result is undef due to given undef' do expect( evaluate(source: "get(undef, '')")).to be_nil end it 'when result is undef due to navigation into undef' do expect( evaluate(source: "get(undef, '0')")).to be_nil end it 'when navigation results in explicit undef in an array' do expect( evaluate(source: "get([undef], '0')")).to be_nil end it 'when navigation results in explicit undef in a hash' do expect( evaluate(source: "get(a => undef, 'a')")).to be_nil end it 'when navigation references unavailable value in an array' do expect( evaluate(source: "get([1], '2')")).to be_nil end it 'when navigation references unavailable value in a hash' do expect( evaluate(source: "get(a => 43, 'b')")).to be_nil end end context 'returns default value' do it 'when result is undef due to given undef' do expect( evaluate(source: "get(undef, '', 'ok')")).to eql('ok') end it 'when result is undef due to navigation into undef' do expect( evaluate(source: "get(undef, '0', 'ok')")).to eql('ok') end it 'when navigation results in explicit undef in array' do expect( evaluate(source: "get([undef], '0', 'ok')")).to eql('ok') end it 'when navigation results in explicit undef in hash' do expect( evaluate(source: "get(a => undef, 'a', 'ok')")).to eql('ok') end it 'when navigation references unavailable value in an array' do expect( evaluate(source: "get([1], '2', 'ok')")).to eql('ok') end it 'when navigation references unavailable value in a hash' do expect( evaluate(source: "get(a => 43, 'b', 'ok')")).to eql('ok') end end it 'returns value if given empty navigation' do expect(evaluate(source: "get('ok', '')")).to eql('ok') end it 'navigates into array as given by navigation string' do expect( evaluate( source: "get(['nope', ['ok']], '1.0')")).to eql('ok') end it 'navigates into hash as given by navigation string' do expect( evaluate( source: "get(a => 'nope', b=> ['ok'], 'b.0')")).to eql('ok') end it 'navigates into hash with numeric key' do expect( evaluate( source: "get(a => 'nope', 0=> ['ok'], '0.0')")).to eql('ok') end it 'navigates into hash with numeric string but requires quoting' do expect( evaluate( source: "get(a => 'nope', '0'=> ['ok'], '\"0\".0')")).to eql('ok') end it 'can navigate a key with . when it is quoted' do expect( evaluate( variables: {'x' => {'a.b' => ['nope', ['ok']]}}, source: "get($x, '\"a.b\".1.0')" ) ).to eql('ok') end it 'an error is raised when navigating with string key into an array' do expect { evaluate(source: "get(['nope', ['ok']], '1.blue')") }.to raise_error(/The given data requires an Integer index/) end it 'calls a given block with EXPECTED_INTEGER_INDEX if navigating into array with string' do expect(evaluate( source: "get(['nope', ['ok']], '1.blue') |$error| { if $error.issue_code =~ /^EXPECTED_INTEGER_INDEX$/ {'ok'} else { 'nope'} }" )).to eql('ok') end it 'calls a given block with EXPECTED_COLLECTION if navigating into something not Undef or Collection' do expect(evaluate( source: "get(['nope', /nah/], '1.blue') |$error| { if $error.issue_code =~ /^EXPECTED_COLLECTION$/ {'ok'} else { 'nope'} }" )).to eql('ok') end context 'it does not pick the default value when undef is returned by error handling block' do it 'for "expected integer" case' do expect(evaluate( source: "get(['nope', ['ok']], '1.blue', 'nope') |$msg| { undef }" )).to be_nil end it 'for "expected collection" case' do expect(evaluate( source: "get(['nope', /nah/], '1.blue') |$msg| { undef }" )).to be_nil end end it 'does not call a given block if navigation string has syntax error' do expect { evaluate(source: "get(['nope', /nah/], '1....') |$msg| { fail('so sad') }") }.to raise_error(/Syntax error/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/call_spec.rb
spec/unit/functions/call_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the call method' do include PuppetSpec::Compiler include PuppetSpec::Files include Matchers::Resource context "should be callable as" 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) { { 'modules' => { 'test' => { 'functions' => { 'call_me.pp' => 'function test::call_me() { "called" }', 'abc.pp' => 'function test::abc() { "a-b-c" }', 'dash.pp' => 'function test::dash() { "-" }' } } } } } let(:populated_env_dir) do dir_contained_in(environments_dir, env_name => env_dir_files) PuppetSpec::Files.record_tmp(env_dir) env_dir end it 'call on a built-in 4x Ruby API function' do expect(compile_to_catalog(<<-CODE, node)).to have_resource('Notify[a]') $a = call('split', 'a-b-c', '-') notify { $a[0]: } CODE end it 'call on a Puppet language function with no arguments' do expect(compile_to_catalog(<<-CODE, node)).to have_resource('Notify[called]') notify { test::call_me(): } CODE end it 'call a Ruby 4x API built-in with block' do catalog = compile_to_catalog(<<-CODE, node) $a = 'each' $b = [1,2,3] call($a, $b) |$index, $v| { file { "/file_$v": ensure => present } } CODE expect(catalog.resource(:file, "/file_1")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_2")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present') end it 'call with the calling context' do expect(eval_and_collect_notices(<<-CODE, node)).to eq(['a']) class a { call('notice', $title) } include a CODE end it 'call on a non-existent function name' do expect { compile_to_catalog(<<-CODE, node) }.to raise_error(Puppet::Error, /Unknown function/) $a = call('not_a_function_name') notify { $a: } CODE end it 'call a deferred value' do expect(compile_to_catalog(<<-CODE, node)).to have_resource('Notify[a]') $d = Deferred('split', ['a-b-c', '-']) $a = $d.call() notify { $a[0]: } CODE end it 'resolves deferred value arguments in an array when calling a deferred' do expect(compile_to_catalog(<<-CODE,node)).to have_resource('Notify[a]') $d = Deferred('split', [Deferred('test::abc'), '-']) $a = $d.call() notify { $a[0]: } CODE end it 'resolves deferred value arguments in a Sensitive when calling a deferred' do expect(compile_to_catalog(<<-CODE, node)).to have_resource('Notify[a]') function my_split(Sensitive $sensy, $on) { $sensy.unwrap |$x| { split($x, $on) } } $d = Deferred('my_split', [ Sensitive(Deferred('test::abc')), '-']) $a = $d.call() notify { $a[0]: } CODE end it 'resolves deferred value arguments in a Hash when calling a deferred' do expect(compile_to_catalog(<<-CODE, node)).to have_resource('Notify[a]') function my_split(Hash $hashy, $on) { split($hashy['key'], $on) } $d = Deferred('my_split', [ {'key' => Deferred('test::abc')}, '-']) $a = $d.call() notify { $a[0]: } CODE end it 'resolves deferred value arguments in a nested structure when calling a deferred' do expect(compile_to_catalog(<<-CODE,node)).to have_resource('Notify[a]') function my_split(Hash $hashy, Array[Sensitive] $sensy) { split($hashy['key'][0], $sensy[0].unwrap |$x| {$x}) } $d = Deferred('my_split', [ {'key' => [Deferred('test::abc')]}, [Sensitive(Deferred('test::dash'))]]) $a = $d.call() notify { $a[0]: } CODE end it 'call dig into a variable' do expect(compile_to_catalog(<<-CODE, node)).to have_resource('Notify[value 3]') $x = { 'a' => [1,2,3] } $d = Deferred('$x', ['a', 2]) $a = $d.call() notify { "value $a": } CODE end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/keys_spec.rb
spec/unit/functions/keys_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the keys function' do include PuppetSpec::Compiler include Matchers::Resource it 'returns the keys in the hash in the order they appear in a hash iteration' do expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[apples & oranges]') $k = {'apples' => 1, 'oranges' => 2}.keys notify { "${k[0]} & ${k[1]}": } SRC end it 'returns an empty array for an empty hash' do expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[0]') $v = {}.keys.reduce(0) |$m, $v| { $m+1 } notify { "${v}": } SRC end it 'includes an undef key if one is present in the hash' do expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[Undef]') $types = {undef => 1}.keys.map |$v| { $v.type } notify { "${types[0]}": } SRC end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/lookup_fixture_spec.rb
spec/unit/functions/lookup_fixture_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet_spec/files' require 'puppet/pops' require 'deep_merge/core' # Tests the lookup function using fixtures describe 'The lookup function' do include PuppetSpec::Compiler # Assembles code that includes the *abc* class and compiles it into a catalog. This class will use the global # variable $args to perform a lookup and assign the result to $abc::result. Unless the $block is set to # the string 'no_block_present', it will be passed as a lambda to the lookup. The assembled code will declare # a notify resource with a name that is formed by interpolating the result into a format string. # # The method performs the folloging steps. # # - Build the code that: # - sets the $args variable from _lookup_args_ # - sets the $block parameter to the given block or the string 'no_block_present' # - includes the abc class # - assigns the $abc::result to $r # - interpolates a string using _fmt_ (which is assumed to use $r) # - declares a notify resource from the interpolated string # - Compile the code into a catalog # - Return the name of all Notify resources in that catalog # # @param fmt [String] The puppet interpolated string used when creating the notify title # @param *args [String] splat of args that will be concatenated to form the puppet args sent to lookup # @return [Array<String>] List of names of Notify resources in the resulting catalog # def assemble_and_compile(fmt, *lookup_args, &block) assemble_and_compile_with_block(fmt, "'no_block_present'", *lookup_args, &block) end def assemble_and_compile_with_block(fmt, block, *lookup_args, &cblock) compile_and_get_notifications(<<-END.unindent, &cblock) $args = [#{lookup_args.join(',')}] $block = #{block} include abc $r = if $abc::result == undef { 'no_value' } else { $abc::result } notify { \"#{fmt}\": } END end def compile_and_get_notifications(code) Puppet[:code] = code node.environment.check_for_reparse catalog = block_given? ? compiler.compile { |cat| yield(compiler.topscope); cat } : compiler.compile catalog.resources.map(&:ref).filter_map { |r| r[7..-2] if r.start_with?('Notify[') } end # There is a fully configured 'production' environment in fixtures at this location let(:environmentpath) { File.join(my_fixture_dir, 'environments') } let(:node) { Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production') } let(:compiler) { Puppet::Parser::Compiler.new(node) } 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, '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. # environments = Puppet::Environments::Directories.new(environmentpath, []) Puppet.override(:environments => environments) do example.run end end context 'using valid parameters' do it 'can lookup value provided by the environment' do resources = assemble_and_compile('${r}', "'abc::a'") expect(resources).to include('env_a') end it 'can lookup value provided by the module' do resources = assemble_and_compile('${r}', "'abc::b'") expect(resources).to include('module_b') end it "can lookup value provided by the module that has 'function' data_provider entry in metadata.json" do resources = compile_and_get_notifications("$args = ['meta::b']\ninclude meta\nnotify { $meta::result: }\n") expect(resources).to include('module_b') end it 'can lookup value provided in global scope' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = assemble_and_compile('${r}', "'abc::a'") expect(resources).to include('global_a') end it 'will stop at first found name when several names are provided' do resources = assemble_and_compile('${r}', "['abc::b', 'abc::a']") expect(resources).to include('module_b') end it 'can lookup value provided by the module that is overriden by environment' do resources = assemble_and_compile('${r}', "'abc::c'") expect(resources).to include('env_c') end it "can 'unique' merge values provided by both the module and the environment" do resources = assemble_and_compile('${r[0]}_${r[1]}', "'abc::c'", 'Array[String]', "'unique'") expect(resources).to include('env_c_module_c') end it "can 'hash' merge values provided by the environment only" do resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::d'", 'Hash[String,String]', "'hash'") expect(resources).to include('env_d1_env_d2_env_d3') end it "can 'hash' merge values provided by both the environment and the module" do resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::e'", 'Hash[String,String]', "'hash'") expect(resources).to include('env_e1_module_e2_env_e3') end it "can 'hash' merge values provided by global, environment, and module" do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::e'", 'Hash[String,String]', "'hash'") expect(resources).to include('global_e1_module_e2_env_e3') end it "can pass merge parameter in the form of a hash with a 'strategy=>unique'" do resources = assemble_and_compile('${r[0]}_${r[1]}', "'abc::c'", 'Array[String]', "{strategy => 'unique'}") expect(resources).to include('env_c_module_c') end it "can pass merge parameter in the form of a hash with 'strategy=>hash'" do resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::e'", 'Hash[String,String]', "{strategy => 'hash'}") expect(resources).to include('env_e1_module_e2_env_e3') end it "can pass merge parameter in the form of a hash with a 'strategy=>deep'" do resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::e'", 'Hash[String,String]', "{strategy => 'deep'}") expect(resources).to include('env_e1_module_e2_env_e3') end it "will fail unless merge in the form of a hash contains a 'strategy'" do expect do assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::e'", 'Hash[String,String]', "{merge_key => 'hash'}") end.to raise_error(Puppet::ParseError, /hash given as 'merge' must contain the name of a strategy/) end it 'will raise an exception when value is not found for single key and no default is provided' do expect do assemble_and_compile('${r}', "'abc::x'") end.to raise_error(Puppet::ParseError, /did not find a value for the name 'abc::x'/) end it 'can lookup an undef value' do resources = assemble_and_compile('${r}', "'abc::n'") expect(resources).to include('no_value') end it 'will not replace an undef value with a given default' do resources = assemble_and_compile('${r}', "'abc::n'", 'undef', 'undef', '"default_n"') expect(resources).to include('no_value') end it 'will not accept a succesful lookup of an undef value when the type rejects it' do expect do assemble_and_compile('${r}', "'abc::n'", 'String') end.to raise_error(Puppet::ParseError, /Found value has wrong type, expects a String value, got Undef/) end it 'will raise an exception when value is not found for array key and no default is provided' do expect do assemble_and_compile('${r}', "['abc::x', 'abc::y']") end.to raise_error(Puppet::ParseError, /did not find a value for any of the names \['abc::x', 'abc::y'\]/) end it 'can lookup and deep merge shallow values provided by the environment only' do resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::d'", 'Hash[String,String]', "'deep'") expect(resources).to include('env_d1_env_d2_env_d3') end it 'can lookup and deep merge shallow values provided by both the module and the environment' do resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::e'", 'Hash[String,String]', "'deep'") expect(resources).to include('env_e1_module_e2_env_e3') end it 'can lookup and deep merge deep values provided by global, environment, and module' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = assemble_and_compile('${r[k1][s1]}_${r[k1][s2]}_${r[k1][s3]}_${r[k2][s1]}_${r[k2][s2]}_${r[k2][s3]}', "'abc::f'", 'Hash[String,Hash[String,String]]', "'deep'") expect(resources).to include('global_f11_env_f12_module_f13_env_f21_module_f22_global_f23') end it 'will propagate resolution_type :array to Hiera when merge == \'unique\'' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = assemble_and_compile('${r[0]}_${r[1]}_${r[2]}', "'abc::c'", 'Array[String]', "'unique'") expect(resources).to include('global_c_env_c_module_c') end it 'will propagate a Hash resolution_type with :behavior => :native to Hiera when merge == \'hash\'' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = assemble_and_compile('${r[k1]}_${r[k2]}_${r[k3]}', "'abc::e'", 'Hash[String,String]', "{strategy => 'hash'}") expect(resources).to include('global_e1_module_e2_env_e3') end it 'will propagate a Hash resolution_type with :behavior => :deeper to Hiera when merge == \'deep\'' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = assemble_and_compile('${r[k1][s1]}_${r[k1][s2]}_${r[k1][s3]}_${r[k2][s1]}_${r[k2][s2]}_${r[k2][s3]}', "'abc::f'", 'Hash[String,Hash[String,String]]', "'deep'") expect(resources).to include('global_f11_env_f12_module_f13_env_f21_module_f22_global_f23') end it 'will propagate a Hash resolution_type with symbolic deep merge options to Hiera' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = assemble_and_compile('${r[k1][s1]}_${r[k1][s2]}_${r[k1][s3]}_${r[k2][s1]}_${r[k2][s2]}_${r[k2][s3]}', "'abc::f'", 'Hash[String,Hash[String,String]]', "{ 'strategy' => 'deep', 'knockout_prefix' => '--' }") expect(resources).to include('global_f11_env_f12_module_f13_env_f21_module_f22_global_f23') end context 'with provided default' do it 'will return default when lookup fails' do resources = assemble_and_compile('${r}', "'abc::x'", 'String', 'undef', "'dflt_x'") expect(resources).to include('dflt_x') end it 'can precede default parameter with undef as the value_type and undef as the merge type' do resources = assemble_and_compile('${r}', "'abc::x'", 'undef', 'undef', "'dflt_x'") expect(resources).to include('dflt_x') end it 'can use array' do resources = assemble_and_compile('${r[0]}_${r[1]}', "'abc::x'", 'Array[String]', 'undef', "['dflt_x', 'dflt_y']") expect(resources).to include('dflt_x_dflt_y') end it 'can use hash' do resources = assemble_and_compile('${r[a]}_${r[b]}', "'abc::x'", 'Hash[String,String]', 'undef', "{'a' => 'dflt_x', 'b' => 'dflt_y'}") expect(resources).to include('dflt_x_dflt_y') end it 'fails unless default is an instance of value_type' do expect do assemble_and_compile('${r[a]}_${r[b]}', "'abc::x'", 'Hash[String,String]', 'undef', "{'a' => 'dflt_x', 'b' => 32}") end.to raise_error(Puppet::ParseError, /Default value has wrong type, entry 'b' expects a String value, got Integer/) end end context 'with a default block' do it 'will be called when lookup fails' do resources = assemble_and_compile_with_block('${r}', "'dflt_x'", "'abc::x'") expect(resources).to include('dflt_x') end it 'will not called when lookup succeeds but the found value is nil' do resources = assemble_and_compile_with_block('${r}', "'dflt_x'", "'abc::n'") expect(resources).to include('no_value') end it 'can use array' do resources = assemble_and_compile_with_block('${r[0]}_${r[1]}', "['dflt_x', 'dflt_y']", "'abc::x'") expect(resources).to include('dflt_x_dflt_y') end it 'can use hash' do resources = assemble_and_compile_with_block('${r[a]}_${r[b]}', "{'a' => 'dflt_x', 'b' => 'dflt_y'}", "'abc::x'") expect(resources).to include('dflt_x_dflt_y') end it 'can return undef from block' do resources = assemble_and_compile_with_block('${r}', 'undef', "'abc::x'") expect(resources).to include('no_value') end it 'fails unless block returns an instance of value_type' do expect do assemble_and_compile_with_block('${r[a]}_${r[b]}', "{'a' => 'dflt_x', 'b' => 32}", "'abc::x'", 'Hash[String,String]') end.to raise_error(Puppet::ParseError, /Value returned from default block has wrong type, entry 'b' expects a String value, got Integer/) end it 'receives a single name parameter' do resources = assemble_and_compile_with_block('${r}', 'true', "'name_x'") expect(resources).to include('name_x') end it 'receives an array name parameter' do resources = assemble_and_compile_with_block('${r[0]}_${r[1]}', 'true', "['name_x', 'name_y']") expect(resources).to include('name_x_name_y') end end end context 'and using dotted keys' do it 'can access values in data using dot notation' do source = <<-PUPPET function environment::data() { { a => { b => { c => 'the data' }}} } notice(lookup('a.b.c')) PUPPET expect(eval_and_collect_notices(source)).to include('the data') end it 'can find data using quoted dot notation' do source = <<-PUPPET function environment::data() { { 'a.b.c' => 'the data' } } notice(lookup('"a.b.c"')) PUPPET expect(eval_and_collect_notices(source)).to include('the data') end it 'can access values in data using a mix of dot notation and quoted dot notation' do source = <<-PUPPET function environment::data() { { 'a' => { 'b.c' => 'the data' }} } notice(lookup('a."b.c"')) PUPPET expect(eval_and_collect_notices(source)).to include('the data') end end context 'passing a hash as the only parameter' do it 'can pass a single name correctly' do resources = assemble_and_compile('${r}', "{name => 'abc::a'}") expect(resources).to include('env_a') end it 'can pass a an array of names correctly' do resources = assemble_and_compile('${r}', "{name => ['abc::b', 'abc::a']}") expect(resources).to include('module_b') end it 'can pass an override map and find values there even though they would be found' do resources = assemble_and_compile('${r}', "{name => 'abc::a', override => { abc::a => 'override_a'}}") expect(resources).to include('override_a') end it 'can pass an default_values_hash and find values there correctly' do resources = assemble_and_compile('${r}', "{name => 'abc::x', default_values_hash => { abc::x => 'extra_x'}}") expect(resources).to include('extra_x') end it 'can pass an default_values_hash but not use it when value is found elsewhere' do resources = assemble_and_compile('${r}', "{name => 'abc::a', default_values_hash => { abc::a => 'extra_a'}}") expect(resources).to include('env_a') end it 'can pass an default_values_hash but not use it when value is found elsewhere even when found value is undef' do resources = assemble_and_compile('${r}', "{name => 'abc::n', default_values_hash => { abc::n => 'extra_n'}}") expect(resources).to include('no_value') end it 'can pass an override and an default_values_hash and find the override value' do resources = assemble_and_compile('${r}', "{name => 'abc::x', override => { abc::x => 'override_x'}, default_values_hash => { abc::x => 'extra_x'}}") expect(resources).to include('override_x') end it 'will raise an exception when value is not found for single key and no default is provided' do expect do assemble_and_compile('${r}', "{name => 'abc::x'}") end.to raise_error(Puppet::ParseError, /did not find a value for the name 'abc::x'/) end it 'will not raise an exception when value is not found default value is nil' do resources = assemble_and_compile('${r}', "{name => 'abc::x', default_value => undef}") expect(resources).to include('no_value') end end context 'accessing from outside a module' do it 'will both log a warning and raise an exception when key in the function provided module data is not prefixed' do logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = "include bad_data\nlookup('bad_data::b')" expect { compiler.compile }.to raise_error(Puppet::ParseError, /did not find a value for the name 'bad_data::b'/) end warnings = logs.filter_map { |log| log.message if log.level == :warning } expect(warnings).to include("Module 'bad_data': Value returned from deprecated API function 'bad_data::data' must use keys qualified with the name of the module; got b") end it 'will succeed finding prefixed keys even when a key in the function provided module data is not prefixed' do logs = [] resources = nil Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do resources = compile_and_get_notifications(<<-PUPPET.unindent) include bad_data notify { lookup('bad_data::c'): } PUPPET expect(resources).to include('module_c') end warnings = logs.filter_map { |log| log.message if log.level == :warning } expect(warnings).to include("Module 'bad_data': Value returned from deprecated API function 'bad_data::data' must use keys qualified with the name of the module; got b") end it 'will resolve global, environment, and module correctly' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = compile_and_get_notifications(<<-PUPPET.unindent) include bca $r = lookup(bca::e, Hash[String,String], hash) notify { "${r[k1]}_${r[k2]}_${r[k3]}": } PUPPET expect(resources).to include('global_e1_module_bca_e2_env_bca_e3') end it 'will resolve global and environment correctly when module has no provider' do Puppet.settings[:hiera_config] = File.join(my_fixture_dir, 'hiera.yaml') resources = compile_and_get_notifications(<<-PUPPET.unindent) include no_provider $r = lookup(no_provider::e, Hash[String,String], hash) notify { "${r[k1]}_${r[k2]}_${r[k3]}": } PUPPET expect(resources).to include('global_e1__env_no_provider_e3') # k2 is missing end end context 'accessing bad data' do it 'a warning will be logged when key in the function provided module data is not prefixed' do Puppet[:code] = "include bad_data\nlookup('bad_data::c')" logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile end warnings = logs.filter_map { |log| log.message if log.level == :warning } expect(warnings).to include("Module 'bad_data': Value returned from deprecated API function 'bad_data::data' must use keys qualified with the name of the module; got b") end it 'a warning will be logged when key in the hiera provided module data is not prefixed' do Puppet[:code] = "include hieraprovider\nlookup('hieraprovider::test::param_a')" logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile end warnings = logs.filter_map { |log| log.message if log.level == :warning } expect(warnings).to include("Module 'hieraprovider': Value returned from data_hash function 'json_data', when using location '#{environmentpath}/production/modules/hieraprovider/data/first.json', must use keys qualified with the name of the module; got test::param_b") end end context 'accessing empty files' do # An empty YAML file is OK and should be treated as a file that contains no keys it "will fail normally with a 'did not find a value' error when a yaml file is empty" do Puppet[:code] = "include empty_yaml\nlookup('empty_yaml::a')" expect { compiler.compile }.to raise_error(Puppet::ParseError, /did not find a value for the name 'empty_yaml::a'/) end # An empty JSON file is not OK. Should yield a parse error it "will fail with a LookupError indicating a parser failure when a json file is empty" do Puppet[:code] = "include empty_json\nlookup('empty_json::a')" expect { compiler.compile }.to raise_error(Puppet::DataBinding::LookupError, /Unable to parse/) end end context 'accessing nil values' do it 'will find a key with undef value in a yaml file' do Puppet[:code] = 'include empty_key_yaml' compiler.compile do |catalog| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true) begin Puppet::Pops::Lookup.lookup('empty_key_yaml::has_undef_value', nil, nil, false, nil, lookup_invocation) rescue Puppet::Error end expect(lookup_invocation.explainer.explain).to include(<<-EOS.unindent(' ')) Path "#{environmentpath}/production/modules/empty_key_yaml/data/empty_key.yaml" Original path: "empty_key" Found key: "empty_key_yaml::has_undef_value" value: nil EOS end end it 'will find a key with undef value in a json file' do Puppet[:code] = 'include empty_key_json' compiler.compile do |catalog| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true) begin Puppet::Pops::Lookup.lookup('empty_key_json::has_undef_value', nil, nil, false, nil, lookup_invocation) rescue Puppet::Error end expect(lookup_invocation.explainer.explain).to include(<<-EOS.unindent(' ')) Path "#{environmentpath}/production/modules/empty_key_json/data/empty_key.json" Original path: "empty_key" Found key: "empty_key_json::has_undef_value" value: nil EOS end end end context 'using explain' do it 'will explain that module is not found' do Puppet[:code] = 'undef' compiler.compile do |catalog| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true) begin Puppet::Pops::Lookup.lookup('ppx::e', nil, nil, false, nil, lookup_invocation) rescue Puppet::Error end expect(lookup_invocation.explainer.explain).to include('Module "ppx" not found') end end it 'will explain that module does not find a key' do Puppet[:code] = 'undef' compiler.compile do |catalog| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true) begin Puppet::Pops::Lookup.lookup('abc::x', nil, nil, false, nil, lookup_invocation) rescue Puppet::Error end expect(lookup_invocation.explainer.explain).to include(<<-EOS.unindent(' ')) Module "abc" Data Provider (hiera configuration version 5) Deprecated API function "abc::data" No such key: "abc::x" EOS end end it 'will explain deep merge results without options' do assemble_and_compile('${r}', "'abc::a'") do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, true) Puppet::Pops::Lookup.lookup('abc::e', Puppet::Pops::Types::TypeParser.singleton.parse('Hash[String,String]'), nil, false, 'deep', lookup_invocation) expect(lookup_invocation.explainer.explain).to eq(<<-EOS.unindent) Searching for "abc::e" Merge strategy deep Global Data Provider (hiera configuration version 5) No such key: "abc::e" Environment Data Provider (hiera configuration version 5) Deprecated API function "environment::data" Found key: "abc::e" value: { "k1" => "env_e1", "k3" => "env_e3" } Module "abc" Data Provider (hiera configuration version 5) Deprecated API function "abc::data" Found key: "abc::e" value: { "k1" => "module_e1", "k2" => "module_e2" } Merged result: { "k1" => "env_e1", "k2" => "module_e2", "k3" => "env_e3" } EOS end end it 'will explain deep merge results with options' do assemble_and_compile('${r}', "'abc::a'") do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, true) Puppet::Pops::Lookup.lookup('abc::e', Puppet::Pops::Types::TypeParser.singleton.parse('Hash[String,String]'), nil, false, { 'strategy' => 'deep', 'merge_hash_arrays' => true }, lookup_invocation) expect(lookup_invocation.explainer.explain).to include(<<-EOS.unindent(' ')) Merge strategy deep Options: { "merge_hash_arrays" => true } EOS end end it 'will handle merge when no entries are not found' do assemble_and_compile('${r}', "'hieraprovider::test::param_a'") do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, true) begin Puppet::Pops::Lookup.lookup('hieraprovider::test::not_found', nil, nil, false, 'deep', lookup_invocation) rescue Puppet::DataBinding::LookupError end expect(lookup_invocation.explainer.explain).to eq(<<-EOS.unindent) Searching for "hieraprovider::test::not_found" Merge strategy deep Global Data Provider (hiera configuration version 5) No such key: "hieraprovider::test::not_found" Environment Data Provider (hiera configuration version 5) Deprecated API function "environment::data" No such key: "hieraprovider::test::not_found" Module "hieraprovider" Data Provider (hiera configuration version 4) Using configuration "#{environmentpath}/production/modules/hieraprovider/hiera.yaml" Hierarchy entry "two paths" Merge strategy deep Path "#{environmentpath}/production/modules/hieraprovider/data/first.json" Original path: "first" No such key: "hieraprovider::test::not_found" Path "#{environmentpath}/production/modules/hieraprovider/data/second_not_present.json" Original path: "second_not_present" Path not found EOS end end it 'will explain value access caused by dot notation in key' do assemble_and_compile('${r}', "'abc::a'") do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, true) Puppet::Pops::Lookup.lookup('abc::f.k1.s1', Puppet::Pops::Types::TypeParser.singleton.parse('String'), nil, false, nil, lookup_invocation) expect(lookup_invocation.explainer.explain).to include(<<-EOS.unindent(' ')) Sub key: "k1.s1" Found key: "k1" value: { "s1" => "env_f11", "s2" => "env_f12" } Found key: "s1" value: "env_f11" EOS end end it 'will provide a hash containing all explanation elements' do assemble_and_compile('${r}', "'abc::a'") do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, true) Puppet::Pops::Lookup.lookup('abc::e', Puppet::Pops::Types::TypeParser.singleton.parse('Hash[String,String]'), nil, false, { 'strategy' => 'deep', 'merge_hash_arrays' => true }, lookup_invocation) expect(lookup_invocation.explainer.to_hash).to eq( { :type => :root, :key => 'abc::e', :branches => [ { :value => { 'k1' => 'env_e1', 'k2' => 'module_e2', 'k3' => 'env_e3' }, :event => :result, :merge => :deep, :options => { 'merge_hash_arrays' => true }, :type => :merge, :branches => [ { :key => 'abc::e', :event => :not_found, :type => :data_provider, :name => 'Global Data Provider (hiera configuration version 5)' }, { :type => :data_provider, :name => 'Environment Data Provider (hiera configuration version 5)', :branches => [ { :type => :data_provider, :name => 'Deprecated API function "environment::data"', :key => 'abc::e', :value => { 'k1' => 'env_e1', 'k3' => 'env_e3' }, :event => :found } ] }, { :type => :data_provider, :name => 'Module "abc" Data Provider (hiera configuration version 5)', :module => 'abc', :branches => [ { :type => :data_provider, :name => 'Deprecated API function "abc::data"', :key => 'abc::e', :event => :found, :value => { 'k1' => 'module_e1', 'k2' => 'module_e2' } } ] } ] } ] } ) end end it 'will explain that "lookup_options" is an invalid key' do assemble_and_compile('${r}', "'abc::a'") do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, true) begin Puppet::Pops::Lookup.lookup('lookup_options', nil, nil, false, nil, lookup_invocation) rescue Puppet::Error end expect(lookup_invocation.explainer.explain.chomp).to eq('Invalid key "lookup_options"') end end it 'will explain that "lookup_options" is an invalid key for any key starting with "lookup_options."' do assemble_and_compile('${r}', "'abc::a'") do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, true) begin Puppet::Pops::Lookup.lookup('lookup_options.subkey', nil, nil, false, nil, lookup_invocation) rescue Puppet::Error end expect(lookup_invocation.explainer.explain.chomp).to eq('Invalid key "lookup_options"') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/each_spec.rb
spec/unit/functions/each_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'shared_behaviours/iterative_functions' describe 'the each method' do include PuppetSpec::Compiler context "should be callable as" do it 'each on an array selecting each value' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $a.each |$v| { file { "/file_$v": ensure => present } } MANIFEST expect(catalog.resource(:file, "/file_1")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_2")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present') end it 'each on an array selecting each value - function call style' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] each ($a) |$index, $v| { file { "/file_$v": ensure => present } } MANIFEST expect(catalog.resource(:file, "/file_1")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_2")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present') end it 'each on an array with index' do catalog = compile_to_catalog(<<-MANIFEST) $a = [present, absent, present] $a.each |$k,$v| { file { "/file_${$k+1}": ensure => $v } } MANIFEST expect(catalog.resource(:file, "/file_1")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_2")['ensure']).to eq('absent') expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present') end it 'each on a hash selecting entries' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>'present','b'=>'absent','c'=>'present'} $a.each |$e| { file { "/file_${e[0]}": ensure => $e[1] } } MANIFEST expect(catalog.resource(:file, "/file_a")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_b")['ensure']).to eq('absent') expect(catalog.resource(:file, "/file_c")['ensure']).to eq('present') end it 'each on a hash selecting key and value' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>present,'b'=>absent,'c'=>present} $a.each |$k, $v| { file { "/file_$k": ensure => $v } } MANIFEST expect(catalog.resource(:file, "/file_a")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_b")['ensure']).to eq('absent') expect(catalog.resource(:file, "/file_c")['ensure']).to eq('present') end it 'each on a hash selecting key and value (using captures-last parameter)' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>present,'b'=>absent,'c'=>present} $a.each |*$kv| { file { "/file_${kv[0]}": ensure => $kv[1] } } MANIFEST expect(catalog.resource(:file, "/file_a")['ensure']).to eq('present') expect(catalog.resource(:file, "/file_b")['ensure']).to eq('absent') expect(catalog.resource(:file, "/file_c")['ensure']).to eq('present') end end context "should produce receiver" do it 'each checking produced value using single expression' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, 3, 2] $b = $a.each |$x| { "unwanted" } file { "/file_${b[1]}": ensure => present } MANIFEST expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present') end end it_should_behave_like 'all iterative functions argument checks', 'each' it_should_behave_like 'all iterative functions hash handling', 'each' end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/strip_spec.rb
spec/unit/functions/strip_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the strip function' do include PuppetSpec::Compiler include Matchers::Resource it 'removes leading and trailing whitepsace' do expect(compile_to_catalog("notify { String(\" abc\t\n \".strip == 'abc'): }")).to have_resource('Notify[true]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.strip == 42): }")).to have_resource('Notify[true]') end it 'returns rstripped version of each entry in an array' do expect(compile_to_catalog("notify { String([' a ', ' b ', ' c '].strip == ['a', 'b', 'c']): }")).to have_resource('Notify[true]') end it 'returns rstripped version of each entry in an Iterator' do expect(compile_to_catalog("notify { String([' a ', ' b ', ' c '].reverse_each.strip == ['c', 'b', 'a']): }")).to have_resource('Notify[true]') end it 'errors when given a a nested Array' do expect { compile_to_catalog("['a', 'b', ['c']].strip")}.to raise_error(/'strip' parameter 'arg' expects a value of type Numeric, String, or Iterable/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/join_spec.rb
spec/unit/functions/join_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the join function' do include PuppetSpec::Compiler include Matchers::Resource it 'joins an array with empty string delimiter if delimiter is not given' do expect(compile_to_catalog("notify { join([1,2,3]): }")).to have_resource('Notify[123]') end it 'joins an array with given string delimiter' do expect(compile_to_catalog("notify { join([1,2,3],'x'): }")).to have_resource('Notify[1x2x3]') end it 'results in empty string if array is empty' do expect(compile_to_catalog('notify { "x${join([])}y": }')).to have_resource('Notify[xy]') end it 'flattens nested arrays' do expect(compile_to_catalog("notify { join([1,2,[3,4]]): }")).to have_resource('Notify[1234]') end it 'does not flatten arrays nested in hashes' do if Gem::Requirement.create(['>= 3.4.0']).satisfied_by?(Gem::Version.new(RUBY_VERSION.dup)) expect(compile_to_catalog("notify { join([1,2,{a => [3,4]}]): }")).to have_resource('Notify[12{"a" => [3, 4]}]') else expect(compile_to_catalog("notify { join([1,2,{a => [3,4]}]): }")).to have_resource('Notify[12{"a"=>[3, 4]}]') end end it 'formats nil/undef as empty string' do expect(compile_to_catalog('notify { join([undef, undef], "x"): }')).to have_resource('Notify[x]') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/round_spec.rb
spec/unit/functions/round_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the round function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an integer' do [ 0, 1, -1].each do |x| it "called as round(#{x}) results in the same value" do expect(compile_to_catalog("notify { String( round(#{x}) == #{x}): }")).to have_resource("Notify[true]") end end end context 'for a float' do { 0.0 => 0, 1.1 => 1, -1.1 => -1, 2.9 => 3, 2.1 => 2, 2.49 => 2, 2.50 => 3, -2.9 => -3, }.each_pair do |x, expected| it "called as round(#{x}) results in #{expected}" do expect(compile_to_catalog("notify { String( round(#{x}) == #{expected}): }")).to have_resource("Notify[true]") end end end [[1,2,3], {'a' => 10}, '"42"'].each do |x| it "errors for a value of class #{x.class}" do expect{ compile_to_catalog("round(#{x})") }.to raise_error(/expects a Numeric value/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/lookup_spec.rb
spec/unit/functions/lookup_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet_spec/files' require 'puppet/pops' require 'deep_merge/core' describe "The lookup function" do include PuppetSpec::Compiler include PuppetSpec::Files let(:env_name) { 'spec' } let(:code_dir_files) { {} } let(:code_dir) { tmpdir('code') } let(:ruby_dir) { tmpdir('ruby') } let(:env_modules) { {} } let(:env_hiera_yaml) do <<-YAML.unindent --- version: 5 hierarchy: - name: "Common" data_hash: yaml_data path: "common.yaml" YAML end let(:env_data) { {} } let(:environment_files) do { env_name => { 'modules' => env_modules, 'hiera.yaml' => env_hiera_yaml, 'data' => env_data } } end let(:logs) { [] } let(:scope_additions ) { {} } 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 } } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, env_name, 'modules')]) } let(:environments) { Puppet::Environments::Directories.new(populated_env_dir, []) } let(:node) { Puppet::Node.new('test_lookup', :environment => env) } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:lookup_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'lookup') } let(:invocation_with_explain) { Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true) } let(:explanation) { invocation_with_explain.explainer.explain } let(:populated_code_dir) do dir_contained_in(code_dir, code_dir_files) code_dir end let(:env_dir) do d = File.join(populated_code_dir, 'environments') Dir.mkdir(d) d end let(:populated_env_dir) do dir_contained_in(env_dir, environment_files) env_dir end before(:each) do Puppet.settings[:codedir] = code_dir Puppet.push_context(:environments => environments, :current_environment => env) end after(:each) do Puppet.pop_context if Object.const_defined?(:Hiera) Hiera.send(:remove_instance_variable, :@config) if Hiera.instance_variable_defined?(:@config) Hiera.send(:remove_instance_variable, :@logger) if Hiera.instance_variable_defined?(:@logger) if Hiera.const_defined?(:Config) Hiera::Config.send(:remove_instance_variable, :@config) if Hiera::Config.instance_variable_defined?(:@config) end if Hiera.const_defined?(:Backend) && Hiera::Backend.respond_to?(:clear!) Hiera::Backend.clear! end end end def collect_notices(code, explain = false, &block) Puppet[:code] = code Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do scope = compiler.topscope scope['domain'] = 'example.com' scope_additions.each_pair { |k, v| scope[k] = v } if explain begin invocation_with_explain.lookup('dummy', nil) do if block_given? compiler.compile { |catalog| block.call(compiler.topscope); catalog } else compiler.compile end end rescue RuntimeError => e invocation_with_explain.report_text { e.message } end else if block_given? compiler.compile { |catalog| block.call(compiler.topscope); catalog } else compiler.compile end end end nil end def lookup(key, options = {}, explain = false, type = nil) value_type = type ? ", #{type}" : '' nc_opts = options.empty? ? '' : ", #{Puppet::Pops::Types::TypeFormatter.string(options)}" keys = key.is_a?(Array) ? key : [key] collect_notices(keys.map { |k| "notice(String(lookup('#{k}'#{value_type}#{nc_opts}), '%p'))" }.join("\n"), explain) if explain explanation else result = notices.map { |n| Puppet::Pops::Types::TypeParser.singleton.parse_literal(n) } key.is_a?(Array) ? result : result[0] end end def explain(key, options = {}) lookup(key, options, true)[1] explanation end context 'with faulty hiera.yaml configuration' do context 'in global layer' do let(:global_data) do { 'common.yaml' => <<-YAML.unindent a: value a (from global) YAML } end let(:code_dir_files) do { 'hiera.yaml' => hiera_yaml, 'data' => global_data } end before(:each) do # Need to set here since spec_helper defines these settings in its "before each" Puppet.settings[:codedir] = populated_code_dir Puppet.settings[:hiera_config] = File.join(code_dir, 'hiera.yaml') end context 'using a not yet supported hiera version' do let(:hiera_yaml) { <<-YAML.unindent } version: 6 YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error("This runtime does not support hiera.yaml version 6 (file: #{code_dir}/hiera.yaml)") end end context 'with multiply defined backend using hiera version 3' do let(:hiera_yaml) { <<-YAML.unindent } :version: 3 :backends: - yaml - json - yaml YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "Backend 'yaml' is defined more than once. First defined at (line: 3) (file: #{code_dir}/hiera.yaml, line: 5)") end end context 'using hiera version 4' do let(:hiera_yaml) { <<-YAML.unindent } version: 4 YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "hiera.yaml version 4 cannot be used in the global layer (file: #{code_dir}/hiera.yaml)") end end context 'using hiera version 5' do context 'with multiply defined hierarchy' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common path: common.yaml - name: Other path: other.yaml - name: Common path: common.yaml YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "Hierarchy name 'Common' defined more than once. First defined at (line: 3) (file: #{code_dir}/hiera.yaml, line: 7)") end end context 'with hiera3_backend that is provided as data_hash function' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common hiera3_backend: hocon path: common.conf YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "Use \"data_hash: hocon_data\" instead of \"hiera3_backend: hocon\" (file: #{code_dir}/hiera.yaml, line: 4)") end end context 'with no data provider function defined' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 defaults: datadir: data hierarchy: - name: Common path: common.txt YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "One of data_hash, lookup_key, data_dig, or hiera3_backend must be defined in hierarchy 'Common' (file: #{code_dir}/hiera.yaml)") end end context 'with multiple data providers in defaults' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 defaults: data_hash: yaml_data lookup_key: eyaml_lookup_key datadir: data hierarchy: - name: Common path: common.txt YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "Only one of data_hash, lookup_key, data_dig, or hiera3_backend can be defined in defaults (file: #{code_dir}/hiera.yaml)") end end context 'with non existing data provider function' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common data_hash: nonesuch_txt_data path: common.yaml YAML it 'fails and reports error' do Puppet[:strict] = :error expect { lookup('a') }.to raise_error( "Unable to find 'data_hash' function named 'nonesuch_txt_data' (file: #{code_dir}/hiera.yaml)") end end context 'with a declared default_hierarchy' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common path: common.yaml default_hierarchy: - name: Defaults path: defaults.yaml YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "'default_hierarchy' is only allowed in the module layer (file: #{code_dir}/hiera.yaml, line: 5)") end end context 'with missing variables' do let(:scope_additions) { { 'fqdn' => 'test.example.com' } } let(:hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common # don't report this line %{::nonesuch} path: "%{::fqdn}/%{::nonesuch}/data.yaml" YAML it 'fails and reports errors when strict == error' do expect { lookup('a') }.to raise_error("Function lookup() did not find a value for the name 'a'") end end context 'using interpolation functions' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common # don't report this line %{::nonesuch} path: "%{lookup('fqdn')}/data.yaml" YAML it 'fails and reports errors when strict == error' do expect { lookup('a') }.to raise_error("Interpolation using method syntax is not allowed in this context (file: #{code_dir}/hiera.yaml)") end end end end context 'in environment layer' do context 'using hiera version 4' do context 'with an unknown backend' do let(:env_hiera_yaml) { <<-YAML.unindent } version: 4 hierarchy: - name: Common backend: nonesuch path: common.yaml YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "No data provider is registered for backend 'nonesuch' (file: #{env_dir}/spec/hiera.yaml, line: 4)") end end context 'with multiply defined hierarchy' do let(:env_hiera_yaml) { <<-YAML.unindent } version: 4 hierarchy: - name: Common backend: yaml path: common.yaml - name: Other backend: yaml path: other.yaml - name: Common backend: yaml path: common.yaml YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "Hierarchy name 'Common' defined more than once. First defined at (line: 3) (file: #{env_dir}/spec/hiera.yaml, line: 9)") end end end context 'using hiera version 5' do context 'with a hiera3_backend declaration' do let(:env_hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common hiera3_backend: something YAML it 'fails and reports error' do expect { lookup('a') }.to raise_error( "'hiera3_backend' is only allowed in the global layer (file: #{env_dir}/spec/hiera.yaml, line: 4)") end end context 'with a declared default_hierarchy' do let(:env_hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: Common path: common.yaml default_hierarchy: - name: Defaults path: defaults.yaml YAML it 'fails and reports error' do Puppet[:strict] = :error expect { lookup('a') }.to raise_error( "'default_hierarchy' is only allowed in the module layer (file: #{env_dir}/spec/hiera.yaml, line: 5)") end end end end end context 'with an environment' do let(:env_data) do { 'common.yaml' => <<-YAML.unindent --- a: value a (from environment) c: c_b: value c_b (from environment) mod_a::a: value mod_a::a (from environment) mod_a::hash_a: a: value mod_a::hash_a.a (from environment) mod_a::hash_b: a: value mod_a::hash_b.a (from environment) hash_b: hash_ba: bab: value hash_b.hash_ba.bab (from environment) hash_c: hash_ca: caa: value hash_c.hash_ca.caa (from environment) lookup_options: mod_a::hash_b: merge: hash hash_c: merge: hash YAML } end it 'finds data in the environment' do expect(lookup('a')).to eql('value a (from environment)') end context 'with log-level debug' do before(:each) { Puppet[:log_level] = 'debug' } it 'does not report a regular lookup as APL' do expect(lookup('a')).to eql('value a (from environment)') expect(debugs.count { |dbg| dbg =~ /\A\s*Automatic Parameter Lookup of/ }).to eql(0) end it 'reports regular lookup as lookup' do expect(lookup('a')).to eql('value a (from environment)') expect(debugs.count { |dbg| dbg =~ /\A\s*Lookup of/ }).to eql(1) end it 'does not report APL as lookup' do collect_notices("class mod_a($a) { notice($a) }; include mod_a") expect(debugs.count { |dbg| dbg =~ /\A\s*Lookup of/ }).to eql(0) end it 'reports APL as APL' do collect_notices("class mod_a($a) { notice($a) }; include mod_a") expect(debugs.count { |dbg| dbg =~ /\A\s*Automatic Parameter Lookup of/ }).to eql(1) end end context 'that has no lookup configured' do let(:environment_files) do { env_name => { 'data' => env_data } } end it 'does not find data in the environment' do expect { lookup('a') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'a'/) end context "but an environment.conf with 'environment_data_provider=hiera'" do let(:environment_files) do { env_name => { 'environment.conf' => "environment_data_provider=hiera\n", 'data' => env_data } } end it 'finds data in the environment and reports deprecation warning for environment.conf' do expect(lookup('a')).to eql('value a (from environment)') expect(warnings).to include(/Defining environment_data_provider='hiera' in environment.conf is deprecated. A 'hiera.yaml' file should be used instead/) end context 'and a hiera.yaml file' do let(:env_hiera_yaml) do <<-YAML.unindent --- version: 4 hierarchy: - name: common backend: yaml YAML end let(:environment_files) do { env_name => { 'hiera.yaml' => env_hiera_yaml, 'environment.conf' => "environment_data_provider=hiera\n", 'data' => env_data } } end it 'finds data in the environment and reports deprecation warnings for both environment.conf and hiera.yaml' do expect(lookup('a')).to eql('value a (from environment)') expect(warnings).to include(/Defining environment_data_provider='hiera' in environment.conf is deprecated/) expect(warnings).to include(/Use of 'hiera.yaml' version 4 is deprecated. It should be converted to version 5/) end end end context "but an environment.conf with 'environment_data_provider=function'" do let(:environment_files) do { env_name => { 'environment.conf' => "environment_data_provider=function\n", 'functions' => { 'environment' => { 'data.pp' => <<-PUPPET.unindent } function environment::data() { { 'a' => 'value a' } } PUPPET } } } end it 'finds data in the environment and reports deprecation warning for environment.conf' do expect(lookup('a')).to eql('value a') expect(warnings).to include(/Defining environment_data_provider='function' in environment.conf is deprecated. A 'hiera.yaml' file should be used instead/) expect(warnings).to include(/Using of legacy data provider function 'environment::data'. Please convert to a 'data_hash' function/) end end end context 'that has interpolated paths configured' do let(:env_hiera_yaml) do <<-YAML.unindent --- version: 5 hierarchy: - name: "Varying" data_hash: yaml_data path: "#{data_path}" YAML end let(:environment_files) do { env_name => { 'hiera.yaml' => env_hiera_yaml, 'modules' => {}, 'data' => { 'x.yaml' => <<-YAML.unindent, y: value y from x YAML 'x_d.yaml' => <<-YAML.unindent, y: value y from x_d YAML 'x_e.yaml' => <<-YAML.unindent, y: value y from x_e YAML } } } end context 'using local variable reference' do let(:data_path) { 'x%{var.sub}.yaml' } it 'reloads the configuration if interpolated values change' do Puppet[:log_level] = 'debug' collect_notices("notice('success')") do |scope| scope['var'] = {} expect(lookup_func.call(scope, 'y')).to eql('value y from x') nested_scope = scope.compiler.newscope(scope) nested_scope['var'] = { 'sub' => '_d' } expect(lookup_func.call(nested_scope, 'y')).to eql('value y from x_d') nested_scope = scope.compiler.newscope(scope) nested_scope['var'] = { 'sub' => '_e' } expect(lookup_func.call(nested_scope, 'y')).to eql('value y from x_e') end expect(notices).to eql(['success']) expect(debugs.any? { |m| m =~ /Hiera configuration recreated due to change of scope variables used in interpolation expressions/ }).to be_truthy end it 'does not include the lookups performed during stability check in explain output' do Puppet[:log_level] = 'debug' collect_notices("notice('success')") do |scope| var = { 'sub' => '_d' } scope['var'] = var expect(lookup_func.call(scope, 'y')).to eql('value y from x_d') # Second call triggers the check expect(lookup_func.call(scope, 'y')).to eql('value y from x_d') end expect(notices).to eql(['success']) expect(debugs.any? { |m| m =~ /Sub key: "sub"/ }).to be_falsey end end context 'using global variable reference' do let(:data_path) { 'x%{::var.sub}.yaml' } it 'does not raise an error when reloads the configuration if interpolating undefined values' do collect_notices("notice('success')") do |scope| expect { lookup_func.call(scope, 'y') }.to_not raise_error end end it 'does not reload the configuration if value changes locally' do Puppet[:log_level] = 'debug' collect_notices("notice('success')") do |scope| scope['var'] = { 'sub' => '_d' } expect(lookup_func.call(scope, 'y')).to eql('value y from x_d') nested_scope = scope.compiler.newscope(scope) nested_scope['var'] = { 'sub' => '_e' } expect(lookup_func.call(nested_scope, 'y')).to eql('value y from x_d') end expect(notices).to eql(['success']) expect(debugs.any? { |m| m =~ /Hiera configuration recreated due to change of scope variables used in interpolation expressions/ }).to be_falsey end end end context 'that uses reserved' do let(:environment_files) do { env_name => { 'hiera.yaml' => hiera_yaml } } end context 'option' do let(:hiera_yaml) { <<-YAML.unindent } version: 5 hierarchy: - name: "Illegal" options: #{opt_spec} data_hash: yaml_data YAML context 'path' do let(:opt_spec) { 'path: data/foo.yaml' } it 'fails and reports the reserved option key' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/Option key 'path' used in hierarchy 'Illegal' is reserved by Puppet/) end end end context 'uri' do let(:opt_spec) { 'uri: file:///data/foo.yaml' } it 'fails and reports the reserved option key' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/Option key 'uri' used in hierarchy 'Illegal' is reserved by Puppet/) end end end end context 'default option' do let(:hiera_yaml) { <<-YAML.unindent } --- version: 5 defaults: options: #{opt_spec} hierarchy: - name: "Illegal" data_hash: yaml_data YAML context 'path' do let(:opt_spec) { 'path: data/foo.yaml' } it 'fails and reports the reserved option key' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/Option key 'path' used in defaults is reserved by Puppet/) end end end context 'uri' do let(:opt_spec) { 'uri: file:///data/foo.yaml' } it 'fails and reports the reserved option key' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/Option key 'uri' used in defaults is reserved by Puppet/) end end end end end context 'with yaml data file' do let(:environment_files) do { env_name => { 'hiera.yaml' => <<-YAML.unindent, --- version: 5 YAML 'data' => { 'common.yaml' => common_yaml } } } end context 'that contains hash values with interpolated keys' do let(:common_yaml) do <<-YAML.unindent --- a: "%{key}": "the %{value}" b: "Detail in %{lookup('a.a_key')}" YAML end it 'interpolates both key and value"' do Puppet[:log_level] = 'debug' collect_notices("notice('success')") do |scope| scope['key'] = '' scope['value'] = '' expect(lookup_func.call(scope, 'a')).to eql({'' => 'the '}) nested_scope = scope.compiler.newscope(scope) nested_scope['key'] = 'a_key' nested_scope['value'] = 'interpolated value' expect(lookup_func.call(nested_scope, 'a')).to eql({'a_key' => 'the interpolated value'}) end expect(notices).to eql(['success']) end it 'navigates to a value behind an interpolated key"' do Puppet[:log_level] = 'debug' collect_notices("notice('success')") do |scope| scope['key'] = 'a_key' scope['value'] = 'interpolated value' expect(lookup_func.call(scope, 'a.a_key')).to eql('the interpolated value') end expect(notices).to eql(['success']) end it 'navigates to a value behind an interpolated key using an interpolated value"' do Puppet[:log_level] = 'debug' collect_notices("notice('success')") do |scope| scope['key'] = 'a_key' scope['value'] = 'interpolated value' expect(lookup_func.call(scope, 'b')).to eql('Detail in the interpolated value') end expect(notices).to eql(['success']) end end context 'that is empty' do let(:common_yaml) { '' } it 'fails with a "did not find"' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/did not find a value for the name 'a'/) end end it 'logs a warning that the file does not contain a hash' do expect { lookup('a') }.to raise_error(Puppet::DataBinding::LookupError) expect(warnings).to include(/spec\/data\/common.yaml: file does not contain a valid yaml hash/) end end context 'that contains illegal yaml' do let(:common_yaml) { "@!#%**&:\n" } it 'fails lookup and that the key is not found' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/Unable to parse/) end end end context 'that contains a legal yaml that is not a hash' do let(:common_yaml) { "- A list\n- of things" } it 'fails with a "invalid yaml hash"' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/spec\/data\/common.yaml: file does not contain a valid yaml hash/) end end context 'when strict mode is off' do before :each do Puppet[:strict] = :warning end it 'fails with a "did not find"' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/did not find a value for the name 'a'/) end end it 'logs a warning that the file does not contain a hash' do expect { lookup('a') }.to raise_error(Puppet::DataBinding::LookupError) expect(warnings).to include(/spec\/data\/common.yaml: file does not contain a valid yaml hash/) end end end context 'that contains a legal yaml hash with illegal types' do let(:common_yaml) do <<-YAML.unindent --- a: !ruby/object:Puppet::Graph::Key value: x YAML end it 'fails lookup and reports parsing failed' do expect { lookup('a') }.to raise_error do |e| expect(e.message).to match(/Unable to parse .*: Tried to load unspecified class: Puppet::Graph::Key/) end end end context 'that contains a legal yaml hash with unexpected types' do let(:common_yaml) do <<-YAML.unindent --- a: 123 YAML end it 'fails lookup and reports a type mismatch' do expect { lookup('a', {}, false, String) }.to raise_error do |e| expect(e.message).to match(/Found value has wrong type, expects a String value, got Integer \(line: 1, column: \d+\)/) end end end context 'that contains illegal interpolations' do context 'in the form of an alias that is not the entire string' do let(:common_yaml) { <<-YAML.unindent } a: "%{alias('x')} and then some" x: value x YAML it 'fails lookup and reports a type mismatch' do expect { lookup('a') }.to raise_error("'alias' interpolation is only permitted if the expression is equal to the entire string") end end context 'in the form of an unknown function name' do let(:common_yaml) { <<-YAML.unindent } a: "%{what('x')}" x: value x YAML it 'fails lookup and reports a type mismatch' do expect { lookup('a') }.to raise_error("Unknown interpolation method 'what'") end end end context 'that contains an array with duplicates' do let(:common_yaml) { <<-YAML.unindent } a: - alpha - bravo - charlie - bravo YAML it 'retains the duplicates when using default merge strategy' do expect(lookup('a')).to eql(%w(alpha bravo charlie bravo)) end it 'does deduplification when using merge strategy "unique"' do expect(lookup('a', :merge => 'unique')).to eql(%w(alpha bravo charlie)) end end end context 'with lookup_options' do let(:environment_files) do { env_name => { 'hiera.yaml' => <<-YAML.unindent, --- version: 5 YAML 'data' => { 'common.yaml' => common_yaml } } } end context 'that are empty' do let(:common_yaml) { <<-YAML.unindent } lookup_options: a: b YAML it 'ignores empty options' do expect(lookup('a')).to eq("b") end end context 'that contains a legal yaml hash with unexpected types' do let(:common_yaml) { <<-YAML.unindent } lookup_options: :invalid_symbol YAML it 'fails lookup and reports a type mismatch' do expect { lookup('a') }.to raise_error(Puppet::DataBinding::LookupError, /has wrong type, expects Puppet::LookupValue, got Runtime\[ruby, 'Symbol'\]/) end end end context 'with lookup_options configured using patterns' do let(:mod_common) { <<-YAML.unindent mod::hash_a: aa: aaa: aaa (from module) ab: aba: aba (from module) mod::hash_b: ba: baa: baa (from module) bb: bba: bba (from module) lookup_options: '^mod::ha.*_a': merge: deep '^mod::ha.*_b': merge: deep YAML } let(:mod_base) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => mod_common } } end let(:env_modules) do { 'mod' => mod_base } end let(:env_hiera_yaml) do <<-YAML.unindent --- version: 5 hierarchy: - name: X paths: - first.yaml - second.yaml YAML end let(:env_lookup_options) { <<-YAML.unindent } lookup_options: b: merge: hash '^[^b]$': merge: deep '^c': merge: first '^b': merge: first '^mod::ha.*_b': merge: hash YAML let(:env_data) do { 'first.yaml' => <<-YAML.unindent + env_lookup_options, a: aa: aaa: a.aa.aaa b: ba: baa: b.ba.baa bb: bba: b.bb.bba c: ca: caa: c.ca.caa mod::hash_a: aa: aab: aab (from environment) ab: aba: aba (from environment) abb: abb (from environment) mod::hash_b: ba: bab: bab (from environment) bc:
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/unwrap_spec.rb
spec/unit/functions/unwrap_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the unwrap function' do include PuppetSpec::Compiler include Matchers::Resource it 'unwraps a sensitive value' do code = <<-CODE $sensitive = Sensitive.new("12345") notice("unwrapped value is ${sensitive.unwrap}") CODE expect(eval_and_collect_notices(code)).to eq(['unwrapped value is 12345']) end it 'just returns a non-sensitive value' do code = <<-CODE $non_sensitive = "12345" notice("value is still ${non_sensitive.unwrap}") CODE expect(eval_and_collect_notices(code)).to eq(['value is still 12345']) end it 'unwraps a sensitive value when given a code block' do code = <<-CODE $sensitive = Sensitive.new("12345") $split = $sensitive.unwrap |$unwrapped| { notice("unwrapped value is $unwrapped") $unwrapped.split(/3/) } notice("split is $split") CODE expect(eval_and_collect_notices(code)).to eq(['unwrapped value is 12345', 'split is [12, 45]']) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/tree_each_spec.rb
spec/unit/functions/tree_each_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'shared_behaviours/iterative_functions' describe 'the tree_each function' do include PuppetSpec::Compiler context "can be called on" do it 'an Array, yielding path and value when lambda has arity 2' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each() |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [] value: [1, 2, 3]', 'path: [0] value: 1', 'path: [1] value: 2', 'path: [2] value: 3', '' ].join("\n")) end it 'an Array, yielding only value when lambda has arity 1' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each() | $v| { -%> path: - value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: - value: [1, 2, 3]', 'path: - value: 1', 'path: - value: 2', 'path: - value: 3', '' ].join("\n")) end it 'a Hash, yielding path and value when lambda has arity 2' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>'apple','b'=>'banana'} $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each() |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [] value: {a => apple, b => banana}', 'path: [a] value: apple', 'path: [b] value: banana', '' ].join("\n")) end it 'a Hash, yielding only value when lambda has arity 1' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>'apple','b'=>'banana'} $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each() | $v| { -%> path: - value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: - value: {a => apple, b => banana}', 'path: - value: apple', 'path: - value: banana', '' ].join("\n")) end it 'an Object, yielding path and value when lambda has arity 2' do # this also tests that include_refs => true includes references catalog = compile_to_catalog(<<-MANIFEST) type Person = Object[{attributes => { name => String, father => Optional[Person], mother => { kind => reference, type => Optional[Person] } }}] $adam = Person({name => 'Adam'}) $eve = Person({name => 'Eve'}) $cain = Person({name => 'Cain', mother => $eve, father => $adam}) $awan = Person({name => 'Awan', mother => $eve, father => $adam}) $enoch = Person({name => 'Enoch', mother => $awan, father => $cain}) $msg = inline_epp(@(TEMPLATE)) <% $enoch.tree_each({include_containers=>false, include_refs => true}) |$path, $v| { unless $v =~ Undef {-%> path: <%= $path %> value: <%= $v %> <% }} -%> | TEMPLATE notify {'with_refs': message => $msg} MANIFEST expect(catalog.resource(:notify, 'with_refs')['message']).to eq( [ 'path: [name] value: Enoch', 'path: [father, name] value: Cain', 'path: [father, father, name] value: Adam', 'path: [father, mother, name] value: Eve', 'path: [mother, name] value: Awan', 'path: [mother, father, name] value: Adam', 'path: [mother, mother, name] value: Eve', '' ].join("\n")) end end context 'a yielded path' do it 'holds integer values for Array index at each level' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each() |$path, $v| { -%> path: <%= $path %> t: <%= $path.map |$x| { type($x, generalized) } %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [] t: [] value: [1, [2, [3]]]', 'path: [0] t: [Integer] value: 1', 'path: [1] t: [Integer] value: [2, [3]]', 'path: [1, 0] t: [Integer, Integer] value: 2', 'path: [1, 1] t: [Integer, Integer] value: [3]', 'path: [1, 1, 0] t: [Integer, Integer, Integer] value: 3', '' ].join("\n")) end it 'holds Any values for Hash keys at each level' do catalog = compile_to_catalog(<<-MANIFEST) $a = {a => 1, /fancy/=> {c => 2, d=>{[e] => 3}}} $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each() |$path, $v| { -%> path: <%= $path %> t: <%= $path.map |$x| { type($x, generalized) } %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [] t: [] value: {a => 1, /fancy/ => {c => 2, d => {[e] => 3}}}', 'path: [a] t: [String] value: 1', 'path: [/fancy/] t: [Regexp[/fancy/]] value: {c => 2, d => {[e] => 3}}', 'path: [/fancy/, c] t: [Regexp[/fancy/], String] value: 2', 'path: [/fancy/, d] t: [Regexp[/fancy/], String] value: {[e] => 3}', 'path: [/fancy/, d, [e]] t: [Regexp[/fancy/], String, Array[String]] value: 3', '' ].join("\n")) end end it 'errors when asked to operate on a String' do expect { compile_to_catalog(<<-MANIFEST) "hello".tree_each() |$path, $v| { notice "$v" } MANIFEST }.to raise_error(/expects a value of type Iterator, Array, Hash, or Object/) end context 'produces' do it 'the receiver when given a lambda' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, 3, 2] $b = $a.tree_each |$path, $x| { "unwanted" } file { "/file_${b[1]}": ensure => present } MANIFEST expect(catalog.resource(:file, "/file_3")['ensure']).to eq('present') end it 'an Iterator when not given a lambda' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, 3, 2] $b = $a.tree_each file { "/file_${$b =~ Iterator}": ensure => present } MANIFEST expect(catalog.resource(:file, "/file_true")['ensure']).to eq('present') end end context 'a produced iterator' do ['depth_first', 'breadth_first'].each do |order| context "for #{order} can be unrolled by creating an Array using" do it "the () operator" do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, 3, 2] $b = Array($a.tree_each({order => #{order}})) $msg = inline_epp(@(TEMPLATE)) <% $b.each() |$v| { -%> path: <%= $v[0] %> value: <%= $v[1] %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, "test")['message']).to eq([ 'path: [] value: [1, 3, 2]', 'path: [0] value: 1', 'path: [1] value: 3', 'path: [2] value: 2', '' ].join("\n")) end it "the splat operator" do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, 3, 2] $b = *$a.tree_each({order => #{order}}) assert_type(Array[Array], $b) $msg = inline_epp(@(TEMPLATE)) <% $b.each() |$v| { -%> path: <%= $v[0] %> value: <%= $v[1] %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, "test")['message']).to eq([ 'path: [] value: [1, 3, 2]', 'path: [0] value: 1', 'path: [1] value: 3', 'path: [2] value: 2', '' ].join("\n")) end end end end context 'recursively yields under the control of options such that' do it 'both containers and leafs are included by default' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each() |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [] value: [1, [2, [3]]]', 'path: [0] value: 1', 'path: [1] value: [2, [3]]', 'path: [1, 0] value: 2', 'path: [1, 1] value: [3]', 'path: [1, 1, 0] value: 3', '' ].join("\n")) end it 'containers are skipped when option include_containers=false is used' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({include_containers => false}) |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [0] value: 1', 'path: [1, 0] value: 2', 'path: [1, 1, 0] value: 3', '' ].join("\n")) end it 'values are skipped when option include_values=false is used' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({include_values => false}) |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [] value: [1, [2, [3]]]', 'path: [1] value: [2, [3]]', 'path: [1, 1] value: [3]', '' ].join("\n")) end it 'the root container is skipped when option include_root=false is used' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({include_root => false, include_values => false}) |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [1] value: [2, [3]]', 'path: [1, 1] value: [3]', '' ].join("\n")) end it 'containers must be included for root to be included' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({include_containers => false, include_root => true}) |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [0] value: 1', 'path: [1, 0] value: 2', 'path: [1, 1, 0] value: 3', '' ].join("\n")) end it 'errors when asked to exclude both containers and values' do expect { compile_to_catalog(<<-MANIFEST) [1,2,3].tree_each({include_containers => false, include_values => false}) |$path, $v| { notice "$v" } MANIFEST }.to raise_error(/Options 'include_containers' and 'include_values' cannot both be false/) end it 'tree nodes are yielded in depth first order if option order=depth_first' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3], 4], 5] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({order => depth_first, include_containers => false}) |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [0] value: 1', 'path: [1, 0] value: 2', 'path: [1, 1, 0] value: 3', 'path: [1, 2] value: 4', 'path: [2] value: 5', '' ].join("\n")) end it 'tree nodes are yielded in breadth first order if option order=breadth_first' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3], 4], 5] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({order => breadth_first, include_containers => false}) |$path, $v| { -%> path: <%= $path %> value: <%= $v %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [0] value: 1', 'path: [2] value: 5', 'path: [1, 0] value: 2', 'path: [1, 2] value: 4', 'path: [1, 1, 0] value: 3', '' ].join("\n")) end it 'attributes of an Object of "reference" kind are not yielded by default' do catalog = compile_to_catalog(<<-MANIFEST) type Person = Object[{attributes => { name => String, father => Optional[Person], mother => { kind => reference, type => Optional[Person] } }}] $adam = Person({name => 'Adam'}) $eve = Person({name => 'Eve'}) $cain = Person({name => 'Cain', mother => $eve, father => $adam}) $awan = Person({name => 'Awan', mother => $eve, father => $adam}) $enoch = Person({name => 'Enoch', mother => $awan, father => $cain}) $msg = inline_epp(@(TEMPLATE)) <% $enoch.tree_each({include_containers=>false }) |$path, $v| { unless $v =~ Undef {-%> path: <%= $path %> value: <%= $v %> <% }} -%> | TEMPLATE notify {'by_default': message => $msg} $msg2 = inline_epp(@(TEMPLATE)) <% $enoch.tree_each({include_containers=>false, include_refs => false}) |$path, $v| { unless $v =~ Undef {-%> path: <%= $path %> value: <%= $v %> <% }} -%> | TEMPLATE notify {'when_false': message => $msg2} MANIFEST expected_refs_excluded_result = [ 'path: [name] value: Enoch', 'path: [father, name] value: Cain', 'path: [father, father, name] value: Adam', '' ].join("\n") expect(catalog.resource(:notify, 'by_default')['message']).to eq(expected_refs_excluded_result) expect(catalog.resource(:notify, 'when_false')['message']).to eq(expected_refs_excluded_result) end end context 'can be chained' do it 'with reverse_each()' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({include_containers => false}).reverse_each |$v| { -%> path: <%= $v[0] %> value: <%= $v[1] %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [1, 1, 0] value: 3', 'path: [1, 0] value: 2', 'path: [0] value: 1', '' ].join("\n")) end it 'with step()' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,[2,[3,[4,[5]]]]] $msg = inline_epp(@(TEMPLATE)) <% $a.tree_each({include_containers => false}).step(2) |$v| { -%> path: <%= $v[0] %> value: <%= $v[1] %> <% } -%> | TEMPLATE notify {'test': message => $msg} MANIFEST expect(catalog.resource(:notify, 'test')['message']).to eq( [ 'path: [0] value: 1', 'path: [1, 1, 0] value: 3', 'path: [1, 1, 1, 1, 0] value: 5', '' ].join("\n")) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/slice_spec.rb
spec/unit/functions/slice_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'methods' do include PuppetSpec::Compiler include Matchers::Resource before :each do node = Puppet::Node.new("floppy", :environment => 'production') @compiler = Puppet::Parser::Compiler.new(node) @scope = Puppet::Parser::Scope.new(@compiler) @topscope = @scope.compiler.topscope @scope.parent = @topscope end context "should be callable on array as" do it 'slice with explicit parameters' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, present, 2, absent, 3, present] $a.slice(2) |$k,$v| { file { "/file_${$k}": ensure => $v } } MANIFEST expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'absent') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') end it 'slice with captures last' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, present, 2, absent, 3, present] $a.slice(2) |*$kv| { file { "/file_${$kv[0]}": ensure => $kv[1] } } MANIFEST expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'absent') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') end it 'slice with one parameter' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, present, 2, absent, 3, present] $a.slice(2) |$k| { file { "/file_${$k[0]}": ensure => $k[1] } } MANIFEST expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'absent') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') end it 'slice with shorter last slice' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, present, 2, present, 3, absent] $a.slice(4) |$a, $b, $c, $d| { file { "/file_$a.$c": ensure => $b } } MANIFEST expect(catalog).to have_resource("File[/file_1.2]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_3.]").with_parameter(:ensure, 'absent') end end context "should be callable on hash as" do it 'slice with explicit parameters, missing are empty' do catalog = compile_to_catalog(<<-MANIFEST) $a = {1=>present, 2=>present, 3=>absent} $a.slice(2) |$a,$b| { file { "/file_${a[0]}.${b[0]}": ensure => $a[1] } } MANIFEST expect(catalog).to have_resource("File[/file_1.2]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_3.]").with_parameter(:ensure, 'absent') end end context "should be callable on enumerable types as" do it 'slice with integer range' do catalog = compile_to_catalog(<<-MANIFEST) $a = Integer[1,4] $a.slice(2) |$a,$b| { file { "/file_${a}.${b}": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_1.2]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_3.4]").with_parameter(:ensure, 'present') end it 'slice with integer' do catalog = compile_to_catalog(<<-MANIFEST) 4.slice(2) |$a,$b| { file { "/file_${a}.${b}": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_0.1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_2.3]").with_parameter(:ensure, 'present') end it 'slice with string' do catalog = compile_to_catalog(<<-MANIFEST) 'abcd'.slice(2) |$a,$b| { file { "/file_${a}.${b}": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_a.b]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_c.d]").with_parameter(:ensure, 'present') end end context "when called without a block" do it "should produce an array with the result" do catalog = compile_to_catalog(<<-MANIFEST) $a = [1, present, 2, absent, 3, present] $a.slice(2).each |$k| { file { "/file_${$k[0]}": ensure => $k[1] } } MANIFEST expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'absent') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/lstrip_spec.rb
spec/unit/functions/lstrip_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the lstrip function' do include PuppetSpec::Compiler include Matchers::Resource it 'removes leading whitepsace' do expect(compile_to_catalog("notify { String(\"\t\n abc \".lstrip == 'abc '): }")).to have_resource('Notify[true]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.lstrip == 42): }")).to have_resource('Notify[true]') end it 'returns lstripped version of each entry in an array' do expect(compile_to_catalog("notify { String([' a ', ' b ', ' c '].lstrip == ['a ', 'b ', 'c ']): }")).to have_resource('Notify[true]') end it 'returns lstripped version of each entry in an Iterator' do expect(compile_to_catalog("notify { String([' a', ' b', ' c'].reverse_each.lstrip == ['c', 'b', 'a']): }")).to have_resource('Notify[true]') end it 'errors when given a a nested Array' do expect { compile_to_catalog("['a', 'b', ['c']].lstrip")}.to raise_error(/'lstrip' parameter 'arg' expects a value of type Numeric, String, or Iterable/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/max_spec.rb
spec/unit/functions/max_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the max function' do include PuppetSpec::Compiler include Matchers::Resource let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } it 'errors if not give at least one argument' do expect{ compile_to_catalog("max()") }.to raise_error(/Wrong number of arguments need at least one/) end context 'compares numbers' do { [0, 1] => 1, [-1, 0] => 0, [-1.0, 0] => 0, }.each_pair do |values, expected| it "called as max(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( max(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'compares strings that are not numbers without deprecation warning' do it "string as number is deprecated" do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String( max('a', 'b') == 'b'): }")).to have_resource("Notify[true]") end expect(warnings).to_not include(/auto conversion of .* is deprecated/) end end context 'compares strings as numbers if possible and issues deprecation warning' do { [20, "'100'"] => "'100'", ["'20'", "'100'"] => "'100'", ["'20'", 100] => "100", [20, "'100x'"] => "20", ["20", "'100x'"] => "20", ["'20x'", 100] => "'20x'", }.each_pair do |values, expected| it "called as max(#{values[0]}, #{values[1]}) results in the value #{expected}" do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String( max(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end expect(warnings).to include(/auto conversion of .* is deprecated/) end end { [20, "'1e2'"] => "'1e2'", [20, "'1E2'"] => "'1E2'", [20, "'10_0'"] => "'10_0'", [20, "'100.0'"] => "'100.0'", }.each_pair do |values, expected| it "called as max(#{values[0]}, #{values[1]}) results in the value #{expected}" do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String( max(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end expect(warnings).to include(/auto conversion of .* is deprecated/) end end end context 'compares semver' do { ["Semver('2.0.0')", "Semver('10.0.0')"] => "Semver('10.0.0')", ["Semver('5.5.5')", "Semver('5.6.7')"] => "Semver('5.6.7')", }.each_pair do |values, expected| it "called as max(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( max(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'compares timespans' do { ["Timespan(2)", "Timespan(77.3)"] => "Timespan(77.3)", ["Timespan('1-00:00:00')", "Timespan('2-00:00:00')"] => "Timespan('2-00:00:00')", }.each_pair do |values, expected| it "called as max(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( max(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'compares timestamps' do { ["Timestamp(0)", "Timestamp(298922400)"] => "Timestamp(298922400)", ["Timestamp('1970-01-01T12:00:00.000')", "Timestamp('1979-06-22T18:00:00.000')"] => "Timestamp('1979-06-22T18:00:00.000')", }.each_pair do |values, expected| it "called as max(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( max(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'compares all except numeric and string by conversion to string and issues deprecation warning' do { [[20], "'a'"] => "'a'", # after since '[' is before 'a' ["{'a' => 10}", "'a'"] => "{'a' => 10}", # after since '{' is after 'a' [false, 'fal'] => "false", # the boolean since text 'false' is longer ['/b/', "'(?-mix:c)'"] => "'(?-mix:c)'", # because regexp to_s is a (?-mix:b) string ["Timestamp(1)", "'1980 a.d'"] => "'1980 a.d'", # because timestamp to_s is a date-time string here starting with 1970 }.each_pair do |values, expected| it "called as max(#{values[0]}, #{values[1]}) results in the value #{expected} and issues deprecation warning" do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String( max(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end expect(warnings).to include(/auto conversion of .* is deprecated/) end end end it "accepts a lambda that takes over the comparison (here avoiding the string as number conversion)" do src = <<-SRC $val = max("2", "10") |$a, $b| { compare($a, $b) } notify { String( $val == "2"): } SRC expect(compile_to_catalog(src)).to have_resource("Notify[true]") end context 'compares entries in a single array argument as if they were splatted as individual args' do { [1,2,3] => 3, ["1", "2","3"] => "'3'", [1, "2", 3] => 3, }.each_pair do |value, expected| it "called as max(#{value}) results in the value #{expected}" do src = "notify { String( max(#{value}) == #{expected}): }" expect(compile_to_catalog(src)).to have_resource("Notify[true]") end end { [1,2,3] => 3, ["10","2","3"] => "'3'", [1,"x",3] => "'x'", }.each_pair do |value, expected| it "called as max(#{value}) with a lambda using compare() results in the value #{expected}" do src = <<-"SRC" function s_after_n($a,$b) { case [$a, $b] { [String, Numeric]: { 1 } [Numeric, String]: { -1 } default: { compare($a, $b) } } } notify { String( max(#{value}) |$a,$b| {s_after_n($a,$b) } == #{expected}): } SRC expect(compile_to_catalog(src)).to have_resource("Notify[true]") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/find_template_spec.rb
spec/unit/functions/find_template_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'puppet_spec/files' describe 'the find_template function' do include PuppetSpec::Compiler include Matchers::Resource include PuppetSpec::Files def with_file_content(content) path = tmpfile('find-file-function') file = File.new(path, 'wb') file.sync = true file.print content yield path end it 'finds an existing absolute file when given arguments individually' do with_file_content('one') do |one| with_file_content('two') do |two| expect(compile_to_catalog("notify { find_template('#{one}', '#{two}'):}")).to have_resource("Notify[#{one}]") end end end it 'skips non existing files' do with_file_content('one') do |one| with_file_content('two') do |two| expect(compile_to_catalog("notify { find_template('#{one}/nope', '#{two}'):}")).to have_resource("Notify[#{two}]") end end end it 'accepts arguments given as an array' do with_file_content('one') do |one| with_file_content('two') do |two| expect(compile_to_catalog("notify { find_template(['#{one}', '#{two}']):}")).to have_resource("Notify[#{one}]") end end end it 'finds an existing file in a module' do with_file_content('file content') do |name| mod = double('module') allow(mod).to receive(:template).with('myfile').and_return(name) Puppet[:code] = "notify { find_template('mymod/myfile'):}" node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) allow(compiler.environment).to receive(:module).with('mymod').and_return(mod) expect(compiler.compile().filter { |r| r.virtual? }).to have_resource("Notify[#{name}]") end end it 'returns undef when none of the paths were found' do mod = double('module') allow(mod).to receive(:template).with('myfile').and_return(nil) Puppet[:code] = "notify { String(type(find_template('mymod/myfile', 'nomod/nofile'))):}" node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) # For a module that does not have the file allow(compiler.environment).to receive(:module).with('mymod').and_return(mod) # For a module that does not exist allow(compiler.environment).to receive(:module).with('nomod').and_return(nil) expect(compiler.compile().filter { |r| r.virtual? }).to have_resource("Notify[Undef]") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/epp_spec.rb
spec/unit/functions/epp_spec.rb
require 'spec_helper' describe "the epp function" do include PuppetSpec::Files let :node do Puppet::Node.new('localhost') end let :compiler do Puppet::Parser::Compiler.new(node) end let :scope do compiler.topscope end context "when accessing scope variables as $ variables" do it "looks up the value from the scope" do scope["what"] = "are belong" expect(eval_template("all your base <%= $what %> to us")).to eq("all your base are belong to us") end it "looks up a fully qualified value from the scope" do scope["what::is"] = "are belong" expect(eval_template("all your base <%= $what::is %> to us")).to eq("all your base are belong to us") end it "gets error accessing a variable that does not exist" do expect { eval_template("<%= $kryptonite == undef %>")}.to raise_error(/Evaluation Error: Unknown variable: 'kryptonite'./) end it "get nil accessing a variable that does not exist when strict mode is off" do Puppet[:strict_variables] = false Puppet[:strict] = :warning expect(eval_template("<%= $kryptonite == undef %>")).to eq("true") end it "gets error accessing a variable that is malformed" do expect { eval_template("<%= $kryptonite::bbbbbbbbbbbb::cccccccc::ddd::USER %>")}.to raise_error( /Illegal variable name, The given name 'kryptonite::bbbbbbbbbbbb::cccccccc::ddd::USER' does not conform to the naming rule/) end it "gets error accessing a variable that is malformed as reported in PUP-7848" do expect { eval_template("USER='<%= $hg_oais::archivematica::requirements::automation_tools::USER %>'")}.to raise_error( /Illegal variable name, The given name 'hg_oais::archivematica::requirements::automation_tools::USER' does not conform to the naming rule/) end it "get nil accessing a variable that is undef" do scope['undef_var'] = nil expect(eval_template("<%= $undef_var == undef %>")).to eq("true") end it "gets shadowed variable if args are given" do scope['phantom'] = 'of the opera' expect(eval_template_with_args("<%= $phantom == dragos %>", 'phantom' => 'dragos')).to eq("true") end it "can use values from the global scope for defaults" do scope['phantom'] = 'of the opera' expect(eval_template("<%- |$phantom = $::phantom| -%><%= $phantom %>")).to eq("of the opera") end it "will not use values from the enclosing scope for defaults" do scope['the_phantom'] = 'of the state opera' scope.new_ephemeral(true) scope['the_phantom'] = 'of the local opera' expect(scope['the_phantom']).to eq('of the local opera') expect(eval_template("<%- |$phantom = $the_phantom| -%><%= $phantom %>")).to eq("of the state opera") end it "uses the default value if the given value is undef/nil" do expect(eval_template_with_args("<%- |$phantom = 'inside your mind'| -%><%= $phantom %>", 'phantom' => nil)).to eq("inside your mind") end it "gets shadowed variable if args are given and parameters are specified" do scope['x'] = 'wrong one' expect(eval_template_with_args("<%- |$x| -%><%= $x == correct %>", 'x' => 'correct')).to eq("true") end it "raises an error if required variable is not given" do scope['x'] = 'wrong one' expect do eval_template("<%-| $x |-%><%= $x == correct %>") end.to raise_error(/expects a value for parameter 'x'/) end it 'raises an error if invalid arguments are given' do scope['x'] = 'wrong one' expect do eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct', 'y' => 'surplus') end.to raise_error(/has no parameter named 'y'/) end end context "when given an empty template" do it "allows the template file to be empty" do expect(eval_template("")).to eq("") end it "allows the template to have empty body after parameters" do expect(eval_template_with_args("<%-|$x|%>", 'x'=>1)).to eq("") end end context "when using typed parameters" do it "allows a passed value that matches the parameter's type" do expect(eval_template_with_args("<%-|String $x|-%><%= $x == correct %>", 'x' => 'correct')).to eq("true") end it "does not allow slurped parameters" do expect do eval_template_with_args("<%-|*$x|-%><%= $x %>", 'x' => 'incorrect') end.to raise_error(/'captures rest' - not supported in an Epp Template/) end it "raises an error when the passed value does not match the parameter's type" do expect do eval_template_with_args("<%-|Integer $x|-%><%= $x %>", 'x' => 'incorrect') end.to raise_error(/parameter 'x' expects an Integer value, got String/) end it "raises an error when the default value does not match the parameter's type" do expect do eval_template("<%-|Integer $x = 'nope'|-%><%= $x %>") end.to raise_error(/parameter 'x' expects an Integer value, got String/) end it "allows an parameter to default to undef" do expect(eval_template("<%-|Optional[Integer] $x = undef|-%><%= $x == undef %>")).to eq("true") end end it "preserves CRLF when reading the template" do expect(eval_template("some text that\r\nis static with CRLF")).to eq("some text that\r\nis static with CRLF") end # although never a problem with epp it "is not interfered with by having a variable named 'string' (#14093)" do scope['string'] = "this output should not be seen" expect(eval_template("some text that is static")).to eq("some text that is static") end it "has access to a variable named 'string' (#14093)" do scope['string'] = "the string value" expect(eval_template("string was: <%= $string %>")).to eq("string was: the string value") end describe 'when loading from modules' do include PuppetSpec::Files it 'an epp template is found' do modules_dir = dir_containing('modules', { 'testmodule' => { 'templates' => { 'the_x.epp' => 'The x is <%= $x %>' } }}) Puppet.override({:current_environment => (env = Puppet::Node::Environment.create(:testload, [ modules_dir ]))}, "test") do node.environment = env expect(epp_function.call(scope, 'testmodule/the_x.epp', { 'x' => '3'} )).to eql("The x is 3") end end end def eval_template_with_args(content, args_hash) file_path = tmpdir('epp_spec_content') filename = File.join(file_path, "template.epp") File.open(filename, "wb+") { |f| f.write(content) } allow(Puppet::Parser::Files).to receive(:find_template).and_return(filename) epp_function.call(scope, 'template', args_hash) end def eval_template(content) file_path = tmpdir('epp_spec_content') filename = File.join(file_path, "template.epp") File.open(filename, "wb+") { |f| f.write(content) } allow(Puppet::Parser::Files).to receive(:find_template).and_return(filename) epp_function.call(scope, 'template') end def epp_function() scope.compiler.loaders.public_environment_loader.load(:function, 'epp') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/strftime_spec.rb
spec/unit/functions/strftime_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe 'the strftime function' do include PuppetSpec::Compiler def test_format(ctor_arg, format, expected) expect(eval_and_collect_notices("notice(strftime(Timespan(#{ctor_arg}), '#{format}'))")).to eql(["#{expected}"]) end context 'when applied to a Timespan' do [ ['hours', 'H', 2], ['minutes', 'M', 2], ['seconds', 'S', 2], ].each do |field, fmt, dflt_width| ctor_arg = "{#{field}=>3}" it "%#{fmt} width defaults to #{dflt_width}" do test_format(ctor_arg, "%#{fmt}", sprintf("%0#{dflt_width}d", 3)) end it "%_#{fmt} pads with space" do test_format(ctor_arg, "%_#{fmt}", sprintf("% #{dflt_width}d", 3)) end it "%-#{fmt} does not pad" do test_format(ctor_arg, "%-#{fmt}", '3') end it "%10#{fmt} pads with zeroes to specified width" do test_format(ctor_arg, "%10#{fmt}", sprintf("%010d", 3)) end it "%_10#{fmt} pads with space to specified width" do test_format(ctor_arg, "%_10#{fmt}", sprintf("% 10d", 3)) end it "%-10#{fmt} does not pad even if width is specified" do test_format(ctor_arg, "%-10#{fmt}", '3') end end [ ['milliseconds', 'L', 3], ['nanoseconds', 'N', 9], ['milliseconds', '3N', 3], ['microseconds', '6N', 6], ['nanoseconds', '9N', 9], ].each do |field, fmt, dflt_width| ctor_arg = "{#{field}=>3000}" it "%#{fmt} width defaults to #{dflt_width}" do test_format(ctor_arg, "%#{fmt}", sprintf("%-#{dflt_width}d", 3000)) end it "%_#{fmt} pads with space" do test_format(ctor_arg, "%_#{fmt}", sprintf("%-#{dflt_width}d", 3000)) end it "%-#{fmt} does not pad" do test_format(ctor_arg, "%-#{fmt}", '3000') end end it 'can use a format containing all format characters, flags, and widths' do test_format("{string => '100-14:02:24.123456000', format => '%D-%H:%M:%S.%9N'}", '%_10D%%%03H:%-M:%S.%9N', ' 100%014:2:24.123456000') end it 'can format and strip excess zeroes from fragment using no-padding flag' do test_format("{string => '100-14:02:24.123456000', format => '%D-%H:%M:%S.%N'}", '%D-%H:%M:%S.%-N', '100-14:02:24.123456') end it 'can format and replace excess zeroes with spaces from fragment using space-padding flag and default widht' do test_format("{string => '100-14:02:24.123456000', format => '%D-%H:%M:%S.%N'}", '%D-%H:%M:%S.%_N', '100-14:02:24.123456 ') end it 'can format and replace excess zeroes with spaces from fragment using space-padding flag and specified width' do test_format("{string => '100-14:02:24.123400000', format => '%D-%H:%M:%S.%N'}", '%D-%H:%M:%S.%_6N', '100-14:02:24.1234 ') end it 'can format and retain excess zeroes in fragment using default width' do test_format("{string => '100-14:02:24.123400000', format => '%D-%H:%M:%S.%N'}", '%D-%H:%M:%S.%N', '100-14:02:24.123400000') end it 'can format and retain excess zeroes in fragment using specified width' do test_format("{string => '100-14:02:24.123400000', format => '%D-%H:%M:%S.%N'}", '%D-%H:%M:%S.%6N', '100-14:02:24.123400') end end def test_timestamp_format(ctor_arg, format, expected) expect(eval_and_collect_notices("notice(strftime(Timestamp('#{ctor_arg}'), '#{format}'))")).to eql(["#{expected}"]) end def test_timestamp_format_tz(ctor_arg, format, tz, expected) expect(eval_and_collect_notices("notice(strftime(Timestamp('#{ctor_arg}'), '#{format}', '#{tz}'))")).to eql(["#{expected}"]) end def collect_log(code, node = Puppet::Node.new('foonode')) Puppet[:code] = code compiler = Puppet::Parser::Compiler.new(node) node.environment.check_for_reparse logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile end logs end context 'when applied to a Timestamp' do it 'can format a timestamp with a format pattern' do test_timestamp_format('2016-09-23T13:14:15.123 UTC', '%Y-%m-%d %H:%M:%S.%L %z', '2016-09-23 13:14:15.123 +0000') end it 'can format a timestamp using a specific timezone' do test_timestamp_format_tz('2016-09-23T13:14:15.123 UTC', '%Y-%m-%d %H:%M:%S.%L %z', 'EST', '2016-09-23 08:14:15.123 -0500') end end context 'when used with dispatcher covering legacy stdlib API (String format, String timeszone = undef)' do it 'produces the current time when used with one argument' do before_eval = Time.now notices = eval_and_collect_notices("notice(strftime('%F %T'))") expect(notices).not_to be_empty expect(notices[0]).to match(/\A\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\z/) parsed_time = DateTime.strptime(notices[0], '%F %T').to_time expect(Time.now.to_i >= parsed_time.to_i && parsed_time.to_i >= before_eval.to_i).to be_truthy end it 'emits a deprecation warning when used with one argument' do log = collect_log("notice(strftime('%F %T'))") warnings = log.select { |log_entry| log_entry.level == :warning }.map { |log_entry| log_entry.message } expect(warnings).not_to be_empty expect(warnings[0]).to match(/The argument signature \(String format, \[String timezone\]\) is deprecated for #strftime/) end it 'produces the current time formatted with specific timezone when used with two arguments' do before_eval = Time.now notices = eval_and_collect_notices("notice(strftime('%F %T %:z', 'EST'))") expect(notices).not_to be_empty expect(notices[0]).to match(/\A\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} -05:00\z/) parsed_time = DateTime.strptime(notices[0], '%F %T %z').to_time expect(Time.now.to_i >= parsed_time.to_i && parsed_time.to_i >= before_eval.to_i).to be_truthy end it 'emits a deprecation warning when using legacy format with two arguments' do log = collect_log("notice(strftime('%F %T', 'EST'))") warnings = log.select { |log_entry| log_entry.level == :warning }.map { |log_entry| log_entry.message } expect(warnings).not_to be_empty expect(warnings[0]).to match(/The argument signature \(String format, \[String timezone\]\) is deprecated for #strftime/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/index_spec.rb
spec/unit/functions/index_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'shared_behaviours/iterative_functions' describe 'the index function' do include PuppetSpec::Compiler context "should be callable on Array with" do it 'a lambda to compute match' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.index |$v| { $v == 2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "1")['ensure']).to eq('present') end it 'a lambda taking two arguments to compute match' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.index |$i, $v| { $i == 2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "2")['ensure']).to eq('present') end it 'a given value' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.index(3) file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "2")['ensure']).to eq('present') end end context "should be callable on Hash with" do it 'a lambda to compute match' do catalog = compile_to_catalog(<<-MANIFEST) $h = {1 => 10, 2 => 20, 3 => 30 } $n = $h.index |$v| { $v == 20 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "2")['ensure']).to eq('present') end it 'a lambda taking two arguments to compute match' do catalog = compile_to_catalog(<<-MANIFEST) $h = {1 => 10, 2 => 20, 3 => 30 } $n = $h.index |$k, $v| { $k == 3 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "3")['ensure']).to eq('present') end it 'a given value' do catalog = compile_to_catalog(<<-MANIFEST) $h = {1 => 10, 2 => 20, 3 => 30 } $n = $h.index(20) file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "2")['ensure']).to eq('present') end end context "should be callable on String with" do it 'a lambda to compute match' do catalog = compile_to_catalog(<<-MANIFEST) $s = "foobarfuu" $n = $s.index |$v| { $v == 'o' } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "1")['ensure']).to eq('present') end it 'a lambda taking two arguments to compute match' do catalog = compile_to_catalog(<<-MANIFEST) $s = "foobarfuu" $n = $s.index |$i, $v| { $i == 2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "2")['ensure']).to eq('present') end it 'a given value returns index of first found substring given as a string' do catalog = compile_to_catalog(<<-MANIFEST) $s = "foobarfuu" $n = $s.index('fu') file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "6")['ensure']).to eq('present') end it 'a given value returns index of first found substring given as a regexp' do catalog = compile_to_catalog(<<-MANIFEST) $s = "foobarfuub" $n = $s.index(/f(oo|uu)b/) file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "0")['ensure']).to eq('present') end end context "should be callable on an iterable" do it 'for example a reverse_each' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.reverse_each.index |$v| { $v == 1 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "2")['ensure']).to eq('present') end end context 'stops iteration when result is known' do it 'true when boolean true is found' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.index |$i, $v| { if $i == 0 { true } else { fail("unwanted") } } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "0")['ensure']).to eq('present') end end context 'returns undef when value is not found' do it 'when using array and a lambda' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.index |$v| { $v == 'blue' } file { "test": ensure => if $n =~ Undef { present } else {absent} } MANIFEST expect(catalog.resource(:file, "test")['ensure']).to eq('present') end it 'when using array and a value' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.index('blue') file { "test": ensure => if $n =~ Undef { present } else {absent} } MANIFEST expect(catalog.resource(:file, "test")['ensure']).to eq('present') end it 'when using a hash and a lambda' do catalog = compile_to_catalog(<<-MANIFEST) $h = {1 => 10, 2 => 20, 3 => 30} $n = $h.index |$v| { $v == 'blue' } file { "test": ensure => if $n =~ Undef { present } else {absent} } MANIFEST expect(catalog.resource(:file, "test")['ensure']).to eq('present') end it 'when using a hash and a value' do catalog = compile_to_catalog(<<-MANIFEST) $h = {1 => 10, 2 => 20, 3 => 30} $n = $h.index('blue') file { "test": ensure => if $n =~ Undef { present } else {absent} } MANIFEST expect(catalog.resource(:file, "test")['ensure']).to eq('present') end it 'when using a String and a lambda' do catalog = compile_to_catalog(<<-MANIFEST) $s = "foobarfuub" $n = $s.index() |$v| { false } file { "test": ensure => if $n =~ Undef { present } else {absent} } MANIFEST expect(catalog.resource(:file, "test")['ensure']).to eq('present') end it 'when using a String and a value' do catalog = compile_to_catalog(<<-MANIFEST) $s = "foobarfuub" $n = $s.index('banana') file { "test": ensure => if $n =~ Undef { present } else {absent} } MANIFEST expect(catalog.resource(:file, "test")['ensure']).to eq('present') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/regsubst_spec.rb
spec/unit/functions/regsubst_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/loaders' describe 'the regsubst function' do before(:each) do loaders = Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) Puppet.push_context({:loaders => loaders}, "test-examples") end after(:each) do Puppet.pop_context() end def regsubst(*args) Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'regsubst').call({}, *args) end let(:type_parser) { Puppet::Pops::Types::TypeParser.singleton } context 'when using a string pattern' do it 'should raise an Error if there is less than 3 arguments' do expect { regsubst('foo', 'bar') }.to raise_error(/expects between 3 and 5 arguments, got 2/) end it 'should raise an Error if there is more than 5 arguments' do expect { regsubst('foo', 'bar', 'gazonk', 'G', 'U', 'y') }.to raise_error(/expects between 3 and 5 arguments, got 6/) end it 'should raise an Error if given a bad flag' do expect { regsubst('foo', 'bar', 'gazonk', 'X') }.to raise_error(/parameter 'flags' expects an undef value or a match for Pattern\[\/\^\[GEIM\]\*\$\/\], got 'X'/) end it 'should raise an Error if given a bad encoding' do expect { regsubst('foo', 'bar', 'gazonk', nil, 'X') }.to raise_error(/parameter 'encoding' expects a match for Enum\['E', 'N', 'S', 'U'\], got 'X'/) end it 'should raise an Error if given a bad regular expression' do expect { regsubst('foo', '(', 'gazonk') }.to raise_error(/pattern with unmatched parenthesis/) end it 'should handle case insensitive flag' do expect(regsubst('the monkey breaks baNAna trees', 'b[an]+a', 'coconut', 'I')).to eql('the monkey breaks coconut trees') end it 'should allow hash as replacement' do expect(regsubst('tuto', '[uo]', { 'u' => 'o', 'o' => 'u' }, 'G')).to eql('totu') end end context 'when using a regexp pattern' do it 'should raise an Error if there is less than 3 arguments' do expect { regsubst('foo', /bar/) }.to raise_error(/expects between 3 and 5 arguments, got 2/) end it 'should raise an Error if there is more than 5 arguments' do expect { regsubst('foo', /bar/, 'gazonk', 'G', 'E', 'y') }.to raise_error(/expects between 3 and 5 arguments, got 6/) end it 'should raise an Error if given a flag other thant G' do expect { regsubst('foo', /bar/, 'gazonk', 'I') }.to raise_error(/expects one of/) end it 'should handle global substitutions' do expect(regsubst("the monkey breaks\tbanana trees", /[ \t]/, '--', 'G')).to eql('the--monkey--breaks--banana--trees') end it 'should accept Type[Regexp]' do expect(regsubst('abc', type_parser.parse("Regexp['b']"), '_')).to eql('a_c') end it 'should treat Regexp as Regexp[//]' do expect(regsubst('abc', type_parser.parse("Regexp"), '_', 'G')).to eql('_a_b_c_') end it 'should allow hash as replacement' do expect(regsubst('tuto', /[uo]/, { 'u' => 'o', 'o' => 'u' }, 'G')).to eql('totu') end end context 'when using an array target' do it 'should perform substitutions in all elements and return array when using regexp pattern' do expect(regsubst(['a#a', 'b#b', 'c#c'], /#/, '_')).to eql(['a_a', 'b_b', 'c_c']) end it 'should perform substitutions in all elements when using string pattern' do expect(regsubst(['a#a', 'b#b', 'c#c'], '#', '_')).to eql(['a_a', 'b_b', 'c_c']) end it 'should perform substitutions in all elements when using Type[Regexp] pattern' do expect(regsubst(['a#a', 'b#b', 'c#c'], type_parser.parse('Regexp[/#/]'), '_')).to eql(['a_a', 'b_b', 'c_c']) end it 'should handle global substitutions with groups on all elements' do expect(regsubst( ['130.236.254.10', 'foo.example.com', 'coconut', '10.20.30.40'], /([^.]+)/, '<\1>', 'G') ).to eql(['<130>.<236>.<254>.<10>', '<foo>.<example>.<com>','<coconut>', '<10>.<20>.<30>.<40>']) end it 'should return an empty array if given an empty array and string pattern' do expect(regsubst([], '', '')).to eql([]) end it 'should return an empty array if given an empty array and regexp pattern' do expect(regsubst([], //, '')).to eql([]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/module_directory_spec.rb
spec/unit/functions/module_directory_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'puppet_spec/files' describe 'the module_directory function' do include PuppetSpec::Compiler include Matchers::Resource include PuppetSpec::Files it 'returns first found module from one or more given names' do mod = double('module') allow(mod).to receive(:path).and_return('expected_path') Puppet[:code] = "notify { module_directory('one', 'two'):}" node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) allow(compiler.environment).to receive(:module).with('one').and_return(nil) allow(compiler.environment).to receive(:module).with('two').and_return(mod) expect(compiler.compile()).to have_resource("Notify[expected_path]") end it 'returns first found module from one or more given names in an array' do mod = double('module') allow(mod).to receive(:path).and_return('expected_path') Puppet[:code] = "notify { module_directory(['one', 'two']):}" node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) allow(compiler.environment).to receive(:module).with('one').and_return(nil) allow(compiler.environment).to receive(:module).with('two').and_return(mod) expect(compiler.compile()).to have_resource("Notify[expected_path]") end it 'returns undef when none of the modules were found' do mod = double('module') allow(mod).to receive(:path).and_return('expected_path') Puppet[:code] = "notify { String(type(module_directory('one', 'two'))):}" node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) allow(compiler.environment).to receive(:module).with('one').and_return(nil) allow(compiler.environment).to receive(:module).with('two').and_return(nil) expect(compiler.compile()).to have_resource("Notify[Undef]") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/convert_to_spec.rb
spec/unit/functions/convert_to_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the convert_to function' do include PuppetSpec::Compiler include Matchers::Resource it 'converts and returns the converted when no lambda is given' do expect(compile_to_catalog('notify{ "testing-${[a,1].convert_to(Hash) =~ Hash}": }')).to have_resource('Notify[testing-true]') end it 'converts given value to instance of type and calls a lambda with converted value' do expect(compile_to_catalog('"1".convert_to(Integer) |$x| { notify { "testing-${x.type(generalized)}": } }')).to have_resource('Notify[testing-Integer]') end it 'returns the lambda return when lambda is given' do expect(compile_to_catalog('notify{ "testing-${[a,1].convert_to(Hash) |$x| { yay }}": }')).to have_resource('Notify[testing-yay]') end it 'passes on additional arguments to the new function' do expect(compile_to_catalog('"111".convert_to(Integer, 2) |$x| { notify { "testing-${x}": } }')).to have_resource('Notify[testing-7]') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/next_spec.rb
spec/unit/functions/next_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the next function' do include PuppetSpec::Compiler include Matchers::Resource context 'exits a block yielded to iteratively' do it 'with a given value as result for this iteration' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[100, 4, 6]]') $result = String([1,2,3].map |$x| { if $x == 1 { next(100) } $x*2 }) notify { $result: } CODE end it 'with undef value as result for this iteration when next is not given an argument' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[undef, 4, 6]]') $result = String([1,2,3].map |$x| { if $x == 1 { next() } $x*2 }) notify { $result: } CODE end end it 'can be called without parentheses around the argument' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[100, 4, 6]]') $result = String([1,2,3].map |$x| { if $x == 1 { next 100 } $x*2 }) notify { $result: } CODE end it 'has the same effect as a return when called from within a block not used in an iteration' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[100]') $result = String(with(1) |$x| { if $x == 1 { next(100) } 200 }) notify { $result: } CODE end it 'has the same effect as a return when called from within a function' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[102, 200, 300]]') function do_next() { next(100) } $result = String([1,2,3].map |$x| { if $x == 1 { next do_next()+2 } $x*do_next() }) notify { $result: } CODE end it 'provides early exit from a class and keeps the class' do expect(eval_and_collect_notices(<<-CODE)).to eql(['a', 'c', 'true', 'true']) class notices_c { notice 'c' } class does_next { notice 'a' if 1 == 1 { next() } # avoid making next line statically unreachable notice 'b' } # include two classes to check that next does not do an early return from # the include function. include(does_next, notices_c) notice defined(does_next) notice defined(notices_c) CODE end it 'provides early exit from a user defined resource and keeps the resource' do expect(eval_and_collect_notices(<<-CODE)).to eql(['the_doer_of_next', 'copy_cat', 'true', 'true']) define does_next { notice $title if 1 == 1 { next() } # avoid making next line statically unreachable notice 'b' } define checker { notice defined(Does_next['the_doer_of_next']) notice defined(Does_next['copy_cat']) } # create two instances to ensure next does not break the entire # resource expression does_next { ['the_doer_of_next', 'copy_cat']: } checker { 'needed_because_evaluation_order': } CODE end it 'can not be called from top scope' do expect do compile_to_catalog(<<-CODE) # line 1 # line 2 next() CODE end.to raise_error(/next\(\) from context where this is illegal .*/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/shared.rb
spec/unit/functions/shared.rb
shared_examples_for 'all functions transforming relative to absolute names' do |func_name| before(:each) do # mock that the class 'myclass' exists which are needed for the 'require' functions # as it checks the existence of the required class @klass = double('class', :name => "myclass") allow(@scope.environment.known_resource_types).to receive(:find_hostclass).and_return(@klass) @resource = Puppet::Parser::Resource.new(:file, "/my/file", :scope => @scope, :source => "source") allow(@scope).to receive(:resource).and_return(@resource) end it 'accepts a Class[name] type' do expect(@scope.compiler).to receive(:evaluate_classes).with(["::myclass"], @scope, false) @scope.call_function(func_name, [Puppet::Pops::Types::TypeFactory.host_class('myclass')]) end it 'accepts a Resource[class, name] type' do expect(@scope.compiler).to receive(:evaluate_classes).with(["::myclass"], @scope, false) @scope.call_function(func_name, [Puppet::Pops::Types::TypeFactory.resource('class', 'myclass')]) end it 'raises and error for unspecific Class' do expect { @scope.call_function(func_name, [Puppet::Pops::Types::TypeFactory.host_class()]) }.to raise_error(ArgumentError, /Cannot use an unspecific Class\[\] Type/) end it 'raises and error for Resource that is not of class type' do expect { @scope.call_function(func_name, [Puppet::Pops::Types::TypeFactory.resource('file')]) }.to raise_error(ArgumentError, /Cannot use a Resource\[File\] where a Resource\['class', name\] is expected/) end it 'raises and error for Resource that is unspecific' do expect { @scope.call_function(func_name, [Puppet::Pops::Types::TypeFactory.resource()]) }.to raise_error(ArgumentError, /Cannot use an unspecific Resource\[\] where a Resource\['class', name\] is expected/) end it 'raises and error for Resource[class] that is unspecific' do expect { @scope.call_function(func_name, [Puppet::Pops::Types::TypeFactory.resource('class')]) }.to raise_error(ArgumentError, /Cannot use an unspecific Resource\['class'\] where a Resource\['class', name\] is expected/) end end shared_examples_for 'an inclusion function, regardless of the type of class reference,' do |function| it "and #{function} a class absolutely, even when a relative namespaced class of the same name is present" do catalog = compile_to_catalog(<<-MANIFEST) class foo { class bar { } #{function} bar } class bar { } include foo MANIFEST expect(catalog.classes).to include('foo','bar') end it "and #{function} a class absolutely by Class['type'] reference" do catalog = compile_to_catalog(<<-MANIFEST) class foo { class bar { } #{function} Class['bar'] } class bar { } include foo MANIFEST expect(catalog.classes).to include('foo','bar') end it "and #{function} a class absolutely by Resource['type','title'] reference" do catalog = compile_to_catalog(<<-MANIFEST) class foo { class bar { } #{function} Resource['class','bar'] } class bar { } include foo MANIFEST expect(catalog.classes).to include('foo','bar') end end shared_examples_for 'an inclusion function, when --tasks is on,' do |function| it "is not available when --tasks is on" do Puppet[:tasks] = true expect do compile_to_catalog(<<-MANIFEST) #{function}(bar) MANIFEST end.to raise_error(Puppet::ParseError, /is only available when compiling a catalog/) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/lest_spec.rb
spec/unit/functions/lest_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the lest function' do include PuppetSpec::Compiler include Matchers::Resource it 'calls a lambda passing no argument' do expect(compile_to_catalog("lest(undef) || { notify { testing: } }")).to have_resource('Notify[testing]') end it 'produces what lambda returns if value is undef' do expect(compile_to_catalog("notify{ lest(undef) || { testing }: }")).to have_resource('Notify[testing]') end it 'does not call lambda if argument is not undef' do expect(compile_to_catalog('lest(1) || { notify { "failed": } }')).to_not have_resource('Notify[failed]') end it 'produces given argument if given not undef' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test_yay_ing]') notify{ "test${lest('_yay_') || { '_oh_no_' }}ing": } SOURCE end it 'errors when lambda wants too many args' do expect do compile_to_catalog('lest(1) |$x| { }') end.to raise_error(/'lest' block expects no arguments, got 1/m) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/format_handler_spec.rb
spec/unit/network/format_handler_spec.rb
require 'spec_helper' require 'puppet/network/format_handler' describe Puppet::Network::FormatHandler do before(:each) do @saved_formats = Puppet::Network::FormatHandler.instance_variable_get(:@formats).dup Puppet::Network::FormatHandler.instance_variable_set(:@formats, {}) end after(:each) do Puppet::Network::FormatHandler.instance_variable_set(:@formats, @saved_formats) end describe "when creating formats" do it "should instance_eval any block provided when creating a format" do format = Puppet::Network::FormatHandler.create(:test_format) do def asdfghjkl; end end expect(format).to respond_to(:asdfghjkl) end end describe "when retrieving formats" do let!(:format) { Puppet::Network::FormatHandler.create(:the_format, :extension => "foo", :mime => "foo/bar") } it "should be able to retrieve a format by name" do expect(Puppet::Network::FormatHandler.format(:the_format)).to equal(format) end it "should be able to retrieve a format by extension" do expect(Puppet::Network::FormatHandler.format_by_extension("foo")).to equal(format) end it "should return nil if asked to return a format by an unknown extension" do expect(Puppet::Network::FormatHandler.format_by_extension("yayness")).to be_nil end it "should be able to retrieve formats by name irrespective of case" do expect(Puppet::Network::FormatHandler.format(:The_Format)).to equal(format) end it "should be able to retrieve a format by mime type" do expect(Puppet::Network::FormatHandler.mime("foo/bar")).to equal(format) end it "should be able to retrieve a format by mime type irrespective of case" do expect(Puppet::Network::FormatHandler.mime("Foo/Bar")).to equal(format) end end describe "#most_suitable_formats_for" do before :each do Puppet::Network::FormatHandler.create(:one, :extension => "foo", :mime => "text/one") Puppet::Network::FormatHandler.create(:two, :extension => "bar", :mime => "application/two") end let(:format_one) { Puppet::Network::FormatHandler.format(:one) } let(:format_two) { Puppet::Network::FormatHandler.format(:two) } def suitable_in_setup_formats(accepted) Puppet::Network::FormatHandler.most_suitable_formats_for(accepted, [:one, :two]) end it "finds the most preferred format when anything is acceptable" do expect(Puppet::Network::FormatHandler.most_suitable_formats_for(["*/*"], [:two, :one])).to eq([format_two]) end it "finds no format when none are acceptable" do expect(suitable_in_setup_formats(["three"])).to eq([]) end it "returns only the accepted and supported format" do expect(suitable_in_setup_formats(["three", "two"])).to eq([format_two]) end it "returns only accepted and supported formats, in order of accepted" do expect(suitable_in_setup_formats(["three", "two", "one"])).to eq([format_two, format_one]) end it "allows specifying acceptable formats by mime type" do expect(suitable_in_setup_formats(["text/one"])).to eq([format_one]) end it "ignores quality specifiers" do expect(suitable_in_setup_formats(["two;q=0.8", "text/one;q=0.9"])).to eq([format_two, format_one]) end it "allows specifying acceptable formats by canonical name" do expect(suitable_in_setup_formats([:one])).to eq([format_one]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/authorization_spec.rb
spec/unit/network/authorization_spec.rb
require 'spec_helper' require 'puppet/network/authorization' describe Puppet::Network::Authorization do it "accepts an auth config loader class" do Puppet::Network::Authorization.authconfigloader_class = Object end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/format_support_spec.rb
spec/unit/network/format_support_spec.rb
require 'spec_helper' require 'puppet/network/format_handler' require 'puppet/network/format_support' class FormatTester include Puppet::Network::FormatSupport end describe Puppet::Network::FormatHandler do before(:each) do @saved_formats = Puppet::Network::FormatHandler.instance_variable_get(:@formats).dup Puppet::Network::FormatHandler.instance_variable_set(:@formats, {}) end after(:each) do Puppet::Network::FormatHandler.instance_variable_set(:@formats, @saved_formats) end describe "when listing formats" do before(:each) do one = Puppet::Network::FormatHandler.create(:one, :weight => 1) allow(one).to receive(:supported?).and_return(true) two = Puppet::Network::FormatHandler.create(:two, :weight => 6) allow(two).to receive(:supported?).and_return(true) three = Puppet::Network::FormatHandler.create(:three, :weight => 2) allow(three).to receive(:supported?).and_return(true) four = Puppet::Network::FormatHandler.create(:four, :weight => 8) allow(four).to receive(:supported?).and_return(false) end it "should return all supported formats in decreasing order of weight" do expect(FormatTester.supported_formats).to eq([:two, :three, :one]) end end it "should return the first format as the default format" do expect(FormatTester).to receive(:supported_formats).and_return [:one, :two] expect(FormatTester.default_format).to eq(:one) end describe "with a preferred serialization format setting" do before do one = Puppet::Network::FormatHandler.create(:one, :weight => 1) allow(one).to receive(:supported?).and_return(true) two = Puppet::Network::FormatHandler.create(:two, :weight => 6) allow(two).to receive(:supported?).and_return(true) end describe "that is supported" do before do Puppet[:preferred_serialization_format] = :one end it "should return the preferred serialization format first" do expect(FormatTester.supported_formats).to eq([:one, :two]) end end describe "that is not supported" do before do Puppet[:preferred_serialization_format] = :unsupported end it "should return the default format first" do expect(FormatTester.supported_formats).to eq([:two, :one]) end it "should log a debug message" do Puppet[:log_level] = 'debug' expect(Puppet).to receive(:debug) { |&b| expect(b.call).to eq("Value of 'preferred_serialization_format' (unsupported) is invalid for FormatTester, using default (two)") } expect(Puppet).to receive(:debug) { |&b| expect(b.call).to eq("FormatTester supports formats: two one") } FormatTester.supported_formats end end end describe "when using formats" do let(:format) { Puppet::Network::FormatHandler.create(:my_format, :mime => "text/myformat") } it "should use the Format to determine whether a given format is supported" do expect(format).to receive(:supported?).with(FormatTester) FormatTester.support_format?(:my_format) end it "should call the format-specific converter when asked to convert from a given format" do expect(format).to receive(:intern).with(FormatTester, "mydata") FormatTester.convert_from(:my_format, "mydata") end it "should call the format-specific converter when asked to convert from a given format by mime-type" do expect(format).to receive(:intern).with(FormatTester, "mydata") FormatTester.convert_from("text/myformat", "mydata") end it "should call the format-specific converter when asked to convert from a given format by format instance" do expect(format).to receive(:intern).with(FormatTester, "mydata") FormatTester.convert_from(format, "mydata") end it "should raise a FormatError when an exception is encountered when converting from a format" do expect(format).to receive(:intern).with(FormatTester, "mydata").and_raise("foo") expect do FormatTester.convert_from(:my_format, "mydata") end.to raise_error( Puppet::Network::FormatHandler::FormatError, 'Could not intern from my_format: foo' ) end it "should be able to use a specific hook for converting into multiple instances" do expect(format).to receive(:intern_multiple).with(FormatTester, "mydata") FormatTester.convert_from_multiple(:my_format, "mydata") end it "should raise a FormatError when an exception is encountered when converting multiple items from a format" do expect(format).to receive(:intern_multiple).with(FormatTester, "mydata").and_raise("foo") expect do FormatTester.convert_from_multiple(:my_format, "mydata") end.to raise_error(Puppet::Network::FormatHandler::FormatError, 'Could not intern_multiple from my_format: foo') end it "should be able to use a specific hook for rendering multiple instances" do expect(format).to receive(:render_multiple).with("mydata") FormatTester.render_multiple(:my_format, "mydata") end it "should raise a FormatError when an exception is encountered when rendering multiple items into a format" do expect(format).to receive(:render_multiple).with("mydata").and_raise("foo") expect do FormatTester.render_multiple(:my_format, "mydata") end.to raise_error(Puppet::Network::FormatHandler::FormatError, 'Could not render_multiple to my_format: foo') end end describe "when an instance" do let(:format) { Puppet::Network::FormatHandler.create(:foo, :mime => "text/foo") } it "should list as supported a format that reports itself supported" do expect(format).to receive(:supported?).and_return(true) expect(FormatTester.new.support_format?(:foo)).to be_truthy end it "should raise a FormatError when a rendering error is encountered" do tester = FormatTester.new expect(format).to receive(:render).with(tester).and_raise("eh") expect do tester.render(:foo) end.to raise_error(Puppet::Network::FormatHandler::FormatError, 'Could not render to foo: eh') end it "should call the format-specific converter when asked to convert to a given format" do tester = FormatTester.new expect(format).to receive(:render).with(tester).and_return("foo") expect(tester.render(:foo)).to eq("foo") end it "should call the format-specific converter when asked to convert to a given format by mime-type" do tester = FormatTester.new expect(format).to receive(:render).with(tester).and_return("foo") expect(tester.render("text/foo")).to eq("foo") end it "should call the format converter when asked to convert to a given format instance" do tester = FormatTester.new expect(format).to receive(:render).with(tester).and_return("foo") expect(tester.render(format)).to eq("foo") end it "should render to the default format if no format is provided when rendering" do expect(FormatTester).to receive(:default_format).and_return(:foo) tester = FormatTester.new expect(format).to receive(:render).with(tester) tester.render end it "should call the format-specific converter when asked for the mime-type of a given format" do tester = FormatTester.new expect(format).to receive(:mime).and_return("text/foo") expect(tester.mime(:foo)).to eq("text/foo") end it "should return the default format mime-type if no format is provided" do expect(FormatTester).to receive(:default_format).and_return(:foo) tester = FormatTester.new expect(format).to receive(:mime).and_return("text/foo") expect(tester.mime).to eq("text/foo") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/format_spec.rb
spec/unit/network/format_spec.rb
require 'spec_helper' require 'puppet/network/format' # A class with all of the necessary # hooks. class FormatRenderer def self.to_multiple_my_format(list) end def self.from_multiple_my_format(text) end def self.from_my_format(text) end def to_my_format end end describe Puppet::Network::Format do describe "when initializing" do it "should require a name" do expect { Puppet::Network::Format.new }.to raise_error(ArgumentError) end it "should be able to provide its name" do expect(Puppet::Network::Format.new(:my_format).name).to eq(:my_format) end it "should always convert its name to a downcased symbol" do expect(Puppet::Network::Format.new(:My_Format).name).to eq(:my_format) end it "should be able to set its downcased mime type at initialization" do format = Puppet::Network::Format.new(:my_format, :mime => "Foo/Bar") expect(format.mime).to eq("foo/bar") end it "should default to text plus the name of the format as the mime type" do expect(Puppet::Network::Format.new(:my_format).mime).to eq("text/my_format") end it "should fail if unsupported options are provided" do expect { Puppet::Network::Format.new(:my_format, :foo => "bar") }.to raise_error(ArgumentError) end end describe "instances" do before do @format = Puppet::Network::Format.new(:my_format) end it "should support being confined" do expect(@format).to respond_to(:confine) end it "should not be considered suitable if confinement conditions are not met" do @format.confine :true => false expect(@format).not_to be_suitable end it "should be able to determine if a class is supported" do expect(@format).to respond_to(:supported?) end it "should consider a class to be supported if it has the individual and multiple methods for rendering and interning" do expect(@format).to be_supported(FormatRenderer) end it "should default to its required methods being the individual and multiple methods for rendering and interning" do expect(Puppet::Network::Format.new(:foo).required_methods.sort { |a,b| a.to_s <=> b.to_s }).to eq([:intern_method, :intern_multiple_method, :render_multiple_method, :render_method].sort { |a,b| a.to_s <=> b.to_s }) end it "should consider a class supported if the provided class has all required methods present" do format = Puppet::Network::Format.new(:foo) [:intern_method, :intern_multiple_method, :render_multiple_method, :render_method].each do |method| expect(format).to receive(:required_method_present?).with(method, String, anything).and_return(true) end expect(format).to be_required_methods_present(String) end it "should consider a class not supported if any required methods are missing from the provided class" do format = Puppet::Network::Format.new(:foo) allow(format).to receive(:required_method_present?).and_return(true) expect(format).to receive(:required_method_present?).with(:intern_method, anything, anything).and_return(false) expect(format).not_to be_required_methods_present(String) end it "should be able to specify the methods required for support" do expect(Puppet::Network::Format.new(:foo, :required_methods => [:render_method, :intern_method]).required_methods).to eq([:render_method, :intern_method]) end it "should only test for required methods if specific methods are specified as required" do format = Puppet::Network::Format.new(:foo, :required_methods => [:intern_method]) expect(format).to receive(:required_method_present?).with(:intern_method, anything, anything) format.required_methods_present?(String) end it "should not consider a class supported unless the format is suitable" do expect(@format).to receive(:suitable?).and_return(false) expect(@format).not_to be_supported(FormatRenderer) end it "should always downcase mimetypes" do @format.mime = "Foo/Bar" expect(@format.mime).to eq("foo/bar") end it "should support having a weight" do expect(@format).to respond_to(:weight) end it "should default to a weight of of 5" do expect(@format.weight).to eq(5) end it "should be able to override its weight at initialization" do expect(Puppet::Network::Format.new(:foo, :weight => 1).weight).to eq(1) end it "should default to its extension being equal to its name" do expect(Puppet::Network::Format.new(:foo).extension).to eq("foo") end it "should support overriding the extension" do expect(Puppet::Network::Format.new(:foo, :extension => "bar").extension).to eq("bar") end it "doesn't support charset by default" do expect(Puppet::Network::Format.new(:foo).charset).to be_nil end it "allows charset to be set to 'utf-8'" do expect(Puppet::Network::Format.new(:foo, :charset => Encoding::UTF_8).charset).to eq(Encoding::UTF_8) end [:intern_method, :intern_multiple_method, :render_multiple_method, :render_method].each do |method| it "should allow assignment of the #{method}" do expect(Puppet::Network::Format.new(:foo, method => :foo).send(method)).to eq(:foo) end end end describe "when converting between instances and formatted text" do before do @format = Puppet::Network::Format.new(:my_format) @instance = FormatRenderer.new end it "should have a method for rendering a single instance" do expect(@format).to respond_to(:render) end it "should have a method for rendering multiple instances" do expect(@format).to respond_to(:render_multiple) end it "should have a method for interning text" do expect(@format).to respond_to(:intern) end it "should have a method for interning text into multiple instances" do expect(@format).to respond_to(:intern_multiple) end it "should return the results of calling the instance-specific render method if the method is present" do expect(@instance).to receive(:to_my_format).and_return("foo") expect(@format.render(@instance)).to eq("foo") end it "should return the results of calling the class-specific render_multiple method if the method is present" do expect(@instance.class).to receive(:to_multiple_my_format).and_return(["foo"]) expect(@format.render_multiple([@instance])).to eq(["foo"]) end it "should return the results of calling the class-specific intern method if the method is present" do expect(FormatRenderer).to receive(:from_my_format).with("foo").and_return(@instance) expect(@format.intern(FormatRenderer, "foo")).to equal(@instance) end it "should return the results of calling the class-specific intern_multiple method if the method is present" do expect(FormatRenderer).to receive(:from_multiple_my_format).with("foo").and_return([@instance]) expect(@format.intern_multiple(FormatRenderer, "foo")).to eq([@instance]) end it "should fail if asked to render and the instance does not respond to 'to_<format>'" do expect { @format.render("foo") }.to raise_error(NotImplementedError) end it "should fail if asked to intern and the class does not respond to 'from_<format>'" do expect { @format.intern(String, "foo") }.to raise_error(NotImplementedError) end it "should fail if asked to intern multiple and the class does not respond to 'from_multiple_<format>'" do expect { @format.intern_multiple(String, "foo") }.to raise_error(NotImplementedError) end it "should fail if asked to render multiple and the instance does not respond to 'to_multiple_<format>'" do expect { @format.render_multiple(["foo", "bar"]) }.to raise_error(NotImplementedError) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/formats_spec.rb
spec/unit/network/formats_spec.rb
require 'spec_helper' require 'puppet/network/formats' require 'puppet/network/format_support' class FormatsTest include Puppet::Network::FormatSupport attr_accessor :string def ==(other) string == other.string end def self.from_data_hash(data) new(data['string']) end def initialize(string) @string = string end def to_data_hash(*args) { 'string' => @string } end def to_binary string end def self.from_binary(data) self.new(data) end end describe "Puppet Network Format" do it "should include a msgpack format", :if => Puppet.features.msgpack? do expect(Puppet::Network::FormatHandler.format(:msgpack)).not_to be_nil end describe "msgpack", :if => Puppet.features.msgpack? do let(:msgpack) { Puppet::Network::FormatHandler.format(:msgpack) } it "should have its mime type set to application/x-msgpack" do expect(msgpack.mime).to eq("application/x-msgpack") end it "should have a nil charset" do expect(msgpack.charset).to be_nil end it "should have a weight of 20" do expect(msgpack.weight).to eq(20) end it "should fail when one element does not have a from_data_hash" do expect do msgpack.intern_multiple(Hash, MessagePack.pack(["foo"])) end.to raise_error(NoMethodError) end it "should be able to serialize a catalog" do cat = Puppet::Resource::Catalog.new('foo', Puppet::Node::Environment.create(:testing, [])) cat.add_resource(Puppet::Resource.new(:file, 'my_file')) catunpack = MessagePack.unpack(cat.to_msgpack) expect(catunpack).to include( "tags"=>[], "name"=>"foo", "version"=>nil, "environment"=>"testing", "edges"=>[], "classes"=>[] ) expect(catunpack["resources"][0]).to include( "type"=>"File", "title"=>"my_file", "exported"=>false ) expect(catunpack["resources"][0]["tags"]).to include( "file", "my_file" ) end end describe "yaml" do let(:yaml) { Puppet::Network::FormatHandler.format(:yaml) } it "should have its mime type set to text/yaml" do expect(yaml.mime).to eq("text/yaml") end # we shouldn't be using yaml on the network it "should have a nil charset" do expect(yaml.charset).to be_nil end it "should be supported on Strings" do expect(yaml).to be_supported(String) end it "should render by calling 'to_yaml' on the instance" do instance = double('instance') expect(instance).to receive(:to_yaml).and_return("foo") expect(yaml.render(instance)).to eq("foo") end it "should render multiple instances by calling 'to_yaml' on the array" do instances = [double('instance')] expect(instances).to receive(:to_yaml).and_return("foo") expect(yaml.render_multiple(instances)).to eq("foo") end it "should deserialize YAML" do expect(yaml.intern(String, YAML.dump("foo"))).to eq("foo") end it "should deserialize symbols as strings" do expect { yaml.intern(String, YAML.dump(:foo))}.to raise_error(Puppet::Network::FormatHandler::FormatError) end it "should skip data_to_hash if data is already an instance of the specified class" do # The rest terminus for the report indirected type relies on this behavior data = YAML.dump([1, 2]) instance = yaml.intern(Array, data) expect(instance).to eq([1, 2]) end it "should load from yaml when deserializing an array" do text = YAML.dump(["foo"]) expect(yaml.intern_multiple(String, text)).to eq(["foo"]) end it "fails intelligibly instead of calling to_json with something other than a hash" do expect do yaml.intern(Puppet::Node, '') end.to raise_error(Puppet::Network::FormatHandler::FormatError, /did not contain a valid instance/) end it "fails intelligibly when intern_multiple is called and yaml doesn't decode to an array" do expect do yaml.intern_multiple(Puppet::Node, '') end.to raise_error(Puppet::Network::FormatHandler::FormatError, /did not contain a collection/) end it "fails intelligibly instead of calling to_json with something other than a hash when interning multiple" do expect do yaml.intern_multiple(Puppet::Node, YAML.dump(["hello"])) end.to raise_error(Puppet::Network::FormatHandler::FormatError, /did not contain a valid instance/) end it 'accepts indirected classes' do [ Puppet::Node::Facts.new('foo', {}), Puppet::Node.new('foo'), Puppet::Resource.new('File', '/foo'), Puppet::Transaction::Report.new('foo'), Puppet::Resource::Catalog.new ].each { |obj| yaml.intern(obj.class, YAML.dump(obj.to_data_hash)) } end it 'raises when interning an instance of an unacceptable indirected type' do obj = :something expect { yaml.intern(obj.class, YAML.dump(obj)) }.to raise_error(Puppet::Network::FormatHandler::FormatError, /Tried to load unspecified class: Symbol/) end it 'raises when interning multple instances of an unacceptable indirected type' do obj = :something expect { yaml.intern_multiple(obj.class, YAML.dump([obj])) }.to raise_error(Puppet::Network::FormatHandler::FormatError, /Tried to load unspecified class: Symbol/) end end describe "plaintext" do let(:text) { Puppet::Network::FormatHandler.format(:s) } it "should have its mimetype set to text/plain" do expect(text.mime).to eq("text/plain") end it "should use 'utf-8' charset" do expect(text.charset).to eq(Encoding::UTF_8) end it "should use 'txt' as its extension" do expect(text.extension).to eq("txt") end end describe "dot" do let(:dot) { Puppet::Network::FormatHandler.format(:dot) } it "should have its mimetype set to text/dot" do expect(dot.mime).to eq("text/dot") end end describe Puppet::Network::FormatHandler.format(:binary) do let(:binary) { Puppet::Network::FormatHandler.format(:binary) } it "should exist" do expect(binary).not_to be_nil end it "should have its mimetype set to application/octet-stream" do expect(binary.mime).to eq("application/octet-stream") end it "should have a nil charset" do expect(binary.charset).to be_nil end it "should not be supported by default" do expect(binary).to_not be_supported(String) end it "should render an instance as binary" do instance = FormatsTest.new("foo") expect(binary.render(instance)).to eq("foo") end it "should intern an instance from a JSON hash" do instance = binary.intern(FormatsTest, "foo") expect(instance.string).to eq("foo") end it "should fail if its multiple_render method is used" do expect { binary.render_multiple("foo") }.to raise_error(NotImplementedError, /can not render multiple instances to application\/octet-stream/) end it "should fail if its multiple_intern method is used" do expect { binary.intern_multiple(String, "foo") }.to raise_error(NotImplementedError, /can not intern multiple instances from application\/octet-stream/) end it "should have a weight of 1" do expect(binary.weight).to eq(1) end end describe "pson", :if => Puppet.features.pson? do let(:pson) { Puppet::Network::FormatHandler.format(:pson) } it "should include a pson format" do expect(pson).not_to be_nil end it "should have its mime type set to text/pson" do expect(pson.mime).to eq("text/pson") end it "should have a nil charset" do expect(pson.charset).to be_nil end it "should require the :render_method" do expect(pson.required_methods).to be_include(:render_method) end it "should require the :intern_method" do expect(pson.required_methods).to be_include(:intern_method) end it "should have a weight of 10" do expect(pson.weight).to eq(10) end it "should render an instance as pson" do instance = FormatsTest.new("foo") expect(pson.render(instance)).to eq({"string" => "foo"}.to_pson) end it "should render multiple instances as pson" do instances = [FormatsTest.new("foo")] expect(pson.render_multiple(instances)).to eq([{"string" => "foo"}].to_pson) end it "should intern an instance from a pson hash" do text = PSON.dump({"string" => "parsed_pson"}) instance = pson.intern(FormatsTest, text) expect(instance.string).to eq("parsed_pson") end it "should skip data_to_hash if data is already an instance of the specified class" do # The rest terminus for the report indirected type relies on this behavior data = PSON.dump([1, 2]) instance = pson.intern(Array, data) expect(instance).to eq([1, 2]) end it "should intern multiple instances from a pson array" do text = PSON.dump( [ { "string" => "BAR" }, { "string" => "BAZ" } ] ) expect(pson.intern_multiple(FormatsTest, text)).to eq([FormatsTest.new('BAR'), FormatsTest.new('BAZ')]) end it "should unwrap the data from legacy clients" do text = PSON.dump( { "type" => "FormatsTest", "data" => { "string" => "parsed_json" } } ) instance = pson.intern(FormatsTest, text) expect(instance.string).to eq("parsed_json") end it "fails intelligibly when given invalid data" do expect do pson.intern(Puppet::Node, '') end.to raise_error(PSON::ParserError, /source did not contain any PSON/) end end describe "json" do let(:json) { Puppet::Network::FormatHandler.format(:json) } it "should include a json format" do expect(json).not_to be_nil end it "should have its mime type set to application/json" do expect(json.mime).to eq("application/json") end it "should use 'utf-8' charset" do expect(json.charset).to eq(Encoding::UTF_8) end it "should require the :render_method" do expect(json.required_methods).to be_include(:render_method) end it "should require the :intern_method" do expect(json.required_methods).to be_include(:intern_method) end it "should have a weight of 15" do expect(json.weight).to eq(15) end it "should render an instance as JSON" do instance = FormatsTest.new("foo") expect(json.render(instance)).to eq({"string" => "foo"}.to_json) end it "should render multiple instances as a JSON array of hashes" do instances = [FormatsTest.new("foo")] expect(json.render_multiple(instances)).to eq([{"string" => "foo"}].to_json) end it "should render multiple instances as a JSON array of hashes when multi_json is not present" do hide_const("MultiJson") if defined?(MultiJson) instances = [FormatsTest.new("foo")] expect(json.render_multiple(instances)).to eq([{"string" => "foo"}].to_json) end it "should intern an instance from a JSON hash" do text = Puppet::Util::Json.dump({"string" => "parsed_json"}) instance = json.intern(FormatsTest, text) expect(instance.string).to eq("parsed_json") end it "should skip data_to_hash if data is already an instance of the specified class" do # The rest terminus for the report indirected type relies on this behavior data = Puppet::Util::Json.dump([1, 2]) instance = json.intern(Array, data) expect(instance).to eq([1, 2]) end it "should intern multiple instances from a JSON array of hashes" do text = Puppet::Util::Json.dump( [ { "string" => "BAR" }, { "string" => "BAZ" } ] ) expect(json.intern_multiple(FormatsTest, text)).to eq([FormatsTest.new('BAR'), FormatsTest.new('BAZ')]) end it "should reject wrapped data from legacy clients as they've never supported JSON" do text = Puppet::Util::Json.dump( { "type" => "FormatsTest", "data" => { "string" => "parsed_json" } } ) instance = json.intern(FormatsTest, text) expect(instance.string).to be_nil end it "fails intelligibly when given invalid data" do expect do json.intern(Puppet::Node, '') end.to raise_error(Puppet::Util::Json::ParseError) end end describe ":console format" do let(:console) { Puppet::Network::FormatHandler.format(:console) } it "should include a console format" do expect(console).to be_an_instance_of Puppet::Network::Format end [:intern, :intern_multiple].each do |method| it "should not implement #{method}" do expect { console.send(method, String, 'blah') }.to raise_error NotImplementedError end end context "when rendering ruby types" do ["hello", 1, 1.0].each do |input| it "should just return a #{input.inspect}" do expect(console.render(input)).to eq(input) end end { true => "true", false => "false", nil => "null", }.each_pair do |input, output| it "renders #{input.class} as '#{output}'" do expect(console.render(input)).to eq(output) end end it "renders an Object as its quoted inspect value" do obj = Object.new expect(console.render(obj)).to eq("\"#{obj.inspect}\"") end end context "when rendering arrays" do { [] => "", [1, 2] => "1\n2\n", ["one"] => "one\n", [{1 => 1}] => "{1\s*=>\s*1}\n", [[1, 2], [3, 4]] => "[1, 2]\n[3, 4]\n" }.each_pair do |input, output| it "should render #{input.inspect} as one item per line" do expect(console.render(input)).to match(output) end end end context "when rendering hashes" do { {} => "", {1 => 2} => "1 2\n", {"one" => "two"} => "one \"two\"\n", # odd that two is quoted but one isn't {[1,2] => 3, [2,3] => 5, [3,4] => 7} => "{\n \"[1, 2]\": 3,\n \"[2, 3]\": 5,\n \"[3, 4]\": 7\n}", {{1 => 2} => {3 => 4}} => "{\n \"{1\s*=>\s*2}\": {\n \"3\": 4\n }\n}" }.each_pair do |input, output| it "should render #{input.inspect}" do expect(console.render(input)).to match(output) end end it "should render a {String,Numeric}-keyed Hash into a table" do json = Puppet::Network::FormatHandler.format(:json) 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(console.render(hash)).to eq <<EOT 5 5 6.0 6 four #{json.render(object).chomp} one 1 three {} two [] EOT end end context "when rendering face-related objects" do it "pretty prints facts" do tm = Time.new(2016, 1, 27, 19, 30, 0) values = { "architecture" => "x86_64", "os" => { "release" => { "full" => "15.6.0" } }, "system_uptime" => { "seconds" => 505532 } } facts = Puppet::Node::Facts.new("foo", values) facts.timestamp = tm # For some reason, render omits the last newline, seems like a bug expect(console.render(facts)).to eq(<<EOT.chomp) { "name": "foo", "values": { "architecture": "x86_64", "os": { "release": { "full": "15.6.0" } }, "system_uptime": { "seconds": 505532 } }, "timestamp": "#{tm.iso8601(9)}" } EOT end end end describe ":flat format" do let(:flat) { Puppet::Network::FormatHandler.format(:flat) } it "should include a flat format" do expect(flat).to be_an_instance_of Puppet::Network::Format end [:intern, :intern_multiple].each do |method| it "should not implement #{method}" do expect { flat.send(method, String, 'blah') }.to raise_error NotImplementedError end end context "when rendering arrays" do { [] => "", [1, 2] => "0=1\n1=2\n", ["one"] => "0=one\n", [{"one" => 1}, {"two" => 2}] => "0.one=1\n1.two=2\n", [['something', 'for'], ['the', 'test']] => "0=[\"something\", \"for\"]\n1=[\"the\", \"test\"]\n" }.each_pair do |input, output| it "should render #{input.inspect} as one item per line" do expect(flat.render(input)).to eq(output) end end end context "when rendering hashes" do { {} => "", {1 => 2} => "1=2\n", {"one" => "two"} => "one=two\n", {[1,2] => 3, [2,3] => 5, [3,4] => 7} => "[1, 2]=3\n[2, 3]=5\n[3, 4]=7\n", }.each_pair do |input, output| it "should render #{input.inspect}" do expect(flat.render(input)).to eq(output) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/authconfig_spec.rb
spec/unit/network/authconfig_spec.rb
require 'spec_helper' require 'puppet/network/authconfig' describe Puppet::Network::AuthConfig do it "accepts an auth provider class" do Puppet::Network::AuthConfig.authprovider_class = Object end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/uri_spec.rb
spec/unit/network/uri_spec.rb
require 'spec_helper' require 'puppet/network/uri' describe Puppet::Network::Uri do include Puppet::Network::Uri describe '.mask_credentials' do let(:address_with_passwd) { 'https://admin:S3cr3T@puppetforge.acmecorp.com/' } let(:masked) { 'https://admin:***@puppetforge.acmecorp.com/' } let(:address) { 'https://puppetforge.acmecorp.com/' } subject do input = to_be_masked.dup result = mask_credentials(input) raise 'illegal unexpected modification' if input != to_be_masked result end describe 'if password was given in URI' do describe 'as a String' do let(:to_be_masked) { address_with_passwd } it 'should mask out password' do is_expected.to eq(masked) end end describe 'as an URI' do let(:to_be_masked) { URI.parse(address_with_passwd) } it 'should mask out password' do is_expected.to eq(masked) end end end describe "if password wasn't given in URI" do describe 'as a String' do let(:to_be_masked) { address } it "shouldn't add mask to URI" do is_expected.to eq(address) end end describe 'as an URI' do let(:to_be_masked) { URI.parse(address) } it "shouldn't add mask to URI" do is_expected.to eq(address) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http_pool_spec.rb
spec/unit/network/http_pool_spec.rb
require 'spec_helper' require 'puppet/network/http_pool' class Puppet::Network::HttpPool::FooClient def initialize(host, port, options = {}) @host = host @port = port end attr_reader :host, :port end describe Puppet::Network::HttpPool do include PuppetSpec::Files describe "when registering an http client class" do let(:http_impl) { Puppet::Network::HttpPool::FooClient } around :each do |example| orig_class = Puppet::Network::HttpPool.http_client_class begin example.run ensure Puppet::Network::HttpPool.http_client_class = orig_class end end it "returns instances of the http client class" do Puppet::Network::HttpPool.http_client_class = http_impl http = Puppet::Network::HttpPool.http_instance("me", 54321) expect(http).to be_an_instance_of(http_impl) expect(http.host).to eq('me') expect(http.port).to eq(54321) end it "uses the default http client" do expect(Puppet.runtime[:http]).to be_an_instance_of(Puppet::HTTP::Client) end it "switches to the external client implementation" do Puppet::Network::HttpPool.http_client_class = http_impl expect(Puppet.runtime[:http]).to be_an_instance_of(Puppet::HTTP::ExternalClient) end it "always uses an explicitly registered http implementation" do Puppet::Network::HttpPool.http_client_class = http_impl new_impl = double('new_http_impl') Puppet.initialize_settings([], true, true, http: new_impl) expect(Puppet.runtime[:http]).to eq(new_impl) end end describe "when managing http instances" do it "should return an http instance created with the passed host and port" do http = Puppet::Network::HttpPool.http_instance("me", 54321) expect(http).to be_a_kind_of Puppet::Network::HTTP::Connection expect(http.address).to eq('me') expect(http.port).to eq(54321) end it "should enable ssl on the http instance by default" do expect(Puppet::Network::HttpPool.http_instance("me", 54321)).to be_use_ssl end it "can set ssl using an option" do expect(Puppet::Network::HttpPool.http_instance("me", 54321, false)).not_to be_use_ssl expect(Puppet::Network::HttpPool.http_instance("me", 54321, true)).to be_use_ssl end context "when calling 'connection'" do it 'requires an ssl_context' do expect { Puppet::Network::HttpPool.connection('me', 8140) }.to raise_error(ArgumentError, "An ssl_context is required when connecting to 'https://me:8140'") end it 'creates a verifier from the context' do ssl_context = Puppet::SSL::SSLContext.new expect( Puppet::Network::HttpPool.connection('me', 8140, ssl_context: ssl_context).verifier ).to be_a_kind_of(Puppet::SSL::Verifier) end it 'does not use SSL when specified' do expect(Puppet::Network::HttpPool.connection('me', 8140, use_ssl: false)).to_not be_use_ssl end it 'defaults to SSL' do ssl_context = Puppet::SSL::SSLContext.new conn = Puppet::Network::HttpPool.connection('me', 8140, ssl_context: ssl_context) expect(conn).to be_use_ssl end it 'warns if an ssl_context is used for an http connection' do expect(Puppet).to receive(:warning).with("An ssl_context is unnecessary when connecting to 'http://me:8140' and will be ignored") ssl_context = Puppet::SSL::SSLContext.new Puppet::Network::HttpPool.connection('me', 8140, use_ssl: false, ssl_context: ssl_context) end end describe 'peer verification' do before(:each) do Puppet[:ssldir] = tmpdir('ssl') Puppet.settings.use(:main) Puppet[:certname] = 'signed' File.write(Puppet[:localcacert], cert_fixture('ca.pem')) File.write(Puppet[:hostcrl], crl_fixture('crl.pem')) File.write(Puppet[:hostcert], cert_fixture('signed.pem')) File.write(Puppet[:hostprivkey], key_fixture('signed-key.pem')) end it 'enables peer verification by default' do stub_request(:get, "https://me:54321") conn = Puppet::Network::HttpPool.http_instance("me", 54321, true) expect_any_instance_of(Net::HTTP).to receive(:start) do |http| expect(http.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER) end conn.get('/') end it 'can disable peer verification' do stub_request(:get, "https://me:54321") conn = Puppet::Network::HttpPool.http_instance("me", 54321, true, false) expect_any_instance_of(Net::HTTP).to receive(:start) do |http| expect(http.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE) end conn.get('/') end end it "should not cache http instances" do expect(Puppet::Network::HttpPool.http_instance("me", 54321)). not_to equal(Puppet::Network::HttpPool.http_instance("me", 54321)) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/response_spec.rb
spec/unit/network/http/response_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/handler' require 'puppet/network/http' describe Puppet::Network::HTTP::Response do include PuppetSpec::Files let(:handler) { PuppetSpec::Handler.new } let(:response) { {} } let(:subject) { described_class.new(handler, response) } let(:body_utf8) { JSON.dump({ "foo" => "bar"}).encode('UTF-8') } let(:body_shift_jis) { [130, 174].pack('C*').force_encoding(Encoding::Shift_JIS) } let(:invalid_shift_jis) { "\xC0\xFF".force_encoding(Encoding::Shift_JIS) } context "when passed a response body" do it "passes the status code and body to the handler" do expect(handler).to receive(:set_response).with(response, body_utf8, 200) subject.respond_with(200, 'application/json', body_utf8) end it "accepts a File body" do file = tmpfile('response_spec') expect(handler).to receive(:set_response).with(response, file, 200) subject.respond_with(200, 'application/octet-stream', file) end end context "when passed a content type" do it "accepts a mime string" do expect(handler).to receive(:set_content_type).with(response, 'application/json; charset=utf-8') subject.respond_with(200, 'application/json', body_utf8) end it "accepts a format object" do formatter = Puppet::Network::FormatHandler.format(:json) expect(handler).to receive(:set_content_type).with(response, 'application/json; charset=utf-8') subject.respond_with(200, formatter, body_utf8) end end context "when resolving charset" do context "with binary content" do it "omits the charset" do body_binary = [0xDEADCAFE].pack('L') formatter = Puppet::Network::FormatHandler.format(:binary) expect(handler).to receive(:set_content_type).with(response, 'application/octet-stream') subject.respond_with(200, formatter, body_binary) end end context "with text/plain content" do let(:formatter) { Puppet::Network::FormatHandler.format(:s) } it "sets the charset to UTF-8 for content already in that format" do body_pem = "BEGIN CERTIFICATE".encode('UTF-8') expect(handler).to receive(:set_content_type).with(response, 'text/plain; charset=utf-8') subject.respond_with(200, formatter, body_pem) end it "encodes the content to UTF-8 for content not already in UTF-8" do expect(handler).to receive(:set_content_type).with(response, 'text/plain; charset=utf-8') expect(handler).to receive(:set_response).with(response, body_shift_jis.encode('utf-8'), 200) subject.respond_with(200, formatter, body_shift_jis) end it "raises an exception if transcoding fails" do expect { subject.respond_with(200, formatter, invalid_shift_jis) }.to raise_error(EncodingError, /"\\xFF" on Shift_JIS/) end end context "with application/json content" do let(:formatter) { Puppet::Network::FormatHandler.format(:json) } it "sets the charset to UTF-8 for content already in that format" do expect(handler).to receive(:set_content_type).with(response, 'application/json; charset=utf-8') subject.respond_with(200, formatter, body_utf8) end it "encodes the content to UTF-8 for content not already in UTF-8" do expect(handler).to receive(:set_content_type).with(response, 'application/json; charset=utf-8') expect(handler).to receive(:set_response).with(response, body_shift_jis.encode('utf-8'), 200) subject.respond_with(200, formatter, body_shift_jis) end it "raises an exception if transcoding fails" do expect { subject.respond_with(200, formatter, invalid_shift_jis) }.to raise_error(EncodingError, /"\\xFF" on Shift_JIS/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/request_spec.rb
spec/unit/network/http/request_spec.rb
require 'spec_helper' require 'puppet_spec/network' require 'puppet/network/http' describe Puppet::Network::HTTP::Request do include PuppetSpec::Network let(:json_formatter) { Puppet::Network::FormatHandler.format(:json) } let(:pson_formatter) { Puppet::Network::FormatHandler.format(:pson) } def headers { 'accept' => 'application/json', 'content-type' => 'application/json' } end def a_request(headers, body = "") described_class.from_hash( :method => "PUT", :path => "/path/to/endpoint", :body => body, :headers => headers ) end context "when resolving the formatter for the request body" do it "returns the formatter for that Content-Type" do request = a_request(headers.merge("content-type" => "application/json")) expect(request.formatter).to eq(json_formatter) end it "raises HTTP 400 if Content-Type is missing" do request = a_request({}) expect { request.formatter }.to raise_error(bad_request_error, /No Content-Type header was received, it isn't possible to unserialize the request/) end it "raises HTTP 415 if Content-Type is unsupported" do request = a_request(headers.merge('content-type' => 'application/ogg')) expect { request.formatter }.to raise_error(unsupported_media_type_error, /Unsupported Media Type: Client sent a mime-type \(application\/ogg\) that doesn't correspond to a format we support/) end it "raises HTTP 415 if Content-Type is unsafe yaml" do request = a_request(headers.merge('content-type' => 'yaml')) expect { request.formatter }.to raise_error(unsupported_media_type_error, /Unsupported Media Type: Client sent a mime-type \(yaml\) that doesn't correspond to a format we support/) end it "raises HTTP 415 if Content-Type is unsafe b64_zlib_yaml" do request = a_request(headers.merge('content-type' => 'b64_zlib_yaml')) expect { request.formatter }.to raise_error(unsupported_media_type_error, /Unsupported Media Type: Client sent a mime-type \(b64_zlib_yaml\) that doesn't correspond to a format we support/) end end context "when resolving the formatter for the response body" do context "when the client doesn't specify an Accept header" do it "raises HTTP 400 if the server doesn't specify a default" do request = a_request({}) expect { request.response_formatters_for([:json]) }.to raise_error(bad_request_error, /Missing required Accept header/) end it "uses the server default" do request = a_request({}) expect(request.response_formatters_for([:json], 'application/json')).to eq([json_formatter]) end end it "returns accepted and supported formats, in the accepted order" do request = a_request(headers.merge('accept' => 'application/json, application/x-msgpack, text/pson')) expect(request.response_formatters_for([:pson, :json])).to eq([json_formatter, pson_formatter]) end it "selects the second format if the first one isn't supported by the server" do request = a_request(headers.merge('accept' => 'application/json, text/pson')) expect(request.response_formatters_for([:pson])).to eq([pson_formatter]) end it "raises HTTP 406 if Accept doesn't include any server-supported formats" do request = a_request(headers.merge('accept' => 'application/ogg')) expect { request.response_formatters_for([:json]) }.to raise_error(not_acceptable_error, /No supported formats are acceptable \(Accept: application\/ogg\)/) end it "raises HTTP 406 if Accept resolves to unsafe yaml" do request = a_request(headers.merge('accept' => 'yaml')) expect { request.response_formatters_for([:json]) }.to raise_error(not_acceptable_error, /No supported formats are acceptable \(Accept: yaml\)/) end it "raises HTTP 406 if Accept resolves to unsafe b64_zlib_yaml" do request = a_request(headers.merge('accept' => 'b64_zlib_yaml')) expect { request.response_formatters_for([:json]) }.to raise_error(not_acceptable_error, /No supported formats are acceptable \(Accept: b64_zlib_yaml\)/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/api_spec.rb
spec/unit/network/http/api_spec.rb
require 'spec_helper' require 'puppet_spec/handler' require 'puppet/network/http' require 'puppet/version' describe Puppet::Network::HTTP::API do def respond(text) lambda { |req, res| res.respond_with(200, "text/plain", text) } end describe "#not_found" do let(:response) { Puppet::Network::HTTP::MemoryResponse.new } let(:routes) { Puppet::Network::HTTP::Route.path(Regexp.new("foo")). any. chain(Puppet::Network::HTTP::Route.path(%r{^/bar$}).get(respond("bar")), Puppet::Network::HTTP::API.not_found) } it "mounts the chained routes" do request = Puppet::Network::HTTP::Request.from_hash(:path => "foo/bar") routes.process(request, response) expect(response.code).to eq(200) expect(response.body).to eq("bar") end it "responds to unknown paths with a 404" do request = Puppet::Network::HTTP::Request.from_hash(:path => "foo/unknown") expect do routes.process(request, response) end.to raise_error(Puppet::Network::HTTP::Error::HTTPNotFoundError) end end describe "Puppet API" do let(:handler) { PuppetSpec::Handler.new(Puppet::Network::HTTP::API.server_routes, Puppet::Network::HTTP::API.not_found_upgrade) } let(:server_prefix) { Puppet::Network::HTTP::SERVER_URL_PREFIX } it "raises a not-found error for non-CA or server routes and suggests an upgrade" do req = Puppet::Network::HTTP::Request.from_hash(:path => "/unknown") res = {} handler.process(req, res) expect(res[:status]).to eq(404) expect(res[:body]).to include("Puppet version: #{Puppet.version}") end describe "when processing Puppet 3 routes" do it "gives an upgrade message for server routes" do req = Puppet::Network::HTTP::Request.from_hash(:path => "/production/node/foo") res = {} handler.process(req, res) expect(res[:status]).to eq(404) expect(res[:body]).to include("Puppet version: #{Puppet.version}") expect(res[:body]).to include("Supported /puppet API versions: #{Puppet::Network::HTTP::SERVER_URL_VERSIONS}") end it "gives an upgrade message for CA routes" do req = Puppet::Network::HTTP::Request.from_hash(:path => "/production/certificate/foo") res = {} handler.process(req, res) expect(res[:status]).to eq(404) expect(res[:body]).to include("Puppet version: #{Puppet.version}") expect(res[:body]).to include("Supported /puppet API versions: #{Puppet::Network::HTTP::SERVER_URL_VERSIONS}") end end describe "when processing server routes" do # simulate puppetserver registering its authconfigloader class around :each do |example| Puppet::Network::Authorization.authconfigloader_class = Object begin example.run ensure Puppet::Network::Authorization.authconfigloader_class = nil end end it "responds to v3 indirector requests" do req = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_prefix}/v3/node/foo", :params => {:environment => "production"}, :headers => {'accept' => "application/json"}) res = {} handler.process(req, res) expect(res[:status]).to eq(200) end it "responds to v3 environments requests" do req = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_prefix}/v3/environments") res = {} handler.process(req, res) expect(res[:status]).to eq(200) end it "responds with a not found error to non-v3 requests and does not suggest an upgrade" do req = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_prefix}/unknown") res = {} handler.process(req, res) expect(res[:status]).to eq(404) expect(res[:body]).to include("No route for GET #{server_prefix}/unknown") expect(res[:body]).not_to include("Puppet version: #{Puppet.version}") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/connection_spec.rb
spec/unit/network/http/connection_spec.rb
require 'spec_helper' require 'puppet/network/http/connection' require 'puppet/test_ca' describe Puppet::Network::HTTP::Connection do let(:host) { "me.example.com" } let(:port) { 8140 } let(:path) { '/foo' } let(:url) { "https://#{host}:#{port}#{path}" } let(:params) { { 'key' => 'a value' } } let(:encoded_url_with_params) { "#{url}?%7B%22key%22:%22a%20value%22%7D" } let(:ssl_context) { Puppet::SSL::SSLProvider.new.create_system_context(cacerts: []) } let(:verifier) { Puppet::SSL::Verifier.new(host, ssl_context) } shared_examples_for "an HTTP connection" do |klass| subject { klass.new(host, port, :verifier => verifier) } context "when providing HTTP connections" do context "when initializing http instances" do it "should return an http instance created with the passed host and port" do conn = klass.new(host, port, :verifier => verifier) expect(conn.address).to eq(host) expect(conn.port).to eq(port) end it "should enable ssl on the http instance by default" do conn = klass.new(host, port, :verifier => verifier) expect(conn).to be_use_ssl end it "can disable ssl using an option and ignore the verify" do conn = klass.new(host, port, :use_ssl => false) expect(conn).to_not be_use_ssl end it "can enable ssl using an option" do conn = klass.new(host, port, :use_ssl => true, :verifier => verifier) expect(conn).to be_use_ssl end it "ignores the ':verify' option when ssl is disabled" do conn = klass.new(host, port, :use_ssl => false, :verifier => verifier) expect(conn.verifier).to be_nil end it "wraps the validator in an adapter" do conn = klass.new(host, port, :verifier => verifier) expect(conn.verifier).to be_a(Puppet::SSL::Verifier) end it "should raise Puppet::Error when invalid options are specified" do expect { klass.new(host, port, :invalid_option => nil) }.to raise_error(Puppet::Error, 'Unrecognized option(s): :invalid_option') end it "accepts a verifier" do verifier = Puppet::SSL::Verifier.new(host, double('ssl_context')) conn = klass.new(host, port, :use_ssl => true, :verifier => verifier) expect(conn.verifier).to eq(verifier) end it "raises if the wrong verifier class is specified" do expect { klass.new(host, port, :verifier => Object.new) }.to raise_error(ArgumentError, "Expected an instance of Puppet::SSL::Verifier but was passed a Object") end end end context "for streaming GET requests" do it 'yields the response' do stub_request(:get, url) expect { |b| subject.request_get('/foo', {}, &b) }.to yield_with_args(Net::HTTPResponse) end it "stringifies keys and encodes values in the query" do stub_request(:get, encoded_url_with_params) subject.request_get("#{path}?#{params.to_json}") { |_| } end it "merges custom headers with default ones" do stub_request(:get, url).with(headers: { 'X-Foo' => 'Bar', 'User-Agent' => /./ }) subject.request_get(path, {'X-Foo' => 'Bar'}) { |_| } end it "returns the response" do stub_request(:get, url) response = subject.request_get(path) { |_| } expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:get, url_with_query) response = subject.request_get(url_with_query) { |_| } expect(response).to be_an_instance_of(Net::HTTPOK) end end context "for streaming head requests" do it 'yields the response when request_head is called' do stub_request(:head, url) expect { |b| subject.request_head('/foo', {}, &b) }.to yield_with_args(Net::HTTPResponse) end it "stringifies keys and encodes values in the query" do stub_request(:head, encoded_url_with_params) subject.request_head("#{path}?#{params.to_json}") { |_| } end it "merges custom headers with default ones" do stub_request(:head, url).with(headers: { 'X-Foo' => 'Bar', 'User-Agent' => /./ }) subject.request_head(path, {'X-Foo' => 'Bar'}) { |_| } end it "returns the response" do stub_request(:head, url) response = subject.request_head(path) { |_| } expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:head, url_with_query) response = subject.request_head(url_with_query) { |_| } expect(response).to be_an_instance_of(Net::HTTPOK) end end context "for streaming post requests" do it 'yields the response when request_post is called' do stub_request(:post, url) expect { |b| subject.request_post('/foo', "param: value", &b) }.to yield_with_args(Net::HTTPResponse) end it "stringifies keys and encodes values in the query" do stub_request(:post, encoded_url_with_params) subject.request_post("#{path}?#{params.to_json}", "") { |_| } end it "merges custom headers with default ones" do stub_request(:post, url).with(headers: { 'X-Foo' => 'Bar', 'User-Agent' => /./ }) subject.request_post(path, "", {'X-Foo' => 'Bar'}) { |_| } end it "returns the response" do stub_request(:post, url) response = subject.request_post(path, "") { |_| } expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:post, url_with_query) response = subject.request_post(url_with_query, "") { |_| } expect(response).to be_an_instance_of(Net::HTTPOK) end end context "for GET requests" do it "includes default HTTP headers" do stub_request(:get, url).with(headers: {'User-Agent' => /./}) subject.get(path) end it "stringifies keys and encodes values in the query" do stub_request(:get, encoded_url_with_params) subject.get("#{path}?#{params.to_json}") end it "merges custom headers with default ones" do stub_request(:get, url).with(headers: { 'X-Foo' => 'Bar', 'User-Agent' => /./ }) subject.get(path, {'X-Foo' => 'Bar'}) end it "returns the response" do stub_request(:get, url) response = subject.get(path) expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "returns the entire response body" do stub_request(:get, url).to_return(body: "abc") response = subject.get(path) expect(response.body).to eq("abc") end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:get, url_with_query) response = subject.get(url_with_query) expect(response).to be_an_instance_of(Net::HTTPOK) end end context "for HEAD requests" do it "includes default HTTP headers" do stub_request(:head, url).with(headers: {'User-Agent' => /./}) subject.head(path) end it "stringifies keys and encodes values in the query" do stub_request(:head, encoded_url_with_params) subject.head("#{path}?#{params.to_json}") end it "merges custom headers with default ones" do stub_request(:head, url).with(headers: { 'X-Foo' => 'Bar', 'User-Agent' => /./ }) subject.head(path, {'X-Foo' => 'Bar'}) end it "returns the response" do stub_request(:head, url) response = subject.head(path) expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:head, url_with_query) response = subject.head(url_with_query) expect(response).to be_an_instance_of(Net::HTTPOK) end end context "for PUT requests" do it "includes default HTTP headers" do stub_request(:put, url).with(headers: {'User-Agent' => /./}) subject.put(path, "", {'Content-Type' => 'text/plain'}) end it "stringifies keys and encodes values in the query" do stub_request(:put, encoded_url_with_params) subject.put("#{path}?#{params.to_json}", "") end it "includes custom headers" do stub_request(:put, url).with(headers: { 'X-Foo' => 'Bar' }) subject.put(path, "", {'X-Foo' => 'Bar', 'Content-Type' => 'text/plain'}) end it "returns the response" do stub_request(:put, url) response = subject.put(path, "", {'Content-Type' => 'text/plain'}) expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "sets content-type for the body" do stub_request(:put, url).with(headers: {"Content-Type" => "text/plain"}) subject.put(path, "hello", {'Content-Type' => 'text/plain'}) end it 'sends an empty body' do stub_request(:put, url).with(body: '') subject.put(path, nil) end it 'defaults content-type to application/x-www-form-urlencoded' do stub_request(:put, url).with(headers: {'Content-Type' => 'application/x-www-form-urlencoded'}) subject.put(path, '') end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:put, url_with_query) response = subject.put(url_with_query, '') expect(response).to be_an_instance_of(Net::HTTPOK) end end context "for POST requests" do it "includes default HTTP headers" do stub_request(:post, url).with(headers: {'User-Agent' => /./}) subject.post(path, "", {'Content-Type' => 'text/plain'}) end it "stringifies keys and encodes values in the query" do stub_request(:post, encoded_url_with_params) subject.post("#{path}?#{params.to_json}", "", {'Content-Type' => 'text/plain'}) end it "includes custom headers" do stub_request(:post, url).with(headers: { 'X-Foo' => 'Bar' }) subject.post(path, "", {'X-Foo' => 'Bar', 'Content-Type' => 'text/plain'}) end it "returns the response" do stub_request(:post, url) response = subject.post(path, "", {'Content-Type' => 'text/plain'}) expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "sets content-type for the body" do stub_request(:post, url).with(headers: {"Content-Type" => "text/plain"}) subject.post(path, "hello", {'Content-Type' => 'text/plain'}) end it 'sends an empty body' do stub_request(:post, url).with(body: '') subject.post(path, nil) end it 'defaults content-type to application/x-www-form-urlencoded' do stub_request(:post, url).with(headers: {'Content-Type' => 'application/x-www-form-urlencoded'}) subject.post(path, "") end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:post, url_with_query) response = subject.post(url_with_query, '') expect(response).to be_an_instance_of(Net::HTTPOK) end end context "for DELETE requests" do it "includes default HTTP headers" do stub_request(:delete, url).with(headers: {'User-Agent' => /./}) subject.delete(path) end it "merges custom headers with default ones" do stub_request(:delete, url).with(headers: { 'X-Foo' => 'Bar', 'User-Agent' => /./ }) subject.delete(path, {'X-Foo' => 'Bar'}) end it "stringifies keys and encodes values in the query" do stub_request(:delete, encoded_url_with_params) subject.delete("#{path}?#{params.to_json}") end it "returns the response" do stub_request(:delete, url) response = subject.delete(path) expect(response).to be_an_instance_of(Net::HTTPOK) expect(response.code).to eq("200") end it "returns the entire response body" do stub_request(:delete, url).to_return(body: "abc") expect(subject.delete(path).body).to eq("abc") end it "accepts a URL string as the path" do url_with_query = "#{url}?foo=bar" stub_request(:delete, url_with_query) response = subject.delete(url_with_query) expect(response).to be_an_instance_of(Net::HTTPOK) end end context "when response is a redirect" do subject { klass } def create_connection(options = {}) options[:use_ssl] = false options[:verifier] = verifier subject.new(host, port, options) end def redirect_to(url) { status: 302, headers: { 'Location' => url } } end it "should follow the redirect to the final resource location" do stub_request(:get, "http://me.example.com:8140/foo").to_return(redirect_to("http://me.example.com:8140/bar")) stub_request(:get, "http://me.example.com:8140/bar").to_return(status: 200) create_connection.get('/foo') end def expects_limit_exceeded(conn) expect { conn.get('/') }.to raise_error(Puppet::Network::HTTP::RedirectionLimitExceededException) end it "should not follow any redirects when the limit is 0" do stub_request(:get, "http://me.example.com:8140/").to_return(redirect_to("http://me.example.com:8140/foo")) conn = create_connection(:redirect_limit => 0) expects_limit_exceeded(conn) end it "should follow the redirect once" do stub_request(:get, "http://me.example.com:8140/").to_return(redirect_to("http://me.example.com:8140/foo")) stub_request(:get, "http://me.example.com:8140/foo").to_return(redirect_to("http://me.example.com:8140/bar")) conn = create_connection(:redirect_limit => 1) expects_limit_exceeded(conn) end it "should raise an exception when the redirect limit is exceeded" do stub_request(:get, "http://me.example.com:8140/").to_return(redirect_to("http://me.example.com:8140/foo")) stub_request(:get, "http://me.example.com:8140/foo").to_return(redirect_to("http://me.example.com:8140/bar")) stub_request(:get, "http://me.example.com:8140/bar").to_return(redirect_to("http://me.example.com:8140/baz")) stub_request(:get, "http://me.example.com:8140/baz").to_return(redirect_to("http://me.example.com:8140/qux")) conn = create_connection(:redirect_limit => 3) expects_limit_exceeded(conn) end it 'raises an exception when the location header is missing' do stub_request(:get, "http://me.example.com:8140/").to_return(status: 302) expect { create_connection.get('/') }.to raise_error(Puppet::HTTP::ProtocolError, /Location response header is missing/) end end context "when response indicates an overloaded server" do def retry_after(datetime) stub_request(:get, url) .to_return(status: [503, 'Service Unavailable'], headers: {'Retry-After' => datetime}).then .to_return(status: 200) end it "should return a 503 response if Retry-After is not set" do stub_request(:get, url).to_return(status: [503, 'Service Unavailable']) result = subject.get('/foo') expect(result.code).to eq("503") end it "should return a 503 response if Retry-After is not convertible to an Integer or RFC 2822 Date" do retry_after('foo') expect { subject.get('/foo') }.to raise_error(Puppet::HTTP::ProtocolError, /Failed to parse Retry-After header 'foo'/) end it "should close the connection before sleeping" do retry_after('42') http1 = Net::HTTP.new(host, port) http1.use_ssl = true allow(http1).to receive(:started?).and_return(true) http2 = Net::HTTP.new(host, port) http2.use_ssl = true allow(http1).to receive(:started?).and_return(true) # The "with_connection" method is required to yield started connections pool = Puppet.runtime[:http].pool allow(pool).to receive(:with_connection).and_yield(http1).and_yield(http2) expect(http1).to receive(:finish).ordered expect(::Kernel).to receive(:sleep).with(42).ordered subject.get('/foo') end it "should sleep and retry if Retry-After is an Integer" do retry_after('42') expect(::Kernel).to receive(:sleep).with(42) result = subject.get('/foo') expect(result.code).to eq("200") end it "should sleep and retry if Retry-After is an RFC 2822 Date" do retry_after('Wed, 13 Apr 2005 15:18:05 GMT') now = DateTime.new(2005, 4, 13, 8, 17, 5, '-07:00') allow(DateTime).to receive(:now).and_return(now) expect(::Kernel).to receive(:sleep).with(60) result = subject.get('/foo') expect(result.code).to eq("200") end it "should sleep for no more than the Puppet runinterval" do retry_after('60') Puppet[:runinterval] = 30 expect(::Kernel).to receive(:sleep).with(30) subject.get('/foo') end it "should sleep for 0 seconds if the RFC 2822 date has past" do retry_after('Wed, 13 Apr 2005 15:18:05 GMT') expect(::Kernel).to receive(:sleep).with(0) subject.get('/foo') end end context "basic auth" do let(:auth) { { :user => 'user', :password => 'password' } } let(:creds) { [ 'user', 'password'] } it "is allowed in get requests" do stub_request(:get, url).with(basic_auth: creds) subject.get('/foo', nil, :basic_auth => auth) end it "is allowed in post requests" do stub_request(:post, url).with(basic_auth: creds) subject.post('/foo', 'data', nil, :basic_auth => auth) end it "is allowed in head requests" do stub_request(:head, url).with(basic_auth: creds) subject.head('/foo', nil, :basic_auth => auth) end it "is allowed in delete requests" do stub_request(:delete, url).with(basic_auth: creds) subject.delete('/foo', nil, :basic_auth => auth) end it "is allowed in put requests" do stub_request(:put, url).with(basic_auth: creds) subject.put('/foo', 'data', nil, :basic_auth => auth) end end it "sets HTTP User-Agent header" do puppet_ua = "Puppet/#{Puppet.version} Ruby/#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} (#{RUBY_PLATFORM})" stub_request(:get, url).with(headers: { 'User-Agent' => puppet_ua }) subject.get('/foo') end describe 'connection request errors' do it "logs and raises generic http errors" do generic_error = Net::HTTPError.new('generic error', double("response")) stub_request(:get, url).to_raise(generic_error) expect(Puppet).to receive(:log_exception).with(anything, /^.*failed.*: generic error$/) expect { subject.get('/foo') }.to raise_error(generic_error) end it "logs and raises timeout errors" do timeout_error = Net::OpenTimeout.new stub_request(:get, url).to_raise(timeout_error) expect(Puppet).to receive(:log_exception).with(anything, /^.*timed out .*after .* seconds/) expect { subject.get('/foo') }.to raise_error(timeout_error) end it "logs and raises eof errors" do eof_error = EOFError stub_request(:get, url).to_raise(eof_error) expect(Puppet).to receive(:log_exception).with(anything, /^.*interrupted after .* seconds$/) expect { subject.get('/foo') }.to raise_error(eof_error) end end end describe Puppet::Network::HTTP::Connection do it_behaves_like "an HTTP connection", described_class end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/route_spec.rb
spec/unit/network/http/route_spec.rb
require 'spec_helper' require 'puppet/indirector_testing' require 'puppet/network/http' describe Puppet::Network::HTTP::Route do def request(method, path) Puppet::Network::HTTP::Request.from_hash({ :method => method, :path => path, :routing_path => path }) end def respond(text) lambda { |req, res| res.respond_with(200, "text/plain", text) } end let(:req) { request("GET", "/vtest/foo") } let(:res) { Puppet::Network::HTTP::MemoryResponse.new } describe "an HTTP Route" do it "can match a request" do route = Puppet::Network::HTTP::Route.path(%r{^/vtest}) expect(route.matches?(req)).to be_truthy end it "will raise a Method Not Allowed error when no handler for the request's method is given" do route = Puppet::Network::HTTP::Route.path(%r{^/vtest}).post(respond("ignored")) expect do route.process(req, res) end.to raise_error(Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError) end it "can match any HTTP method" do route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).any(respond("used")) expect(route.matches?(req)).to be_truthy route.process(req, res) expect(res.body).to eq("used") end it "processes DELETE requests" do route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).delete(respond("used")) route.process(request("DELETE", "/vtest/foo"), res) expect(res.body).to eq("used") end it "does something when it doesn't know the verb" do route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}) expect do route.process(request("UNKNOWN", "/vtest/foo"), res) end.to raise_error(Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError, /UNKNOWN/) end it "calls the method handlers in turn" do call_count = 0 handler = lambda { |request, response| call_count += 1 } route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).get(handler, handler) route.process(req, res) expect(call_count).to eq(2) end it "stops calling handlers if one of them raises an error" do ignored_called = false ignored = lambda { |req, res| ignored_called = true } raise_error = lambda { |req, res| raise Puppet::Network::HTTP::Error::HTTPNotAuthorizedError, "go away" } route = Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).get(raise_error, ignored) expect do route.process(req, res) end.to raise_error(Puppet::Network::HTTP::Error::HTTPNotAuthorizedError) expect(ignored_called).to be_falsey end it "chains to other routes after calling its handlers" do inner_route = Puppet::Network::HTTP::Route.path(%r{^/inner}).any(respond("inner")) unused_inner_route = Puppet::Network::HTTP::Route.path(%r{^/unused_inner}).any(respond("unused")) top_route = Puppet::Network::HTTP::Route.path(%r{^/vtest}).any(respond("top")).chain(unused_inner_route, inner_route) top_route.process(request("GET", "/vtest/inner"), res) expect(res.body).to eq("topinner") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/error_spec.rb
spec/unit/network/http/error_spec.rb
require 'spec_helper' require 'matchers/json' require 'puppet/network/http' describe Puppet::Network::HTTP::Error do include JSONMatchers describe Puppet::Network::HTTP::Error::HTTPError do it "should serialize to JSON that matches the error schema" do error = Puppet::Network::HTTP::Error::HTTPError.new("I don't like the looks of you", 400, :SHIFTY_USER) expect(error.to_json).to validate_against('api/schemas/error.json') end end describe Puppet::Network::HTTP::Error::HTTPServerError do it "should serialize to JSON that matches the error schema" do begin raise Exception, "a wild Exception appeared!" rescue Exception => e culpable = e end error = Puppet::Network::HTTP::Error::HTTPServerError.new(culpable) expect(error.to_json).to validate_against('api/schemas/error.json') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/handler_spec.rb
spec/unit/network/http/handler_spec.rb
require 'spec_helper' require 'puppet_spec/handler' require 'puppet/indirector_testing' require 'puppet/network/http' describe Puppet::Network::HTTP::Handler do before :each do Puppet::IndirectorTesting.indirection.terminus_class = :memory end let(:indirection) { Puppet::IndirectorTesting.indirection } def a_request(method = "HEAD", path = "/production/#{indirection.name}/unknown") { :accept_header => "application/json", :content_type_header => "application/json", :method => method, :path => path, :params => {}, :client_cert => nil, :headers => {}, :body => nil } end let(:handler) { PuppetSpec::Handler.new() } describe "the HTTP Handler" do def respond(text) lambda { |req, res| res.respond_with(200, "text/plain", text) } end it "hands the request to the first route that matches the request path" do handler = PuppetSpec::Handler.new( Puppet::Network::HTTP::Route.path(%r{^/foo}).get(respond("skipped")), Puppet::Network::HTTP::Route.path(%r{^/vtest}).get(respond("used")), Puppet::Network::HTTP::Route.path(%r{^/vtest/foo}).get(respond("ignored"))) req = a_request("GET", "/vtest/foo") res = {} handler.process(req, res) expect(res[:body]).to eq("used") end it "raises an error if multiple routes with the same path regex are registered" do expect do PuppetSpec::Handler.new( Puppet::Network::HTTP::Route.path(%r{^/foo}).get(respond("ignored")), Puppet::Network::HTTP::Route.path(%r{^/foo}).post(respond("also ignored")) ) end.to raise_error(ArgumentError) end it "raises an HTTP not found error if no routes match" do handler = PuppetSpec::Handler.new req = a_request("GET", "/vtest/foo") res = {} handler.process(req, res) res_body = JSON(res[:body]) expect(res[:content_type_header]).to eq("application/json; charset=utf-8") expect(res_body["issue_kind"]).to eq("HANDLER_NOT_FOUND") expect(res_body["message"]).to eq("Not Found: No route for GET /vtest/foo") expect(res[:status]).to eq(404) end it "returns a structured error response when the server encounters an internal error" do error = StandardError.new("the sky is falling!") original_stacktrace = ['a.rb', 'b.rb'] error.set_backtrace(original_stacktrace) handler = PuppetSpec::Handler.new( Puppet::Network::HTTP::Route.path(/.*/).get(lambda { |_, _| raise error})) # Stacktraces should be included in logs expect(Puppet).to receive(:err).with("Server Error: the sky is falling!\na.rb\nb.rb") req = a_request("GET", "/vtest/foo") res = {} handler.process(req, res) res_body = JSON(res[:body]) expect(res[:content_type_header]).to eq("application/json; charset=utf-8") expect(res_body["issue_kind"]).to eq(Puppet::Network::HTTP::Issues::RUNTIME_ERROR.to_s) expect(res_body["message"]).to eq("Server Error: the sky is falling!") expect(res[:status]).to eq(500) end end describe "when processing a request" do let(:response) do { :status => 200 } end it "should setup a profiler when the puppet-profiling header exists" do request = a_request request[:headers][Puppet::Network::HTTP::HEADER_ENABLE_PROFILING.downcase] = "true" p = PuppetSpec::HandlerProfiler.new expect(Puppet::Util::Profiler).to receive(:add_profiler).with(be_a(Puppet::Util::Profiler::WallClock)).and_return(p) expect(Puppet::Util::Profiler).to receive(:remove_profiler).with(p) handler.process(request, response) end it "should not setup profiler when the profile parameter is missing" do request = a_request request[:params] = { } expect(Puppet::Util::Profiler).not_to receive(:add_profiler) handler.process(request, response) end it "should still find the correct format if content type contains charset information" do request = Puppet::Network::HTTP::Request.new({ 'content-type' => "text/plain; charset=UTF-8" }, {}, 'GET', '/', nil) expect(request.formatter.name).to eq(:s) end # PUP-3272 # This used to be for YAML, and doing a to_yaml on an array. # The result with to_json is something different, the result is a string # Which seems correct. Looks like this was some kind of nesting option "yaml inside yaml" ? # Removing the test # it "should deserialize JSON parameters" do # params = {'my_param' => [1,2,3].to_json} # # decoded_params = handler.send(:decode_params, params) # # decoded_params.should == {:my_param => [1,2,3]} # end end describe "when resolving node" do it "should use a look-up from the ip address" do expect(Resolv).to receive(:getname).with("1.2.3.4").and_return("host.domain.com") handler.resolve_node(:ip => "1.2.3.4") end it "should return the look-up result" do allow(Resolv).to receive(:getname).with("1.2.3.4").and_return("host.domain.com") expect(handler.resolve_node(:ip => "1.2.3.4")).to eq("host.domain.com") end it "should return the ip address if resolving fails" do allow(Resolv).to receive(:getname).with("1.2.3.4").and_raise(RuntimeError, "no such host") expect(handler.resolve_node(:ip => "1.2.3.4")).to eq("1.2.3.4") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/api/indirected_routes_spec.rb
spec/unit/network/http/api/indirected_routes_spec.rb
require 'spec_helper' require 'puppet/network/http' require 'puppet/network/http/api/indirected_routes' require 'puppet/indirector_testing' require 'puppet_spec/network' RSpec::Matchers.define_negated_matcher :excluding, :include describe Puppet::Network::HTTP::API::IndirectedRoutes do include PuppetSpec::Network let(:indirection) { Puppet::IndirectorTesting.indirection } let(:handler) { Puppet::Network::HTTP::API::IndirectedRoutes.new } let(:response) { Puppet::Network::HTTP::MemoryResponse.new } before do Puppet::IndirectorTesting.indirection.terminus_class = :memory Puppet::IndirectorTesting.indirection.terminus.clear end describe "when converting a URI into a request" do let(:environment) { Puppet::Node::Environment.create(:env, []) } let(:env_loaders) { Puppet::Environments::Static.new(environment) } let(:params) { { :environment => "env" } } around do |example| Puppet.override(:environments => env_loaders) do example.run end end it "should get the environment from a query parameter" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[3][:environment].to_s).to eq("env") end it "should fail if there is no environment specified" do expect { handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", {}) }.to raise_error(bad_request_error) end it "should fail if the environment is not alphanumeric" do expect { handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", {:environment => "env ness"}) }.to raise_error(bad_request_error) end it "should fail if the indirection does not match the prefix" do expect { handler.uri2indirection("GET", "#{master_url_prefix}/certificate/foo", params) }.to raise_error(bad_request_error) end it "should fail if the indirection does not have the correct version" do expect { handler.uri2indirection("GET", "#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v1/node/bar", params) }.to raise_error(bad_request_error) end it "should not pass a bucket_path parameter through (See Bugs #13553, #13518, #13511)" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", { :environment => "env", :bucket_path => "/malicious/path" })[3]).not_to include({ :bucket_path => "/malicious/path" }) end it "should pass allowed parameters through" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", { :environment => "env", :allowed_param => "value" })[3]).to include({ :allowed_param => "value" }) end it "should return the environment as a Puppet::Node::Environment" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[3][:environment]).to be_a(Puppet::Node::Environment) end it "should use the first field of the URI as the indirection name" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[0].name).to eq(:node) end it "should fail if the indirection name is not alphanumeric" do expect { handler.uri2indirection("GET", "#{master_url_prefix}/foo ness/bar", params) }.to raise_error(bad_request_error) end it "should use the remainder of the URI as the indirection key" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[2]).to eq("bar") end it "should support the indirection key being a /-separated file path" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bee/baz/bomb", params)[2]).to eq("bee/baz/bomb") end it "should fail if no indirection key is specified" do expect { handler.uri2indirection("GET", "#{master_url_prefix}/node", params) }.to raise_error(bad_request_error) end it "should choose 'find' as the indirection method if the http method is a GET and the indirection name is singular" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/node/bar", params)[1]).to eq(:find) end it "should choose 'find' as the indirection method if the http method is a POST and the indirection name is singular" do expect(handler.uri2indirection("POST", "#{master_url_prefix}/node/bar", params)[1]).to eq(:find) end it "should choose 'head' as the indirection method if the http method is a HEAD and the indirection name is singular" do expect(handler.uri2indirection("HEAD", "#{master_url_prefix}/node/bar", params)[1]).to eq(:head) end it "should choose 'search' as the indirection method if the http method is a GET and the indirection name is plural" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/nodes/bar", params)[1]).to eq(:search) end it "should choose 'save' as the indirection method if the http method is a PUT and the indirection name is facts" do expect(handler.uri2indirection("PUT", "#{master_url_prefix}/facts/puppet.node.test", params)[0].name).to eq(:facts) end it "should change indirection name to 'node' if the http method is a GET and the indirection name is nodes" do expect(handler.uri2indirection("GET", "#{master_url_prefix}/nodes/bar", params)[0].name).to eq(:node) end it "should choose 'delete' as the indirection method if the http method is a DELETE and the indirection name is singular" do expect(handler.uri2indirection("DELETE", "#{master_url_prefix}/node/bar", params)[1]).to eq(:destroy) end it "should choose 'save' as the indirection method if the http method is a PUT and the indirection name is singular" do expect(handler.uri2indirection("PUT", "#{master_url_prefix}/node/bar", params)[1]).to eq(:save) end it "should fail if an indirection method cannot be picked" do expect { handler.uri2indirection("UPDATE", "#{master_url_prefix}/node/bar", params) }.to raise_error(method_not_allowed_error) end it "should not URI unescape the indirection key" do escaped = Puppet::Util.uri_encode("foo bar") _, _, key, _ = handler.uri2indirection("GET", "#{master_url_prefix}/node/#{escaped}", params) expect(key).to eq(escaped) end end describe "when processing a request" do it "should raise not_found_error if the indirection does not support remote requests" do request = a_request_that_heads(Puppet::IndirectorTesting.new("my data")) expect(indirection).to receive(:allow_remote_requests?).and_return(false) expect { handler.call(request, response) }.to raise_error(not_found_error) end it "should raise not_found_error if the environment does not exist" do Puppet.override(:environments => Puppet::Environments::Static.new()) do request = a_request_that_heads(Puppet::IndirectorTesting.new("my data")) expect { handler.call(request, response) }.to raise_error(not_found_error) end end end describe "when finding a model instance" do it "uses the first supported format for the response" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_finds(data, :accept_header => "unknown, application/json") handler.call(request, response) expect(response.body).to eq(data.render(:json)) expect(response.type).to eq(Puppet::Network::FormatHandler.format(:json)) end it "falls back to the next supported format", if: Puppet.features.pson? do Puppet[:allow_pson_serialization] = true data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_finds(data, :accept_header => "application/json, text/pson") allow(data).to receive(:to_json).and_raise(Puppet::Network::FormatHandler::FormatError, 'Could not render to Puppet::Network::Format[json]: source sequence is illegal/malformed utf-8') expect(Puppet).to receive(:warning).with(/Failed to serialize Puppet::IndirectorTesting for 'my data': Could not render to Puppet::Network::Format\[json\]/) handler.call(request, response) expect(response.body).to eq(data.render(:pson)) expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson)) end it "should pass the result through without rendering it if the result is a string" do data = Puppet::IndirectorTesting.new("my data") data_string = "my data string" request = a_request_that_finds(data, :accept_header => "application/json") expect(indirection).to receive(:find).and_return(data_string) handler.call(request, response) expect(response.body).to eq(data_string) expect(response.type).to eq(Puppet::Network::FormatHandler.format(:json)) end it "should raise not_found_error when no model instance can be found" do data = Puppet::IndirectorTesting.new("my data") request = a_request_that_finds(data, :accept_header => "unknown, application/json") expect { handler.call(request, response) }.to raise_error(not_found_error) end it "should raise FormatError if tries to fallback" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_finds(data, :accept_header => "unknown, text/pson") allow(Puppet.features).to receive(:pson?).and_return(true) allow(data).to receive(:to_pson).and_raise(Puppet::Network::FormatHandler::FormatError, 'Could not render to Puppet::Network::Format[pson]: source sequence is illegal/malformed utf-8') expect { handler.call(request, response) }.to raise_error(Puppet::Network::FormatHandler::FormatError, %r{Failed to serialize Puppet::IndirectorTesting for 'my data': Could not render to Puppet::Network::Format\[pson\]}) end end describe "when searching for model instances" do it "uses the first supported format for the response" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_searches(Puppet::IndirectorTesting.new("my"), :accept_header => "unknown, application/json") handler.call(request, response) expect(response.type).to eq(Puppet::Network::FormatHandler.format(:json)) expect(response.body).to eq(Puppet::IndirectorTesting.render_multiple(:json, [data])) end it "falls back to the next supported format", if: Puppet.features.pson? do Puppet[:allow_pson_serialization] = true data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_searches(Puppet::IndirectorTesting.new("my"), :accept_header => "application/json, text/pson") allow(data).to receive(:to_json).and_raise(Puppet::Network::FormatHandler::FormatError, 'Could not render to Puppet::Network::Format[json]: source sequence is illegal/malformed utf-8') expect(Puppet).to receive(:warning).with(/Failed to serialize Puppet::IndirectorTesting for 'my': Could not render_multiple to Puppet::Network::Format\[json\]/) handler.call(request, response) expect(response.type).to eq(Puppet::Network::FormatHandler.format(:pson)) expect(response.body).to eq(Puppet::IndirectorTesting.render_multiple(:pson, [data])) end it "raises 406 not acceptable if no formats are accceptable" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_searches(Puppet::IndirectorTesting.new("my"), :accept_header => "unknown") expect { handler.call(request, response) }.to raise_error(Puppet::Network::HTTP::Error::HTTPNotAcceptableError, %r{No supported formats are acceptable \(Accept: unknown\)}) end it "raises FormatError if tries to fallback" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_searches(Puppet::IndirectorTesting.new("my"), :accept_header => "unknown, text/pson") allow(Puppet.features).to receive(:pson?).and_return(true) allow(data).to receive(:to_pson).and_raise(Puppet::Network::FormatHandler::FormatError, 'Could not render to Puppet::Network::Format[pson]: source sequence is illegal/malformed utf-8') expect { handler.call(request, response) }.to raise_error(Puppet::Network::FormatHandler::FormatError, %r{Failed to serialize Puppet::IndirectorTesting for 'my': Could not render_multiple to Puppet::Network::Format\[pson\]}) end it "should return [] when searching returns an empty array" do request = a_request_that_searches(Puppet::IndirectorTesting.new("nothing"), :accept_header => "unknown, application/json") handler.call(request, response) expect(response.body).to eq("[]") expect(response.type).to eq(Puppet::Network::FormatHandler.format(:json)) end it "should raise not_found_error when searching returns nil" do request = a_request_that_searches(Puppet::IndirectorTesting.new("nothing"), :accept_header => "unknown, application/json") expect(indirection).to receive(:search).and_return(nil) expect { handler.call(request, response) }.to raise_error(not_found_error) end end describe "when destroying a model instance" do it "destroys the data indicated in the request" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_destroys(data) handler.call(request, response) expect(Puppet::IndirectorTesting.indirection.find("my data")).to be_nil end it "uses the first supported format for the response" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_destroys(data, :accept_header => "unknown, application/json") handler.call(request, response) expect(response.body).to eq(data.render(:json)) expect(response.type).to eq(Puppet::Network::FormatHandler.format(:json)) end it "raises an error and does not destroy when no accepted formats are known" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_destroys(data, :accept_header => "unknown, also/unknown") expect { handler.call(request, response) }.to raise_error(not_acceptable_error) expect(Puppet::IndirectorTesting.indirection.find("my data")).not_to be_nil end end describe "when saving a model instance" do it "allows an empty body when the format supports it" do class Puppet::IndirectorTesting::Nonvalidatingmemory < Puppet::IndirectorTesting::Memory def validate_key(_) # nothing end end indirection.terminus_class = :nonvalidatingmemory data = Puppet::IndirectorTesting.new("test") request = a_request_that_submits(data, :content_type_header => "application/octet-stream", :body => '') handler.call(request, response) saved = Puppet::IndirectorTesting.indirection.find("test") expect(saved.name).to eq('') end it "saves the data sent in the request" do data = Puppet::IndirectorTesting.new("my data") request = a_request_that_submits(data) handler.call(request, response) saved = Puppet::IndirectorTesting.indirection.find("my data") expect(saved.name).to eq(data.name) end it "responds with bad request when failing to parse the body" do data = Puppet::IndirectorTesting.new("my data") request = a_request_that_submits(data, :content_type_header => 'application/json', :body => "this is invalid json content") expect { handler.call(request, response) }.to raise_error(bad_request_error, /The request body is invalid: Could not intern from json/) end it "responds with unsupported media type error when submitted content is known, but not supported by the model" do data = Puppet::IndirectorTesting.new("my data") request = a_request_that_submits(data, :content_type_header => 's') expect(data).to_not be_support_format('s') expect { handler.call(request, response) }.to raise_error(unsupported_media_type_error, /Client sent a mime-type \(s\) that doesn't correspond to a format we support/) end it "uses the first supported format for the response" do data = Puppet::IndirectorTesting.new("my data") request = a_request_that_submits(data, :accept_header => "unknown, application/json") handler.call(request, response) expect(response.body).to eq(data.render(:json)) expect(response.type).to eq(Puppet::Network::FormatHandler.format(:json)) end it "raises an error and does not save when no accepted formats are known" do data = Puppet::IndirectorTesting.new("my data") request = a_request_that_submits(data, :accept_header => "unknown, also/unknown") expect { handler.call(request, response) }.to raise_error(not_acceptable_error) expect(Puppet::IndirectorTesting.indirection.find("my data")).to be_nil end end describe "when performing head operation" do it "should not generate a response when a model head call succeeds" do data = Puppet::IndirectorTesting.new("my data") indirection.save(data, "my data") request = a_request_that_heads(data) handler.call(request, response) expect(response.code).to eq(nil) end it "should raise not_found_error when the model head call returns false" do data = Puppet::IndirectorTesting.new("my data") request = a_request_that_heads(data) expect { handler.call(request, response) }.to raise_error(not_found_error) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/api/master_spec.rb
spec/unit/network/http/api/master_spec.rb
# Tests the backwards compatibility of our master -> server changes # in the HTTP API # This may be removed in Puppet 8 require 'spec_helper' require 'puppet/network/http' require 'puppet_spec/network' describe Puppet::Network::HTTP::API::Master::V3 do include PuppetSpec::Network let(:response) { Puppet::Network::HTTP::MemoryResponse.new } let(:server_url_prefix) { "#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3" } let(:server_routes) { Puppet::Network::HTTP::Route. path(Regexp.new("#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/")). any. chain(Puppet::Network::HTTP::API::Master::V3.routes) } # simulate puppetserver registering its authconfigloader class around :each do |example| Puppet::Network::Authorization.authconfigloader_class = Object begin example.run ensure Puppet::Network::Authorization.authconfigloader_class = nil end end it "mounts the environments endpoint" do request = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_url_prefix}/environments") server_routes.process(request, response) expect(response.code).to eq(200) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/api/server/v3_spec.rb
spec/unit/network/http/api/server/v3_spec.rb
require 'spec_helper' require 'puppet/network/http' require 'puppet_spec/network' describe Puppet::Network::HTTP::API::Server::V3 do include PuppetSpec::Network let(:response) { Puppet::Network::HTTP::MemoryResponse.new } let(:server_url_prefix) { "#{Puppet::Network::HTTP::SERVER_URL_PREFIX}/v3" } let(:server_routes) { Puppet::Network::HTTP::Route. path(Regexp.new("#{Puppet::Network::HTTP::SERVER_URL_PREFIX}/")). any. chain(Puppet::Network::HTTP::API::Server::V3.routes) } # simulate puppetserver registering its authconfigloader class around :each do |example| Puppet::Network::Authorization.authconfigloader_class = Object begin example.run ensure Puppet::Network::Authorization.authconfigloader_class = nil end end it "mounts the environments endpoint" do request = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_url_prefix}/environments") server_routes.process(request, response) expect(response.code).to eq(200) end it "matches only complete routes" do request = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_url_prefix}/foo/environments") expect { server_routes.process(request, response) }.to raise_error(Puppet::Network::HTTP::Error::HTTPNotFoundError) request = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_url_prefix}/foo/environment/production") expect { server_routes.process(request, response) }.to raise_error(Puppet::Network::HTTP::Error::HTTPNotFoundError) end it "mounts indirected routes" do request = Puppet::Network::HTTP::Request. from_hash(:path => "#{server_url_prefix}/node/foo", :params => {:environment => "production"}, :headers => {"accept" => "application/json"}) server_routes.process(request, response) expect(response.code).to eq(200) end it "responds to unknown paths by raising not_found_error" do request = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_url_prefix}/unknown") expect { server_routes.process(request, response) }.to raise_error(not_found_error) end it "checks authorization for indirected routes" do Puppet::Network::Authorization.authconfigloader_class = nil request = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_url_prefix}/catalog/foo") expect { server_routes.process(request, response) }.to raise_error(Puppet::Network::HTTP::Error::HTTPNotAuthorizedError, %r{Not Authorized: Forbidden request: /puppet/v3/catalog/foo \(method GET\)}) end it "checks authorization for environments" do Puppet::Network::Authorization.authconfigloader_class = nil request = Puppet::Network::HTTP::Request.from_hash(:path => "#{server_url_prefix}/environments") expect { server_routes.process(request, response) }.to raise_error(Puppet::Network::HTTP::Error::HTTPNotAuthorizedError, %r{Not Authorized: Forbidden request: /puppet/v3/environments \(method GET\)}) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/network/http/api/server/v3/environments_spec.rb
spec/unit/network/http/api/server/v3/environments_spec.rb
require 'spec_helper' require 'puppet/node/environment' require 'puppet/network/http' require 'matchers/json' describe Puppet::Network::HTTP::API::Server::V3::Environments do include JSONMatchers let(:environment) { Puppet::Node::Environment.create(:production, ["/first", "/second"], '/manifests') } let(:loader) { Puppet::Environments::Static.new(environment) } let(:handler) { Puppet::Network::HTTP::API::Server::V3::Environments.new(loader) } let(:request) { Puppet::Network::HTTP::Request.from_hash(:headers => { 'accept' => 'application/json' }) } let(:response) { Puppet::Network::HTTP::MemoryResponse.new } it "responds with all of the available environments" do handler.call(request, response) expect(response.code).to eq(200) expect(response.type).to eq("application/json") expect(JSON.parse(response.body)).to eq({ "search_paths" => loader.search_paths, "environments" => { "production" => { "settings" => { "modulepath" => [File.expand_path("/first"), File.expand_path("/second")], "manifest" => File.expand_path("/manifests"), "environment_timeout" => 0, "config_version" => "" } } } }) end it "the response conforms to the environments schema for unlimited timeout" do Puppet[:environment_timeout] = 'unlimited' handler.call(request, response) expect(response.body).to validate_against('api/schemas/environments.json') end it "the response conforms to the environments schema for integer timeout" do Puppet[:environment_timeout] = 1 handler.call(request, response) expect(response.body).to validate_against('api/schemas/environments.json') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/fileset_spec.rb
spec/unit/file_serving/fileset_spec.rb
require 'spec_helper' require 'puppet/file_serving/fileset' describe Puppet::FileServing::Fileset do include PuppetSpec::Files let(:somefile) { make_absolute("/some/file") } context "when initializing" do it "requires a path" do expect { Puppet::FileServing::Fileset.new }.to raise_error(ArgumentError) end it "fails if its path is not fully qualified" do expect { Puppet::FileServing::Fileset.new("some/file") }.to raise_error(ArgumentError, "Fileset paths must be fully qualified: some/file") end it "removes a trailing file path separator" do path_with_separator = "#{somefile}#{File::SEPARATOR}" expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) fileset = Puppet::FileServing::Fileset.new(path_with_separator) expect(fileset.path).to eq(somefile) end it "can be created from the root directory" do path = File.expand_path(File::SEPARATOR) expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(double('stat')) fileset = Puppet::FileServing::Fileset.new(path) expect(fileset.path).to eq(path) end it "fails if its path does not exist" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_raise(Errno::ENOENT) expect { Puppet::FileServing::Fileset.new(somefile) }.to raise_error(ArgumentError, "Fileset paths must exist") end it "accepts a 'recurse' option" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) set = Puppet::FileServing::Fileset.new(somefile, :recurse => true) expect(set.recurse).to be_truthy end it "accepts a 'recurselimit' option" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) set = Puppet::FileServing::Fileset.new(somefile, :recurselimit => 3) expect(set.recurselimit).to eq(3) end it "accepts a 'max_files' option" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) set = Puppet::FileServing::Fileset.new(somefile, :recurselimit => 3, :max_files => 100) expect(set.recurselimit).to eq(3) expect(set.max_files).to eq(100) end it "accepts an 'ignore' option" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) set = Puppet::FileServing::Fileset.new(somefile, :ignore => ".svn") expect(set.ignore).to eq([".svn"]) end it "accepts a 'links' option" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) set = Puppet::FileServing::Fileset.new(somefile, :links => :manage) expect(set.links).to eq(:manage) end it "accepts a 'checksum_type' option" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) set = Puppet::FileServing::Fileset.new(somefile, :checksum_type => :test) expect(set.checksum_type).to eq(:test) end it "fails if 'links' is set to anything other than :manage or :follow" do expect { Puppet::FileServing::Fileset.new(somefile, :links => :whatever) }.to raise_error(ArgumentError, "Invalid :links value 'whatever'") end it "defaults to 'false' for recurse" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) expect(Puppet::FileServing::Fileset.new(somefile).recurse).to eq(false) end it "defaults to :infinite for recurselimit" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) expect(Puppet::FileServing::Fileset.new(somefile).recurselimit).to eq(:infinite) end it "defaults to an empty ignore list" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) expect(Puppet::FileServing::Fileset.new(somefile).ignore).to eq([]) end it "defaults to :manage for links" do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) expect(Puppet::FileServing::Fileset.new(somefile).links).to eq(:manage) end describe "using an indirector request" do let(:values) { { :links => :manage, :ignore => %w{a b}, :recurse => true, :recurselimit => 1234 } } before :each do expect(Puppet::FileSystem).to receive(:lstat).with(somefile).and_return(double('stat')) end [:recurse, :recurselimit, :ignore, :links].each do |option| it "passes the #{option} option on to the fileset if present" do request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil, {option => values[option]}) expect(Puppet::FileServing::Fileset.new(somefile, request).send(option)).to eq(values[option]) end end it "converts the integer as a string to their integer counterpart when setting options" do request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil, {:recurselimit => "1234"}) expect(Puppet::FileServing::Fileset.new(somefile, request).recurselimit).to eq(1234) end it "converts the string 'true' to the boolean true when setting options" do request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil, {:recurse => "true"}) expect(Puppet::FileServing::Fileset.new(somefile, request).recurse).to eq(true) end it "converts the string 'false' to the boolean false when setting options" do request = Puppet::Indirector::Request.new(:file_serving, :find, "foo", nil, {:recurse => "false"}) expect(Puppet::FileServing::Fileset.new(somefile, request).recurse).to eq(false) end end end context "when recursing" do before do @path = make_absolute("/my/path") allow(Puppet::FileSystem).to receive(:lstat).with(@path).and_return(double('stat', :directory? => true)) @fileset = Puppet::FileServing::Fileset.new(@path) @dirstat = double('dirstat', :directory? => true) @filestat = double('filestat', :directory? => false) end def mock_dir_structure(path, stat_method = :lstat) allow(Puppet::FileSystem).to receive(stat_method).with(path).and_return(@dirstat) # Keep track of the files we're stubbing. @files = %w{.} top_names = %w{one two .svn CVS} sub_names = %w{file1 file2 .svn CVS 0 false} allow(Dir).to receive(:entries).with(path, {encoding: Encoding::UTF_8}).and_return(top_names) top_names.each do |subdir| @files << subdir # relative path subpath = File.join(path, subdir) allow(Puppet::FileSystem).to receive(stat_method).with(subpath).and_return(@dirstat) allow(Dir).to receive(:entries).with(subpath, {encoding: Encoding::UTF_8}).and_return(sub_names) sub_names.each do |file| @files << File.join(subdir, file) # relative path subfile_path = File.join(subpath, file) allow(Puppet::FileSystem).to receive(stat_method).with(subfile_path).and_return(@filestat) end end end def mock_big_dir_structure(path, stat_method = :lstat) allow(Puppet::FileSystem).to receive(stat_method).with(path).and_return(@dirstat) # Keep track of the files we're stubbing. @files = %w{.} top_names = (1..10).map {|i| "dir_#{i}" } sub_names = (1..100).map {|i| "file__#{i}" } allow(Dir).to receive(:entries).with(path, {encoding: Encoding::UTF_8}).and_return(top_names) top_names.each do |subdir| @files << subdir # relative path subpath = File.join(path, subdir) allow(Puppet::FileSystem).to receive(stat_method).with(subpath).and_return(@dirstat) allow(Dir).to receive(:entries).with(subpath, {encoding: Encoding::UTF_8}).and_return(sub_names) sub_names.each do |file| @files << File.join(subdir, file) # relative path subfile_path = File.join(subpath, file) allow(Puppet::FileSystem).to receive(stat_method).with(subfile_path).and_return(@filestat) end end end def setup_mocks_for_dir(mock_dir, base_path) path = File.join(base_path, mock_dir.name) allow(Puppet::FileSystem).to receive(:lstat).with(path).and_return(MockStat.new(path, true)) allow(Dir).to receive(:entries).with(path, {encoding: Encoding::UTF_8}).and_return(['.', '..'] + mock_dir.entries.map(&:name)) mock_dir.entries.each do |entry| setup_mocks_for_entry(entry, path) end end def setup_mocks_for_file(mock_file, base_path) path = File.join(base_path, mock_file.name) allow(Puppet::FileSystem).to receive(:lstat).with(path).and_return(MockStat.new(path, false)) end def setup_mocks_for_entry(entry, base_path) case entry when MockDirectory setup_mocks_for_dir(entry, base_path) when MockFile setup_mocks_for_file(entry, base_path) end end MockStat = Struct.new(:path, :directory) do # struct doesn't support thing ending in ? def directory? directory end end MockDirectory = Struct.new(:name, :entries) MockFile = Struct.new(:name) it "doesn't ignore pending directories when the last entry at the top level is a file" do structure = MockDirectory.new('path', [MockDirectory.new('dir1', [MockDirectory.new('a', [MockFile.new('f')])]), MockFile.new('file')]) setup_mocks_for_dir(structure, make_absolute('/your')) fileset = Puppet::FileServing::Fileset.new(make_absolute('/your/path')) fileset.recurse = true fileset.links = :manage expect(fileset.files).to eq([".", "dir1", "file", "dir1/a", "dir1/a/f"]) end it "recurses through the whole file tree if :recurse is set to 'true'" do mock_dir_structure(@path) @fileset.recurse = true expect(@fileset.files.sort).to eq(@files.sort) end it "does not recurse if :recurse is set to 'false'" do mock_dir_structure(@path) @fileset.recurse = false expect(@fileset.files).to eq(%w{.}) end it "recurses to the level set by :recurselimit" do mock_dir_structure(@path) @fileset.recurse = true @fileset.recurselimit = 1 expect(@fileset.files).to eq(%w{. one two .svn CVS}) end it "ignores the '.' and '..' directories in subdirectories" do mock_dir_structure(@path) @fileset.recurse = true expect(@fileset.files.sort).to eq(@files.sort) end it "does not fail if the :ignore value provided is nil" do mock_dir_structure(@path) @fileset.recurse = true @fileset.ignore = nil expect { @fileset.files }.to_not raise_error end it "ignores files that match a single pattern in the ignore list" do mock_dir_structure(@path) @fileset.recurse = true @fileset.ignore = ".svn" expect(@fileset.files.find { |file| file.include?(".svn") }).to be_nil end it "ignores files that match any of multiple patterns in the ignore list" do mock_dir_structure(@path) @fileset.recurse = true @fileset.ignore = %w{.svn CVS} expect(@fileset.files.find { |file| file.include?(".svn") or file.include?("CVS") }).to be_nil end it "ignores files that match a pattern given as a number" do mock_dir_structure(@path) @fileset.recurse = true @fileset.ignore = [0] expect(@fileset.files.find { |file| file.include?("0") }).to be_nil end it "raises exception if number of files is greater than :max_files" do mock_dir_structure(@path) @fileset.recurse = true @fileset.max_files = 22 expect { @fileset.files }.to raise_error(Puppet::Error, "The directory '#{@path}' contains 28 entries, which exceeds the limit of 22 specified by the max_files parameter for this resource. The limit may be increased, but be aware that large number of file resources can result in excessive resource consumption and degraded performance. Consider using an alternate method to manage large directory trees") end it "logs a warning if number of files is greater than soft max_files limit of 1000" do mock_big_dir_structure(@path) @fileset.recurse = true expect(Puppet).to receive(:warning).with("The directory '#{@path}' contains 1010 entries, which exceeds the default soft limit 1000 and may cause excessive resource consumption and degraded performance. To remove this warning set a value for `max_files` parameter or consider using an alternate method to manage large directory trees") expect { @fileset.files }.to_not raise_error end it "does not emit a warning if max_files is -1" do mock_big_dir_structure(@path) @fileset.recurse = true @fileset.max_files = -1 expect(Puppet).to receive(:warning).never @fileset.files end it "does not emit a warning if max_files is `-1`(string)" do mock_big_dir_structure(@path) @fileset.recurse = true @fileset.max_files = '-1' expect(Puppet).to receive(:warning).never @fileset.files end it "ignores files that match a pattern given as a boolean" do mock_dir_structure(@path) @fileset.recurse = true @fileset.ignore = [false] expect(@fileset.files.find { |file| file.include?("false") }).to be_nil end it "uses Puppet::FileSystem#stat if :links is set to :follow" do mock_dir_structure(@path, :stat) @fileset.recurse = true @fileset.links = :follow expect(@fileset.files.sort).to eq(@files.sort) end it "uses Puppet::FileSystem#lstat if :links is set to :manage" do mock_dir_structure(@path, :lstat) @fileset.recurse = true @fileset.links = :manage expect(@fileset.files.sort).to eq(@files.sort) end it "works when paths have regexp significant characters" do @path = make_absolute("/my/path/rV1x2DafFr0R6tGG+1bbk++++TM") stat = double('dir_stat', :directory? => true) expect(Puppet::FileSystem).to receive(:lstat).with(@path).and_return(double(@path, :stat => stat, :lstat => stat)) @fileset = Puppet::FileServing::Fileset.new(@path) mock_dir_structure(@path) @fileset.recurse = true expect(@fileset.files.sort).to eq(@files.sort) end end it "manages the links to missing files" do path = make_absolute("/my/path") stat = double('stat', :directory? => true) expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(stat) expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stat) link_path = File.join(path, "mylink") expect(Puppet::FileSystem).to receive(:stat).with(link_path).and_raise(Errno::ENOENT) allow(Dir).to receive(:entries).with(path, {encoding: Encoding::UTF_8}).and_return(["mylink"]) fileset = Puppet::FileServing::Fileset.new(path) fileset.links = :follow fileset.recurse = true expect(fileset.files.sort).to eq(%w{. mylink}.sort) end context "when merging other filesets" do before do @paths = [make_absolute("/first/path"), make_absolute("/second/path"), make_absolute("/third/path")] allow(Puppet::FileSystem).to receive(:lstat).and_return(double('stat', :directory? => false)) @filesets = @paths.collect do |path| allow(Puppet::FileSystem).to receive(:lstat).with(path).and_return(double('stat', :directory? => true)) Puppet::FileServing::Fileset.new(path, {:recurse => true}) end allow(Dir).to receive(:entries).and_return([]) end it "returns a hash of all files in each fileset with the value being the base path" do expect(Dir).to receive(:entries).with(make_absolute("/first/path"), {encoding: Encoding::UTF_8}).and_return(%w{one uno}) expect(Dir).to receive(:entries).with(make_absolute("/second/path"), {encoding: Encoding::UTF_8}).and_return(%w{two dos}) expect(Dir).to receive(:entries).with(make_absolute("/third/path"), {encoding: Encoding::UTF_8}).and_return(%w{three tres}) expect(Puppet::FileServing::Fileset.merge(*@filesets)).to eq({ "." => make_absolute("/first/path"), "one" => make_absolute("/first/path"), "uno" => make_absolute("/first/path"), "two" => make_absolute("/second/path"), "dos" => make_absolute("/second/path"), "three" => make_absolute("/third/path"), "tres" => make_absolute("/third/path"), }) end it "includes the base directory from the first fileset" do expect(Dir).to receive(:entries).with(make_absolute("/first/path"), {encoding: Encoding::UTF_8}).and_return(%w{one}) expect(Dir).to receive(:entries).with(make_absolute("/second/path"), {encoding: Encoding::UTF_8}).and_return(%w{two}) expect(Puppet::FileServing::Fileset.merge(*@filesets)["."]).to eq(make_absolute("/first/path")) end it "uses the base path of the first found file when relative file paths conflict" do expect(Dir).to receive(:entries).with(make_absolute("/first/path"), {encoding: Encoding::UTF_8}).and_return(%w{one}) expect(Dir).to receive(:entries).with(make_absolute("/second/path"), {encoding: Encoding::UTF_8}).and_return(%w{one}) expect(Puppet::FileServing::Fileset.merge(*@filesets)["one"]).to eq(make_absolute("/first/path")) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/metadata_spec.rb
spec/unit/file_serving/metadata_spec.rb
require 'spec_helper' require 'puppet/file_serving/metadata' require 'matchers/json' describe Puppet::FileServing::Metadata do let(:foobar) { File.expand_path('/foo/bar') } it "should be a subclass of Base" do expect(Puppet::FileServing::Metadata.superclass).to equal(Puppet::FileServing::Base) end it "should indirect file_metadata" do expect(Puppet::FileServing::Metadata.indirection.name).to eq(:file_metadata) end it "should have a method that triggers attribute collection" do expect(Puppet::FileServing::Metadata.new(foobar)).to respond_to(:collect) end it "should default to json" do expect(Puppet::FileServing::Metadata.default_format).to eq(:json) end it "should support json and yaml" do # msgpack and pson are optional, so using include instead of eq expect(Puppet::FileServing::Metadata.supported_formats).to include(:json, :yaml) end it "should support deserialization" do expect(Puppet::FileServing::Metadata).to respond_to(:from_data_hash) end describe "when serializing" do let(:metadata) { Puppet::FileServing::Metadata.new(foobar) } it "the data should include the path, relative_path, links, owner, group, mode, checksum, type, and destination" do expect(metadata.to_data_hash.keys.sort).to eq(%w{ path relative_path links owner group mode checksum type destination }.sort) end it "should pass the path in the hash verbatim" do expect(metadata.to_data_hash['path']).to eq(metadata.path) end it "should pass the relative_path in the hash verbatim" do expect(metadata.to_data_hash['relative_path']).to eq(metadata.relative_path) end it "should pass the links in the hash as a string" do expect(metadata.to_data_hash['links']).to eq(metadata.links.to_s) end it "should pass the path owner in the hash verbatim" do expect(metadata.to_data_hash['owner']).to eq(metadata.owner) end it "should pass the group in the hash verbatim" do expect(metadata.to_data_hash['group']).to eq(metadata.group) end it "should pass the mode in the hash verbatim" do expect(metadata.to_data_hash['mode']).to eq(metadata.mode) end it "should pass the ftype in the hash verbatim as the 'type'" do expect(metadata.to_data_hash['type']).to eq(metadata.ftype) end it "should pass the destination verbatim" do expect(metadata.to_data_hash['destination']).to eq(metadata.destination) end it "should pass the checksum in the hash as a nested hash" do expect(metadata.to_data_hash['checksum']).to be_is_a(Hash) end it "should pass the checksum_type in the hash verbatim as the checksum's type" do expect(metadata.to_data_hash['checksum']['type']).to eq(metadata.checksum_type) end it "should pass the checksum in the hash verbatim as the checksum's value" do expect(metadata.to_data_hash['checksum']['value']).to eq(metadata.checksum) end describe "when a source and content_uri are set" do before do metadata.source = '/foo' metadata.content_uri = 'puppet:///foo' end it "the data should include the path, relative_path, links, owner, group, mode, checksum, type, destination, source, and content_uri" do expect(metadata.to_data_hash.keys.sort).to eq(%w{ path relative_path links owner group mode checksum type destination source content_uri }.sort) end it "should pass the source in the hash verbatim" do expect(metadata.to_data_hash['source']).to eq(metadata.source) end it "should pass the content_uri in the hash verbatim" do expect(metadata.to_data_hash['content_uri']).to eq(metadata.content_uri) end end describe "when assigning a content_uri" do it "should fail if uri is invalid" do expect { metadata.content_uri = '://' }.to raise_error ArgumentError, /Could not understand URI :\/\// end it "should accept characters that require percent-encoding" do uri = 'puppet:///modules/foo/files/ %:?#[]@!$&\'()*+,;=' metadata.content_uri = uri expect(metadata.content_uri).to eq(uri) end it "should accept UTF-8 characters" do # 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 <U+070E> - 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ۿᚠ<U+070E> uri = "puppet:///modules/foo/files/ #{mixed_utf8}" metadata.content_uri = uri expect(metadata.content_uri).to eq(uri) expect(metadata.content_uri.encoding).to eq(Encoding::UTF_8) end it "should always set it as UTF-8" do uri = "puppet:///modules/foo/files/".encode(Encoding::ASCII) metadata.content_uri = uri expect(metadata.content_uri).to eq(uri) expect(metadata.content_uri.encoding).to eq(Encoding::UTF_8) end it "should fail if uri is opaque" do expect { metadata.content_uri = 'scheme:www.example.com' }.to raise_error ArgumentError, "Cannot use opaque URLs 'scheme:www.example.com'" end it "should fail if uri is not a puppet scheme" do expect { metadata.content_uri = 'http://www.example.com' }.to raise_error ArgumentError, "Must use URLs of type puppet as content URI" end end end end describe Puppet::FileServing::Metadata, :uses_checksums => true do include JSONMatchers include PuppetSpec::Files shared_examples_for "metadata collector" do let(:metadata) do data = described_class.new(path) data.collect data end describe "when collecting attributes" do describe "when managing files" do let(:path) { tmpfile('file_serving_metadata') } let(:time) { Time.now } before :each do FileUtils.touch(path) end describe "checksumming" do with_digest_algorithms do before :each do File.open(path, "wb") {|f| f.print(plaintext)} end it "should default to a checksum of the proper type with the file's current checksum" do expect(metadata.checksum).to eq("{#{digest_algorithm}}#{checksum}") end it "should give a #{Puppet[:digest_algorithm]} when checksum_type is set" do Puppet[:digest_algorithm] = nil metadata.checksum_type = digest_algorithm metadata.collect expect(metadata.checksum).to eq("{#{digest_algorithm}}#{checksum}") end end it "should give a mtime checksum when checksum_type is set" do metadata.checksum_type = "mtime" expect(metadata).to receive(:mtime_file).and_return(time) metadata.collect expect(metadata.checksum).to eq("{mtime}#{time}") end it "should give a ctime checksum when checksum_type is set" do metadata.checksum_type = "ctime" expect(metadata).to receive(:ctime_file).and_return(time) metadata.collect expect(metadata.checksum).to eq("{ctime}#{time}") end end it "should validate against the schema" do expect(metadata.to_json).to validate_against('api/schemas/file_metadata.json') end describe "when a source and content_uri are set" do before do metadata.source = '/foo' metadata.content_uri = 'puppet:///foo' end it "should validate against the schema" do expect(metadata.to_json).to validate_against('api/schemas/file_metadata.json') end end end describe "when managing directories" do let(:path) { tmpdir('file_serving_metadata_dir') } let(:time) { Time.now } before :each do expect(metadata).to receive(:ctime_file).and_return(time) end it "should only use checksums of type 'ctime' for directories" do metadata.collect expect(metadata.checksum).to eq("{ctime}#{time}") end it "should only use checksums of type 'ctime' for directories even if checksum_type set" do metadata.checksum_type = "mtime" expect(metadata).not_to receive(:mtime_file) metadata.collect expect(metadata.checksum).to eq("{ctime}#{time}") end it "should validate against the schema" do metadata.collect expect(metadata.to_json).to validate_against('api/schemas/file_metadata.json') end end end end describe "WindowsStat", :if => Puppet::Util::Platform.windows? do include PuppetSpec::Files it "should return default owner, group and mode when the given path has an invalid DACL (such as a non-NTFS volume)" do invalid_error = Puppet::Util::Windows::Error.new('Invalid DACL', 1336) path = tmpfile('foo') FileUtils.touch(path) allow(Puppet::Util::Windows::Security).to receive(:get_owner).with(path).and_raise(invalid_error) allow(Puppet::Util::Windows::Security).to receive(:get_group).with(path).and_raise(invalid_error) allow(Puppet::Util::Windows::Security).to receive(:get_mode).with(path).and_raise(invalid_error) stat = Puppet::FileSystem.stat(path) win_stat = Puppet::FileServing::Metadata::WindowsStat.new(stat, path, :ignore) expect(win_stat.owner).to eq('S-1-5-32-544') expect(win_stat.group).to eq('S-1-0-0') expect(win_stat.mode).to eq(0644) end it "should still raise errors that are not the result of an 'Invalid DACL'" do invalid_error = ArgumentError.new('bar') path = tmpfile('bar') FileUtils.touch(path) allow(Puppet::Util::Windows::Security).to receive(:get_owner).with(path).and_raise(invalid_error) allow(Puppet::Util::Windows::Security).to receive(:get_group).with(path).and_raise(invalid_error) allow(Puppet::Util::Windows::Security).to receive(:get_mode).with(path).and_raise(invalid_error) stat = Puppet::FileSystem.stat(path) expect { Puppet::FileServing::Metadata::WindowsStat.new(stat, path, :use) }.to raise_error("Unsupported Windows source permissions option use") end end shared_examples_for "metadata collector symlinks" do let(:metadata) do data = described_class.new(path) data.collect data end describe "when collecting attributes" do describe "when managing links" do # 'path' is a link that points to 'target' let(:path) { tmpfile('file_serving_metadata_link') } let(:target) { tmpfile('file_serving_metadata_target') } let(:fmode) { Puppet::FileSystem.lstat(path).mode & 0777 } before :each do File.open(target, "wb") {|f| f.print('some content')} set_mode(0644, target) Puppet::FileSystem.symlink(target, path) end it "should read links instead of returning their checksums" do expect(metadata.destination).to eq(target) end it "should validate against the schema" do expect(metadata.to_json).to validate_against('api/schemas/file_metadata.json') end end end describe Puppet::FileServing::Metadata, " when finding the file to use for setting attributes" do let(:path) { tmpfile('file_serving_metadata_find_file') } before :each do File.open(path, "wb") {|f| f.print('some content')} set_mode(0755, path) end it "should accept a base path to which the file should be relative" do dir = tmpdir('metadata_dir') metadata = described_class.new(dir) metadata.relative_path = 'relative_path' FileUtils.touch(metadata.full_path) metadata.collect end it "should use the set base path if one is not provided" do metadata.collect end it "should raise an exception if the file does not exist" do File.delete(path) expect { metadata.collect}.to raise_error(Errno::ENOENT) end it "should validate against the schema" do expect(metadata.to_json).to validate_against('api/schemas/file_metadata.json') end end end describe "on POSIX systems", :if => Puppet.features.posix? do let(:owner) {10} let(:group) {20} before :each do allow_any_instance_of(File::Stat).to receive(:uid).and_return(owner) allow_any_instance_of(File::Stat).to receive(:gid).and_return(group) end describe "when collecting attributes when managing files" do let(:metadata) do data = described_class.new(path) data.collect data end let(:path) { tmpfile('file_serving_metadata') } before :each do FileUtils.touch(path) end it "should set the owner to the Process's current owner" do expect(metadata.owner).to eq(Process.euid) end it "should set the group to the Process's current group" do expect(metadata.group).to eq(Process.egid) end it "should set the mode to the default mode" do set_mode(33261, path) expect(metadata.mode).to eq(0644) end end it_should_behave_like "metadata collector" it_should_behave_like "metadata collector symlinks" def set_mode(mode, path) File.chmod(mode, path) end end describe "on Windows systems", :if => Puppet::Util::Platform.windows? do let(:owner) {'S-1-1-50'} let(:group) {'S-1-1-51'} before :each do require 'puppet/util/windows/security' allow(Puppet::Util::Windows::Security).to receive(:get_owner).and_return(owner) allow(Puppet::Util::Windows::Security).to receive(:get_group).and_return(group) end describe "when collecting attributes when managing files" do let(:metadata) do data = described_class.new(path) data.collect data end let(:path) { tmpfile('file_serving_metadata') } before :each do FileUtils.touch(path) end it "should set the owner to the Process's current owner" do expect(metadata.owner).to eq("S-1-5-32-544") end it "should set the group to the Process's current group" do expect(metadata.group).to eq("S-1-0-0") end it "should set the mode to the default mode" do set_mode(33261, path) expect(metadata.mode).to eq(0644) end end it_should_behave_like "metadata collector" it_should_behave_like "metadata collector symlinks" if Puppet.features.manages_symlinks? describe "if ACL metadata cannot be collected" do let(:path) { tmpdir('file_serving_metadata_acl') } let(:metadata) do data = described_class.new(path) data.collect data end let (:invalid_dacl_error) do Puppet::Util::Windows::Error.new('Invalid DACL', 1336) end it "should default owner" do allow(Puppet::Util::Windows::Security).to receive(:get_owner).and_return(nil) expect(metadata.owner).to eq('S-1-5-32-544') end it "should default group" do allow(Puppet::Util::Windows::Security).to receive(:get_group).and_return(nil) expect(metadata.group).to eq('S-1-0-0') end it "should default mode" do allow(Puppet::Util::Windows::Security).to receive(:get_mode).and_return(nil) expect(metadata.mode).to eq(0644) end describe "when the path raises an Invalid ACL error" do # these simulate the behavior of a symlink file whose target does not support ACLs it "should default owner" do allow(Puppet::Util::Windows::Security).to receive(:get_owner).and_raise(invalid_dacl_error) expect(metadata.owner).to eq('S-1-5-32-544') end it "should default group" do allow(Puppet::Util::Windows::Security).to receive(:get_group).and_raise(invalid_dacl_error) expect(metadata.group).to eq('S-1-0-0') end it "should default mode" do allow(Puppet::Util::Windows::Security).to receive(:get_mode).and_raise(invalid_dacl_error) expect(metadata.mode).to eq(0644) end end end def set_mode(mode, path) Puppet::Util::Windows::Security.set_mode(mode, path) end end end describe Puppet::FileServing::Metadata, " when pointing to a link", :if => Puppet.features.manages_symlinks?, :uses_checksums => true do with_digest_algorithms do describe "when links are managed" do before do path = "/base/path/my/file" @file = Puppet::FileServing::Metadata.new(path, :links => :manage) stat = double("stat", :uid => 1, :gid => 2, :ftype => "link", :mode => 0755) expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stat) expect(Puppet::FileSystem).to receive(:readlink).with(path).and_return("/some/other/path") allow(@file).to receive("#{digest_algorithm}_file".intern).and_return(checksum) # Remove these when :managed links are no longer checksumed. if Puppet::Util::Platform.windows? win_stat = double('win_stat', :owner => 'snarf', :group => 'thundercats', :ftype => 'link', :mode => 0755) allow(Puppet::FileServing::Metadata::WindowsStat).to receive(:new).and_return(win_stat) end end it "should store the destination of the link in :destination if links are :manage" do @file.collect expect(@file.destination).to eq("/some/other/path") end pending "should not collect the checksum if links are :manage" do # We'd like this to be true, but we need to always collect the checksum because in the server/client/server round trip we lose the distintion between manage and follow. @file.collect expect(@file.checksum).to be_nil end it "should collect the checksum if links are :manage" do # see pending note above @file.collect expect(@file.checksum).to eq("{#{digest_algorithm}}#{checksum}") end end describe "when links are followed" do before do path = "/base/path/my/file" @file = Puppet::FileServing::Metadata.new(path, :links => :follow) stat = double("stat", :uid => 1, :gid => 2, :ftype => "file", :mode => 0755) expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(stat) expect(Puppet::FileSystem).not_to receive(:readlink) if Puppet::Util::Platform.windows? win_stat = double('win_stat', :owner => 'snarf', :group => 'thundercats', :ftype => 'file', :mode => 0755) allow(Puppet::FileServing::Metadata::WindowsStat).to receive(:new).and_return(win_stat) end allow(@file).to receive("#{digest_algorithm}_file".intern).and_return(checksum) end it "should not store the destination of the link in :destination if links are :follow" do @file.collect expect(@file.destination).to be_nil end it "should collect the checksum if links are :follow" do @file.collect expect(@file.checksum).to eq("{#{digest_algorithm}}#{checksum}") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/terminus_selector_spec.rb
spec/unit/file_serving/terminus_selector_spec.rb
require 'spec_helper' require 'puppet/file_serving/terminus_selector' describe Puppet::FileServing::TerminusSelector do class TestSelector include Puppet::FileServing::TerminusSelector end def create_request(key) Puppet::Indirector::Request.new(:indirection_name, :find, key, nil, {node: 'whatever'}) end subject { TestSelector.new } describe "when being used to select termini" do it "should return :file if the request key is fully qualified" do request = create_request(File.expand_path('/foo')) expect(subject.select(request)).to eq(:file) end it "should return :file_server if the request key is relative" do request = create_request('modules/my_module/path/to_file') expect(subject.select(request)).to eq(:file_server) end it "should return :file if the URI protocol is set to 'file'" do request = create_request(Puppet::Util.path_to_uri(File.expand_path("/foo")).to_s) expect(subject.select(request)).to eq(:file) end it "should return :http if the URI protocol is set to 'http'" do request = create_request("http://www.example.com") expect(subject.select(request)).to eq(:http) end it "should return :http if the URI protocol is set to 'https'" do request = create_request("https://www.example.com") expect(subject.select(request)).to eq(:http) end it "should return :http if the path starts with a double slash" do request = create_request("https://www.example.com//index.html") expect(subject.select(request)).to eq(:http) end it "should fail when a protocol other than :puppet, :http(s) or :file is used" do request = create_request("ftp://ftp.example.com") expect { subject.select(request) }.to raise_error(ArgumentError, /URI protocol 'ftp' is not currently supported for file serving/) end describe "and the protocol is 'puppet'" do it "should choose :rest when a server is specified" do request = create_request("puppet://puppetserver.example.com") expect(subject.select(request)).to eq(:rest) end # This is so a given file location works when bootstrapping with no server. it "should choose :rest when default_file_terminus is rest" do Puppet[:server] = 'localhost' request = create_request("puppet:///plugins") expect(subject.select(request)).to eq(:rest) end it "should choose :file_server when default_file_terminus is file_server and no server is specified on the request" do Puppet[:default_file_terminus] = 'file_server' request = create_request("puppet:///plugins") expect(subject.select(request)).to eq(:file_server) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount_spec.rb
spec/unit/file_serving/mount_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount' describe Puppet::FileServing::Mount do it "should use 'mount[$name]' as its string form" do expect(Puppet::FileServing::Mount.new("foo").to_s).to eq("mount[foo]") end end describe Puppet::FileServing::Mount, " when initializing" do it "should fail on non-alphanumeric name" do expect { Puppet::FileServing::Mount.new("non alpha") }.to raise_error(ArgumentError) end it "should allow dashes in its name" do expect(Puppet::FileServing::Mount.new("non-alpha").name).to eq("non-alpha") end end describe Puppet::FileServing::Mount, " when finding files" do it "should fail" do expect { Puppet::FileServing::Mount.new("test").find("foo", :one => "two") }.to raise_error(NotImplementedError) end end describe Puppet::FileServing::Mount, " when searching for files" do it "should fail" do expect { Puppet::FileServing::Mount.new("test").search("foo", :one => "two") }.to raise_error(NotImplementedError) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/configuration_spec.rb
spec/unit/file_serving/configuration_spec.rb
require 'spec_helper' require 'puppet/file_serving/configuration' describe Puppet::FileServing::Configuration do include PuppetSpec::Files before :each do @path = make_absolute("/path/to/configuration/file.conf") Puppet[:trace] = false Puppet[:fileserverconfig] = @path end after :each do Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil) end it "should make :new a private method" do # Ruby 3.3 includes "class" in the error, 3.2 does not. expect { Puppet::FileServing::Configuration.new }.to raise_error(NoMethodError, /private method .*new' called for( class)? Puppet::FileServing::Configuration/) end it "should return the same configuration each time 'configuration' is called" do expect(Puppet::FileServing::Configuration.configuration).to equal(Puppet::FileServing::Configuration.configuration) end describe "when initializing" do it "should work without a configuration file" do allow(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(false) expect { Puppet::FileServing::Configuration.configuration }.to_not raise_error end it "should parse the configuration file if present" do allow(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true) @parser = double('parser') expect(@parser).to receive(:parse).and_return({}) allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(@parser) Puppet::FileServing::Configuration.configuration end it "should determine the path to the configuration file from the Puppet settings" do Puppet::FileServing::Configuration.configuration end end describe "when parsing the configuration file" do before do allow(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true) @parser = double('parser') allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(@parser) end it "should set the mount list to the results of parsing" do expect(@parser).to receive(:parse).and_return("one" => double("mount")) config = Puppet::FileServing::Configuration.configuration expect(config.mounted?("one")).to be_truthy end it "should not raise exceptions" do expect(@parser).to receive(:parse).and_raise(ArgumentError) expect { Puppet::FileServing::Configuration.configuration }.to_not raise_error end it "should replace the existing mount list with the results of reparsing" do expect(@parser).to receive(:parse).and_return("one" => double("mount")) config = Puppet::FileServing::Configuration.configuration expect(config.mounted?("one")).to be_truthy # Now parse again expect(@parser).to receive(:parse).and_return("two" => double('other')) config.send(:readconfig, false) expect(config.mounted?("one")).to be_falsey expect(config.mounted?("two")).to be_truthy end it "should not replace the mount list until the file is entirely parsed successfully" do expect(@parser).to receive(:parse).and_return("one" => double("mount")) expect(@parser).to receive(:parse).and_raise(ArgumentError) config = Puppet::FileServing::Configuration.configuration # Now parse again, so the exception gets thrown config.send(:readconfig, false) expect(config.mounted?("one")).to be_truthy end it "should add modules, plugins, scripts, and tasks mounts even if the file does not exist" do expect(Puppet::FileSystem).to receive(:exist?).and_return(false) # the file doesn't exist config = Puppet::FileServing::Configuration.configuration expect(config.mounted?("modules")).to be_truthy expect(config.mounted?("plugins")).to be_truthy expect(config.mounted?("scripts")).to be_truthy expect(config.mounted?("tasks")).to be_truthy end it "should allow all access to modules, plugins, scripts, and tasks if no fileserver.conf exists" do expect(Puppet::FileSystem).to receive(:exist?).and_return(false) # the file doesn't exist modules = double('modules') allow(Puppet::FileServing::Mount::Modules).to receive(:new).and_return(modules) plugins = double('plugins') allow(Puppet::FileServing::Mount::Plugins).to receive(:new).and_return(plugins) tasks = double('tasks') allow(Puppet::FileServing::Mount::Tasks).to receive(:new).and_return(tasks) scripts = double('scripts') allow(Puppet::FileServing::Mount::Scripts).to receive(:new).and_return(scripts) Puppet::FileServing::Configuration.configuration end it "should not allow access from all to modules, plugins, scripts, and tasks if the fileserver.conf provided some rules" do expect(Puppet::FileSystem).to receive(:exist?).and_return(false) # the file doesn't exist modules = double('modules') allow(Puppet::FileServing::Mount::Modules).to receive(:new).and_return(modules) plugins = double('plugins') allow(Puppet::FileServing::Mount::Plugins).to receive(:new).and_return(plugins) tasks = double('tasks') allow(Puppet::FileServing::Mount::Tasks).to receive(:new).and_return(tasks) scripts = double('scripts', :empty? => false) allow(Puppet::FileServing::Mount::Scripts).to receive(:new).and_return(scripts) Puppet::FileServing::Configuration.configuration end it "should add modules, plugins, scripts, and tasks mounts even if they are not returned by the parser" do expect(@parser).to receive(:parse).and_return("one" => double("mount")) expect(Puppet::FileSystem).to receive(:exist?).and_return(true) # the file doesn't exist config = Puppet::FileServing::Configuration.configuration expect(config.mounted?("modules")).to be_truthy expect(config.mounted?("plugins")).to be_truthy expect(config.mounted?("scripts")).to be_truthy expect(config.mounted?("tasks")).to be_truthy end end describe "when finding the specified mount" do it "should choose the named mount if one exists" do config = Puppet::FileServing::Configuration.configuration expect(config).to receive(:mounts).and_return("one" => "foo") expect(config.find_mount("one", double('env'))).to eq("foo") end it "should return nil if there is no such named mount" do config = Puppet::FileServing::Configuration.configuration env = double('environment') mount = double('mount') allow(config).to receive(:mounts).and_return("modules" => mount) expect(config.find_mount("foo", env)).to be_nil end end describe "#split_path" do let(:config) { Puppet::FileServing::Configuration.configuration } let(:request) { double('request', :key => "foo/bar/baz", :options => {}, :node => nil, :environment => double("env")) } before do allow(config).to receive(:find_mount) end it "should reread the configuration" do expect(config).to receive(:readconfig) config.split_path(request) end it "should treat the first field of the URI path as the mount name" do expect(config).to receive(:find_mount).with("foo", anything) config.split_path(request) end it "should fail if the mount name is not alpha-numeric" do expect(request).to receive(:key).and_return("foo&bar/asdf") expect { config.split_path(request) }.to raise_error(ArgumentError) end it "should support dashes in the mount name" do expect(request).to receive(:key).and_return("foo-bar/asdf") expect { config.split_path(request) }.to_not raise_error end it "should use the mount name and environment to find the mount" do expect(config).to receive(:find_mount).with("foo", request.environment) allow(request).to receive(:node).and_return("mynode") config.split_path(request) end it "should return nil if the mount cannot be found" do expect(config).to receive(:find_mount).and_return(nil) expect(config.split_path(request)).to be_nil end it "should return the mount and the relative path if the mount is found" do mount = double('mount', :name => "foo") expect(config).to receive(:find_mount).and_return(mount) expect(config.split_path(request)).to eq([mount, "bar/baz"]) end it "should remove any double slashes" do allow(request).to receive(:key).and_return("foo/bar//baz") mount = double('mount', :name => "foo") expect(config).to receive(:find_mount).and_return(mount) expect(config.split_path(request)).to eq([mount, "bar/baz"]) end it "should fail if the path contains .." do allow(request).to receive(:key).and_return('module/foo/../../bar') expect do config.split_path(request) end.to raise_error(ArgumentError, /Invalid relative path/) end it "should return the relative path as nil if it is an empty string" do expect(request).to receive(:key).and_return("foo") mount = double('mount', :name => "foo") expect(config).to receive(:find_mount).and_return(mount) expect(config.split_path(request)).to eq([mount, nil]) end it "should add 'modules/' to the relative path if the modules mount is used but not specified, for backward compatibility" do expect(request).to receive(:key).and_return("foo/bar") mount = double('mount', :name => "modules") expect(config).to receive(:find_mount).and_return(mount) expect(config.split_path(request)).to eq([mount, "foo/bar"]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/content_spec.rb
spec/unit/file_serving/content_spec.rb
require 'spec_helper' require 'puppet/file_serving/content' describe Puppet::FileServing::Content do let(:path) { File.expand_path('/path') } it "should be a subclass of Base" do expect(Puppet::FileServing::Content.superclass).to equal(Puppet::FileServing::Base) end it "should indirect file_content" do expect(Puppet::FileServing::Content.indirection.name).to eq(:file_content) end it "should only support the binary format" do expect(Puppet::FileServing::Content.supported_formats).to eq([:binary]) end it "should have a method for collecting its attributes" do expect(Puppet::FileServing::Content.new(path)).to respond_to(:collect) end it "should not retrieve and store its contents when its attributes are collected" do content = Puppet::FileServing::Content.new(path) expect(File).not_to receive(:read).with(path) content.collect expect(content.instance_variable_get("@content")).to be_nil end it "should have a method for setting its content" do content = Puppet::FileServing::Content.new(path) expect(content).to respond_to(:content=) end it "should make content available when set externally" do content = Puppet::FileServing::Content.new(path) content.content = "foo/bar" expect(content.content).to eq("foo/bar") end it "should be able to create a content instance from binary file contents" do expect(Puppet::FileServing::Content).to respond_to(:from_binary) end it "should create an instance with a fake file name and correct content when converting from binary" do instance = double('instance') expect(Puppet::FileServing::Content).to receive(:new).with("/this/is/a/fake/path").and_return(instance) expect(instance).to receive(:content=).with("foo/bar") expect(Puppet::FileServing::Content.from_binary("foo/bar")).to equal(instance) end it "should return an opened File when converted to binary" do content = Puppet::FileServing::Content.new(path) expect(File).to receive(:new).with(path, "rb").and_return(:file) expect(content.to_binary).to eq(:file) end end describe Puppet::FileServing::Content, "when returning the contents" do let(:path) { File.expand_path('/my/path') } let(:content) { Puppet::FileServing::Content.new(path, :links => :follow) } it "should fail if the file is a symlink and links are set to :manage" do content.links = :manage expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(double("stat", :ftype => "symlink")) expect { content.content }.to raise_error(ArgumentError) end it "should fail if a path is not set" do expect { content.content }.to raise_error(Errno::ENOENT) end it "should raise Errno::ENOENT if the file is absent" do content.path = File.expand_path("/there/is/absolutely/no/chance/that/this/path/exists") expect { content.content }.to raise_error(Errno::ENOENT) end it "should return the contents of the path if the file exists" do expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(double('stat', :ftype => 'file')) expect(Puppet::FileSystem).to receive(:binread).with(path).and_return(:mycontent) expect(content.content).to eq(:mycontent) end it "should cache the returned contents" do expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(double('stat', :ftype => 'file')) expect(Puppet::FileSystem).to receive(:binread).with(path).and_return(:mycontent) content.content # The second run would throw a failure if the content weren't being cached. content.content end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/http_metadata_spec.rb
spec/unit/file_serving/http_metadata_spec.rb
require 'spec_helper' require 'puppet/file_serving/http_metadata' require 'matchers/json' require 'net/http' require 'digest' describe Puppet::FileServing::HttpMetadata do let(:foobar) { File.expand_path('/foo/bar') } it "should be a subclass of Metadata" do expect( described_class.superclass ).to be Puppet::FileServing::Metadata end describe "when initializing" do let(:http_response) { Net::HTTPOK.new(1.0, '200', 'OK') } it "can be instantiated from a HTTP response object" do expect( described_class.new(http_response) ).to_not be_nil end it "represents a plain file" do expect( described_class.new(http_response).ftype ).to eq 'file' end it "carries no information on owner, group and mode" do metadata = described_class.new(http_response) expect( metadata.owner ).to be_nil expect( metadata.group ).to be_nil expect( metadata.mode ).to be_nil end it "skips md5 checksum type in collect on FIPS enabled platforms" do allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true) http_response['X-Checksum-Md5'] = 'c58989e9740a748de4f5054286faf99b' metadata = described_class.new(http_response) metadata.collect expect( metadata.checksum_type ).to eq :mtime end context "with no Last-Modified or Content-MD5 header from the server" do it "should use :mtime as the checksum type, based on current time" do # Stringifying Time.now does some rounding; do so here so we don't end up with a time # that's greater than the stringified version returned by collect. time = Time.parse(Time.now.to_s) metadata = described_class.new(http_response) metadata.collect expect( metadata.checksum_type ).to eq :mtime checksum = metadata.checksum expect( checksum[0...7] ).to eq '{mtime}' expect( Time.parse(checksum[7..-1]) ).to be >= time end end context "with a Last-Modified header from the server" do let(:time) { Time.now.utc } it "should use :mtime as the checksum type, based on Last-Modified" do # HTTP uses "GMT" not "UTC" http_response.add_field('last-modified', time.strftime("%a, %d %b %Y %T GMT")) metadata = described_class.new(http_response) metadata.collect expect( metadata.checksum_type ).to eq :mtime expect( metadata.checksum ).to eq "{mtime}#{time.to_time.utc}" end end context "with a Content-MD5 header being received" do let(:input) { Time.now.to_s } let(:base64) { Digest::MD5.new.base64digest input } let(:hex) { Digest::MD5.new.hexdigest input } it "should use the md5 checksum" do http_response.add_field('content-md5', base64) metadata = described_class.new(http_response) metadata.collect expect( metadata.checksum_type ).to eq :md5 expect( metadata.checksum ).to eq "{md5}#{hex}" end end context "with X-Checksum-Md5" do let(:md5) { "c58989e9740a748de4f5054286faf99b" } it "should use the md5 checksum" do http_response.add_field('X-Checksum-Md5', md5) metadata = described_class.new(http_response) metadata.collect expect( metadata.checksum_type ).to eq :md5 expect( metadata.checksum ).to eq "{md5}#{md5}" end end context "with X-Checksum-Sha1" do let(:sha1) { "01e4d15746f4274b84d740a93e04b9fd2882e3ea" } it "should use the SHA1 checksum" do http_response.add_field('X-Checksum-Sha1', sha1) metadata = described_class.new(http_response) metadata.collect expect( metadata.checksum_type ).to eq :sha1 expect( metadata.checksum ).to eq "{sha1}#{sha1}" end end context "with X-Checksum-Sha256" do let(:sha256) { "a3eda98259c30e1e75039c2123670c18105e1c46efb672e42ca0e4cbe77b002a" } it "should use the SHA256 checksum" do http_response.add_field('X-Checksum-Sha256', sha256) metadata = described_class.new(http_response) metadata.collect expect( metadata.checksum_type ).to eq :sha256 expect( metadata.checksum ).to eq "{sha256}#{sha256}" end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/terminus_helper_spec.rb
spec/unit/file_serving/terminus_helper_spec.rb
require 'spec_helper' require 'puppet/file_serving/terminus_helper' class Puppet::FileServing::TestHelper include Puppet::FileServing::TerminusHelper attr_reader :model def initialize(model) @model = model end end describe Puppet::FileServing::TerminusHelper do before do @model = double('model') @helper = Puppet::FileServing::TestHelper.new(@model) @request = double('request', :key => "url", :options => {}) @fileset = double('fileset', :files => [], :path => "/my/file") allow(Puppet::FileServing::Fileset).to receive(:new).with("/my/file", {}).and_return(@fileset) end it "should find a file with absolute path" do file = double('file', :collect => nil) expect(file).to receive(:collect).with(no_args) expect(@model).to receive(:new).with("/my/file", {:relative_path => nil}).and_return(file) @helper.path2instance(@request, "/my/file") end it "should pass through links, checksum_type, and source_permissions" do file = double('file', :checksum_type= => nil, :links= => nil, :collect => nil) [[:checksum_type, :sha256], [:links, true], [:source_permissions, :use]].each {|k, v| expect(file).to receive(k.to_s+'=').with(v) @request.options[k] = v } expect(file).to receive(:collect) expect(@model).to receive(:new).with("/my/file", {:relative_path => :file}).and_return(file) @helper.path2instance(@request, "/my/file", {:relative_path => :file}) end it "should use a fileset to find paths" do @fileset = double('fileset', :files => [], :path => "/my/files") expect(Puppet::FileServing::Fileset).to receive(:new).with("/my/file", anything).and_return(@fileset) @helper.path2instances(@request, "/my/file") end it "should support finding across multiple paths by merging the filesets" do first = double('fileset', :files => [], :path => "/first/file") expect(Puppet::FileServing::Fileset).to receive(:new).with("/first/file", anything).and_return(first) second = double('fileset', :files => [], :path => "/second/file") expect(Puppet::FileServing::Fileset).to receive(:new).with("/second/file", anything).and_return(second) expect(Puppet::FileServing::Fileset).to receive(:merge).with(first, second).and_return({}) @helper.path2instances(@request, "/first/file", "/second/file") end it "should pass the indirection request to the Fileset at initialization" do expect(Puppet::FileServing::Fileset).to receive(:new).with(anything, @request).and_return(@fileset) @helper.path2instances(@request, "/my/file") end describe "when creating instances" do before do allow(@request).to receive(:key).and_return("puppet://host/mount/dir") @one = double('one', :links= => nil, :collect => nil) @two = double('two', :links= => nil, :collect => nil) @fileset = double('fileset', :files => %w{one two}, :path => "/my/file") allow(Puppet::FileServing::Fileset).to receive(:new).and_return(@fileset) end it "should set each returned instance's path to the original path" do expect(@model).to receive(:new).with("/my/file", anything).and_return(@one, @two) @helper.path2instances(@request, "/my/file") end it "should set each returned instance's relative path to the file-specific path" do expect(@model).to receive(:new).with(anything, hash_including(relative_path: "one")).and_return(@one) expect(@model).to receive(:new).with(anything, hash_including(relative_path: "two")).and_return(@two) @helper.path2instances(@request, "/my/file") end it "should set the links value on each instance if one is provided" do expect(@one).to receive(:links=).with(:manage) expect(@two).to receive(:links=).with(:manage) expect(@model).to receive(:new).and_return(@one, @two) @request.options[:links] = :manage @helper.path2instances(@request, "/my/file") end it "should set the request checksum_type if one is provided" do expect(@one).to receive(:checksum_type=).with(:test) expect(@two).to receive(:checksum_type=).with(:test) expect(@model).to receive(:new).and_return(@one, @two) @request.options[:checksum_type] = :test @helper.path2instances(@request, "/my/file") end it "should collect the instance's attributes" do expect(@one).to receive(:collect) expect(@two).to receive(:collect) expect(@model).to receive(:new).and_return(@one, @two) @helper.path2instances(@request, "/my/file") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/base_spec.rb
spec/unit/file_serving/base_spec.rb
require 'spec_helper' require 'puppet/file_serving/base' describe Puppet::FileServing::Base do let(:path) { File.expand_path('/module/dir/file') } let(:file) { File.expand_path('/my/file') } it "should accept a path" do expect(Puppet::FileServing::Base.new(path).path).to eq(path) end it "should require that paths be fully qualified" do expect { Puppet::FileServing::Base.new("module/dir/file") }.to raise_error(ArgumentError) end it "should allow specification of whether links should be managed" do expect(Puppet::FileServing::Base.new(path, :links => :manage).links).to eq(:manage) end it "should have a :source attribute" do file = Puppet::FileServing::Base.new(path) expect(file).to respond_to(:source) expect(file).to respond_to(:source=) end it "should consider :ignore links equivalent to :manage links" do expect(Puppet::FileServing::Base.new(path, :links => :ignore).links).to eq(:manage) end it "should fail if :links is set to anything other than :manage, :follow, or :ignore" do expect { Puppet::FileServing::Base.new(path, :links => :else) }.to raise_error(ArgumentError) end it "should allow links values to be set as strings" do expect(Puppet::FileServing::Base.new(path, :links => "follow").links).to eq(:follow) end it "should default to :manage for :links" do expect(Puppet::FileServing::Base.new(path).links).to eq(:manage) end it "should allow specification of a relative path" do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect(Puppet::FileServing::Base.new(path, :relative_path => "my/file").relative_path).to eq("my/file") end it "should have a means of determining if the file exists" do expect(Puppet::FileServing::Base.new(file)).to respond_to(:exist?) end it "should correctly indicate if the file is present" do expect(Puppet::FileSystem).to receive(:lstat).with(file).and_return(double('stat')) expect(Puppet::FileServing::Base.new(file).exist?).to be_truthy end it "should correctly indicate if the file is absent" do expect(Puppet::FileSystem).to receive(:lstat).with(file).and_raise(RuntimeError) expect(Puppet::FileServing::Base.new(file).exist?).to be_falsey end describe "when setting the relative path" do it "should require that the relative path be unqualified" do @file = Puppet::FileServing::Base.new(path) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect { @file.relative_path = File.expand_path("/qualified/file") }.to raise_error(ArgumentError) end end describe "when determining the full file path" do let(:path) { File.expand_path('/this/file') } let(:file) { Puppet::FileServing::Base.new(path) } it "should return the path if there is no relative path" do expect(file.full_path).to eq(path) end it "should return the path if the relative_path is set to ''" do file.relative_path = "" expect(file.full_path).to eq(path) end it "should return the path if the relative_path is set to '.'" do file.relative_path = "." expect(file.full_path).to eq(path) end it "should return the path joined with the relative path if there is a relative path and it is not set to '/' or ''" do file.relative_path = "not/qualified" expect(file.full_path).to eq(File.join(path, "not/qualified")) end it "should strip extra slashes" do file = Puppet::FileServing::Base.new(File.join(File.expand_path('/'), "//this//file")) expect(file.full_path).to eq(path) end end describe "when handling a UNC file path on Windows" do let(:path) { '//server/share/filename' } let(:file) { Puppet::FileServing::Base.new(path) } before :each do allow(Puppet::Util::Platform).to receive(:windows?).and_return(true) end it "should preserve double slashes at the beginning of the path" do expect(file.full_path).to eq(path) end it "should strip double slashes not at the beginning of the path" do file = Puppet::FileServing::Base.new('//server//share//filename') expect(file.full_path).to eq(path) end end describe "when stat'ing files" do let(:path) { File.expand_path('/this/file') } let(:file) { Puppet::FileServing::Base.new(path) } let(:stat) { double('stat', :ftype => 'file' ) } let(:stubbed_file) { double(path, :stat => stat, :lstat => stat)} it "should stat the file's full path" do expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stat) file.stat end it "should fail if the file does not exist" do expect(Puppet::FileSystem).to receive(:lstat).with(path).and_raise(Errno::ENOENT) expect { file.stat }.to raise_error(Errno::ENOENT) end it "should use :lstat if :links is set to :manage" do expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stubbed_file) file.stat end it "should use :stat if :links is set to :follow" do expect(Puppet::FileSystem).to receive(:stat).with(path).and_return(stubbed_file) file.links = :follow file.stat end end describe "#absolute?" do it "should be accept POSIX paths" do expect(Puppet::FileServing::Base).to be_absolute('/') end it "should accept Windows paths on Windows" do allow(Puppet::Util::Platform).to receive(:windows?).and_return(true) allow(Puppet.features).to receive(:posix?).and_return(false) expect(Puppet::FileServing::Base).to be_absolute('c:/foo') end it "should reject Windows paths on POSIX" do allow(Puppet::Util::Platform).to receive(:windows?).and_return(false) expect(Puppet::FileServing::Base).not_to be_absolute('c:/foo') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount/file_spec.rb
spec/unit/file_serving/mount/file_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount/file' module FileServingMountTesting def stub_facter(hostname) allow(Facter).to receive(:value).with("networking.hostname").and_return(hostname.sub(/\..+/, '')) allow(Facter).to receive(:value).with("networking.domain").and_return(hostname.sub(/^[^.]+\./, '')) end end describe Puppet::FileServing::Mount::File do it "should be invalid if it does not have a path" do expect { Puppet::FileServing::Mount::File.new("foo").validate }.to raise_error(ArgumentError) end it "should be valid if it has a path" do allow(FileTest).to receive(:directory?).and_return(true) allow(FileTest).to receive(:readable?).and_return(true) mount = Puppet::FileServing::Mount::File.new("foo") mount.path = "/foo" expect { mount.validate }.not_to raise_error end describe "when setting the path" do before do @mount = Puppet::FileServing::Mount::File.new("test") @dir = "/this/path/does/not/exist" end it "should fail if the path is not a directory" do expect(FileTest).to receive(:directory?).and_return(false) expect { @mount.path = @dir }.to raise_error(ArgumentError) end it "should fail if the path is not readable" do expect(FileTest).to receive(:directory?).and_return(true) expect(FileTest).to receive(:readable?).and_return(false) expect { @mount.path = @dir }.to raise_error(ArgumentError) end end describe "when substituting hostnames and ip addresses into file paths" do include FileServingMountTesting before do allow(FileTest).to receive(:directory?).and_return(true) allow(FileTest).to receive(:readable?).and_return(true) @mount = Puppet::FileServing::Mount::File.new("test") @host = "host.domain.com" end after :each do Puppet::FileServing::Mount::File.instance_variable_set(:@localmap, nil) end it "should replace incidences of %h in the path with the client's short name" do @mount.path = "/dir/%h/yay" expect(@mount.path(@host)).to eq("/dir/host/yay") end it "should replace incidences of %H in the path with the client's fully qualified name" do @mount.path = "/dir/%H/yay" expect(@mount.path(@host)).to eq("/dir/host.domain.com/yay") end it "should replace incidences of %d in the path with the client's domain name" do @mount.path = "/dir/%d/yay" expect(@mount.path(@host)).to eq("/dir/domain.com/yay") end it "should perform all necessary replacements" do @mount.path = "/%h/%d/%H" expect(@mount.path(@host)).to eq("/host/domain.com/host.domain.com") end it "should use local host information if no client data is provided" do stub_facter("myhost.mydomain.com") @mount.path = "/%h/%d/%H" expect(@mount.path).to eq("/myhost/mydomain.com/myhost.mydomain.com") end end describe "when determining the complete file path" do include FileServingMountTesting before do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(FileTest).to receive(:directory?).and_return(true) allow(FileTest).to receive(:readable?).and_return(true) @mount = Puppet::FileServing::Mount::File.new("test") @mount.path = "/mount" stub_facter("myhost.mydomain.com") @host = "host.domain.com" end it "should return nil if the file is absent" do allow(Puppet::FileSystem).to receive(:exist?).and_return(false) expect(@mount.complete_path("/my/path", nil)).to be_nil end it "should write a log message if the file is absent" do allow(Puppet::FileSystem).to receive(:exist?).and_return(false) expect(Puppet).to receive(:info).with("File does not exist or is not accessible: /mount/my/path") @mount.complete_path("/my/path", nil) end it "should return the file path if the file is present" do allow(Puppet::FileSystem).to receive(:exist?).with("/my/path").and_return(true) expect(@mount.complete_path("/my/path", nil)).to eq("/mount/my/path") end it "should treat a nil file name as the path to the mount itself" do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect(@mount.complete_path(nil, nil)).to eq("/mount") end it "should use the client host name if provided in the options" do @mount.path = "/mount/%h" expect(@mount.complete_path("/my/path", @host)).to eq("/mount/host/my/path") end it "should perform replacements on the base path" do @mount.path = "/blah/%h" expect(@mount.complete_path("/my/stuff", @host)).to eq("/blah/host/my/stuff") end it "should not perform replacements on the per-file path" do @mount.path = "/blah" expect(@mount.complete_path("/%h/stuff", @host)).to eq("/blah/%h/stuff") end it "should look for files relative to its base directory" do expect(@mount.complete_path("/my/stuff", @host)).to eq("/mount/my/stuff") end end describe "when finding files" do include FileServingMountTesting before do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(FileTest).to receive(:directory?).and_return(true) allow(FileTest).to receive(:readable?).and_return(true) @mount = Puppet::FileServing::Mount::File.new("test") @mount.path = "/mount" stub_facter("myhost.mydomain.com") @host = "host.domain.com" @request = double('request', :node => "foo") end it "should return the results of the complete file path" do allow(Puppet::FileSystem).to receive(:exist?).and_return(false) expect(@mount).to receive(:complete_path).with("/my/path", "foo").and_return("eh") expect(@mount.find("/my/path", @request)).to eq("eh") end end describe "when searching for files" do include FileServingMountTesting before do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(FileTest).to receive(:directory?).and_return(true) allow(FileTest).to receive(:readable?).and_return(true) @mount = Puppet::FileServing::Mount::File.new("test") @mount.path = "/mount" stub_facter("myhost.mydomain.com") @host = "host.domain.com" @request = double('request', :node => "foo") end it "should return the results of the complete file path as an array" do allow(Puppet::FileSystem).to receive(:exist?).and_return(false) expect(@mount).to receive(:complete_path).with("/my/path", "foo").and_return("eh") expect(@mount.search("/my/path", @request)).to eq(["eh"]) end it "should return nil if the complete path is nil" do allow(Puppet::FileSystem).to receive(:exist?).and_return(false) expect(@mount).to receive(:complete_path).with("/my/path", "foo").and_return(nil) expect(@mount.search("/my/path", @request)).to be_nil end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount/modules_spec.rb
spec/unit/file_serving/mount/modules_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount/modules' describe Puppet::FileServing::Mount::Modules do before do @mount = Puppet::FileServing::Mount::Modules.new("modules") @environment = double('environment', :module => nil) @request = double('request', :environment => @environment) end describe "when finding files" do it "should fail if no module is specified" do expect { @mount.find("", @request) }.to raise_error(/No module specified/) end it "should use the provided environment to find the module" do expect(@environment).to receive(:module) @mount.find("foo", @request) end it "should treat the first field of the relative path as the module name" do expect(@environment).to receive(:module).with("foo") @mount.find("foo/bar/baz", @request) end it "should return nil if the specified module does not exist" do expect(@environment).to receive(:module).with("foo") @mount.find("foo/bar/baz", @request) end it "should return the file path from the module" do mod = double('module') expect(mod).to receive(:file).with("bar/baz").and_return("eh") expect(@environment).to receive(:module).with("foo").and_return(mod) expect(@mount.find("foo/bar/baz", @request)).to eq("eh") end end describe "when searching for files" do it "should fail if no module is specified" do expect { @mount.search("", @request) }.to raise_error(/No module specified/) end it "should use the node's environment to search the module" do expect(@environment).to receive(:module) @mount.search("foo", @request) end it "should treat the first field of the relative path as the module name" do expect(@environment).to receive(:module).with("foo") @mount.search("foo/bar/baz", @request) end it "should return nil if the specified module does not exist" do expect(@environment).to receive(:module).with("foo").and_return(nil) @mount.search("foo/bar/baz", @request) end it "should return the file path as an array from the module" do mod = double('module') expect(mod).to receive(:file).with("bar/baz").and_return("eh") expect(@environment).to receive(:module).with("foo").and_return(mod) expect(@mount.search("foo/bar/baz", @request)).to eq(["eh"]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount/pluginfacts_spec.rb
spec/unit/file_serving/mount/pluginfacts_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount/pluginfacts' describe Puppet::FileServing::Mount::PluginFacts do before do @mount = Puppet::FileServing::Mount::PluginFacts.new("pluginfacts") @environment = double('environment', :module => nil) @options = { :recurse => true } @request = double('request', :environment => @environment, :options => @options) end describe "when finding files" do it "should use the provided environment to find the modules" do expect(@environment).to receive(:modules).and_return([]) @mount.find("foo", @request) end it "should return nil if no module can be found with a matching plugin" do mod = double('module') allow(mod).to receive(:pluginfact).with("foo/bar").and_return(nil) allow(@environment).to receive(:modules).and_return([mod]) expect(@mount.find("foo/bar", @request)).to be_nil end it "should return the file path from the module" do mod = double('module') allow(mod).to receive(:pluginfact).with("foo/bar").and_return("eh") allow(@environment).to receive(:modules).and_return([mod]) expect(@mount.find("foo/bar", @request)).to eq("eh") end end describe "when searching for files" do it "should use the node's environment to find the modules" do expect(@environment).to receive(:modules).at_least(:once).and_return([]) allow(@environment).to receive(:modulepath).and_return(["/tmp/modules"]) @mount.search("foo", @request) end it "should return modulepath if no modules can be found that have plugins" do mod = double('module') allow(mod).to receive(:pluginfacts?).and_return(false) allow(@environment).to receive(:modules).and_return([]) allow(@environment).to receive(:modulepath).and_return(["/"]) expect(@options).to receive(:[]=).with(:recurse, false) expect(@mount.search("foo/bar", @request)).to eq(["/"]) end it "should return the default search module path if no modules can be found that have plugins and modulepath is invalid" do mod = double('module') allow(mod).to receive(:pluginfacts?).and_return(false) allow(@environment).to receive(:modules).and_return([]) allow(@environment).to receive(:modulepath).and_return([]) expect(@mount.search("foo/bar", @request)).to eq([Puppet[:codedir]]) end it "should return the plugin paths for each module that has plugins" do one = double('module', :pluginfacts? => true, :plugin_fact_directory => "/one") two = double('module', :pluginfacts? => true, :plugin_fact_directory => "/two") allow(@environment).to receive(:modules).and_return([one, two]) expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two}) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount/tasks_spec.rb
spec/unit/file_serving/mount/tasks_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount/tasks' describe Puppet::FileServing::Mount::Tasks do before do @mount = Puppet::FileServing::Mount::Tasks.new("tasks") @environment = double('environment', :module => nil) @request = double('request', :environment => @environment) end describe "when finding task files" do it "should fail if no task is specified" do expect { @mount.find("", @request) }.to raise_error(/No task specified/) end it "should use the request's environment to find the module" do mod_name = 'foo' expect(@environment).to receive(:module).with(mod_name) @mount.find(mod_name, @request) end it "should use the first segment of the request's path as the module name" do expect(@environment).to receive(:module).with("foo") @mount.find("foo/bartask", @request) end it "should return nil if the module in the path doesn't exist" do expect(@environment).to receive(:module).with("foo").and_return(nil) expect(@mount.find("foo/bartask", @request)).to be_nil end it "should return the file path from the module" do mod = double('module') expect(mod).to receive(:task_file).with("bartask").and_return("mocked") expect(@environment).to receive(:module).with("foo").and_return(mod) expect(@mount.find("foo/bartask", @request)).to eq("mocked") end end describe "when searching for task files" do it "should fail if no module is specified" do expect { @mount.search("", @request) }.to raise_error(/No task specified/) end it "should use the request's environment to find the module" do mod_name = 'foo' expect(@environment).to receive(:module).with(mod_name) @mount.search(mod_name, @request) end it "should use the first segment of the request's path as the module name" do expect(@environment).to receive(:module).with("foo") @mount.search("foo/bartask", @request) end it "should return nil if the module in the path doesn't exist" do expect(@environment).to receive(:module).with("foo").and_return(nil) expect(@mount.search("foo/bartask", @request)).to be_nil end it "should return the file path from the module" do mod = double('module') expect(mod).to receive(:task_file).with("bartask").and_return("mocked") expect(@environment).to receive(:module).with("foo").and_return(mod) expect(@mount.search("foo/bartask", @request)).to eq(["mocked"]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount/scripts_spec.rb
spec/unit/file_serving/mount/scripts_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount/scripts' describe Puppet::FileServing::Mount::Scripts do before do @mount = Puppet::FileServing::Mount::Scripts.new("scripts") @environment = double('environment', :module => nil) @request = double('request', :environment => @environment) end describe "when finding files" do it "should fail if no module is specified" do expect { @mount.find("", @request) }.to raise_error(/No module specified/) end it "should use the provided environment to find the module" do expect(@environment).to receive(:module) @mount.find("foo", @request) end it "should treat the first field of the relative path as the module name" do expect(@environment).to receive(:module).with("foo") @mount.find("foo/bar/baz", @request) end it "should return nil if the specified module does not exist" do expect(@environment).to receive(:module).with("foo") @mount.find("foo/bar/baz", @request) end it "should return the file path from the module" do mod = double('module') expect(mod).to receive(:script).with("bar/baz").and_return("eh") expect(@environment).to receive(:module).with("foo").and_return(mod) expect(@mount.find("foo/bar/baz", @request)).to eq("eh") end end describe "when searching for files" do it "should fail if no module is specified" do expect { @mount.search("", @request) }.to raise_error(/No module specified/) end it "should use the node's environment to search the module" do expect(@environment).to receive(:module) @mount.search("foo", @request) end it "should treat the first field of the relative path as the module name" do expect(@environment).to receive(:module).with("foo") @mount.search("foo/bar/baz", @request) end it "should return nil if the specified module does not exist" do expect(@environment).to receive(:module).with("foo").and_return(nil) @mount.search("foo/bar/baz", @request) end it "should return the script path as an array from the module" do mod = double('module') expect(mod).to receive(:script).with("bar/baz").and_return("eh") expect(@environment).to receive(:module).with("foo").and_return(mod) expect(@mount.search("foo/bar/baz", @request)).to eq(["eh"]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount/plugins_spec.rb
spec/unit/file_serving/mount/plugins_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount/plugins' describe Puppet::FileServing::Mount::Plugins do before do @mount = Puppet::FileServing::Mount::Plugins.new("plugins") @environment = double('environment', :module => nil) @options = { :recurse => true } @request = double('request', :environment => @environment, :options => @options) end describe "when finding files" do it "should use the provided environment to find the modules" do expect(@environment).to receive(:modules).and_return([]) @mount.find("foo", @request) end it "should return nil if no module can be found with a matching plugin" do mod = double('module') allow(mod).to receive(:plugin).with("foo/bar").and_return(nil) allow(@environment).to receive(:modules).and_return([mod]) expect(@mount.find("foo/bar", @request)).to be_nil end it "should return the file path from the module" do mod = double('module') allow(mod).to receive(:plugin).with("foo/bar").and_return("eh") allow(@environment).to receive(:modules).and_return([mod]) expect(@mount.find("foo/bar", @request)).to eq("eh") end end describe "when searching for files" do it "should use the node's environment to find the modules" do expect(@environment).to receive(:modules).at_least(:once).and_return([]) allow(@environment).to receive(:modulepath).and_return(["/tmp/modules"]) @mount.search("foo", @request) end it "should return modulepath if no modules can be found that have plugins" do mod = double('module') allow(mod).to receive(:plugins?).and_return(false) allow(@environment).to receive(:modules).and_return([]) allow(@environment).to receive(:modulepath).and_return(["/"]) expect(@options).to receive(:[]=).with(:recurse, false) expect(@mount.search("foo/bar", @request)).to eq(["/"]) end it "should return the default search module path if no modules can be found that have plugins and modulepath is invalid" do mod = double('module') allow(mod).to receive(:plugins?).and_return(false) allow(@environment).to receive(:modules).and_return([]) allow(@environment).to receive(:modulepath).and_return([]) expect(@mount.search("foo/bar", @request)).to eq([Puppet[:codedir]]) end it "should return the plugin paths for each module that has plugins" do one = double('module', :plugins? => true, :plugin_directory => "/one") two = double('module', :plugins? => true, :plugin_directory => "/two") allow(@environment).to receive(:modules).and_return([one, two]) expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two}) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/mount/locales_spec.rb
spec/unit/file_serving/mount/locales_spec.rb
require 'spec_helper' require 'puppet/file_serving/mount/locales' describe Puppet::FileServing::Mount::Locales do before do @mount = Puppet::FileServing::Mount::Locales.new("locales") @environment = double('environment', :module => nil) @options = { :recurse => true } @request = double('request', :environment => @environment, :options => @options) end describe "when finding files" do it "should use the provided environment to find the modules" do expect(@environment).to receive(:modules).and_return([]) @mount.find("foo", @request) end it "should return nil if no module can be found with a matching locale" do mod = double('module') allow(mod).to receive(:locale).with("foo/bar").and_return(nil) allow(@environment).to receive(:modules).and_return([mod]) expect(@mount.find("foo/bar", @request)).to be_nil end it "should return the file path from the module" do mod = double('module') allow(mod).to receive(:locale).with("foo/bar").and_return("eh") allow(@environment).to receive(:modules).and_return([mod]) expect(@mount.find("foo/bar", @request)).to eq("eh") end end describe "when searching for files" do it "should use the node's environment to find the modules" do expect(@environment).to receive(:modules).at_least(:once).and_return([]) allow(@environment).to receive(:modulepath).and_return(["/tmp/modules"]) @mount.search("foo", @request) end it "should return modulepath if no modules can be found that have locales" do mod = double('module') allow(mod).to receive(:locales?).and_return(false) allow(@environment).to receive(:modules).and_return([]) allow(@environment).to receive(:modulepath).and_return(["/"]) expect(@options).to receive(:[]=).with(:recurse, false) expect(@mount.search("foo/bar", @request)).to eq(["/"]) end it "should return the default search module path if no modules can be found that have locales and modulepath is invalid" do mod = double('module') allow(mod).to receive(:locales?).and_return(false) allow(@environment).to receive(:modules).and_return([]) allow(@environment).to receive(:modulepath).and_return([]) expect(@mount.search("foo/bar", @request)).to eq([Puppet[:codedir]]) end it "should return the locale paths for each module that has locales" do one = double('module', :locales? => true, :locale_directory => "/one") two = double('module', :locales? => true, :locale_directory => "/two") allow(@environment).to receive(:modules).and_return([one, two]) expect(@mount.search("foo/bar", @request)).to eq(%w{/one /two}) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_serving/configuration/parser_spec.rb
spec/unit/file_serving/configuration/parser_spec.rb
require 'spec_helper' require 'puppet/file_serving/configuration/parser' module FSConfigurationParserTesting def write_config_file(content) # We want an array, but we actually want our carriage returns on all of it. File.open(@path, 'w') {|f| f.puts content} end end describe Puppet::FileServing::Configuration::Parser do include PuppetSpec::Files before :each do @path = tmpfile('fileserving_config') FileUtils.touch(@path) @parser = Puppet::FileServing::Configuration::Parser.new(@path) end describe Puppet::FileServing::Configuration::Parser, " when parsing" do include FSConfigurationParserTesting it "should allow comments" do write_config_file("# this is a comment\n") expect { @parser.parse }.not_to raise_error end it "should allow blank lines" do write_config_file("\n") expect { @parser.parse }.not_to raise_error end it "should return a hash of the created mounts" do mount1 = double('one', :validate => true) mount2 = double('two', :validate => true) expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(mount1) expect(Puppet::FileServing::Mount::File).to receive(:new).with("two").and_return(mount2) write_config_file "[one]\n[two]\n" result = @parser.parse expect(result["one"]).to equal(mount1) expect(result["two"]).to equal(mount2) end it "should only allow mount names that are alphanumeric plus dashes" do write_config_file "[a*b]\n" expect { @parser.parse }.to raise_error(ArgumentError) end it "should fail if the value for path starts with an equals sign" do write_config_file "[one]\npath = /testing" expect { @parser.parse }.to raise_error(ArgumentError) end it "should validate each created mount" do mount1 = double('one') expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(mount1) write_config_file "[one]\n" expect(mount1).to receive(:validate) @parser.parse end it "should fail if any mount does not pass validation" do mount1 = double('one') expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(mount1) write_config_file "[one]\n" expect(mount1).to receive(:validate).and_raise(RuntimeError) expect { @parser.parse }.to raise_error(RuntimeError) end it "should return comprehensible error message, if invalid line detected" do write_config_file "[one]\n\n\x01path /etc/puppetlabs/puppet/files\n\x01allow *\n" expect { @parser.parse }.to raise_error(ArgumentError, /Invalid entry at \(file: .*, line: 3\): .*/) end end describe Puppet::FileServing::Configuration::Parser, " when parsing mount attributes" do include FSConfigurationParserTesting before do @mount = double('testmount', :name => "one", :validate => true) expect(Puppet::FileServing::Mount::File).to receive(:new).with("one").and_return(@mount) end it "should set the mount path to the path attribute from that section" do write_config_file "[one]\npath /some/path\n" expect(@mount).to receive(:path=).with("/some/path") @parser.parse end [:allow,:deny].each { |acl_type| it "should ignore inline comments in #{acl_type}" do write_config_file "[one]\n#{acl_type} something \# will it work?\n" expect(@parser.parse).to eq('one' => @mount) end it "should ignore #{acl_type} from ACLs with varying spacing around commas" do write_config_file "[one]\n#{acl_type} someone,sometwo, somethree , somefour ,somefive\n" expect(@parser.parse).to eq('one' => @mount) end it "should log an error and print the location of the #{acl_type} rule" do write_config_file(<<~CONFIG) [one] #{acl_type} one CONFIG expect(Puppet).to receive(:err).with(/Entry '#{acl_type} one' is unsupported and will be ignored at \(file: .*, line: 2\)/) @parser.parse end } it "should not generate an error when parsing 'allow *'" do write_config_file "[one]\nallow *\n" expect(Puppet).to receive(:err).never @parser.parse end it "should return comprehensible error message, if failed on invalid attribute" do write_config_file "[one]\ndo something\n" expect { @parser.parse }.to raise_error(ArgumentError, /Invalid argument 'do' at \(file: .*, line: 2\)/) end end describe Puppet::FileServing::Configuration::Parser, " when parsing the modules mount" do include FSConfigurationParserTesting before do @mount = double('modulesmount', :name => "modules", :validate => true) end it "should create an instance of the Modules Mount class" do write_config_file "[modules]\n" expect(Puppet::FileServing::Mount::Modules).to receive(:new).with("modules").and_return(@mount) @parser.parse end it "should warn if a path is set" do write_config_file "[modules]\npath /some/path\n" expect(Puppet::FileServing::Mount::Modules).to receive(:new).with("modules").and_return(@mount) expect(Puppet).to receive(:warning) @parser.parse end end describe Puppet::FileServing::Configuration::Parser, " when parsing the scripts mount" do include FSConfigurationParserTesting before do @mount = double('scriptsmount', :name => "scripts", :validate => true) end it "should create an instance of the Scripts Mount class" do write_config_file "[scripts]\n" expect(Puppet::FileServing::Mount::Scripts).to receive(:new).with("scripts").and_return(@mount) @parser.parse end it "should warn if a path is set" do write_config_file "[scripts]\npath /some/path\n" expect(Puppet::FileServing::Mount::Scripts).to receive(:new).with("scripts").and_return(@mount) expect(Puppet).to receive(:warning) @parser.parse end end describe Puppet::FileServing::Configuration::Parser, " when parsing the plugins mount" do include FSConfigurationParserTesting before do @mount = double('pluginsmount', :name => "plugins", :validate => true) end it "should create an instance of the Plugins Mount class" do write_config_file "[plugins]\n" expect(Puppet::FileServing::Mount::Plugins).to receive(:new).with("plugins").and_return(@mount) @parser.parse end it "should warn if a path is set" do write_config_file "[plugins]\npath /some/path\n" expect(Puppet).to receive(:warning) @parser.parse end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/hiera/scope_spec.rb
spec/unit/hiera/scope_spec.rb
require 'spec_helper' require 'hiera/scope' require 'puppet_spec/scope' describe Hiera::Scope do include PuppetSpec::Scope let(:real) { create_test_scope_for_node("test_node") } let(:scope) { Hiera::Scope.new(real) } describe "#initialize" do it "should store the supplied puppet scope" do expect(scope.real).to eq(real) end end describe "#[]" do it "should return nil when no value is found and strict mode is off" do Puppet[:strict] = :warning expect(scope["foo"]).to eq(nil) end it "should raise error by default when no value is found" do expect { scope["foo"] }.to raise_error(/Undefined variable 'foo'/) end it "should treat '' as nil" do real["foo"] = "" expect(scope["foo"]).to eq(nil) end it "should return found data" do real["foo"] = "bar" expect(scope["foo"]).to eq("bar") end it "preserves the case of a string that is found" do real["foo"] = "CAPITAL!" expect(scope["foo"]).to eq("CAPITAL!") end it "aliases $module_name as calling_module" do real["module_name"] = "the_module" expect(scope["calling_module"]).to eq("the_module") end it "uses the name of the of the scope's class as the calling_class" do real.source = Puppet::Resource::Type.new(:hostclass, "testing", :module_name => "the_module") expect(scope["calling_class"]).to eq("testing") end it "downcases the calling_class" do real.source = Puppet::Resource::Type.new(:hostclass, "UPPER CASE", :module_name => "the_module") expect(scope["calling_class"]).to eq("upper case") end it "looks for the class which includes the defined type as the calling_class" do parent = create_test_scope_for_node("parent") real.parent = parent parent.source = Puppet::Resource::Type.new(:hostclass, "name_of_the_class_including_the_definition", :module_name => "class_module") real.source = Puppet::Resource::Type.new(:definition, "definition_name", :module_name => "definition_module") expect(scope["calling_class"]).to eq("name_of_the_class_including_the_definition") end end describe "#exist?" do it "should correctly report missing data" do real["nil_value"] = nil real["blank_value"] = "" expect(scope.exist?("nil_value")).to eq(true) expect(scope.exist?("blank_value")).to eq(true) expect(scope.exist?("missing_value")).to eq(false) end it "should always return true for calling_class and calling_module" do expect(scope.include?("calling_class")).to eq(true) expect(scope.include?("calling_class_path")).to eq(true) expect(scope.include?("calling_module")).to eq(true) end end describe "#call_function" do it "should delegate a call to call_function to the real scope" do expect(real).to receive(:call_function).once scope.call_function('some_function', [1,2,3]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/metadata_spec.rb
spec/unit/module_tool/metadata_spec.rb
require 'spec_helper' require 'puppet/module_tool' describe Puppet::ModuleTool::Metadata do let(:data) { {} } let(:metadata) { Puppet::ModuleTool::Metadata.new } describe 'property lookups' do subject { metadata } %w[ name version author summary license source project_page issues_url dependencies dashed_name release_name description data_provider].each do |prop| describe "##{prop}" do it "responds to the property" do subject.send(prop) end end end end describe "#update" do subject { metadata.update(data) } context "with a valid name" do let(:data) { { 'name' => 'billgates-mymodule' } } it "extracts the author name from the name field" do expect(subject.to_hash['author']).to eq('billgates') end it "extracts a module name from the name field" do expect(subject.module_name).to eq('mymodule') end context "and existing author" do before { metadata.update('author' => 'foo') } it "avoids overwriting the existing author" do expect(subject.to_hash['author']).to eq('foo') end end end context "with a valid name and author" do let(:data) { { 'name' => 'billgates-mymodule', 'author' => 'foo' } } it "use the author name from the author field" do expect(subject.to_hash['author']).to eq('foo') end context "and preexisting author" do before { metadata.update('author' => 'bar') } it "avoids overwriting the existing author" do expect(subject.to_hash['author']).to eq('foo') end end end context "with an invalid name" do context "(short module name)" do let(:data) { { 'name' => 'mymodule' } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name") end end context "(missing namespace)" do let(:data) { { 'name' => '/mymodule' } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name") end end context "(missing module name)" do let(:data) { { 'name' => 'namespace/' } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the field must be a namespaced module name") end end context "(invalid namespace)" do let(:data) { { 'name' => "dolla'bill$-mymodule" } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the namespace contains non-alphanumeric characters") end end context "(non-alphanumeric module name)" do let(:data) { { 'name' => "dollabils-fivedolla'" } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the module name contains non-alphanumeric (or underscore) characters") end end context "(module name starts with a number)" do let(:data) { { 'name' => "dollabills-5dollars" } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError, "Invalid 'name' field in metadata.json: the module name must begin with a letter") end end end context "with an invalid version" do let(:data) { { 'version' => '3.0' } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError, "Invalid 'version' field in metadata.json: version string cannot be parsed as a valid Semantic Version") end end context "with a valid source" do context "which is a GitHub URL" do context "with a scheme" do before { metadata.update('source' => 'https://github.com/billgates/amazingness') } it "predicts a default project_page" do expect(subject.to_hash['project_page']).to eq('https://github.com/billgates/amazingness') end it "predicts a default issues_url" do expect(subject.to_hash['issues_url']).to eq('https://github.com/billgates/amazingness/issues') end end context "without a scheme" do before { metadata.update('source' => 'github.com/billgates/amazingness') } it "predicts a default project_page" do expect(subject.to_hash['project_page']).to eq('https://github.com/billgates/amazingness') end it "predicts a default issues_url" do expect(subject.to_hash['issues_url']).to eq('https://github.com/billgates/amazingness/issues') end end end context "which is not a GitHub URL" do before { metadata.update('source' => 'https://notgithub.com/billgates/amazingness') } it "does not predict a default project_page" do expect(subject.to_hash['project_page']).to be nil end it "does not predict a default issues_url" do expect(subject.to_hash['issues_url']).to be nil end end context "which is not a URL" do before { metadata.update('source' => 'my brain') } it "does not predict a default project_page" do expect(subject.to_hash['project_page']).to be nil end it "does not predict a default issues_url" do expect(subject.to_hash['issues_url']).to be nil end end end context "with a valid dependency" do let(:data) { {'dependencies' => [{'name' => 'puppetlabs-goodmodule'}] }} it "adds the dependency" do expect(subject.dependencies.size).to eq(1) end end context "with a invalid dependency name" do let(:data) { {'dependencies' => [{'name' => 'puppetlabsbadmodule'}] }} it "raises an exception" do expect { subject }.to raise_error(ArgumentError) end end context "with a valid dependency version range" do let(:data) { {'dependencies' => [{'name' => 'puppetlabs-badmodule', 'version_requirement' => '>= 2.0.0'}] }} it "adds the dependency" do expect(subject.dependencies.size).to eq(1) end end context "with a invalid version range" do let(:data) { {'dependencies' => [{'name' => 'puppetlabsbadmodule', 'version_requirement' => '>= banana'}] }} it "raises an exception" do expect { subject }.to raise_error(ArgumentError) end end context "with duplicate dependencies" do let(:data) { {'dependencies' => [{'name' => 'puppetlabs-dupmodule', 'version_requirement' => '1.0.0'}, {'name' => 'puppetlabs-dupmodule', 'version_requirement' => '0.0.1'}] } } it "raises an exception" do expect { subject }.to raise_error(ArgumentError) end end context "adding a duplicate dependency" do let(:data) { {'dependencies' => [{'name' => 'puppetlabs-origmodule', 'version_requirement' => '1.0.0'}] }} it "with a different version raises an exception" do metadata.add_dependency('puppetlabs-origmodule', '>= 0.0.1') expect { subject }.to raise_error(ArgumentError) end it "with the same version does not add another dependency" do metadata.add_dependency('puppetlabs-origmodule', '1.0.0') expect(subject.dependencies.size).to eq(1) end end context 'with valid data_provider' do let(:data) { {'data_provider' => 'the_name'} } it 'validates the provider correctly' do expect { subject }.not_to raise_error end it 'returns the provider' do expect(subject.data_provider).to eq('the_name') end end context 'with invalid data_provider' do let(:data) { } it "raises exception unless argument starts with a letter" do expect { metadata.update('data_provider' => '_the_name') }.to raise_error(ArgumentError, /field 'data_provider' must begin with a letter/) expect { metadata.update('data_provider' => '') }.to raise_error(ArgumentError, /field 'data_provider' must begin with a letter/) end it "raises exception if argument contains non-alphanumeric characters" do expect { metadata.update('data_provider' => 'the::name') }.to raise_error(ArgumentError, /field 'data_provider' contains non-alphanumeric characters/) end it "raises exception unless argument is a string" do expect { metadata.update('data_provider' => 23) }.to raise_error(ArgumentError, /field 'data_provider' must be a string/) end end end describe '#dashed_name' do it 'returns nil in the absence of a module name' do expect(metadata.update('version' => '1.0.0').release_name).to be_nil end it 'returns a hyphenated string containing namespace and module name' do data = metadata.update('name' => 'foo-bar') expect(data.dashed_name).to eq('foo-bar') end it 'properly handles slash-separated names' do data = metadata.update('name' => 'foo/bar') expect(data.dashed_name).to eq('foo-bar') end it 'is unaffected by author name' do data = metadata.update('name' => 'foo/bar', 'author' => 'me') expect(data.dashed_name).to eq('foo-bar') end end describe '#release_name' do it 'returns nil in the absence of a module name' do expect(metadata.update('version' => '1.0.0').release_name).to be_nil end it 'returns nil in the absence of a version' do expect(metadata.update('name' => 'foo/bar').release_name).to be_nil end it 'returns a hyphenated string containing module name and version' do data = metadata.update('name' => 'foo/bar', 'version' => '1.0.0') expect(data.release_name).to eq('foo-bar-1.0.0') end it 'is unaffected by author name' do data = metadata.update('name' => 'foo/bar', 'version' => '1.0.0', 'author' => 'me') expect(data.release_name).to eq('foo-bar-1.0.0') end end describe "#to_hash" do subject { metadata.to_hash } it "contains the default set of keys" do expect(subject.keys.sort).to eq(%w[ name version author summary license source issues_url project_page dependencies data_provider].sort) end describe "['license']" do it "defaults to Apache 2" do expect(subject['license']).to eq("Apache-2.0") end end describe "['dependencies']" do it "defaults to an empty set" do expect(subject['dependencies']).to eq(Set.new) end end context "when updated with non-default data" do subject { metadata.update('license' => 'MIT', 'non-standard' => 'yup').to_hash } it "overrides the defaults" do expect(subject['license']).to eq('MIT') end it 'contains unanticipated values' do expect(subject['non-standard']).to eq('yup') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/install_directory_spec.rb
spec/unit/module_tool/install_directory_spec.rb
require 'spec_helper' require 'puppet/module_tool/install_directory' describe Puppet::ModuleTool::InstallDirectory do def expect_normal_results results = installer.run expect(results[:installed_modules].length).to eq 1 expect(results[:installed_modules][0][:module]).to eq("pmtacceptance-stdlib") expect(results[:installed_modules][0][:version][:vstring]).to eq("1.0.0") results end it "(#15202) creates the install directory" do target_dir = the_directory('foo', :directory? => false, :exist? => false) expect(target_dir).to receive(:mkpath) install = Puppet::ModuleTool::InstallDirectory.new(target_dir) install.prepare('pmtacceptance-stdlib', '1.0.0') end it "(#15202) errors when the directory is not accessible" do target_dir = the_directory('foo', :directory? => false, :exist? => false) expect(target_dir).to receive(:mkpath).and_raise(Errno::EACCES) install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error( Puppet::ModuleTool::Errors::PermissionDeniedCreateInstallDirectoryError ) end it "(#15202) errors when an entry along the path is not a directory" do target_dir = the_directory("foo/bar", :exist? => false, :directory? => false) expect(target_dir).to receive(:mkpath).and_raise(Errno::EEXIST) install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error(Puppet::ModuleTool::Errors::InstallPathExistsNotDirectoryError) end it "(#15202) simply re-raises an unknown error" do target_dir = the_directory("foo/bar", :exist? => false, :directory? => false) expect(target_dir).to receive(:mkpath).and_raise("unknown error") install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error("unknown error") end it "(#15202) simply re-raises an unknown system call error" do target_dir = the_directory("foo/bar", :exist? => false, :directory? => false) expect(target_dir).to receive(:mkpath).and_raise(SystemCallError, "unknown") install = Puppet::ModuleTool::InstallDirectory.new(target_dir) expect { install.prepare('module', '1.0.1') }.to raise_error(SystemCallError) end def the_directory(name, options) dir = double("Pathname<#{name}>") allow(dir).to receive(:exist?).and_return(options.fetch(:exist?, true)) allow(dir).to receive(:directory?).and_return(options.fetch(:directory?, true)) dir end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/tar_spec.rb
spec/unit/module_tool/tar_spec.rb
require 'spec_helper' require 'puppet/module_tool/tar' describe Puppet::ModuleTool::Tar do [ { :name => 'ObscureLinuxDistro', :win => false }, { :name => 'Windows', :win => true } ].each do |os| it "always prefers minitar if it and zlib are present, even with tar available" do allow(Facter).to receive(:value).with('os.family').and_return(os[:name]) allow(Puppet::Util).to receive(:which).with('tar').and_return('/usr/bin/tar') allow(Puppet::Util::Platform).to receive(:windows?).and_return(os[:win]) allow(Puppet).to receive(:features).and_return(double(:minitar? => true, :zlib? => true)) expect(described_class.instance).to be_a_kind_of Puppet::ModuleTool::Tar::Mini end end it "falls back to tar when minitar not present and not on Windows" do allow(Facter).to receive(:value).with('os.family').and_return('ObscureLinuxDistro') allow(Puppet::Util).to receive(:which).with('tar').and_return('/usr/bin/tar') allow(Puppet::Util::Platform).to receive(:windows?).and_return(false) allow(Puppet).to receive(:features).and_return(double(:minitar? => false)) expect(described_class.instance).to be_a_kind_of Puppet::ModuleTool::Tar::Gnu end it "fails when there is no possible implementation" do allow(Facter).to receive(:value).with('os.family').and_return('Windows') allow(Puppet::Util).to receive(:which).with('tar') allow(Puppet::Util::Platform).to receive(:windows?).and_return(true) allow(Puppet).to receive(:features).and_return(double(:minitar? => false, :zlib? => false)) expect { described_class.instance }.to raise_error RuntimeError, /No suitable tar/ end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/application_spec.rb
spec/unit/module_tool/application_spec.rb
require 'spec_helper' require 'puppet/module_tool' describe Puppet::ModuleTool::Applications::Application do describe 'app' do good_versions = %w{ 1.2.4 0.0.1 0.0.0 0.0.2-git-8-g3d316d1 0.0.3-b1 10.100.10000 0.1.2-rc1 0.1.2-dev-1 0.1.2-svn12345 0.1.2-3 } bad_versions = %w{ 0.1 0 0.1.2.3 dev 0.1.2beta } let :app do Class.new(described_class).new end good_versions.each do |ver| it "should accept version string #{ver}" do app.parse_filename("puppetlabs-ntp-#{ver}") end end bad_versions.each do |ver| it "should not accept version string #{ver}" do expect { app.parse_filename("puppetlabs-ntp-#{ver}") }.to raise_error(ArgumentError, /(Invalid version format|Could not parse filename)/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/installed_modules_spec.rb
spec/unit/module_tool/installed_modules_spec.rb
require 'spec_helper' require 'puppet/module_tool/installed_modules' require 'puppet_spec/modules' describe Puppet::ModuleTool::InstalledModules do include PuppetSpec::Files around do |example| dir = tmpdir("deep_path") FileUtils.mkdir_p(@modpath = File.join(dir, "modpath")) @env = Puppet::Node::Environment.create(:env, [@modpath]) Puppet.override(:current_environment => @env) do example.run end end it 'works when given a semantic version' do mod = PuppetSpec::Modules.create('goodsemver', @modpath, :metadata => {:version => '1.2.3'}) installed = described_class.new(@env) expect(installed.modules["puppetlabs-#{mod.name}"].version).to eq(SemanticPuppet::Version.parse('1.2.3')) end it 'defaults when not given a semantic version' do mod = PuppetSpec::Modules.create('badsemver', @modpath, :metadata => {:version => 'banana'}) expect(Puppet).to receive(:warning).with(/Semantic Version/) installed = described_class.new(@env) expect(installed.modules["puppetlabs-#{mod.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0')) end it 'defaults when not given a full semantic version' do mod = PuppetSpec::Modules.create('badsemver', @modpath, :metadata => {:version => '1.2'}) expect(Puppet).to receive(:warning).with(/Semantic Version/) installed = described_class.new(@env) expect(installed.modules["puppetlabs-#{mod.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0')) end it 'still works if there is an invalid version in one of the modules' do mod1 = PuppetSpec::Modules.create('badsemver', @modpath, :metadata => {:version => 'banana'}) mod2 = PuppetSpec::Modules.create('goodsemver', @modpath, :metadata => {:version => '1.2.3'}) mod3 = PuppetSpec::Modules.create('notquitesemver', @modpath, :metadata => {:version => '1.2'}) expect(Puppet).to receive(:warning).with(/Semantic Version/).twice installed = described_class.new(@env) expect(installed.modules["puppetlabs-#{mod1.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0')) expect(installed.modules["puppetlabs-#{mod2.name}"].version).to eq(SemanticPuppet::Version.parse('1.2.3')) expect(installed.modules["puppetlabs-#{mod3.name}"].version).to eq(SemanticPuppet::Version.parse('0.0.0')) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/tar/gnu_spec.rb
spec/unit/module_tool/tar/gnu_spec.rb
require 'spec_helper' require 'puppet/module_tool' describe Puppet::ModuleTool::Tar::Gnu, unless: Puppet::Util::Platform.windows? do let(:sourcedir) { '/space path/the/src/dir' } let(:sourcefile) { '/space path/the/module.tar.gz' } let(:destdir) { '/space path/the/dest/dir' } let(:destfile) { '/space path/the/dest/fi le.tar.gz' } let(:safe_sourcedir) { '/space\ path/the/src/dir' } let(:safe_sourcefile) { '/space\ path/the/module.tar.gz' } let(:safe_destdir) { '/space\ path/the/dest/dir' } let(:safe_destfile) { 'fi\ le.tar.gz' } it "unpacks a tar file" do expect(Puppet::Util::Execution).to receive(:execute).with("gzip -dc #{safe_sourcefile} | tar --extract --no-same-owner --directory #{safe_destdir} --file -") expect(Puppet::Util::Execution).to receive(:execute).with(['find', destdir, '-type', 'd', '-exec', 'chmod', '755', '{}', '+']) expect(Puppet::Util::Execution).to receive(:execute).with(['find', destdir, '-type', 'f', '-exec', 'chmod', 'u+rw,g+r,a-st', '{}', '+']) expect(Puppet::Util::Execution).to receive(:execute).with(['chown', '-R', '<owner:group>', destdir]) subject.unpack(sourcefile, destdir, '<owner:group>') end it "packs a tar file" do expect(Puppet::Util::Execution).to receive(:execute).with("tar cf - #{safe_sourcedir} | gzip -c > #{safe_destfile}") subject.pack(sourcedir, destfile) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/tar/mini_spec.rb
spec/unit/module_tool/tar/mini_spec.rb
require 'spec_helper' require 'puppet/module_tool' describe Puppet::ModuleTool::Tar::Mini, :if => (Puppet.features.minitar? and Puppet.features.zlib?) do let(:sourcefile) { '/the/module.tar.gz' } let(:destdir) { File.expand_path '/the/dest/dir' } let(:sourcedir) { '/the/src/dir' } let(:destfile) { '/the/dest/file.tar.gz' } let(:minitar) { described_class.new } class MockFileStatEntry def initialize(mode = 0100) @mode = mode end end it "unpacks a tar file with correct permissions" do entry = unpacks_the_entry(:file_start, 'thefile') minitar.unpack(sourcefile, destdir, 'uid') expect(entry.instance_variable_get(:@mode)).to eq(0755) end it "does not allow an absolute path" do unpacks_the_entry(:file_start, '/thefile') expect { minitar.unpack(sourcefile, destdir, 'uid') }.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError, "Attempt to install file with an invalid path into \"/thefile\" under \"#{destdir}\"") end it "does not allow a file to be written outside the destination directory" do unpacks_the_entry(:file_start, '../../thefile') expect { minitar.unpack(sourcefile, destdir, 'uid') }.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError, "Attempt to install file with an invalid path into \"#{File.expand_path('/the/thefile')}\" under \"#{destdir}\"") end it "does not allow a directory to be written outside the destination directory" do unpacks_the_entry(:dir, '../../thedir') expect { minitar.unpack(sourcefile, destdir, 'uid') }.to raise_error(Puppet::ModuleTool::Errors::InvalidPathInPackageError, "Attempt to install file with an invalid path into \"#{File.expand_path('/the/thedir')}\" under \"#{destdir}\"") end it "unpacks on Windows" do unpacks_the_entry(:file_start, 'thefile', nil) entry = minitar.unpack(sourcefile, destdir, 'uid') # Windows does not use these permissions. expect(entry.instance_variable_get(:@mode)).to eq(nil) end it "packs a tar file" do writer = double('GzipWriter') expect(Zlib::GzipWriter).to receive(:open).with(destfile).and_yield(writer) stats = {:mode => 0222} expect(Minitar).to receive(:pack).with(sourcedir, writer).and_yield(:file_start, 'abc', stats) minitar.pack(sourcedir, destfile) end it "packs a tar file on Windows" do writer = double('GzipWriter') expect(Zlib::GzipWriter).to receive(:open).with(destfile).and_yield(writer) expect(Minitar).to receive(:pack).with(sourcedir, writer). and_yield(:file_start, 'abc', {:entry => MockFileStatEntry.new(nil)}) minitar.pack(sourcedir, destfile) end def unpacks_the_entry(type, name, mode = 0100) reader = double('GzipReader') expect(Zlib::GzipReader).to receive(:open).with(sourcefile).and_yield(reader) expect(minitar).to receive(:find_valid_files).with(reader).and_return([name]) entry = MockFileStatEntry.new(mode) expect(Minitar).to receive(:unpack).with(reader, destdir, [name], {:fsync => false}). and_yield(type, name, {:entry => entry}) entry end describe "Extracts tars with long and short pathnames" do let (:sourcetar) { fixtures('module.tar.gz') } let (:longfilepath) { "puppetlabs-dsc-1.0.0/lib/puppet_x/dsc_resources/xWebAdministration/DSCResources/MSFT_xWebAppPoolDefaults/MSFT_xWebAppPoolDefaults.schema.mof" } let (:shortfilepath) { "puppetlabs-dsc-1.0.0/README.md" } it "unpacks a tar with a short path length" do extractdir = PuppetSpec::Files.tmpdir('minitar') minitar.unpack(sourcetar,extractdir,'module') expect(File).to exist(File.expand_path("#{extractdir}/#{shortfilepath}")) end it "unpacks a tar with a long path length" do extractdir = PuppetSpec::Files.tmpdir('minitar') minitar.unpack(sourcetar,extractdir,'module') expect(File).to exist(File.expand_path("#{extractdir}/#{longfilepath}")) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/applications/checksummer_spec.rb
spec/unit/module_tool/applications/checksummer_spec.rb
require 'spec_helper' require 'puppet/module_tool/applications' require 'puppet_spec/files' require 'pathname' describe Puppet::ModuleTool::Applications::Checksummer do let(:tmpdir) do Pathname.new(PuppetSpec::Files.tmpdir('checksummer')) end let(:checksums) { Puppet::ModuleTool::Checksums.new(tmpdir).data } subject do described_class.run(tmpdir) end before do File.open(tmpdir + 'README', 'w') { |f| f.puts "This is a README!" } File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changelog!" } File.open(tmpdir + 'DELETEME', 'w') { |f| f.puts "I've got a really good feeling about this!" } Dir.mkdir(tmpdir + 'pkg') File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm unimportant!" } File.open(tmpdir + 'metadata.json', 'w') { |f| f.puts '{"name": "package-name", "version": "1.0.0"}' } File.open(tmpdir + 'checksums.json', 'w') { |f| f.puts '{}' } end context 'with checksums.json' do before do File.open(tmpdir + 'checksums.json', 'w') { |f| f.puts checksums.to_json } File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" } File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" } (tmpdir + 'DELETEME').unlink end it 'reports changed files' do expect(subject).to include 'CHANGES' end it 'reports removed files' do expect(subject).to include 'DELETEME' end it 'does not report unchanged files' do expect(subject).to_not include 'README' end it 'does not report build artifacts' do expect(subject).to_not include 'pkg/build-artifact' end it 'does not report checksums.json' do expect(subject).to_not include 'checksums.json' end end context 'without checksums.json' do context 'but with metadata.json containing checksums' do before do (tmpdir + 'checksums.json').unlink File.open(tmpdir + 'metadata.json', 'w') { |f| f.puts "{\"checksums\":#{checksums.to_json}}" } File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" } File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" } (tmpdir + 'DELETEME').unlink end it 'reports changed files' do expect(subject).to include 'CHANGES' end it 'reports removed files' do expect(subject).to include 'DELETEME' end it 'does not report unchanged files' do expect(subject).to_not include 'README' end it 'does not report build artifacts' do expect(subject).to_not include 'pkg/build-artifact' end it 'does not report checksums.json' do expect(subject).to_not include 'checksums.json' end end context 'and with metadata.json that does not contain checksums' do before do (tmpdir + 'checksums.json').unlink File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" } File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" } (tmpdir + 'DELETEME').unlink end it 'fails' do expect { subject }.to raise_error(ArgumentError, 'No file containing checksums found.') end end context 'and without metadata.json' do before do (tmpdir + 'checksums.json').unlink (tmpdir + 'metadata.json').unlink File.open(tmpdir + 'CHANGES', 'w') { |f| f.puts "This is a changed log!" } File.open(tmpdir + 'pkg' + 'build-artifact', 'w') { |f| f.puts "I'm still unimportant!" } (tmpdir + 'DELETEME').unlink end it 'fails' do expect { subject }.to raise_error(ArgumentError, 'No file containing checksums found.') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/applications/uninstaller_spec.rb
spec/unit/module_tool/applications/uninstaller_spec.rb
require 'spec_helper' require 'puppet/module_tool' require 'tmpdir' require 'puppet_spec/module_tool/shared_functions' require 'puppet_spec/module_tool/stub_source' describe Puppet::ModuleTool::Applications::Uninstaller do include PuppetSpec::ModuleTool::SharedFunctions include PuppetSpec::Files before do FileUtils.mkdir_p(primary_dir) FileUtils.mkdir_p(secondary_dir) end let(:environment) do Puppet.lookup(:current_environment).override_with( :vardir => vardir, :modulepath => [ primary_dir, secondary_dir ] ) end let(:vardir) { tmpdir('uninstaller') } let(:primary_dir) { File.join(vardir, "primary") } let(:secondary_dir) { File.join(vardir, "secondary") } let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new } let(:module) { 'module-not_installed' } let(:application) do opts = options Puppet::ModuleTool.set_option_defaults(opts) Puppet::ModuleTool::Applications::Uninstaller.new(self.module, opts) end def options { :environment => environment } end subject { application.run } context "when the module is not installed" do it "should fail" do expect(subject).to include :result => :failure end end context "when the module is installed" do let(:module) { 'pmtacceptance-stdlib' } before { preinstall('pmtacceptance-stdlib', '1.0.0') } before { preinstall('pmtacceptance-apache', '0.0.4') } it "should uninstall the module" do expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib") end it "should only uninstall the requested module" do subject[:affected_modules].length == 1 end it 'should refuse to uninstall in FIPS mode' do allow(Facter).to receive(:value).with(:fips_enabled).and_return(true) err = subject[:error][:oneline] expect(err).to eq("Either the `--ignore_changes` or `--force` argument must be specified to uninstall modules when running in FIPS mode.") end context 'in two modulepaths' do before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) } it "should fail if a module exists twice in the modpath" do expect(subject).to include :result => :failure end end context "when options[:version] is specified" do def options super.merge(:version => '1.0.0') end it "should uninstall the module if the version matches" do expect(subject[:affected_modules].length).to eq(1) expect(subject[:affected_modules].first.version).to eq("1.0.0") end context 'but not matched' do def options super.merge(:version => '2.0.0') end it "should not uninstall the module if the version does not match" do expect(subject).to include :result => :failure end end end context "when the module metadata is missing" do before { File.unlink(File.join(primary_dir, 'stdlib', 'metadata.json')) } it "should not uninstall the module" do expect(application.run[:result]).to eq(:failure) end end context "when the module has local changes" do before do mark_changed(File.join(primary_dir, 'stdlib')) end it "should not uninstall the module" do expect(subject).to include :result => :failure end end context "when uninstalling the module will cause broken dependencies" do before { preinstall('pmtacceptance-apache', '0.10.0') } it "should not uninstall the module" do expect(subject).to include :result => :failure end end context 'with --ignore-changes' do def options super.merge(:ignore_changes => true) end context 'with local changes' do before do mark_changed(File.join(primary_dir, 'stdlib')) end it 'overwrites the installed module with the greatest version matching that range' do expect(subject).to include :result => :success end it 'uninstalls in FIPS mode' do allow(Facter).to receive(:value).with(:fips_enabled).and_return(true) expect(subject).to include :result => :success end end context 'without local changes' do it 'overwrites the installed module with the greatest version matching that range' do expect(subject).to include :result => :success end end end context "when using the --force flag" do def options super.merge(:force => true) end context "with local changes" do before do mark_changed(File.join(primary_dir, 'stdlib')) end it "should ignore local changes" do expect(subject[:affected_modules].length).to eq(1) expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib") end it 'uninstalls in FIPS mode' do allow(Facter).to receive(:value).with(:fips_enabled).and_return(true) expect(subject).to include :result => :success end end context "while depended upon" do before { preinstall('pmtacceptance-apache', '0.10.0') } it "should ignore broken dependencies" do expect(subject[:affected_modules].length).to eq(1) expect(subject[:affected_modules].first.forge_name).to eq("pmtacceptance/stdlib") end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/applications/unpacker_spec.rb
spec/unit/module_tool/applications/unpacker_spec.rb
require 'spec_helper' require 'puppet/util/json' require 'puppet/module_tool/applications' require 'puppet/file_system' require 'puppet_spec/modules' describe Puppet::ModuleTool::Applications::Unpacker do include PuppetSpec::Files let(:target) { tmpdir("unpacker") } let(:module_name) { 'myusername-mytarball' } let(:filename) { tmpdir("module") + "/module.tar.gz" } let(:working_dir) { tmpdir("working_dir") } before :each do allow(Puppet.settings).to receive(:[]) allow(Puppet.settings).to receive(:[]).with(:module_working_dir).and_return(working_dir) end it "should attempt to untar file to temporary location" do untar = double('Tar') expect(untar).to receive(:unpack).with(filename, anything, anything) do |src, dest, _| FileUtils.mkdir(File.join(dest, 'extractedmodule')) File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file| file.puts Puppet::Util::Json.dump('name' => module_name, 'version' => '1.0.0') end true end expect(Puppet::ModuleTool::Tar).to receive(:instance).and_return(untar) Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target) expect(File).to be_directory(File.join(target, 'mytarball')) end it "should warn about symlinks", :if => Puppet.features.manages_symlinks? do untar = double('Tar') expect(untar).to receive(:unpack).with(filename, anything, anything) do |src, dest, _| FileUtils.mkdir(File.join(dest, 'extractedmodule')) File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file| file.puts Puppet::Util::Json.dump('name' => module_name, 'version' => '1.0.0') end FileUtils.touch(File.join(dest, 'extractedmodule/tempfile')) Puppet::FileSystem.symlink(File.join(dest, 'extractedmodule/tempfile'), File.join(dest, 'extractedmodule/tempfile2')) true end expect(Puppet::ModuleTool::Tar).to receive(:instance).and_return(untar) expect(Puppet).to receive(:warning).with(/symlinks/i) Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target) expect(File).to be_directory(File.join(target, 'mytarball')) end it "should warn about symlinks in subdirectories", :if => Puppet.features.manages_symlinks? do untar = double('Tar') expect(untar).to receive(:unpack).with(filename, anything, anything) do |src, dest, _| FileUtils.mkdir(File.join(dest, 'extractedmodule')) File.open(File.join(dest, 'extractedmodule', 'metadata.json'), 'w+') do |file| file.puts Puppet::Util::Json.dump('name' => module_name, 'version' => '1.0.0') end FileUtils.mkdir(File.join(dest, 'extractedmodule/manifests')) FileUtils.touch(File.join(dest, 'extractedmodule/manifests/tempfile')) Puppet::FileSystem.symlink(File.join(dest, 'extractedmodule/manifests/tempfile'), File.join(dest, 'extractedmodule/manifests/tempfile2')) true end expect(Puppet::ModuleTool::Tar).to receive(:instance).and_return(untar) expect(Puppet).to receive(:warning).with(/symlinks/i) Puppet::ModuleTool::Applications::Unpacker.run(filename, :target_dir => target) expect(File).to be_directory(File.join(target, 'mytarball')) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/applications/installer_spec.rb
spec/unit/module_tool/applications/installer_spec.rb
require 'spec_helper' require 'puppet/module_tool/applications' require 'puppet_spec/module_tool/shared_functions' require 'puppet_spec/module_tool/stub_source' require 'tmpdir' describe Puppet::ModuleTool::Applications::Installer, :unless => RUBY_PLATFORM == 'java' do include PuppetSpec::ModuleTool::SharedFunctions include PuppetSpec::Files include PuppetSpec::Fixtures before do FileUtils.mkdir_p(primary_dir) FileUtils.mkdir_p(secondary_dir) end let(:vardir) { tmpdir('installer') } let(:primary_dir) { File.join(vardir, "primary") } let(:secondary_dir) { File.join(vardir, "secondary") } let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new } let(:install_dir) do dir = double("Puppet::ModuleTool::InstallDirectory") allow(dir).to receive(:prepare) allow(dir).to receive(:target).and_return(primary_dir) dir end before do SemanticPuppet::Dependency.clear_sources allow_any_instance_of(Puppet::ModuleTool::Applications::Installer).to receive(:module_repository).and_return(remote_source) end if Puppet::Util::Platform.windows? before :each do Puppet[:module_working_dir] = tmpdir('module_tool_install').gsub('/', '\\') end end def installer(modname, target_dir, options) Puppet::ModuleTool.set_option_defaults(options) Puppet::ModuleTool::Applications::Installer.new(modname, target_dir, options) end let(:environment) do Puppet.lookup(:current_environment).override_with( :vardir => vardir, :modulepath => [ primary_dir, secondary_dir ] ) end context '#run' do let(:module) { 'pmtacceptance-stdlib' } def options { :environment => environment } end let(:application) { installer(self.module, install_dir, options) } subject { application.run } it 'installs the specified module' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0') end it 'reports a meaningful error if the name is invalid' do app = installer('ntp', install_dir, options) results = app.run expect(results).to include :result => :failure expect(results[:error][:oneline]).to eq("Could not install 'ntp', did you mean 'puppetlabs-ntp'?") expect(results[:error][:multiline]).to eq(<<~END.chomp) Could not install module 'ntp' The name 'ntp' is invalid Did you mean `puppet module install puppetlabs-ntp`? END end context 'with a tarball file' do let(:module) { fixtures('stdlib.tgz') } it 'installs the specified tarball' do expect(subject).to include :result => :success graph_should_include 'puppetlabs-stdlib', nil => v('3.2.0') end context 'with --ignore-dependencies' do def options super.merge(:ignore_dependencies => true) end it 'installs the specified tarball' do expect(remote_source).not_to receive(:fetch) expect(subject).to include :result => :success graph_should_include 'puppetlabs-stdlib', nil => v('3.2.0') end end context 'with dependencies' do let(:module) { fixtures('java.tgz') } it 'installs the specified tarball' do expect(subject).to include :result => :success graph_should_include 'puppetlabs-java', nil => v('1.0.0') graph_should_include 'puppetlabs-stdlib', nil => v('4.1.0') end context 'with --ignore-dependencies' do def options super.merge(:ignore_dependencies => true) end it 'installs the specified tarball without dependencies' do expect(remote_source).not_to receive(:fetch) expect(subject).to include :result => :success graph_should_include 'puppetlabs-java', nil => v('1.0.0') graph_should_include 'puppetlabs-stdlib', nil end end end end context 'with dependencies' do let(:module) { 'pmtacceptance-apache' } it 'installs the specified module and its dependencies' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', nil => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0') end context 'and using --ignore_dependencies' do def options super.merge(:ignore_dependencies => true) end it 'installs only the specified module' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', nil => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', nil end end context 'that are already installed' do context 'and satisfied' do before { preinstall('pmtacceptance-stdlib', '4.1.0') } it 'installs only the specified module' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', nil => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', :path => primary_dir end context '(outdated but suitable version)' do before { preinstall('pmtacceptance-stdlib', '2.4.0') } it 'installs only the specified module' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', nil => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', v('2.4.0') => v('2.4.0'), :path => primary_dir end end context '(outdated and unsuitable version)' do before { preinstall('pmtacceptance-stdlib', '1.0.0') } it 'installs a version that is compatible with the installed dependencies' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', nil => v('0.0.4') graph_should_include 'pmtacceptance-stdlib', nil end end end context 'but not satisfied' do let(:module) { 'pmtacceptance-keystone' } def options super.merge(:version => '2.0.0') end before { preinstall('pmtacceptance-mysql', '2.1.0') } it 'installs only the specified module' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-keystone', nil => v('2.0.0') graph_should_include 'pmtacceptance-mysql', v('2.1.0') => v('2.1.0') graph_should_include 'pmtacceptance-stdlib', nil end end end context 'that are already installed in other modulepath directories' do before { preinstall('pmtacceptance-stdlib', '1.0.0', :into => secondary_dir) } let(:module) { 'pmtacceptance-apache' } context 'without dependency updates' do it 'installs the module only' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', nil => v('0.0.4') graph_should_include 'pmtacceptance-stdlib', nil end end context 'with dependency updates' do before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) } it 'installs the module and upgrades dependencies in-place' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', nil => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0'), :path => secondary_dir end end end end context 'with a specified' do context 'version' do def options super.merge(:version => '3.0.0') end it 'installs the specified release (or a prerelease thereof)' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', nil => v('3.0.0') end end context 'version range' do def options super.merge(:version => '3.x') end it 'installs the greatest available version matching that range' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', nil => v('3.2.0') end end end context 'when depended upon' do before { preinstall('pmtacceptance-keystone', '2.1.0') } let(:module) { 'pmtacceptance-mysql' } it 'installs the greatest available version meeting the dependency constraints' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-mysql', nil => v('0.9.0') end context 'with a --version that can satisfy' do def options super.merge(:version => '0.8.0') end it 'installs the greatest available version satisfying both constraints' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-mysql', nil => v('0.8.0') end context 'with an already installed dependency' do before { preinstall('pmtacceptance-stdlib', '2.6.0') } def options super.merge(:version => '0.7.0') end it 'installs given version without errors and does not change version of dependency' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-mysql', nil => v('0.7.0') expect(subject[:error]).to be_nil graph_should_include 'pmtacceptance-stdlib', v('2.6.0') => v('2.6.0') end end end context 'with a --version that cannot satisfy' do def options super.merge(:version => '> 1.0.0') end it 'fails to install, since there is no version that can satisfy both constraints' do expect(subject).to include :result => :failure end context 'with unsatisfiable dependencies' do let(:graph) { double(SemanticPuppet::Dependency::Graph, :modules => ['pmtacceptance-mysql']) } let(:exception) { SemanticPuppet::Dependency::UnsatisfiableGraph.new(graph, constraint) } before do allow(SemanticPuppet::Dependency).to receive(:resolve).and_raise(exception) end context 'with known constraint' do let(:constraint) { 'pmtacceptance-mysql' } it 'prints a detailed error containing the modules that would not be satisfied' do expect(subject[:error]).to include(:multiline) expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (> 1.0.0)") expect(subject[:error][:multiline]).to include("The requested version cannot satisfy one or more of the following installed modules:") expect(subject[:error][:multiline]).to include("pmtacceptance-keystone, expects 'pmtacceptance-mysql': >=0.6.1 <1.0.0") expect(subject[:error][:multiline]).to include("Use `puppet module install 'pmtacceptance-mysql' --ignore-dependencies` to install only this module") end end context 'with missing constraint' do let(:constraint) { nil } it 'prints the generic error message' do expect(subject[:error]).to include(:multiline) expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (> 1.0.0)") expect(subject[:error][:multiline]).to include("The requested version cannot satisfy all dependencies") end end context 'with unknown constraint' do let(:constraint) { 'another' } it 'prints the generic error message' do expect(subject[:error]).to include(:multiline) expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (> 1.0.0)") expect(subject[:error][:multiline]).to include("The requested version cannot satisfy all dependencies") end end end context 'with --ignore-dependencies' do def options super.merge(:ignore_dependencies => true) end it 'fails to install, since ignore_dependencies should still respect dependencies from installed modules' do expect(subject).to include :result => :failure end end context 'with --force' do def options super.merge(:force => true) end it 'installs the greatest available version, ignoring dependencies' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-mysql', nil => v('2.1.0') end end context 'with an already installed dependency' do let(:graph) { double(SemanticPuppet::Dependency::Graph, :dependencies => { 'pmtacceptance-mysql' => { :version => '2.1.0' } }, :modules => ['pmtacceptance-mysql'], :unsatisfied => 'pmtacceptance-stdlib' ) } let(:unsatisfiable_graph_exception) { SemanticPuppet::Dependency::UnsatisfiableGraph.new(graph) } before do allow(SemanticPuppet::Dependency).to receive(:resolve).and_raise(unsatisfiable_graph_exception) allow(unsatisfiable_graph_exception).to receive(:respond_to?).and_return(true) allow(unsatisfiable_graph_exception).to receive(:unsatisfied).and_return(graph.unsatisfied) preinstall('pmtacceptance-stdlib', '2.6.0') end def options super.merge(:version => '2.1.0') end it 'fails to install and outputs a multiline error containing the versions, expectations and workaround' do expect(subject).to include :result => :failure expect(subject[:error]).to include(:multiline) expect(subject[:error][:multiline]).to include("Could not install module 'pmtacceptance-mysql' (v2.1.0)") expect(subject[:error][:multiline]).to include("The requested version cannot satisfy one or more of the following installed modules:") expect(subject[:error][:multiline]).to include("pmtacceptance-stdlib, installed: 2.6.0, expected: >= 2.2.1") expect(subject[:error][:multiline]).to include("Use `puppet module install 'pmtacceptance-mysql' --ignore-dependencies` to install only this module") end end end end context 'when already installed' do before { preinstall('pmtacceptance-stdlib', '1.0.0') } context 'but matching the requested version' do it 'does nothing, since the installed version satisfies' do expect(subject).to include :result => :noop end context 'with --force' do def options super.merge(:force => true) end it 'does reinstall the module' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0') end end context 'with local changes' do before do release = application.send(:installed_modules)['pmtacceptance-stdlib'] mark_changed(release.mod.path) end it 'does nothing, since local changes do not affect that' do expect(subject).to include :result => :noop end context 'with --force' do def options super.merge(:force => true) end it 'does reinstall the module, since --force ignores local changes' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0') end end end end context 'but not matching the requested version' do def options super.merge(:version => '2.x') end it 'fails to install the module, since it is already installed' do expect(subject).to include :result => :failure expect(subject[:error]).to include :oneline => "'pmtacceptance-stdlib' (v2.x) requested; 'pmtacceptance-stdlib' (v1.0.0) already installed" end context 'with --force' do def options super.merge(:force => true) end it 'installs the greatest version matching the new version range' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('2.6.0') end end end end context 'when a module with the same name is already installed' do let(:module) { 'pmtacceptance-stdlib' } before { preinstall('puppetlabs-stdlib', '4.1.0') } it 'fails to install, since two modules with the same name cannot be installed simultaneously' do expect(subject).to include :result => :failure end context 'using --force' do def options super.merge(:force => true) end it 'overwrites the existing module with the greatest version of the requested module' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0') end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool/applications/upgrader_spec.rb
spec/unit/module_tool/applications/upgrader_spec.rb
require 'spec_helper' require 'puppet/module_tool/applications' require 'puppet_spec/module_tool/shared_functions' require 'puppet_spec/module_tool/stub_source' require 'tmpdir' describe Puppet::ModuleTool::Applications::Upgrader do include PuppetSpec::ModuleTool::SharedFunctions include PuppetSpec::Files before do FileUtils.mkdir_p(primary_dir) FileUtils.mkdir_p(secondary_dir) end let(:vardir) { tmpdir('upgrader') } let(:primary_dir) { File.join(vardir, "primary") } let(:secondary_dir) { File.join(vardir, "secondary") } let(:remote_source) { PuppetSpec::ModuleTool::StubSource.new } let(:environment) do Puppet.lookup(:current_environment).override_with( :vardir => vardir, :modulepath => [ primary_dir, secondary_dir ] ) end before do SemanticPuppet::Dependency.clear_sources allow_any_instance_of(Puppet::ModuleTool::Applications::Upgrader).to receive(:module_repository).and_return(remote_source) end if Puppet::Util::Platform.windows? before :each do allow(Puppet.settings).to receive(:[]) allow(Puppet.settings).to receive(:[]).with(:module_working_dir).and_return(Dir.mktmpdir('upgradertmp')) end end def upgrader(name, options = {}) Puppet::ModuleTool.set_option_defaults(options) Puppet::ModuleTool::Applications::Upgrader.new(name, options) end describe '#run' do let(:module) { 'pmtacceptance-stdlib' } def options { :environment => environment } end let(:application) { upgrader(self.module, options) } subject { application.run } it 'fails if the module is not already installed' do expect(subject).to include :result => :failure expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}'; module is not installed" end context 'for an installed module' do context 'with only one version' do before { preinstall('puppetlabs-oneversion', '0.0.1') } let(:module) { 'puppetlabs-oneversion' } it 'declines to upgrade' do expect(subject).to include :result => :noop expect(subject[:error][:multiline]).to match(/already the latest version/) end end context 'without dependencies' do before { preinstall('pmtacceptance-stdlib', '1.0.0') } context 'without options' do it 'properly upgrades the module to the greatest version' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0') end end context 'with version range' do def options super.merge(:version => '3.x') end context 'not matching the installed version' do it 'properly upgrades the module to the greatest version within that range' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('3.2.0') end end context 'matching the installed version' do context 'with more recent version' do before { preinstall('pmtacceptance-stdlib', '3.0.0')} it 'properly upgrades the module to the greatest version within that range' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('3.0.0') => v('3.2.0') end end context 'without more recent version' do before { preinstall('pmtacceptance-stdlib', '3.2.0')} context 'without options' do it 'declines to upgrade' do expect(subject).to include :result => :noop expect(subject[:error][:multiline]).to match(/already the latest version/) end end context 'with --force' do def options super.merge(:force => true) end it 'overwrites the installed module with the greatest version matching that range' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('3.2.0') => v('3.2.0') end end end end end end context 'that is depended upon' do # pmtacceptance-keystone depends on pmtacceptance-mysql >=0.6.1 <1.0.0 before { preinstall('pmtacceptance-keystone', '2.1.0') } before { preinstall('pmtacceptance-mysql', '0.9.0') } let(:module) { 'pmtacceptance-mysql' } context 'and out of date' do before { preinstall('pmtacceptance-mysql', '0.8.0') } it 'properly upgrades to the greatest version matching the dependency' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-mysql', v('0.8.0') => v('0.9.0') end end context 'and up to date' do it 'declines to upgrade' do expect(subject).to include :result => :failure end end context 'when specifying a violating version range' do def options super.merge(:version => '2.1.0') end it 'fails to upgrade the module' do # TODO: More helpful error message? expect(subject).to include :result => :failure expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}' (v0.9.0 -> v2.1.0); no version satisfies all dependencies" end context 'using --force' do def options super.merge(:force => true) end it 'overwrites the installed module with the specified version' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-mysql', v('0.9.0') => v('2.1.0') end end end end context 'with local changes' do before { preinstall('pmtacceptance-stdlib', '1.0.0') } before do release = application.send(:installed_modules)['pmtacceptance-stdlib'] mark_changed(release.mod.path) end it 'fails to upgrade' do expect(subject).to include :result => :failure expect(subject[:error]).to include :oneline => "Could not upgrade '#{self.module}'; module has had changes made locally" end context 'with --ignore-changes' do def options super.merge(:ignore_changes => true) end it 'overwrites the installed module with the greatest version matching that range' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-stdlib', v('1.0.0') => v('4.1.0') end end end context 'with dependencies' do context 'that are unsatisfied' do def options super.merge(:version => '0.1.1') end before { preinstall('pmtacceptance-apache', '0.0.3') } let(:module) { 'pmtacceptance-apache' } it 'upgrades the module and installs the missing dependencies' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.1.1') graph_should_include 'pmtacceptance-stdlib', nil => v('4.1.0'), :action => :install end end context 'with older major versions' do # pmtacceptance-apache 0.0.4 has no dependency on pmtacceptance-stdlib # the next available version (0.1.1) and all subsequent versions depend on pmtacceptance-stdlib >= 2.2.1 before { preinstall('pmtacceptance-apache', '0.0.3') } before { preinstall('pmtacceptance-stdlib', '1.0.0') } let(:module) { 'pmtacceptance-apache' } it 'refuses to upgrade the installed dependency to a new major version, but upgrades the module to the greatest compatible version' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.0.4') end context 'using --ignore_dependencies' do def options super.merge(:ignore_dependencies => true) end it 'upgrades the module to the greatest available version' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0') end end end context 'with satisfying major versions' do before { preinstall('pmtacceptance-apache', '0.0.3') } before { preinstall('pmtacceptance-stdlib', '2.0.0') } let(:module) { 'pmtacceptance-apache' } it 'upgrades the module and its dependencies to their greatest compatible versions' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0') end end context 'with satisfying versions' do before { preinstall('pmtacceptance-apache', '0.0.3') } before { preinstall('pmtacceptance-stdlib', '2.4.0') } let(:module) { 'pmtacceptance-apache' } it 'upgrades the module to the greatest available version' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', nil end end context 'with current versions' do before { preinstall('pmtacceptance-apache', '0.0.3') } before { preinstall('pmtacceptance-stdlib', '2.6.0') } let(:module) { 'pmtacceptance-apache' } it 'upgrades the module to the greatest available version' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', nil end end context 'with shared dependencies' do # bacula 0.0.3 depends on stdlib >= 2.2.0 and pmtacceptance/mysql >= 1.0.0 # bacula 0.0.2 depends on stdlib >= 2.2.0 and pmtacceptance/mysql >= 0.0.1 # bacula 0.0.1 depends on stdlib >= 2.2.0 # keystone 2.1.0 depends on pmtacceptance/stdlib >= 2.5.0 and pmtacceptance/mysql >=0.6.1 <1.0.0 before { preinstall('pmtacceptance-bacula', '0.0.1') } before { preinstall('pmtacceptance-mysql', '0.9.0') } before { preinstall('pmtacceptance-keystone', '2.1.0') } let(:module) { 'pmtacceptance-bacula' } it 'upgrades the module to the greatest version compatible with all other installed modules' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-bacula', v('0.0.1') => v('0.0.2') end context 'using --force' do def options super.merge(:force => true) end it 'upgrades the module to the greatest version available' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-bacula', v('0.0.1') => v('0.0.3') end end end context 'in other modulepath directories' do before { preinstall('pmtacceptance-apache', '0.0.3') } before { preinstall('pmtacceptance-stdlib', '1.0.0', :into => secondary_dir) } let(:module) { 'pmtacceptance-apache' } context 'with older major versions' do it 'upgrades the module to the greatest version compatible with the installed modules' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.0.4') graph_should_include 'pmtacceptance-stdlib', nil end end context 'with satisfying major versions' do before { preinstall('pmtacceptance-stdlib', '2.0.0', :into => secondary_dir) } it 'upgrades the module and its dependencies to their greatest compatible versions, in-place' do expect(subject).to include :result => :success graph_should_include 'pmtacceptance-apache', v('0.0.3') => v('0.10.0') graph_should_include 'pmtacceptance-stdlib', v('2.0.0') => v('2.6.0'), :path => secondary_dir end end end end end context 'when in FIPS mode...' do it 'module unpgrader refuses to run' do allow(Facter).to receive(:value).with(:fips_enabled).and_return(true) expect { application.run }.to raise_error(/Module upgrade is prohibited in FIPS mode/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/agent/disabler_spec.rb
spec/unit/agent/disabler_spec.rb
require 'spec_helper' require 'puppet/agent' require 'puppet/agent/locker' class DisablerTester include Puppet::Agent::Disabler end describe Puppet::Agent::Disabler do before do @disabler = DisablerTester.new end ## These tests are currently very implementation-specific, and they rely heavily on ## having access to the "disable_lockfile" method. However, I've made this method private ## because it really shouldn't be exposed outside of our implementation... therefore ## these tests have to use a lot of ".send" calls. They should probably be cleaned up ## but for the moment I wanted to make sure not to lose any of the functionality of ## the tests. --cprice 2012-04-16 it "should use an JsonLockfile instance as its disable_lockfile" do expect(@disabler.send(:disable_lockfile)).to be_instance_of(Puppet::Util::JsonLockfile) end it "should use puppet's :agent_disabled_lockfile' setting to determine its lockfile path" do lockfile = File.expand_path("/my/lock.disabled") Puppet[:agent_disabled_lockfile] = lockfile lock = Puppet::Util::JsonLockfile.new(lockfile) expect(Puppet::Util::JsonLockfile).to receive(:new).with(lockfile).and_return(lock) @disabler.send(:disable_lockfile) end it "should reuse the same lock file each time" do expect(@disabler.send(:disable_lockfile)).to equal(@disabler.send(:disable_lockfile)) end it "should lock the file when disabled" do expect(@disabler.send(:disable_lockfile)).to receive(:lock) @disabler.disable end it "should unlock the file when enabled" do expect(@disabler.send(:disable_lockfile)).to receive(:unlock) @disabler.enable end it "should check the lock if it is disabled" do expect(@disabler.send(:disable_lockfile)).to receive(:locked?) @disabler.disabled? end it "should report the disable message when disabled" do Puppet[:agent_disabled_lockfile] = PuppetSpec::Files.tmpfile("lock") msg = "I'm busy, go away" @disabler.disable(msg) expect(@disabler.disable_message).to eq(msg) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/agent/locker_spec.rb
spec/unit/agent/locker_spec.rb
require 'spec_helper' require 'puppet/agent' require 'puppet/agent/locker' class LockerTester include Puppet::Agent::Locker end describe Puppet::Agent::Locker do before do @locker = LockerTester.new end ## These tests are currently very implementation-specific, and they rely heavily on ## having access to the lockfile object. However, I've made this method private ## because it really shouldn't be exposed outside of our implementation... therefore ## these tests have to use a lot of ".send" calls. They should probably be cleaned up ## but for the moment I wanted to make sure not to lose any of the functionality of ## the tests. --cprice 2012-04-16 it "should use a Pidlock instance as its lockfile" do expect(@locker.send(:lockfile)).to be_instance_of(Puppet::Util::Pidlock) end it "should use puppet's agent_catalog_run_lockfile' setting to determine its lockfile path" do lockfile = File.expand_path("/my/lock") Puppet[:agent_catalog_run_lockfile] = lockfile lock = Puppet::Util::Pidlock.new(lockfile) expect(Puppet::Util::Pidlock).to receive(:new).with(lockfile).and_return(lock) @locker.send(:lockfile) end it "#lockfile_path provides the path to the lockfile" do lockfile = File.expand_path("/my/lock") Puppet[:agent_catalog_run_lockfile] = lockfile expect(@locker.lockfile_path).to eq(File.expand_path("/my/lock")) end it "should reuse the same lock file each time" do expect(@locker.send(:lockfile)).to equal(@locker.send(:lockfile)) end it "should have a method that yields when a lock is attained" do expect(@locker.send(:lockfile)).to receive(:lock).and_return(true) yielded = false @locker.lock do yielded = true end expect(yielded).to be_truthy end it "should return the block result when the lock method successfully locked" do expect(@locker.send(:lockfile)).to receive(:lock).and_return(true) expect(@locker.lock { :result }).to eq(:result) end it "should raise LockError when the lock method does not receive the lock" do expect(@locker.send(:lockfile)).to receive(:lock).and_return(false) expect { @locker.lock {} }.to raise_error(Puppet::LockError) end it "should not yield when the lock method does not receive the lock" do expect(@locker.send(:lockfile)).to receive(:lock).and_return(false) yielded = false expect { @locker.lock { yielded = true } }.to raise_error(Puppet::LockError) expect(yielded).to be_falsey end it "should not unlock when a lock was not received" do expect(@locker.send(:lockfile)).to receive(:lock).and_return(false) expect(@locker.send(:lockfile)).not_to receive(:unlock) expect { @locker.lock {} }.to raise_error(Puppet::LockError) end it "should unlock after yielding upon obtaining a lock" do allow(@locker.send(:lockfile)).to receive(:lock).and_return(true) expect(@locker.send(:lockfile)).to receive(:unlock) @locker.lock {} end it "should unlock after yielding upon obtaining a lock, even if the block throws an exception" do allow(@locker.send(:lockfile)).to receive(:lock).and_return(true) expect(@locker.send(:lockfile)).to receive(:unlock) expect { @locker.lock { raise "foo" } }.to raise_error(RuntimeError) end it "should be considered running if the lockfile is locked" do expect(@locker.send(:lockfile)).to receive(:locked?).and_return(true) expect(@locker).to be_running end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/generate_spec.rb
spec/unit/face/generate_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/face' describe Puppet::Face[:generate, :current] do include PuppetSpec::Files let(:genface) { Puppet::Face[:generate, :current] } # * Format is 'pcore' by default # * Format is accepted as 'pcore' # * Any format expect 'pcore' is an error # * Produces output to '<envroot>/.resource_types' # * Produces all types found on the module path (that are not in puppet core) # * Output files match input # * Removes files for which there is no input # * Updates a pcore file if it is out of date # * The --force flag overwrite the output even if it is up to date # * Environment is set with --environment (setting) (not tested explicitly) # Writes output for: # - isomorphic # - parameters # - properties # - title patterns # - type information is written when the type is X, Y, or Z # # Additional features # - blacklist? whitelist? types to exclude/include # - generate one resource type (somewhere on modulepath) # - output to directory of choice # - clean, clean the output directory (similar to force) # [:types].each do |action| it { is_expected.to be_action(action) } it { is_expected.to respond_to(action) } end context "when used from an interactive terminal" do before :each do from_an_interactive_terminal end context "in an environment with two modules containing resource types" do let(:dir) do dir_containing('environments', { 'testing_generate' => { 'environment.conf' => "modulepath = modules", 'manifests' => { 'site.pp' => "" }, 'modules' => { 'm1' => { 'lib' => { 'puppet' => { 'type' => { 'test1.rb' => <<-EOF module Puppet Type.newtype(:test1) do @doc = "Docs for resource" newproperty(:message) do desc "Docs for 'message' property" end newparam(:name) do desc "Docs for 'name' parameter" isnamevar end end; end EOF } } }, }, 'm2' => { 'lib' => { 'puppet' => { 'type' => { 'test2.rb' => <<-EOF module Puppet Type.newtype(:test2) do @doc = "Docs for resource" newproperty(:message) do desc "Docs for 'message' property" end newparam(:name) do desc "Docs for 'name' parameter" isnamevar end end;end EOF } } }, } }}}) end let(:modulepath) do File.join(dir, 'testing_generate', 'modules') end let(:m1) do File.join(modulepath, 'm1') end let(:m2) do File.join(modulepath, 'm2') end let(:outputdir) do File.join(dir, 'testing_generate', '.resource_types') end around(:each) do |example| Puppet.settings.initialize_global_settings Puppet[:manifest] = '' loader = Puppet::Environments::Directories.new(dir, []) Puppet.override(:environments => loader) do Puppet.override(:current_environment => loader.get('testing_generate')) do example.run end end end it 'error if format is given as something other than pcore' do expect { genface.types(:format => 'json') }.to raise_exception(ArgumentError, /'json' is not a supported format for type generation/) end it 'accepts --format pcore as a format' do expect { genface.types(:format => 'pcore') }.not_to raise_error end it 'sets pcore as the default format' do expect(Puppet::Generate::Type).to receive(:find_inputs).with(:pcore).and_return([]) genface.types() end it 'finds all files to generate types for' do # using expects and returning what the side effect should have been # (There is no way to call the original when mocking expected parameters). input1 = Puppet::Generate::Type::Input.new(m1, File.join(m1, 'lib', 'puppet', 'type', 'test1.rb'), :pcore) input2 = Puppet::Generate::Type::Input.new(m1, File.join(m2, 'lib', 'puppet', 'type', 'test2.rb'), :pcore) expect(Puppet::Generate::Type::Input).to receive(:new).with(m1, File.join(m1, 'lib', 'puppet', 'type', 'test1.rb'), :pcore).and_return(input1) expect(Puppet::Generate::Type::Input).to receive(:new).with(m2, File.join(m2, 'lib', 'puppet', 'type', 'test2.rb'), :pcore).and_return(input2) genface.types end it 'creates output directory <env>/.resource_types/ if it does not exist' do expect(Puppet::FileSystem.exist?(outputdir)).to be(false) genface.types expect(Puppet::FileSystem.dir_exist?(outputdir)).to be(true) end it 'creates output with matching names for each input' do expect(Puppet::FileSystem.exist?(outputdir)).to be(false) genface.types children = Puppet::FileSystem.children(outputdir).map {|p| Puppet::FileSystem.basename_string(p) } expect(children.sort).to eql(['test1.pp', 'test2.pp']) end it 'tolerates that <env>/.resource_types/ directory exists' do Puppet::FileSystem.mkpath(outputdir) expect(Puppet::FileSystem.exist?(outputdir)).to be(true) genface.types expect(Puppet::FileSystem.dir_exist?(outputdir)).to be(true) end it 'errors if <env>/.resource_types exists and is not a directory' do expect(Puppet::FileSystem.exist?(outputdir)).to be(false) # assert it is not already there Puppet::FileSystem.touch(outputdir) expect(Puppet::FileSystem.exist?(outputdir)).to be(true) expect(Puppet::FileSystem.directory?(outputdir)).to be(false) expect { genface.types }.to raise_error(ArgumentError, /The output directory '#{outputdir}' exists and is not a directory/) end it 'does not overwrite if files exists and are up to date' do # create them (first run) genface.types stats_before = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))] # generate again genface.types stats_after = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))] expect(stats_before <=> stats_after).to be(0) end it 'overwrites if files exists that are not up to date while keeping up to date files' do # create them (first run) genface.types stats_before = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))] # fake change in input test1 - sorry about the sleep (which there was a better way to change the modtime sleep(1) Puppet::FileSystem.touch(File.join(m1, 'lib', 'puppet', 'type', 'test1.rb')) # generate again genface.types # assert that test1 was overwritten (later) but not test2 (same time) stats_after = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))] expect(stats_before[1] <=> stats_after[1]).to be(0) expect(stats_before[0] <=> stats_after[0]).to be(-1) end it 'overwrites all files when called with --force' do # create them (first run) genface.types stats_before = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))] # generate again sleep(1) # sorry, if there is no delay the stats will be the same genface.types(:force => true) stats_after = [Puppet::FileSystem.stat(File.join(outputdir, 'test1.pp')), Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp'))] expect(stats_before <=> stats_after).to be(-1) end it 'removes previously generated files from output when there is no input for it' do # create them (first run) genface.types stat_before = Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp')) # remove input Puppet::FileSystem.unlink(File.join(m1, 'lib', 'puppet', 'type', 'test1.rb')) # generate again genface.types # assert that test1 was deleted but not test2 (same time) expect(Puppet::FileSystem.exist?(File.join(outputdir, 'test1.pp'))).to be(false) stats_after = Puppet::FileSystem.stat(File.join(outputdir, 'test2.pp')) expect(stat_before <=> stats_after).to be(0) end end context "in an environment with a faulty type" do let(:dir) do dir_containing('environments', { 'testing_generate2' => { 'environment.conf' => "modulepath = modules", 'manifests' => { 'site.pp' => "" }, 'modules' => { 'm3' => { 'lib' => { 'puppet' => { 'type' => { 'test3.rb' => <<-EOF module Puppet Type.newtype(:test3) do @doc = "Docs for resource" def self.title_patterns identity = lambda {|x| x} [ [ /^(.*)_(.*)$/, [ [:name, identity ] ] ] ] end newproperty(:message) do desc "Docs for 'message' property" end newparam(:name) do desc "Docs for 'name' parameter" isnamevar end end; end EOF } } } } }}}) end let(:modulepath) do File.join(dir, 'testing_generate2', 'modules') end let(:m3) do File.join(modulepath, 'm3') end around(:each) do |example| Puppet.settings.initialize_global_settings Puppet[:manifest] = '' loader = Puppet::Environments::Directories.new(dir, []) Puppet.override(:environments => loader) do Puppet.override(:current_environment => loader.get('testing_generate2')) do example.run end end end it 'fails when using procs for title patterns' do expect { genface.types(:format => 'pcore') }.to exit_with(1) end end end def from_an_interactive_terminal allow(STDIN).to receive(:tty?).and_return(true) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/epp_face_spec.rb
spec/unit/face/epp_face_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/face' describe Puppet::Face[:epp, :current] do include PuppetSpec::Files let(:eppface) { Puppet::Face[:epp, :current] } context "validate" do context "from an interactive terminal" do before :each do from_an_interactive_terminal end it "validates the template referenced as an absolute file" do template_name = 'template1.epp' dir = dir_containing('templates', { template_name => "<%= |$a $b |%>" }) template = File.join(dir, template_name) expect { eppface.validate(template) }.to raise_exception(Puppet::Error, /Errors while validating epp/) end it "runs error free when there are no validation errors from an absolute file" do template_name = 'template1.epp' dir = dir_containing('templates', { template_name => "just text" }) template = File.join(dir, template_name) expect { eppface.validate(template) }.to_not raise_exception() end it "reports missing files" do expect do eppface.validate("missing.epp") end.to raise_error(Puppet::Error, /One or more file\(s\) specified did not exist.*missing\.epp/m) end context "in an environment with templates" do let(:dir) do dir_containing('environments', { 'production' => { 'modules' => { 'm1' => { 'templates' => { 'greetings.epp' => "<% |$subject = world| %>hello <%= $subject -%>", 'broken.epp' => "<% | $a $b | %> I am broken", 'broken2.epp' => "<% | $a $b | %> I am broken too" }}, 'm2' => { 'templates' => { 'goodbye.epp' => "<% | $subject = world |%>goodbye <%= $subject -%>", 'broken3.epp' => "<% | $a $b | %> I am broken too" }} }}}) end around(:each) do |example| Puppet.settings.initialize_global_settings loader = Puppet::Environments::Directories.new(dir, []) Puppet.override(:environments => loader) do example.run end end it "parses supplied template files in different modules of a directory environment" do expect(eppface.validate('m1/greetings.epp')).to be_nil expect(eppface.validate('m2/goodbye.epp')).to be_nil end it "finds errors in supplied template file in the context of a directory environment" do expect { eppface.validate('m1/broken.epp') }.to raise_exception(Puppet::Error, /Errors while validating epp/) expect(@logs.join).to match(/Syntax error at 'b'/) end it "stops on first error by default" do expect { eppface.validate('m1/broken.epp', 'm1/broken2.epp') }.to raise_exception(Puppet::Error, /Errors while validating epp/) expect(@logs.join).to match(/Syntax error at 'b'.*broken\.epp/) expect(@logs.join).to_not match(/Syntax error at 'b'.*broken2\.epp/) end it "continues after error when --continue_on_error is given" do expect { eppface.validate('m1/broken.epp', 'm1/broken2.epp', :continue_on_error => true) }.to raise_exception(Puppet::Error, /Errors while validating epp/) expect(@logs.join).to match(/Syntax error at 'b'.*broken\.epp/) expect(@logs.join).to match(/Syntax error at 'b'.*broken2\.epp/) end it "validates all templates in the environment" do pending "NOT IMPLEMENTED YET" expect { eppface.validate(:continue_on_error => true) }.to raise_exception(Puppet::Error, /Errors while validating epp/) expect(@logs.join).to match(/Syntax error at 'b'.*broken\.epp/) expect(@logs.join).to match(/Syntax error at 'b'.*broken2\.epp/) expect(@logs.join).to match(/Syntax error at 'b'.*broken3\.epp/) end end end it "validates the contents of STDIN when no files given and STDIN is not a tty" do from_a_piped_input_of("<% | $a $oh_no | %> I am broken") expect { eppface.validate() }.to raise_exception(Puppet::Error, /Errors while validating epp/) expect(@logs.join).to match(/Syntax error at 'oh_no'/) end it "validates error free contents of STDIN when no files given and STDIN is not a tty" do from_a_piped_input_of("look, just text") expect(eppface.validate()).to be_nil end end context "dump" do it "prints the AST of a template given with the -e option" do expect(eppface.dump({ :e => 'hello world' })).to eq("(lambda (epp (block\n (render-s 'hello world')\n)))\n") end it "prints the AST of a template given as an absolute file" do template_name = 'template1.epp' dir = dir_containing('templates', { template_name => "hello world" }) template = File.join(dir, template_name) expect(eppface.dump(template)).to eq("(lambda (epp (block\n (render-s 'hello world')\n)))\n") end it "adds a header between dumps by default" do template_name1 = 'template1.epp' template_name2 = 'template2.epp' dir = dir_containing('templates', { template_name1 => "hello world", template_name2 => "hello again"} ) template1 = File.join(dir, template_name1) template2 = File.join(dir, template_name2) # Do not move the text block, the left margin and indentation matters expect(eppface.dump(template1, template2)).to eq( <<-"EOT" ) --- #{template1} (lambda (epp (block (render-s 'hello world') ))) --- #{template2} (lambda (epp (block (render-s 'hello again') ))) EOT end it "dumps non validated content when given --no-validate" do template_name = 'template1.epp' dir = dir_containing('templates', { template_name => "<% 1 2 3 %>" }) template = File.join(dir, template_name) expect(eppface.dump(template, :validate => false)).to eq("(lambda (epp (block\n 1\n 2\n 3\n)))\n") end it "validated content when given --validate" do template_name = 'template1.epp' dir = dir_containing('templates', { template_name => "<% 1 2 3 %>" }) template = File.join(dir, template_name) expect(eppface.dump(template, :validate => true)).to eq("") expect(@logs.join).to match(/This Literal Integer has no effect.*\(file: .*\/template1\.epp, line: 1, column: 4\)/) end it "validated content by default" do template_name = 'template1.epp' dir = dir_containing('templates', { template_name => "<% 1 2 3 %>" }) template = File.join(dir, template_name) expect(eppface.dump(template)).to eq("") expect(@logs.join).to match(/This Literal Integer has no effect.*\(file: .*\/template1\.epp, line: 1, column: 4\)/) end it "informs the user of files that don't exist" do expected_message = /One or more file\(s\) specified did not exist:\n\s*does_not_exist_here\.epp/m expect { eppface.dump('does_not_exist_here.epp') }.to raise_exception(Puppet::Error, expected_message) end it "dumps the AST of STDIN when no files given and STDIN is not a tty" do from_a_piped_input_of("hello world") expect(eppface.dump()).to eq("(lambda (epp (block\n (render-s 'hello world')\n)))\n") end it "logs an error if the input cannot be parsed even if validation is off" do from_a_piped_input_of("<% |$a $b| %> oh no") expect(eppface.dump(:validate => false)).to eq("") expect(@logs[0].message).to match(/Syntax error at 'b'/) expect(@logs[0].level).to eq(:err) end context "using 'pn' format" do it "prints the AST of the given expression in PN format" do expect(eppface.dump({ :format => 'pn', :e => 'hello world' })).to eq( '(lambda {:body [(epp (render-s "hello world"))]})') end it "pretty prints the AST of the given expression in PN format when --pretty is given" do expect(eppface.dump({ :pretty => true, :format => 'pn', :e => 'hello world' })).to eq(<<-RESULT.unindent[0..-2]) (lambda { :body [ (epp (render-s "hello world"))]}) RESULT end end context "using 'json' format" do it "prints the AST of the given expression in JSON based on the PN format" do expect(eppface.dump({ :format => 'json', :e => 'hello world' })).to eq( '{"^":["lambda",{"#":["body",[{"^":["epp",{"^":["render-s","hello world"]}]}]]}]}') end it "pretty prints the AST of the given expression in JSON based on the PN format when --pretty is given" do expect(eppface.dump({ :pretty => true, :format => 'json', :e => 'hello world' })).to eq(<<-RESULT.unindent[0..-2]) { "^": [ "lambda", { "#": [ "body", [ { "^": [ "epp", { "^": [ "render-s", "hello world" ] } ] } ] ] } ] } RESULT end end end context "render" do it "renders input from stdin" do from_a_piped_input_of("hello world") expect(eppface.render()).to eq("hello world") end it "renders input from command line" do expect(eppface.render(:e => 'hello world')).to eq("hello world") end it "renders input from an absolute file" do template_name = 'template1.epp' dir = dir_containing('templates', { template_name => "absolute world" }) template = File.join(dir, template_name) expect(eppface.render(template)).to eq("absolute world") end it "renders expressions" do expect(eppface.render(:e => '<% $x = "mr X"%>hello <%= $x %>')).to eq("hello mr X") end it "adds values given in a puppet hash given on command line with --values" do expect(eppface.render(:e => 'hello <%= $x %>', :values => '{x => "mr X"}')).to eq("hello mr X") end it "adds fully qualified values given in a puppet hash given on command line with --values" do expect(eppface.render(:e => 'hello <%= $mr::x %>', :values => '{mr::x => "mr X"}')).to eq("hello mr X") end it "adds fully qualified values with leading :: given in a puppet hash given on command line with --values" do expect(eppface.render(:e => 'hello <%= $::mr %>', :values => '{"::mr" => "mr X"}')).to eq("hello mr X") end it "adds values given in a puppet hash produced by a .pp file given with --values_file" do file_name = 'values.pp' dir = dir_containing('values', { file_name => '{x => "mr X"}' }) values_file = File.join(dir, file_name) expect(eppface.render(:e => 'hello <%= $x %>', :values_file => values_file)).to eq("hello mr X") end it "adds values given in a yaml hash given with --values_file" do file_name = 'values.yaml' dir = dir_containing('values', { file_name => "---\n x: 'mr X'" }) values_file = File.join(dir, file_name) expect(eppface.render(:e => 'hello <%= $x %>', :values_file => values_file)).to eq("hello mr X") end it "merges values from values file and command line with command line having higher precedence" do file_name = 'values.yaml' dir = dir_containing('values', { file_name => "---\n x: 'mr X'\n word: 'goodbye'" }) values_file = File.join(dir, file_name) expect(eppface.render(:e => '<%= $word %> <%= $x %>', :values_file => values_file, :values => '{x => "mr Y"}') ).to eq("goodbye mr Y") end it "sets $facts" do expect(eppface.render({ :e => 'facts is hash: <%= $facts =~ Hash %>' })).to eql("facts is hash: true") end it "sets $trusted" do expect(eppface.render({ :e => 'trusted is hash: <%= $trusted =~ Hash %>' })).to eql("trusted is hash: true") end it 'initializes the 4x loader' do expect(eppface.render({ :e => <<-EPP.unindent })).to eql("\nString\n\nInteger\n\nBoolean\n") <% $data = [type('a',generalized), type(2,generalized), type(true,generalized)] -%> <% $data.each |$value| { %> <%= $value %> <% } -%> EPP end it "facts can be added to" do expect(eppface.render({ :facts => {'the_crux' => 'biscuit'}, :e => '<%= $facts[the_crux] %>', })).to eql("biscuit") end it "facts can be overridden" do expect(eppface.render({ :facts => {'os' => {'name' => 'Merwin'} }, :e => '<%= $facts[os][name] %>', })).to eql("Merwin") end context "in an environment with templates" do let(:dir) do dir_containing('environments', { 'production' => { 'modules' => { 'm1' => { 'templates' => { 'greetings.epp' => "<% |$subject = world| %>hello <%= $subject -%>", 'factshash.epp' => "fact = <%= $facts[the_fact] -%>", 'fact.epp' => "fact = <%= $the_fact -%>", }}, 'm2' => { 'templates' => { 'goodbye.epp' => "<% | $subject = world |%>goodbye <%= $subject -%>", }} }, 'extra' => { 'facts.yaml' => "---\n the_fact: 42" } }}) end around(:each) do |example| Puppet.settings.initialize_global_settings loader = Puppet::Environments::Directories.new(dir, []) Puppet.override(:environments => loader) do example.run end end it "renders supplied template files in different modules of a directory environment" do expect(eppface.render('m1/greetings.epp')).to eq("hello world") expect(eppface.render('m2/goodbye.epp')).to eq("goodbye world") end it "makes facts available in $facts" do facts_file = File.join(dir, 'production', 'extra', 'facts.yaml') expect(eppface.render('m1/factshash.epp', :facts => facts_file)).to eq("fact = 42") end it "makes facts available individually" do facts_file = File.join(dir, 'production', 'extra', 'facts.yaml') expect(eppface.render('m1/fact.epp', :facts => facts_file)).to eq("fact = 42") end it "renders multiple files separated by headers by default" do # chomp the last newline, it is put there by heredoc expect(eppface.render('m1/greetings.epp', 'm2/goodbye.epp')).to eq(<<-EOT.chomp) --- m1/greetings.epp hello world --- m2/goodbye.epp goodbye world EOT end it "outputs multiple files verbatim when --no-headers is given" do expect(eppface.render('m1/greetings.epp', 'm2/goodbye.epp', :header => false)).to eq("hello worldgoodbye world") end end end def from_an_interactive_terminal allow(STDIN).to receive(:tty?).and_return(true) end def from_a_piped_input_of(contents) allow(STDIN).to receive(:tty?).and_return(false) allow(STDIN).to receive(:read).and_return(contents) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/facts_spec.rb
spec/unit/face/facts_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet/indirector/facts/facter' require 'puppet/indirector/facts/rest' describe Puppet::Face[:facts, '0.0.1'] do describe "#find" do it { is_expected.to be_action :find } end describe '#upload' do let(:model) { Puppet::Node::Facts } let(:test_data) { model.new('puppet.node.test', {test_fact: 'test value'}) } let(:facter_terminus) { model.indirection.terminus(:facter) } before(:each) do Puppet[:facts_terminus] = :memory Puppet::Node::Facts.indirection.save(test_data) allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=).with(:facter) Puppet.settings.parse_config(<<-CONF) [main] server=puppet.server.invalid certname=puppet.node.invalid [agent] server=puppet.server.test node_name_value=puppet.node.test CONF # Faces start in :user run mode Puppet.settings.preferred_run_mode = :user end it "uploads facts as application/json" do stub_request(:put, 'https://puppet.server.test:8140/puppet/v3/facts/puppet.node.test?environment=*root*') .with( headers: { 'Content-Type' => 'application/json' }, body: hash_including( { "name" => "puppet.node.test", "values" => { "test_fact" => "test value" } } ) ) subject.upload end it "passes the current environment" do stub_request(:put, 'https://puppet.server.test:8140/puppet/v3/facts/puppet.node.test?environment=qa') Puppet.override(:current_environment => Puppet::Node::Environment.remote('qa')) do subject.upload end end it "uses settings from the agent section of puppet.conf to resolve the node name" do stub_request(:put, /puppet.node.test/) subject.upload end it "logs the name of the server that received the upload" do stub_request(:put, 'https://puppet.server.test:8140/puppet/v3/facts/puppet.node.test?environment=*root*') subject.upload expect(@logs).to be_any {|log| log.level == :notice && log.message =~ /Uploading facts for '.*' to 'puppet\.server\.test'/} end end describe "#show" do it { is_expected.to be_action :show } end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/plugin_spec.rb
spec/unit/face/plugin_spec.rb
require 'spec_helper' require 'puppet/face' describe Puppet::Face[:plugin, :current] do let(:pluginface) { described_class } let(:action) { pluginface.get_action(:download) } def render(result) action.when_rendering(:console).call(result) end context "download" do around do |example| Puppet.override(server_agent_version: "5.3.4") do example.run end end context "when i18n is enabled" do before(:each) do Puppet[:disable_i18n] = false end it "downloads plugins, external facts, and locales" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([]) pluginface.download expect(receive_count).to eq(3) end it "renders 'No plugins downloaded' if nothing was downloaded" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([]) result = pluginface.download expect(receive_count).to eq(3) expect(render(result)).to eq('No plugins downloaded.') end it "renders comma separate list of downloaded file names" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do receive_count += 1 case receive_count when 1 %w[/a] when 2 %w[/b] when 3 %w[/c] end end result = pluginface.download expect(receive_count).to eq(3) expect(render(result)).to eq('Downloaded these plugins: /a, /b, /c') end end context "when i18n is enabled" do before(:each) do Puppet[:disable_i18n] = true end it "downloads only plugins and external facts, no locales" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([]) pluginface.download expect(receive_count).to eq(2) end it "renders 'No plugins downloaded' if nothing was downloaded, without checking for locales" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([]) result = pluginface.download expect(receive_count).to eq(2) expect(render(result)).to eq('No plugins downloaded.') end it "renders comma separate list of downloaded file names" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do receive_count += 1 case receive_count when 1 %w[/a] when 2 %w[/b] when 3 %w[/c] end end result = pluginface.download expect(receive_count).to eq(2) expect(render(result)).to eq('Downloaded these plugins: /a, /b') end end end context "download when server_agent_version is 5.3.3" do around do |example| Puppet.override(server_agent_version: "5.3.3") do example.run end end it "downloads plugins, and external facts, but not locales" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1}.and_return([]) pluginface.download end it "renders comma separate list of downloaded file names that does not include locales" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do receive_count += 1 receive_count == 1 ? %w[/a] : %w[/b] end result = pluginface.download expect(receive_count).to eq(2) expect(render(result)).to eq('Downloaded these plugins: /a, /b') end end context "download when server_agent_version is blank" do around do |example| Puppet.override(server_agent_version: "") do example.run end end it "downloads plugins, and external facts, but not locales" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { receive_count += 1 }.and_return([]) pluginface.download expect(receive_count).to eq(2) end it "renders comma separate list of downloaded file names that does not include locales" do receive_count = 0 allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do receive_count += 1 receive_count == 1 ? %w[/a] : %w[/b] end result = pluginface.download expect(receive_count).to eq(2) expect(render(result)).to eq('Downloaded these plugins: /a, /b') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/help_spec.rb
spec/unit/face/help_spec.rb
require 'spec_helper' require 'puppet/face' describe Puppet::Face[:help, '0.0.1'] do it 'has a help action' do expect(subject).to be_action :help end it 'has a default action of help' do expect(subject.get_action('help')).to be_default end it 'accepts a call with no arguments' do expect { subject.help() }.to_not raise_error end it 'accepts a face name' do expect { subject.help(:help) }.to_not raise_error end it 'accepts a face and action name' do expect { subject.help(:help, :help) }.to_not raise_error end it 'fails if more than a face and action are given' do expect { subject.help(:help, :help, :for_the_love_of_god) }.to raise_error ArgumentError end it "treats :current and 'current' identically" do expect(subject.help(:help, :version => :current)).to eq( subject.help(:help, :version => 'current') ) end it 'raises an error when the face is unavailable' do expect { subject.help(:huzzah, :bar, :version => '17.0.0') }.to raise_error(ArgumentError, /Could not find version 17\.0\.0/) end it 'finds a face by version' do face = Puppet::Face[:huzzah, :current] expect(subject.help(:huzzah, :version => face.version)). to eq(subject.help(:huzzah, :version => :current)) end context 'rendering has an error' do it 'raises an ArgumentError if the face raises a StandardError' do face = Puppet::Face[:module, :current] allow(face).to receive(:short_description).and_raise(StandardError, 'whoops') expect { subject.help(:module) }.to raise_error(ArgumentError, /Detail: "whoops"/) end it 'raises an ArgumentError if the face raises a LoadError' do face = Puppet::Face[:module, :current] allow(face).to receive(:short_description).and_raise(LoadError, 'cannot load such file -- yard') expect { subject.help(:module) }.to raise_error(ArgumentError, /Detail: "cannot load such file -- yard"/) end context 'with face actions' do it 'returns an error if we can not get an action for the module' do face = Puppet::Face[:module, :current] allow(face).to receive(:get_action).and_return(nil) expect {subject.help('module', 'list')}.to raise_error(ArgumentError, /Unable to load action list from Puppet::Face/) end end end context 'when listing subcommands' do subject { Puppet::Face[:help, :current].help } RSpec::Matchers.define :have_a_summary do match do |instance| instance.summary.is_a?(String) end end # Check a precondition for the next block; if this fails you have # something odd in your set of face, and we skip testing things that # matter. --daniel 2011-04-10 it 'has at least one face with a summary' do expect(Puppet::Face.faces).to be_any do |name| Puppet::Face[name, :current].summary end end it 'lists all faces which are runnable from the command line' do help_face = Puppet::Face[:help, :current] # The main purpose of the help face is to provide documentation for # command line users. It shouldn't show documentation for faces # that can't be run from the command line, so, rather than iterating # over all available faces, we need to iterate over the subcommands # that are available from the command line. Puppet::Application.available_application_names.each do |name| next unless help_face.is_face_app?(name) next if help_face.exclude_from_docs?(name) face = Puppet::Face[name, :current] summary = face.summary expect(subject).to match(%r{ #{name} }) summary and expect(subject).to match(%r{ #{name} +#{summary}}) end end context 'face summaries' do it 'can generate face summaries' do faces = Puppet::Face.faces expect(faces.length).to be > 0 faces.each do |name| expect(Puppet::Face[name, :current]).to have_a_summary end end end it 'lists all legacy applications' do Puppet::Face[:help, :current].legacy_applications.each do |appname| expect(subject).to match(%r{ #{appname} }) summary = Puppet::Face[:help, :current].horribly_extract_summary_from(appname) summary_regex = Regexp.escape(summary) summary and expect(subject).to match(%r{ #{summary_regex}$}) end end end context 'deprecated faces' do it 'prints a deprecation warning for deprecated faces' do allow(Puppet::Face[:module, :current]).to receive(:deprecated?).and_return(true) expect(Puppet::Face[:help, :current].help(:module)).to match(/Warning: 'puppet module' is deprecated/) end end context '#all_application_summaries' do it 'appends a deprecation warning for deprecated faces' do # Stub the module face as deprecated expect(Puppet::Face[:module, :current]).to receive(:deprecated?).and_return(true) Puppet::Face[:help, :current].all_application_summaries.each do |appname,summary| expect(summary).to match(/Deprecated/) if appname == 'module' end end end context '#legacy_applications' do subject { Puppet::Face[:help, :current].legacy_applications } # If we don't, these tests are ... less than useful, because they assume # it. When this breaks you should consider ditching the entire feature # and tests, but if not work out how to fake one. --daniel 2011-04-11 it { expect(subject.count).to be > 1 } # Meh. This is nasty, but we can't control the other list; the specific # bug that caused these to be listed is annoyingly subtle and has a nasty # fix, so better to have a "fail if you do something daft" trigger in # place here, I think. --daniel 2011-04-11 %w{face_base indirection_base}.each do |name| it { is_expected.not_to include name } end end context 'help for legacy applications' do subject { Puppet::Face[:help, :current] } let :appname do subject.legacy_applications.first end # This test is purposely generic, so that as we eliminate legacy commands # we don't get into a loop where we either test a face-based replacement # and fail to notice breakage, or where we have to constantly rewrite this # test and all. --daniel 2011-04-11 it 'returns the legacy help when given the subcommand' do help = subject.help(appname) expect(help).to match(/puppet-#{appname}/) %w{SYNOPSIS USAGE DESCRIPTION OPTIONS COPYRIGHT}.each do |heading| expect(help).to match(/^#{heading}$/) end end it 'fails when asked for an action on a legacy command' do expect { subject.help(appname, :whatever) }. to raise_error(ArgumentError, /The legacy subcommand '#{appname}' does not support supplying an action/) end context 'rendering has an error' do it 'raises an ArgumentError if a legacy application raises a StandardError' do allow_any_instance_of(Puppet::Application[appname].class).to receive(:help).and_raise(StandardError, 'whoops') expect { subject.help(appname) }.to raise_error(ArgumentError, /Detail: "whoops"/) end it 'raises an ArgumentError if a legacy application raises a LoadError' do allow_any_instance_of(Puppet::Application[appname].class).to receive(:help).and_raise(LoadError, 'cannot load such file -- yard') expect { subject.help(appname) }.to raise_error(ArgumentError, /Detail: "cannot load such file -- yard"/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/parser_spec.rb
spec/unit/face/parser_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/face' require 'puppet/application/parser' describe Puppet::Face[:parser, :current] do include PuppetSpec::Files let(:parser) { Puppet::Face[:parser, :current] } context "validate" do let(:validate_app) do Puppet::Application::Parser.new.tap do |app| allow(app).to receive(:action).and_return(parser.get_action(:validate)) end end context "from an interactive terminal" do before :each do from_an_interactive_terminal end after(:each) do # Reset cache of loaders (many examples run in the *root* environment # which exists in "eternity") Puppet.lookup(:current_environment).loaders = nil end it "validates the configured site manifest when no files are given" do manifest = file_containing('site.pp', "{ invalid =>") configured_environment = Puppet::Node::Environment.create(:default, [], manifest) Puppet.override(:current_environment => configured_environment) do parse_errors = parser.validate() expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue) end end it "validates the given file" do manifest = file_containing('site.pp', "{ invalid =>") parse_errors = parser.validate(manifest) expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue) end it "validates static heredoc with specified syntax" do manifest = file_containing('site.pp', "@(EOT:pp) { invalid => EOT ") parse_errors = parser.validate(manifest) expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue) end it "does not validates dynamic heredoc with specified syntax" do manifest = file_containing('site.pp', "@(\"EOT\":pp) {invalid => ${1+1} EOT") parse_errors = parser.validate(manifest) expect(parse_errors).to be_empty end it "runs error free when there are no validation errors" do manifest = file_containing('site.pp', "notify { valid: }") parse_errors = parser.validate(manifest) expect(parse_errors).to be_empty end it "runs error free when there is a puppet function in manifest being validated" do manifest = file_containing('site.pp', "function valid() { 'valid' } notify{ valid(): }") parse_errors = parser.validate(manifest) expect(parse_errors).to be_empty end it "runs error free when there is a type alias in a manifest that requires type resolution" do manifest = file_containing('site.pp', "type A = String; type B = Array[A]; function valid(B $x) { $x } notify{ valid([valid]): }") parse_errors = parser.validate(manifest) expect(parse_errors).to be_empty end it "reports missing files" do expect do parser.validate("missing.pp") end.to raise_error(Puppet::Error, /One or more file\(s\) specified did not exist.*missing\.pp/m) end it "parses supplied manifest files in the context of a directory environment" do manifest = file_containing('test.pp', "{ invalid =>") env = Puppet::Node::Environment.create(:special, []) env_loader = Puppet::Environments::Static.new(env) Puppet.override({:environments => env_loader, :current_environment => env}) do parse_errors = parser.validate(manifest) expect(parse_errors[manifest]).to be_a_kind_of(Puppet::ParseErrorWithIssue) end end end context "when no files given and STDIN is not a tty" do it "validates the contents of STDIN" do from_a_piped_input_of("{ invalid =>") Puppet.override(:current_environment => Puppet::Node::Environment.create(:special, [])) do parse_errors = parser.validate() expect(parse_errors['STDIN']).to be_a_kind_of(Puppet::ParseErrorWithIssue) end end it "runs error free when contents of STDIN is valid" do from_a_piped_input_of("notify { valid: }") Puppet.override(:current_environment => Puppet::Node::Environment.create(:special, [])) do parse_errors = parser.validate() expect(parse_errors).to be_empty end end end context "when invoked with console output renderer" do before(:each) do validate_app.render_as = :console end it "logs errors using Puppet.log_exception" do manifest = file_containing('test.pp', "{ invalid =>") results = parser.validate(manifest) results.each do |_, error| expect(Puppet).to receive(:log_exception).with(error) end expect { validate_app.render(results, nil) }.to raise_error(SystemExit) end end context "when invoked with --render-as=json" do before(:each) do validate_app.render_as = :json end it "outputs errors in a JSON document to stdout" do manifest = file_containing('test.pp', "{ invalid =>") results = parser.validate(manifest) expected_json = /\A{.*#{Regexp.escape('"message":')}\s*#{Regexp.escape('"Syntax error at end of input"')}.*}\Z/m expect { validate_app.render(results, nil) }.to output(expected_json).to_stdout.and raise_error(SystemExit) end end end context "dump" do it "prints the AST of the passed expression" do expect(parser.dump({ :e => 'notice hi' })).to eq("(invoke notice hi)\n") end it "prints the AST of the code read from the passed files" do first_manifest = file_containing('site.pp', "notice hi") second_manifest = file_containing('site2.pp', "notice bye") output = parser.dump(first_manifest, second_manifest) expect(output).to match(/site\.pp.*\(invoke notice hi\)/) expect(output).to match(/site2\.pp.*\(invoke notice bye\)/) end it "informs the user of files that don't exist" do expect(parser.dump('does_not_exist_here.pp')).to match(/did not exist:\s*does_not_exist_here\.pp/m) end it "prints the AST of STDIN when no files given and STDIN is not a tty" do from_a_piped_input_of("notice hi") Puppet.override(:current_environment => Puppet::Node::Environment.create(:special, [])) do expect(parser.dump()).to eq("(invoke notice hi)\n") end end it "logs an error if the input cannot be parsed" do output = parser.dump({ :e => '{ invalid =>' }) expect(output).to eq("") expect(@logs[0].message).to eq("Syntax error at end of input") expect(@logs[0].level).to eq(:err) end it "logs an error if the input begins with a UTF-8 BOM (Byte Order Mark)" do utf8_bom_manifest = file_containing('utf8_bom.pp', "\uFEFFnotice hi") output = parser.dump(utf8_bom_manifest) expect(output).to eq("") expect(@logs[1].message).to eq("Illegal UTF-8 Byte Order mark at beginning of input: [EF BB BF] - remove these from the puppet source") expect(@logs[1].level).to eq(:err) end it "runs error free when there is a puppet function in manifest being dumped" do expect { manifest = file_containing('site.pp', "function valid() { 'valid' } notify{ valid(): }") parser.dump(manifest) }.to_not raise_error end it "runs error free when there is a type alias in a manifest that requires type resolution" do expect { manifest = file_containing('site.pp', "type A = String; type B = Array[A]; function valid(B $x) { $x } notify{ valid([valid]): }") parser.dump(manifest) }.to_not raise_error end context "using 'pn' format" do it "prints the AST of the given expression in PN format" do expect(parser.dump({ :format => 'pn', :e => 'if $x { "hi ${x[2]}" }' })).to eq( '(if {:test (var "x") :then [(concat "hi " (str (access (var "x") 2)))]})') end it "pretty prints the AST of the given expression in PN format when --pretty is given" do expect(parser.dump({ :pretty => true, :format => 'pn', :e => 'if $x { "hi ${x[2]}" }' })).to eq(<<-RESULT.unindent[0..-2]) (if { :test (var "x") :then [ (concat "hi " (str (access (var "x") 2)))]}) RESULT end end context "using 'json' format" do it "prints the AST of the given expression in JSON based on the PN format" do expect(parser.dump({ :format => 'json', :e => 'if $x { "hi ${x[2]}" }' })).to eq( '{"^":["if",{"#":["test",{"^":["var","x"]},"then",[{"^":["concat","hi ",{"^":["str",{"^":["access",{"^":["var","x"]},2]}]}]}]]}]}') end it "pretty prints the AST of the given expression in JSON based on the PN format when --pretty is given" do expect(parser.dump({ :pretty => true, :format => 'json', :e => 'if $x { "hi ${x[2]}" }' })).to eq(<<-RESULT.unindent[0..-2]) { "^": [ "if", { "#": [ "test", { "^": [ "var", "x" ] }, "then", [ { "^": [ "concat", "hi ", { "^": [ "str", { "^": [ "access", { "^": [ "var", "x" ] }, 2 ] } ] } ] } ] ] } ] } RESULT end end end def from_an_interactive_terminal allow(STDIN).to receive(:tty?).and_return(true) end def from_a_piped_input_of(contents) allow(STDIN).to receive(:tty?).and_return(false) allow(STDIN).to receive(:read).and_return(contents) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/config_spec.rb
spec/unit/face/config_spec.rb
require 'spec_helper' require 'puppet/face' describe Puppet::Face[:config, '0.0.1'] do let(:config) { described_class } def render(action, result) config.get_action(action).when_rendering(:console).call(result) end FS = Puppet::FileSystem it "prints a single setting without the name" do Puppet[:trace] = true result = subject.print("trace") expect(render(:print, result)).to eq("true\n") end it "prints multiple settings with the names" do Puppet[:trace] = true Puppet[:syslogfacility] = "file" result = subject.print("trace", "syslogfacility") expect(render(:print, result)).to eq(<<-OUTPUT) syslogfacility = file trace = true OUTPUT end it "prints environment_timeout=unlimited correctly" do Puppet[:environment_timeout] = "unlimited" result = subject.print("environment_timeout") expect(render(:print, result)).to eq("unlimited\n") end it "prints arrays correctly" do pending "Still doesn't print arrays like they would appear in config" Puppet[:server_list] = %w{server1 server2} result = subject.print("server_list") expect(render(:print, result)).to eq("server1, server2\n") end it "prints the setting from the selected section" do Puppet.settings.parse_config(<<-CONF) [user] syslogfacility = file CONF result = subject.print("syslogfacility", :section => "user") expect(render(:print, result)).to eq("file\n") end it "prints the section and environment, and not a warning, when a section is given and verbose is set" do Puppet.settings.parse_config(<<-CONF) [user] syslogfacility = file CONF #This has to be after the settings above, which resets the value Puppet[:log_level] = 'info' expect(Puppet).not_to receive(:warning) expect { result = subject.print("syslogfacility", :section => "user") expect(render(:print, result)).to eq("file\n") }.to output("\e[1;33mResolving settings from section 'user' in environment 'production'\e[0m\n").to_stderr end it "prints a warning and the section and environment when no section is given and verbose is set" do Puppet[:log_level] = 'info' Puppet[:trace] = true expect(Puppet).to receive(:warning).with("No section specified; defaulting to 'main'.\nSet the config section " + "by using the `--section` flag.\nFor example, `puppet config --section user print foo`.\nFor more " + "information, see https://puppet.com/docs/puppet/latest/configuration.html") expect { result = subject.print("trace") expect(render(:print, result)).to eq("true\n") }.to output("\e[1;33mResolving settings from section 'main' in environment 'production'\e[0m\n").to_stderr end it "does not print a warning or the section and environment when no section is given and verbose is not set" do Puppet[:log_level] = 'notice' Puppet[:trace] = true expect(Puppet).not_to receive(:warning) expect { result = subject.print("trace") expect(render(:print, result)).to eq("true\n") }.to_not output.to_stderr end it "defaults to all when no arguments are given" do result = subject.print expect(render(:print, result).lines.to_a.length).to eq(Puppet.settings.to_a.length) end it "prints out all of the settings when asked for 'all'" do result = subject.print('all') expect(render(:print, result).lines.to_a.length).to eq(Puppet.settings.to_a.length) end it "stringifies all keys for network format handlers to consume" do Puppet[:syslogfacility] = "file" result = subject.print expect(result["syslogfacility"]).to eq("file") expect(result.keys).to all(be_a(String)) end it "stringifies multiple keys for network format handlers to consume" do Puppet[:trace] = true Puppet[:syslogfacility] = "file" expect(subject.print("trace", "syslogfacility")).to eq({"syslogfacility" => "file", "trace" => true}) end it "stringifies single key for network format handlers to consume" do Puppet[:trace] = true expect(subject.print("trace")).to eq({"trace" => true}) end context "when setting config values" do let(:config_file) { '/foo/puppet.conf' } let(:path) { Pathname.new(config_file).expand_path } before(:each) do Puppet[:config] = config_file allow(Puppet::FileSystem).to receive(:pathname).with(path.to_s).and_return(path) allow(Puppet::FileSystem).to receive(:dir_mkpath) allow(Puppet::FileSystem).to receive(:touch) end it "prints the section and environment when no section is given and verbose is set" do Puppet[:log_level] = 'info' allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) expect { subject.set('certname', 'bar') }.to output("\e[1;33mResolving settings from section 'main' in environment 'production'\e[0m\n").to_stderr end it "prints the section and environment when a section is given and verbose is set" do Puppet[:log_level] = 'info' allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) expect { subject.set('certname', 'bar', {:section => "baz"}) }.to output("\e[1;33mResolving settings from section 'baz' in environment 'production'\e[0m\n").to_stderr end it "writes to the correct puppet config file" do expect(Puppet::FileSystem).to receive(:open).with(path, anything, anything) subject.set('certname', 'bar') end it "creates a config file if one does not exist" do allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) expect(Puppet::FileSystem).to receive(:touch).with(path) subject.set('certname', 'bar') end it "sets the supplied config/value in the default section (main)" do allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new]) manipulator = Puppet::Settings::IniFile::Manipulator.new(config) allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator) expect(manipulator).to receive(:set).with("main", "certname", "bar") subject.set('certname', 'bar') end it "sets the value in the supplied section" do allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new]) manipulator = Puppet::Settings::IniFile::Manipulator.new(config) allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator) expect(manipulator).to receive(:set).with("baz", "certname", "bar") subject.set('certname', 'bar', {:section => "baz"}) end it "does not duplicate an existing default section when a section is not specified" do contents = <<-CONF [main] myport = 4444 CONF myfile = StringIO.new(contents) allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(myfile) subject.set('certname', 'bar') expect(myfile.string).to match(/certname = bar/) expect(myfile.string).not_to match(/main.*main/) end it "opens the file with UTF-8 encoding" do expect(Puppet::FileSystem).to receive(:open).with(path, nil, 'r+:UTF-8') subject.set('certname', 'bar') end it "sets settings into the [server] section when setting [master] section settings" do initial_contents = <<~CONFIG [master] node_terminus = none reports = log CONFIG myinitialfile = StringIO.new(initial_contents) allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(myinitialfile) expect { subject.set('node_terminus', 'exec', {:section => 'master'}) }.to output("Deleted setting from 'master': 'node_terminus = none', and adding it to 'server' section\n").to_stdout expect(myinitialfile.string).to match(<<~CONFIG) [master] reports = log [server] node_terminus = exec CONFIG end it "setting [master] section settings, sets settings into [server] section instead" do myinitialfile = StringIO.new("") allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(myinitialfile) subject.set('node_terminus', 'exec', {:section => 'master'}) expect(myinitialfile.string).to match(<<~CONFIG) [server] node_terminus = exec CONFIG end end context 'when the puppet.conf file does not exist' do let(:config_file) { '/foo/puppet.conf' } let(:path) { Pathname.new(config_file).expand_path } before(:each) do Puppet[:config] = config_file allow(Puppet::FileSystem).to receive(:pathname).with(path.to_s).and_return(path) end it 'prints a message when the puppet.conf file does not exist' do allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false) expect(Puppet).to receive(:warning).with("The puppet.conf file does not exist #{path.to_s}") subject.delete('setting', {:section => 'main'}) end end context 'when deleting config values' do let(:config_file) { '/foo/puppet.conf' } let(:path) { Pathname.new(config_file).expand_path } before(:each) do Puppet[:config] = config_file allow(Puppet::FileSystem).to receive(:pathname).with(path.to_s).and_return(path) allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) end it 'prints a message about what was deleted' do allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new]) manipulator = Puppet::Settings::IniFile::Manipulator.new(config) allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator) expect(manipulator).to receive(:delete).with('main', 'setting').and_return(' setting=value') expect { subject.delete('setting', {:section => 'main'}) }.to output("Deleted setting from 'main': 'setting=value'\n").to_stdout end it 'prints a warning when a setting is not found to delete' do allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new]) manipulator = Puppet::Settings::IniFile::Manipulator.new(config) allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator) expect(manipulator).to receive(:delete).with('main', 'setting').and_return(nil) expect(Puppet).to receive(:warning).with("No setting found in configuration file for section 'main' setting name 'setting'") subject.delete('setting', {:section => 'main'}) end ['master', 'server'].each do |section| describe "when deleting from [#{section}] section" do it "deletes section values from both [server] and [master] sections" do allow(Puppet::FileSystem).to receive(:open).with(path, anything, anything).and_yield(StringIO.new) config = Puppet::Settings::IniFile.new([Puppet::Settings::IniFile::DefaultSection.new]) manipulator = Puppet::Settings::IniFile::Manipulator.new(config) allow(Puppet::Settings::IniFile::Manipulator).to receive(:new).and_return(manipulator) expect(manipulator).to receive(:delete).with('master', 'setting').and_return('setting=value') expect(manipulator).to receive(:delete).with('server', 'setting').and_return('setting=value') expect { subject.delete('setting', {:section => section}) }.to output(/Deleted setting from 'master': 'setting'\nDeleted setting from 'server': 'setting'\n/).to_stdout end end end end shared_examples_for :config_printing_a_section do |section| def add_section_option(args, section) args << { :section => section } if section args end it "prints directory env settings for an env that exists" do FS.overlay( FS::MemoryFile.a_directory(File.expand_path("/dev/null/environments"), [ FS::MemoryFile.a_directory("production", [ FS::MemoryFile.a_missing_file("environment.conf"), ]), ]) ) do args = "environmentpath","manifest","modulepath","environment","basemodulepath" result = subject.print(*add_section_option(args, section)) expect(render(:print, result)).to eq(<<-OUTPUT) basemodulepath = #{File.expand_path("/some/base")} environment = production environmentpath = #{File.expand_path("/dev/null/environments")} manifest = #{File.expand_path("/dev/null/environments/production/manifests")} modulepath = #{File.expand_path("/dev/null/environments/production/modules")}#{File::PATH_SEPARATOR}#{File.expand_path("/some/base")} OUTPUT end end it "interpolates settings in environment.conf" do FS.overlay( FS::MemoryFile.a_directory(File.expand_path("/dev/null/environments"), [ FS::MemoryFile.a_directory("production", [ FS::MemoryFile.a_regular_file_containing("environment.conf", <<-CONTENT), modulepath=/custom/modules#{File::PATH_SEPARATOR}$basemodulepath CONTENT ]), ]) ) do args = "environmentpath","manifest","modulepath","environment","basemodulepath" result = subject.print(*add_section_option(args, section)) expect(render(:print, result)).to eq(<<-OUTPUT) basemodulepath = #{File.expand_path("/some/base")} environment = production environmentpath = #{File.expand_path("/dev/null/environments")} manifest = #{File.expand_path("/dev/null/environments/production/manifests")} modulepath = #{File.expand_path("/custom/modules")}#{File::PATH_SEPARATOR}#{File.expand_path("/some/base")} OUTPUT end end it "prints the default configured env settings for an env that does not exist" do Puppet[:environment] = 'doesnotexist' FS.overlay( FS::MemoryFile.a_directory(File.expand_path("/dev/null/environments"), [ FS::MemoryFile.a_missing_file("doesnotexist") ]) ) do args = "environmentpath","manifest","modulepath","environment","basemodulepath" result = subject.print(*add_section_option(args, section)) expect(render(:print, result)).to eq(<<-OUTPUT) basemodulepath = #{File.expand_path("/some/base")} environment = doesnotexist environmentpath = #{File.expand_path("/dev/null/environments")} manifest = modulepath = OUTPUT end end end context "when printing environment settings" do context "from main section" do before(:each) do Puppet.settings.parse_config(<<-CONF) [main] environmentpath=$confdir/environments basemodulepath=/some/base CONF end it_behaves_like :config_printing_a_section, nil end context "from master section" do before(:each) do Puppet.settings.parse_config(<<-CONF) [master] environmentpath=$confdir/environments basemodulepath=/some/base CONF end it_behaves_like :config_printing_a_section, :master end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/catalog_spec.rb
spec/unit/face/catalog_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet/indirector/facts/facter' require 'puppet/indirector/facts/rest' describe Puppet::Face[:catalog, '0.0.1'] do describe '#download' do let(:model) { Puppet::Node::Facts } let(:test_data) { model.new('puppet.node.test', {test_fact: 'catalog_face_request_test_value'}) } let(:catalog) { Puppet::Resource::Catalog.new('puppet.node.test', Puppet::Node::Environment.remote(Puppet[:environment].to_sym)) } before(:each) do Puppet[:facts_terminus] = :memory Puppet::Node::Facts.indirection.save(test_data) allow(Puppet::Face[:catalog, "0.0.1"]).to receive(:save).once Puppet.settings.parse_config(<<-CONF) [main] server=puppet.server.test certname=puppet.node.test CONF # Faces start in :user run mode Puppet.settings.preferred_run_mode = :user end it "adds facts to the catalog request" do stub_request(:post, 'https://puppet.server.test:8140/puppet/v3/catalog/puppet.node.test?environment=*root*') .with( headers: { 'Content-Type' => 'application/x-www-form-urlencoded' }, body: hash_including(facts: URI.encode_www_form_component(Puppet::Node::Facts.indirection.find('puppet.node.test').to_json)) ).to_return(:status => 200, :body => catalog.render(:json), :headers => {'Content-Type' => 'application/json'}) subject.download end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/node_spec.rb
spec/unit/face/node_spec.rb
require 'spec_helper' require 'puppet/face' describe Puppet::Face[:node, '0.0.1'] do describe '#cleanup' do it "should clean everything" do { "cert" => ['hostname'], "cached_facts" => ['hostname'], "cached_node" => ['hostname'], "reports" => ['hostname'], }.each { |k, v| expect(subject).to receive("clean_#{k}".to_sym).with(*v) } subject.cleanup('hostname') end end describe 'when running #clean' do it 'should invoke #cleanup' do expect(subject).to receive(:cleanup).with('hostname') subject.clean('hostname') end end describe "clean action" do before :each do allow(subject).to receive(:cleanup) end it "should have a clean action" do expect(subject).to be_action :clean end it "should not accept a call with no arguments" do expect { subject.clean() }.to raise_error(RuntimeError, /At least one node should be passed/) end it "should accept a node name" do expect { subject.clean('hostname') }.to_not raise_error end it "should accept more than one node name" do expect do subject.clean('hostname', 'hostname2', {}) end.to_not raise_error expect do subject.clean('hostname', 'hostname2', 'hostname3') end.to_not raise_error end context "clean action" do subject { Puppet::Face[:node, :current] } before :each do allow(Puppet::Util::Log).to receive(:newdestination) allow(Puppet::Util::Log).to receive(:level=) end describe "during setup" do it "should set facts terminus and cache class to yaml" do expect(Puppet::Node::Facts.indirection).to receive(:terminus_class=).with(:yaml) expect(Puppet::Node::Facts.indirection).to receive(:cache_class=).with(:yaml) subject.clean('hostname') end it "should run in server mode" do subject.clean('hostname') expect(Puppet.run_mode).to be_server end it "should set node cache as yaml" do expect(Puppet::Node.indirection).to receive(:terminus_class=).with(:yaml) expect(Puppet::Node.indirection).to receive(:cache_class=).with(:yaml) subject.clean('hostname') end end describe "when cleaning certificate", :if => Puppet.features.puppetserver_ca? do it "should call the CA CLI gem's clean action" do expect_any_instance_of(Puppetserver::Ca::Action::Clean). to receive(:clean_certs). with(['hostname'], anything). and_return(:success) if Puppet[:cadir].start_with?(Puppet[:ssldir]) expect_any_instance_of(LoggerIO). to receive(:warn). with(/cadir is currently configured to be inside/) end expect(Puppet).not_to receive(:warning) result = subject.clean_cert('hostname') expect(result).to eq(0) end it "should not call the CA CLI gem's clean action if the gem is missing" do expect(Puppet.features).to receive(:puppetserver_ca?).and_return(false) expect_any_instance_of(Puppetserver::Ca::Action::Clean).not_to receive(:run) subject.clean_cert("hostname") end end describe "when cleaning cached facts" do it "should destroy facts" do @host = 'node' expect(Puppet::Node::Facts.indirection).to receive(:destroy).with(@host) subject.clean_cached_facts(@host) end end describe "when cleaning cached node" do it "should destroy the cached node" do expect(Puppet::Node.indirection).to receive(:destroy).with(@host) subject.clean_cached_node(@host) end end describe "when cleaning archived reports" do it "should tell the reports to remove themselves" do allow(Puppet::Transaction::Report.indirection).to receive(:destroy).with(@host) subject.clean_reports(@host) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/module/install_spec.rb
spec/unit/face/module/install_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet/module_tool' describe "puppet module install" do include PuppetSpec::Files describe "action" do let(:name) { double(:name) } let(:target_dir) { tmpdir('module install face action') } let(:options) { { :target_dir => target_dir } } it 'should invoke the Installer app' do expect(Puppet::ModuleTool).to receive(:set_option_defaults).with(options) expect(Puppet::ModuleTool::Applications::Installer).to receive(:run) do |mod, target, opts| expect(mod).to eql(name) expect(opts).to eql(options) expect(target).to be_a(Puppet::ModuleTool::InstallDirectory) expect(target.target).to eql(Pathname.new(target_dir)) end Puppet::Face[:module, :current].install(name, options) end end describe "inline documentation" do subject { Puppet::Face.find_action(:module, :install) } its(:summary) { should =~ /install.*module/im } its(:description) { should =~ /install.*module/im } its(:returns) { should =~ /pathname/i } its(:examples) { should_not be_empty } %w{ license copyright summary description returns examples }.each do |doc| context "of the" do its(doc.to_sym) { should_not =~ /(FIXME|REVISIT|TODO)/ } end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/module/upgrade_spec.rb
spec/unit/face/module/upgrade_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet/module_tool' describe "puppet module upgrade" do subject { Puppet::Face[:module, :current] } let(:options) do {} end describe "inline documentation" do subject { Puppet::Face[:module, :current].get_action :upgrade } its(:summary) { should =~ /upgrade.*module/im } its(:description) { should =~ /upgrade.*module/im } its(:returns) { should =~ /hash/i } its(:examples) { should_not be_empty } %w{ license copyright summary description returns examples }.each do |doc| context "of the" do its(doc.to_sym) { should_not =~ /(FIXME|REVISIT|TODO)/ } end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/module/list_spec.rb
spec/unit/face/module/list_spec.rb
# encoding: UTF-8 require 'spec_helper' require 'puppet/face' require 'puppet/module_tool' require 'puppet_spec/modules' describe "puppet module list" do include PuppetSpec::Files around do |example| dir = tmpdir("deep_path") FileUtils.mkdir_p(@modpath1 = File.join(dir, "modpath1")) FileUtils.mkdir_p(@modpath2 = File.join(dir, "modpath2")) FileUtils.mkdir_p(@modpath3 = File.join(dir, "modpath3")) env = Puppet::Node::Environment.create(:env, [@modpath1, @modpath2]) Puppet.override(:current_environment => env) do example.run end end it "should return an empty list per dir in path if there are no modules" do expect(Puppet::Face[:module, :current].list[:modules_by_path]).to eq({ @modpath1 => [], @modpath2 => [] }) end it "should include modules separated by the environment's modulepath" do foomod1 = PuppetSpec::Modules.create('foo', @modpath1) barmod1 = PuppetSpec::Modules.create('bar', @modpath1) foomod2 = PuppetSpec::Modules.create('foo', @modpath2) usedenv = Puppet::Node::Environment.create(:useme, [@modpath1, @modpath2, @modpath3]) Puppet.override(:environments => Puppet::Environments::Static.new(usedenv)) do expect(Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path]).to eq({ @modpath1 => [ Puppet::Module.new('bar', barmod1.path, usedenv), Puppet::Module.new('foo', foomod1.path, usedenv) ], @modpath2 => [Puppet::Module.new('foo', foomod2.path, usedenv)], @modpath3 => [], }) end end it "should use the specified environment" do foomod = PuppetSpec::Modules.create('foo', @modpath1) barmod = PuppetSpec::Modules.create('bar', @modpath1) usedenv = Puppet::Node::Environment.create(:useme, [@modpath1, @modpath2, @modpath3]) Puppet.override(:environments => Puppet::Environments::Static.new(usedenv)) do expect(Puppet::Face[:module, :current].list(:environment => 'useme')[:modules_by_path]).to eq({ @modpath1 => [ Puppet::Module.new('bar', barmod.path, usedenv), Puppet::Module.new('foo', foomod.path, usedenv) ], @modpath2 => [], @modpath3 => [], }) end end it "should use the specified modulepath" do foomod = PuppetSpec::Modules.create('foo', @modpath1) barmod = PuppetSpec::Modules.create('bar', @modpath2) modules = Puppet::Face[:module, :current].list(:modulepath => "#{@modpath1}#{File::PATH_SEPARATOR}#{@modpath2}")[:modules_by_path] expect(modules[@modpath1].first.name).to eq('foo') expect(modules[@modpath1].first.path).to eq(foomod.path) expect(modules[@modpath1].first.environment.modulepath).to eq([@modpath1, @modpath2]) expect(modules[@modpath2].first.name).to eq('bar') expect(modules[@modpath2].first.path).to eq(barmod.path) expect(modules[@modpath2].first.environment.modulepath).to eq([@modpath1, @modpath2]) end it "prefers a given modulepath over the modulepath from the given environment" do foomod = PuppetSpec::Modules.create('foo', @modpath1) barmod = PuppetSpec::Modules.create('bar', @modpath2) modules = Puppet::Face[:module, :current].list(:environment => 'myenv', :modulepath => "#{@modpath1}#{File::PATH_SEPARATOR}#{@modpath2}")[:modules_by_path] expect(modules[@modpath1].first.name).to eq('foo') expect(modules[@modpath1].first.path).to eq(foomod.path) expect(modules[@modpath1].first.environment.modulepath).to eq([@modpath1, @modpath2]) expect(modules[@modpath1].first.environment.name).to_not eq(:myenv) expect(modules[@modpath2].first.name).to eq('bar') expect(modules[@modpath2].first.path).to eq(barmod.path) expect(modules[@modpath2].first.environment.modulepath).to eq([@modpath1, @modpath2]) expect(modules[@modpath2].first.environment.name).to_not eq(:myenv) end describe "inline documentation" do subject { Puppet::Face[:module, :current].get_action(:list) } its(:summary) { should =~ /list.*module/im } its(:description) { should =~ /list.*module/im } its(:returns) { should =~ /hash of paths to module objects/i } its(:examples) { should_not be_empty } end describe "when rendering to console" do let(:face) { Puppet::Face[:module, :current] } let(:action) { face.get_action(:list) } def console_output(options={}) result = face.list(options) action.when_rendering(:console).call(result, options) end it "should explicitly state when a modulepath is empty" do empty_modpath = tmpdir('empty') expected = <<-HEREDOC.gsub(' ', '') #{empty_modpath} (no modules installed) HEREDOC expect(console_output(:modulepath => empty_modpath)).to eq(expected) end it "should print both modules with and without metadata" do modpath = tmpdir('modpath') PuppetSpec::Modules.create('nometadata', modpath) PuppetSpec::Modules.create('metadata', modpath, :metadata => {:author => 'metaman'}) env = Puppet::Node::Environment.create(:environ, [modpath]) Puppet.override(:current_environment => env) do expected = <<-HEREDOC.gsub(' ', '') #{modpath} ├── metaman-metadata (\e[0;36mv9.9.9\e[0m) └── nometadata (\e[0;36m???\e[0m) HEREDOC expect(console_output).to eq(expected) end end it "should print the modulepaths in the order they are in the modulepath setting" do path1 = tmpdir('b') path2 = tmpdir('c') path3 = tmpdir('a') env = Puppet::Node::Environment.create(:environ, [path1, path2, path3]) Puppet.override(:current_environment => env) do expected = <<-HEREDOC.gsub(' ', '') #{path1} (no modules installed) #{path2} (no modules installed) #{path3} (no modules installed) HEREDOC expect(console_output).to eq(expected) end end it "should print dependencies as a tree" do PuppetSpec::Modules.create('dependable', @modpath1, :metadata => { :version => '0.0.5'}) PuppetSpec::Modules.create( 'other_mod', @modpath1, :metadata => { :version => '1.0.0', :dependencies => [{ "version_requirement" => ">= 0.0.5", "name" => "puppetlabs/dependable" }] } ) expected = <<-HEREDOC.gsub(' ', '') #{@modpath1} └─┬ puppetlabs-other_mod (\e[0;36mv1.0.0\e[0m) └── puppetlabs-dependable (\e[0;36mv0.0.5\e[0m) #{@modpath2} (no modules installed) HEREDOC expect(console_output(:tree => true)).to eq(expected) end it "should print both modules with and without metadata as a tree" do PuppetSpec::Modules.create('nometadata', @modpath1) PuppetSpec::Modules.create('metadata', @modpath1, :metadata => {:author => 'metaman'}) expected = <<-HEREDOC.gsub(' ', '') #{@modpath1} ├── metaman-metadata (\e[0;36mv9.9.9\e[0m) └── nometadata (\e[0;36m???\e[0m) #{@modpath2} (no modules installed) HEREDOC expect(console_output).to eq(expected) end it "should warn about missing dependencies" do PuppetSpec::Modules.create('depender', @modpath1, :metadata => { :version => '1.0.0', :dependencies => [{ "version_requirement" => ">= 0.0.5", "name" => "puppetlabs/dependable" }] }) expect(Puppet).to receive(:warning).with(match(/Missing dependency 'puppetlabs-dependable'/).and match(/'puppetlabs-depender' \(v1\.0\.0\) requires 'puppetlabs-dependable' \(>= 0\.0\.5\)/)) console_output(:tree => true) end it "should warn about out of range dependencies" do PuppetSpec::Modules.create('dependable', @modpath1, :metadata => { :version => '0.0.1'}) PuppetSpec::Modules.create('depender', @modpath1, :metadata => { :version => '1.0.0', :dependencies => [{ "version_requirement" => ">= 0.0.5", "name" => "puppetlabs/dependable" }] }) expect(Puppet).to receive(:warning).with(match(/Module 'puppetlabs-dependable' \(v0\.0\.1\) fails to meet some dependencies/).and match(/'puppetlabs-depender' \(v1\.0\.0\) requires 'puppetlabs-dependable' \(>= 0\.0\.5\)/)) console_output(:tree => true) end end describe "when rendering as json" do let(:face) { Puppet::Face[:module, :current] } let(:action) { face.get_action(:list) } it "should warn about missing dependencies" do PuppetSpec::Modules.create('depender', @modpath1, :metadata => { :version => '1.0.0', :dependencies => [{ "version_requirement" => ">= 0.0.5", "name" => "puppetlabs/dependable" }] }) result = face.list expect(result.dig(:unmet_dependencies, :missing)).to include( "puppetlabs/dependable" => { errors: ["'puppetlabs-depender' (v1.0.0) requires 'puppetlabs-dependable' (>= 0.0.5)"], parent: { name: "puppetlabs/depender", :version=>"v1.0.0" }, version: nil } ) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face/module/uninstall_spec.rb
spec/unit/face/module/uninstall_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet/module_tool' describe "puppet module uninstall" do include PuppetSpec::Files describe "action" do let(:name) { 'module-name' } let(:options) { Hash.new } it 'should invoke the Uninstaller app' do expect(Puppet::ModuleTool).to receive(:set_option_defaults).with(options) expect(Puppet::ModuleTool::Applications::Uninstaller).to receive(:run).with(name, options) Puppet::Face[:module, :current].uninstall(name, options) end context 'slash-separated module name' do let(:name) { 'module/name' } it 'should invoke the Uninstaller app' do expect(Puppet::ModuleTool).to receive(:set_option_defaults).with(options) expect(Puppet::ModuleTool::Applications::Uninstaller).to receive(:run).with('module-name', options) Puppet::Face[:module, :current].uninstall(name, options) end end end describe "inline documentation" do subject { Puppet::Face.find_action(:module, :uninstall) } its(:summary) { should =~ /uninstall.*module/im } its(:description) { should =~ /uninstall.*module/im } its(:returns) { should =~ /uninstalled modules/i } its(:examples) { should_not be_empty } %w{ license copyright summary description returns examples }.each do |doc| context "of the" do its(doc.to_sym) { should_not =~ /(FIXME|REVISIT|TODO)/ } end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confine/exists_spec.rb
spec/unit/confine/exists_spec.rb
require 'spec_helper' require 'puppet/confine/exists' describe Puppet::Confine::Exists do before do @confine = Puppet::Confine::Exists.new("/my/file") @confine.label = "eh" end it "should be named :exists" do expect(Puppet::Confine::Exists.name).to eq(:exists) end it "should not pass if exists is nil" do confine = Puppet::Confine::Exists.new(nil) confine.label = ":exists => nil" expect(confine).to receive(:pass?).with(nil) expect(confine).not_to be_valid end it "should use the 'pass?' method to test validity" do expect(@confine).to receive(:pass?).with("/my/file") @confine.valid? end it "should return false if the value is false" do expect(@confine.pass?(false)).to be_falsey end it "should return false if the value does not point to a file" do expect(Puppet::FileSystem).to receive(:exist?).with("/my/file").and_return(false) expect(@confine.pass?("/my/file")).to be_falsey end it "should return true if the value points to a file" do expect(Puppet::FileSystem).to receive(:exist?).with("/my/file").and_return(true) expect(@confine.pass?("/my/file")).to be_truthy end it "should produce a message saying that a file is missing" do expect(@confine.message("/my/file")).to be_include("does not exist") end describe "and the confine is for binaries" do before do allow(@confine).to receive(:for_binary).and_return(true) end it "should use its 'which' method to look up the full path of the file" do expect(@confine).to receive(:which).and_return(nil) @confine.pass?("/my/file") end it "should return false if no executable can be found" do expect(@confine).to receive(:which).with("/my/file").and_return(nil) expect(@confine.pass?("/my/file")).to be_falsey end it "should return true if the executable can be found" do expect(@confine).to receive(:which).with("/my/file").and_return("/my/file") expect(@confine.pass?("/my/file")).to be_truthy end end it "should produce a summary containing all missing files" do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect(Puppet::FileSystem).to receive(:exist?).with("/two").and_return(false) expect(Puppet::FileSystem).to receive(:exist?).with("/four").and_return(false) confine = Puppet::Confine::Exists.new %w{/one /two /three /four} expect(confine.summary).to eq(%w{/two /four}) end it "should summarize multiple instances by returning a flattened array of their summaries" do c1 = double('1', :summary => %w{one}) c2 = double('2', :summary => %w{two}) c3 = double('3', :summary => %w{three}) expect(Puppet::Confine::Exists.summarize([c1, c2, c3])).to eq(%w{one two three}) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confine/false_spec.rb
spec/unit/confine/false_spec.rb
require 'spec_helper' require 'puppet/confine/false' describe Puppet::Confine::False do it "should be named :false" do expect(Puppet::Confine::False.name).to eq(:false) end it "should require a value" do expect { Puppet::Confine.new }.to raise_error(ArgumentError) end describe "when passing in a lambda as a value for lazy evaluation" do it "should accept it" do confine = Puppet::Confine::False.new(lambda { false }) expect(confine.values).to eql([false]) end describe "when enforcing cache-positive behavior" do def cached_value_of(confine) confine.instance_variable_get(:@cached_value) end it "should cache a false value" do confine = Puppet::Confine::False.new(lambda { false }) confine.values expect(cached_value_of(confine)).to eql([false]) end it "should not cache a true value" do confine = Puppet::Confine::False.new(lambda { true }) confine.values expect(cached_value_of(confine)).to be_nil end end end describe "when testing values" do before { @confine = Puppet::Confine::False.new("foo") } it "should use the 'pass?' method to test validity" do @confine = Puppet::Confine::False.new("foo") @confine.label = "eh" expect(@confine).to receive(:pass?).with("foo") @confine.valid? end it "should return true if the value is false" do expect(@confine.pass?(false)).to be_truthy end it "should return false if the value is not false" do expect(@confine.pass?("else")).to be_falsey end it "should produce a message that a value is true" do @confine = Puppet::Confine::False.new("foo") expect(@confine.message("eh")).to be_include("true") end end it "should be able to produce a summary with the number of incorrectly true values" do confine = Puppet::Confine::False.new %w{one two three four} expect(confine).to receive(:pass?).exactly(4).times.and_return(true, false, true, false) expect(confine.summary).to eq(2) end it "should summarize multiple instances by summing their summaries" do c1 = double('1', :summary => 1) c2 = double('2', :summary => 2) c3 = double('3', :summary => 3) expect(Puppet::Confine::False.summarize([c1, c2, c3])).to eq(6) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confine/variable_spec.rb
spec/unit/confine/variable_spec.rb
require 'spec_helper' require 'puppet/confine/variable' describe Puppet::Confine::Variable do it "should be named :variable" do expect(Puppet::Confine::Variable.name).to eq(:variable) end it "should require a value" do expect { Puppet::Confine::Variable.new }.to raise_error(ArgumentError) end it "should always convert values to an array" do expect(Puppet::Confine::Variable.new("/some/file").values).to be_instance_of(Array) end it "should have an accessor for its name" do expect(Puppet::Confine::Variable.new(:bar)).to respond_to(:name) end describe "when testing values" do before do @confine = Puppet::Confine::Variable.new("foo") @confine.name = :myvar end it "should use settings if the variable name is a valid setting" do expect(Puppet.settings).to receive(:valid?).with(:myvar).and_return(true) expect(Puppet.settings).to receive(:value).with(:myvar).and_return("foo") @confine.valid? end it "should use Facter if the variable name is not a valid setting" do expect(Puppet.settings).to receive(:valid?).with(:myvar).and_return(false) expect(Facter).to receive(:value).with(:myvar).and_return("foo") @confine.valid? end it "should be valid if the value matches the facter value" do expect(@confine).to receive(:test_value).and_return("foo") expect(@confine).to be_valid end it "should return false if the value does not match the facter value" do expect(@confine).to receive(:test_value).and_return("fee") expect(@confine).not_to be_valid end it "should be case insensitive" do expect(@confine).to receive(:test_value).and_return("FOO") expect(@confine).to be_valid end it "should not care whether the value is a string or symbol" do expect(@confine).to receive(:test_value).and_return("FOO") expect(@confine).to be_valid end it "should produce a message that the fact value is not correct" do @confine = Puppet::Confine::Variable.new(%w{bar bee}) @confine.name = "eh" message = @confine.message("value") expect(message).to be_include("facter") expect(message).to be_include("bar,bee") end it "should be valid if the test value matches any of the provided values" do @confine = Puppet::Confine::Variable.new(%w{bar bee}) expect(@confine).to receive(:test_value).and_return("bee") expect(@confine).to be_valid end end describe "when summarizing multiple instances" do it "should return a hash of failing variables and their values" do c1 = Puppet::Confine::Variable.new("one") c1.name = "uno" expect(c1).to receive(:valid?).and_return(false) c2 = Puppet::Confine::Variable.new("two") c2.name = "dos" expect(c2).to receive(:valid?).and_return(true) c3 = Puppet::Confine::Variable.new("three") c3.name = "tres" expect(c3).to receive(:valid?).and_return(false) expect(Puppet::Confine::Variable.summarize([c1, c2, c3])).to eq({"uno" => %w{one}, "tres" => %w{three}}) end it "should combine the values of multiple confines with the same fact" do c1 = Puppet::Confine::Variable.new("one") c1.name = "uno" expect(c1).to receive(:valid?).and_return(false) c2 = Puppet::Confine::Variable.new("two") c2.name = "uno" expect(c2).to receive(:valid?).and_return(false) expect(Puppet::Confine::Variable.summarize([c1, c2])).to eq({"uno" => %w{one two}}) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confine/true_spec.rb
spec/unit/confine/true_spec.rb
require 'spec_helper' require 'puppet/confine/true' describe Puppet::Confine::True do it "should be named :true" do expect(Puppet::Confine::True.name).to eq(:true) end it "should require a value" do expect { Puppet::Confine::True.new }.to raise_error(ArgumentError) end describe "when passing in a lambda as a value for lazy evaluation" do it "should accept it" do confine = Puppet::Confine::True.new(lambda { true }) expect(confine.values).to eql([true]) end describe "when enforcing cache-positive behavior" do def cached_value_of(confine) confine.instance_variable_get(:@cached_value) end it "should cache a true value" do confine = Puppet::Confine::True.new(lambda { true }) confine.values expect(cached_value_of(confine)).to eql([true]) end it "should not cache a false value" do confine = Puppet::Confine::True.new(lambda { false }) confine.values expect(cached_value_of(confine)).to be_nil end end end describe "when testing values" do before do @confine = Puppet::Confine::True.new("foo") @confine.label = "eh" end it "should use the 'pass?' method to test validity" do expect(@confine).to receive(:pass?).with("foo") @confine.valid? end it "should return true if the value is not false" do expect(@confine.pass?("else")).to be_truthy end it "should return false if the value is false" do expect(@confine.pass?(nil)).to be_falsey end it "should produce the message that a value is false" do expect(@confine.message("eh")).to be_include("false") end end it "should produce the number of false values when asked for a summary" do @confine = Puppet::Confine::True.new %w{one two three four} expect(@confine).to receive(:pass?).exactly(4).times.and_return(true, false, true, false) expect(@confine.summary).to eq(2) end it "should summarize multiple instances by summing their summaries" do c1 = double('1', :summary => 1) c2 = double('2', :summary => 2) c3 = double('3', :summary => 3) expect(Puppet::Confine::True.summarize([c1, c2, c3])).to eq(6) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confine/feature_spec.rb
spec/unit/confine/feature_spec.rb
require 'spec_helper' require 'puppet/confine/feature' describe Puppet::Confine::Feature do it "should be named :feature" do expect(Puppet::Confine::Feature.name).to eq(:feature) end it "should require a value" do expect { Puppet::Confine::Feature.new }.to raise_error(ArgumentError) end it "should always convert values to an array" do expect(Puppet::Confine::Feature.new("/some/file").values).to be_instance_of(Array) end describe "when testing values" do before do @confine = Puppet::Confine::Feature.new("myfeature") @confine.label = "eh" end it "should use the Puppet features instance to test validity" do Puppet.features.add(:myfeature) do true end @confine.valid? end it "should return true if the feature is present" do Puppet.features.add(:myfeature) do true end expect(@confine.pass?("myfeature")).to be_truthy end it "should return false if the value is false" do Puppet.features.add(:myfeature) do false end expect(@confine.pass?("myfeature")).to be_falsey end it "should log that a feature is missing" do expect(@confine.message("myfeat")).to be_include("missing") end end it "should summarize multiple instances by returning a flattened array of all missing features" do confines = [] confines << Puppet::Confine::Feature.new(%w{one two}) confines << Puppet::Confine::Feature.new(%w{two}) confines << Puppet::Confine::Feature.new(%w{three four}) features = double('feature') allow(features).to receive(:one?) allow(features).to receive(:two?) allow(features).to receive(:three?) allow(features).to receive(:four?) allow(Puppet).to receive(:features).and_return(features) expect(Puppet::Confine::Feature.summarize(confines).sort).to eq(%w{one two three four}.sort) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/relationship_spec.rb
spec/unit/parser/relationship_spec.rb
require 'spec_helper' require 'puppet/parser/relationship' describe Puppet::Parser::Relationship do before do @source = Puppet::Resource.new(:mytype, "source") @target = Puppet::Resource.new(:mytype, "target") @extra_resource = Puppet::Resource.new(:mytype, "extra") @extra_resource2 = Puppet::Resource.new(:mytype, "extra2") @dep = Puppet::Parser::Relationship.new(@source, @target, :relationship) end describe "when evaluating" do before do @catalog = Puppet::Resource::Catalog.new @catalog.add_resource(@source) @catalog.add_resource(@target) @catalog.add_resource(@extra_resource) @catalog.add_resource(@extra_resource2) end it "should fail if the source resource cannot be found" do @catalog = Puppet::Resource::Catalog.new @catalog.add_resource @target expect { @dep.evaluate(@catalog) }.to raise_error(ArgumentError) end it "should fail if the target resource cannot be found" do @catalog = Puppet::Resource::Catalog.new @catalog.add_resource @source expect { @dep.evaluate(@catalog) }.to raise_error(ArgumentError) end it "should add the target as a 'before' value if the type is 'relationship'" do @dep.type = :relationship @dep.evaluate(@catalog) expect(@source[:before]).to be_include("Mytype[target]") end it "should add the target as a 'notify' value if the type is 'subscription'" do @dep.type = :subscription @dep.evaluate(@catalog) expect(@source[:notify]).to be_include("Mytype[target]") end it "should supplement rather than clobber existing relationship values" do @source[:before] = "File[/bar]" @dep.evaluate(@catalog) # this test did not work before. It was appending the resources # together as a string expect(@source[:before].class == Array).to be_truthy expect(@source[:before]).to be_include("Mytype[target]") expect(@source[:before]).to be_include("File[/bar]") end it "should supplement rather than clobber existing resource relationships" do @source[:before] = @extra_resource @dep.evaluate(@catalog) expect(@source[:before].class == Array).to be_truthy expect(@source[:before]).to be_include("Mytype[target]") expect(@source[:before]).to be_include(@extra_resource) end it "should supplement rather than clobber multiple existing resource relationships" do @source[:before] = [@extra_resource, @extra_resource2] @dep.evaluate(@catalog) expect(@source[:before].class == Array).to be_truthy expect(@source[:before]).to be_include("Mytype[target]") expect(@source[:before]).to be_include(@extra_resource) expect(@source[:before]).to be_include(@extra_resource2) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/type_loader_spec.rb
spec/unit/parser/type_loader_spec.rb
require 'spec_helper' require 'puppet/parser/type_loader' require 'puppet/parser/parser_factory' require 'puppet_spec/modules' require 'puppet_spec/files' describe Puppet::Parser::TypeLoader do include PuppetSpec::Modules include PuppetSpec::Files let(:empty_hostclass) { Puppet::Parser::AST::Hostclass.new('') } let(:loader) { Puppet::Parser::TypeLoader.new(:myenv) } let(:my_env) { Puppet::Node::Environment.create(:myenv, []) } around do |example| envs = Puppet::Environments::Static.new(my_env) Puppet.override(:environments => envs) do example.run end end it "should support an environment" do loader = Puppet::Parser::TypeLoader.new(:myenv) expect(loader.environment.name).to eq(:myenv) end it "should delegate its known resource types to its environment" do expect(loader.known_resource_types).to be_instance_of(Puppet::Resource::TypeCollection) end describe "when loading names from namespaces" do it "should do nothing if the name to import is an empty string" do expect(loader.try_load_fqname(:hostclass, "")).to be_nil end it "should attempt to import each generated name" do expect(loader).to receive(:import_from_modules).with("foo/bar").and_return([]) expect(loader).to receive(:import_from_modules).with("foo").and_return([]) loader.try_load_fqname(:hostclass, "foo::bar") end it "should attempt to load each possible name going from most to least specific" do ['foo/bar/baz', 'foo/bar', 'foo'].each do |path| expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).with(path, anything).and_return([nil, []]).ordered end loader.try_load_fqname(:hostclass, 'foo::bar::baz') end end describe "when importing" do let(:stub_parser) { double('Parser', :file= => nil, :parse => empty_hostclass) } before(:each) do allow(Puppet::Parser::ParserFactory).to receive(:parser).and_return(stub_parser) end it "should find all manifests matching the file or pattern" do expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).with("myfile", anything).and_return(["modname", %w{one}]) loader.import("myfile", "/path") end it "should pass the environment when looking for files" do expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).with(anything, loader.environment).and_return(["modname", %w{one}]) loader.import("myfile", "/path") end it "should fail if no files are found" do expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).and_return([nil, []]) expect { loader.import("myfile", "/path") }.to raise_error(/No file\(s\) found for import/) end it "should parse each found file" do expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).and_return(["modname", [make_absolute("/one")]]) expect(loader).to receive(:parse_file).with(make_absolute("/one")).and_return(Puppet::Parser::AST::Hostclass.new('')) loader.import("myfile", "/path") end it "should not attempt to import files that have already been imported" do loader = Puppet::Parser::TypeLoader.new(:myenv) expect(Puppet::Parser::Files).to receive(:find_manifests_in_modules).twice.and_return(["modname", %w{/one}]) expect(loader.import("myfile", "/path")).not_to be_empty expect(loader.import("myfile", "/path")).to be_empty end end describe "when importing all" do let(:base) { tmpdir("base") } let(:modulebase1) { File.join(base, "first") } let(:modulebase2) { File.join(base, "second") } let(:my_env) { Puppet::Node::Environment.create(:myenv, [modulebase1, modulebase2]) } before do # Create two module path directories FileUtils.mkdir_p(modulebase1) FileUtils.mkdir_p(modulebase2) end def mk_module(basedir, name) PuppetSpec::Modules.create(name, basedir) end # We have to pass the base path so that we can # write to modules that are in the second search path def mk_manifests(base, mod, files) files.collect do |file| name = mod.name + "::" + file.gsub("/", "::") path = File.join(base, mod.name, "manifests", file + ".pp") FileUtils.mkdir_p(File.split(path)[0]) # write out the class File.open(path, "w") { |f| f.print "class #{name} {}" } name end end it "should load all puppet manifests from all modules in the specified environment" do module1 = mk_module(modulebase1, "one") module2 = mk_module(modulebase2, "two") mk_manifests(modulebase1, module1, %w{a b}) mk_manifests(modulebase2, module2, %w{c d}) loader.import_all expect(loader.environment.known_resource_types.hostclass("one::a")).to be_instance_of(Puppet::Resource::Type) expect(loader.environment.known_resource_types.hostclass("one::b")).to be_instance_of(Puppet::Resource::Type) expect(loader.environment.known_resource_types.hostclass("two::c")).to be_instance_of(Puppet::Resource::Type) expect(loader.environment.known_resource_types.hostclass("two::d")).to be_instance_of(Puppet::Resource::Type) end it "should not load manifests from duplicate modules later in the module path" do module1 = mk_module(modulebase1, "one") # duplicate module2 = mk_module(modulebase2, "one") mk_manifests(modulebase1, module1, %w{a}) mk_manifests(modulebase2, module2, %w{c}) loader.import_all expect(loader.environment.known_resource_types.hostclass("one::c")).to be_nil end it "should load manifests from subdirectories" do module1 = mk_module(modulebase1, "one") mk_manifests(modulebase1, module1, %w{a a/b a/b/c}) loader.import_all expect(loader.environment.known_resource_types.hostclass("one::a::b")).to be_instance_of(Puppet::Resource::Type) expect(loader.environment.known_resource_types.hostclass("one::a::b::c")).to be_instance_of(Puppet::Resource::Type) end it "should skip modules that don't have manifests" do mk_module(modulebase1, "one") module2 = mk_module(modulebase2, "two") mk_manifests(modulebase2, module2, %w{c d}) loader.import_all expect(loader.environment.known_resource_types.hostclass("one::a")).to be_nil expect(loader.environment.known_resource_types.hostclass("two::c")).to be_instance_of(Puppet::Resource::Type) expect(loader.environment.known_resource_types.hostclass("two::d")).to be_instance_of(Puppet::Resource::Type) end end describe "when parsing a file" do it "requests a new parser instance for each file" do parser = double('Parser', :file= => nil, :parse => empty_hostclass) expect(Puppet::Parser::ParserFactory).to receive(:parser).twice.and_return(parser) loader.parse_file("/my/file") loader.parse_file("/my/other_file") end it "assigns the parser its file and then parses" do parser = double('parser') expect(Puppet::Parser::ParserFactory).to receive(:parser).and_return(parser) expect(parser).to receive(:file=).with("/my/file") expect(parser).to receive(:parse).and_return(empty_hostclass) loader.parse_file("/my/file") end end it "should be able to add classes to the current resource type collection" do file = tmpfile("simple_file.pp") File.open(file, "w") { |f| f.puts "class foo {}" } loader.import(File.basename(file), File.dirname(file)) expect(loader.known_resource_types.hostclass("foo")).to be_instance_of(Puppet::Resource::Type) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/templatewrapper_spec.rb
spec/unit/parser/templatewrapper_spec.rb
require 'spec_helper' require 'puppet/parser/templatewrapper' describe Puppet::Parser::TemplateWrapper do include PuppetSpec::Files let(:known_resource_types) { Puppet::Resource::TypeCollection.new("env") } let(:scope) do compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("mynode")) allow(compiler.environment).to receive(:known_resource_types).and_return(known_resource_types) Puppet::Parser::Scope.new compiler end let(:tw) { Puppet::Parser::TemplateWrapper.new(scope) } it "fails if a template cannot be found" do expect(Puppet::Parser::Files).to receive(:find_template).and_return(nil) expect { tw.file = "fake_template" }.to raise_error(Puppet::ParseError) end it "stringifies as template[<filename>] for a file based template" do allow(Puppet::Parser::Files).to receive(:find_template).and_return("/tmp/fake_template") tw.file = "fake_template" expect(tw.to_s).to eql("template[/tmp/fake_template]") end it "stringifies as template[inline] for a string-based template" do expect(tw.to_s).to eql("template[inline]") end it "reads and evaluates a file-based template" do given_a_template_file("fake_template", "template contents") tw.file = "fake_template" expect(tw.result).to eql("template contents") end it "provides access to the name of the template via #file" do full_file_name = given_a_template_file("fake_template", "<%= file %>") tw.file = "fake_template" expect(tw.result).to eq(full_file_name) end it "ignores a leading BOM" do full_file_name = given_a_template_file("bom_template", "\uFEFF<%= file %>") tw.file = "bom_template" expect(tw.result).to eq(full_file_name) end it "evaluates a given string as a template" do expect(tw.result("template contents")).to eql("template contents") end it "provides the defined classes with #classes" do catalog = double('catalog', :classes => ["class1", "class2"]) expect(scope).to receive(:catalog).and_return(catalog) expect(tw.classes).to eq(["class1", "class2"]) end it "provides all the tags with #all_tags" do catalog = double('catalog', :tags => ["tag1", "tag2"]) expect(scope).to receive(:catalog).and_return(catalog) expect(tw.all_tags).to eq(["tag1","tag2"]) end it "raises not implemented error" do expect { tw.tags }.to raise_error(NotImplementedError, /Call 'all_tags' instead/) end it "raises error on access to removed in-scope variables via method calls" do scope["in_scope_variable"] = "is good" expect { tw.result("<%= in_scope_variable %>") }.to raise_error(/undefined local variable or metho.*in_scope_variable'/ ) end it "reports that variable is available when it is in scope" do scope["in_scope_variable"] = "is good" expect(tw.result("<%= has_variable?('in_scope_variable') %>")).to eq("true") end it "reports that a variable is not available when it is not in scope" do expect(tw.result("<%= has_variable?('not_in_scope_variable') %>")).to eq("false") end it "provides access to in-scope variables via instance variables" do scope["one"] = "foo" expect(tw.result("<%= @one %>")).to eq("foo") end %w{! . ; :}.each do |badchar| it "translates #{badchar} to _ in instance variables" do scope["one#{badchar}"] = "foo" expect(tw.result("<%= @one_ %>")).to eq("foo") end end def given_a_template_file(name, contents) full_name = tmpfile("template_#{name}") File.binwrite(full_name, contents) allow(Puppet::Parser::Files).to receive(:find_template). with(name, anything()). and_return(full_name) full_name end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/scope_spec.rb
spec/unit/parser/scope_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet_spec/scope' describe Puppet::Parser::Scope do include PuppetSpec::Scope before :each do @scope = Puppet::Parser::Scope.new( Puppet::Parser::Compiler.new(Puppet::Node.new("foo")) ) @scope.source = Puppet::Resource::Type.new(:node, :foo) @topscope = @scope.compiler.topscope @scope.parent = @topscope end describe "create_test_scope_for_node" do let(:node_name) { "node_name_foo" } let(:scope) { create_test_scope_for_node(node_name) } it "should be a kind of Scope" do expect(scope).to be_a_kind_of(Puppet::Parser::Scope) end it "should set the source to a node resource" do expect(scope.source).to be_a_kind_of(Puppet::Resource::Type) end it "should have a compiler" do expect(scope.compiler).to be_a_kind_of(Puppet::Parser::Compiler) end it "should set the parent to the compiler topscope" do expect(scope.parent).to be(scope.compiler.topscope) end end it "should generate a simple string when inspecting a scope" do expect(@scope.inspect).to eq("Scope()") end it "should generate a simple string when inspecting a scope with a resource" do @scope.resource="foo::bar" expect(@scope.inspect).to eq("Scope(foo::bar)") end it "should generate a path if there is one on the puppet stack" do result = Puppet::Pops::PuppetStack.stack('/tmp/kansas.pp', 42, @scope, 'inspect', []) expect(result).to eq("Scope(/tmp/kansas.pp, 42)") end it "should generate an <env> shortened path if path points into the environment" do env_path = @scope.environment.configuration.path_to_env mocked_path = File.join(env_path, 'oz.pp') result = Puppet::Pops::PuppetStack.stack(mocked_path, 42, @scope, 'inspect', []) expect(result).to eq("Scope(<env>/oz.pp, 42)") end it "should generate a <module> shortened path if path points into a module" do mocked_path = File.join(@scope.environment.full_modulepath[0], 'mymodule', 'oz.pp') result = Puppet::Pops::PuppetStack.stack(mocked_path, 42, @scope, 'inspect', []) expect(result).to eq("Scope(<module>/mymodule/oz.pp, 42)") end it "should return a scope for use in a test harness" do expect(create_test_scope_for_node("node_name_foo")).to be_a_kind_of(Puppet::Parser::Scope) end it "should be able to retrieve class scopes by name" do @scope.class_set "myname", "myscope" expect(@scope.class_scope("myname")).to eq("myscope") end it "should be able to retrieve class scopes by object" do klass = double('ast_class') expect(klass).to receive(:name).and_return("myname") @scope.class_set "myname", "myscope" expect(@scope.class_scope(klass)).to eq("myscope") end it "should be able to retrieve its parent module name from the source of its parent type" do @topscope.source = Puppet::Resource::Type.new(:hostclass, :foo, :module_name => "foo") expect(@scope.parent_module_name).to eq("foo") end it "should return a nil parent module name if it has no parent" do expect(@topscope.parent_module_name).to be_nil end it "should return a nil parent module name if its parent has no source" do expect(@scope.parent_module_name).to be_nil end it "should get its environment from its compiler" do env = Puppet::Node::Environment.create(:testing, []) compiler = double('compiler', :environment => env, :is_a? => true) scope = Puppet::Parser::Scope.new(compiler) expect(scope.environment).to equal(env) end it "should fail if no compiler is supplied" do expect { Puppet::Parser::Scope.new }.to raise_error(ArgumentError, /wrong number of arguments/) end it "should fail if something that isn't a compiler is supplied" do expect { Puppet::Parser::Scope.new(nil) }.to raise_error(Puppet::DevError, /you must pass a compiler instance/) end describe "when custom functions are called" do let(:env) { Puppet::Node::Environment.create(:testing, []) } let(:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new('foo', :environment => env)) } let(:scope) { Puppet::Parser::Scope.new(compiler) } it "calls methods prefixed with function_ as custom functions" do expect(scope.function_sprintf(["%b", 123])).to eq("1111011") end it "raises an error when arguments are not passed in an Array" do expect do scope.function_sprintf("%b", 123) end.to raise_error ArgumentError, /custom functions must be called with a single array that contains the arguments/ end it "raises an error on subsequent calls when arguments are not passed in an Array" do scope.function_sprintf(["first call"]) expect do scope.function_sprintf("%b", 123) end.to raise_error ArgumentError, /custom functions must be called with a single array that contains the arguments/ end it "raises NoMethodError when the not prefixed" do expect { scope.sprintf(["%b", 123]) }.to raise_error(NoMethodError) end it "raises NoMethodError when prefixed with function_ but it doesn't exist" do expect { scope.function_fake_bs(['cows']) }.to raise_error(NoMethodError) end end describe "when initializing" do it "should extend itself with its environment's Functions module as well as the default" do env = Puppet::Node::Environment.create(:myenv, []) root = Puppet.lookup(:root_environment) compiler = double('compiler', :environment => env, :is_a? => true) scope = Puppet::Parser::Scope.new(compiler) expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(env)) expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(root)) end it "should extend itself with the default Functions module if its environment is the default" do root = Puppet.lookup(:root_environment) node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) scope = Puppet::Parser::Scope.new(compiler) expect(scope.singleton_class.ancestors).to be_include(Puppet::Parser::Functions.environment_module(root)) end end describe "when looking up a variable" do before :each do Puppet[:strict] = :warning end it "should support :lookupvar and :setvar for backward compatibility" do @scope.setvar("var", "yep") expect(@scope.lookupvar("var")).to eq("yep") end it "should fail if invoked with a non-string name" do expect { @scope[:foo] }.to raise_error(Puppet::ParseError, /Scope variable name .* not a string/) expect { @scope[:foo] = 12 }.to raise_error(Puppet::ParseError, /Scope variable name .* not a string/) end it "should return nil for unset variables when --strict variables is not in effect" do expect(@scope["var"]).to be_nil end it "answers exist? with boolean false for non existing variables" do expect(@scope.exist?("var")).to be(false) end it "answers exist? with boolean false for non existing variables" do @scope["var"] = "yep" expect(@scope.exist?("var")).to be(true) end it "should be able to look up values" do @scope["var"] = "yep" expect(@scope["var"]).to eq("yep") end it "should be able to look up hashes" do @scope["var"] = {"a" => "b"} expect(@scope["var"]).to eq({"a" => "b"}) end it "should be able to look up variables in parent scopes" do @topscope["var"] = "parentval" expect(@scope["var"]).to eq("parentval") end it "should prefer its own values to parent values" do @topscope["var"] = "parentval" @scope["var"] = "childval" expect(@scope["var"]).to eq("childval") end it "should be able to detect when variables are set" do @scope["var"] = "childval" expect(@scope).to be_include("var") end it "does not allow changing a set value" do @scope["var"] = "childval" expect { @scope["var"] = "change" }.to raise_error(Puppet::Error, "Cannot reassign variable '$var'") end it "should be able to detect when variables are not set" do expect(@scope).not_to be_include("var") end it "warns and return nil for non found unqualified variable" do expect(Puppet).to receive(:warn_once) expect(@scope["santa_clause"]).to be_nil end it "warns once for a non found variable" do expect(Puppet).to receive(:send_log).with(:warning, be_a(String)).once expect([@scope["santa_claus"],@scope["santa_claus"]]).to eq([nil, nil]) end it "warns and return nil for non found qualified variable" do expect(Puppet).to receive(:warn_once) expect(@scope["north_pole::santa_clause"]).to be_nil end it "does not warn when a numeric variable is missing - they always exist" do expect(Puppet).not_to receive(:warn_once) expect(@scope["1"]).to be_nil end describe "and the variable is qualified" do before :each do @known_resource_types = @scope.environment.known_resource_types node = Puppet::Node.new('localhost') @compiler = Puppet::Parser::Compiler.new(node) end def newclass(name) @known_resource_types.add Puppet::Resource::Type.new(:hostclass, name) end def create_class_scope(name) klass = newclass(name) catalog = Puppet::Resource::Catalog.new catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => Puppet::Parser::Scope.new(@compiler))) Puppet::Parser::Resource.new("class", name, :scope => @scope, :source => double('source'), :catalog => catalog).evaluate @scope.class_scope(klass) end it "should be able to look up explicitly fully qualified variables from compiler's top scope" do expect(Puppet).not_to receive(:deprecation_warning) other_scope = @scope.compiler.topscope other_scope["othervar"] = "otherval" expect(@scope["::othervar"]).to eq("otherval") end it "should be able to look up explicitly fully qualified variables from other scopes" do expect(Puppet).not_to receive(:deprecation_warning) other_scope = create_class_scope("other") other_scope["var"] = "otherval" expect(@scope["::other::var"]).to eq("otherval") end it "should be able to look up deeply qualified variables" do expect(Puppet).not_to receive(:deprecation_warning) other_scope = create_class_scope("other::deep::klass") other_scope["var"] = "otherval" expect(@scope["other::deep::klass::var"]).to eq("otherval") end it "should return nil for qualified variables that cannot be found in other classes" do create_class_scope("other::deep::klass") expect(@scope["other::deep::klass::var"]).to be_nil end it "should warn and return nil for qualified variables whose classes have not been evaluated" do newclass("other::deep::klass") expect(Puppet).to receive(:warn_once) expect(@scope["other::deep::klass::var"]).to be_nil end it "should warn and return nil for qualified variables whose classes do not exist" do expect(Puppet).to receive(:warn_once) expect(@scope["other::deep::klass::var"]).to be_nil end it "should return nil when asked for a non-string qualified variable from a class that does not exist" do expect(@scope["other::deep::klass::var"]).to be_nil end it "should return nil when asked for a non-string qualified variable from a class that has not been evaluated" do allow(@scope).to receive(:warning) newclass("other::deep::klass") expect(@scope["other::deep::klass::var"]).to be_nil end end context "and strict_variables is true" do before(:each) do Puppet[:strict_variables] = true end it "should throw a symbol when unknown variable is looked up" do expect { @scope['john_doe'] }.to throw_symbol(:undefined_variable) end it "should throw a symbol when unknown qualified variable is looked up" do expect { @scope['nowhere::john_doe'] }.to throw_symbol(:undefined_variable) end it "should not raise an error when built in variable is looked up" do expect { @scope['caller_module_name'] }.to_not raise_error expect { @scope['module_name'] }.to_not raise_error end end context "and strict_variables is false and --strict=off" do before(:each) do Puppet[:strict_variables] = false Puppet[:strict] = :off end it "should not error when unknown variable is looked up and produce nil" do expect(@scope['john_doe']).to be_nil end it "should not error when unknown qualified variable is looked up and produce nil" do expect(@scope['nowhere::john_doe']).to be_nil end end context "and strict_variables is false and --strict=warning" do before(:each) do Puppet[:strict_variables] = false Puppet[:strict] = :warning end it "should not error when unknown variable is looked up" do expect(@scope['john_doe']).to be_nil end it "should not error when unknown qualified variable is looked up" do expect(@scope['nowhere::john_doe']).to be_nil end end context "and strict_variables is false and --strict=error" do before(:each) do Puppet[:strict_variables] = false Puppet[:strict] = :error end it "should raise error when unknown variable is looked up" do expect { @scope['john_doe'] }.to raise_error(/Undefined variable/) end it "should not throw a symbol when unknown qualified variable is looked up" do expect { @scope['nowhere::john_doe'] }.to raise_error(/Undefined variable/) end end end describe "when calling number?" do it "should return nil if called with anything not a number" do expect(Puppet::Parser::Scope.number?([2])).to be_nil end it "should return a Integer for an Integer" do expect(Puppet::Parser::Scope.number?(2)).to be_a(Integer) end it "should return a Float for a Float" do expect(Puppet::Parser::Scope.number?(2.34)).to be_an_instance_of(Float) end it "should return 234 for '234'" do expect(Puppet::Parser::Scope.number?("234")).to eq(234) end it "should return nil for 'not a number'" do expect(Puppet::Parser::Scope.number?("not a number")).to be_nil end it "should return 23.4 for '23.4'" do expect(Puppet::Parser::Scope.number?("23.4")).to eq(23.4) end it "should return 23.4e13 for '23.4e13'" do expect(Puppet::Parser::Scope.number?("23.4e13")).to eq(23.4e13) end it "should understand negative numbers" do expect(Puppet::Parser::Scope.number?("-234")).to eq(-234) end it "should know how to convert exponential float numbers ala '23e13'" do expect(Puppet::Parser::Scope.number?("23e13")).to eq(23e13) end it "should understand hexadecimal numbers" do expect(Puppet::Parser::Scope.number?("0x234")).to eq(0x234) end it "should understand octal numbers" do expect(Puppet::Parser::Scope.number?("0755")).to eq(0755) end it "should return nil on malformed integers" do expect(Puppet::Parser::Scope.number?("0.24.5")).to be_nil end it "should convert strings with leading 0 to integer if they are not octal" do expect(Puppet::Parser::Scope.number?("0788")).to eq(788) end it "should convert strings of negative integers" do expect(Puppet::Parser::Scope.number?("-0788")).to eq(-788) end it "should return nil on malformed hexadecimal numbers" do expect(Puppet::Parser::Scope.number?("0x89g")).to be_nil end end describe "when using ephemeral variables" do it "should store the variable value" do @scope.set_match_data({1 => :value}) expect(@scope["1"]).to eq(:value) end it "should raise an error when setting numerical variable" do expect { @scope.setvar("1", :value3, :ephemeral => true) }.to raise_error(Puppet::ParseError, /Cannot assign to a numeric match result variable/) end describe "with more than one level" do it "should prefer latest ephemeral scopes" do @scope.set_match_data({0 => :earliest}) @scope.new_ephemeral @scope.set_match_data({0 => :latest}) expect(@scope["0"]).to eq(:latest) end it "should be able to report the current level" do expect(@scope.ephemeral_level).to eq(1) @scope.new_ephemeral expect(@scope.ephemeral_level).to eq(2) end it "should not check presence of an ephemeral variable across multiple levels" do @scope.new_ephemeral @scope.set_match_data({1 => :value1}) @scope.new_ephemeral @scope.set_match_data({0 => :value2}) @scope.new_ephemeral expect(@scope.include?("1")).to be_falsey end it "should return false when an ephemeral variable doesn't exist in any ephemeral scope" do @scope.new_ephemeral @scope.set_match_data({1 => :value1}) @scope.new_ephemeral @scope.set_match_data({0 => :value2}) @scope.new_ephemeral expect(@scope.include?("2")).to be_falsey end it "should not get ephemeral values from earlier scope when not in later" do @scope.set_match_data({1 => :value1}) @scope.new_ephemeral @scope.set_match_data({0 => :value2}) expect(@scope.include?("1")).to be_falsey end describe "when using a guarded scope" do it "should remove ephemeral scopes up to this level" do @scope.set_match_data({1 => :value1}) @scope.new_ephemeral @scope.set_match_data({1 => :value2}) @scope.with_guarded_scope do @scope.new_ephemeral @scope.set_match_data({1 => :value3}) end expect(@scope["1"]).to eq(:value2) end end end end context "when using ephemeral as local scope" do it "should store all variables in local scope" do @scope.new_ephemeral true @scope.setvar("apple", :fruit) expect(@scope["apple"]).to eq(:fruit) end it 'should store an undef in local scope and let it override parent scope' do @scope['cloaked'] = 'Cloak me please' @scope.new_ephemeral(true) @scope['cloaked'] = nil expect(@scope['cloaked']).to eq(nil) end it "should be created from a hash" do @scope.ephemeral_from({ "apple" => :fruit, "strawberry" => :berry}) expect(@scope["apple"]).to eq(:fruit) expect(@scope["strawberry"]).to eq(:berry) end end describe "when setting ephemeral vars from matches" do before :each do @match = double('match', :is_a? => true) allow(@match).to receive(:[]).with(0).and_return("this is a string") allow(@match).to receive(:captures).and_return([]) allow(@scope).to receive(:setvar) end it "should accept only MatchData" do expect { @scope.ephemeral_from("match") }.to raise_error(ArgumentError, /Invalid regex match data/) end it "should set $0 with the full match" do # This is an internal impl detail test expect(@scope).to receive(:new_match_scope) do |arg| expect(arg[0]).to eq("this is a string") end @scope.ephemeral_from(@match) end it "should set every capture as ephemeral var" do # This is an internal impl detail test allow(@match).to receive(:[]).with(1).and_return(:capture1) allow(@match).to receive(:[]).with(2).and_return(:capture2) expect(@scope).to receive(:new_match_scope) do |arg| expect(arg[1]).to eq(:capture1) expect(arg[2]).to eq(:capture2) end @scope.ephemeral_from(@match) end it "should shadow previous match variables" do # This is an internal impl detail test allow(@match).to receive(:[]).with(1).and_return(:capture1) allow(@match).to receive(:[]).with(2).and_return(:capture2) @match2 = double('match', :is_a? => true) allow(@match2).to receive(:[]).with(1).and_return(:capture2_1) allow(@match2).to receive(:[]).with(2).and_return(nil) @scope.ephemeral_from(@match) @scope.ephemeral_from(@match2) expect(@scope.lookupvar('2')).to eq(nil) end it "should create a new ephemeral level" do level_before = @scope.ephemeral_level @scope.ephemeral_from(@match) expect(level_before < @scope.ephemeral_level) end end describe "when managing defaults" do it "should be able to set and lookup defaults" do param = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source")) @scope.define_settings(:mytype, param) expect(@scope.lookupdefaults(:mytype)).to eq({:myparam => param}) end it "should fail if a default is already defined and a new default is being defined" do param = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source")) @scope.define_settings(:mytype, param) expect { @scope.define_settings(:mytype, param) }.to raise_error(Puppet::ParseError, /Default already defined .* cannot redefine/) end it "should return multiple defaults at once" do param1 = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source")) @scope.define_settings(:mytype, param1) param2 = Puppet::Parser::Resource::Param.new(:name => :other, :value => "myvalue", :source => double("source")) @scope.define_settings(:mytype, param2) expect(@scope.lookupdefaults(:mytype)).to eq({:myparam => param1, :other => param2}) end it "should look up defaults defined in parent scopes" do param1 = Puppet::Parser::Resource::Param.new(:name => :myparam, :value => "myvalue", :source => double("source")) @scope.define_settings(:mytype, param1) child_scope = @scope.newscope param2 = Puppet::Parser::Resource::Param.new(:name => :other, :value => "myvalue", :source => double("source")) child_scope.define_settings(:mytype, param2) expect(child_scope.lookupdefaults(:mytype)).to eq({:myparam => param1, :other => param2}) end end context "#true?" do { "a string" => true, "true" => true, "false" => true, true => true, "" => false, :undef => false, nil => false }.each do |input, output| it "should treat #{input.inspect} as #{output}" do expect(Puppet::Parser::Scope.true?(input)).to eq(output) end end end context "when producing a hash of all variables (as used in templates)" do it "should contain all defined variables in the scope" do @scope.setvar("orange", :tangerine) @scope.setvar("pear", :green) expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green }) end it "should contain variables in all local scopes (#21508)" do @scope.new_ephemeral true @scope.setvar("orange", :tangerine) @scope.setvar("pear", :green) @scope.new_ephemeral true @scope.setvar("apple", :red) expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green, 'apple' => :red }) end it "should contain all defined variables in the scope and all local scopes" do @scope.setvar("orange", :tangerine) @scope.setvar("pear", :green) @scope.new_ephemeral true @scope.setvar("apple", :red) expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green, 'apple' => :red }) end it "should not contain varaibles in match scopes (non local emphemeral)" do @scope.new_ephemeral true @scope.setvar("orange", :tangerine) @scope.setvar("pear", :green) @scope.ephemeral_from(/(f)(o)(o)/.match('foo')) expect(@scope.to_hash).to eq({'orange' => :tangerine, 'pear' => :green }) end it "should delete values that are :undef in inner scope" do @scope.new_ephemeral true @scope.setvar("orange", :tangerine) @scope.setvar("pear", :green) @scope.new_ephemeral true @scope.setvar("apple", :red) @scope.setvar("orange", :undef) expect(@scope.to_hash).to eq({'pear' => :green, 'apple' => :red }) end it "should not delete values that are :undef in inner scope when include_undef is true" do @scope.new_ephemeral true @scope.setvar("orange", :tangerine) @scope.setvar("pear", :green) @scope.new_ephemeral true @scope.setvar("apple", :red) @scope.setvar("orange", :undef) expect(@scope.to_hash(true, true)).to eq({'pear' => :green, 'apple' => :red, 'orange' => :undef }) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/files_spec.rb
spec/unit/parser/files_spec.rb
require 'spec_helper' require 'puppet/parser/files' describe Puppet::Parser::Files do include PuppetSpec::Files let(:modulepath) { tmpdir("modulepath") } let(:environment) { Puppet::Node::Environment.create(:testing, [modulepath]) } let(:mymod) { File.join(modulepath, "mymod") } let(:mymod_files) { File.join(mymod, "files") } let(:mymod_a_file) { File.join(mymod_files, "some.txt") } let(:mymod_templates) { File.join(mymod, "templates") } let(:mymod_a_template) { File.join(mymod_templates, "some.erb") } let(:mymod_manifests) { File.join(mymod, "manifests") } let(:mymod_init_manifest) { File.join(mymod_manifests, "init.pp") } let(:mymod_another_manifest) { File.join(mymod_manifests, "another.pp") } let(:an_absolute_file_path_outside_of_module) { make_absolute("afilenamesomewhere") } before do FileUtils.mkdir_p(mymod_files) File.open(mymod_a_file, 'w') do |f| f.puts('something') end FileUtils.mkdir_p(mymod_templates) File.open(mymod_a_template, 'w') do |f| f.puts('<%= "something" %>') end FileUtils.mkdir_p(mymod_manifests) File.open(mymod_init_manifest, 'w') do |f| f.puts('class mymod { }') end File.open(mymod_another_manifest, 'w') do |f| f.puts('class mymod::another { }') end end describe "when searching for files" do it "returns fully-qualified file names directly" do expect(Puppet::Parser::Files.find_file(an_absolute_file_path_outside_of_module, environment)).to eq(an_absolute_file_path_outside_of_module) end it "returns the full path to the file if given a modulename/relative_filepath selector " do expect(Puppet::Parser::Files.find_file("mymod/some.txt", environment)).to eq(mymod_a_file) end it "returns nil if the module is not found" do expect(Puppet::Parser::Files.find_file("mod_does_not_exist/myfile", environment)).to be_nil end it "also returns nil if the module is found, but the file is not" do expect(Puppet::Parser::Files.find_file("mymod/file_does_not_exist", environment)).to be_nil end end describe "when searching for templates" do it "returns fully-qualified templates directly" do expect(Puppet::Parser::Files.find_template(an_absolute_file_path_outside_of_module, environment)).to eq(an_absolute_file_path_outside_of_module) end it "returns the full path to the template if given a modulename/relative_templatepath selector" do expect(Puppet::Parser::Files.find_template("mymod/some.erb", environment)).to eq(mymod_a_template) end it "returns nil if the module is not found" do expect(Puppet::Parser::Files.find_template("module_does_not_exist/mytemplate", environment)).to be_nil end it "returns nil if the module is found, but the template is not " do expect(Puppet::Parser::Files.find_template("mymod/template_does_not_exist", environment)).to be_nil end end describe "when searching for manifests in a module" do let(:no_manifests_found) { [nil, []] } it "ignores invalid module names" do expect(Puppet::Parser::Files.find_manifests_in_modules("mod.has.invalid.name/init.pp", environment)).to eq(no_manifests_found) end it "returns no files when no module is found" do expect(Puppet::Parser::Files.find_manifests_in_modules("not_here_module/init.pp", environment)).to eq(no_manifests_found) end it "returns the name of the module and the manifests from the first found module" do expect(Puppet::Parser::Files.find_manifests_in_modules("mymod/init.pp", environment) ).to eq(["mymod", [mymod_init_manifest]]) end it "always includes init.pp if present" do expect(Puppet::Parser::Files.find_manifests_in_modules("mymod/another.pp", environment) ).to eq(["mymod", [mymod_init_manifest, mymod_another_manifest]]) end it "does not find the module when it is a different environment" do different_env = Puppet::Node::Environment.create(:different, []) expect(Puppet::Parser::Files.find_manifests_in_modules("mymod/init.pp", different_env)).to eq(no_manifests_found) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/functions_spec.rb
spec/unit/parser/functions_spec.rb
require 'spec_helper' describe Puppet::Parser::Functions do def callable_functions_from(mod) Class.new { include mod }.new end let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) } let(:environment) { Puppet::Node::Environment.create(:myenv, []) } before do Puppet::Parser::Functions.reset end it "should have a method for returning an environment-specific module" do expect(Puppet::Parser::Functions.environment_module(environment)).to be_instance_of(Module) end describe "when calling newfunction" do it "should create the function in the environment module" do Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } expect(function_module).to be_method_defined :function_name end it "should warn if the function already exists" do Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } expect(Puppet).to receive(:warning) Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } end it "should raise an error if the function type is not correct" do expect { Puppet::Parser::Functions.newfunction("name", :type => :unknown) { |args| } }.to raise_error Puppet::DevError, "Invalid statement type :unknown" end it "instruments the function to profile the execution" do messages = [] Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::WallClock.new(proc { |msg| messages << msg }, "id")) Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } callable_functions_from(function_module).function_name([]) expect(messages.first).to match(/Called name/) end end describe "when calling function to test function existence" do before :each do Puppet[:strict] = :error end it "emits a deprecation warning when loading all 3.x functions" do allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:loadall) Puppet::Parser::Functions.autoloader.loadall expect(@logs.map(&:to_s)).to include(/The method 'Puppet::Parser::Functions.autoloader#loadall' is deprecated in favor of using 'Scope#call_function/) end it "emits a deprecation warning when loading a single 3.x function" do allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:load) Puppet::Parser::Functions.autoloader.load('beatles') expect(@logs.map(&:to_s)).to include(/The method 'Puppet::Parser::Functions.autoloader#load\("beatles"\)' is deprecated in favor of using 'Scope#call_function'/) end it "emits a deprecation warning when checking if a 3x function is loaded" do allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:loaded?).and_return(false) Puppet::Parser::Functions.autoloader.loaded?('beatles') expect(@logs.map(&:to_s)).to include(/The method 'Puppet::Parser::Functions.autoloader#loaded\?\(\"beatles\"\)' is deprecated in favor of using 'Scope#call_function'/) end it "should return false if the function doesn't exist" do allow(Puppet::Parser::Functions.autoloader.delegatee).to receive(:load) expect(Puppet::Parser::Functions.function("name")).to be_falsey end it "should return its name if the function exists" do Puppet::Parser::Functions.newfunction("name", :type => :rvalue) { |args| } expect(Puppet::Parser::Functions.function("name")).to eq("function_name") end it "should try to autoload the function if it doesn't exist yet" do expect(Puppet::Parser::Functions.autoloader.delegatee).to receive(:load) Puppet::Parser::Functions.function("name") end it "combines functions from the root with those from the current environment" do Puppet.override(:current_environment => Puppet.lookup(:root_environment)) do Puppet::Parser::Functions.newfunction("onlyroot", :type => :rvalue) do |args| end end Puppet.override(:current_environment => Puppet::Node::Environment.create(:other, [])) do Puppet::Parser::Functions.newfunction("other_env", :type => :rvalue) do |args| end expect(Puppet::Parser::Functions.function("onlyroot")).to eq("function_onlyroot") expect(Puppet::Parser::Functions.function("other_env")).to eq("function_other_env") end expect(Puppet::Parser::Functions.function("other_env")).to be_falsey end end describe "when calling function to test arity" do let(:function_module) { Puppet::Parser::Functions.environment_module(Puppet.lookup(:current_environment)) } it "should raise an error if the function is called with too many arguments" do Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| } expect { callable_functions_from(function_module).function_name([1,2,3]) }.to raise_error ArgumentError end it "should raise an error if the function is called with too few arguments" do Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| } expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError end it "should not raise an error if the function is called with correct number of arguments" do Puppet::Parser::Functions.newfunction("name", :arity => 2) { |args| } expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error end it "should raise an error if the variable arg function is called with too few arguments" do Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| } expect { callable_functions_from(function_module).function_name([1]) }.to raise_error ArgumentError end it "should not raise an error if the variable arg function is called with correct number of arguments" do Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| } expect { callable_functions_from(function_module).function_name([1,2]) }.to_not raise_error end it "should not raise an error if the variable arg function is called with more number of arguments" do Puppet::Parser::Functions.newfunction("name", :arity => -3) { |args| } expect { callable_functions_from(function_module).function_name([1,2,3]) }.to_not raise_error end end describe "::arity" do it "returns the given arity of a function" do Puppet::Parser::Functions.newfunction("name", :arity => 4) { |args| } expect(Puppet::Parser::Functions.arity(:name)).to eq(4) end it "returns -1 if no arity is given" do Puppet::Parser::Functions.newfunction("name") { |args| } expect(Puppet::Parser::Functions.arity(:name)).to eq(-1) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/parser/resource_spec.rb
spec/unit/parser/resource_spec.rb
require 'spec_helper' describe Puppet::Parser::Resource do before do environment = Puppet::Node::Environment.create(:testing, []) @node = Puppet::Node.new("yaynode", :environment => environment) @known_resource_types = environment.known_resource_types @compiler = Puppet::Parser::Compiler.new(@node) @source = newclass "" @scope = @compiler.topscope end def mkresource(args = {}) args[:source] ||= @source args[:scope] ||= @scope params = args[:parameters] || {:one => "yay", :three => "rah"} if args[:parameters] == :none args.delete(:parameters) elsif not args[:parameters].is_a? Array args[:parameters] = paramify(args[:source], params) end Puppet::Parser::Resource.new("resource", "testing", args) end def param(name, value, source) Puppet::Parser::Resource::Param.new(:name => name, :value => value, :source => source) end def paramify(source, hash) hash.collect do |name, value| Puppet::Parser::Resource::Param.new( :name => name, :value => value, :source => source ) end end def newclass(name) @known_resource_types.add Puppet::Resource::Type.new(:hostclass, name) end def newdefine(name) @known_resource_types.add Puppet::Resource::Type.new(:definition, name) end def newnode(name) @known_resource_types.add Puppet::Resource::Type.new(:node, name) end it "should get its environment from its scope" do scope = double('scope', :source => double("source")) expect(scope).to receive(:environment).and_return("foo").at_least(:once) expect(scope).to receive(:lookupdefaults).and_return({}) expect(Puppet::Parser::Resource.new("file", "whatever", :scope => scope).environment).to eq("foo") end it "should use the scope's environment as its environment" do expect(@scope).to receive(:environment).and_return("myenv").at_least(:once) expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope).environment).to eq("myenv") end it "should be isomorphic if it is builtin and models an isomorphic type" do expect(Puppet::Type.type(:file)).to receive(:isomorphic?).and_return(true) @resource = expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_truthy end it "should not be isomorphic if it is builtin and models a non-isomorphic type" do expect(Puppet::Type.type(:file)).to receive(:isomorphic?).and_return(false) @resource = expect(Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_falsey end it "should be isomorphic if it is not builtin" do newdefine "whatever" @resource = expect(Puppet::Parser::Resource.new("whatever", "whatever", :scope => @scope, :source => @source).isomorphic?).to be_truthy end it "should have an array-indexing method for retrieving parameter values" do @resource = mkresource expect(@resource[:one]).to eq("yay") end it "should use a Puppet::Resource for converting to a ral resource" do trans = double('resource', :to_ral => "yay") @resource = mkresource expect(@resource).to receive(:copy_as_resource).and_return(trans) expect(@resource.to_ral).to eq("yay") end it "should be able to use the indexing operator to access parameters" do resource = Puppet::Parser::Resource.new("resource", "testing", :source => "source", :scope => @scope) resource["foo"] = "bar" expect(resource["foo"]).to eq("bar") end it "should return the title when asked for a parameter named 'title'" do expect(Puppet::Parser::Resource.new("resource", "testing", :source => @source, :scope => @scope)[:title]).to eq("testing") end describe "when initializing" do before do @arguments = {:scope => @scope} end it "should fail unless hash is specified" do expect { Puppet::Parser::Resource.new('file', '/my/file', nil) }.to raise_error(ArgumentError, /Resources require a hash as last argument/) end it "should attempt to externalize filepaths via the environment" do environment = Puppet::Node::Environment.create(:testing, []) expect(environment).to receive(:externalize_path).at_least(:once).and_return("foo") Puppet[:code] = "notify { 'hello': }" catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone', environment: environment) notify = catalog.resource('Notify[hello]') expect(notify.file).to eq("foo") end it "should set the reference correctly" do res = Puppet::Parser::Resource.new("resource", "testing", @arguments) expect(res.ref).to eq("Resource[testing]") end it "should be tagged with user tags" do tags = [ "tag1", "tag2" ] @arguments[:parameters] = [ param(:tag, tags , :source) ] res = Puppet::Parser::Resource.new("resource", "testing", @arguments) expect(res).to be_tagged("tag1") expect(res).to be_tagged("tag2") end end describe "when evaluating" do before do @catalog = Puppet::Resource::Catalog.new source = double('source') allow(source).to receive(:module_name) @scope = Puppet::Parser::Scope.new(@compiler, :source => source) @catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => @scope)) end it "should evaluate the associated AST definition" do definition = newdefine "mydefine" res = Puppet::Parser::Resource.new("mydefine", "whatever", :scope => @scope, :source => @source, :catalog => @catalog) expect(definition).to receive(:evaluate_code).with(res) res.evaluate end it "should evaluate the associated AST class" do @class = newclass "myclass" res = Puppet::Parser::Resource.new("class", "myclass", :scope => @scope, :source => @source, :catalog => @catalog) expect(@class).to receive(:evaluate_code).with(res) res.evaluate end it "should evaluate the associated AST node" do nodedef = newnode("mynode") res = Puppet::Parser::Resource.new("node", "mynode", :scope => @scope, :source => @source, :catalog => @catalog) expect(nodedef).to receive(:evaluate_code).with(res) res.evaluate end it "should add an edge to any specified stage for class resources" do @compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {}) other_stage = Puppet::Parser::Resource.new(:stage, "other", :scope => @scope, :catalog => @catalog) @compiler.add_resource(@scope, other_stage) resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog) resource[:stage] = 'other' @compiler.add_resource(@scope, resource) resource.evaluate expect(@compiler.catalog.edge?(other_stage, resource)).to be_truthy end it "should fail if an unknown stage is specified" do @compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {}) resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog) resource[:stage] = 'other' expect { resource.evaluate }.to raise_error(ArgumentError, /Could not find stage other specified by/) end it "should add edges from the class resources to the parent's stage if no stage is specified" do foo_stage = Puppet::Parser::Resource.new(:stage, :foo_stage, :scope => @scope, :catalog => @catalog) @compiler.add_resource(@scope, foo_stage) @compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {}) resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog) resource[:stage] = 'foo_stage' @compiler.add_resource(@scope, resource) resource.evaluate expect(@compiler.catalog).to be_edge(foo_stage, resource) end it 'should allow a resource reference to be undef' do Puppet[:code] = "notify { 'hello': message=>'yo', notify => undef }" catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone') edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]} expect(edges).to include(['Class[main]', 'Notify[hello]']) end it 'should evaluate class in the same file without include' do Puppet[:code] = <<-MANIFEST class a($myvar = 'hello') {} class { 'a': myvar => 'goodbye' } notify { $a::myvar: } MANIFEST catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone') expect(catalog.resource('Notify[goodbye]')).to be_a(Puppet::Resource) end it "should allow edges to propagate multiple levels down the scope hierarchy" do Puppet[:code] = <<-MANIFEST stage { before: before => Stage[main] } class alpha { include beta } class beta { include gamma } class gamma { } class { alpha: stage => before } MANIFEST catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone') # Stringify them to make for easier lookup edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]} expect(edges).to include(["Stage[before]", "Class[Alpha]"]) expect(edges).to include(["Stage[before]", "Class[Beta]"]) expect(edges).to include(["Stage[before]", "Class[Gamma]"]) end it "should use the specified stage even if the parent scope specifies one" do Puppet[:code] = <<-MANIFEST stage { before: before => Stage[main], } stage { after: require => Stage[main], } class alpha { class { beta: stage => after } } class beta { } class { alpha: stage => before } MANIFEST catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone') edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]} expect(edges).to include(["Stage[before]", "Class[Alpha]"]) expect(edges).to include(["Stage[after]", "Class[Beta]"]) end it "should add edges from top-level class resources to the main stage if no stage is specified" do main = @compiler.catalog.resource(:stage, :main) @compiler.environment.known_resource_types.add Puppet::Resource::Type.new(:hostclass, "foo", {}) resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope, :catalog => @catalog) @compiler.add_resource(@scope, resource) resource.evaluate expect(@compiler.catalog).to be_edge(main, resource) end it 'should assign default value to generated resource' do Puppet[:code] = <<-PUPPET define one($var) { notify { "${var} says hello": } } define two($x = $title) { One { var => $x } one { a: } one { b: var => 'bill'} } two { 'bob': } PUPPET catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone') edges = catalog.edges.map {|e| [e.source.ref, e.target.ref]} expect(edges).to include(['One[a]', 'Notify[bob says hello]']) expect(edges).to include(['One[b]', 'Notify[bill says hello]']) end it 'should override default value with new value' do Puppet[:code] = <<-PUPPET.unindent class foo { File { ensure => file, mode => '644', owner => 'root', group => 'root', } file { '/tmp/foo': ensure => directory } File['/tmp/foo'] { mode => '0755' } } include foo PUPPET catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new 'anyone') file = catalog.resource('File[/tmp/foo]') expect(file).to be_a(Puppet::Resource) expect(file['mode']).to eql('0755') end end describe 'when evaluating resource defaults' do let(:resource) { Puppet::Parser::Resource.new('file', 'whatever', :scope => @scope, :source => @source) } it 'should add all defaults available from the scope' do expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => param(:owner, 'default', @source)) expect(resource[:owner]).to eq('default') end it 'should not replace existing parameters with defaults' do expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => param(:owner, 'replaced', @source)) r = Puppet::Parser::Resource.new('file', 'whatever', :scope => @scope, :source => @source, :parameters => [ param(:owner, 'oldvalue', @source) ]) expect(r[:owner]).to eq('oldvalue') end it 'should override defaults with new parameters' do expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => param(:owner, 'replaced', @source)) resource.set_parameter(:owner, 'newvalue') expect(resource[:owner]).to eq('newvalue') end it 'should add a copy of each default, rather than the actual default parameter instance' do newparam = param(:owner, 'default', @source) other = newparam.dup other.value = "other" expect(newparam).to receive(:dup).and_return(other) expect(@scope).to receive(:lookupdefaults).with('File').and_return(:owner => newparam) expect(resource[:owner]).to eq('other') end it "should tag with value of default parameter named 'tag'" do expect(@scope).to receive(:lookupdefaults).with('File').and_return(:tag => param(:tag, 'the_tag', @source)) expect(resource.tags).to include('the_tag') end end describe "when finishing" do before do @resource = Puppet::Parser::Resource.new("file", "whatever", :scope => @scope, :source => @source) end it "should do nothing if it has already been finished" do @resource.finish expect(@resource).not_to receive(:add_scope_tags) @resource.finish end it "converts parameters with Sensitive values to unwrapped values and metadata" do @resource[:content] = Puppet::Pops::Types::PSensitiveType::Sensitive.new("hunter2") @resource.finish expect(@resource[:content]).to eq "hunter2" expect(@resource.sensitive_parameters).to eq [:content] end end describe "when being tagged" do before do @scope_resource = double('scope_resource', :tags => %w{srone srtwo}) allow(@scope).to receive(:resource).and_return(@scope_resource) @resource = Puppet::Parser::Resource.new("file", "yay", :scope => @scope, :source => double('source')) end it "should get tagged with the resource type" do expect(@resource.tags).to be_include("file") end it "should get tagged with the title" do expect(@resource.tags).to be_include("yay") end it "should get tagged with each name in the title if the title is a qualified class name" do resource = Puppet::Parser::Resource.new("file", "one::two", :scope => @scope, :source => double('source')) expect(resource.tags).to be_include("one") expect(resource.tags).to be_include("two") end it "should get tagged with each name in the type if the type is a qualified class name" do resource = Puppet::Parser::Resource.new("one::two", "whatever", :scope => @scope, :source => double('source')) expect(resource.tags).to be_include("one") expect(resource.tags).to be_include("two") end it "should not get tagged with non-alphanumeric titles" do resource = Puppet::Parser::Resource.new("file", "this is a test", :scope => @scope, :source => double('source')) expect(resource.tags).not_to be_include("this is a test") end it "should fail on tags containing '*' characters" do expect { @resource.tag("bad*tag") }.to raise_error(Puppet::ParseError) end it "should fail on tags starting with '-' characters" do expect { @resource.tag("-badtag") }.to raise_error(Puppet::ParseError) end it "should fail on tags containing ' ' characters" do expect { @resource.tag("bad tag") }.to raise_error(Puppet::ParseError) end it "should allow alpha tags" do expect { @resource.tag("good_tag") }.to_not raise_error end end describe "when merging overrides" do def resource_type(name) double(name, :child_of? => false) end before do @source = resource_type("source1") @resource = mkresource :source => @source @override = mkresource :source => @source end it "should fail when the override was not created by a parent class" do @override.source = resource_type("source2") expect(@override.source).to receive(:child_of?).with(@source).and_return(false) expect { @resource.merge(@override) }.to raise_error(Puppet::ParseError) end it "should succeed when the override was created in the current scope" do @source3 = resource_type("source3") @resource.source = @source3 @override.source = @resource.source expect(@override.source).not_to receive(:child_of?).with(@source3) params = {:a => :b, :c => :d} expect(@override).to receive(:parameters).and_return(params) expect(@resource).to receive(:override_parameter).with(:b) expect(@resource).to receive(:override_parameter).with(:d) @resource.merge(@override) end it "should succeed when a parent class created the override" do @source3 = resource_type("source3") @resource.source = @source3 @override.source = resource_type("source4") expect(@override.source).to receive(:child_of?).with(@source3).and_return(true) params = {:a => :b, :c => :d} expect(@override).to receive(:parameters).and_return(params) expect(@resource).to receive(:override_parameter).with(:b) expect(@resource).to receive(:override_parameter).with(:d) @resource.merge(@override) end it "should add new parameters when the parameter is not set" do allow(@source).to receive(:child_of?).and_return(true) @override.set_parameter(:testing, "value") @resource.merge(@override) expect(@resource[:testing]).to eq("value") end it "should replace existing parameter values" do allow(@source).to receive(:child_of?).and_return(true) @resource.set_parameter(:testing, "old") @override.set_parameter(:testing, "value") @resource.merge(@override) expect(@resource[:testing]).to eq("value") end it "should add values to the parameter when the override was created with the '+>' syntax" do allow(@source).to receive(:child_of?).and_return(true) param = Puppet::Parser::Resource::Param.new(:name => :testing, :value => "testing", :source => @resource.source) param.add = true @override.set_parameter(param) @resource.set_parameter(:testing, "other") @resource.merge(@override) expect(@resource[:testing]).to eq(%w{other testing}) end it "should not merge parameter values when multiple resources are overriden with '+>' at once " do @resource_2 = mkresource :source => @source @resource. set_parameter(:testing, "old_val_1") @resource_2.set_parameter(:testing, "old_val_2") allow(@source).to receive(:child_of?).and_return(true) param = Puppet::Parser::Resource::Param.new(:name => :testing, :value => "new_val", :source => @resource.source) param.add = true @override.set_parameter(param) @resource. merge(@override) @resource_2.merge(@override) expect(@resource [:testing]).to eq(%w{old_val_1 new_val}) expect(@resource_2[:testing]).to eq(%w{old_val_2 new_val}) end it "should promote tag overrides to real tags" do allow(@source).to receive(:child_of?).and_return(true) param = Puppet::Parser::Resource::Param.new(:name => :tag, :value => "testing", :source => @resource.source) @override.set_parameter(param) @resource.merge(@override) expect(@resource.tagged?("testing")).to be_truthy end end it "should be able to be converted to a normal resource" do @source = double('scope', :name => "myscope") @resource = mkresource :source => @source expect(@resource).to respond_to(:copy_as_resource) end describe "when being converted to a resource" do before do @parser_resource = mkresource :scope => @scope, :parameters => {:foo => "bar", :fee => "fum"} end it "should create an instance of Puppet::Resource" do expect(@parser_resource.copy_as_resource).to be_instance_of(Puppet::Resource) end it "should set the type correctly on the Puppet::Resource" do expect(@parser_resource.copy_as_resource.type).to eq(@parser_resource.type) end it "should set the title correctly on the Puppet::Resource" do expect(@parser_resource.copy_as_resource.title).to eq(@parser_resource.title) end it "should copy over all of the parameters" do result = @parser_resource.copy_as_resource.to_hash # The name will be in here, also. expect(result[:foo]).to eq("bar") expect(result[:fee]).to eq("fum") end it "should copy over the tags" do @parser_resource.tag "foo" @parser_resource.tag "bar" expect(@parser_resource.copy_as_resource.tags).to eq(@parser_resource.tags) end it "should copy over the line" do @parser_resource.line = 40 expect(@parser_resource.copy_as_resource.line).to eq(40) end it "should copy over the file" do @parser_resource.file = "/my/file" expect(@parser_resource.copy_as_resource.file).to eq("/my/file") end it "should copy over the 'exported' value" do @parser_resource.exported = true expect(@parser_resource.copy_as_resource.exported).to be_truthy end it "should copy over the 'virtual' value" do @parser_resource.virtual = true expect(@parser_resource.copy_as_resource.virtual).to be_truthy end it "should convert any parser resource references to Puppet::Resource instances" do ref = Puppet::Resource.new("file", "/my/file") @parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ref} result = @parser_resource.copy_as_resource expect(result[:fee]).to eq(Puppet::Resource.new(:file, "/my/file")) end it "should convert any parser resource references to Puppet::Resource instances even if they are in an array" do ref = Puppet::Resource.new("file", "/my/file") @parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ["a", ref]} result = @parser_resource.copy_as_resource expect(result[:fee]).to eq(["a", Puppet::Resource.new(:file, "/my/file")]) end it "should convert any parser resource references to Puppet::Resource instances even if they are in an array of array, and even deeper" do ref1 = Puppet::Resource.new("file", "/my/file1") ref2 = Puppet::Resource.new("file", "/my/file2") @parser_resource = mkresource :source => @source, :parameters => {:foo => "bar", :fee => ["a", [ref1,ref2]]} result = @parser_resource.copy_as_resource expect(result[:fee]).to eq(["a", Puppet::Resource.new(:file, "/my/file1"), Puppet::Resource.new(:file, "/my/file2")]) end it "should fail if the same param is declared twice" do expect do @parser_resource = mkresource :source => @source, :parameters => [ Puppet::Parser::Resource::Param.new( :name => :foo, :value => "bar", :source => @source ), Puppet::Parser::Resource::Param.new( :name => :foo, :value => "baz", :source => @source ) ] end.to raise_error(Puppet::ParseError) end end describe "when setting parameters" do before do @source = newclass "foobar" @resource = Puppet::Parser::Resource.new :foo, "bar", :scope => @scope, :source => @source end it "should accept Param instances and add them to the parameter list" do param = Puppet::Parser::Resource::Param.new :name => "foo", :value => "bar", :source => @source @resource.set_parameter(param) expect(@resource["foo"]).to eq("bar") end it "should allow parameters to be set to 'false'" do @resource.set_parameter("myparam", false) expect(@resource["myparam"]).to be_falsey end it "should use its source when provided a parameter name and value" do @resource.set_parameter("myparam", "myvalue") expect(@resource["myparam"]).to eq("myvalue") end end # part of #629 -- the undef keyword. Make sure 'undef' params get skipped. it "should not include 'undef' parameters when converting itself to a hash" do resource = Puppet::Parser::Resource.new "file", "/tmp/testing", :source => double("source"), :scope => @scope resource[:owner] = :undef resource[:mode] = "755" expect(resource.to_hash[:owner]).to be_nil end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false