repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/verifier_spec.rb
spec/unit/ssl/verifier_spec.rb
require 'spec_helper' describe Puppet::SSL::Verifier do let(:options) { {} } let(:ssl_context) { Puppet::SSL::SSLContext.new(options) } let(:host) { 'example.com' } let(:http) { Net::HTTP.new(host) } let(:verifier) { described_class.new(host, ssl_context) } context '#reusable?' do it 'Verifiers with the same ssl_context are reusable' do expect(verifier).to be_reusable(described_class.new(host, ssl_context)) end it 'Verifiers with different ssl_contexts are not reusable' do expect(verifier).to_not be_reusable(described_class.new(host, Puppet::SSL::SSLContext.new)) end end context '#setup_connection' do it 'copies parameters from the ssl_context to the connection' do store = double('store') options.merge!(store: store) verifier.setup_connection(http) expect(http.cert_store).to eq(store) end it 'defaults to VERIFY_PEER' do expect(http).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER) verifier.setup_connection(http) end it 'only uses VERIFY_NONE if explicitly disabled' do options.merge!(verify_peer: false) expect(http).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE) verifier.setup_connection(http) end it 'registers a verify callback' do verifier.setup_connection(http) expect(http.verify_callback).to eq(verifier) end end context '#handle_connection_error' do let(:peer_cert) { cert_fixture('127.0.0.1.pem') } let(:chain) { [peer_cert] } let(:ssl_error) { OpenSSL::SSL::SSLError.new("certificate verify failed") } it "raises a verification error for a CA cert" do store_context = double('store_context', current_cert: peer_cert, chain: [peer_cert], error: OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, error_string: "unable to get local issuer certificate") verifier.call(false, store_context) expect { verifier.handle_connection_error(http, ssl_error) }.to raise_error(Puppet::SSL::CertVerifyError, "certificate verify failed [unable to get local issuer certificate for CN=127.0.0.1]") end it "raises a verification error for the server cert" do store_context = double('store_context', current_cert: peer_cert, chain: chain, error: OpenSSL::X509::V_ERR_CERT_REJECTED, error_string: "certificate rejected") verifier.call(false, store_context) expect { verifier.handle_connection_error(http, ssl_error) }.to raise_error(Puppet::SSL::CertVerifyError, "certificate verify failed [certificate rejected for CN=127.0.0.1]") end it "raises cert mismatch error on ruby < 2.4" do expect(http).to receive(:peer_cert).and_return(peer_cert) store_context = double('store_context') verifier.call(true, store_context) ssl_error = OpenSSL::SSL::SSLError.new("hostname 'example'com' does not match the server certificate") expect { verifier.handle_connection_error(http, ssl_error) }.to raise_error(Puppet::Error, "Server hostname 'example.com' did not match server certificate; expected one of 127.0.0.1, DNS:127.0.0.1, DNS:127.0.0.2") end it "raises cert mismatch error on ruby >= 2.4" do store_context = double('store_context', current_cert: peer_cert, chain: chain, error: OpenSSL::X509::V_OK, error_string: "ok") verifier.call(false, store_context) expect { verifier.handle_connection_error(http, ssl_error) }.to raise_error(Puppet::Error, "Server hostname 'example.com' did not match server certificate; expected one of 127.0.0.1, DNS:127.0.0.1, DNS:127.0.0.2") end it 're-raises other ssl connection errors' do err = OpenSSL::SSL::SSLError.new("This version of OpenSSL does not support FIPS mode") expect { verifier.handle_connection_error(http, err) }.to raise_error(err) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/certificate_signer_spec.rb
spec/unit/ssl/certificate_signer_spec.rb
require 'spec_helper' describe Puppet::SSL::CertificateSigner do include PuppetSpec::Files let(:wrong_key) { OpenSSL::PKey::RSA.new(512) } let(:client_cert) { cert_fixture('signed.pem') } # jruby-openssl >= 0.13.0 (JRuby >= 9.3.5.0) raises an error when signing a # certificate when there is a discrepancy between the certificate and key. it 'raises if client cert signature is invalid', if: Puppet::Util::Platform.jruby? && RUBY_VERSION.to_f >= 2.6 do expect { client_cert.sign(wrong_key, OpenSSL::Digest::SHA256.new) }.to raise_error(OpenSSL::X509::CertificateError, 'invalid public key data') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/gettext/module_loading_spec.rb
spec/unit/gettext/module_loading_spec.rb
require 'spec_helper' require 'puppet_spec/modules' require 'puppet_spec/files' require 'puppet/gettext/module_translations' describe Puppet::ModuleTranslations do include PuppetSpec::Files describe "loading translations from the module path" do let(:modpath) { tmpdir('modpath') } let(:module_a) { PuppetSpec::Modules.create( "mod_a", modpath, :metadata => { :author => 'foo' }, :environment => double("environment")) } let(:module_b) { PuppetSpec::Modules.create( "mod_b", modpath, :metadata => { :author => 'foo' }, :environment => double("environment")) } it "should attempt to load translations only for modules that have them" do expect(module_a).to receive(:has_translations?).and_return(false) expect(module_b).to receive(:has_translations?).and_return(true) expect(Puppet::GettextConfig).to receive(:load_translations).with("foo-mod_b", File.join(modpath, "mod_b", "locales"), :po).and_return(true) Puppet::ModuleTranslations.load_from_modulepath([module_a, module_b]) end end describe "loading translations from $vardir" do let(:vardir) { dir_containing("vardir", { "locales" => { "ja" => { "foo-mod_a.po" => "" } } }) } it "should attempt to load translations for the current locale" do expect(Puppet::GettextConfig).to receive(:current_locale).and_return("ja") expect(Puppet::GettextConfig).to receive(:load_translations).with("foo-mod_a", File.join(vardir, "locales"), :po).and_return(true) Puppet::ModuleTranslations.load_from_vardir(vardir) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/gettext/config_spec.rb
spec/unit/gettext/config_spec.rb
require 'puppet/gettext/config' require 'spec_helper' describe Puppet::GettextConfig do require 'puppet_spec/files' include PuppetSpec::Files include Puppet::GettextConfig let(:local_path) do local_path ||= Puppet::GettextConfig::LOCAL_PATH end let(:windows_path) do windows_path ||= Puppet::GettextConfig::WINDOWS_PATH end let(:posix_path) do windows_path ||= Puppet::GettextConfig::POSIX_PATH end before(:each) do allow(Puppet::GettextConfig).to receive(:gettext_loaded?).and_return(true) end after(:each) do Puppet::GettextConfig.set_locale('en') Puppet::GettextConfig.delete_all_text_domains end # These tests assume gettext is enabled, but it will be disabled when the # first time the `Puppet[:disable_i18n]` setting is resolved around(:each) do |example| disabled = Puppet::GettextConfig.instance_variable_get(:@gettext_disabled) Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, false) begin example.run ensure Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, disabled) end end describe 'setting and getting the locale' do it 'should return "en" when gettext is unavailable' do allow(Puppet::GettextConfig).to receive(:gettext_loaded?).and_return(false) expect(Puppet::GettextConfig.current_locale).to eq('en') end it 'should allow the locale to be set' do Puppet::GettextConfig.set_locale('hu') expect(Puppet::GettextConfig.current_locale).to eq('hu') end end describe 'translation mode selection' do it 'should select PO mode when given a local config path' do expect(Puppet::GettextConfig.translation_mode(local_path)).to eq(:po) end it 'should select PO mode when given a non-package config path' do expect(Puppet::GettextConfig.translation_mode('../fake/path')).to eq(:po) end it 'should select MO mode when given a Windows package config path' do expect(Puppet::GettextConfig.translation_mode(windows_path)).to eq(:mo) end it 'should select MO mode when given a POSIX package config path' do expect(Puppet::GettextConfig.translation_mode(posix_path)).to eq(:mo) end end describe 'loading translations' do context 'when given a nil locale path' do it 'should return false' do expect(Puppet::GettextConfig.load_translations('puppet', nil, :po)).to be false end end context 'when given a valid locale file location' do it 'should return true' do expect(Puppet::GettextConfig).to receive(:add_repository_to_domain).with('puppet', local_path, :po, anything) expect(Puppet::GettextConfig.load_translations('puppet', local_path, :po)).to be true end end context 'when given a bad file format' do it 'should raise an exception' do expect { Puppet::GettextConfig.load_translations('puppet', local_path, :bad_format) }.to raise_error(Puppet::Error) end end end describe "setting up text domains" do it 'can create the default text domain after another is set' do Puppet::GettextConfig.delete_all_text_domains FastGettext.text_domain = 'other' Puppet::GettextConfig.create_default_text_domain end it 'should add puppet translations to the default text domain' do expect(Puppet::GettextConfig).to receive(:load_translations).with('puppet', local_path, :po, Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN).and_return(true) Puppet::GettextConfig.create_default_text_domain expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN) end it 'should copy default translations when creating a non-default text domain' do Puppet::GettextConfig.reset_text_domain(:test) expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test) end it 'should normalize domain name when creating a non-default text domain' do Puppet::GettextConfig.reset_text_domain('test') expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test) end end describe "clearing the configured text domain" do it 'succeeds' do Puppet::GettextConfig.clear_text_domain expect(FastGettext.text_domain).to eq(FastGettext.default_text_domain) end it 'falls back to default' do Puppet::GettextConfig.reset_text_domain(:test) expect(FastGettext.text_domain).to eq(:test) Puppet::GettextConfig.clear_text_domain expect(FastGettext.text_domain).to eq(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN) end end describe "deleting text domains" do it 'can delete a text domain by name' do Puppet::GettextConfig.reset_text_domain(:test) expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test) Puppet::GettextConfig.delete_text_domain(:test) expect(Puppet::GettextConfig.loaded_text_domains).to eq([Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN]) end it 'can delete all non-default text domains' do Puppet::GettextConfig.reset_text_domain(:test) expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test) Puppet::GettextConfig.delete_environment_text_domains expect(Puppet::GettextConfig.loaded_text_domains).to eq([Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN]) end it 'can delete all text domains' do Puppet::GettextConfig.reset_text_domain(:test) expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test) Puppet::GettextConfig.delete_all_text_domains expect(Puppet::GettextConfig.loaded_text_domains).to be_empty end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/partition_spec.rb
spec/unit/functions/partition_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the partition function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an array' do it 'partitions by item' do manifest = "notify { String(partition(['', b, ab]) |$s| { $s.empty }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[[[''], ['b', 'ab']]]") end it 'partitions by index, item' do manifest = "notify { String(partition(['', b, ab]) |$i, $s| { $i == 2 or $s.empty }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[[['', 'ab'], ['b']]]") end end context 'for a hash' do it 'partitions by key-value pair' do manifest = "notify { String(partition(a => [1, 2], b => []) |$kv| { $kv[1].empty }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[[[['b', []]], [['a', [1, 2]]]]]") end it 'partitions by key, value' do manifest = "notify { String(partition(a => [1, 2], b => []) |$k, $v| { $v.empty }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[[[['b', []]], [['a', [1, 2]]]]]") end end context 'for a string' do it 'fails' do manifest = "notify { String(partition('something') |$s| { $s.empty }): }" expect { compile_to_catalog(manifest) }.to raise_error(Puppet::PreformattedError) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/floor_spec.rb
spec/unit/functions/floor_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the floor function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an integer' do [ 0, 1, -1].each do |x| it "called as floor(#{x}) results in the same value" do expect(compile_to_catalog("notify { String( floor(#{x}) == #{x}): }")).to have_resource("Notify[true]") end end end context 'for a float' do { 0.0 => 0, 1.1 => 1, -1.1 => -2, }.each_pair do |x, expected| it "called as floor(#{x}) results in #{expected}" do expect(compile_to_catalog("notify { String( floor(#{x}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'for a string' do let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } { "0" => 0, "1" => 1, "-1" => -1, "0.0" => 0, "1.1" => 1, "-1.1" => -2, "0777" => 777, "-0777" => -777, "0xFF" => 0xFF, }.each_pair do |x, expected| it "called as floor('#{x}') results in #{expected} and a deprecation warning" do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String( floor('#{x}') == #{expected}): }")).to have_resource("Notify[true]") end expect(warnings).to include(/auto conversion of .* is deprecated/) end end ['blue', '0.2.3'].each do |x| it "errors as the string '#{x}' cannot be converted to a float (indirectly deprecated)" do expect{ compile_to_catalog("floor('#{x}')") }.to raise_error(/cannot convert given value to a floating point value/) end end end [[1,2,3], {'a' => 10}].each do |x| it "errors for a value of class #{x.class} (indirectly deprecated)" do expect{ compile_to_catalog("floor(#{x})") }.to raise_error(/expects a value of type Numeric or String/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/step_spec.rb
spec/unit/functions/step_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'shared_behaviours/iterative_functions' describe 'the step method' do include PuppetSpec::Compiler it 'raises an error when given a type that cannot be iterated' do expect do compile_to_catalog(<<-MANIFEST) 3.14.step(1) |$v| { } MANIFEST end.to raise_error(Puppet::Error, /expects an Iterable value, got Float/) end it 'raises an error when called with more than two arguments and a block' do expect do compile_to_catalog(<<-MANIFEST) [1].step(1,2) |$v| { } MANIFEST end.to raise_error(Puppet::Error, /expects 2 arguments, got 3/) end it 'raises an error when called with more than two arguments and without a block' do expect do compile_to_catalog(<<-MANIFEST) [1].step(1,2) MANIFEST end.to raise_error(Puppet::Error, /expects 2 arguments, got 3/) end it 'raises an error when called with a block with too many required parameters' do expect do compile_to_catalog(<<-MANIFEST) [1].step(1) |$v1, $v2| { } MANIFEST end.to raise_error(Puppet::Error, /block expects 1 argument, got 2/) end it 'raises an error when called with a block with too few parameters' do expect do compile_to_catalog(<<-MANIFEST) [1].step(1) | | { } MANIFEST end.to raise_error(Puppet::Error, /block expects 1 argument, got none/) end it 'raises an error when called with step == 0' do expect do compile_to_catalog(<<-MANIFEST) [1].step(0) |$x| { } MANIFEST end.to raise_error(Puppet::Error, /'step' expects an Integer\[1\] value, got Integer\[0, 0\]/) end it 'raises an error when step is not an integer' do expect do compile_to_catalog(<<-MANIFEST) [1].step('three') |$x| { } MANIFEST end.to raise_error(Puppet::Error, /'step' expects an Integer value, got String/) end it 'does not raise an error when called with a block with too many but optional arguments' do expect do compile_to_catalog(<<-MANIFEST) [1].step(1) |$v1, $v2=extra| { } MANIFEST end.to_not raise_error end it 'returns Undef when called with a block' do expect do compile_to_catalog(<<-MANIFEST) assert_type(Undef, [1].step(2) |$x| { $x }) MANIFEST end.not_to raise_error end it 'returns an Iterable when called without a block' do expect do compile_to_catalog(<<-MANIFEST) assert_type(Iterable, [1].step(2)) MANIFEST end.not_to raise_error end it 'should produce "times" interval of integer according to step' do expect(eval_and_collect_notices('10.step(2) |$x| { notice($x) }')).to eq(['0', '2', '4', '6', '8']) end it 'should produce interval of Integer[5,20] according to step' do expect(eval_and_collect_notices('Integer[5,20].step(4) |$x| { notice($x) }')).to eq(['5', '9', '13', '17']) end it 'should produce the elements of [a,b,c,d,e,f,g,h] according to step' do expect(eval_and_collect_notices('[a,b,c,d,e,f,g,h].step(2) |$x| { notice($x) }')).to eq(%w(a c e g)) end it 'should produce the elements {a=>1,b=>2,c=>3,d=>4,e=>5,f=>6,g=>7,h=>8} according to step' do expect(eval_and_collect_notices('{a=>1,b=>2,c=>3,d=>4,e=>5,f=>6,g=>7,h=>8}.step(2) |$t| { notice($t[1]) }')).to eq(%w(1 3 5 7)) end it 'should produce the choices of Enum[a,b,c,d,e,f,g,h] according to step' do expect(eval_and_collect_notices('Enum[a,b,c,d,e,f,g,h].step(2) |$x| { notice($x) }')).to eq(%w(a c e g)) end it 'should produce descending interval of Integer[5,20] when chained after a reverse_each' do expect(eval_and_collect_notices('Integer[5,20].reverse_each.step(4) |$x| { notice($x) }')).to eq(['20', '16', '12', '8']) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/break_spec.rb
spec/unit/functions/break_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the break function' do include PuppetSpec::Compiler include Matchers::Resource context do it 'breaks iteration as if at end of input in a map for an array' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[1, 2]]') function please_break() { [1,2,3].map |$x| { if $x == 3 { break() } $x } } notify { String(please_break()): } CODE end it 'breaks iteration as if at end of input in a map for a hash' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[1, 2]]') function please_break() { {'a' => 1, 'b' => 2, 'c' => 3}.map |$x, $y| { if $y == 3 { break() } $y } } notify { String(please_break()): } CODE end it 'breaks iteration as if at end of input in a reduce for an array' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[6]') function please_break() { [1,2,3,4].reduce |$memo, $x| { if $x == 4 { break() } $memo + $x } } notify { String(please_break()): } CODE end it 'breaks iteration as if at end of input in a reduce for a hash' do expect(compile_to_catalog(<<-CODE)).to have_resource("Notify[['abc', 6]]") function please_break() { {'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4}.reduce |$memo, $x| { if $x[1] == 4 { break() } $string = "${memo[0]}${x[0]}" $number = $memo[1] + $x[1] [$string, $number] } } notify { String(please_break()): } CODE end it 'breaks iteration as if at end of input in an each for an array' do expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]') function please_break() { [1,2,3].each |$x| { if $x == 3 { break() } notify { "$x": } } } please_break() CODE end it 'breaks iteration as if at end of input in an each for a hash' do expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]') function please_break() { {'a' => 1, 'b' => 2, 'c' => 3}.each |$x, $y| { if $y == 3 { break() } notify { "$y": } } } please_break() CODE end it 'breaks iteration as if at end of input in a reverse_each' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[2]') function please_break() { [1,2,3].reverse_each |$x| { if $x == 1 { break() } notify { "$x": } } } please_break() CODE end it 'breaks iteration as if at end of input in a map for a hash' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[1, 2]]') function please_break() { {'a' => 1, 'b' => 2, 'c' => 3}.map |$x, $y| { if $y == 3 { break() } $y } } notify { String(please_break()): } CODE end it 'breaks iteration as if at end of input in a reduce for an array' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[6]') function please_break() { [1,2,3,4].reduce |$memo, $x| { if $x == 4 { break() } $memo + $x } } notify { String(please_break()): } CODE end it 'breaks iteration as if at end of input in a reduce for a hash' do expect(compile_to_catalog(<<-CODE)).to have_resource("Notify[['abc', 6]]") function please_break() { {'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4}.reduce |$memo, $x| { if $x[1] == 4 { break() } $string = "${memo[0]}${x[0]}" $number = $memo[1] + $x[1] [$string, $number] } } notify { String(please_break()): } CODE end it 'breaks iteration as if at end of input in an each for an array' do expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]') function please_break() { [1,2,3].each |$x| { if $x == 3 { break() } notify { "$x": } } } please_break() CODE end it 'breaks iteration as if at end of input in an each for a hash' do expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]') function please_break() { {'a' => 1, 'b' => 2, 'c' => 3}.each |$x, $y| { if $y == 3 { break() } notify { "$y": } } } please_break() CODE end it 'breaks iteration as if at end of input in a reverse_each' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[2]') function please_break() { [1,2,3].reverse_each |$x| { if $x == 1 { break() } notify { "$x": } } } please_break() CODE end it 'does not provide early exit from a class' do # A break would semantically mean that the class should not be included - as if the # iteration over class names should stop. That is too magic and should # be done differently by the user. # expect do compile_to_catalog(<<-CODE) class does_break { notice 'a' if 1 == 1 { break() } # avoid making next line statically unreachable notice 'b' } include(does_break) CODE end.to raise_error(/break\(\) from context where this is illegal \(file: unknown, line: 3\) on node.*/) end it 'does not provide early exit from a define' do # A break would semantically mean that the resource should not be created - as if the # iteration over resource titles should stop. That is too magic and should # be done differently by the user. # expect do compile_to_catalog(<<-CODE) define does_break { notice 'a' if 1 == 1 { break() } # avoid making next line statically unreachable notice 'b' } does_break { 'no_you_cannot': } CODE end.to raise_error(/break\(\) from context where this is illegal \(file: unknown, line: 3\) on node.*/) end it 'can be called when nested in a function to make that function behave as a break' do # This allows functions like break_when(...) to be implemented by calling break() conditionally # expect(eval_and_collect_notices(<<-CODE)).to eql(['[100]']) function nested_break($x) { if $x == 2 { break() } else { $x * 100 } } function example() { [1,2,3].map |$x| { nested_break($x) } } notice example() CODE end it 'can not be called nested from top scope' do expect do compile_to_catalog(<<-CODE) # line 1 # line 2 $result = with(1) |$x| { with($x) |$x| {break() }} notice $result CODE end.to raise_error(/break\(\) from context where this is illegal \(file: unknown, line: 3\) on node.*/) end it 'can not be called from top scope' do expect do compile_to_catalog(<<-CODE) # line 1 # line 2 break() CODE end.to raise_error(/break\(\) from context where this is illegal \(file: unknown, line: 3\) on node.*/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/min_spec.rb
spec/unit/functions/min_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the min 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("min()") }.to raise_error(/Wrong number of arguments need at least one/) end context 'compares numbers' do { [0, 1] => 0, [-1, 0] => -1, [-1.0, 0] => -1.0, }.each_pair do |values, expected| it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( min(#{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( min('a', 'b') == 'a'): }")).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 outputs deprecation warning' do { [20, "'100'"] => 20, ["'20'", "'100'"] => "'20'", ["'20'", 100] => "'20'", [20, "'100x'"] => "'100x'", ["20", "'100x'"] => "'100x'", ["'20x'", 100] => 100, }.each_pair do |values, expected| it "called as min(#{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( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end expect(warnings).to include(/auto conversion of .* is deprecated/) end end { [20, "'1e2'"] => 20, [20, "'1E2'"] => 20, [20, "'10_0'"] => 20, [20, "'100.0'"] => 20, }.each_pair do |values, expected| it "called as min(#{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( min(#{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('2.0.0')", ["Semver('5.5.5')", "Semver('5.6.7')"] => "Semver('5.5.5')", }.each_pair do |values, expected| it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'compares timespans' do { ["Timespan(2)", "Timespan(77.3)"] => "Timespan(2)", ["Timespan('1-00:00:00')", "Timespan('2-00:00:00')"] => "Timespan('1-00:00:00')", }.each_pair do |values, expected| it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'compares timestamps' do { ["Timestamp(0)", "Timestamp(298922400)"] => "Timestamp(0)", ["Timestamp('1970-01-01T12:00:00.000')", "Timestamp('1979-06-22T18:00:00.000')"] => "Timestamp('1970-01-01T12:00:00.000')", }.each_pair do |values, expected| it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do expect(compile_to_catalog("notify { String( min(#{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'"] => [20], # before since '[' is before 'a' ["{'a' => 10}", "'|a'"] => "{'a' => 10}", # before since '{' is before '|' [false, 'fal'] => "'fal'", # 'fal' before since shorter than 'false' ['/b/', "'(?-mix:a)'"] => "'(?-mix:a)'", # because regexp to_s is a (?-mix:b) string ["Timestamp(1)", "'1556 a.d'"] => "'1556 a.d'", # because timestamp to_s is a date-time string here starting with 1970 }.each_pair do |values, expected| it "called as min(#{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( min(#{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 = min("2", "10") |$a, $b| { compare($a, $b) } notify { String( $val == "10"): } 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] => 1, ["1", "2","3"] => "'1'", [1,"2",3] => 1, }.each_pair do |value, expected| it "called as max(#{value}) results in the value #{expected}" do src = "notify { String( min(#{value}) == #{expected}): }" expect(compile_to_catalog(src)).to have_resource("Notify[true]") end end { [1,2,3] => 1, ["10","2","3"] => "'10'", [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 n_after_s($a,$b) { case [$a, $b] { [String, Numeric]: { -1 } [Numeric, String]: { 1 } default: { compare($a, $b) } } } notify { String( min(#{value}) |$a,$b| {n_after_s($a,$b) } == #{expected}): } SRC expect(compile_to_catalog(src)).to have_resource("Notify[true]") end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/getvar_spec.rb
spec/unit/functions/getvar_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the getvar function' do include PuppetSpec::Compiler include Matchers::Resource context 'returns undef value' do it 'when result is undef due to missing variable' do expect( evaluate(source: "getvar('x')")).to be_nil end it 'when result is undef due to resolved undef variable value' do expect( evaluate(source: "$x = undef; getvar('x')")).to be_nil end it 'when result is undef due to navigation into undef' do expect( evaluate(source: "$x = undef; getvar('x.0')")).to be_nil end end context 'returns default value' do it 'when result is undef due to missing variable' do expect( evaluate(source: "getvar('x', 'ok')")).to eql('ok') end it 'when result is undef due to resolved undef variable value' do expect( evaluate(source: "$x = undef; getvar('x', 'ok')")).to eql('ok') end it 'when result is undef due to navigation into undef' do expect( evaluate(source: "$x = undef; getvar('x.0', 'ok')")).to eql('ok') end end it 'returns value of $variable if dotted navigation is not present' do expect(evaluate(source: "$x = 'testing'; getvar('x')")).to eql('testing') end it 'returns value of fully qualified $namespace::variable if dotted navigation is not present' do expect(evaluate( code: "class testing::nested { $x = ['ok'] } include 'testing::nested'", source: "getvar('testing::nested::x.0')" )).to eql('ok') end it 'navigates into $variable if given dot syntax after variable name' do expect( evaluate( variables: {'x'=> ['nope', ['ok']]}, source: "getvar('x.1.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: "getvar('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: "$x =['nope', ['ok']]; getvar('x.1.blue')") }.to raise_error(/The given data requires an Integer index/) end ['X', ':::x', 'x:::x', 'x-x', '_x::x', 'x::', '1'].each do |var_string| it "an error pointing out that varible is invalid is raised for variable '#{var_string}'" do expect { evaluate(source: "getvar(\"#{var_string}.1.blue\")") }.to raise_error(/The given string does not start with a valid variable name/) end end it 'calls a given block with EXPECTED_INTEGER_INDEX if navigating into array with string' do expect(evaluate( source: "$x = ['nope', ['ok']]; getvar('x.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: "$x = ['nope', /nah/]; getvar('x.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: "$x = ['nope', ['ok']]; getvar('x.1.blue', 'nope') |$msg| { undef }" )).to be_nil end it 'for "expected collection" case' do expect(evaluate( source: "$x = ['nope', /nah/]; getvar('x.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: "$x = ['nope', /nah/]; getvar('x.1....') |$msg| { fail('so sad') }" )}.to raise_error(/Syntax error/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/any_spec.rb
spec/unit/functions/any_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'shared_behaviours/iterative_functions' describe 'the any method' do include PuppetSpec::Compiler context "should be callable as" do it 'any on an array' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.any |$v| { $v == 2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'any on an array with index' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.any |$i, $v| { $i == 2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'any on a hash selecting entries' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>'ah','b'=>'be','c'=>'ce'} $n = $a.any |$e| { $e[1] == 'be' } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'any on a hash selecting key and value' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>'ah','b'=>'be','c'=>'ce'} $n = $a.any |$k, $v| { $v == 'be' } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['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.any |$v| { if $v == 1 { true } else { fail("unwanted") } } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end end context "produces a boolean" do it 'true when boolean true is found' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.any |$v| { true } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'true when truthy is found' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.any |$v| { 42 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'false when truthy is not found (all undef)' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.any |$v| { undef } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "false")['ensure']).to eq('present') end it 'false when truthy is not found (all false)' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.any |$v| { false } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "false")['ensure']).to eq('present') end end it_should_behave_like 'all iterative functions argument checks', 'any' it_should_behave_like 'all iterative functions hash handling', 'any' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/require_spec.rb
spec/unit/functions/require_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet/parser/functions' require 'matchers/containment_matchers' require 'matchers/resource' require 'matchers/include_in_order' require 'unit/functions/shared' describe 'The "require" function' do include PuppetSpec::Compiler include ContainmentMatchers include Matchers::Resource before(:each) do compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo")) @scope = compiler.topscope end it 'includes a class that is not already included' do catalog = compile_to_catalog(<<-MANIFEST) class required { notify { "required": } } require required MANIFEST expect(catalog.classes).to include("required") end it 'sets the require attribute on the requiring resource' do catalog = compile_to_catalog(<<-MANIFEST) class required { notify { "required": } } class requiring { require required } include requiring MANIFEST requiring = catalog.resource("Class", "requiring") expect(requiring["require"]).to be_instance_of(Array) expect(requiring["require"][0]).to be_instance_of(Puppet::Resource) expect(requiring["require"][0].to_s).to eql("Class[Required]") end it 'appends to the require attribute on the requiring resource if it already has requirements' do catalog = compile_to_catalog(<<-MANIFEST) class required { } class also_required { } class requiring { require required require also_required } include requiring MANIFEST requiring = catalog.resource("Class", "requiring") expect(requiring["require"]).to be_instance_of(Array) expect(requiring["require"][0]).to be_instance_of(Puppet::Resource) expect(requiring["require"][0].to_s).to eql("Class[Required]") expect(requiring["require"][1]).to be_instance_of(Puppet::Resource) expect(requiring["require"][1].to_s).to eql("Class[Also_required]") end it "includes the class when using a fully qualified anchored name" do catalog = compile_to_catalog(<<-MANIFEST) class required { notify { "required": } } require ::required MANIFEST expect(catalog.classes).to include("required") end it_should_behave_like 'all functions transforming relative to absolute names', :require it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :require it_should_behave_like 'an inclusion function, when --tasks is on,', :require end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/match_spec.rb
spec/unit/functions/match_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/loaders' describe 'the match 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 let(:func) do Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'match') end let(:type_parser) { Puppet::Pops::Types::TypeParser.singleton } it 'matches string and regular expression without captures' do expect(func.call({}, 'abc123', /[a-z]+[1-9]+/)).to eql(['abc123']) end it 'matches string and regular expression with captures' do expect(func.call({}, 'abc123', /([a-z]+)([1-9]+)/)).to eql(['abc123', 'abc', '123']) end it 'produces nil if match is not found' do expect(func.call({}, 'abc123', /([x]+)([6]+)/)).to be_nil end [ 'Pattern[/([a-z]+)([1-9]+)/]', # regexp 'Pattern["([a-z]+)([1-9]+)"]', # string 'Regexp[/([a-z]+)([1-9]+)/]', # regexp type 'Pattern[/x9/, /([a-z]+)([1-9]+)/]', # regexp, first found matches ].each do |pattern| it "matches string and type #{pattern} with captures" do expect(func.call({}, 'abc123', type(pattern))).to eql(['abc123', 'abc', '123']) end it "matches string with an alias type for #{pattern} with captures" do expect(func.call({}, 'abc123', alias_type("MyAlias", type(pattern)))).to eql(['abc123', 'abc', '123']) end it "matches string with a matching variant type for #{pattern} with captures" do expect(func.call({}, 'abc123', variant_type(type(pattern)))).to eql(['abc123', 'abc', '123']) end end it 'matches an array of strings and yields a map of the result' do expect(func.call({}, ['abc123', '2a', 'xyz2'], /([a-z]+)[1-9]+/)).to eql([['abc123', 'abc'], nil, ['xyz2', 'xyz']]) end it 'raises error if Regexp type without regexp is used' do expect{func.call({}, 'abc123', type('Regexp'))}.to raise_error(ArgumentError, /Given Regexp Type has no regular expression/) end def variant_type(*t) Puppet::Pops::Types::PVariantType.new(t) end def alias_type(name, t) # Create an alias using a nil AST (which is never used because it is given a type as resolution) Puppet::Pops::Types::PTypeAliasType.new(name, nil, t) end def type(s) Puppet::Pops::Types::TypeParser.singleton.parse(s) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/return_spec.rb
spec/unit/functions/return_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the return function' do include PuppetSpec::Compiler include Matchers::Resource context 'returns from outer function when called from nested block' do it 'with a given value as function result' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[100]') function please_return() { [1,2,3].map |$x| { if $x == 1 { return(100) } 200 } 300 } notify { String(please_return()): } CODE end it 'with undef value as function result when not given an argument' do # strict mode is off so behavior this test is trying to check isn't stubbed out Puppet[:strict_variables] = false Puppet[:strict] = :warning expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[xy]') function please_return() { [1,2,3].map |$x| { if $x == 1 { return() } 200 } 300 } notify { "x${please_return}y": } CODE end end it 'can be called without parentheses around the argument' do expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[100]') function please_return() { if 1 == 1 { return 100 } 200 } notify { String(please_return()): } 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 { return() } # 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 { return() } # 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 be called when nested in a function to make that function return' do expect(eval_and_collect_notices(<<-CODE)).to eql(['100']) function nested_return() { with(1) |$x| { with($x) |$x| {return(100) }} } notice nested_return() CODE end it 'can not be called nested from top scope' do expect do compile_to_catalog(<<-CODE) # line 1 # line 2 $result = with(1) |$x| { with($x) |$x| {return(100) }} notice $result CODE end.to raise_error(/return\(\) from context where this is illegal \(file: unknown, line: 3\) on node.*/) end it 'can not be called from top scope' do expect do compile_to_catalog(<<-CODE) # line 1 # line 2 return() CODE end.to raise_error(/return\(\) from context where this is illegal \(file: unknown, line: 3\) on node.*/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/downcase_spec.rb
spec/unit/functions/downcase_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the downcase function' do include PuppetSpec::Compiler include Matchers::Resource it 'returns lower case version of a string' do expect(compile_to_catalog("notify { 'ABC'.downcase: }")).to have_resource('Notify[abc]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.downcase == 42): }")).to have_resource('Notify[true]') end it 'performs downcase of international UTF-8 characters' do expect(compile_to_catalog("notify { 'ÅÄÖ'.downcase: }")).to have_resource('Notify[åäö]') end it 'returns lower case version of each entry in an array (recursively)' do expect(compile_to_catalog("notify { String(['A', ['B', ['C']]].downcase == ['a', ['b', ['c']]]): }")).to have_resource('Notify[true]') end it 'returns lower case version of keys and values in a hash (recursively)' do expect(compile_to_catalog("notify { String({'A'=>'B','C'=>{'D'=>'E'}}.downcase == {'a'=>'b', 'c'=>{'d'=>'e'}}): }")).to have_resource('Notify[true]') end it 'returns lower case version of keys and values in nested hash / array structure' do expect(compile_to_catalog("notify { String({'A'=>['B'],'C'=>[{'D'=>'E'}]}.downcase == {'a'=>['b'],'c'=>[{'d'=>'e'}]}): }")).to have_resource('Notify[true]') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/new_spec.rb
spec/unit/functions/new_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the new function' do include PuppetSpec::Compiler include Matchers::Resource it 'yields converted value if given a block' do expect(compile_to_catalog(<<-MANIFEST $x = Integer.new('42') |$x| { $x+2 } notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 44]') end it 'produces undef if given an undef value and type accepts it' do expect(compile_to_catalog(<<-MANIFEST $x = Optional[Integer].new(undef) notify { "one${x}word": } MANIFEST )).to have_resource('Notify[oneword]') end it 'errors if given undef and type does not accept the value' do expect{compile_to_catalog(<<-MANIFEST $x = Integer.new(undef) notify { "one${x}word": } MANIFEST )}.to raise_error(Puppet::Error, /of type Undef cannot be converted to Integer/) end it 'errors if converted value is not assignable to the type' do expect{compile_to_catalog(<<-MANIFEST $x = Integer[1,5].new('42') notify { "one${x}word": } MANIFEST )}.to raise_error(Puppet::Error, /expects an Integer\[1, 5\] value, got Integer\[42, 42\]/) end it 'accepts and returns a second parameter that is an instance of the first, even when the type has no backing new_function' do expect(eval_and_collect_notices(<<-MANIFEST)).to eql(%w(true true true true true true)) notice(undef == Undef(undef)) notice(default == Default(default)) notice(Any == Type(Any)) $b = Binary('YmluYXI=') notice($b == Binary($b)) $t = Timestamp('2012-03-04T09:10:11.001') notice($t == Timestamp($t)) type MyObject = Object[{attributes => {'type' => String}}] $o = MyObject('Remote') notice($o == MyObject($o)) MANIFEST end context 'when invoked on NotUndef' do it 'produces an instance of the NotUndef nested type' do expect(compile_to_catalog(<<-MANIFEST $x = NotUndef[Integer].new(42) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 42]') end it 'produces the given value when there is no type specified' do expect(compile_to_catalog(<<-MANIFEST $x = NotUndef.new(42) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 42]') end end context 'when invoked on an Integer' do it 'produces 42 when given the integer 42' do expect(compile_to_catalog(<<-MANIFEST $x = Integer.new(42) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 42]') end it 'produces 3 when given the float 3.1415' do expect(compile_to_catalog(<<-MANIFEST $x = Integer.new(3.1415) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 3]') end it 'produces 0 from false' do expect(compile_to_catalog(<<-MANIFEST $x = Integer.new(false) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 0]') end it 'produces 1 from true' do expect(compile_to_catalog(<<-MANIFEST $x = Integer.new(true) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 1]') end it "produces an absolute value when third argument is 'true'" do expect(eval_and_collect_notices(<<-MANIFEST notice(Integer.new(-42, 10, true)) MANIFEST )).to eql(['42']) end it "does not produce an absolute value when third argument is 'false'" do expect(eval_and_collect_notices(<<-MANIFEST notice(Integer.new(-42, 10, false)) MANIFEST )).to eql(['-42']) end it "produces an absolute value from hash {from => val, abs => true}" do expect(eval_and_collect_notices(<<-MANIFEST notice(Integer.new({from => -42, abs => true})) MANIFEST )).to eql(['42']) end it "does not produce an absolute value from hash {from => val, abs => false}" do expect(eval_and_collect_notices(<<-MANIFEST notice(Integer.new({from => -42, abs => false})) MANIFEST )).to eql(['-42']) end context 'when prefixed by a sign' do { '+1' => 1, '-1' => -1, '+ 1' => 1, '- 1' => -1, '+0x10' => 16, '+ 0x10' => 16, '-0x10' => -16, '- 0x10' => -16 }.each do |str, result| it "produces #{result} from the string '#{str}'" do expect(compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}") notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource("Notify[Integer, #{result}]") end end end context "when radix is not set it uses default and" do { "10" => 10, "010" => 8, "0x10" => 16, "0X10" => 16, '0B111' => 7, '0b111' => 7 }.each do |str, result| it "produces #{result} from the string '#{str}'" do expect(compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}") notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource("Notify[Integer, #{result}]") end end { '0x0G' => :error, '08' => :error, '10F' => :error, '0B2' => :error, }.each do |str, result| it "errors when given a non Integer compliant string '#{str}'" do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}") MANIFEST )}.to raise_error(Puppet::Error, /invalid value|cannot be converted to Integer/) end end end context "when radix is explicitly set to 'default' it" do { "10" => 10, "010" => 8, "0x10" => 16, "0X10" => 16, '0B111' => 7, '0b111' => 7 }.each do |str, result| it "produces #{result} from the string '#{str}'" do expect(compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", default) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource("Notify[Integer, #{result}]") end end end context "when radix is explicitly set to '2' it" do { "10" => 2, "010" => 2, "00010" => 2, '0B111' => 7, '0b111' => 7, '+0B111' => 7, '-0b111' => -7, '+ 0B111'=> 7, '- 0b111'=> -7 }.each do |str, result| it "produces #{result} from the string '#{str}'" do expect(compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 2) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource("Notify[Integer, #{result}]") end end { '0x10' => :error, '0X10' => :error, '+0X10' => :error, '-0X10' => :error, '+ 0X10'=> :error, '- 0X10'=> :error }.each do |str, result| it "errors when given the non binary value compliant string '#{str}'" do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 2) MANIFEST )}.to raise_error(Puppet::Error, /invalid value/) end end end context "when radix is explicitly set to '8' it" do { "10" => 8, "010" => 8, "00010" => 8, '+00010' => 8, '-00010' => -8, '+ 00010'=> 8, '- 00010'=> -8, }.each do |str, result| it "produces #{result} from the string '#{str}'" do expect(compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 8) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource("Notify[Integer, #{result}]") end end { "0x10" => :error, '0X10' => :error, '0B10' => :error, '0b10' => :error, '+0b10' => :error, '-0b10' => :error, '+ 0b10'=> :error, '- 0b10'=> :error, }.each do |str, result| it "errors when given the non octal value compliant string '#{str}'" do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 8) MANIFEST )}.to raise_error(Puppet::Error, /invalid value/) end end end context "when radix is explicitly set to '16' it" do { "10" => 16, "010" => 16, "00010" => 16, "0x10" => 16, "0X10" => 16, "0b1" => 16*11+1, "0B1" => 16*11+1, '+0B1' => 16*11+1, '-0B1' => -16*11-1, '+ 0B1' => 16*11+1, '- 0B1' => -16*11-1, }.each do |str, result| it "produces #{result} from the string '#{str}'" do expect(compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 16) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource("Notify[Integer, #{result}]") end end { '0XGG' => :error, '+0XGG' => :error, '-0XGG' => :error, '+ 0XGG'=> :error, '- 0XGG'=> :error, }.each do |str, result| it "errors when given the non hexadecimal value compliant string '#{str}'" do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 8) MANIFEST )}.to raise_error(Puppet::Error, /The string '#{Regexp.escape(str)}' cannot be converted to Integer/) end end end context "when radix is explicitly set to '10' it" do { "10" => 10, "010" => 10, "00010" => 10, "08" => 8, "0008" => 8, }.each do |str, result| it "produces #{result} from the string '#{str}'" do expect(compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 10) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource("Notify[Integer, #{result}]") end end { '0X10' => :error, '0b10' => :error, '0B10' => :error, }.each do |str, result| it "errors when given the non binary value compliant string '#{str}'" do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new("#{str}", 10) MANIFEST )}.to raise_error(Puppet::Error, /invalid value/) end end end context "input can be given in long form " do { {'from' => "10", 'radix' => 2} => 2, {'from' => "10", 'radix' => 8} => 8, {'from' => "10", 'radix' => 10} => 10, {'from' => "10", 'radix' => 16} => 16, {'from' => "10", 'radix' => :default} => 10, }.each do |options, result| it "produces #{result} from the long form '#{options}'" do src = <<-"MANIFEST" $x = Integer.new(#{options.to_s.gsub(/:/, '')}) notify { "${type($x, generalized)}, $x": } MANIFEST expect(compile_to_catalog(src)).to have_resource("Notify[Integer, #{result}]") end end end context 'errors when' do it 'radix is wrong and when given directly' do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new('10', 3) MANIFEST )}.to raise_error(Puppet::Error, /Illegal radix/) end it 'radix is wrong and when given in long form' do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new({from =>'10', radix=>3}) MANIFEST )}.to raise_error(Puppet::Error, /Illegal radix/) end it 'value is not numeric and given directly' do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new('eleven', 10) MANIFEST )}.to raise_error(Puppet::Error, /The string 'eleven' cannot be converted to Integer/) end it 'value is not numeric and given in long form' do expect{compile_to_catalog(<<-"MANIFEST" $x = Integer.new({from => 'eleven', radix => 10}) MANIFEST )}.to raise_error(Puppet::Error, /The string 'eleven' cannot be converted to Integer/) end end end context 'when invoked on Numeric' do { 42 => "Notify[Integer, 42]", 42.3 => "Notify[Float, 42.3]", "42.0" => "Notify[Float, 42.0]", "+42.0" => "Notify[Float, 42.0]", "-42.0" => "Notify[Float, -42.0]", "+ 42.0" => "Notify[Float, 42.0]", "- 42.0" => "Notify[Float, -42.0]", "42.3" => "Notify[Float, 42.3]", "0x10" => "Notify[Integer, 16]", "010" => "Notify[Integer, 8]", "0.10" => "Notify[Float, 0.1]", "0b10" => "Notify[Integer, 2]", "0" => "Notify[Integer, 0]", false => "Notify[Integer, 0]", true => "Notify[Integer, 1]", }.each do |input, result| it "produces #{result} when given the value #{input.inspect}" do expect(compile_to_catalog(<<-MANIFEST $x = Numeric.new(#{input.inspect}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end it "produces a result when long from hash {from => val} is used" do expect(compile_to_catalog(<<-MANIFEST $x = Numeric.new({from=>'42'}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Integer, 42]') end it "produces an absolute value when second argument is 'true'" do expect(eval_and_collect_notices(<<-MANIFEST notice(Numeric.new(-42.3, true)) MANIFEST )).to eql(['42.3']) end it "does not produce an absolute value when second argument is 'false'" do expect(eval_and_collect_notices(<<-MANIFEST notice(Numeric.new(-42.3, false)) MANIFEST )).to eql(['-42.3']) end it "produces an absolute value from hash {from => val, abs => true}" do expect(eval_and_collect_notices(<<-MANIFEST notice(Numeric.new({from => -42.3, abs => true})) MANIFEST )).to eql(['42.3']) end it "does not produce an absolute value from hash {from => val, abs => false}" do expect(eval_and_collect_notices(<<-MANIFEST notice(Numeric.new({from => -42.3, abs => false})) MANIFEST )).to eql(['-42.3']) end end context 'when invoked on Float' do { 42 => "Notify[Float, 42.0]", 42.3 => "Notify[Float, 42.3]", "42.0" => "Notify[Float, 42.0]", "+42.0" => "Notify[Float, 42.0]", "-42.0" => "Notify[Float, -42.0]", "+ 42.0" => "Notify[Float, 42.0]", "- 42.0" => "Notify[Float, -42.0]", "42.3" => "Notify[Float, 42.3]", "0x10" => "Notify[Float, 16.0]", "010" => "Notify[Float, 10.0]", "0.10" => "Notify[Float, 0.1]", false => "Notify[Float, 0.0]", true => "Notify[Float, 1.0]", '0b10' => "Notify[Float, 2.0]", '0B10' => "Notify[Float, 2.0]", }.each do |input, result| it "produces #{result} when given the value #{input.inspect}" do expect(compile_to_catalog(<<-MANIFEST $x = Float.new(#{input.inspect}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end it "produces a result when long from hash {from => val} is used" do expect(compile_to_catalog(<<-MANIFEST $x = Float.new({from=>42}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Float, 42.0]') end it "produces an absolute value when second argument is 'true'" do expect(eval_and_collect_notices(<<-MANIFEST notice(Float.new(-42.3, true)) MANIFEST )).to eql(['42.3']) end it "does not produce an absolute value when second argument is 'false'" do expect(eval_and_collect_notices(<<-MANIFEST notice(Float.new(-42.3, false)) MANIFEST )).to eql(['-42.3']) end it "produces an absolute value from hash {from => val, abs => true}" do expect(eval_and_collect_notices(<<-MANIFEST notice(Float.new({from => -42.3, abs => true})) MANIFEST )).to eql(['42.3']) end it "does not produce an absolute value from hash {from => val, abs => false}" do expect(eval_and_collect_notices(<<-MANIFEST notice(Float.new({from => -42.3, abs => false})) MANIFEST )).to eql(['-42.3']) end end context 'when invoked on Boolean' do { true => 'Notify[Boolean, true]', false => 'Notify[Boolean, false]', 0 => 'Notify[Boolean, false]', 1 => 'Notify[Boolean, true]', 0.0 => 'Notify[Boolean, false]', 1.0 => 'Notify[Boolean, true]', 'true' => 'Notify[Boolean, true]', 'TrUe' => 'Notify[Boolean, true]', 'yes' => 'Notify[Boolean, true]', 'YeS' => 'Notify[Boolean, true]', 'y' => 'Notify[Boolean, true]', 'Y' => 'Notify[Boolean, true]', 'false' => 'Notify[Boolean, false]', 'no' => 'Notify[Boolean, false]', 'n' => 'Notify[Boolean, false]', 'FalSE' => 'Notify[Boolean, false]', 'nO' => 'Notify[Boolean, false]', 'N' => 'Notify[Boolean, false]', }.each do |input, result| it "produces #{result} when given the value #{input.inspect}" do expect(compile_to_catalog(<<-MANIFEST $x = Boolean.new(#{input.inspect}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end it "errors when given an non boolean representation like the string 'hello'" do expect{compile_to_catalog(<<-"MANIFEST" $x = Boolean.new('hello') MANIFEST )}.to raise_error(Puppet::Error, /The string 'hello' cannot be converted to Boolean/) end it "does not convert an undef (as may be expected, but is handled as every other undef)" do expect{compile_to_catalog(<<-"MANIFEST" $x = Boolean.new(undef) MANIFEST )}.to raise_error(Puppet::Error, /of type Undef cannot be converted to Boolean/) end end context 'when invoked on Array' do { [] => 'Notify[Array[Unit], []]', [true] => 'Notify[Array[Boolean], [true]]', {'a'=>true, 'b' => false} => 'Notify[Array[Array[ScalarData]], [[a, true], [b, false]]]', 'abc' => 'Notify[Array[String[1, 1]], [a, b, c]]', 3 => 'Notify[Array[Integer], [0, 1, 2]]', }.each do |input, result| it "produces #{result} when given the value #{input.inspect} and wrap is not given" do expect(compile_to_catalog(<<-MANIFEST $x = Array.new(#{input.inspect}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end { true => /of type Boolean cannot be converted to Array/, 42.3 => /of type Float cannot be converted to Array/, }.each do |input, error_match| it "errors when given an non convertible #{input.inspect} when wrap is not given" do expect{compile_to_catalog(<<-"MANIFEST" $x = Array.new(#{input.inspect}) MANIFEST )}.to raise_error(Puppet::Error, error_match) end end { [] => 'Notify[Array[Unit], []]', [true] => 'Notify[Array[Boolean], [true]]', {'a'=>true} => 'Notify[Array[Hash[String, Boolean]], [{a => true}]]', 'hello' => 'Notify[Array[String], [hello]]', true => 'Notify[Array[Boolean], [true]]', 42 => 'Notify[Array[Integer], [42]]', }.each do |input, result| it "produces #{result} when given the value #{input.inspect} and wrap is given" do expect(compile_to_catalog(<<-MANIFEST $x = Array.new(#{input.inspect}, true) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end it 'produces an array of byte integer values when given a Binary' do expect(compile_to_catalog(<<-MANIFEST $x = Array.new(Binary('ABC', '%s')) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Array[Integer], [65, 66, 67]]') end it 'wraps a binary when given extra argument true' do expect(compile_to_catalog(<<-MANIFEST $x = Array[Any].new(Binary('ABC', '%s'), true) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Array[Binary], [QUJD]]') end end context 'when invoked on Tuple' do { 'abc' => 'Notify[Array[String[1, 1]], [a, b, c]]', 3 => 'Notify[Array[Integer], [0, 1, 2]]', }.each do |input, result| it "produces #{result} when given the value #{input.inspect} and wrap is not given" do expect(compile_to_catalog(<<-MANIFEST $x = Tuple[Any,3].new(#{input.inspect}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end it "errors when tuple requirements are not met" do expect{compile_to_catalog(<<-"MANIFEST" $x = Tuple[Integer,6].new(3) MANIFEST )}.to raise_error(Puppet::Error, /expects size to be at least 6, got 3/) end end context 'when invoked on Hash' do { {} => 'Notify[Hash[0, 0], {}]', [] => 'Notify[Hash[0, 0], {}]', {'a'=>true} => 'Notify[Hash[String, Boolean], {a => true}]', [1,2,3,4] => 'Notify[Hash[Integer, Integer], {1 => 2, 3 => 4}]', [[1,2],[3,4]] => 'Notify[Hash[Integer, Integer], {1 => 2, 3 => 4}]', 'abcd' => 'Notify[Hash[String[1, 1], String[1, 1]], {a => b, c => d}]', 4 => 'Notify[Hash[Integer, Integer], {0 => 1, 2 => 3}]', }.each do |input, result| it "produces #{result} when given the value #{input.inspect}" do expect(compile_to_catalog(<<-MANIFEST $x = Hash.new(#{input.inspect}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end { true => /Value of type Boolean cannot be converted to Hash/, [1,2,3] => /odd number of arguments for Hash/, }.each do |input, error_match| it "errors when given an non convertible #{input.inspect}" do expect{compile_to_catalog(<<-"MANIFEST" $x = Hash.new(#{input.inspect}) MANIFEST )}.to raise_error(Puppet::Error, error_match) end end context 'when using the optional "tree" format' do it 'can convert a tree in flat form to a hash' do expect(compile_to_catalog(<<-"MANIFEST" $x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2,0], d]], tree) notify { test: message => $x } MANIFEST )).to have_resource('Notify[test]').with_parameter(:message, { 0 => 'a', 1 => { 0 => 'b', 1=> 'c'}, 2 => {0 => 'd'} }) end it 'preserves array in flattened tree but overwrites entries if they are present' do expect(compile_to_catalog(<<-"MANIFEST" $x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2], [overwritten, kept]], [[2,0], d]], tree) notify { test: message => $x } MANIFEST )).to have_resource('Notify[test]').with_parameter(:message, { 0 => 'a', 1 => { 0 => 'b', 1=> 'c'}, 2 => ['d', 'kept'] }) end it 'preserves hash in flattened tree but overwrites entries if they are present' do expect(compile_to_catalog(<<-"MANIFEST" $x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2], {0 => 0, kept => 1}], [[2,0], d]], tree) notify { test: message => $x } MANIFEST )).to have_resource('Notify[test]').with_parameter(:message, { 0 => 'a', 1 => { 0 => 'b', 1=> 'c'}, 2 => {0=>'d', 'kept'=>1} }) end end context 'when using the optional "tree_hash" format' do it 'turns array in flattened tree into hash' do expect(compile_to_catalog(<<-"MANIFEST" $x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2], [overwritten, kept]], [[2,0], d]], hash_tree) notify { test: message => $x } MANIFEST )).to have_resource('Notify[test]').with_parameter(:message, { 0=>'a', 1=>{ 0=>'b', 1=>'c'}, 2=>{0=>'d', 1=>'kept'}}) end end end context 'when invoked on Struct' do { {'a' => 2} => 'Notify[Struct[{\'a\' => Integer[2, 2]}], {a => 2}]', }.each do |input, result| it "produces #{result} when given the value #{input.inspect}" do expect(compile_to_catalog(<<-MANIFEST $x = Struct[{a => Integer[2]}].new(#{input.inspect}) notify { "${type($x)}, $x": } MANIFEST )).to have_resource(result) end end it "errors when tuple requirements are not met" do expect{compile_to_catalog(<<-"MANIFEST" $x = Struct[{a => Integer[2]}].new({a => 0}) MANIFEST )}.to raise_error(Puppet::Error, /entry 'a' expects an Integer\[2\]/) end end context 'when invoked on String' do { {} => 'Notify[String, {}]', [] => 'Notify[String, []]', {'a'=>true} => "Notify[String, {'a' => true}]", [1,2,3,4] => 'Notify[String, [1, 2, 3, 4]]', [[1,2],[3,4]] => 'Notify[String, [[1, 2], [3, 4]]]', 'abcd' => 'Notify[String, abcd]', 4 => 'Notify[String, 4]', }.each do |input, result| it "produces #{result} when given the value #{input.inspect}" do expect(compile_to_catalog(<<-MANIFEST $x = String.new(#{input.inspect}) notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource(result) end end end context 'when invoked on a type alias' do it 'delegates the new to the aliased type' do expect(compile_to_catalog(<<-MANIFEST type X = Boolean $x = X.new('yes') notify { "${type($x, generalized)}, $x": } MANIFEST )).to have_resource('Notify[Boolean, true]') end end context 'when invoked on a Type' do it 'creates a Type from its string representation' do expect(compile_to_catalog(<<-MANIFEST $x = Type.new('Integer[3,10]') notify { "${type($x)}": } MANIFEST )).to have_resource('Notify[Type[Integer[3, 10]]]') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/dig_spec.rb
spec/unit/functions/dig_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the dig function' do include PuppetSpec::Compiler include Matchers::Resource it 'returns a value from an array index via integer index' do expect(compile_to_catalog("notify { [testing].dig(0): }")).to have_resource('Notify[testing]') end it 'returns undef if given an undef key' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test-Undef-ing]') notify { "test-${type([testing].dig(undef))}-ing": } SOURCE end it 'returns undef if starting with undef' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test-Undef-ing]') notify { "test-${type(undef.dig(undef))}-ing": } SOURCE end it 'returns a value from an hash key via given key' do expect(compile_to_catalog("notify { {key => testing}.dig(key): }")).to have_resource('Notify[testing]') end it 'continues digging if result is an array' do expect(compile_to_catalog("notify { [nope, [testing]].dig(1, 0): }")).to have_resource('Notify[testing]') end it 'continues digging if result is a hash' do expect(compile_to_catalog("notify { [nope, {yes => testing}].dig(1, yes): }")).to have_resource('Notify[testing]') end it 'stops digging when step is undef' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[testing]') $result = [nope, {yes => testing}].dig(1, no, 2) notify { "test${result}ing": } SOURCE end it 'errors if step is neither Array nor Hash' do expect { compile_to_catalog(<<-SOURCE)}.to raise_error(/The given data does not contain a Collection at \[1, "yes"\], got 'String'/) $result = [nope, {yes => testing}].dig(1, yes, 2) notify { "test${result}ing": } SOURCE end it 'errors if not given a non Collection as the starting point' do expect { compile_to_catalog(<<-SOURCE)}.to raise_error(/'dig' parameter 'data' expects a value of type Undef or Collection, got String/) "hello".dig(1, yes, 2) SOURCE end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/size_spec.rb
spec/unit/functions/size_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the size function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an array it' do it 'returns 0 when empty' do expect(compile_to_catalog("notify { String(size([])): }")).to have_resource('Notify[0]') end it 'returns number of elements when not empty' do expect(compile_to_catalog("notify { String(size([1, 2, 3])): }")).to have_resource('Notify[3]') end end context 'for a hash it' do it 'returns 0 empty' do expect(compile_to_catalog("notify { String(size({})): }")).to have_resource('Notify[0]') end it 'returns number of elements when not empty' do expect(compile_to_catalog("notify { String(size({1=>1,2=>2})): }")).to have_resource('Notify[2]') end end context 'for a string it' do it 'returns 0 when empty' do expect(compile_to_catalog("notify { String(size('')): }")).to have_resource('Notify[0]') end it 'returns number of characters when not empty' do # note the multibyte characters - åäö each taking two bytes in UTF-8 expect(compile_to_catalog('notify { String(size("\u00e5\u00e4\u00f6")): }')).to have_resource('Notify[3]') end end context 'for a binary it' do it 'returns 0 when empty' do expect(compile_to_catalog("notify { String(size(Binary(''))): }")).to have_resource('Notify[0]') end it 'returns number of bytes when not empty' do expect(compile_to_catalog("notify { String(size(Binary('b25l'))): }")).to have_resource('Notify[3]') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/inline_epp_spec.rb
spec/unit/functions/inline_epp_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe "the inline_epp function" do include PuppetSpec::Files include PuppetSpec::Compiler let :node do Puppet::Node.new('localhost') end let :compiler do Puppet::Parser::Compiler.new(node) end let :scope do Puppet::Parser::Scope.new(compiler) 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 "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 "get nil accessing a variable that is undef" do scope['undef_var'] = :undef 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 "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 { eval_template_with_args("<%-| $x |-%><%= $x == correct %>", {}) }.to raise_error(/expects a value for parameter 'x'/) end it 'raises an error if unexpected arguments are given' do scope['x'] = 'wrong one' expect { eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct', 'y' => 'surplus') }.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 it "renders a block expression" do expect(eval_template_with_args("<%= { $y = $x $x + 1} %>", 'x' => 2)).to eq("3") 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 context "when using Sensitive" do it "returns an unwrapped sensitive value as a String" do expect(eval_and_collect_notices(<<~END)).to eq(["opensesame"]) notice(inline_epp("<%= Sensitive('opensesame').unwrap %>")) END end it "rewraps a sensitive value" do # note entire result is redacted, not just sensitive part expect(eval_and_collect_notices(<<~END)).to eq(["Sensitive [value redacted]"]) notice(inline_epp("This is sensitive <%= Sensitive('opensesame') %>")) END end it "can be double wrapped" do catalog = compile_to_catalog(<<~END) notify { 'title': message => Sensitive(inline_epp("<%= Sensitive('opensesame') %>")) } END expect(catalog.resource(:notify, 'title')['message']).to eq('opensesame') end end def eval_template_with_args(content, args_hash) epp_function.call(scope, content, args_hash) end def eval_template(content) epp_function.call(scope, content) end def epp_function() scope.compiler.loaders.public_environment_loader.load(:function, 'inline_epp') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/then_spec.rb
spec/unit/functions/then_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the then function' do include PuppetSpec::Compiler include Matchers::Resource it 'calls a lambda passing one argument' do expect(compile_to_catalog("then(testing) |$x| { notify { $x: } }")).to have_resource('Notify[testing]') end it 'produces what lambda returns if value is not undef' do expect(compile_to_catalog("notify{ then(1) |$x| { testing }: }")).to have_resource('Notify[testing]') end it 'does not call lambda if argument is undef' do expect(compile_to_catalog('then(undef) |$x| { notify { "failed": } }')).to_not have_resource('Notify[failed]') end it 'produces undef if given value is undef' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test-Undef-ing]') notify{ "test-${type(then(undef) |$x| { testing })}-ing": } SOURCE end it 'errors when lambda wants too many args' do expect do compile_to_catalog('then(1) |$x, $y| { }') end.to raise_error(/'then' block expects 1 argument, got 2/m) end it 'errors when lambda wants too few args' do expect do compile_to_catalog('then(1) || { }') end.to raise_error(/'then' block expects 1 argument, got none/m) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/camelcase_spec.rb
spec/unit/functions/camelcase_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the camelcase function' do include PuppetSpec::Compiler include Matchers::Resource it 'replaces initial <char> and each _<char> with upper case version of the char' do expect(compile_to_catalog("notify { 'abc_def'.camelcase: }")).to have_resource('Notify[AbcDef]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.camelcase == 42): }")).to have_resource('Notify[true]') end it 'performs camelcase of international UTF-8 characters' do expect(compile_to_catalog("notify { 'åäö_äö'.camelcase: }")).to have_resource('Notify[ÅäöÄö]') end it 'returns capitalized version of each entry in an array' do expect(compile_to_catalog("notify { String(['a_a', 'b_a', 'c_a'].camelcase == ['AA', 'BA', 'CA']): }")).to have_resource('Notify[true]') end it 'returns capitalized version of each entry in an Iterator' do expect(compile_to_catalog("notify { String(['a_a', 'b_a', 'c_a'].reverse_each.camelcase == ['CA', 'BA', 'AA']): }")).to have_resource('Notify[true]') end it 'errors when given a a nested Array' do expect { compile_to_catalog("['a', 'b', ['c']].camelcase")}.to raise_error(/'camelcase' parameter 'arg' expects a value of type Numeric, String, or Iterable/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/all_spec.rb
spec/unit/functions/all_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'shared_behaviours/iterative_functions' describe 'the all method' do include PuppetSpec::Compiler context "should be callable as" do it 'all on an array' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $n = $a.all |$v| { $v > 0 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'all on an array with index' do catalog = compile_to_catalog(<<-MANIFEST) $a = [0,2,4] $n = $a.all |$i, $v| { $v == $i * 2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'all on a hash selecting entries' do catalog = compile_to_catalog(<<-MANIFEST) $a = {0=>0,1=>2,2=>4} $n = $a.all |$e| { $e[1] == $e[0]*2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'all on a hash selecting key and value' do catalog = compile_to_catalog(<<-MANIFEST) $a = {0=>0,1=>2,2=>4} $n = $a.all |$k,$v| { $v == $k*2 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end end context "produces a boolean" do it 'true when boolean true is found' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.all |$v| { true } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'true when truthy is found' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.all |$v| { 42 } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "true")['ensure']).to eq('present') end it 'false when truthy is not found (all undef)' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.all |$v| { undef } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "false")['ensure']).to eq('present') end it 'false when truthy is not found (all false)' do catalog = compile_to_catalog(<<-MANIFEST) $a = [6,6,6] $n = $a.all |$v| { false } file { "$n": ensure => present } MANIFEST expect(catalog.resource(:file, "false")['ensure']).to eq('present') end end it_should_behave_like 'all iterative functions argument checks', 'any' it_should_behave_like 'all iterative functions hash handling', 'any' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/include_spec.rb
spec/unit/functions/include_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet/parser/functions' require 'matchers/containment_matchers' require 'matchers/resource' require 'matchers/include_in_order' require 'unit/functions/shared' describe 'The "include" function' do include PuppetSpec::Compiler include ContainmentMatchers include Matchers::Resource before(:each) do compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo")) @scope = Puppet::Parser::Scope.new(compiler) end it "includes a class" do catalog = compile_to_catalog(<<-MANIFEST) class included { notify { "included": } } include included MANIFEST expect(catalog.classes).to include("included") end it "includes a class when using a fully qualified anchored name" do catalog = compile_to_catalog(<<-MANIFEST) class included { notify { "included": } } include ::included MANIFEST expect(catalog.classes).to include("included") end it "includes multiple classes" do catalog = compile_to_catalog(<<-MANIFEST) class included { notify { "included": } } class included_too { notify { "included_too": } } include included, included_too MANIFEST expect(catalog.classes).to include("included") expect(catalog.classes).to include("included_too") end it "includes multiple classes given as an array" do catalog = compile_to_catalog(<<-MANIFEST) class included { notify { "included": } } class included_too { notify { "included_too": } } include [included, included_too] MANIFEST expect(catalog.classes).to include("included") expect(catalog.classes).to include("included_too") end it "flattens nested arrays" do catalog = compile_to_catalog(<<-MANIFEST) class included { notify { "included": } } class included_too { notify { "included_too": } } include [[[included], [[[included_too]]]]] MANIFEST expect(catalog.classes).to include("included") expect(catalog.classes).to include("included_too") end it "raises an error if class does not exist" do expect { compile_to_catalog(<<-MANIFEST) include the_god_in_your_religion MANIFEST }.to raise_error(Puppet::Error) end { "''" => 'empty string', 'undef' => 'undef', "['']" => 'empty string', "[undef]" => 'undef' }.each_pair do |value, name_kind| it "raises an error if class is #{name_kind}" do expect { compile_to_catalog(<<-MANIFEST) include #{value} MANIFEST }.to raise_error(/Cannot use #{name_kind}/) end end it "does not contained the included class in the current class" do catalog = compile_to_catalog(<<-MANIFEST) class not_contained { notify { "not_contained": } } class container { include not_contained } include container MANIFEST expect(catalog).to_not contain_class("not_contained").in("container") end it 'produces an array with a single class references given a single argument' do catalog = compile_to_catalog(<<-MANIFEST) class a { notify { "a": } } $x = include(a) Array[Type[Class], 1, 1].assert_type($x) notify { 'feedback': message => "$x" } MANIFEST feedback = catalog.resource("Notify", "feedback") expect(feedback[:message]).to eql("[Class[a]]") end it 'produces an array with class references given multiple arguments' do catalog = compile_to_catalog(<<-MANIFEST) class a { notify { "a": } } class b { notify { "b": } } $x = include(a, b) Array[Type[Class], 2, 2].assert_type($x) notify { 'feedback': message => "$x" } MANIFEST feedback = catalog.resource("Notify", "feedback") expect(feedback[:message]).to eql("[Class[a], Class[b]]") end it 'allows the result to be used in a relationship operation' do catalog = compile_to_catalog(<<-MANIFEST) class a { notify { "a": } } class b { notify { "b": } } notify { 'c': } include(a, b) -> Notify[c] MANIFEST # Assert relationships are formed expect(catalog.resource("Class", "a")[:before][0]).to eql('Notify[c]') expect(catalog.resource("Class", "b")[:before][0]).to eql('Notify[c]') end it_should_behave_like 'all functions transforming relative to absolute names', :include it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :include it_should_behave_like 'an inclusion function, when --tasks is on,', :include end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/annotate_spec.rb
spec/unit/functions/annotate_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/compiler' describe 'the annotate function' do include PuppetSpec::Compiler let(:annotation) { <<-PUPPET } type MyAdapter = Object[{ parent => Annotation, attributes => { id => Integer, value => String[1] } }] PUPPET let(:annotation2) { <<-PUPPET } type MyAdapter2 = Object[{ parent => Annotation, attributes => { id => Integer, value => String[1] } }] PUPPET context 'with object and hash arguments' do it 'creates new annotation on object' do code = <<-PUPPET #{annotation} type MyObject = Object[{ }] $my_object = MyObject({}) MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value' }) notice(MyAdapter.annotate($my_object).value) PUPPET expect(eval_and_collect_notices(code)).to eql(['annotation value']) end it 'forces creation of new annotation' do code = <<-PUPPET #{annotation} type MyObject = Object[{ }] $my_object = MyObject({}) MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value' }) notice(MyAdapter.annotate($my_object).value) MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value 2' }) notice(MyAdapter.annotate($my_object).value) PUPPET expect(eval_and_collect_notices(code)).to eql(['annotation value', 'annotation value 2']) end end context 'with object and block arguments' do it 'creates new annotation on object' do code = <<-PUPPET #{annotation} type MyObject = Object[{ }] $my_object = MyObject({}) MyAdapter.annotate($my_object) || { { 'id' => 2, 'value' => 'annotation value' } } notice(MyAdapter.annotate($my_object).value) PUPPET expect(eval_and_collect_notices(code)).to eql(['annotation value']) end it 'does not recreate annotation' do code = <<-PUPPET #{annotation} type MyObject = Object[{ }] $my_object = MyObject({}) MyAdapter.annotate($my_object) || { notice('should call this'); { 'id' => 2, 'value' => 'annotation value' } } MyAdapter.annotate($my_object) || { notice('should not call this'); { 'id' => 2, 'value' => 'annotation value 2' } } notice(MyAdapter.annotate($my_object).value) PUPPET expect(eval_and_collect_notices(code)).to eql(['should call this', 'annotation value']) end end it "with object and 'clear' arguments, clears and returns annotation" do code = <<-PUPPET #{annotation} type MyObject = Object[{ }] $my_object = MyObject({}) MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value' }) notice(MyAdapter.annotate($my_object, clear).value) notice(MyAdapter.annotate($my_object) == undef) PUPPET expect(eval_and_collect_notices(code)).to eql(['annotation value', 'true']) end context 'when object is an annotated Type' do it 'finds annotation declared in the type' do code = <<-PUPPET #{annotation} type MyObject = Object[{ annotations => { MyAdapter => { 'id' => 2, 'value' => 'annotation value' } } }] notice(MyAdapter.annotate(MyObject).value) PUPPET expect(eval_and_collect_notices(code)).to eql(['annotation value']) end it 'fails attempts to clear a declared annotation' do code = <<-PUPPET #{annotation} type MyObject = Object[{ annotations => { MyAdapter => { 'id' => 2, 'value' => 'annotation value' } } }] notice(MyAdapter.annotate(MyObject).value) notice(MyAdapter.annotate(MyObject, clear).value) PUPPET expect { eval_and_collect_notices(code) }.to raise_error(/attempt to clear MyAdapter annotation declared on MyObject/) end it 'fails attempts to redefine a declared annotation' do code = <<-PUPPET #{annotation} type MyObject = Object[{ annotations => { MyAdapter => { 'id' => 2, 'value' => 'annotation value' } } }] notice(MyAdapter.annotate(MyObject).value) notice(MyAdapter.annotate(MyObject, { 'id' => 3, 'value' => 'some other value' }).value) PUPPET expect { eval_and_collect_notices(code) }.to raise_error(/attempt to redefine MyAdapter annotation declared on MyObject/) end it 'allows annotation that are not declared in the type' do code = <<-PUPPET #{annotation} #{annotation2} type MyObject = Object[{ annotations => { MyAdapter => { 'id' => 2, 'value' => 'annotation value' } } }] notice(MyAdapter.annotate(MyObject).value) notice(MyAdapter2.annotate(MyObject, { 'id' => 3, 'value' => 'some other value' }).value) PUPPET expect(eval_and_collect_notices(code)).to eql(['annotation value', 'some other value']) end end it 'used on Pcore, can add multiple annotations an object' do code = <<-PUPPET #{annotation} #{annotation2} type MyObject = Object[{ }] $my_object = Pcore.annotate(MyObject({}), { MyAdapter => { 'id' => 2, 'value' => 'annotation value' }, MyAdapter2 => { 'id' => 3, 'value' => 'second annotation value' } }) notice(MyAdapter.annotate($my_object).value) notice(MyAdapter2.annotate($my_object).value) PUPPET expect(eval_and_collect_notices(code)).to eql(['annotation value', 'second annotation value']) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/binary_file_spec.rb
spec/unit/functions/binary_file_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'puppet_spec/files' describe 'the binary_file 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 'reads an existing absolute file' do with_file_content('one') do |one| # Note that Binary to String produced Base64 encoded version of 'one' which is 'b23l' expect(compile_to_catalog("notify { String(binary_file('#{one}')):}")).to have_resource("Notify[b25l]") end end it 'errors on non existing files' do expect do with_file_content('one') do |one| compile_to_catalog("notify { binary_file('#{one}/nope'):}") end end.to raise_error(/The given file '.+\/nope' does not exist/) end it 'reads an existing file in a module' do with_file_content('binary_data') do |name| mod = double('module') allow(mod).to receive(:file).with('myfile').and_return(name) Puppet[:code] = "notify { String(binary_file('mymod/myfile')):}" node = Puppet::Node.new('localhost') compiler = Puppet::Parser::Compiler.new(node) allow(compiler.environment).to receive(:module).with('mymod').and_return(mod) # Note that the Binary to string produces Base64 encoded version of 'binary_data' which is 'YmluYXJ5X2RhdGE=' expect(compiler.compile().filter { |r| r.virtual? }).to have_resource("Notify[YmluYXJ5X2RhdGE=]") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/type_spec.rb
spec/unit/functions/type_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the type function' do include PuppetSpec::Compiler include Matchers::Resource it 'produces the type of a given value with default detailed quality' do expect(compile_to_catalog('notify { "${ type([2, 3.14]) }": }')).to have_resource( 'Notify[Tuple[Integer[2, 2], Float[3.14, 3.14]]]') end it 'produces the type of a give value with detailed quality when quality is given' do expect(compile_to_catalog('notify { "${ type([2, 3.14], detailed) }": }')).to have_resource( 'Notify[Tuple[Integer[2, 2], Float[3.14, 3.14]]]') end it 'produces the type of a given value with reduced quality when quality is given' do expect(compile_to_catalog('notify { "${ type([2, 3.14], reduced) }": }')).to have_resource( 'Notify[Array[Numeric, 2, 2]]') end it 'produces the type of a given value with generalized quality when quality is given' do expect(compile_to_catalog('notify { "${ type([2, 3.14], generalized) }": }')).to have_resource( 'Notify[Array[Numeric]]') end it 'errors when given a fault inference quality' do expect do compile_to_catalog("notify { type([2, 4.14], gobbledygooked): }") end.to raise_error(/expects a match for Enum\['detailed', 'generalized', 'reduced'\], got 'gobbledygooked'/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/with_spec.rb
spec/unit/functions/with_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the with function' do include PuppetSpec::Compiler include Matchers::Resource it 'calls a lambda passing no arguments' do expect(compile_to_catalog("with() || { notify { testing: } }")).to have_resource('Notify[testing]') end it 'calls a lambda passing a single argument' do expect(compile_to_catalog('with(1) |$x| { notify { "testing$x": } }')).to have_resource('Notify[testing1]') end it 'calls a lambda passing more than one argument' do expect(compile_to_catalog('with(1, 2) |*$x| { notify { "testing${x[0]}, ${x[1]}": } }')).to have_resource('Notify[testing1, 2]') end it 'passes a type reference to a lambda' do expect(compile_to_catalog('notify { test: message => "data" } with(Notify[test]) |$x| { notify { "${x[message]}": } }')).to have_resource('Notify[data]') end it 'errors when not given enough arguments for the lambda' do expect do compile_to_catalog('with(1) |$x, $y| { }') end.to raise_error(/Parameter \$y is required but no value was given/m) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/length_spec.rb
spec/unit/functions/length_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the length function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an array it' do it 'returns 0 when empty' do expect(compile_to_catalog("notify { String(length([])): }")).to have_resource('Notify[0]') end it 'returns number of elements when not empty' do expect(compile_to_catalog("notify { String(length([1, 2, 3])): }")).to have_resource('Notify[3]') end end context 'for a hash it' do it 'returns 0 empty' do expect(compile_to_catalog("notify { String(length({})): }")).to have_resource('Notify[0]') end it 'returns number of elements when not empty' do expect(compile_to_catalog("notify { String(length({1=>1,2=>2})): }")).to have_resource('Notify[2]') end end context 'for a string it' do it 'returns 0 when empty' do expect(compile_to_catalog("notify { String(length('')): }")).to have_resource('Notify[0]') end it 'returns number of characters when not empty' do # note the multibyte characters - åäö each taking two bytes in UTF-8 expect(compile_to_catalog('notify { String(length("\u00e5\u00e4\u00f6")): }')).to have_resource('Notify[3]') end end context 'for a binary it' do it 'returns 0 when empty' do expect(compile_to_catalog("notify { String(length(Binary(''))): }")).to have_resource('Notify[0]') end it 'returns number of bytes when not empty' do expect(compile_to_catalog("notify { String(length(Binary('b25l'))): }")).to have_resource('Notify[3]') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/hiera_spec.rb
spec/unit/functions/hiera_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet/pops' describe 'when calling' do include PuppetSpec::Compiler include PuppetSpec::Files let(:global_dir) { tmpdir('global') } let(:env_config) { {} } let(:hiera_yaml) { <<-YAML.unindent } --- :backends: - yaml - hieraspec :yaml: :datadir: #{global_dir}/hieradata :hierarchy: - first - second YAML let(:hieradata_files) do { 'first.yaml' => <<-YAML.unindent, --- a: first a class_name: "-- %{calling_class} --" class_path: "-- %{calling_class_path} --" module: "-- %{calling_module} --" mod_name: "-- %{module_name} --" database_user: name: postgres uid: 500 gid: 500 groups: db: 520 b: b1: first b1 b2: first b2 fbb: - mod::foo - mod::bar - mod::baz empty_array: [] nested_array: first: - 10 - 11 second: - 21 - 22 dotted.key: a: dotted.key a b: dotted.key b dotted.array: - a - b YAML 'second.yaml' => <<-YAML.unindent, --- a: second a b: b1: second b1 b3: second b3 YAML 'the_override.yaml' => <<-YAML.unindent --- key: foo_result YAML } end let(:environment_files) do { 'test' => { 'modules' => { 'mod' => { 'manifests' => { 'foo.pp' => <<-PUPPET.unindent, class mod::foo { notice(hiera('class_name')) notice(hiera('class_path')) notice(hiera('module')) notice(hiera('mod_name')) } PUPPET 'bar.pp' => <<-PUPPET.unindent, class mod::bar {} PUPPET 'baz.pp' => <<-PUPPET.unindent class mod::baz {} PUPPET }, 'hiera.yaml' => <<-YAML.unindent, --- version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent mod::c: mod::c (from module) YAML } } } }.merge(env_config) } end let(:global_files) do { 'hiera.yaml' => hiera_yaml, 'hieradata' => hieradata_files, 'environments' => environment_files } end let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } let(:env_dir) { File.join(global_dir, 'environments') } let(:env) { Puppet::Node::Environment.create(:test, [File.join(env_dir, 'test', 'modules')]) } let(:environments) { Puppet::Environments::Directories.new(env_dir, []) } let(:node) { Puppet::Node.new('test_hiera', :environment => env) } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera') } before(:all) do $LOAD_PATH.unshift(File.join(my_fixture_dir)) end after(:all) do Hiera::Backend.send(:remove_const, :Hieraspec_backend) if Hiera::Backend.const_defined?(:Hieraspec_backend) $LOAD_PATH.shift end before(:each) do Puppet.settings[:codedir] = global_dir Puppet.settings[:hiera_config] = File.join(global_dir, 'hiera.yaml') end around(:each) do |example| dir_contained_in(global_dir, global_files) Puppet.override(:environments => environments, :current_environment => env) do example.run end end def with_scope(code = 'undef') result = nil Puppet[:code] = 'undef' Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile do |catalog| result = yield(compiler.topscope) catalog end end result end def func(*args, &block) with_scope { |scope| the_func.call(scope, *args, &block) } end context 'hiera', :if => Puppet.features.hiera? do it 'should require a key argument' do expect { func([]) }.to raise_error(ArgumentError) end it 'should raise a useful error when nil is returned' do expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/) end it 'should use the "first" merge strategy' do expect(func('a')).to eql('first a') end it 'should allow lookup with quoted dotted key' do expect(func("'dotted.key'")).to eql({'a' => 'dotted.key a', 'b' => 'dotted.key b'}) end it 'should allow lookup with dotted key' do expect(func('database_user.groups.db')).to eql(520) end it 'should not find data in module' do expect(func('mod::c', 'default mod::c')).to eql('default mod::c') end it 'should propagate optional override' do ovr = 'the_override' expect(func('key', nil, ovr)).to eql('foo_result') end it 'backend data sources, including optional overrides, are propagated to custom backend' do expect(func('datasources', nil, 'the_override')).to eql(['the_override', 'first', 'second']) end it 'a hiera v3 scope is used', :if => Puppet.features.hiera? do expect(eval_and_collect_notices(<<-PUPPET, node)).to eql(['-- testing --', '-- mod::foo --', '-- mod/foo --', '-- mod --', '-- mod --']) class testing () { notice(hiera('class_name')) } include testing include mod::foo PUPPET end it 'should return default value nil when key is not found' do expect(func('foo', nil)).to be_nil end it "should return default value '' when key is not found" do expect(func('foo', '')).to eq('') end it 'should use default block' do expect(func('foo') { |k| "default for key '#{k}'" }).to eql("default for key 'foo'") end it 'should propagate optional override when combined with default block' do ovr = 'the_override' with_scope do |scope| expect(the_func.call(scope, 'key', ovr) { |k| "default for key '#{k}'" }).to eql('foo_result') expect(the_func.call(scope, 'foo.bar', ovr) { |k| "default for key '#{k}'" }).to eql("default for key 'foo.bar'") end end it 'should log deprecation errors' do func('a') expect(warnings).to include(/The function 'hiera' is deprecated in favor of using 'lookup'. See https:/) end context 'with environment with configured data provider' do let(:env_config) { { 'hiera.yaml' => <<-YAML.unindent, --- version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent --- a: a (from environment) e: e (from environment) YAML } } } it 'should find data globally' do expect(func('a')).to eql('first a') end it 'should find data in the environment' do expect(func('e')).to eql('e (from environment)') end it 'should find data in module' do expect(func('mod::c')).to eql('mod::c (from module)') end end it 'should not be disabled by data_binding_terminus setting' do Puppet[:data_binding_terminus] = 'none' expect(func('a')).to eql('first a') end end context 'hiera_array', :if => Puppet.features.hiera? do let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_array') } it 'should require a key argument' do expect { func([]) }.to raise_error(ArgumentError) end it 'should raise a useful error when nil is returned' do expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/) end it 'should log deprecation errors' do func('fbb') expect(warnings).to include(/The function 'hiera_array' is deprecated in favor of using 'lookup'/) end it 'should use the array resolution_type' do expect(func('fbb', {'fbb' => 'foo_result'})).to eql(%w[mod::foo mod::bar mod::baz]) end it 'should allow lookup with quoted dotted key' do expect(func("'dotted.array'")).to eql(['a', 'b']) end it 'should fail lookup with dotted key' do expect{ func('nested_array.0.first') }.to raise_error(/Resolution type :array is illegal when accessing values using dotted keys. Offending key was 'nested_array.0.first'/) end it 'should use default block' do expect(func('foo') { |k| ['key', k] }).to eql(%w[key foo]) end end context 'hiera_hash', :if => Puppet.features.hiera? do let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_hash') } it 'should require a key argument' do expect { func([]) }.to raise_error(ArgumentError) end it 'should raise a useful error when nil is returned' do expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/) end it 'should use the hash resolution_type' do expect(func('b', {'b' => 'foo_result'})).to eql({ 'b1' => 'first b1', 'b2' => 'first b2', 'b3' => 'second b3'}) end it 'should lookup and return a hash' do expect(func('database_user')).to eql({ 'name' => 'postgres', 'uid' => 500, 'gid' => 500, 'groups' => { 'db' => 520 }}) end it 'should allow lookup with quoted dotted key' do expect(func("'dotted.key'")).to eql({'a' => 'dotted.key a', 'b' => 'dotted.key b'}) end it 'should fail lookup with dotted key' do expect{ func('database_user.groups') }.to raise_error(/Resolution type :hash is illegal when accessing values using dotted keys. Offending key was 'database_user.groups'/) end it 'should log deprecation errors' do func('b') expect(warnings).to include(/The function 'hiera_hash' is deprecated in favor of using 'lookup'. See https:/) end it 'should use default block' do expect(func('foo') { |k| {'key' => k} }).to eql({'key' => 'foo'}) end end context 'hiera_include', :if => Puppet.features.hiera? do let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_include') } it 'should require a key argument' do expect { func([]) }.to raise_error(ArgumentError) end it 'should raise a useful error when nil is returned' do expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/) end it 'should use the array resolution_type to include classes' do expect(func('fbb').map { |c| c.class_name }).to eql(%w[mod::foo mod::bar mod::baz]) end it 'should log deprecation errors' do func('fbb') expect(warnings).to include(/The function 'hiera_include' is deprecated in favor of using 'lookup'. See https:/) end it 'should not raise an error if the resulting hiera lookup returns an empty array' do expect { func('empty_array') }.to_not raise_error end it 'should use default block array to include classes' do expect(func('foo') { |k| ['mod::bar', "mod::#{k}"] }.map { |c| c.class_name }).to eql(%w[mod::bar mod::foo]) end end context 'with custom backend and merge_behavior declared in hiera.yaml', :if => Puppet.features.hiera? do let(:merge_behavior) { 'deeper' } let(:hiera_yaml) do <<-YAML.unindent --- :backends: - yaml - hieraspec :yaml: :datadir: #{global_dir}/hieradata :hierarchy: - common - other :merge_behavior: #{merge_behavior} :deep_merge_options: :unpack_arrays: ',' YAML end let(:global_files) do { 'hiera.yaml' => hiera_yaml, 'hieradata' => { 'common.yaml' => <<-YAML.unindent, da: - da 0 - da 1 dm: dm1: dm11: value of dm11 (from common) dm12: value of dm12 (from common) dm2: dm21: value of dm21 (from common) hash: array: - x1,x2 array: - x1,x2 YAML 'other.yaml' => <<-YAML.unindent, da: - da 2,da 3 dm: dm1: dm11: value of dm11 (from other) dm13: value of dm13 (from other) dm3: dm31: value of dm31 (from other) hash: array: - x3 - x4 array: - x3 - x4 YAML } } end context 'hiera_hash' do let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_hash') } context "using 'deeper'" do it 'declared merge_behavior is honored' do expect(func('dm')).to eql({ 'dm1' => { 'dm11' => 'value of dm11 (from common)', 'dm12' => 'value of dm12 (from common)', 'dm13' => 'value of dm13 (from other)' }, 'dm2' => { 'dm21' => 'value of dm21 (from common)' }, 'dm3' => { 'dm31' => 'value of dm31 (from other)' } }) end it "merge behavior is propagated to a custom backend as 'hash'" do expect(func('resolution_type')).to eql({ 'resolution_type' => 'hash' }) end it 'fails on attempts to merge an array' do expect {func('da')}.to raise_error(/expects a Hash value/) end it 'honors option :unpack_arrays: (unsupported by puppet)' do expect(func('hash')).to eql({'array' => %w(x3 x4 x1 x2)}) end end context "using 'deep'" do let(:merge_behavior) { 'deep' } it 'honors option :unpack_arrays: (unsupported by puppet)' do expect(func('hash')).to eql({'array' => %w(x1 x2 x3 x4)}) end end end context 'hiera_array', :if => Puppet.features.hiera? do let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_array') } it 'declared merge_behavior is ignored' do expect(func('da')).to eql(['da 0', 'da 1', 'da 2,da 3']) end it "merge behavior is propagated to a custom backend as 'array'" do expect(func('resolution_type')).to eql(['resolution_type', 'array']) end end context 'hiera' do let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera') } it 'declared merge_behavior is ignored' do expect(func('da')).to eql(['da 0', 'da 1']) end it "no merge behavior is propagated to a custom backend" do expect(func('resolution_type')).to eql('resolution_type=') end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/unique_spec.rb
spec/unit/functions/unique_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the unique function' do include PuppetSpec::Compiler include Matchers::Resource context 'produces the unique set of chars from a String such that' do it 'same case is considered unique' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "abc") notify{ 'test': message => 'abcbbcc'.unique } SOURCE end it 'different case is not considered unique' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "abcABC") notify{ 'test': message => 'abcAbbBccC'.unique } SOURCE end it 'case independent matching can be performed with a lambda' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "abc") notify{ 'test': message => 'abcAbbBccC'.unique |$x| { String($x, '%d') } } SOURCE end it 'the first found value in the unique set is used' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "AbC") notify{ 'test': message => 'AbCAbbBccC'.unique |$x| { String($x, '%d') } } SOURCE end end context 'produces the unique set of values from an Array such that' do it 'ruby equality is used to compute uniqueness by default' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['a', 'b', 'c', 'B', 'C']) notify{ 'test': message => [a, b, c, a, 'B', 'C'].unique } SOURCE end it 'accepts a lambda to perform the value to use for uniqueness' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['a', 'b', 'c']) notify{ 'test': message => [a, b, c, a, 'B', 'C'].unique |$x| { String($x, '%d') }} SOURCE end it 'the first found value in the unique set is used' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['A', 'b', 'C']) notify{ 'test': message => ['A', b, 'C', a, 'B', 'c'].unique |$x| { String($x, '%d') }} SOURCE end end context 'produces the unique set of values from an Hash such that' do it 'resulting keys and values in hash are arrays' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, {['a'] => [10], ['b']=>[20]}) notify{ 'test': message => {a => 10, b => 20}.unique } SOURCE end it 'resulting keys contain all keys with same value' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, {['a', 'b'] => [10], ['c']=>[20]}) notify{ 'test': message => {a => 10, b => 10, c => 20}.unique } SOURCE end it 'resulting values contain Ruby == unique set of values' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, {['a'] => [10], ['b', 'c']=>[11, 20]}) notify{ 'test': message => {a => 10, b => 11, c => 20}.unique |$x| { if $x > 10 {bigly} else { $x }}} SOURCE end end context 'produces the unique set of values from an Iterable' do it 'such as reverse_each - in reverse order' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['B','b','a']) notify{ 'test': message => ['a', 'b', 'B'].reverse_each.unique } SOURCE end it 'such as Integer[1,5]' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, [1,2,3,4,5]) notify{ 'test': message => Integer[1,5].unique } SOURCE end it 'such as the Integer 3' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, [0,1,2]) notify{ 'test': message => 3.unique } SOURCE end it 'allows lambda to be used with Iterable' do expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['B','a']) notify{ 'test': message => ['a', 'b', 'B'].reverse_each.unique |$x| { String($x, '%d') }} SOURCE end end it 'errors when given unsupported data type as input' do expect do compile_to_catalog(<<-SOURCE) undef.unique SOURCE end.to raise_error(/expects an Iterable value, got Undef/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/capitalize_spec.rb
spec/unit/functions/capitalize_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the capitalize function' do include PuppetSpec::Compiler include Matchers::Resource it 'returns initial char upper case version of a string' do expect(compile_to_catalog("notify { 'abc'.capitalize: }")).to have_resource('Notify[Abc]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.capitalize == 42): }")).to have_resource('Notify[true]') end it 'performs capitalize of international UTF-8 characters' do expect(compile_to_catalog("notify { 'åäö'.capitalize: }")).to have_resource('Notify[Åäö]') end it 'returns capitalized version of each entry in an array' do expect(compile_to_catalog("notify { String(['aa', 'ba', 'ca'].capitalize == ['Aa', 'Ba', 'Ca']): }")).to have_resource('Notify[true]') end it 'returns capitalized version of each entry in an Iterator' do expect(compile_to_catalog("notify { String(['aa', 'ba', 'ca'].reverse_each.capitalize == ['Ca', 'Ba', 'Aa']): }")).to have_resource('Notify[true]') end it 'errors when given a a nested Array' do expect { compile_to_catalog("['a', 'b', ['c']].capitalize")}.to raise_error(/'capitalize' parameter 'arg' expects a value of type Numeric, String, or Iterable/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/chomp_spec.rb
spec/unit/functions/chomp_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the chomp function' do include PuppetSpec::Compiler include Matchers::Resource it 'removes line endings CR LF from a string' do expect(compile_to_catalog("notify { String(\"abc\r\n\".chomp == 'abc'): }")).to have_resource('Notify[true]') end it 'removes line ending CR from a string' do expect(compile_to_catalog("notify { String(\"abc\r\".chomp == 'abc'): }")).to have_resource('Notify[true]') end it 'removes line ending LF from a string' do expect(compile_to_catalog("notify { String(\"abc\n\".chomp == 'abc'): }")).to have_resource('Notify[true]') end it 'does not removes LF before CR line ending from a string' do expect(compile_to_catalog("notify { String(\"abc\n\r\".chomp == \"abc\n\"): }")).to have_resource('Notify[true]') end it 'returns empty string for an empty string' do expect(compile_to_catalog("notify { String(''.chomp == ''): }")).to have_resource('Notify[true]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.chomp == 42): }")).to have_resource('Notify[true]') end it 'returns chomped version of each entry in an array' do expect(compile_to_catalog("notify { String([\"a\n\", \"b\n\", \"c\n\"].chomp == ['a', 'b', 'c']): }")).to have_resource('Notify[true]') end it 'returns chopped version of each entry in an Iterator' do expect(compile_to_catalog("notify { String([\"a\n\", \"b\n\", \"c\n\"].reverse_each.chomp == ['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']].chomp")}.to raise_error(/'chomp' parameter 'arg' expects a value of type Numeric, String, or Iterable/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/flatten_spec.rb
spec/unit/functions/flatten_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the flatten function' do include PuppetSpec::Compiler include Matchers::Resource let(:array_fmt) { { 'format' => "%(a", 'separator'=>""} } it 'returns flattened array of all its given arguments' do expect(compile_to_catalog("notify { String([1,[2,[3]]].flatten, Array => #{array_fmt}): }")).to have_resource('Notify[(123)]') end it 'accepts a single non array value which results in it being wrapped in an array' do expect(compile_to_catalog("notify { String(flatten(1), Array => #{array_fmt}): }")).to have_resource('Notify[(1)]') end it 'accepts a single array value - (which is a noop)' do expect(compile_to_catalog("notify { String(flatten([1]), Array => #{array_fmt}): }")).to have_resource('Notify[(1)]') end it 'it does not flatten a hash - it is a value that gets wrapped' do expect(compile_to_catalog("notify { String(flatten({a=>1}), Array => #{array_fmt}): }")).to have_resource("Notify[({'a' => 1})]") end it 'accepts mix of array and non array arguments and concatenates and flattens them' do expect(compile_to_catalog("notify { String(flatten([1],2,[[3,4]]), Array => #{array_fmt}): }")).to have_resource('Notify[(1234)]') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/compare_spec.rb
spec/unit/functions/compare_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the compare function' do include PuppetSpec::Compiler include Matchers::Resource { [0, 1] => -1, [1, 0] => 1, [1, 1] => 0, [0.0, 1.0] => -1, [1.0, 0.0] => 1, [1.0, 1.0] => 0, [0.0, 1] => -1, [1.0, 0] => 1, [1.0, 1] => 0, [0, 1.0] => -1, [1, 0.0] => 1, [1, 1.0] => 0, }.each_pair do |values, expected| it "compares numeric/numeric such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end { ['"a"', '"b"'] => -1, ['"b"', '"a"'] => 1, ['"b"', '"b"'] => 0, ['"A"', '"b"'] => -1, ['"B"', '"a"'] => 1, ['"B"', '"b"'] => 0, }.each_pair do |values, expected| it "compares String values by default such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end it "compares String values with third true arg such that compare(#{values[0]}, #{values[1]}, true) returns #{expected}" do expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}, true) == #{expected}): }")).to have_resource("Notify[true]") end end { ['"a"', '"b"'] => -1, ['"b"', '"a"'] => 1, ['"b"', '"b"'] => 0, ['"A"', '"b"'] => -1, ['"B"', '"a"'] => -1, ['"B"', '"b"'] => -1, }.each_pair do |values, expected| it "compares String values with third arg false such that compare(#{values[0]}, #{values[1]}, false) returns #{expected}" do expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}, false) == #{expected}): }")).to have_resource("Notify[true]") end end { ["Semver('1.0.0')", "Semver('2.0.0')"] => -1, ["Semver('2.0.0')", "Semver('1.0.0')"] => 1, ["Semver('2.0.0')", "Semver('2.0.0')"] => 0, }.each_pair do |values, expected| it "compares Semver values such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end { ["Timespan(1)", "Timespan(2)"] => -1, ["Timespan(2)", "Timespan(1)"] => 1, ["Timespan(1)", "Timespan(1)"] => 0, ["Timespan(1)", 2] => -1, ["Timespan(2)", 1] => 1, ["Timespan(1)", 1] => 0, [1, "Timespan(2)"] => -1, [2, "Timespan(1)"] => 1, [1, "Timespan(1)"] => 0, ["Timestamp(1)", "Timestamp(2)"] => -1, ["Timestamp(2)", "Timestamp(1)"] => 1, ["Timestamp(1)", "Timestamp(1)"] => 0, ["Timestamp(1)", 2] => -1, ["Timestamp(2)", 1] => 1, ["Timestamp(1)", 1] => 0, [1, "Timestamp(2)"] => -1, [2, "Timestamp(1)"] => 1, [1, "Timestamp(1)"] => 0, }.each_pair do |values, expected| it "compares time values such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]") end end context "errors when" do [ [true, false], ['/x/', '/x/'], ['undef', 'undef'], ['undef', 1], [1, 'undef'], [[1], [1]], [{'a' => 1}, {'b' => 1}], ].each do |a, b| it "given values of non comparable types #{a.class}, #{b.class}" do expect { compile_to_catalog("compare(#{a},#{b})")}.to raise_error(/Non comparable type/) end end [ [10, '"hello"'], ['"hello"', 10], [10.0, '"hello"'], ['"hello"', 10.0], ['Timespan(1)', '"hello"'], ['Timestamp(1)', '"hello"'], ['Timespan(1)', 'Semver("1.2.3")'], ['Timestamp(1)', 'Semver("1.2.3")'], ].each do |a, b| it "given values of comparable, but incompatible types #{a.class}, #{b.class}" do expect { compile_to_catalog("compare(#{a},#{b})")}.to raise_error(/Can only compare values of the same type/) end end [ [10, 10], [10.0, 10], ['Timespan(1)', 'Timespan(1)'], ['Timestamp(1)', 'Timestamp(1)'], ['Semver("1.2.3")', 'Semver("1.2.3")'], ].each do |a, b| it "given ignore case true when values are comparable, but not both being strings" do expect { compile_to_catalog("compare(#{a},#{b}, true)")}.to raise_error(/can only be used when comparing strings/) end it "given ignore case false when values are comparable, but not both being strings" do expect { compile_to_catalog("compare(#{a},#{b}, false)")}.to raise_error(/can only be used when comparing strings/) end end it "given more than three arguments" do expect { compile_to_catalog("compare('a','b', false, false)")}.to raise_error(/Accepts at most 3 arguments, got 4/) end end # Error if not the same except Timestamp and Timespan that accepts Numeric on either side # Error for non supported - Boolean, Regexp, etc end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/contain_spec.rb
spec/unit/functions/contain_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet/parser/functions' require 'matchers/containment_matchers' require 'matchers/resource' require 'matchers/include_in_order' require 'unit/functions/shared' describe 'The "contain" function' do include PuppetSpec::Compiler include ContainmentMatchers include Matchers::Resource before(:each) do compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo")) @scope = Puppet::Parser::Scope.new(compiler) end it "includes the class" do catalog = compile_to_catalog(<<-MANIFEST) class contained { notify { "contained": } } class container { contain contained } include container MANIFEST expect(catalog.classes).to include("contained") end it "includes the class when using a fully qualified anchored name" do catalog = compile_to_catalog(<<-MANIFEST) class contained { notify { "contained": } } class container { contain ::contained } include container MANIFEST expect(catalog.classes).to include("contained") end it "ensures that the edge is with the correct class" do catalog = compile_to_catalog(<<-MANIFEST) class outer { class named { } contain outer::named } class named { } include named include outer MANIFEST expect(catalog).to have_resource("Class[Named]") expect(catalog).to have_resource("Class[Outer]") expect(catalog).to have_resource("Class[Outer::Named]") expect(catalog).to contain_class("outer::named").in("outer") end it "makes the class contained in the current class" do catalog = compile_to_catalog(<<-MANIFEST) class contained { notify { "contained": } } class container { contain contained } include container MANIFEST expect(catalog).to contain_class("contained").in("container") end it "can contain multiple classes" do catalog = compile_to_catalog(<<-MANIFEST) class a { notify { "a": } } class b { notify { "b": } } class container { contain a, b } include container MANIFEST expect(catalog).to contain_class("a").in("container") expect(catalog).to contain_class("b").in("container") end context "when containing a class in multiple classes" do it "creates a catalog with all containment edges" do catalog = compile_to_catalog(<<-MANIFEST) class contained { notify { "contained": } } class container { contain contained } class another { contain contained } include container include another MANIFEST expect(catalog).to contain_class("contained").in("container") expect(catalog).to contain_class("contained").in("another") end it "and there are no dependencies applies successfully" do manifest = <<-MANIFEST class contained { notify { "contained": } } class container { contain contained } class another { contain contained } include container include another MANIFEST expect { apply_compiled_manifest(manifest) }.not_to raise_error end it "and there are explicit dependencies on the containing class causes a dependency cycle" do manifest = <<-MANIFEST class contained { notify { "contained": } } class container { contain contained } class another { contain contained } include container include another Class["container"] -> Class["another"] MANIFEST expect { apply_compiled_manifest(manifest) }.to raise_error( Puppet::Error, /One or more resource dependency cycles detected in graph/ ) end end it "does not create duplicate edges" do catalog = compile_to_catalog(<<-MANIFEST) class contained { notify { "contained": } } class container { contain contained contain contained } include container MANIFEST contained = catalog.resource("Class", "contained") container = catalog.resource("Class", "container") expect(catalog.edges_between(container, contained).count).to eq 1 end context "when a containing class has a dependency order" do it "the contained class is applied in that order" do catalog = compile_to_relationship_graph(<<-MANIFEST) class contained { notify { "contained": } } class container { contain contained } class first { notify { "first": } } class last { notify { "last": } } include container, first, last Class["first"] -> Class["container"] -> Class["last"] MANIFEST expect(order_resources_traversed_in(catalog)).to include_in_order( "Notify[first]", "Notify[contained]", "Notify[last]" ) end end it 'produces an array with a single class references given a single argument' do catalog = compile_to_catalog(<<-MANIFEST) class a { notify { "a": } } class container { $x = contain(a) Array[Type[Class], 1, 1].assert_type($x) notify { 'feedback': message => "$x" } } include container MANIFEST feedback = catalog.resource("Notify", "feedback") expect(feedback[:message]).to eql("[Class[a]]") end it 'produces an array with class references given multiple arguments' do catalog = compile_to_catalog(<<-MANIFEST) class a { notify { "a": } } class b { notify { "b": } } class container { $x = contain(a, b) Array[Type[Class], 2, 2].assert_type($x) notify { 'feedback': message => "$x" } } include container MANIFEST feedback = catalog.resource("Notify", "feedback") expect(feedback[:message]).to eql("[Class[a], Class[b]]") end it 'allows the result to be used in a relationship operation' do catalog = compile_to_catalog(<<-MANIFEST) class a { notify { "a": } } class b { notify { "b": } } notify { 'c': } class container { contain(a, b) -> Notify[c] } include container MANIFEST # Assert relationships are formed expect(catalog.resource("Class", "a")[:before][0]).to eql('Notify[c]') expect(catalog.resource("Class", "b")[:before][0]).to eql('Notify[c]') end it_should_behave_like 'all functions transforming relative to absolute names', :contain it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :contain it_should_behave_like 'an inclusion function, when --tasks is on,', :contain end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/versioncmp_spec.rb
spec/unit/functions/versioncmp_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/loaders' describe "the versioncmp 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 versioncmp(*args) Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'versioncmp').call({}, *args) end let(:type_parser) { Puppet::Pops::Types::TypeParser.singleton } it 'should raise an Error if there is less than 2 arguments' do expect { versioncmp('a,b') }.to raise_error(/expects between 2 and 3 arguments, got 1/) end it 'should raise an Error if there is more than 3 arguments' do expect { versioncmp('a,b','foo', false, 'bar') }.to raise_error(/expects between 2 and 3 arguments, got 4/) end it "should call Puppet::Util::Package.versioncmp (included in scope)" do expect(Puppet::Util::Package).to receive(:versioncmp).with('1.2', '1.3', false).and_return(-1) expect(versioncmp('1.2', '1.3')).to eq(-1) end context "when ignore_trailing_zeroes is true" do it "should equate versions with 2 elements and dots but with unnecessary zero" do expect(versioncmp("10.1.0", "10.1", true)).to eq(0) end it "should equate versions with 1 element and dot but with unnecessary zero" do expect(versioncmp("11.0", "11", true)).to eq(0) end it "should equate versions with 1 element and dot but with unnecessary zeros" do expect(versioncmp("11.00", "11", true)).to eq(0) end it "should equate versions with dots and iregular zeroes" do expect(versioncmp("11.0.00", "11", true)).to eq(0) end it "should equate versions with dashes" do expect(versioncmp("10.1-0", "10.1.0-0", true)).to eq(0) end it "should compare versions with dashes after normalization" do expect(versioncmp("10.1-1", "10.1.0-0", true)).to eq(1) end it "should not normalize versions if zeros are not trailing" do expect(versioncmp("1.1", "1.0.1", true)).to eq(1) end end context "when ignore_trailing_zeroes is false" do it "should not equate versions if zeros are not trailing" do expect(versioncmp("1.1", "1.0.1")).to eq(1) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/abs_spec.rb
spec/unit/functions/abs_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the abs function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an integer' do { 0 => 0, 1 => 1, -1 => 1 }.each_pair do |x, expected| it "called as abs(#{x}) results in #{expected}" do expect(compile_to_catalog("notify { String( abs(#{x}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'for an float' do { 0.0 => 0.0, 1.0 => 1.0, -1.1 => 1.1 }.each_pair do |x, expected| it "called as abs(#{x}) results in #{expected}" do expect(compile_to_catalog("notify { String( abs(#{x}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'for a string' do let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } { "0" => 0, "1" => 1, "-1" => 1, "0.0" => 0.0, "1.1" => 1.1, "-1.1" => 1.1, "0777" => 777, "-0777" => 777, }.each_pair do |x, expected| it "called as abs('#{x}') results in #{expected} and deprecation warning" do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String( abs('#{x}') == #{expected}): }")).to have_resource("Notify[true]") end expect(warnings).to include(/auto conversion of .* is deprecated/) end end ['blue', '0xFF'].each do |x| it "errors when the string is not a decimal integer '#{x}' (indirectly deprecated)" do expect{ compile_to_catalog("abs('#{x}')") }.to raise_error(/was given non decimal string/) end end ['0.2.3', '1E+10'].each do |x| it "errors when the string is not a supported decimal float '#{x}' (indirectly deprecated)" do expect{ compile_to_catalog("abs('#{x}')") }.to raise_error(/was given non decimal string/) end end end [[1,2,3], {'a' => 10}].each do |x| it "errors for a value of class #{x.class}" do expect{ compile_to_catalog("abs(#{x})") }.to raise_error(/expects a value of type Numeric or String/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/logging_spec.rb
spec/unit/functions/logging_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe 'the log function' do include PuppetSpec::Compiler def collect_logs(code) Puppet[:code] = code Puppet[:environment_timeout] = 10 node = Puppet::Node.new('logtest') 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 def expect_log(code, log_level, message) logs = collect_logs(code) # There's a chance that additional messages could have been # added during code compilation like debug messages from # Facter. This happened on Appveyor when the Appveyor image # failed to resolve the domain fact. Since these messages are # not relevant to our test, and since they can (possibly) be # injected at any location in our logs array, it is good enough # to assert that our desired log _is_ included in the logs array # instead of trying to figure out _where_ it is included. expect(logs).to include(satisfy { |log| log.level == log_level && log.message == message }) end before(:each) do Puppet[:log_level] = 'debug' end Puppet::Util::Log.levels.each do |level| context "for log level '#{level}'" do it 'can be called' do expect_log("#{level.to_s}('yay')", level, 'yay') end it 'joins multiple arguments using space' do # Not using the evaluator would result in yay {"a"=>"b", "c"=>"d"} expect_log("#{level.to_s}('a', 'b', 3)", level, 'a b 3') end it 'uses the evaluator to format output' do # Not using the evaluator would result in yay {"a"=>"b", "c"=>"d"} expect_log("#{level.to_s}('yay', {a => b, c => d})", level, 'yay {a => b, c => d}') end it 'returns undef value' do logs = collect_logs("notice(type(#{level.to_s}('yay')))") expect(logs.size).to eql(2) expect(logs[1].level).to eql(:notice) expect(logs[1].message).to eql('Undef') end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/ceiling_spec.rb
spec/unit/functions/ceiling_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the ceiling function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an integer' do [ 0, 1, -1].each do |x| it "called as ceiling(#{x}) results in the same value" do expect(compile_to_catalog("notify { String( ceiling(#{x}) == #{x}): }")).to have_resource("Notify[true]") end end end context 'for a float' do { 0.0 => 0, 1.1 => 2, -1.1 => -1, }.each_pair do |x, expected| it "called as ceiling(#{x}) results in #{expected}" do expect(compile_to_catalog("notify { String( ceiling(#{x}) == #{expected}): }")).to have_resource("Notify[true]") end end end context 'for a string' do let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } { "0" => 0, "1" => 1, "-1" => -1, "0.0" => 0, "1.1" => 2, "-1.1" => -1, "0777" => 777, "-0777" => -777, "0xFF" => 0xFF, }.each_pair do |x, expected| it "called as ceiling('#{x}') results in #{expected} and a deprecation warning" do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String( ceiling('#{x}') == #{expected}): }")).to have_resource("Notify[true]") end expect(warnings).to include(/auto conversion of .* is deprecated/) end end ['blue', '0.2.3'].each do |x| it "errors as the string '#{x}' cannot be converted to a float" do expect{ compile_to_catalog("ceiling('#{x}')") }.to raise_error(/cannot convert given value to a floating point value/) end end end [[1,2,3], {'a' => 10}].each do |x| it "errors for a value of class #{x.class}" do expect{ compile_to_catalog("ceiling(#{x})") }.to raise_error(/expects a value of type Numeric or String/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/map_spec.rb
spec/unit/functions/map_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'shared_behaviours/iterative_functions' describe 'the map method can' do include PuppetSpec::Compiler include Matchers::Resource it 'map on an array (multiplying each value by 2)' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $a.map |$x|{ $x*2}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_4]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present') end it 'map on an enumerable type (multiplying each value by 2)' do catalog = compile_to_catalog(<<-MANIFEST) $a = Integer[1,3] $a.map |$x|{ $x*2}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_4]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present') end it 'map on an integer (multiply each by 3)' do catalog = compile_to_catalog(<<-MANIFEST) 3.map |$x|{ $x*3}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_0]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present') end it 'map on a string' do catalog = compile_to_catalog(<<-MANIFEST) $a = {a=>x, b=>y} "ab".map |$x|{$a[$x]}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_x]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_y]").with_parameter(:ensure, 'present') end it 'map on an array (multiplying value by 10 in even index position)' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $a.map |$i, $x|{ if $i % 2 == 0 {$x} else {$x*10}}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_20]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') end it 'map on a hash selecting keys' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>1,'b'=>2,'c'=>3} $a.map |$x|{ $x[0]}.each |$k|{ file { "/file_$k": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_a]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_b]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_c]").with_parameter(:ensure, 'present') end it 'map on a hash selecting keys - using two block parameters' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>1,'b'=>2,'c'=>3} $a.map |$k,$v|{ file { "/file_$k": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_a]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_b]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_c]").with_parameter(:ensure, 'present') end it 'map on a hash using captures-last parameter' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>present,'b'=>absent,'c'=>present} $a.map |*$kv|{ file { "/file_${kv[0]}": ensure => $kv[1] } } MANIFEST expect(catalog).to have_resource("File[/file_a]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_b]").with_parameter(:ensure, 'absent') expect(catalog).to have_resource("File[/file_c]").with_parameter(:ensure, 'present') end it 'each on a hash selecting value' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>1,'b'=>2,'c'=>3} $a.map |$x|{ $x[1]}.each |$k|{ file { "/file_$k": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') end it 'each on a hash selecting value - using two block parameters' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'a'=>1,'b'=>2,'c'=>3} $a.map |$k,$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') end context "handles data type corner cases" do it "map gets values that are false" do catalog = compile_to_catalog(<<-MANIFEST) $a = [false,false] $a.map |$x| { $x }.each |$i, $v| { file { "/file_$i.$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_0.false]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_1.false]").with_parameter(:ensure, 'present') end it "map gets values that are nil" do Puppet::Parser::Functions.newfunction(:nil_array, :type => :rvalue) do |args| [nil] end catalog = compile_to_catalog(<<-MANIFEST) $a = nil_array() $a.map |$x| { $x }.each |$i, $v| { file { "/file_$i.$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_0.]").with_parameter(:ensure, 'present') end end it_should_behave_like 'all iterative functions argument checks', 'map' it_should_behave_like 'all iterative functions hash handling', 'map' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/find_file_spec.rb
spec/unit/functions/find_file_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'puppet_spec/files' describe 'the find_file 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_file('#{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_file('#{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_file(['#{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(:file).with('myfile').and_return(name) Puppet[:code] = "notify { find_file('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(:file).with('myfile').and_return(nil) Puppet[:code] = "notify { String(type(find_file('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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/sort_spec.rb
spec/unit/functions/sort_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the sort function' do include PuppetSpec::Compiler include Matchers::Resource { "'bac'" => "'abc'", "'BaC'" => "'BCa'", }.each_pair do |value, expected| it "sorts characters in a string such that #{value}.sort results in #{expected}" do expect(compile_to_catalog("notify { String( sort(#{value}) == #{expected}): }")).to have_resource("Notify[true]") end end { "'bac'" => "'abc'", "'BaC'" => "'aBC'", }.each_pair do |value, expected| it "accepts a lambda when sorting characters in a string such that #{value} results in #{expected}" do expect(compile_to_catalog("notify { String( sort(#{value}) |$a,$b| { compare($a,$b) } == #{expected}): }")).to have_resource("Notify[true]") end end { ['b', 'a', 'c'] => ['a', 'b', 'c'], ['B', 'a', 'C'] => ['B', 'C', 'a'], }.each_pair do |value, expected| it "sorts strings in an array such that #{value}.sort results in #{expected}" do expect(compile_to_catalog("notify { String( sort(#{value}) == #{expected}): }")).to have_resource("Notify[true]") end end { ['b', 'a', 'c'] => ['a', 'b', 'c'], ['B', 'a', 'C'] => ['a', 'B', 'C'], }.each_pair do |value, expected| it "accepts a lambda when sorting an array such that #{value} results in #{expected}" do expect(compile_to_catalog("notify { String( sort(#{value}) |$a,$b| { compare($a,$b) } == #{expected}): }")).to have_resource("Notify[true]") end end it 'errors if given a mix of data types' do expect { compile_to_catalog("sort([1, 'a'])")}.to raise_error(/comparison .* failed/) end it 'returns empty string for empty string input' do expect(compile_to_catalog("notify { String(sort('') == ''): }")).to have_resource("Notify[true]") end it 'returns empty string for empty string input' do expect(compile_to_catalog("notify { String(sort([]) == []): }")).to have_resource("Notify[true]") end it 'can sort mixed data types when using a lambda' do # source sorts Numeric before string and uses compare() for same data type src = <<-SRC notify{ String(sort(['b', 3, 'a', 2]) |$a, $b| { case [$a, $b] { [String, Numeric] : { 1 } [Numeric, String] : { -1 } default: { compare($a, $b) } } } == [2, 3,'a', 'b']): } SRC expect(compile_to_catalog(src)).to have_resource("Notify[true]") end it 'errors if lambda does not accept 2 arguments' do expect { compile_to_catalog("sort([1, 'a']) || { }")}.to raise_error(/block expects 2 arguments/) expect { compile_to_catalog("sort([1, 'a']) |$x| { }")}.to raise_error(/block expects 2 arguments/) expect { compile_to_catalog("sort([1, 'a']) |$x,$y, $z| { }")}.to raise_error(/block expects 2 arguments/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/reverse_each_spec.rb
spec/unit/functions/reverse_each_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'shared_behaviours/iterative_functions' describe 'the reverse_each function' do include PuppetSpec::Compiler it 'raises an error when given a type that cannot be iterated' do expect do compile_to_catalog(<<-MANIFEST) 3.14.reverse_each |$v| { } MANIFEST end.to raise_error(Puppet::Error, /expects an Iterable value, got Float/) end it 'raises an error when called with more than one argument and without a block' do expect do compile_to_catalog(<<-MANIFEST) [1].reverse_each(1) MANIFEST end.to raise_error(Puppet::Error, /expects 1 argument, got 2/) end it 'raises an error when called with more than one argument and a block' do expect do compile_to_catalog(<<-MANIFEST) [1].reverse_each(1) |$v| { } MANIFEST end.to raise_error(Puppet::Error, /expects 1 argument, got 2/) end it 'raises an error when called with a block with too many required parameters' do expect do compile_to_catalog(<<-MANIFEST) [1].reverse_each() |$v1, $v2| { } MANIFEST end.to raise_error(Puppet::Error, /block expects 1 argument, got 2/) end it 'raises an error when called with a block with too few parameters' do expect do compile_to_catalog(<<-MANIFEST) [1].reverse_each() | | { } MANIFEST end.to raise_error(Puppet::Error, /block expects 1 argument, got none/) end it 'does not raise an error when called with a block with too many but optional arguments' do expect do compile_to_catalog(<<-MANIFEST) [1].reverse_each() |$v1, $v2=extra| { } MANIFEST end.to_not raise_error end it 'returns an Undef when called with a block' do expect do compile_to_catalog(<<-MANIFEST) assert_type(Undef, [1].reverse_each |$x| { $x }) MANIFEST end.not_to raise_error end it 'returns an Iterable when called without a block' do expect do compile_to_catalog(<<-MANIFEST) assert_type(Iterable, [1].reverse_each) MANIFEST end.not_to raise_error end it 'should produce "times" interval of integer in reverse' do expect(eval_and_collect_notices('5.reverse_each |$x| { notice($x) }')).to eq(['4', '3', '2', '1', '0']) end it 'should produce range Integer[5,8] in reverse' do expect(eval_and_collect_notices('Integer[5,8].reverse_each |$x| { notice($x) }')).to eq(['8', '7', '6', '5']) end it 'should produce the choices of [first,second,third] in reverse' do expect(eval_and_collect_notices('[first,second,third].reverse_each |$x| { notice($x) }')).to eq(%w(third second first)) end it 'should produce the choices of {first => 1,second => 2,third => 3} in reverse' do expect(eval_and_collect_notices('{first => 1,second => 2,third => 3}.reverse_each |$t| { notice($t[0]) }')).to eq(%w(third second first)) end it 'should produce the choices of Enum[first,second,third] in reverse' do expect(eval_and_collect_notices('Enum[first,second,third].reverse_each |$x| { notice($x) }')).to eq(%w(third second first)) end it 'should produce nth element in reverse of range Integer[5,20] when chained after a step' do expect(eval_and_collect_notices('Integer[5,20].step(4).reverse_each |$x| { notice($x) }') ).to eq(['17', '13', '9', '5']) end it 'should produce nth element in reverse of times 5 when chained after a step' do expect(eval_and_collect_notices('5.step(2).reverse_each |$x| { notice($x) }')).to eq(['4', '2', '0']) end it 'should produce nth element in reverse of range Integer[5,20] when chained after a step' do expect(eval_and_collect_notices( '[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20].step(4).reverse_each |$x| { notice($x) }') ).to eq(['17', '13', '9', '5']) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/scanf_spec.rb
spec/unit/functions/scanf_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the scanf function' do include PuppetSpec::Compiler include Matchers::Resource it 'scans a value and returns an array' do expect(compile_to_catalog("$x = '42'.scanf('%i')[0] + 1; notify { \"test$x\": }")).to have_resource('Notify[test43]') end it 'scans a value and returns result of a code block' do expect(compile_to_catalog("$x = '42'.scanf('%i')|$x|{$x[0]} + 1; notify { \"test$x\": }")).to have_resource('Notify[test43]') end it 'returns empty array if nothing was scanned' do expect(compile_to_catalog("$x = 'no'.scanf('%i')[0]; notify { \"test${x}test\": }")).to have_resource('Notify[testtest]') end it 'produces result up to first unsuccessful scan' do expect(compile_to_catalog("$x = '42 no'.scanf('%i'); notify { \"test${x[0]}${x[1]}test\": }")).to have_resource('Notify[test42test]') end it 'errors when not given enough arguments' do expect do compile_to_catalog("'42'.scanf()") end.to raise_error(/'scanf' expects 2 arguments, got 1/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/rstrip_spec.rb
spec/unit/functions/rstrip_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the rstrip function' do include PuppetSpec::Compiler include Matchers::Resource it 'removes trailing whitepsace' do expect(compile_to_catalog("notify { String(\" abc\t\n \".rstrip == ' abc'): }")).to have_resource('Notify[true]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.rstrip == 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 '].rstrip == [' 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.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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/group_by_spec.rb
spec/unit/functions/group_by_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the group_by function' do include PuppetSpec::Compiler include Matchers::Resource context 'for an array' do it 'groups by item' do manifest = "notify { String(group_by([a, b, ab]) |$s| { $s.length }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[{1 => ['a', 'b'], 2 => ['ab']}]") end it 'groups by index, item' do manifest = "notify { String(group_by([a, b, ab]) |$i, $s| { $i%2 + $s.length }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[{1 => ['a'], 2 => ['b', 'ab']}]") end end context 'for a hash' do it 'groups by key-value pair' do manifest = "notify { String(group_by(a => [1, 2], b => [1]) |$kv| { $kv[1].length }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[{2 => [['a', [1, 2]]], 1 => [['b', [1]]]}]") end it 'groups by key, value' do manifest = "notify { String(group_by(a => [1, 2], b => [1]) |$k, $v| { $v.length }): }" expect(compile_to_catalog(manifest)).to have_resource("Notify[{2 => [['a', [1, 2]]], 1 => [['b', [1]]]}]") end end context 'for a string' do it 'fails' do manifest = "notify { String(group_by('something') |$s| { $s.length }): }" expect { compile_to_catalog(manifest) }.to raise_error(Puppet::PreformattedError) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/chop_spec.rb
spec/unit/functions/chop_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the chop function' do include PuppetSpec::Compiler include Matchers::Resource it 'removes last character in a string' do expect(compile_to_catalog("notify { String('abc'.chop == 'ab'): }")).to have_resource('Notify[true]') end it 'returns empty string for an empty string' do expect(compile_to_catalog("notify { String(''.chop == ''): }")).to have_resource('Notify[true]') end it 'removes both CR LF if both are the last characters in a string' do expect(compile_to_catalog("notify { String(\"abc\r\n\".chop == 'abc'): }")).to have_resource('Notify[true]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.chop == 42): }")).to have_resource('Notify[true]') end it 'returns chopped version of each entry in an array' do expect(compile_to_catalog("notify { String(['aa', 'ba', 'ca'].chop == ['a', 'b', 'c']): }")).to have_resource('Notify[true]') end it 'returns chopped version of each entry in an Iterator' do expect(compile_to_catalog("notify { String(['aa', 'bb', 'cc'].reverse_each.chop == ['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']].chop")}.to raise_error(/'chop' parameter 'arg' expects a value of type Numeric, String, or Iterable/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/assert_type_spec.rb
spec/unit/functions/assert_type_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/loaders' require 'puppet_spec/compiler' describe 'the assert_type function' do include PuppetSpec::Compiler after(:all) { Puppet::Pops::Loaders.clear } let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) } let(:func) { loaders.puppet_system_loader.load(:function, 'assert_type') } it 'asserts compliant type by returning the value' do expect(func.call({}, type(String), 'hello world')).to eql('hello world') end it 'accepts type given as a String' do expect(func.call({}, 'String', 'hello world')).to eql('hello world') end it 'asserts non compliant type by raising an error' do expect do func.call({}, type(Integer), 'hello world') end.to raise_error(Puppet::Pops::Types::TypeAssertionError, /expects an Integer value, got String/) end it 'checks that first argument is a type' do expect do func.call({}, 10, 10) end.to raise_error(ArgumentError, "The function 'assert_type' was called with arguments it does not accept. It expects one of: (Type type, Any value, Callable[Type, Type] block?) rejected: parameter 'type' expects a Type value, got Integer (String type_string, Any value, Callable[Type, Type] block?) rejected: parameter 'type_string' expects a String value, got Integer") end it 'allows the second arg to be undef/nil)' do expect do func.call({}, optional(String), nil) end.to_not raise_error end it 'can be called with a callable that receives a specific type' do expected, actual, actual2 = func.call({}, 'Optional[String]', 1) { |expctd, actul| [expctd, actul, actul] } expect(expected.to_s).to eql('Optional[String]') expect(actual.to_s).to eql('Integer[1, 1]') expect(actual2.to_s).to eql('Integer[1, 1]') end def optional(type_ref) Puppet::Pops::Types::TypeFactory.optional(type(type_ref)) end def type(type_ref) Puppet::Pops::Types::TypeFactory.type_of(type_ref) end it 'can validate a resource type' do expect(eval_and_collect_notices("assert_type(Type[Resource], File['/tmp/test']) notice('ok')")).to eq(['ok']) end it 'can validate a type alias' do code = <<-CODE type UnprivilegedPort = Integer[1024,65537] assert_type(UnprivilegedPort, 5432) notice('ok') CODE expect(eval_and_collect_notices(code)).to eq(['ok']) end it 'can validate a type alias passed as a String' do code = <<-CODE type UnprivilegedPort = Integer[1024,65537] assert_type('UnprivilegedPort', 5432) notice('ok') CODE expect(eval_and_collect_notices(code)).to eq(['ok']) end it 'can validate and fail using a type alias' do code = <<-CODE type UnprivilegedPort = Integer[1024,65537] assert_type(UnprivilegedPort, 345) notice('ok') CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects an UnprivilegedPort = Integer\[1024, 65537\] value, got Integer\[345, 345\]/) end it 'will use infer_set to report detailed information about complex mismatches' do code = <<-CODE assert_type(Struct[{a=>Integer,b=>Boolean}], {a=>hej,x=>s}) CODE expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /entry 'a' expects an Integer value, got String.*expects a value for key 'b'.*unrecognized key 'x'/m) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/defined_spec.rb
spec/unit/functions/defined_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/loaders' describe "the 'defined' function" do after(:all) { Puppet::Pops::Loaders.clear } # This loads the function once and makes it easy to call it # It does not matter that it is not bound to the env used later since the function # looks up everything via the scope that is given to it. # The individual tests needs to have a fresh env/catalog set up # let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) } let(:func) { loaders.puppet_system_loader.load(:function, 'defined') } before :each do # A fresh environment is needed for each test since tests creates types and resources 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) @scope = Puppet::Parser::Scope.new(@compiler) 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 newresource(type, title) resource = Puppet::Resource.new(type, title) @compiler.add_resource(@scope, resource) resource end #--- CLASS # context 'can determine if a class' do context 'is defined' do it 'by using the class name in string form' do newclass 'yayness' expect(func.call(@scope, 'yayness')).to be_truthy end it 'by using a Type[Class[name]] type reference' do name = 'yayness' newclass name class_type = Puppet::Pops::Types::TypeFactory.host_class(name) type_type = Puppet::Pops::Types::TypeFactory.type_type(class_type) expect(func.call(@scope, type_type)).to be_truthy end end context 'is not defined' do it 'by using the class name in string form' do expect(func.call(@scope, 'yayness')).to be_falsey end it 'even if there is a define, by using a Type[Class[name]] type reference' do name = 'yayness' newdefine name class_type = Puppet::Pops::Types::TypeFactory.host_class(name) type_type = Puppet::Pops::Types::TypeFactory.type_type(class_type) expect(func.call(@scope, type_type)).to be_falsey end end context 'is defined and realized' do it 'by using a Class[name] reference' do name = 'cowabunga' newclass name newresource(:class, name) class_type = Puppet::Pops::Types::TypeFactory.host_class(name) expect(func.call(@scope, class_type)).to be_truthy end end context 'is not realized' do it '(although defined) by using a Class[name] reference' do name = 'cowabunga' newclass name class_type = Puppet::Pops::Types::TypeFactory.host_class(name) expect(func.call(@scope, class_type)).to be_falsey end it '(and not defined) by using a Class[name] reference' do name = 'cowabunga' class_type = Puppet::Pops::Types::TypeFactory.host_class(name) expect(func.call(@scope, class_type)).to be_falsey end end end #---RESOURCE TYPE # context 'can determine if a resource type' do context 'is defined' do it 'by using the type name (of a built in type) in string form' do expect(func.call(@scope, 'file')).to be_truthy end it 'by using the type name (of a resource type) in string form' do newdefine 'yayness' expect(func.call(@scope, 'yayness')).to be_truthy end it 'by using a File type reference (built in type)' do resource_type = Puppet::Pops::Types::TypeFactory.resource('file') type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type) expect(func.call(@scope, type_type)).to be_truthy end it 'by using a Type[File] type reference' do resource_type = Puppet::Pops::Types::TypeFactory.resource('file') type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type) expect(func.call(@scope, type_type)).to be_truthy end it 'by using a Resource[T] type reference (defined type)' do name = 'yayness' newdefine name resource_type = Puppet::Pops::Types::TypeFactory.resource(name) expect(func.call(@scope, resource_type)).to be_truthy end it 'by using a Type[Resource[T]] type reference (defined type)' do name = 'yayness' newdefine name resource_type = Puppet::Pops::Types::TypeFactory.resource(name) type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type) expect(func.call(@scope, type_type)).to be_truthy end end context 'is not defined' do it 'by using the resource name in string form' do expect(func.call(@scope, 'notatype')).to be_falsey end it 'even if there is a class with the same name, by using a Type[Resource[T]] type reference' do name = 'yayness' newclass name resource_type = Puppet::Pops::Types::TypeFactory.resource(name) type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type) expect(func.call(@scope, type_type)).to be_falsey end end context 'is defined and instance realized' do it 'by using a Resource[T, title] reference for a built in type' do type_name = 'file' title = '/tmp/myfile' newdefine type_name newresource(type_name, title) class_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title) expect(func.call(@scope, class_type)).to be_truthy end it 'by using a Resource[T, title] reference for a defined type' do type_name = 'meme' title = 'cowabunga' newdefine type_name newresource(type_name, title) class_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title) expect(func.call(@scope, class_type)).to be_truthy end end context 'is not realized' do it '(although defined) by using a Resource[T, title] reference or Type[Resource[T, title]] reference' do type_name = 'meme' title = 'cowabunga' newdefine type_name resource_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title) expect(func.call(@scope, resource_type)).to be_falsey type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type) expect(func.call(@scope, type_type)).to be_falsey end it '(and not defined) by using a Resource[T, title] reference or Type[Resource[T, title]] reference' do type_name = 'meme' title = 'cowabunga' resource_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title) expect(func.call(@scope, resource_type)).to be_falsey type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type) expect(func.call(@scope, type_type)).to be_falsey end end end #---VARIABLES # context 'can determine if a variable' do context 'is defined' do it 'by giving the variable in string form' do @scope['x'] = 'something' expect(func.call(@scope, '$x')).to be_truthy end it 'by giving a :: prefixed variable in string form' do @compiler.topscope['x'] = 'something' expect(func.call(@scope, '$::x')).to be_truthy end it 'by giving a numeric variable in string form (when there is a match scope)' do # with no match scope, there are no numeric variables defined expect(func.call(@scope, '$0')).to be_falsey expect(func.call(@scope, '$42')).to be_falsey pattern = Regexp.new('.*') @scope.new_match_scope(pattern.match('anything')) # with a match scope, all numeric variables are set (the match defines if they have a value or not, but they are defined) # even if their value is undef. expect(func.call(@scope, '$0')).to be_truthy expect(func.call(@scope, '$42')).to be_truthy end end context 'is undefined' do it 'by giving a :: prefixed or regular variable in string form' do expect(func.call(@scope, '$x')).to be_falsey expect(func.call(@scope, '$::x')).to be_falsey end end end context 'has any? semantics when given multiple arguments' do it 'and one of the names is a defined user defined type' do newdefine 'yayness' expect(func.call(@scope, 'meh', 'yayness', 'booness')).to be_truthy end it 'and one of the names is a built type' do expect(func.call(@scope, 'meh', 'file', 'booness')).to be_truthy end it 'and one of the names is a defined class' do newclass 'yayness' expect(func.call(@scope, 'meh', 'yayness', 'booness')).to be_truthy end it 'is true when at least one variable exists in scope' do @scope['x'] = 'something' expect(func.call(@scope, '$y', '$x', '$z')).to be_truthy end it 'is false when none of the names are defined' do expect(func.call(@scope, 'meh', 'yayness', 'booness')).to be_falsey end end it 'raises an argument error when asking if Resource type is defined' do resource_type = Puppet::Pops::Types::TypeFactory.resource expect { func.call(@scope, resource_type)}.to raise_error(ArgumentError, /reference to all.*type/) end it 'raises an argument error if you ask if Class is defined' do class_type = Puppet::Pops::Types::TypeFactory.host_class expect { func.call(@scope, class_type) }.to raise_error(ArgumentError, /reference to all.*class/) end it 'raises error if referencing undef' do expect{func.call(@scope, nil)}.to raise_error(ArgumentError, /'defined' parameter 'vals' expects a value of type String, Type\[CatalogEntry\], or Type\[Type\], got Undef/) end it 'raises error if referencing a number' do expect{func.call(@scope, 42)}.to raise_error(ArgumentError, /'defined' parameter 'vals' expects a value of type String, Type\[CatalogEntry\], or Type\[Type\], got Integer/) end it 'is false if referencing empty string' do expect(func.call(@scope, '')).to be_falsey end it "is true if referencing 'main'" do # mimic what compiler does with "main" in intial import newclass '' newresource :class, '' expect(func.call(@scope, 'main')).to be_truthy end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/filter_spec.rb
spec/unit/functions/filter_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'shared_behaviours/iterative_functions' describe 'the filter method' do include PuppetSpec::Compiler include Matchers::Resource it 'should filter on an array (all berries)' do catalog = compile_to_catalog(<<-MANIFEST) $a = ['strawberry','blueberry','orange'] $a.filter |$x|{ $x =~ /berry$/}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_blueberry]").with_parameter(:ensure, 'present') end it 'should filter on enumerable type (Integer)' do catalog = compile_to_catalog(<<-MANIFEST) $a = Integer[1,10] $a.filter |$x|{ $x % 3 == 0}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_9]").with_parameter(:ensure, 'present') end it 'should filter on enumerable type (Integer) using two args index/value' do catalog = compile_to_catalog(<<-MANIFEST) $a = Integer[10,18] $a.filter |$i, $x|{ $i % 3 == 0}.each |$v|{ file { "/file_$v": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_10]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_13]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_16]").with_parameter(:ensure, 'present') end it 'should produce an array when acting on an array' do catalog = compile_to_catalog(<<-MANIFEST) $a = ['strawberry','blueberry','orange'] $b = $a.filter |$x|{ $x =~ /berry$/} file { "/file_${b[0]}": ensure => present } file { "/file_${b[1]}": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_blueberry]").with_parameter(:ensure, 'present') end it 'can filter array using index and value' do catalog = compile_to_catalog(<<-MANIFEST) $a = ['strawberry','blueberry','orange'] $b = $a.filter |$index, $x|{ $index == 0 or $index ==2} file { "/file_${b[0]}": ensure => present } file { "/file_${b[1]}": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_orange]").with_parameter(:ensure, 'present') end it 'can filter array using index and value (using captures-rest)' do catalog = compile_to_catalog(<<-MANIFEST) $a = ['strawberry','blueberry','orange'] $b = $a.filter |*$ix|{ $ix[0] == 0 or $ix[0] ==2} file { "/file_${b[0]}": ensure => present } file { "/file_${b[1]}": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_orange]").with_parameter(:ensure, 'present') end it 'filters on a hash (all berries) by key' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'strawberry'=>'red','blueberry'=>'blue','orange'=>'orange'} $a.filter |$x|{ $x[0] =~ /berry$/}.each |$v|{ file { "/file_${v[0]}": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_blueberry]").with_parameter(:ensure, 'present') end it 'should produce a hash when acting on a hash' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'strawberry'=>'red','blueberry'=>'blue','orange'=>'orange'} $b = $a.filter |$x|{ $x[0] =~ /berry$/} file { "/file_${b['strawberry']}": ensure => present } file { "/file_${b['blueberry']}": ensure => present } file { "/file_${b['orange']}": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_red]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_blue]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_]").with_parameter(:ensure, 'present') end it 'filters on a hash (all berries) by value' do catalog = compile_to_catalog(<<-MANIFEST) $a = {'strawb'=>'red berry','blueb'=>'blue berry','orange'=>'orange fruit'} $a.filter |$x|{ $x[1] =~ /berry$/}.each |$v|{ file { "/file_${v[0]}": ensure => present } } MANIFEST expect(catalog).to have_resource("File[/file_strawb]").with_parameter(:ensure, 'present') expect(catalog).to have_resource("File[/file_blueb]").with_parameter(:ensure, 'present') end it 'filters on an array will include elements for which the block returns truthy' do catalog = compile_to_catalog(<<-MANIFEST) $r = [1, 2, false, undef].filter |$v| { $v } == [1, 2] notify { "eval_${$r}": } MANIFEST expect(catalog).to have_resource('Notify[eval_true]') end it 'filters on a hash will not include elements for which the block returns truthy' do catalog = compile_to_catalog(<<-MANIFEST) $r = {a => 1, b => 2, c => false, d=> undef}.filter |$k, $v| { $v } == {a => 1, b => 2} notify { "eval_${$r}": } MANIFEST expect(catalog).to have_resource('Notify[eval_true]') end it_should_behave_like 'all iterative functions argument checks', 'filter' it_should_behave_like 'all iterative functions hash handling', 'filter' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/reduce_spec.rb
spec/unit/functions/reduce_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'shared_behaviours/iterative_functions' describe 'the reduce method' 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 as" do it 'reduce on an array' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $b = $a.reduce |$memo, $x| { $memo + $x } file { "/file_$b": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present') end it 'reduce on an array with captures rest in lambda' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $b = $a.reduce |*$mx| { $mx[0] + $mx[1] } file { "/file_$b": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present') end it 'reduce on enumerable type' do catalog = compile_to_catalog(<<-MANIFEST) $a = Integer[1,3] $b = $a.reduce |$memo, $x| { $memo + $x } file { "/file_$b": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present') end it 'reduce on an array with start value' do catalog = compile_to_catalog(<<-MANIFEST) $a = [1,2,3] $b = $a.reduce(4) |$memo, $x| { $memo + $x } file { "/file_$b": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_10]").with_parameter(:ensure, 'present') end it 'reduce on a hash' do catalog = compile_to_catalog(<<-MANIFEST) $a = {a=>1, b=>2, c=>3} $start = [ignored, 4] $b = $a.reduce |$memo, $x| {['sum', $memo[1] + $x[1]] } file { "/file_${$b[0]}_${$b[1]}": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_sum_6]").with_parameter(:ensure, 'present') end it 'reduce on a hash with start value' do catalog = compile_to_catalog(<<-MANIFEST) $a = {a=>1, b=>2, c=>3} $start = ['ignored', 4] $b = $a.reduce($start) |$memo, $x| { ['sum', $memo[1] + $x[1]] } file { "/file_${$b[0]}_${$b[1]}": ensure => present } MANIFEST expect(catalog).to have_resource("File[/file_sum_10]").with_parameter(:ensure, 'present') end end it_should_behave_like 'all iterative functions argument checks', 'reduce' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/empty_spec.rb
spec/unit/functions/empty_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the empty function' do include PuppetSpec::Compiler include Matchers::Resource let(:logs) { [] } let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } } context 'for an array it' do it 'returns true when empty' do expect(compile_to_catalog("notify { String(empty([])): }")).to have_resource('Notify[true]') end it 'returns false when not empty' do expect(compile_to_catalog("notify { String(empty([1])): }")).to have_resource('Notify[false]') end end context 'for a hash it' do it 'returns true when empty' do expect(compile_to_catalog("notify { String(empty({})): }")).to have_resource('Notify[true]') end it 'returns false when not empty' do expect(compile_to_catalog("notify { String(empty({1=>1})): }")).to have_resource('Notify[false]') end end context 'for numeric values it' do it 'always returns false for integer values (including 0)' do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String(empty(0)): }")).to have_resource('Notify[false]') end expect(warnings).to include(/Calling function empty\(\) with Numeric value is deprecated/) end it 'always returns false for float values (including 0.0)' do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String(empty(0.0)): }")).to have_resource('Notify[false]') end expect(warnings).to include(/Calling function empty\(\) with Numeric value is deprecated/) end end context 'for a string it' do it 'returns true when empty' do expect(compile_to_catalog("notify { String(empty('')): }")).to have_resource('Notify[true]') end it 'returns false when not empty' do expect(compile_to_catalog("notify { String(empty(' ')): }")).to have_resource('Notify[false]') end end context 'for a sensitive string it' do it 'returns true when empty' do expect(compile_to_catalog("notify { String(empty(Sensitive(''))): }")).to have_resource('Notify[true]') end it 'returns false when not empty' do expect(compile_to_catalog("notify { String(empty(Sensitive(' '))): }")).to have_resource('Notify[false]') end end context 'for a binary it' do it 'returns true when empty' do expect(compile_to_catalog("notify { String(empty(Binary(''))): }")).to have_resource('Notify[true]') end it 'returns false when not empty' do expect(compile_to_catalog("notify { String(empty(Binary('b25l'))): }")).to have_resource('Notify[false]') end end context 'for undef it' do it 'returns true without deprecation warning' do Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(compile_to_catalog("notify { String(empty(undef)): }")).to have_resource('Notify[true]') end expect(warnings).to_not include(/Calling function empty\(\) with Undef value is deprecated/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/split_spec.rb
spec/unit/functions/split_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/loaders' describe 'the split 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 split(*args) Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'split').call({}, *args) end let(:type_parser) { Puppet::Pops::Types::TypeParser.singleton } it 'should raise an Error if there is less than 2 arguments' do expect { split('a,b') }.to raise_error(/'split' expects 2 arguments, got 1/) end it 'should raise an Error if there is more than 2 arguments' do expect { split('a,b','foo', 'bar') }.to raise_error(/'split' expects 2 arguments, got 3/) end it 'should raise a RegexpError if the regexp is malformed' do expect { split('a,b',')') }.to raise_error(/unmatched close parenthesis/) end it 'should handle pattern in string form' do expect(split('a,b',',')).to eql(['a', 'b']) end it 'should handle pattern in Regexp form' do expect(split('a,b',/,/)).to eql(['a', 'b']) end it 'should handle pattern in Regexp Type form' do expect(split('a,b',type_parser.parse('Regexp[/,/]'))).to eql(['a', 'b']) end it 'should handle pattern in Regexp Type form with empty regular expression' do expect(split('ab',type_parser.parse('Regexp[//]'))).to eql(['a', 'b']) end it 'should handle pattern in Regexp Type form with missing regular expression' do expect(split('ab',type_parser.parse('Regexp'))).to eql(['a', 'b']) end it 'should handle sensitive String' do expect(split(Puppet::Pops::Types::PSensitiveType::Sensitive.new('a,b'), ',')).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) expect(split(Puppet::Pops::Types::PSensitiveType::Sensitive.new('a,b'), /,/)).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) expect(split(Puppet::Pops::Types::PSensitiveType::Sensitive.new('a,b'), type_parser.parse('Regexp[/,/]'))).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/values_spec.rb
spec/unit/functions/values_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the values function' do include PuppetSpec::Compiler include Matchers::Resource it 'returns the values in the hash in the order they appear in a hash iteration' do expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[1 & 2]') $k = {'apples' => 1, 'oranges' => 2}.values 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 = {}.values.reduce(0) |$m, $v| { $m+1 } notify { "${v}": } SRC end it 'includes an undef value if one is present in the hash' do expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[Undef]') $types = {a => undef}.values.map |$v| { $v.type } notify { "${types[0]}": } SRC end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions/upcase_spec.rb
spec/unit/functions/upcase_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'the upcase function' do include PuppetSpec::Compiler include Matchers::Resource it 'returns upper case version of a string' do expect(compile_to_catalog("notify { 'abc'.upcase: }")).to have_resource('Notify[ABC]') end it 'returns the value if Numeric' do expect(compile_to_catalog("notify { String(42.upcase == 42): }")).to have_resource('Notify[true]') end it 'performs upcase of international UTF-8 characters' do expect(compile_to_catalog("notify { 'åäö'.upcase: }")).to have_resource('Notify[ÅÄÖ]') end it 'returns upper case version of each entry in an array (recursively)' do expect(compile_to_catalog("notify { String(['a', ['b', ['c']]].upcase == ['A', ['B', ['C']]]): }")).to have_resource('Notify[true]') end it 'returns upper case version of keys and values in a hash (recursively)' do expect(compile_to_catalog("notify { String({'a'=>'b','c'=>{'d'=>'e'}}.upcase == {'A'=>'B', 'C'=>{'D'=>'E'}}): }")).to have_resource('Notify[true]') end it 'returns upper case version of keys and values in nested hash / array structure' do expect(compile_to_catalog("notify { String({'a'=>['b'],'c'=>[{'d'=>'e'}]}.upcase == {'A'=>['B'],'C'=>[{'D'=>'E'}]}): }")).to have_resource('Notify[true]') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 expect(compile_to_catalog("notify { join([1,2,{a => [3,4]}]): }")).to have_resource('Notify[12{"a"=>[3, 4]}]') 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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 context 'when using a Target of Type sensitive String' do it 'should process it' do result = regsubst(Puppet::Pops::Types::PSensitiveType::Sensitive.new('very secret'), 'very', 'top') expect(result).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) expect(result.unwrap).to eq("top secret") end end context 'when using a Target of Type Array with mixed String and sensitive String' do it 'should process it' do my_array = ['very down', Puppet::Pops::Types::PSensitiveType::Sensitive.new('very secret')] expect(regsubst(my_array, 'very', 'top')).to be_a(Array) expect(regsubst(my_array, 'very', 'top')[0]).to eq('top down') result = regsubst(my_array, 'very', 'top')[1] expect(result).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) expect(result.unwrap).to eq('top secret') end end context 'when using a Target of Type Sensitive Array with mixed String and sensitive String' do it 'should process it' do my_array = Puppet::Pops::Types::PSensitiveType::Sensitive.new(['very down', Puppet::Pops::Types::PSensitiveType::Sensitive.new('very secret')]) expect(regsubst(my_array, 'very', 'top')).to be_a(Array) expect(regsubst(my_array, 'very', 'top')[0]).to eq('top down') result = regsubst(my_array, 'very', 'top')[1] expect(result).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive) expect(result.unwrap).to eq('top secret') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 \(file: unknown, line: 3\) on node.*/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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=>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 eq(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=>2}\": {\n \"3\": 4\n }\n}" }.each_pair do |input, output| it "should render #{input.inspect}" do expect(console.render(input)).to eq(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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false