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/settings/path_setting_spec.rb
spec/unit/settings/path_setting_spec.rb
require 'spec_helper' describe Puppet::Settings::PathSetting do subject { described_class.new(:settings => double('settings'), :desc => "test") } context "#munge" do it "should expand all path elements" do munged = subject.munge("hello#{File::PATH_SEPARATOR}good/morning#{File::PATH_SEPARATOR}goodbye") munged.split(File::PATH_SEPARATOR).each do |p| expect(Puppet::Util).to be_absolute_path(p) end end it "should leave nil as nil" do expect(subject.munge(nil)).to be_nil end context "on Windows", :if => Puppet::Util::Platform.windows? do it "should convert \\ to /" do expect(subject.munge('C:\test\directory')).to eq('C:/test/directory') end it "should work with UNC paths" do expect(subject.munge('//localhost/some/path')).to eq('//localhost/some/path') expect(subject.munge('\\\\localhost\some\path')).to eq('//localhost/some/path') 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/settings/priority_setting_spec.rb
spec/unit/settings/priority_setting_spec.rb
require 'spec_helper' require 'puppet/settings' require 'puppet/settings/priority_setting' require 'puppet/util/platform' describe Puppet::Settings::PrioritySetting do let(:setting) { described_class.new(:settings => double('settings'), :desc => "test") } it "is of type :priority" do expect(setting.type).to eq(:priority) end describe "when munging the setting" do it "passes nil through" do expect(setting.munge(nil)).to be_nil end it "returns the same value if given an integer" do expect(setting.munge(5)).to eq(5) end it "returns an integer if given a decimal string" do expect(setting.munge('12')).to eq(12) end it "returns a negative integer if given a negative integer string" do expect(setting.munge('-5')).to eq(-5) end it "fails if given anything else" do [ 'foo', 'realtime', true, 8.3, [] ].each do |value| expect { setting.munge(value) }.to raise_error(Puppet::Settings::ValidationError) end end describe "on a Unix-like platform it", :unless => Puppet::Util::Platform.windows? do it "parses high, normal, low, and idle priorities" do { 'high' => -10, 'normal' => 0, 'low' => 10, 'idle' => 19 }.each do |value, converted_value| expect(setting.munge(value)).to eq(converted_value) end end end describe "on a Windows-like platform it", :if => Puppet::Util::Platform.windows? do it "parses high, normal, low, and idle priorities" do { 'high' => Puppet::FFI::Windows::Constants::HIGH_PRIORITY_CLASS, 'normal' => Puppet::FFI::Windows::Constants::NORMAL_PRIORITY_CLASS, 'low' => Puppet::FFI::Windows::Constants::BELOW_NORMAL_PRIORITY_CLASS, 'idle' => Puppet::FFI::Windows::Constants::IDLE_PRIORITY_CLASS }.each do |value, converted_value| expect(setting.munge(value)).to eq(converted_value) 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/settings/autosign_setting_spec.rb
spec/unit/settings/autosign_setting_spec.rb
require 'spec_helper' require 'puppet/settings' require 'puppet/settings/autosign_setting' describe Puppet::Settings::AutosignSetting do let(:settings) do s = double('settings') allow(s).to receive(:[]).with(:mkusers).and_return(true) allow(s).to receive(:[]).with(:user).and_return('puppet') allow(s).to receive(:[]).with(:group).and_return('puppet') allow(s).to receive(:[]).with(:manage_internal_file_permissions).and_return(true) s end let(:setting) { described_class.new(:name => 'autosign', :section => 'section', :settings => settings, :desc => "test") } it "is of type :file" do expect(setting.type).to eq :file end describe "when munging the setting" do it "passes boolean values through" do expect(setting.munge(true)).to eq true expect(setting.munge(false)).to eq false end it "converts nil to false" do expect(setting.munge(nil)).to eq false end it "munges string 'true' to boolean true" do expect(setting.munge('true')).to eq true end it "munges string 'false' to boolean false" do expect(setting.munge('false')).to eq false end it "passes absolute paths through" do path = File.expand_path('/path/to/autosign.conf') expect(setting.munge(path)).to eq path end it "fails if given anything else" do cases = [1.0, 'sometimes', 'relative/autosign.conf'] cases.each do |invalid| expect { setting.munge(invalid) }.to raise_error Puppet::Settings::ValidationError, /Invalid autosign value/ end end end describe "setting additional setting values" do it "can set the file mode" do setting.mode = '0664' expect(setting.mode).to eq '0664' end it "can set the file owner" do setting.owner = 'service' expect(setting.owner).to eq 'puppet' end it "can set the file group" do setting.group = 'service' expect(setting.group).to eq 'puppet' end end describe "converting the setting to a resource" do it "converts the file path to a file resource", :if => !Puppet::Util::Platform.windows? do path = File.expand_path('/path/to/autosign.conf') allow(settings).to receive(:value).with('autosign', nil, false).and_return(path) allow(Puppet::FileSystem).to receive(:exist?).and_call_original allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) expect(Puppet.features).to receive(:root?).and_return(true) setting.mode = '0664' setting.owner = 'service' setting.group = 'service' resource = setting.to_resource expect(resource.title).to eq path expect(resource[:ensure]).to eq :file expect(resource[:mode]).to eq '664' expect(resource[:owner]).to eq 'puppet' expect(resource[:group]).to eq 'puppet' end it "returns nil when the setting is a boolean" do allow(settings).to receive(:value).with('autosign', nil, false).and_return('true') setting.mode = '0664' setting.owner = 'service' setting.group = 'service' expect(setting.to_resource).to be_nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/settings/certificate_revocation_setting_spec.rb
spec/unit/settings/certificate_revocation_setting_spec.rb
require 'spec_helper' require 'puppet/settings' require 'puppet/settings/certificate_revocation_setting' describe Puppet::Settings::CertificateRevocationSetting do subject { described_class.new(:settings => double('settings'), :desc => "test") } it "is of type :certificate_revocation" do expect(subject.type).to eq :certificate_revocation end describe "munging the value" do ['true', true, 'chain'].each do |setting| it "munges #{setting.inspect} to :chain" do expect(subject.munge(setting)).to eq :chain end end it "munges 'leaf' to :leaf" do expect(subject.munge("leaf")).to eq :leaf end ['false', false, nil].each do |setting| it "munges #{setting.inspect} to false" do expect(subject.munge(setting)).to eq false end end it "raises an error when given an unexpected object type" do expect { subject.munge(1) }.to raise_error(Puppet::Settings::ValidationError, "Invalid certificate revocation value 1: must be one of 'true', 'chain', 'leaf', or 'false'") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/settings/value_translator_spec.rb
spec/unit/settings/value_translator_spec.rb
require 'spec_helper' require 'puppet/settings/value_translator' describe Puppet::Settings::ValueTranslator do let(:translator) { Puppet::Settings::ValueTranslator.new } context "booleans" do it "translates strings representing booleans to booleans" do expect(translator['true']).to eq(true) expect(translator['false']).to eq(false) end it "translates boolean values into themselves" do expect(translator[true]).to eq(true) expect(translator[false]).to eq(false) end it "leaves a boolean string with whitespace as a string" do expect(translator[' true']).to eq(" true") expect(translator['true ']).to eq("true") expect(translator[' false']).to eq(" false") expect(translator['false ']).to eq("false") end end context "numbers" do it "leaves integer strings" do expect(translator["1"]).to eq("1") end it "leaves octal numbers as strings" do expect(translator["011"]).to eq("011") end it "leaves hex numbers as strings" do expect(translator["0x11"]).to eq("0x11") end end context "arbitrary strings" do it "translates an empty string as the empty string" do expect(translator[""]).to eq("") end it "strips double quotes" do expect(translator['"a string"']).to eq('a string') end it "strips single quotes" do expect(translator["'a string'"]).to eq("a string") end it "does not strip preceding whitespace" do expect(translator[" \ta string"]).to eq(" \ta string") end it "strips trailing whitespace" do expect(translator["a string\t "]).to eq("a string") end it "leaves leading quote that is preceded by whitespace" do expect(translator[" 'a string'"]).to eq(" 'a string") end it "leaves trailing quote that is succeeded by whitespace" do expect(translator["'a string' "]).to eq("a string'") end it "leaves quotes that are not at the beginning or end of the string" do expect(translator["a st'\"ring"]).to eq("a st'\"ring") 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/settings/enum_setting_spec.rb
spec/unit/settings/enum_setting_spec.rb
require 'spec_helper' require 'puppet/settings' describe Puppet::Settings::EnumSetting do it "allows a configured value" do setting = enum_setting_allowing("allowed") expect(setting.munge("allowed")).to eq("allowed") end it "disallows a value that is not configured" do setting = enum_setting_allowing("allowed", "also allowed") expect do setting.munge("disallowed") end.to raise_error(Puppet::Settings::ValidationError, "Invalid value 'disallowed' for parameter testing. Allowed values are 'allowed', 'also allowed'") end def enum_setting_allowing(*values) Puppet::Settings::EnumSetting.new(:settings => double('settings'), :name => "testing", :desc => "description of testing", :values => values) 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/settings/duration_setting_spec.rb
spec/unit/settings/duration_setting_spec.rb
require 'spec_helper' require 'puppet/settings' require 'puppet/settings/duration_setting' describe Puppet::Settings::DurationSetting do subject { described_class.new(:settings => double('settings'), :desc => "test") } describe "when munging the setting" do it "should return the same value if given an integer" do expect(subject.munge(5)).to eq(5) end it "should return the same value if given nil" do expect(subject.munge(nil)).to be_nil end it "should return an integer if given a decimal string" do expect(subject.munge("12")).to eq(12) end it "should fail if given anything but a well-formed string, integer, or nil" do [ '', 'foo', '2 d', '2d ', true, Time.now, 8.3, [] ].each do |value| expect { subject.munge(value) }.to raise_error(Puppet::Settings::ValidationError) end end it "should parse strings with units of 'y', 'd', 'h', 'm', or 's'" do # Note: the year value won't jive with most methods of calculating # year due to the Julian calandar having 365.25 days in a year { '3y' => 94608000, '3d' => 259200, '3h' => 10800, '3m' => 180, '3s' => 3 }.each do |value, converted_value| # subject.munge(value).should == converted_value expect(subject.munge(value)).to eq(converted_value) end end # This is to support the `filetimeout` setting it "should allow negative values" do expect(subject.munge(-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/settings/array_setting_spec.rb
spec/unit/settings/array_setting_spec.rb
require 'spec_helper' require 'puppet/settings' require 'puppet/settings/array_setting' describe Puppet::Settings::ArraySetting do subject { described_class.new(:settings => double('settings'), :desc => "test") } it "is of type :array" do expect(subject.type).to eq :array end describe "munging the value" do describe "when given a string" do it "splits multiple values into an array" do expect(subject.munge("foo,bar")).to eq %w[foo bar] end it "strips whitespace between elements" do expect(subject.munge("foo , bar")).to eq %w[foo bar] end it "creates an array when one item is given" do expect(subject.munge("foo")).to eq %w[foo] end end describe "when given an array" do it "returns the array" do expect(subject.munge(%w[foo])).to eq %w[foo] end end it "raises an error when given an unexpected object type" do expect { subject.munge({:foo => 'bar'}) }.to raise_error(ArgumentError, "Expected an Array or String, got a Hash") 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/settings/environment_conf_spec.rb
spec/unit/settings/environment_conf_spec.rb
require 'spec_helper' require 'puppet/settings/environment_conf.rb' describe Puppet::Settings::EnvironmentConf do def setup_environment_conf(config, conf_hash) conf_hash.each do |setting,value| expect(config).to receive(:setting).with(setting).and_return( double('setting', :value => value) ) end end context "with config" do let(:config) { double('config') } let(:envconf) { Puppet::Settings::EnvironmentConf.new("/some/direnv", config, ["/global/modulepath"]) } it "reads a modulepath from config and does not include global_module_path" do setup_environment_conf(config, :modulepath => '/some/modulepath') expect(envconf.modulepath).to eq(File.expand_path('/some/modulepath')) end it "reads a manifest from config" do setup_environment_conf(config, :manifest => '/some/manifest') expect(envconf.manifest).to eq(File.expand_path('/some/manifest')) end it "reads a config_version from config" do setup_environment_conf(config, :config_version => '/some/version.sh') expect(envconf.config_version).to eq(File.expand_path('/some/version.sh')) end it "reads an environment_timeout from config" do setup_environment_conf(config, :environment_timeout => '3m') expect(envconf.environment_timeout).to eq(180) end it "reads a static_catalogs from config" do setup_environment_conf(config, :static_catalogs => true) expect(envconf.static_catalogs).to eq(true) end it "can retrieve untruthy settings" do Puppet[:static_catalogs] = true setup_environment_conf(config, :static_catalogs => false) expect(envconf.static_catalogs).to eq(false) end it "can retrieve raw settings" do setup_environment_conf(config, :manifest => 'manifest.pp') expect(envconf.raw_setting(:manifest)).to eq('manifest.pp') end end context "without config" do let(:envconf) { Puppet::Settings::EnvironmentConf.new("/some/direnv", nil, ["/global/modulepath"]) } it "returns a default modulepath when config has none, with global_module_path" do expect(envconf.modulepath).to eq( [File.expand_path('/some/direnv/modules'), File.expand_path('/global/modulepath')].join(File::PATH_SEPARATOR) ) end it "returns a default manifest when config has none" do expect(envconf.manifest).to eq(File.expand_path('/some/direnv/manifests')) end it "returns nothing for config_version when config has none" do expect(envconf.config_version).to be_nil end it "returns a default of 0 for environment_timeout when config has none" do expect(envconf.environment_timeout).to eq(0) end it "returns default of true for static_catalogs when config has none" do expect(envconf.static_catalogs).to eq(true) end it "can still retrieve raw setting" do expect(envconf.raw_setting(:manifest)).to be_nil end end describe "with disable_per_environment_manifest" do let(:config) { double('config') } let(:envconf) { Puppet::Settings::EnvironmentConf.new("/some/direnv", config, ["/global/modulepath"]) } context "set true" do before(:each) do Puppet[:default_manifest] = File.expand_path('/default/manifest') Puppet[:disable_per_environment_manifest] = true end it "ignores environment.conf manifest" do setup_environment_conf(config, :manifest => '/some/manifest.pp') expect(envconf.manifest).to eq(File.expand_path('/default/manifest')) end it "logs error when environment.conf has manifest set" do setup_environment_conf(config, :manifest => '/some/manifest.pp') envconf.manifest expect(@logs.first.to_s).to match(/disable_per_environment_manifest.*true.*environment.conf.*does not match the default_manifest/) end it "does not log an error when environment.conf does not have a manifest set" do setup_environment_conf(config, :manifest => nil) expect(envconf.manifest).to eq(File.expand_path('/default/manifest')) expect(@logs).to be_empty end end it "uses environment.conf when false" do setup_environment_conf(config, :manifest => '/some/manifest.pp') Puppet[:default_manifest] = File.expand_path('/default/manifest') Puppet[:disable_per_environment_manifest] = false expect(envconf.manifest).to eq(File.expand_path('/some/manifest.pp')) 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/settings/ini_file_spec.rb
spec/unit/settings/ini_file_spec.rb
require 'spec_helper' require 'stringio' require 'puppet/settings/ini_file' describe Puppet::Settings::IniFile 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 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142 let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ𠜎 it "preserves the file when no changes are made" do original_config = <<-CONFIG # comment [section] name = value CONFIG config_fh = a_config_file_containing(original_config) Puppet::Settings::IniFile.update(config_fh) do; end expect(config_fh.string).to eq original_config end it "adds a set name and value to an empty file" do config_fh = a_config_file_containing("") Puppet::Settings::IniFile.update(config_fh) do |config| config.set("the_section", "name", "value") end expect(config_fh.string).to eq "[the_section]\nname = value\n" end it "adds a UTF-8 name and value to an empty file" do config_fh = a_config_file_containing("") Puppet::Settings::IniFile.update(config_fh) do |config| config.set("the_section", mixed_utf8, mixed_utf8.reverse) end expect(config_fh.string).to eq "[the_section]\n#{mixed_utf8} = #{mixed_utf8.reverse}\n" end it "adds a [main] section to a file when it's needed" do config_fh = a_config_file_containing(<<-CONF) [section] name = different value CONF Puppet::Settings::IniFile.update(config_fh) do |config| config.set("main", "name", "value") end expect(config_fh.string).to eq(<<-CONF) [main] name = value [section] name = different value CONF end it "can update values within a UTF-8 section of an existing file" do config_fh = a_config_file_containing(<<-CONF) [#{mixed_utf8}] foo = default CONF Puppet::Settings::IniFile.update(config_fh) do |config| config.set(mixed_utf8, 'foo', 'bar') end expect(config_fh.string).to eq(<<-CONF) [#{mixed_utf8}] foo = bar CONF end it "preserves comments when writing a new name and value" do config_fh = a_config_file_containing("# this is a comment") Puppet::Settings::IniFile.update(config_fh) do |config| config.set("the_section", "name", "value") end expect(config_fh.string).to eq "# this is a comment\n[the_section]\nname = value\n" end it "updates existing names and values in place" do config_fh = a_config_file_containing(<<-CONFIG) # this is the preceding comment [section] name = original value # this is the trailing comment CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "name", "changed value") end expect(config_fh.string).to eq <<-CONFIG # this is the preceding comment [section] name = changed value # this is the trailing comment CONFIG end it "updates existing empty settings" do config_fh = a_config_file_containing(<<-CONFIG) # this is the preceding comment [section] name = # this is the trailing comment CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "name", "changed value") end expect(config_fh.string).to eq <<-CONFIG # this is the preceding comment [section] name = changed value # this is the trailing comment CONFIG end it "can set empty settings" do config_fh = a_config_file_containing(<<-CONFIG) # this is the preceding comment [section] name = original value # this is the trailing comment CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "name", "") end expect(config_fh.string).to eq <<-CONFIG # this is the preceding comment [section] name = # this is the trailing comment CONFIG end it "updates existing UTF-8 name / values in place" do config_fh = a_config_file_containing(<<-CONFIG) # this is the preceding comment [section] ascii = foo A\u06FF\u16A0\u{2070E} = bar # this is the trailing comment CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "ascii", mixed_utf8) config.set("section", mixed_utf8, mixed_utf8.reverse) end expect(config_fh.string).to eq <<-CONFIG # this is the preceding comment [section] ascii = #{mixed_utf8} #{mixed_utf8} = #{mixed_utf8.reverse} # this is the trailing comment CONFIG end it "updates only the value in the selected section" do config_fh = a_config_file_containing(<<-CONFIG) [other_section] name = does not change [section] name = original value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "name", "changed value") end expect(config_fh.string).to eq <<-CONFIG [other_section] name = does not change [section] name = changed value CONFIG end it "considers settings found outside a section to be in section 'main'" do config_fh = a_config_file_containing(<<-CONFIG) name = original value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("main", "name", "changed value") end expect(config_fh.string).to eq <<-CONFIG [main] name = changed value CONFIG end it "adds new settings to an existing section" do config_fh = a_config_file_containing(<<-CONFIG) [section] original = value # comment about 'other' section [other] dont = change CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "updated", "new") end expect(config_fh.string).to eq <<-CONFIG [section] original = value updated = new # comment about 'other' section [other] dont = change CONFIG end it "adds a new setting into an existing, yet empty section" do config_fh = a_config_file_containing(<<-CONFIG) [section] [other] dont = change CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "updated", "new") end expect(config_fh.string).to eq <<-CONFIG [section] updated = new [other] dont = change CONFIG end it "finds settings when the section is split up" do config_fh = a_config_file_containing(<<-CONFIG) [section] name = original value [different] name = other value [section] other_name = different original value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "name", "changed value") config.set("section", "other_name", "other changed value") end expect(config_fh.string).to eq <<-CONFIG [section] name = changed value [different] name = other value [section] other_name = other changed value CONFIG end it "adds a new setting to the appropriate section, when it would be added behind a setting with an identical value in a preceeding section" do config_fh = a_config_file_containing(<<-CONFIG) [different] name = some value [section] name = some value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.set("section", "new", "new value") end expect(config_fh.string).to eq <<-CONFIG [different] name = some value [section] name = some value new = new value CONFIG end context 'config with no main section' do it 'file does not change when there are no sections or entries' do config_fh = a_config_file_containing(<<-CONFIG) CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'missing') end expect(config_fh.string).to eq <<-CONFIG CONFIG end it 'when there is only 1 entry we can delete it' do config_fh = a_config_file_containing(<<-CONFIG) base = value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'base') end expect(config_fh.string).to eq <<-CONFIG CONFIG end it 'we delete 1 entry from the default section and add the [main] section header' do config_fh = a_config_file_containing(<<-CONFIG) base = value other = another value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] other = another value CONFIG end it 'we add [main] to the config file when attempting to delete a setting in another section' do config_fh = a_config_file_containing(<<-CONF) name = different value CONF Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('section', 'name') end expect(config_fh.string).to eq(<<-CONF) [main] name = different value CONF end end context 'config with 1 section' do it 'file does not change when entry to delete does not exist' do config_fh = a_config_file_containing(<<-CONFIG) [main] base = value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'missing') end expect(config_fh.string).to eq <<-CONFIG [main] base = value CONFIG end it 'deletes the 1 entry in the section' do config_fh = a_config_file_containing(<<-CONFIG) [main] base = DELETING CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] CONFIG end it 'deletes the entry and leaves another entry' do config_fh = a_config_file_containing(<<-CONFIG) [main] base = DELETING after = value to keep CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] after = value to keep CONFIG end it 'deletes the entry while leaving other entries' do config_fh = a_config_file_containing(<<-CONFIG) [main] before = value to keep before base = DELETING after = value to keep CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] before = value to keep before after = value to keep CONFIG end it 'when there are two entries of the same setting name delete one of them' do config_fh = a_config_file_containing(<<-CONFIG) [main] base = value base = value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('main', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] base = value CONFIG end end context 'with 2 sections' do it 'file does not change when entry to delete does not exist' do config_fh = a_config_file_containing(<<-CONFIG) [main] base = value [section] CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('section', 'missing') end expect(config_fh.string).to eq <<-CONFIG [main] base = value [section] CONFIG end it 'deletes the 1 entry in the specified section' do config_fh = a_config_file_containing(<<-CONFIG) [main] base = value [section] base = value CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('section', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] base = value [section] CONFIG end it 'deletes the entry while leaving other entries' do config_fh = a_config_file_containing(<<-CONFIG) [main] before = value also staying base = value staying after = value to keep [section] before value in section keeping base = DELETING after = value to keep CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('section', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] before = value also staying base = value staying after = value to keep [section] before value in section keeping after = value to keep CONFIG end end context 'with 2 sections' do it 'deletes the entry while leaving other entries' do config_fh = a_config_file_containing(<<-CONFIG) [main] before = value also staying base = value staying after = value to keep [section] before value in section keeping base = DELETING after = value to keep [otherSection] before value in section keeping base = value to keep really after = value to keep CONFIG Puppet::Settings::IniFile.update(config_fh) do |config| config.delete('section', 'base') end expect(config_fh.string).to eq <<-CONFIG [main] before = value also staying base = value staying after = value to keep [section] before value in section keeping after = value to keep [otherSection] before value in section keeping base = value to keep really after = value to keep CONFIG end end def a_config_file_containing(text) StringIO.new(text.encode(Encoding::UTF_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/settings/terminus_setting_spec.rb
spec/unit/settings/terminus_setting_spec.rb
require 'spec_helper' describe Puppet::Settings::TerminusSetting do let(:setting) { described_class.new(:settings => double('settings'), :desc => "test") } describe "#munge" do it "converts strings to symbols" do expect(setting.munge("string")).to eq(:string) end it "converts '' to nil" do expect(setting.munge('')).to be_nil end it "preserves symbols" do expect(setting.munge(:symbol)).to eq(:symbol) end it "preserves nil" do expect(setting.munge(nil)).to be_nil end it "does not allow unknown types through" do expect { setting.munge(["not a terminus type"]) }.to raise_error Puppet::Settings::ValidationError 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/settings/server_list_setting_spec.rb
spec/unit/settings/server_list_setting_spec.rb
require 'spec_helper' require 'puppet/settings/server_list_setting' describe Puppet::Settings::ServerListSetting do it "prints strings as strings" do settings = Puppet::Settings.new settings.define_settings(:main, neptune: {type: :server_list, desc: 'list of servers'}) server_list_setting = settings.setting(:neptune) expect(server_list_setting.print("jupiter,mars")).to eq("jupiter,mars") end it "prints arrays as strings" do settings = Puppet::Settings.new settings.define_settings(:main, neptune: {type: :server_list, desc: 'list of servers'}) server_list_setting = settings.setting(:neptune) expect(server_list_setting.print([["main", 1234],["production", 8140]])).to eq("main:1234,production:8140") expect(server_list_setting.print([])).to eq("") 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/forge/module_release_spec.rb
spec/unit/forge/module_release_spec.rb
# encoding: utf-8 require 'spec_helper' require 'puppet/forge' require 'net/http' require 'puppet/module_tool' require 'puppet_spec/files' describe Puppet::Forge::ModuleRelease do include PuppetSpec::Files let(:agent) { "Test/1.0" } let(:repository) { Puppet::Forge::Repository.new('http://fake.com', agent) } let(:ssl_repository) { Puppet::Forge::Repository.new('https://fake.com', agent) } let(:api_version) { "v3" } let(:module_author) { "puppetlabs" } let(:module_name) { "stdlib" } let(:module_version) { "4.1.0" } let(:module_full_name) { "#{module_author}-#{module_name}" } let(:module_full_name_versioned) { "#{module_full_name}-#{module_version}" } let(:module_md5) { "bbf919d7ee9d278d2facf39c25578bf8" } let(:module_sha256) { "b4c6f15cec64a9fe16ef0d291e2598fc84f381bc59f0e67198d61706fafedae4" } let(:uri) { " "} let(:release) { Puppet::Forge::ModuleRelease.new(ssl_repository, JSON.parse(release_json)) } let(:mock_file) { double('file', path: '/dev/null') } let(:mock_dir) { tmpdir('dir') } let(:destination) { tmpfile('forge_module_release') } shared_examples 'a module release' do def mock_digest_file_with_md5(md5) allow(Digest::MD5).to receive(:file).and_return(double(:hexdigest => md5)) end describe '#tmpfile' do it 'should be opened in binary mode' do allow(Puppet::Forge::Cache).to receive(:base_path).and_return(Dir.tmpdir) expect(release.send(:tmpfile).binmode?).to be_truthy end end describe '#download' do it 'should download a file' do stub_request(:get, "https://fake.com/#{api_version}/files/#{module_full_name_versioned}.tar.gz").to_return(status: 200, body: '{}') File.open(destination, 'wb') do |fh| release.send(:download, "/#{api_version}/files/#{module_full_name_versioned}.tar.gz", fh) end expect(File.read(destination)).to eq("{}") end it 'should raise a response error when it receives an error from forge' do stub_request(:get, "https://fake.com/some/path").to_return( status: [500, 'server error'], body: '{"error":"invalid module"}' ) expect { release.send(:download, "/some/path", StringIO.new) }.to raise_error Puppet::Forge::Errors::ResponseError end end describe '#unpack' do it 'should call unpacker with correct params' do expect(Puppet::ModuleTool::Applications::Unpacker).to receive(:unpack).with(mock_file.path, mock_dir).and_return(true) release.send(:unpack, mock_file, mock_dir) end end end context 'standard forge module' do let(:release_json) do %Q{ { "uri": "/#{api_version}/releases/#{module_full_name_versioned}", "module": { "uri": "/#{api_version}/modules/#{module_full_name}", "name": "#{module_name}", "owner": { "uri": "/#{api_version}/users/#{module_author}", "username": "#{module_author}", "gravatar_id": "fdd009b7c1ec96e088b389f773e87aec" } }, "version": "#{module_version}", "metadata": { "types": [ ], "license": "Apache 2.0", "checksums": { }, "version": "#{module_version}", "description": "Standard Library for Puppet Modules", "source": "https://github.com/puppetlabs/puppetlabs-stdlib", "project_page": "https://github.com/puppetlabs/puppetlabs-stdlib", "summary": "Puppet Module Standard Library", "dependencies": [ ], "author": "#{module_author}", "name": "#{module_full_name}" }, "tags": [ "puppetlabs", "library", "stdlib", "standard", "stages" ], "file_uri": "/#{api_version}/files/#{module_full_name_versioned}.tar.gz", "file_size": 67586, "file_md5": "#{module_md5}", "file_sha256": "#{module_sha256}", "downloads": 610751, "readme": "", "changelog": "", "license": "", "created_at": "2013-05-13 08:31:19 -0700", "updated_at": "2013-05-13 08:31:19 -0700", "deleted_at": null } } end it_behaves_like 'a module release' context 'when verifying checksums' do let(:json) { JSON.parse(release_json) } def mock_release(json) release = Puppet::Forge::ModuleRelease.new(ssl_repository, json) allow(release).to receive(:tmpfile).and_return(mock_file) allow(release).to receive(:tmpdir).and_return(mock_dir) allow(release).to receive(:download).with("/#{api_version}/files/#{module_full_name_versioned}.tar.gz", mock_file) allow(release).to receive(:unpack) release end it 'verifies using SHA256' do expect(Digest::SHA256).to receive(:file).and_return(double(:hexdigest => module_sha256)) release = mock_release(json) release.prepare end it 'rejects an invalid release with SHA256' do expect(Digest::SHA256).to receive(:file).and_return(double(:hexdigest => 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff')) release = mock_release(json) expect { release.prepare }.to raise_error(RuntimeError, /did not match expected checksum/) end context 'when `file_sha256` is missing' do before(:each) do json.delete('file_sha256') end it 'verifies using MD5 if `file_sha256` is missing' do expect(Digest::MD5).to receive(:file).and_return(double(:hexdigest => module_md5)) release = mock_release(json) release.prepare end it 'rejects an invalid release with MD5' do expect(Digest::MD5).to receive(:file).and_return(double(:hexdigest => 'ffffffffffffffffffffffffffffffff')) release = mock_release(json) expect { release.prepare }.to raise_error(RuntimeError, /did not match expected checksum/) end it 'raises if FIPS is enabled' do allow(Facter).to receive(:value).with(:fips_enabled).and_return(true) release = mock_release(json) expect { release.prepare }.to raise_error(/Module install using MD5 is prohibited in FIPS mode./) end end end end context 'forge module with no dependencies field' do let(:release_json) do %Q{ { "uri": "/#{api_version}/releases/#{module_full_name_versioned}", "module": { "uri": "/#{api_version}/modules/#{module_full_name}", "name": "#{module_name}", "owner": { "uri": "/#{api_version}/users/#{module_author}", "username": "#{module_author}", "gravatar_id": "fdd009b7c1ec96e088b389f773e87aec" } }, "version": "#{module_version}", "metadata": { "types": [ ], "license": "Apache 2.0", "checksums": { }, "version": "#{module_version}", "description": "Standard Library for Puppet Modules", "source": "https://github.com/puppetlabs/puppetlabs-stdlib", "project_page": "https://github.com/puppetlabs/puppetlabs-stdlib", "summary": "Puppet Module Standard Library", "author": "#{module_author}", "name": "#{module_full_name}" }, "tags": [ "puppetlabs", "library", "stdlib", "standard", "stages" ], "file_uri": "/#{api_version}/files/#{module_full_name_versioned}.tar.gz", "file_size": 67586, "file_md5": "#{module_md5}", "file_sha256": "#{module_sha256}", "downloads": 610751, "readme": "", "changelog": "", "license": "", "created_at": "2013-05-13 08:31:19 -0700", "updated_at": "2013-05-13 08:31:19 -0700", "deleted_at": null } } end it_behaves_like 'a module release' end context 'forge module with the minimal set of fields' do let(:release_json) do %Q{ { "uri": "/#{api_version}/releases/#{module_full_name_versioned}", "module": { "uri": "/#{api_version}/modules/#{module_full_name}", "name": "#{module_name}" }, "metadata": { "version": "#{module_version}", "name": "#{module_full_name}" }, "file_uri": "/#{api_version}/files/#{module_full_name_versioned}.tar.gz", "file_size": 67586, "file_md5": "#{module_md5}", "file_sha256": "#{module_sha256}" } } end it_behaves_like 'a module release' end context 'deprecated forge module' do let(:release_json) do %Q{ { "uri": "/#{api_version}/releases/#{module_full_name_versioned}", "module": { "uri": "/#{api_version}/modules/#{module_full_name}", "name": "#{module_name}", "deprecated_at": "2017-10-10 10:21:32 -0700", "owner": { "uri": "/#{api_version}/users/#{module_author}", "username": "#{module_author}", "gravatar_id": "fdd009b7c1ec96e088b389f773e87aec" } }, "version": "#{module_version}", "metadata": { "types": [ ], "license": "Apache 2.0", "checksums": { }, "version": "#{module_version}", "description": "Standard Library for Puppet Modules", "source": "https://github.com/puppetlabs/puppetlabs-stdlib", "project_page": "https://github.com/puppetlabs/puppetlabs-stdlib", "summary": "Puppet Module Standard Library", "dependencies": [ ], "author": "#{module_author}", "name": "#{module_full_name}" }, "tags": [ "puppetlabs", "library", "stdlib", "standard", "stages" ], "file_uri": "/#{api_version}/files/#{module_full_name_versioned}.tar.gz", "file_size": 67586, "file_md5": "#{module_md5}", "file_sha256": "#{module_sha256}", "downloads": 610751, "readme": "", "changelog": "", "license": "", "created_at": "2013-05-13 08:31:19 -0700", "updated_at": "2013-05-13 08:31:19 -0700", "deleted_at": null } } end it_behaves_like 'a module release' describe '#prepare' do before :each do allow(release).to receive(:tmpfile).and_return(mock_file) allow(release).to receive(:tmpdir).and_return(mock_dir) allow(release).to receive(:download) allow(release).to receive(:validate_checksum) allow(release).to receive(:unpack) end it 'should emit warning about module deprecation' do expect(Puppet).to receive(:warning).with(/#{Regexp.escape(module_full_name)}.*deprecated/i) release.prepare 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/forge/repository_spec.rb
spec/unit/forge/repository_spec.rb
# encoding: utf-8 require 'spec_helper' require 'net/http' require 'puppet/forge/repository' require 'puppet/forge/cache' require 'puppet/forge/errors' describe Puppet::Forge::Repository do before(:all) do # any local http proxy will break these tests ENV['http_proxy'] = nil ENV['HTTP_PROXY'] = nil end let(:agent) { "Test/1.0" } let(:repository) { Puppet::Forge::Repository.new('http://fake.com', agent) } it "retrieve accesses the cache" do path = '/module/foo.tar.gz' expect(repository.cache).to receive(:retrieve) repository.retrieve(path) end it "retrieve merges forge URI and path specified" do host = 'http://fake.com/test' path = '/module/foo.tar.gz' uri = [ host, path ].join('') repository = Puppet::Forge::Repository.new(host, agent) expect(repository.cache).to receive(:retrieve).with(uri) repository.retrieve(path) end describe "making a request" do let(:uri) { "http://fake.com/the_path" } it "returns the response object from the request" do stub_request(:get, uri) expect(repository.make_http_request("/the_path")).to be_a_kind_of(Puppet::HTTP::Response) end it "requires path to have a leading slash" do expect { repository.make_http_request("the_path") }.to raise_error(ArgumentError, 'Path must start with forward slash') end it "merges forge URI and path specified" do stub_request(:get, "http://fake.com/test/the_path/") repository = Puppet::Forge::Repository.new('http://fake.com/test', agent) repository.make_http_request("/the_path/") end it "handles trailing slashes when merging URI and path" do stub_request(:get, "http://fake.com/test/the_path") repository = Puppet::Forge::Repository.new('http://fake.com/test/', agent) repository.make_http_request("/the_path") end it 'return a valid exception when there is a communication problem' do stub_request(:get, uri).to_raise(SocketError.new('getaddrinfo: Name or service not known')) expect { repository.make_http_request("/the_path") }.to raise_error(Puppet::Forge::Errors::CommunicationError, %r{Unable to connect to the server at http://fake.com. Detail: Request to http://fake.com/the_path failed after .* seconds: getaddrinfo: Name or service not known.}) end it "sets the user agent for the request" do stub_request(:get, uri).with do |request| expect(request.headers['User-Agent']).to match(/#{agent} #{Regexp.escape(Puppet[:http_user_agent])}/) end repository.make_http_request("/the_path") end it "does not set Authorization header by default" do allow(Puppet.features).to receive(:pe_license?).and_return(false) Puppet[:forge_authorization] = nil stub_request(:get, uri).with do |request| expect(request.headers).to_not include('Authorization') end repository.make_http_request("/the_path") end it "sets Authorization header from config" do token = 'bearer some token' Puppet[:forge_authorization] = token stub_request(:get, uri).with(headers: {'Authorization' => token}) repository.make_http_request("/the_path") end it "sets Authorization header from PE license" do allow(Puppet.features).to receive(:pe_license?).and_return(true) stub_const("PELicense", double(load_license_key: double(authorization_token: "opensesame"))) stub_request(:get, uri).with(headers: {'Authorization' => "opensesame"}) repository.make_http_request("/the_path") end it "sets basic authentication if there isn't forge authorization or PE license" do stub_request(:get, uri).with(basic_auth: ['user1', 'password']) repository = Puppet::Forge::Repository.new('http://user1:password@fake.com', agent) repository.make_http_request("/the_path") end it "omits basic authentication if there is a forge authorization" do token = 'bearer some token' Puppet[:forge_authorization] = token stub_request(:get, uri).with(headers: {'Authorization' => token}) repository = Puppet::Forge::Repository.new('http://user1:password@fake.com', agent) repository.make_http_request("/the_path") end it "encodes the URI path" do stub_request(:get, "http://fake.com/h%C3%A9llo%20world%20!!%20%C3%A7%20%C3%A0") repository.make_http_request("/héllo world !! ç à") end it "connects via proxy" do Puppet[:http_proxy_host] = 'proxy' Puppet[:http_proxy_port] = 1234 stub_request(:get, uri) expect(Net::HTTP).to receive(:new).with(anything, anything, 'proxy', 1234, nil, nil).and_call_original repository.make_http_request("/the_path") end it "connects via authenticating proxy" do Puppet[:http_proxy_host] = 'proxy' Puppet[:http_proxy_port] = 1234 Puppet[:http_proxy_user] = 'user1' Puppet[:http_proxy_password] = 'password' stub_request(:get, uri) expect(Net::HTTP).to receive(:new).with(anything, anything, 'proxy', 1234, "user1", "password").and_call_original repository.make_http_request("/the_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/forge/forge_spec.rb
spec/unit/forge/forge_spec.rb
# encoding: utf-8 require 'spec_helper' require 'net/http' require 'puppet/forge/repository' describe Puppet::Forge do before(:all) do # any local http proxy will break these tests ENV['http_proxy'] = nil ENV['HTTP_PROXY'] = nil end let(:host) { 'http://fake.com' } let(:forge) { Puppet::Forge.new(host) } # different UTF-8 widths # 1-byte A # 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191 # 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160 # 4-byte ܎ - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142 let (:mixed_utf8_query_param) { "foo + A\u06FF\u16A0\u{2070E}" } # Aۿᚠ let (:mixed_utf8_query_param_encoded) { "foo%20%2B%20A%DB%BF%E1%9A%A0%F0%A0%9C%8E"} let (:empty_json) { '{ "results": [], "pagination" : { "next" : null } }' } describe "making a" do before :each do Puppet[:http_proxy_host] = "proxy" Puppet[:http_proxy_port] = 1234 end context "search request" do it "includes any defined module_groups, ensuring to only encode them once in the URI" do Puppet[:module_groups] = 'base+pe' encoded_uri = "#{host}/v3/modules?query=#{mixed_utf8_query_param_encoded}&module_groups=base%20pe" stub_request(:get, encoded_uri).to_return(status: 200, body: empty_json) forge.search(mixed_utf8_query_param) end it "single encodes the search term in the URI" do encoded_uri = "#{host}/v3/modules?query=#{mixed_utf8_query_param_encoded}" stub_request(:get, encoded_uri).to_return(status: 200, body: empty_json) forge.search(mixed_utf8_query_param) end end context "fetch request" do it "includes any defined module_groups, ensuring to only encode them once in the URI" do Puppet[:module_groups] = 'base+pe' module_name = 'puppetlabs-acl' exclusions = "readme%2Cchangelog%2Clicense%2Curi%2Cmodule%2Ctags%2Csupported%2Cfile_size%2Cdownloads%2Ccreated_at%2Cupdated_at%2Cdeleted_at" encoded_uri = "#{host}/v3/releases?module=#{module_name}&sort_by=version&exclude_fields=#{exclusions}&module_groups=base%20pe" stub_request(:get, encoded_uri).to_return(status: 200, body: empty_json) forge.fetch(module_name) end it "single encodes the module name term in the URI" do module_name = "puppetlabs-#{mixed_utf8_query_param}" exclusions = "readme%2Cchangelog%2Clicense%2Curi%2Cmodule%2Ctags%2Csupported%2Cfile_size%2Cdownloads%2Ccreated_at%2Cupdated_at%2Cdeleted_at" encoded_uri = "#{host}/v3/releases?module=puppetlabs-#{mixed_utf8_query_param_encoded}&sort_by=version&exclude_fields=#{exclusions}" stub_request(:get, encoded_uri).to_return(status: 200, body: empty_json) forge.fetch(module_name) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/forge/errors_spec.rb
spec/unit/forge/errors_spec.rb
require 'spec_helper' require 'puppet/forge' describe Puppet::Forge::Errors do describe 'SSLVerifyError' do subject { Puppet::Forge::Errors::SSLVerifyError } let(:exception) { subject.new(:uri => 'https://fake.com:1111') } it 'should return a valid single line error' do expect(exception.message).to eq('Unable to verify the SSL certificate at https://fake.com:1111') end it 'should return a valid multiline error' do expect(exception.multiline).to eq <<-EOS.chomp Could not connect via HTTPS to https://fake.com:1111 Unable to verify the SSL certificate The certificate may not be signed by a valid CA The CA bundle included with OpenSSL may not be valid or up to date EOS end end describe 'CommunicationError' do subject { Puppet::Forge::Errors::CommunicationError } let(:socket_exception) { SocketError.new('There was a problem') } let(:exception) { subject.new(:uri => 'http://fake.com:1111', :original => socket_exception) } it 'should return a valid single line error' do expect(exception.message).to eq('Unable to connect to the server at http://fake.com:1111. Detail: There was a problem.') end it 'should return a valid multiline error' do expect(exception.multiline).to eq <<-EOS.chomp Could not connect to http://fake.com:1111 There was a network communications problem The error we caught said 'There was a problem' Check your network connection and try again EOS end end describe 'ResponseError' do subject { Puppet::Forge::Errors::ResponseError } let(:response) { double(:body => '{}', :code => '404', :reason => "not found") } context 'without message' do let(:exception) { subject.new(:uri => 'http://fake.com:1111', :response => response, :input => 'user/module') } it 'should return a valid single line error' do expect(exception.message).to eq('Request to Puppet Forge failed. Detail: 404 not found.') end it 'should return a valid multiline error' do expect(exception.multiline).to eq <<-eos.chomp Request to Puppet Forge failed. The server being queried was http://fake.com:1111 The HTTP response we received was '404 not found' eos end end context 'with message' do let(:exception) { subject.new(:uri => 'http://fake.com:1111', :response => response, :input => 'user/module', :message => 'no such module') } it 'should return a valid single line error' do expect(exception.message).to eq('Request to Puppet Forge failed. Detail: no such module / 404 not found.') end it 'should return a valid multiline error' do expect(exception.multiline).to eq <<-eos.chomp Request to Puppet Forge failed. The server being queried was http://fake.com:1111 The HTTP response we received was '404 not found' The message we received said 'no such module' eos 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/parameter/path_spec.rb
spec/unit/parameter/path_spec.rb
require 'spec_helper' require 'puppet/parameter/path' [false, true].each do |arrays| describe "Puppet::Parameter::Path with arrays #{arrays}" do it_should_behave_like "all path parameters", :path, :array => arrays do # The new type allows us a test that is guaranteed to go direct to our # validation code, without passing through any "real type" overrides or # whatever on the way. Puppet::Type.newtype(:test_puppet_parameter_path) do newparam(:path, :parent => Puppet::Parameter::Path, :arrays => arrays) do isnamevar accept_arrays arrays end end def instance(path) Puppet::Type.type(:test_puppet_parameter_path).new(:path => path) 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/parameter/value_spec.rb
spec/unit/parameter/value_spec.rb
require 'spec_helper' require 'puppet/parameter' describe Puppet::Parameter::Value do it "should require a name" do expect { Puppet::Parameter::Value.new }.to raise_error(ArgumentError) end it "should set its name" do expect(Puppet::Parameter::Value.new(:foo).name).to eq(:foo) end it "should support regexes as names" do expect { Puppet::Parameter::Value.new(%r{foo}) }.not_to raise_error end it "should mark itself as a regex if its name is a regex" do expect(Puppet::Parameter::Value.new(%r{foo})).to be_regex end it "should always convert its name to a symbol if it is not a regex" do expect(Puppet::Parameter::Value.new("foo").name).to eq(:foo) expect(Puppet::Parameter::Value.new(true).name).to eq(:true) end it "should support adding aliases" do expect(Puppet::Parameter::Value.new("foo")).to respond_to(:alias) end it "should be able to return its aliases" do value = Puppet::Parameter::Value.new("foo") value.alias("bar") value.alias("baz") expect(value.aliases).to eq([:bar, :baz]) end [:block, :method, :event, :required_features].each do |attr| it "should support a #{attr} attribute" do value = Puppet::Parameter::Value.new("foo") expect(value).to respond_to(attr.to_s + "=") expect(value).to respond_to(attr) end end it "should always return events as symbols" do value = Puppet::Parameter::Value.new("foo") value.event = "foo_test" expect(value.event).to eq(:foo_test) end describe "when matching" do describe "a regex" do it "should return true if the regex matches the value" do expect(Puppet::Parameter::Value.new(/\w/)).to be_match("foo") end it "should return false if the regex does not match the value" do expect(Puppet::Parameter::Value.new(/\d/)).not_to be_match("foo") end end describe "a non-regex" do it "should return true if the value, converted to a symbol, matches the name" do expect(Puppet::Parameter::Value.new("foo")).to be_match("foo") expect(Puppet::Parameter::Value.new(:foo)).to be_match(:foo) expect(Puppet::Parameter::Value.new(:foo)).to be_match("foo") expect(Puppet::Parameter::Value.new("foo")).to be_match(:foo) end it "should return false if the value, converted to a symbol, does not match the name" do expect(Puppet::Parameter::Value.new(:foo)).not_to be_match(:bar) end it "should return true if any of its aliases match" do value = Puppet::Parameter::Value.new("foo") value.alias("bar") expect(value).to be_match("bar") 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/parameter/value_collection_spec.rb
spec/unit/parameter/value_collection_spec.rb
require 'spec_helper' require 'puppet/parameter' describe Puppet::Parameter::ValueCollection do before do @collection = Puppet::Parameter::ValueCollection.new end it "should have a method for defining new values" do expect(@collection).to respond_to(:newvalues) end it "should have a method for adding individual values" do expect(@collection).to respond_to(:newvalue) end it "should be able to retrieve individual values" do value = @collection.newvalue(:foo) expect(@collection.value(:foo)).to equal(value) end it "should be able to add an individual value with a block" do @collection.newvalue(:foo) { raise "testing" } expect(@collection.value(:foo).block).to be_instance_of(Proc) end it "should be able to add values that are empty strings" do expect { @collection.newvalue('') }.to_not raise_error end it "should be able to add values that are empty strings" do value = @collection.newvalue('') expect(@collection.match?('')).to equal(value) end describe "when adding a value with a block" do it "should set the method name to 'set_' plus the value name" do value = @collection.newvalue(:myval) { raise "testing" } expect(value.method).to eq("set_myval") end end it "should be able to add an individual value with options" do value = @collection.newvalue(:foo, :method => 'set_myval') expect(value.method).to eq('set_myval') end it "should have a method for validating a value" do expect(@collection).to respond_to(:validate) end it "should have a method for munging a value" do expect(@collection).to respond_to(:munge) end it "should be able to generate documentation when it has both values and regexes" do @collection.newvalues :foo, "bar", %r{test} expect(@collection.doc).to be_instance_of(String) end it "should correctly generate documentation for values" do @collection.newvalues :foo expect(@collection.doc).to be_include("Valid values are `foo`") end it "should correctly generate documentation for regexes" do @collection.newvalues %r{\w+} expect(@collection.doc).to be_include("Values can match `/\\w+/`") end it "should be able to find the first matching value" do @collection.newvalues :foo, :bar expect(@collection.match?("foo")).to be_instance_of(Puppet::Parameter::Value) end it "should be able to match symbols" do @collection.newvalues :foo, :bar expect(@collection.match?(:foo)).to be_instance_of(Puppet::Parameter::Value) end it "should be able to match symbols when a regex is provided" do @collection.newvalues %r{.} expect(@collection.match?(:foo)).to be_instance_of(Puppet::Parameter::Value) end it "should be able to match values using regexes" do @collection.newvalues %r{.} expect(@collection.match?("foo")).not_to be_nil end it "should prefer value matches to regex matches" do @collection.newvalues %r{.}, :foo expect(@collection.match?("foo").name).to eq(:foo) end describe "when validating values" do it "should do nothing if no values or regexes have been defined" do @collection.validate("foo") end it "should fail if the value is not a defined value or alias and does not match a regex" do @collection.newvalues :foo expect { @collection.validate("bar") }.to raise_error(ArgumentError) end it "should succeed if the value is one of the defined values" do @collection.newvalues :foo expect { @collection.validate(:foo) }.to_not raise_error end it "should succeed if the value is one of the defined values even if the definition uses a symbol and the validation uses a string" do @collection.newvalues :foo expect { @collection.validate("foo") }.to_not raise_error end it "should succeed if the value is one of the defined values even if the definition uses a string and the validation uses a symbol" do @collection.newvalues "foo" expect { @collection.validate(:foo) }.to_not raise_error end it "should succeed if the value is one of the defined aliases" do @collection.newvalues :foo @collection.aliasvalue :bar, :foo expect { @collection.validate("bar") }.to_not raise_error end it "should succeed if the value matches one of the regexes" do @collection.newvalues %r{\d} expect { @collection.validate("10") }.to_not raise_error end end describe "when munging values" do it "should do nothing if no values or regexes have been defined" do expect(@collection.munge("foo")).to eq("foo") end it "should return return any matching defined values" do @collection.newvalues :foo, :bar expect(@collection.munge("foo")).to eq(:foo) end it "should return any matching aliases" do @collection.newvalues :foo @collection.aliasvalue :bar, :foo expect(@collection.munge("bar")).to eq(:foo) end it "should return the value if it matches a regex" do @collection.newvalues %r{\w} expect(@collection.munge("bar")).to eq("bar") end it "should return the value if no other option is matched" do @collection.newvalues :foo expect(@collection.munge("bar")).to eq("bar") 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/parameter/package_options_spec.rb
spec/unit/parameter/package_options_spec.rb
require 'spec_helper' require 'puppet/parameter/package_options' describe Puppet::Parameter::PackageOptions do let (:resource) { double('resource') } let (:param) { described_class.new(:resource => resource) } let (:arg) { '/S' } let (:key) { 'INSTALLDIR' } let (:value) { 'C:/mydir' } context '#munge' do # The parser automatically converts single element arrays to just # a single element, why it does this is beyond me. See 46252b5bb8 it 'should accept a string' do expect(param.munge(arg)).to eq([arg]) end it 'should accept a hash' do expect(param.munge({key => value})).to eq([{key => value}]) end it 'should accept an array of strings and hashes' do munged = param.munge([arg, {key => value}, '/NCRC', {'CONF' => 'C:\datadir'}]) expect(munged).to eq([arg, {key => value}, '/NCRC', {'CONF' => 'C:\datadir'}]) end it 'should quote strings' do expect(param.munge('arg one')).to eq(["\"arg one\""]) end it 'should quote hash pairs' do munged = param.munge({'INSTALL DIR' => 'C:\Program Files'}) expect(munged).to eq([{"\"INSTALL DIR\"" => "\"C:\\Program Files\""}]) end it 'should reject symbols' do expect { param.munge([:symbol]) }.to raise_error(Puppet::Error, /Expected either a string or hash of options/) 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/parameter/boolean_spec.rb
spec/unit/parameter/boolean_spec.rb
require 'spec_helper' require 'puppet' require 'puppet/parameter/boolean' describe Puppet::Parameter::Boolean do let (:resource) { double('resource') } describe "after initvars" do before { described_class.initvars } it "should have the correct value_collection" do expect(described_class.value_collection.values.sort).to eq( [:true, :false, :yes, :no].sort ) end end describe "instances" do subject { described_class.new(:resource => resource) } [ true, :true, 'true', :yes, 'yes', 'TrUe', 'yEs' ].each do |arg| it "should munge #{arg.inspect} as true" do expect(subject.munge(arg)).to eq(true) end end [ false, :false, 'false', :no, 'no', 'FaLSE', 'nO' ].each do |arg| it "should munge #{arg.inspect} as false" do expect(subject.munge(arg)).to eq(false) end end [ nil, :undef, 'undef', '0', 0, '1', 1, 9284 ].each do |arg| it "should fail to munge #{arg.inspect}" do expect { subject.munge(arg) }.to raise_error Puppet::Error end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/test/test_helper_spec.rb
spec/unit/test/test_helper_spec.rb
require 'spec_helper' describe "TestHelper" do context "#after_each_test" do it "restores the original environment" do varname = 'test_helper_spec-test_variable' ENV[varname] = "\u16A0" expect(ENV[varname]).to eq("\u16A0") # Prematurely trigger the after_each_test method Puppet::Test::TestHelper.after_each_test expect(ENV[varname]).to be_nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/envelope_spec.rb
spec/unit/indirector/envelope_spec.rb
require 'spec_helper' require 'puppet/indirector/envelope' describe Puppet::Indirector::Envelope do before do @instance = Object.new @instance.extend(Puppet::Indirector::Envelope) end describe "when testing if it is expired" do it "should return false if there is no expiration set" do expect(@instance).not_to be_expired end it "should return true if the current date is after the expiration date" do @instance.expiration = Time.now - 10 expect(@instance).to be_expired end it "should return false if the current date is prior to the expiration date" do @instance.expiration = Time.now + 10 expect(@instance).not_to be_expired end it "should return false if the current date is equal to the expiration date" do now = Time.now allow(Time).to receive(:now).and_return(now) @instance.expiration = now expect(@instance).not_to be_expired 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/indirector/direct_file_server_spec.rb
spec/unit/indirector/direct_file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/direct_file_server' describe Puppet::Indirector::DirectFileServer do before(:each) do class Puppet::FileTestModel extend Puppet::Indirector indirects :file_test_model attr_accessor :path def initialize(path = '/', options = {}) @path = path @options = options end end class Puppet::FileTestModel::DirectFileServer < Puppet::Indirector::DirectFileServer end Puppet::FileTestModel.indirection.terminus_class = :direct_file_server end let(:path) { File.expand_path('/my/local') } let(:terminus) { Puppet::FileTestModel.indirection.terminus(:direct_file_server) } let(:indirection) { Puppet::FileTestModel.indirection } let(:model) { Puppet::FileTestModel } after(:each) do Puppet::FileTestModel.indirection.delete Puppet.send(:remove_const, :FileTestModel) end describe "when finding a single file" do it "should return nil if the file does not exist" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false) expect(indirection.find(path)).to be_nil end it "should return a Content instance created with the full path to the file if the file exists" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) mycontent = double('content', :collect => nil) expect(mycontent).to receive(:collect) expect(model).to receive(:new).and_return(mycontent) expect(indirection.find(path)).to eq(mycontent) end end describe "when creating the instance for a single found file" do let(:data) { double('content', collect: nil) } before(:each) do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) end it "should pass the full path to the instance" do expect(model).to receive(:new).with(path, anything).and_return(data) indirection.find(path) end it "should pass the :links setting on to the created Content instance if the file exists and there is a value for :links" do expect(model).to receive(:new).and_return(data) expect(data).to receive(:links=).with(:manage) indirection.find(path, links: :manage) end it "should set 'checksum_type' on the instances if it is set in the request options" do expect(model).to receive(:new).and_return(data) expect(data).to receive(:checksum_type=).with(:checksum) indirection.find(path, checksum_type: :checksum) end end describe "when searching for multiple files" do it "should return nil if the file does not exist" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false) expect(indirection.search(path)).to be_nil end it "should pass the original request to :path2instances" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) expect(terminus).to receive(:path2instances).with(anything, path) indirection.search(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/indirector/request_spec.rb
spec/unit/indirector/request_spec.rb
require 'spec_helper' require 'matchers/json' require 'puppet/indirector/request' describe Puppet::Indirector::Request do include JSONMatchers describe "when initializing" do it "should always convert the indirection name to a symbol" do expect(Puppet::Indirector::Request.new("ind", :method, "mykey", nil).indirection_name).to eq(:ind) end it "should use provided value as the key if it is a string" do expect(Puppet::Indirector::Request.new(:ind, :method, "mykey", nil).key).to eq("mykey") end it "should use provided value as the key if it is a symbol" do expect(Puppet::Indirector::Request.new(:ind, :method, :mykey, nil).key).to eq(:mykey) end it "should use the name of the provided instance as its key if an instance is provided as the key instead of a string" do instance = double('instance', :name => "mykey") request = Puppet::Indirector::Request.new(:ind, :method, nil, instance) expect(request.key).to eq("mykey") expect(request.instance).to equal(instance) end it "should support options specified as a hash" do expect { Puppet::Indirector::Request.new(:ind, :method, :key, nil, :one => :two) }.to_not raise_error end it "should support nil options" do expect { Puppet::Indirector::Request.new(:ind, :method, :key, nil, nil) }.to_not raise_error end it "should support unspecified options" do expect { Puppet::Indirector::Request.new(:ind, :method, :key, nil) }.to_not raise_error end it "should use an empty options hash if nil was provided" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, nil).options).to eq({}) end it "should default to a nil node" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil).node).to be_nil end it "should set its node attribute if provided in the options" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :node => "foo.com").node).to eq("foo.com") end it "should default to a nil ip" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil).ip).to be_nil end it "should set its ip attribute if provided in the options" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ip => "192.168.0.1").ip).to eq("192.168.0.1") end it "should default to being unauthenticated" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil)).not_to be_authenticated end it "should set be marked authenticated if configured in the options" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :authenticated => "eh")).to be_authenticated end it "should keep its options as a hash even if a node is specified" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :node => "eh").options).to be_instance_of(Hash) end it "should keep its options as a hash even if another option is specified" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :foo => "bar").options).to be_instance_of(Hash) end it "should treat options other than :ip, :node, and :authenticated as options rather than attributes" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :server => "bar").options[:server]).to eq("bar") end it "should normalize options to use symbols as keys" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, "foo" => "bar").options[:foo]).to eq("bar") end describe "and the request key is a URI" do let(:file) { File.expand_path("/my/file with spaces") } let(:an_environment) { Puppet::Node::Environment.create(:an_environment, []) } let(:env_loaders) { Puppet::Environments::Static.new(an_environment) } around(:each) do |example| Puppet.override({ :environments => env_loaders }, "Static environment loader for specs") do example.run end end describe "and the URI is a 'file' URI" do before do @request = Puppet::Indirector::Request.new(:ind, :method, "#{Puppet::Util.uri_unescape(Puppet::Util.path_to_uri(file).to_s)}", nil) end it "should set the request key to the unescaped full file path" do expect(@request.key).to eq(file) end it "should not set the protocol" do expect(@request.protocol).to be_nil end it "should not set the port" do expect(@request.port).to be_nil end it "should not set the server" do expect(@request.server).to be_nil end end it "should set the protocol to the URI scheme" do expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/", nil).protocol).to eq("http") end it "should set the server if a server is provided" do expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/", nil).server).to eq("host") end it "should set the server and port if both are provided" do expect(Puppet::Indirector::Request.new(:ind, :method, "http://host:543/", nil).port).to eq(543) end it "should default to the serverport if the URI scheme is 'puppet'" do Puppet[:serverport] = "321" expect(Puppet::Indirector::Request.new(:ind, :method, "puppet://host/", nil).port).to eq(321) end it "should use the provided port if the URI scheme is not 'puppet'" do expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/", nil).port).to eq(80) end it "should set the request key to the unescaped path from the URI" do expect(Puppet::Indirector::Request.new(:ind, :method, "http://host/stuff with spaces", nil).key).to eq("stuff with spaces") end it "should set the request key to the unescaped path from the URI, in UTF-8 encoding" do path = "\u4e07" uri = "http://host/#{path}" request = Puppet::Indirector::Request.new(:ind, :method, uri, nil) expect(request.key).to eq(path) expect(request.key.encoding).to eq(Encoding::UTF_8) end it "should set the request key properly given a UTF-8 URI" 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> key = "a/path/stu ff/#{mixed_utf8}" req = Puppet::Indirector::Request.new(:ind, :method, "http:///#{key}", nil) expect(req.key).to eq(key) expect(req.key.encoding).to eq(Encoding::UTF_8) expect(req.uri).to eq("http:///#{key}") end it "should set the :uri attribute to the full URI" do expect(Puppet::Indirector::Request.new(:ind, :method, "http:///a/path/stu ff", nil).uri).to eq('http:///a/path/stu ff') end it "should not parse relative URI" do expect(Puppet::Indirector::Request.new(:ind, :method, "foo/bar", nil).uri).to be_nil end it "should not parse opaque URI" do expect(Puppet::Indirector::Request.new(:ind, :method, "mailto:joe", nil).uri).to be_nil end end it "should allow indication that it should not read a cached instance" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ignore_cache => true)).to be_ignore_cache end it "should default to not ignoring the cache" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil)).not_to be_ignore_cache end it "should allow indication that it should not not read an instance from the terminus" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil, :ignore_terminus => true)).to be_ignore_terminus end it "should default to not ignoring the terminus" do expect(Puppet::Indirector::Request.new(:ind, :method, :key, nil)).not_to be_ignore_terminus end end it "should look use the Indirection class to return the appropriate indirection" do ind = double('indirection') expect(Puppet::Indirector::Indirection).to receive(:instance).with(:myind).and_return(ind) request = Puppet::Indirector::Request.new(:myind, :method, :key, nil) expect(request.indirection).to equal(ind) end it "should use its indirection to look up the appropriate model" do ind = double('indirection') expect(Puppet::Indirector::Indirection).to receive(:instance).with(:myind).and_return(ind) request = Puppet::Indirector::Request.new(:myind, :method, :key, nil) expect(ind).to receive(:model).and_return("mymodel") expect(request.model).to eq("mymodel") end it "should fail intelligently when asked to find a model but the indirection cannot be found" do expect(Puppet::Indirector::Indirection).to receive(:instance).with(:myind).and_return(nil) request = Puppet::Indirector::Request.new(:myind, :method, :key, nil) expect { request.model }.to raise_error(ArgumentError) end it "should have a method for determining if the request is plural or singular" do expect(Puppet::Indirector::Request.new(:myind, :method, :key, nil)).to respond_to(:plural?) end it "should be considered plural if the method is 'search'" do expect(Puppet::Indirector::Request.new(:myind, :search, :key, nil)).to be_plural end it "should not be considered plural if the method is not 'search'" do expect(Puppet::Indirector::Request.new(:myind, :find, :key, nil)).not_to be_plural end it "should use its uri, if it has one, as its description" do Puppet.override( { :environments => Puppet::Environments::Static.new(Puppet::Node::Environment.create(:baz, [])) }, "Static loader for spec" ) do expect(Puppet::Indirector::Request.new(:myind, :find, "foo://bar/baz", nil).description).to eq("foo://bar/baz") end end it "should use its indirection name and key, if it has no uri, as its description" do expect(Puppet::Indirector::Request.new(:myind, :find, "key", nil).description).to eq("/myind/key") end it "should set its environment to an environment instance when a string is specified as its environment" do env = Puppet::Node::Environment.create(:foo, []) Puppet.override(:environments => Puppet::Environments::Static.new(env)) do expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :environment => "foo").environment).to eq(env) end end it "should use any passed in environment instances as its environment" do env = Puppet::Node::Environment.create(:foo, []) expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :environment => env).environment).to equal(env) end it "should use the current environment when none is provided" do Puppet[:environment] = "foo" expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil).environment).to eq(Puppet.lookup(:current_environment)) end it "should support converting its options to a hash" do expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil )).to respond_to(:to_hash) end it "should include all of its attributes when its options are converted to a hash" do expect(Puppet::Indirector::Request.new(:myind, :find, "my key", nil, :node => 'foo').to_hash[:node]).to eq('foo') end describe "#remote?" do def request(options = {}) Puppet::Indirector::Request.new('node', 'find', 'localhost', nil, options) end it "should not be unless node or ip is set" do expect(request).not_to be_remote end it "should be remote if node is set" do expect(request(:node => 'example.com')).to be_remote end it "should be remote if ip is set" do expect(request(:ip => '127.0.0.1')).to be_remote end it "should be remote if node and ip are set" do expect(request(:node => 'example.com', :ip => '127.0.0.1')).to be_remote 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/indirector/face_spec.rb
spec/unit/indirector/face_spec.rb
require 'spec_helper' require 'puppet/indirector/face' describe Puppet::Indirector::Face do subject do instance = Puppet::Indirector::Face.new(:test, '0.0.1') indirection = double('indirection', :name => :stub_indirection, :reset_terminus_class => nil) allow(instance).to receive(:indirection).and_return(indirection) instance end it "should be able to return a list of indirections" do expect(Puppet::Indirector::Face.indirections).to be_include("catalog") end it "should return the sorted to_s list of terminus classes" do expect(Puppet::Indirector::Terminus).to receive(:terminus_classes).and_return([ :yaml, :compiler, :rest ]) expect(Puppet::Indirector::Face.terminus_classes(:catalog)).to eq([ 'compiler', 'rest', 'yaml' ]) end describe "as an instance" do it "should be able to determine its indirection" do # Loading actions here can get, um, complicated expect(Puppet::Indirector::Face.new(:catalog, '0.0.1').indirection).to equal(Puppet::Resource::Catalog.indirection) end end [:find, :search, :save, :destroy].each do |method| def params(method, options) if method == :save [nil, options] else [options] end end it "should define a '#{method}' action" do expect(Puppet::Indirector::Face).to be_action(method) end it "should call the indirection method with options when the '#{method}' action is invoked" do expect(subject.indirection).to receive(method).with(:test, *params(method, {})) subject.send(method, :test) end it "should forward passed options" do expect(subject.indirection).to receive(method).with(:test, *params(method, {})) subject.send(method, :test, {}) end end it "should default key to certname for find action" do expect(subject.indirection).to receive(:find).with(Puppet[:certname], {}) subject.send(:find, {}) end it "should be able to override its indirection name" do subject.set_indirection_name :foo expect(subject.indirection_name).to eq(:foo) end it "should be able to set its terminus class" do expect(subject.indirection).to receive(:terminus_class=).with(:myterm) subject.set_terminus(:myterm) end it "should define a class-level 'info' action" do expect(Puppet::Indirector::Face).to be_action(:info) 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/indirector/hiera_spec.rb
spec/unit/indirector/hiera_spec.rb
require 'spec_helper' require 'puppet/data_binding' require 'puppet/indirector/hiera' begin require 'hiera/backend' rescue LoadError => e Puppet.warning(_("Unable to load Hiera 3 backend: %{message}") % {message: e.message}) end describe Puppet::Indirector::Hiera, :if => Puppet.features.hiera? do module Testing module DataBinding class Hiera < Puppet::Indirector::Hiera end end end it_should_behave_like "Hiera indirection", Testing::DataBinding::Hiera, my_fixture_dir end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/rest_spec.rb
spec/unit/indirector/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/rest' class Puppet::TestModel extend Puppet::Indirector indirects :test_model end # The subclass must not be all caps even though the superclass is class Puppet::TestModel::Rest < Puppet::Indirector::REST end class Puppet::FailingTestModel extend Puppet::Indirector indirects :failing_test_model end # The subclass must not be all caps even though the superclass is class Puppet::FailingTestModel::Rest < Puppet::Indirector::REST def find(request) http = Puppet.runtime[:http] response = http.get(URI('http://puppet.example.com:8140/puppet/v3/failing_test_model')) if response.code == 404 return nil unless request.options[:fail_on_404] _, body = parse_response(response) msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(response.url.path, 100), body: body } raise Puppet::Error, msg else raise convert_to_http_error(response) end end end describe Puppet::Indirector::REST do before :each do Puppet::TestModel.indirection.terminus_class = :rest end it "raises when find is called" do expect { Puppet::TestModel.indirection.find('foo') }.to raise_error(NotImplementedError) end it "raises when head is called" do expect { Puppet::TestModel.indirection.head('foo') }.to raise_error(NotImplementedError) end it "raises when search is called" do expect { Puppet::TestModel.indirection.search('foo') }.to raise_error(NotImplementedError) end it "raises when save is called" do expect { Puppet::TestModel.indirection.save(Puppet::TestModel.new, 'foo') }.to raise_error(NotImplementedError) end it "raises when destroy is called" do expect { Puppet::TestModel.indirection.destroy('foo') }.to raise_error(NotImplementedError) end context 'when parsing the response error' do before :each do Puppet::FailingTestModel.indirection.terminus_class = :rest end it 'returns nil if 404 is returned and fail_on_404 is omitted' do stub_request(:get, 'http://puppet.example.com:8140/puppet/v3/failing_test_model').to_return(status: 404) expect(Puppet::FailingTestModel.indirection.find('foo')).to be_nil end it 'raises if 404 is returned and fail_on_404 is true' do stub_request( :get, 'http://puppet.example.com:8140/puppet/v3/failing_test_model', ).to_return(status: 404, headers: { 'Content-Type' => 'text/plain' }, body: 'plaintext') expect { Puppet::FailingTestModel.indirection.find('foo', fail_on_404: true) }.to raise_error(Puppet::Error, 'Find /puppet/v3/failing_test_model resulted in 404 with the message: plaintext') end it 'returns the HTTP reason if the response body is empty' do stub_request(:get, 'http://puppet.example.com:8140/puppet/v3/failing_test_model').to_return(status: [500, 'Internal Server Error']) expect { Puppet::FailingTestModel.indirection.find('foo') }.to raise_error(Net::HTTPError, 'Error 500 on SERVER: Internal Server Error') end it 'parses the response body as text' do stub_request( :get, 'http://puppet.example.com:8140/puppet/v3/failing_test_model' ).to_return(status: [500, 'Internal Server Error'], headers: { 'Content-Type' => 'text/plain' }, body: 'plaintext') expect { Puppet::FailingTestModel.indirection.find('foo') }.to raise_error(Net::HTTPError, 'Error 500 on SERVER: plaintext') end it 'parses the response body as json and returns the "message"' do stub_request( :get, 'http://puppet.example.com:8140/puppet/v3/failing_test_model' ).to_return(status: [500, 'Internal Server Error'], headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({'status' => false, 'message' => 'json error'})) expect { Puppet::FailingTestModel.indirection.find('foo') }.to raise_error(Net::HTTPError, 'Error 500 on SERVER: json error') end it 'parses the response body as pson and returns the "message"', if: Puppet.features.pson? do stub_request( :get, 'http://puppet.example.com:8140/puppet/v3/failing_test_model' ).to_return(status: [500, 'Internal Server Error'], headers: { 'Content-Type' => 'application/pson' }, body: PSON.dump({'status' => false, 'message' => 'pson error'})) expect { Puppet::FailingTestModel.indirection.find('foo') }.to raise_error(Net::HTTPError, 'Error 500 on SERVER: pson error') end it 'returns the response body if no content-type given' do stub_request( :get, 'http://puppet.example.com:8140/puppet/v3/failing_test_model' ).to_return(status: [500, 'Internal Server Error'], body: 'unknown text') expect { Puppet::FailingTestModel.indirection.find('foo') }.to raise_error(Net::HTTPError, 'Error 500 on SERVER: unknown text') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/msgpack_spec.rb
spec/unit/indirector/msgpack_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/indirector/indirector_testing/msgpack' describe Puppet::Indirector::Msgpack, :if => Puppet.features.msgpack? do include PuppetSpec::Files subject { Puppet::IndirectorTesting::Msgpack.new } let :model do Puppet::IndirectorTesting end let :indirection do model.indirection end context "#path" do before :each do Puppet[:server_datadir] = '/sample/datadir/server' Puppet[:client_datadir] = '/sample/datadir/client' end it "uses the :server_datadir setting if this is the server" do allow(Puppet.run_mode).to receive(:server?).and_return(true) expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.msgpack') expect(subject.path('testing')).to eq(expected) end it "uses the :client_datadir setting if this is not the server" do allow(Puppet.run_mode).to receive(:server?).and_return(false) expected = File.join(Puppet[:client_datadir], 'indirector_testing', 'testing.msgpack') expect(subject.path('testing')).to eq(expected) end it "overrides the default extension with a supplied value" do allow(Puppet.run_mode).to receive(:server?).and_return(true) expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.not-msgpack') expect(subject.path('testing', '.not-msgpack')).to eq(expected) end ['../foo', '..\\foo', './../foo', '.\\..\\foo', '/foo', '//foo', '\\foo', '\\\\goo', "test\0/../bar", "test\0\\..\\bar", "..\\/bar", "/tmp/bar", "/tmp\\bar", "tmp\\bar", " / bar", " /../ bar", " \\..\\ bar", "c:\\foo", "c:/foo", "\\\\?\\UNC\\bar", "\\\\foo\\bar", "\\\\?\\c:\\foo", "//?/UNC/bar", "//foo/bar", "//?/c:/foo", ].each do |input| it "should resist directory traversal attacks (#{input.inspect})" do expect { subject.path(input) }.to raise_error ArgumentError, 'invalid key' end end end context "handling requests" do before :each do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:server_datadir] = tmpdir('msgpackdir') FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing')) end let :file do subject.path(request.key) end def with_content(text) FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') {|f| f.write text } yield if block_given? end it "data saves and then loads again correctly" do subject.save(indirection.request(:save, 'example', model.new('banana'))) expect(subject.find(indirection.request(:find, 'example', nil)).value).to eq('banana') end context "#find" do let :request do indirection.request(:find, 'example', nil) end it "returns nil if the file doesn't exist" do expect(subject.find(request)).to be_nil end it "can load a UTF-8 file from disk" do rune_utf8 = "\u16A0\u16C7\u16BB" # ᚠᛇᚻ with_content(model.new(rune_utf8).to_msgpack) do instance = subject.find(request) expect(instance).to be_an_instance_of model expect(instance.value).to eq(rune_utf8) end end it "raises a descriptive error when the file can't be read" do with_content(model.new('foo').to_msgpack) do # I don't like this, but there isn't a credible alternative that # also works on Windows, so a stub it is. At least the expectation # will fail if the implementation changes. Sorry to the next dev. expect(Puppet::FileSystem).to receive(:read).with(file, {:encoding => 'utf-8'}).and_raise(Errno::EPERM) expect { subject.find(request) }. to raise_error Puppet::Error, /Could not read MessagePack/ end end it "raises a descriptive error when the file content is invalid" do with_content("this is totally invalid MessagePack") do expect { subject.find(request) }. to raise_error Puppet::Error, /Could not parse MessagePack data/ end end it "should return an instance of the indirected object when valid" do with_content(model.new(1).to_msgpack) do instance = subject.find(request) expect(instance).to be_an_instance_of model expect(instance.value).to eq(1) end end end context "#save" do let :instance do model.new(4) end let :request do indirection.request(:find, 'example', instance) end it "should save the instance of the request as MessagePack to disk" do subject.save(request) content = File.read(file) expect(MessagePack.unpack(content)['value']).to eq(4) end it "should create the indirection directory if required" do target = File.join(Puppet[:server_datadir], 'indirector_testing') Dir.rmdir(target) subject.save(request) expect(File).to be_directory(target) end end context "#destroy" do let :request do indirection.request(:find, 'example', nil) end it "removes an existing file" do with_content('hello') do subject.destroy(request) end expect(Puppet::FileSystem.exist?(file)).to be_falsey end it "silently succeeds when files don't exist" do Puppet::FileSystem.unlink(file) rescue nil expect(subject.destroy(request)).to be_truthy end it "raises an informative error for other failures" do allow(Puppet::FileSystem).to receive(:unlink).with(file).and_raise(Errno::EPERM, 'fake permission problem') with_content('hello') do expect { subject.destroy(request) }.to raise_error(Puppet::Error) end end end end context "#search" do before :each do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:server_datadir] = tmpdir('msgpackdir') FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing')) end def request(glob) indirection.request(:search, glob, nil) end def create_file(name, value = 12) File.open(subject.path(name, ''), 'w') do |f| f.write Puppet::IndirectorTesting.new(value).to_msgpack end end it "returns an empty array when nothing matches the key as a glob" do expect(subject.search(request('*'))).to eq([]) end it "returns an array with one item if one item matches" do create_file('foo.msgpack', 'foo') create_file('bar.msgpack', 'bar') expect(subject.search(request('f*')).map(&:value)).to eq(['foo']) end it "returns an array of items when more than one item matches" do create_file('foo.msgpack', 'foo') create_file('bar.msgpack', 'bar') create_file('baz.msgpack', 'baz') expect(subject.search(request('b*')).map(&:value)).to match_array(['bar', 'baz']) end it "only items with the .msgpack extension" do create_file('foo.msgpack', 'foo-msgpack') create_file('foo.msgpack~', 'foo-backup') expect(subject.search(request('f*')).map(&:value)).to eq(['foo-msgpack']) 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/indirector/none_spec.rb
spec/unit/indirector/none_spec.rb
require 'spec_helper' require 'puppet/indirector/none' describe Puppet::Indirector::None do before do allow(Puppet::Indirector::Terminus).to receive(:register_terminus_class) allow(Puppet::Indirector::Indirection).to receive(:instance).and_return(indirection) module Testing; end @none_class = class Testing::None < Puppet::Indirector::None self end @data_binder = @none_class.new end let(:model) { double('model') } let(:request) { double('request', :key => "port") } let(:indirection) do double('indirection', :name => :none, :register_terminus_type => nil, :model => model) end it "should not be the default data_binding_terminus" do expect(Puppet.settings[:data_binding_terminus]).not_to eq('none') end describe "the behavior of the find method" do it "should just return nil" do expect(@data_binder.find(request)).to be_nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/plain_spec.rb
spec/unit/indirector/plain_spec.rb
require 'spec_helper' require 'puppet/indirector/plain' describe Puppet::Indirector::Plain do before do allow(Puppet::Indirector::Terminus).to receive(:register_terminus_class) @model = double('model') @indirection = double('indirection', :name => :mystuff, :register_terminus_type => nil, :model => @model) allow(Puppet::Indirector::Indirection).to receive(:instance).and_return(@indirection) module Testing; end @plain_class = class Testing::MyPlain < Puppet::Indirector::Plain self end @searcher = @plain_class.new @request = double('request', :key => "yay") end it "should return return an instance of the indirected model" do object = double('object') expect(@model).to receive(:new).with(@request.key).and_return(object) expect(@searcher.find(@request)).to equal(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/indirector/file_server_spec.rb
spec/unit/indirector/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_server' require 'puppet/file_serving/configuration' describe Puppet::Indirector::FileServer do before :all do class Puppet::FileTestModel extend Puppet::Indirector indirects :file_test_model attr_accessor :path def initialize(path = '/', options = {}) @path = path @options = options end end class Puppet::FileTestModel::FileServer < Puppet::Indirector::FileServer end Puppet::FileTestModel.indirection.terminus_class = :file_server end let(:path) { File.expand_path('/my/local') } let(:terminus) { Puppet::FileTestModel.indirection.terminus(:file_server) } let(:indirection) { Puppet::FileTestModel.indirection } let(:model) { Puppet::FileTestModel } let(:uri) { "puppet://host/my/local/file" } let(:configuration) { double('configuration') } after(:all) do Puppet::FileTestModel.indirection.delete Puppet.send(:remove_const, :FileTestModel) end before(:each)do allow(Puppet::FileServing::Configuration).to receive(:configuration).and_return(configuration) end describe "when finding files" do let(:mount) { double('mount', find: nil) } let(:instance) { double('instance', :links= => nil, :collect => nil) } it "should use the configuration to find the mount and relative path" do expect(configuration).to receive(:split_path) do |args| expect(args.uri).to eq(uri) nil end indirection.find(uri) end it "should return nil if it cannot find the mount" do expect(configuration).to receive(:split_path).and_return([nil, nil]) expect(indirection.find(uri)).to be_nil end it "should use the mount to find the full path" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:find).with("rel/path", anything) indirection.find(uri) end it "should pass the request when finding a file" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:find) { |_, request| expect(request.uri).to eq(uri) }.and_return(nil) indirection.find(uri) end it "should return nil if it cannot find a full path" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:find).with("rel/path", anything) expect(indirection.find(uri)).to be_nil end it "should create an instance with the found path" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:find).with("rel/path", anything).and_return("/my/file") expect(model).to receive(:new).with("/my/file", {:relative_path => nil}).and_return(instance) expect(indirection.find(uri)).to equal(instance) end it "should set 'links' on the instance if it is set in the request options" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:find).with("rel/path", anything).and_return("/my/file") expect(model).to receive(:new).with("/my/file", {:relative_path => nil}).and_return(instance) expect(instance).to receive(:links=).with(true) expect(indirection.find(uri, links: true)).to equal(instance) end it "should collect the instance" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:find).with("rel/path", anything).and_return("/my/file") expect(model).to receive(:new).with("/my/file", {:relative_path => nil}).and_return(instance) expect(instance).to receive(:collect) expect(indirection.find(uri, links: true)).to equal(instance) end end describe "when searching for instances" do let(:mount) { double('mount', find: nil) } it "should use the configuration to search the mount and relative path" do expect(configuration).to receive(:split_path) do |args| expect(args.uri).to eq(uri) end.and_return([nil, nil]) indirection.search(uri) end it "should return nil if it cannot search the mount" do expect(configuration).to receive(:split_path).and_return([nil, nil]) expect(indirection.search(uri)).to be_nil end it "should use the mount to search for the full paths" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search).with("rel/path", anything) indirection.search(uri) end it "should pass the request" do allow(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search) { |_, request| expect(request.uri).to eq(uri) }.and_return(nil) indirection.search(uri) end it "should return nil if searching does not find any full paths" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search).with("rel/path", anything).and_return(nil) expect(indirection.search(uri)).to be_nil end it "should create a fileset with each returned path and merge them" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search).with("rel/path", anything).and_return(%w{/one /two}) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) one = double('fileset_one') expect(Puppet::FileServing::Fileset).to receive(:new).with("/one", anything).and_return(one) two = double('fileset_two') expect(Puppet::FileServing::Fileset).to receive(:new).with("/two", anything).and_return(two) expect(Puppet::FileServing::Fileset).to receive(:merge).with(one, two).and_return([]) indirection.search(uri) end it "should create an instance with each path resulting from the merger of the filesets" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search).with("rel/path", anything).and_return([]) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect(Puppet::FileServing::Fileset).to receive(:merge).and_return("one" => "/one", "two" => "/two") one = double('one', :collect => nil) expect(model).to receive(:new).with("/one", {:relative_path => "one"}).and_return(one) two = double('two', :collect => nil) expect(model).to receive(:new).with("/two", {:relative_path => "two"}).and_return(two) # order can't be guaranteed result = indirection.search(uri) expect(result).to be_include(one) expect(result).to be_include(two) expect(result.length).to eq(2) end it "should set 'links' on the instances if it is set in the request options" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search).with("rel/path", anything).and_return([]) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect(Puppet::FileServing::Fileset).to receive(:merge).and_return("one" => "/one") one = double('one', :collect => nil) expect(model).to receive(:new).with("/one", {:relative_path => "one"}).and_return(one) expect(one).to receive(:links=).with(true) indirection.search(uri, links: true) end it "should set 'checksum_type' on the instances if it is set in the request options" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search).with("rel/path", anything).and_return([]) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect(Puppet::FileServing::Fileset).to receive(:merge).and_return("one" => "/one") one = double('one', :collect => nil) expect(model).to receive(:new).with("/one", {:relative_path => "one"}).and_return(one) expect(one).to receive(:checksum_type=).with(:checksum) indirection.search(uri, checksum_type: :checksum) end it "should collect the instances" do expect(configuration).to receive(:split_path).and_return([mount, "rel/path"]) expect(mount).to receive(:search).with("rel/path", anything).and_return([]) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) expect(Puppet::FileServing::Fileset).to receive(:merge).and_return("one" => "/one") one = double('one') expect(model).to receive(:new).with("/one", {:relative_path => "one"}).and_return(one) expect(one).to receive(:collect) indirection.search(uri) end end describe "when checking authorization" do let(:mount) { double('mount') } let(:request) { Puppet::Indirector::Request.new(:myind, :mymethod, uri, :environment => "myenv") } before(:each) do request.method = :find allow(configuration).to receive(:split_path).and_return([mount, "rel/path"]) allow(request).to receive(:node).and_return("mynode") allow(request).to receive(:ip).and_return("myip") allow(mount).to receive(:name).and_return("myname") allow(mount).to receive(:allowed?).with("mynode", "myip").and_return("something") end it "should return false when destroying" do request.method = :destroy expect(terminus).not_to be_authorized(request) end it "should return false when saving" do request.method = :save expect(terminus).not_to be_authorized(request) end it "should use the configuration to find the mount and relative path" do expect(configuration).to receive(:split_path).with(request) terminus.authorized?(request) end it "should return false if it cannot find the mount" do expect(configuration).to receive(:split_path).and_return([nil, nil]) expect(terminus).not_to be_authorized(request) end it "should return true when no auth directives are defined for the mount point" do expect(terminus).to be_authorized(request) 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/indirector/json_spec.rb
spec/unit/indirector/json_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/indirector/indirector_testing/json' describe Puppet::Indirector::JSON do include PuppetSpec::Files subject { Puppet::IndirectorTesting::JSON.new } let :model do Puppet::IndirectorTesting end let :indirection do model.indirection end context "#path" do before :each do Puppet[:server_datadir] = '/sample/datadir/server' Puppet[:client_datadir] = '/sample/datadir/client' end it "uses the :server_datadir setting if this is the server" do allow(Puppet.run_mode).to receive(:server?).and_return(true) expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.json') expect(subject.path('testing')).to eq(expected) end it "uses the :client_datadir setting if this is not the server" do allow(Puppet.run_mode).to receive(:server?).and_return(false) expected = File.join(Puppet[:client_datadir], 'indirector_testing', 'testing.json') expect(subject.path('testing')).to eq(expected) end it "overrides the default extension with a supplied value" do allow(Puppet.run_mode).to receive(:server?).and_return(true) expected = File.join(Puppet[:server_datadir], 'indirector_testing', 'testing.not-json') expect(subject.path('testing', '.not-json')).to eq(expected) end ['../foo', '..\\foo', './../foo', '.\\..\\foo', '/foo', '//foo', '\\foo', '\\\\goo', "test\0/../bar", "test\0\\..\\bar", "..\\/bar", "/tmp/bar", "/tmp\\bar", "tmp\\bar", " / bar", " /../ bar", " \\..\\ bar", "c:\\foo", "c:/foo", "\\\\?\\UNC\\bar", "\\\\foo\\bar", "\\\\?\\c:\\foo", "//?/UNC/bar", "//foo/bar", "//?/c:/foo", ].each do |input| it "should resist directory traversal attacks (#{input.inspect})" do expect { subject.path(input) }.to raise_error ArgumentError, 'invalid key' end end end context "handling requests" do before :each do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:server_datadir] = tmpdir('jsondir') FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing')) end let :file do subject.path(request.key) end def with_content(text) FileUtils.mkdir_p(File.dirname(file)) File.binwrite(file, text) yield if block_given? end it "data saves and then loads again correctly" do subject.save(indirection.request(:save, 'example', model.new('banana'))) expect(subject.find(indirection.request(:find, 'example', nil)).value).to eq('banana') end context "#find" do let :request do indirection.request(:find, 'example', nil) end it "returns nil if the file doesn't exist" do expect(subject.find(request)).to be_nil end it "raises a descriptive error when the file can't be read" do with_content(model.new('foo').to_json) do # I don't like this, but there isn't a credible alternative that # also works on Windows, so a stub it is. At least the expectation # will fail if the implementation changes. Sorry to the next dev. expect(Puppet::FileSystem).to receive(:read).with(file, anything).and_raise(Errno::EPERM) expect { subject.find(request) }. to raise_error Puppet::Error, /Could not read JSON/ end end it "raises a descriptive error when the file content is invalid" do with_content("this is totally invalid JSON") do expect { subject.find(request) }. to raise_error Puppet::Error, /Could not parse JSON data/ end end it "raises if the content contains binary" do binary = "\xC0\xFF".force_encoding(Encoding::BINARY) with_content(binary) do expect { subject.find(request) }.to raise_error Puppet::Error, /Could not parse JSON data/ end end it "should return an instance of the indirected object when valid" do with_content(model.new(1).to_json) do instance = subject.find(request) expect(instance).to be_an_instance_of model expect(instance.value).to eq(1) end end end context "#save" do let :instance do model.new(4) end let :request do indirection.request(:find, 'example', instance) end it "should save the instance of the request as JSON to disk" do subject.save(request) content = File.read(file) expect(content).to match(/"value"\s*:\s*4/) end it "should create the indirection directory if required" do target = File.join(Puppet[:server_datadir], 'indirector_testing') Dir.rmdir(target) subject.save(request) expect(File).to be_directory(target) end end context "#destroy" do let :request do indirection.request(:find, 'example', nil) end it "removes an existing file" do with_content('hello') do subject.destroy(request) end expect(Puppet::FileSystem.exist?(file)).to be_falsey end it "silently succeeds when files don't exist" do Puppet::FileSystem.unlink(file) rescue nil expect(subject.destroy(request)).to be_truthy end it "raises an informative error for other failures" do allow(Puppet::FileSystem).to receive(:unlink).with(file).and_raise(Errno::EPERM, 'fake permission problem') with_content('hello') do expect { subject.destroy(request) }.to raise_error(Puppet::Error) end end end end context "#search" do before :each do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:server_datadir] = tmpdir('jsondir') FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing')) end def request(glob) indirection.request(:search, glob, nil) end def create_file(name, value = 12) File.open(subject.path(name, ''), 'wb') do |f| f.puts Puppet::IndirectorTesting.new(value).to_json end end it "returns an empty array when nothing matches the key as a glob" do expect(subject.search(request('*'))).to eq([]) end it "returns an array with one item if one item matches" do create_file('foo.json', 'foo') create_file('bar.json', 'bar') expect(subject.search(request('f*')).map(&:value)).to eq(['foo']) end it "returns an array of items when more than one item matches" do create_file('foo.json', 'foo') create_file('bar.json', 'bar') create_file('baz.json', 'baz') expect(subject.search(request('b*')).map(&:value)).to match_array(['bar', 'baz']) end it "only items with the .json extension" do create_file('foo.json', 'foo-json') create_file('foo.pson', 'foo-pson') create_file('foo.json~', 'foo-backup') expect(subject.search(request('f*')).map(&:value)).to eq(['foo-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/indirector/terminus_spec.rb
spec/unit/indirector/terminus_spec.rb
require 'spec_helper' require 'puppet/defaults' require 'puppet/indirector' require 'puppet/indirector/memory' describe Puppet::Indirector::Terminus do before :all do class Puppet::AbstractConcept extend Puppet::Indirector indirects :abstract_concept attr_accessor :name def initialize(name = "name") @name = name end end class Puppet::AbstractConcept::Freedom < Puppet::Indirector::Code end end after :all do # Remove the class, unlinking it from the rest of the system. Puppet.send(:remove_const, :AbstractConcept) if Puppet.const_defined?(:AbstractConcept) end let :terminus_class do Puppet::AbstractConcept::Freedom end let :terminus do terminus_class.new end let :indirection do Puppet::AbstractConcept.indirection end let :model do Puppet::AbstractConcept end it "should provide a method for setting terminus class documentation" do expect(terminus_class).to respond_to(:desc) end it "should support a class-level name attribute" do expect(terminus_class).to respond_to(:name) end it "should support a class-level indirection attribute" do expect(terminus_class).to respond_to(:indirection) end it "should support a class-level terminus-type attribute" do expect(terminus_class).to respond_to(:terminus_type) end it "should support a class-level model attribute" do expect(terminus_class).to respond_to(:model) end it "should accept indirection instances as its indirection" do # The test is that this shouldn't raise, and should preserve the object # instance exactly, hence "equal", not just "==". terminus_class.indirection = indirection expect(terminus_class.indirection).to equal indirection end it "should look up indirection instances when only a name has been provided" do terminus_class.indirection = :abstract_concept expect(terminus_class.indirection).to equal indirection end it "should fail when provided a name that does not resolve to an indirection" do expect { terminus_class.indirection = :exploding_whales }.to raise_error(ArgumentError, /Could not find indirection instance/) # We should still have the default indirection. expect(terminus_class.indirection).to equal indirection end describe "when a terminus instance" do it "should return the class's name as its name" do expect(terminus.name).to eq(:freedom) end it "should return the class's indirection as its indirection" do expect(terminus.indirection).to equal indirection end it "should set the instances's type to the abstract terminus type's name" do expect(terminus.terminus_type).to eq(:code) end it "should set the instances's model to the indirection's model" do expect(terminus.model).to equal indirection.model end end describe "when managing terminus classes" do it "should provide a method for registering terminus classes" do expect(Puppet::Indirector::Terminus).to respond_to(:register_terminus_class) end it "should provide a method for returning terminus classes by name and type" do terminus = double('terminus_type', :name => :abstract, :indirection_name => :whatever) Puppet::Indirector::Terminus.register_terminus_class(terminus) expect(Puppet::Indirector::Terminus.terminus_class(:whatever, :abstract)).to equal(terminus) end it "should set up autoloading for any terminus class types requested" do expect(Puppet::Indirector::Terminus).to receive(:instance_load).with(:test2, "puppet/indirector/test2") Puppet::Indirector::Terminus.terminus_class(:test2, :whatever) end it "should load terminus classes that are not found" do # Set up instance loading; it would normally happen automatically Puppet::Indirector::Terminus.instance_load :test1, "puppet/indirector/test1" expect(Puppet::Indirector::Terminus.instance_loader(:test1)).to receive(:load).with(:yay, anything) Puppet::Indirector::Terminus.terminus_class(:test1, :yay) end it "should fail when no indirection can be found" do expect(Puppet::Indirector::Indirection).to receive(:instance).with(:abstract_concept).and_return(nil) expect { class Puppet::AbstractConcept::Physics < Puppet::Indirector::Code end }.to raise_error(ArgumentError, /Could not find indirection instance/) end it "should register the terminus class with the terminus base class" do expect(Puppet::Indirector::Terminus).to receive(:register_terminus_class) do |type| expect(type.indirection_name).to eq(:abstract_concept) expect(type.name).to eq(:intellect) end begin class Puppet::AbstractConcept::Intellect < Puppet::Indirector::Code end ensure Puppet::AbstractConcept.send(:remove_const, :Intellect) rescue nil end end end describe "when parsing class constants for indirection and terminus names" do before :each do allow(Puppet::Indirector::Terminus).to receive(:register_terminus_class) end let :subclass do subclass = double('subclass') allow(subclass).to receive(:to_s).and_return("TestInd::OneTwo") allow(subclass).to receive(:mark_as_abstract_terminus) subclass end it "should fail when anonymous classes are used" do expect { Puppet::Indirector::Terminus.inherited(Class.new) }.to raise_error(Puppet::DevError, /Terminus subclasses must have associated constants/) end it "should use the last term in the constant for the terminus class name" do expect(subclass).to receive(:name=).with(:one_two) allow(subclass).to receive(:indirection=) Puppet::Indirector::Terminus.inherited(subclass) end it "should convert the terminus name to a downcased symbol" do expect(subclass).to receive(:name=).with(:one_two) allow(subclass).to receive(:indirection=) Puppet::Indirector::Terminus.inherited(subclass) end it "should use the second to last term in the constant for the indirection name" do expect(subclass).to receive(:indirection=).with(:test_ind) allow(subclass).to receive(:name=) allow(subclass).to receive(:terminus_type=) Puppet::Indirector::Memory.inherited(subclass) end it "should convert the indirection name to a downcased symbol" do expect(subclass).to receive(:indirection=).with(:test_ind) allow(subclass).to receive(:name=) allow(subclass).to receive(:terminus_type=) Puppet::Indirector::Memory.inherited(subclass) end it "should convert camel case to lower case with underscores as word separators" do expect(subclass).to receive(:name=).with(:one_two) allow(subclass).to receive(:indirection=) Puppet::Indirector::Terminus.inherited(subclass) end end describe "when creating terminus class types" do before :each do allow(Puppet::Indirector::Terminus).to receive(:register_terminus_class) class Puppet::Indirector::Terminus::TestTerminusType < Puppet::Indirector::Terminus end end after :each do Puppet::Indirector::Terminus.send(:remove_const, :TestTerminusType) end let :subclass do Puppet::Indirector::Terminus::TestTerminusType end it "should set the name of the abstract subclass to be its class constant" do expect(subclass.name).to eq(:test_terminus_type) end it "should mark abstract terminus types as such" do expect(subclass).to be_abstract_terminus end it "should not allow instances of abstract subclasses to be created" do expect { subclass.new }.to raise_error(Puppet::DevError) end end describe "when listing terminus classes" do it "should list the terminus files available to load" do allow_any_instance_of(Puppet::Util::Autoload).to receive(:files_to_load).and_return(["/foo/bar/baz", "/max/runs/marathon"]) expect(Puppet::Indirector::Terminus.terminus_classes('my_stuff')).to eq([:baz, :marathon]) end end describe "when validating a request" do let :request do Puppet::Indirector::Request.new(indirection.name, :find, "the_key", instance) end describe "`instance.name` does not match the key in the request" do let(:instance) { model.new("wrong_key") } it "raises an error " do expect { terminus.validate(request) }.to raise_error( Puppet::Indirector::ValidationError, /Instance name .* does not match requested key/ ) end end describe "`instance` is not an instance of the model class" do let(:instance) { double("instance") } it "raises an error" do expect { terminus.validate(request) }.to raise_error( Puppet::Indirector::ValidationError, /Invalid instance type/ ) end end describe "the instance key and class match the request key and model class" do let(:instance) { model.new("the_key") } it "passes" do terminus.validate(request) 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/indirector/indirection_spec.rb
spec/unit/indirector/indirection_spec.rb
require 'spec_helper' require 'puppet/indirector/indirection' shared_examples_for "Indirection Delegator" do it "should create a request object with the appropriate method name and all of the passed arguments" do request = Puppet::Indirector::Request.new(:indirection, :find, "me", nil) expect(@indirection).to receive(:request).with(@method, "mystuff", nil, {:one => :two}).and_return(request) allow(@terminus).to receive(@method) @indirection.send(@method, "mystuff", :one => :two) end it "should choose the terminus returned by the :terminus_class" do expect(@indirection).to receive(:terminus_class).and_return(:test_terminus) expect(@terminus).to receive(@method) @indirection.send(@method, "me") end it "should let the appropriate terminus perform the lookup" do expect(@terminus).to receive(@method).with(be_a(Puppet::Indirector::Request)) @indirection.send(@method, "me") end end shared_examples_for "Delegation Authorizer" do before do # So the :respond_to? turns out correctly. class << @terminus def authorized? end end end it "should not check authorization if a node name is not provided" do expect(@terminus).not_to receive(:authorized?) allow(@terminus).to receive(@method) # The parenthesis are necessary here, else it looks like a block. allow(@request).to receive(:options).and_return({}) @indirection.send(@method, "/my/key") end it "should pass the request to the terminus's authorization method" do expect(@terminus).to receive(:authorized?).with(be_a(Puppet::Indirector::Request)).and_return(true) allow(@terminus).to receive(@method) @indirection.send(@method, "/my/key", :node => "mynode") end it "should fail if authorization returns false" do expect(@terminus).to receive(:authorized?).and_return(false) allow(@terminus).to receive(@method) expect { @indirection.send(@method, "/my/key", :node => "mynode") }.to raise_error(ArgumentError) end it "should continue if authorization returns true" do expect(@terminus).to receive(:authorized?).and_return(true) allow(@terminus).to receive(@method) @indirection.send(@method, "/my/key", :node => "mynode") end end shared_examples_for "Request validator" do it "asks the terminus to validate the request" do expect(@terminus).to receive(:validate).and_raise(Puppet::Indirector::ValidationError, "Invalid") expect(@terminus).not_to receive(@method) expect { @indirection.send(@method, "key") }.to raise_error Puppet::Indirector::ValidationError end end describe Puppet::Indirector::Indirection do describe "when initializing" do it "should keep a reference to the indirecting model" do model = double('model') @indirection = Puppet::Indirector::Indirection.new(model, :myind) expect(@indirection.model).to equal(model) end it "should set the name" do @indirection = Puppet::Indirector::Indirection.new(double('model'), :myind) expect(@indirection.name).to eq(:myind) end it "should require indirections to have unique names" do @indirection = Puppet::Indirector::Indirection.new(double('model'), :test) expect { Puppet::Indirector::Indirection.new(:test) }.to raise_error(ArgumentError) end it "should extend itself with any specified module" do mod = Module.new @indirection = Puppet::Indirector::Indirection.new(double('model'), :test, :extend => mod) expect(@indirection.singleton_class.included_modules).to include(mod) end after do @indirection.delete if defined?(@indirection) end end describe "when an instance" do before :each do @terminus_class = double('terminus_class') @terminus = double('terminus') allow(@terminus).to receive(:validate) allow(@terminus_class).to receive(:new).and_return(@terminus) @cache = double('cache', :name => "mycache") @cache_class = double('cache_class') allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :cache_terminus).and_return(@cache_class) allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :test_terminus).and_return(@terminus_class) @indirection = Puppet::Indirector::Indirection.new(double('model'), :test) @indirection.terminus_class = :test_terminus @instance = double('instance', :expiration => nil, :expiration= => nil, :name => "whatever") @name = :mything @request = double('instance') end describe 'ensure that indirection settings are threadsafe' do before :each do @alt_term = double('alternate_terminus') expect(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :alternate_terminus).and_return(@alt_term) @alt_cache= double('alternate_cache') expect(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :alternate_cache).and_return(@alt_cache) end it 'does not change the original value when modified in new thread' do Thread.new do @indirection.terminus_class = :alternate_terminus @indirection.terminus_setting = :alternate_terminus_setting @indirection.cache_class = :alternate_cache end.join expect(@indirection.terminus_class).to eq(:test_terminus) expect(@indirection.terminus_setting).to eq(nil) expect(@indirection.cache_class).to eq(nil) end it 'can modify indirection settings globally for all threads using the global setter' do Thread.new do @indirection.set_global_setting(:terminus_class, :alternate_terminus) @indirection.set_global_setting(:terminus_setting, :alternate_terminus_setting) @indirection.set_global_setting(:cache_class, :alternate_cache) end.join expect(@indirection.terminus_class).to eq(:alternate_terminus) expect(@indirection.terminus_setting).to eq(:alternate_terminus_setting) expect(@indirection.cache_class).to eq(:alternate_cache) end end it "should allow setting the ttl" do @indirection.ttl = 300 expect(@indirection.ttl).to eq(300) end it "should default to the :runinterval setting, converted to an integer, for its ttl" do Puppet[:runinterval] = 1800 expect(@indirection.ttl).to eq(1800) end it "should calculate the current expiration by adding the TTL to the current time" do allow(@indirection).to receive(:ttl).and_return(100) now = Time.now allow(Time).to receive(:now).and_return(now) expect(@indirection.expiration).to eq(Time.now + 100) end it "should have a method for creating an indirection request instance" do expect(@indirection).to respond_to(:request) end describe "creates a request" do it "should create it with its name as the request's indirection name" do expect(@indirection.request(:funtest, "yayness", nil).indirection_name).to eq(@indirection.name) end it "should require a method and key" do request = @indirection.request(:funtest, "yayness", nil) expect(request.method).to eq(:funtest) expect(request.key).to eq("yayness") end it "should support optional arguments" do expect(@indirection.request(:funtest, "yayness", nil, :one => :two).options).to eq(:one => :two) end it "should not pass options if none are supplied" do expect(@indirection.request(:funtest, "yayness", nil).options).to eq({}) end it "should return the request" do expect(@indirection.request(:funtest, "yayness", nil)).to be_a(Puppet::Indirector::Request) end end describe "and looking for a model instance" do before { @method = :find } it_should_behave_like "Indirection Delegator" it_should_behave_like "Delegation Authorizer" it_should_behave_like "Request validator" it "should return the results of the delegation" do expect(@terminus).to receive(:find).and_return(@instance) expect(@indirection.find("me")).to equal(@instance) end it "should return false if the instance is false" do expect(@terminus).to receive(:find).and_return(false) expect(@indirection.find("me")).to equal(false) end it "should set the expiration date on any instances without one set" do allow(@terminus).to receive(:find).and_return(@instance) expect(@indirection).to receive(:expiration).and_return(:yay) expect(@instance).to receive(:expiration).and_return(nil) expect(@instance).to receive(:expiration=).with(:yay) @indirection.find("/my/key") end it "should not override an already-set expiration date on returned instances" do allow(@terminus).to receive(:find).and_return(@instance) expect(@indirection).not_to receive(:expiration) expect(@instance).to receive(:expiration).and_return(:yay) expect(@instance).not_to receive(:expiration=) @indirection.find("/my/key") end it "should filter the result instance if the terminus supports it" do allow(@terminus).to receive(:find).and_return(@instance) allow(@terminus).to receive(:respond_to?).with(:filter).and_return(true) expect(@terminus).to receive(:filter).with(@instance) @indirection.find("/my/key") end describe "when caching is enabled" do before do @indirection.cache_class = :cache_terminus allow(@cache_class).to receive(:new).and_return(@cache) allow(@instance).to receive(:expired?).and_return(false) end it "should first look in the cache for an instance" do expect(@terminus).not_to receive(:find) expect(@cache).to receive(:find).and_return(@instance) @indirection.find("/my/key") end it "should not look in the cache if the request specifies not to use the cache" do expect(@terminus).to receive(:find).and_return(@instance) expect(@cache).not_to receive(:find) allow(@cache).to receive(:save) @indirection.find("/my/key", :ignore_cache => true) end it "should still save to the cache even if the cache is being ignored during readin" do expect(@terminus).to receive(:find).and_return(@instance) expect(@cache).to receive(:save) @indirection.find("/my/key", :ignore_cache => true) end it "should not save to the cache if told to skip updating the cache" do expect(@terminus).to receive(:find).and_return(@instance) expect(@cache).to receive(:find).and_return(nil) expect(@cache).not_to receive(:save) @indirection.find("/my/key", :ignore_cache_save => true) end it "should only look in the cache if the request specifies not to use the terminus" do expect(@terminus).not_to receive(:find) expect(@cache).to receive(:find) @indirection.find("/my/key", :ignore_terminus => true) end it "should use a request to look in the cache for cached objects" do expect(@cache).to receive(:find) do |r| expect(r.method).to eq(:find) expect(r.key).to eq("/my/key") @instance end allow(@cache).to receive(:save) @indirection.find("/my/key") end it "should return the cached object if it is not expired" do allow(@instance).to receive(:expired?).and_return(false) allow(@cache).to receive(:find).and_return(@instance) expect(@indirection.find("/my/key")).to equal(@instance) end it "should not fail if the cache fails" do allow(@terminus).to receive(:find).and_return(@instance) expect(@cache).to receive(:find).and_raise(ArgumentError) allow(@cache).to receive(:save) expect { @indirection.find("/my/key") }.not_to raise_error end it "should look in the main terminus if the cache fails" do expect(@terminus).to receive(:find).and_return(@instance) expect(@cache).to receive(:find).and_raise(ArgumentError) allow(@cache).to receive(:save) expect(@indirection.find("/my/key")).to equal(@instance) end it "should send a debug log if it is using the cached object" do expect(Puppet).to receive(:debug) allow(@cache).to receive(:find).and_return(@instance) @indirection.find("/my/key") end it "should not return the cached object if it is expired" do allow(@instance).to receive(:expired?).and_return(true) allow(@cache).to receive(:find).and_return(@instance) allow(@terminus).to receive(:find).and_return(nil) expect(@indirection.find("/my/key")).to be_nil end it "should send an info log if it is using the cached object" do expect(Puppet).to receive(:info) allow(@instance).to receive(:expired?).and_return(true) allow(@cache).to receive(:find).and_return(@instance) allow(@terminus).to receive(:find).and_return(nil) @indirection.find("/my/key") end it "should cache any objects not retrieved from the cache" do expect(@cache).to receive(:find).and_return(nil) expect(@terminus).to receive(:find).and_return(@instance) expect(@cache).to receive(:save) @indirection.find("/my/key") end it "should use a request to look in the cache for cached objects" do expect(@cache).to receive(:find) do |r| expect(r.method).to eq(:find) expect(r.key).to eq("/my/key") nil end allow(@terminus).to receive(:find).and_return(@instance) allow(@cache).to receive(:save) @indirection.find("/my/key") end it "should cache the instance using a request with the instance set to the cached object" do allow(@cache).to receive(:find).and_return(nil) allow(@terminus).to receive(:find).and_return(@instance) expect(@cache).to receive(:save) do |r| expect(r.method).to eq(:save) expect(r.instance).to eq(@instance) end @indirection.find("/my/key") end it "should send an info log that the object is being cached" do allow(@cache).to receive(:find).and_return(nil) allow(@terminus).to receive(:find).and_return(@instance) allow(@cache).to receive(:save) expect(Puppet).to receive(:info) @indirection.find("/my/key") end it "should fail if saving to the cache fails but log the exception" do allow(@cache).to receive(:find).and_return(nil) allow(@terminus).to receive(:find).and_return(@instance) allow(@cache).to receive(:save).and_raise(RuntimeError) expect(Puppet).to receive(:log_exception) expect { @indirection.find("/my/key") }.to raise_error RuntimeError end end end describe "and doing a head operation" do before { @method = :head } it_should_behave_like "Indirection Delegator" it_should_behave_like "Delegation Authorizer" it_should_behave_like "Request validator" it "should return true if the head method returned true" do expect(@terminus).to receive(:head).and_return(true) expect(@indirection.head("me")).to eq(true) end it "should return false if the head method returned false" do expect(@terminus).to receive(:head).and_return(false) expect(@indirection.head("me")).to eq(false) end describe "when caching is enabled" do before do @indirection.cache_class = :cache_terminus allow(@cache_class).to receive(:new).and_return(@cache) allow(@instance).to receive(:expired?).and_return(false) end it "should first look in the cache for an instance" do expect(@terminus).not_to receive(:find) expect(@terminus).not_to receive(:head) expect(@cache).to receive(:find).and_return(@instance) expect(@indirection.head("/my/key")).to eq(true) end it "should not save to the cache" do expect(@cache).to receive(:find).and_return(nil) expect(@cache).not_to receive(:save) expect(@terminus).to receive(:head).and_return(true) expect(@indirection.head("/my/key")).to eq(true) end it "should not fail if the cache fails" do allow(@terminus).to receive(:head).and_return(true) expect(@cache).to receive(:find).and_raise(ArgumentError) expect { @indirection.head("/my/key") }.not_to raise_error end it "should look in the main terminus if the cache fails" do expect(@terminus).to receive(:head).and_return(true) expect(@cache).to receive(:find).and_raise(ArgumentError) expect(@indirection.head("/my/key")).to eq(true) end it "should send a debug log if it is using the cached object" do expect(Puppet).to receive(:debug) allow(@cache).to receive(:find).and_return(@instance) @indirection.head("/my/key") end it "should not accept the cached object if it is expired" do allow(@instance).to receive(:expired?).and_return(true) allow(@cache).to receive(:find).and_return(@instance) allow(@terminus).to receive(:head).and_return(false) expect(@indirection.head("/my/key")).to eq(false) end end end describe "and storing a model instance" do before { @method = :save } it "should return the result of the save" do allow(@terminus).to receive(:save).and_return("foo") expect(@indirection.save(@instance)).to eq("foo") end describe "when caching is enabled" do before do @indirection.cache_class = :cache_terminus allow(@cache_class).to receive(:new).and_return(@cache) allow(@instance).to receive(:expired?).and_return(false) end it "should return the result of saving to the terminus" do request = double('request', :instance => @instance, :node => nil, :ignore_cache_save? => false, :ignore_terminus? => false) expect(@indirection).to receive(:request).and_return(request) allow(@cache).to receive(:save) allow(@terminus).to receive(:save).and_return(@instance) expect(@indirection.save(@instance)).to equal(@instance) end it "should use a request to save the object to the cache" do request = double('request', :instance => @instance, :node => nil, :ignore_cache_save? => false, :ignore_terminus? => false) expect(@indirection).to receive(:request).and_return(request) expect(@cache).to receive(:save).with(request) allow(@terminus).to receive(:save) @indirection.save(@instance) end it "should not save to the cache if the normal save fails" do request = double('request', :instance => @instance, :node => nil, :ignore_terminus? => false) expect(@indirection).to receive(:request).and_return(request) expect(@cache).not_to receive(:save) expect(@terminus).to receive(:save).and_raise("eh") expect { @indirection.save(@instance) }.to raise_error(RuntimeError, /eh/) end it "should not save to the cache if told to ignore saving to the cache" do expect(@terminus).to receive(:save) expect(@cache).not_to receive(:save) @indirection.save(@instance, '/my/key', :ignore_cache_save => true) end it "should only save to the cache if the request specifies not to use the terminus" do expect(@terminus).not_to receive(:save) expect(@cache).to receive(:save) @indirection.save(@instance, "/my/key", :ignore_terminus => true) end end end describe "and removing a model instance" do before { @method = :destroy } it_should_behave_like "Indirection Delegator" it_should_behave_like "Delegation Authorizer" it_should_behave_like "Request validator" it "should return the result of removing the instance" do allow(@terminus).to receive(:destroy).and_return("yayness") expect(@indirection.destroy("/my/key")).to eq("yayness") end describe "when caching is enabled" do before do @indirection.cache_class = :cache_terminus expect(@cache_class).to receive(:new).and_return(@cache) allow(@instance).to receive(:expired?).and_return(false) end it "should use a request instance to search in and remove objects from the cache" do destroy = double('destroy_request', :key => "/my/key", :node => nil) find = double('destroy_request', :key => "/my/key", :node => nil) expect(@indirection).to receive(:request).with(:destroy, "/my/key", nil, be_a(Hash).or(be_nil)).and_return(destroy) expect(@indirection).to receive(:request).with(:find, "/my/key", nil, be_a(Hash).or(be_nil)).and_return(find) cached = double('cache') expect(@cache).to receive(:find).with(find).and_return(cached) expect(@cache).to receive(:destroy).with(destroy) allow(@terminus).to receive(:destroy) @indirection.destroy("/my/key") end end end describe "and searching for multiple model instances" do before { @method = :search } it_should_behave_like "Indirection Delegator" it_should_behave_like "Delegation Authorizer" it_should_behave_like "Request validator" it "should set the expiration date on any instances without one set" do allow(@terminus).to receive(:search).and_return([@instance]) expect(@indirection).to receive(:expiration).and_return(:yay) expect(@instance).to receive(:expiration).and_return(nil) expect(@instance).to receive(:expiration=).with(:yay) @indirection.search("/my/key") end it "should not override an already-set expiration date on returned instances" do allow(@terminus).to receive(:search).and_return([@instance]) expect(@indirection).not_to receive(:expiration) expect(@instance).to receive(:expiration).and_return(:yay) expect(@instance).not_to receive(:expiration=) @indirection.search("/my/key") end it "should return the results of searching in the terminus" do expect(@terminus).to receive(:search).and_return([@instance]) expect(@indirection.search("/my/key")).to eq([@instance]) end end describe "and expiring a model instance" do describe "when caching is not enabled" do it "should do nothing" do expect(@cache_class).not_to receive(:new) @indirection.expire("/my/key") end end describe "when caching is enabled" do before do @indirection.cache_class = :cache_terminus expect(@cache_class).to receive(:new).and_return(@cache) allow(@instance).to receive(:expired?).and_return(false) @cached = double('cached', :expiration= => nil, :name => "/my/key") end it "should use a request to find within the cache" do expect(@cache).to receive(:find) do |r| expect(r).to be_a(Puppet::Indirector::Request) expect(r.method).to eq(:find) nil end @indirection.expire("/my/key") end it "should do nothing if no such instance is cached" do expect(@cache).to receive(:find).and_return(nil) @indirection.expire("/my/key") end it "should log when expiring a found instance" do expect(@cache).to receive(:find).and_return(@cached) allow(@cache).to receive(:save) expect(Puppet).to receive(:info) @indirection.expire("/my/key") end it "should set the cached instance's expiration to a time in the past" do expect(@cache).to receive(:find).and_return(@cached) allow(@cache).to receive(:save) expect(@cached).to receive(:expiration=).with(be < Time.now) @indirection.expire("/my/key") end it "should save the now expired instance back into the cache" do expect(@cache).to receive(:find).and_return(@cached) expect(@cached).to receive(:expiration=).with(be < Time.now) expect(@cache).to receive(:save) @indirection.expire("/my/key") end it "does not expire an instance if told to skip cache saving" do expect(@indirection.cache).not_to receive(:find) expect(@indirection.cache).not_to receive(:save) @indirection.expire("/my/key", :ignore_cache_save => true) end it "should use a request to save the expired resource to the cache" do expect(@cache).to receive(:find).and_return(@cached) expect(@cached).to receive(:expiration=).with(be < Time.now) expect(@cache).to receive(:save) do |r| expect(r).to be_a(Puppet::Indirector::Request) expect(r.instance).to eq(@cached) expect(r.method).to eq(:save) @cached end @indirection.expire("/my/key") end end end after :each do @indirection.delete end end describe "when managing indirection instances" do it "should allow an indirection to be retrieved by name" do @indirection = Puppet::Indirector::Indirection.new(double('model'), :test) expect(Puppet::Indirector::Indirection.instance(:test)).to equal(@indirection) end it "should return nil when the named indirection has not been created" do expect(Puppet::Indirector::Indirection.instance(:test)).to be_nil end it "should allow an indirection's model to be retrieved by name" do mock_model = double('model') @indirection = Puppet::Indirector::Indirection.new(mock_model, :test) expect(Puppet::Indirector::Indirection.model(:test)).to equal(mock_model) end it "should return nil when no model matches the requested name" do expect(Puppet::Indirector::Indirection.model(:test)).to be_nil end after do @indirection.delete if defined?(@indirection) end end describe "when routing to the correct the terminus class" do before do @indirection = Puppet::Indirector::Indirection.new(double('model'), :test) @terminus = double('terminus') @terminus_class = double('terminus class', :new => @terminus) allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :default).and_return(@terminus_class) end it "should fail if no terminus class can be picked" do expect { @indirection.terminus_class }.to raise_error(Puppet::DevError) end it "should choose the default terminus class if one is specified" do @indirection.terminus_class = :default expect(@indirection.terminus_class).to equal(:default) end it "should use the provided Puppet setting if told to do so" do allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :my_terminus).and_return(double("terminus_class2")) Puppet[:node_terminus] = :my_terminus @indirection.terminus_setting = :node_terminus expect(@indirection.terminus_class).to equal(:my_terminus) end it "should fail if the provided terminus class is not valid" do allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :nosuchclass).and_return(nil) expect { @indirection.terminus_class = :nosuchclass }.to raise_error(ArgumentError) end after do @indirection.delete if defined?(@indirection) end end describe "when specifying the terminus class to use" do before do @indirection = Puppet::Indirector::Indirection.new(double('model'), :test) @terminus = double('terminus') allow(@terminus).to receive(:validate) @terminus_class = double('terminus class', :new => @terminus) end it "should allow specification of a terminus type" do expect(@indirection).to respond_to(:terminus_class=) end it "should fail to redirect if no terminus type has been specified" do expect { @indirection.find("blah") }.to raise_error(Puppet::DevError) end it "should fail when the terminus class name is an empty string" do expect { @indirection.terminus_class = "" }.to raise_error(ArgumentError) end it "should fail when the terminus class name is nil" do expect { @indirection.terminus_class = nil }.to raise_error(ArgumentError) end it "should fail when the specified terminus class cannot be found" do expect(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :foo).and_return(nil) expect { @indirection.terminus_class = :foo }.to raise_error(ArgumentError) end it "should select the specified terminus class if a terminus class name is provided" do expect(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :foo).and_return(@terminus_class) expect(@indirection.terminus(:foo)).to equal(@terminus) end it "should use the configured terminus class if no terminus name is specified" do allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :foo).and_return(@terminus_class) @indirection.terminus_class = :foo expect(@indirection.terminus).to equal(@terminus) end after do @indirection.delete if defined?(@indirection) end end describe "when managing terminus instances" do before do @indirection = Puppet::Indirector::Indirection.new(double('model'), :test) @terminus = double('terminus') @terminus_class = double('terminus class') allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :foo).and_return(@terminus_class) end it "should create an instance of the chosen terminus class" do allow(@terminus_class).to receive(:new).and_return(@terminus) expect(@indirection.terminus(:foo)).to equal(@terminus) end # Make sure it caches the terminus. it "should return the same terminus instance each time for a given name" do allow(@terminus_class).to receive(:new).and_return(@terminus) expect(@indirection.terminus(:foo)).to equal(@terminus) expect(@indirection.terminus(:foo)).to equal(@terminus) end it "should not create a terminus instance until one is actually needed" do expect(@indirection).not_to receive(:terminus) Puppet::Indirector::Indirection.new(double('model'), :lazytest) end after do @indirection.delete end end describe "when deciding whether to cache" do before do @indirection = Puppet::Indirector::Indirection.new(double('model'), :test) @terminus = double('terminus') @terminus_class = double('terminus class') allow(@terminus_class).to receive(:new).and_return(@terminus) allow(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :foo).and_return(@terminus_class) @indirection.terminus_class = :foo end it "should provide a method for setting the cache terminus class" do expect(@indirection).to respond_to(:cache_class=) end it "should fail to cache if no cache type has been specified" do expect { @indirection.cache }.to raise_error(Puppet::DevError) end it "should fail to set the cache class when the cache class name is an empty string" do expect { @indirection.cache_class = "" }.to raise_error(ArgumentError) end it "should allow resetting the cache_class to nil" do @indirection.cache_class = nil expect(@indirection.cache_class).to be_nil end it "should fail to set the cache class when the specified cache class cannot be found" do expect(Puppet::Indirector::Terminus).to receive(:terminus_class).with(:test, :foo).and_return(nil) expect { @indirection.cache_class = :foo }.to raise_error(ArgumentError) end after do @indirection.delete end end describe "when using a cache" do before :each do
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/yaml_spec.rb
spec/unit/indirector/yaml_spec.rb
require 'spec_helper' require 'puppet/indirector/yaml' describe Puppet::Indirector::Yaml do include PuppetSpec::Files before(:all) do class Puppet::YamlTestModel extend Puppet::Indirector indirects :yaml_test_model attr_reader :name def initialize(name) @name = name end end class Puppet::YamlTestModel::Yaml < Puppet::Indirector::Yaml; end Puppet::YamlTestModel.indirection.terminus_class = :yaml end after(:all) do Puppet::YamlTestModel.indirection.delete Puppet.send(:remove_const, :YamlTestModel) end let(:model) { Puppet::YamlTestModel } let(:subject) { model.new(:me) } let(:indirection) { model.indirection } let(:terminus) { indirection.terminus(:yaml) } let(:dir) { tmpdir("yaml_indirector") } let(:indirection_dir) { File.join(dir, indirection.name.to_s) } let(:serverdir) { File.expand_path("/server/yaml/dir") } let(:clientdir) { File.expand_path("/client/yaml/dir") } before :each do Puppet[:clientyamldir] = dir allow(Puppet.run_mode).to receive(:server?).and_return(false) end describe "when choosing file location" do it "should use the server_datadir if the run_mode is server" do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:yamldir] = serverdir expect(terminus.path(:me)).to match(/^#{serverdir}/) end it "should use the client yamldir if the run_mode is not server" do allow(Puppet.run_mode).to receive(:server?).and_return(false) Puppet[:clientyamldir] = clientdir expect(terminus.path(:me)).to match(/^#{clientdir}/) end it "should use the extension if one is specified" do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:yamldir] = serverdir expect(terminus.path(:me,'.farfignewton')).to match(%r{\.farfignewton$}) end it "should assume an extension of .yaml if none is specified" do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:yamldir] = serverdir expect(terminus.path(:me)).to match(%r{\.yaml$}) end it "should store all files in a single file root set in the Puppet defaults" do expect(terminus.path(:me)).to match(%r{^#{dir}}) end it "should use the terminus name for choosing the subdirectory" do expect(terminus.path(:me)).to match(%r{^#{dir}/yaml_test_model}) end it "should use the object's name to determine the file name" do expect(terminus.path(:me)).to match(%r{me.yaml$}) end ['../foo', '..\\foo', './../foo', '.\\..\\foo', '/foo', '//foo', '\\foo', '\\\\goo', "test\0/../bar", "test\0\\..\\bar", "..\\/bar", "/tmp/bar", "/tmp\\bar", "tmp\\bar", " / bar", " /../ bar", " \\..\\ bar", "c:\\foo", "c:/foo", "\\\\?\\UNC\\bar", "\\\\foo\\bar", "\\\\?\\c:\\foo", "//?/UNC/bar", "//foo/bar", "//?/c:/foo", ].each do |input| it "should resist directory traversal attacks (#{input.inspect})" do expect { terminus.path(input) }.to raise_error(ArgumentError) end end end describe "when storing objects as YAML" do it "should only store objects that respond to :name" do request = indirection.request(:save, "testing", Object.new) expect { terminus.save(request) }.to raise_error(ArgumentError) end end describe "when retrieving YAML" do it "should read YAML in from disk and convert it to Ruby objects" do terminus.save(indirection.request(:save, "testing", subject)) yaml = terminus.find(indirection.request(:find, "testing", nil)) expect(yaml.name).to eq(:me) end it "should fail coherently when the stored YAML is invalid" do terminus.save(indirection.request(:save, "testing", subject)) # overwrite file File.open(terminus.path('testing'), "w") do |file| file.puts "{ invalid" end expect { terminus.find(indirection.request(:find, "testing", nil)) }.to raise_error(Puppet::Error, /Could not parse YAML data/) end end describe "when searching" do before :each do Puppet[:clientyamldir] = dir end def dir_containing_instances(instances) Dir.mkdir(indirection_dir) instances.each do |hash| File.open(File.join(indirection_dir, "#{hash['name']}.yaml"), 'wb') do |f| f.write(YAML.dump(hash)) end end end it "should return an array of fact instances with one instance for each file when globbing *" do one = { 'name' => 'one', 'values' => { 'foo' => 'bar' } } two = { 'name' => 'two', 'values' => { 'foo' => 'baz' } } dir_containing_instances([one, two]) request = indirection.request(:search, "*", nil) expect(terminus.search(request)).to contain_exactly(one, two) end it "should return an array containing a single instance of fact when globbing 'one*'" do one = { 'name' => 'one', 'values' => { 'foo' => 'bar' } } two = { 'name' => 'two', 'values' => { 'foo' => 'baz' } } dir_containing_instances([one, two]) request = indirection.request(:search, "one*", nil) expect(terminus.search(request)).to eq([one]) end it "should return an empty array when the glob doesn't match anything" do one = { 'name' => 'one', 'values' => { 'foo' => 'bar' } } dir_containing_instances([one]) request = indirection.request(:search, "f*ilglobcanfail*", nil) expect(terminus.search(request)).to eq([]) end describe "when destroying" do let(:path) { File.join(indirection_dir, "one.yaml") } before :each do Puppet[:clientyamldir] = dir one = { 'name' => 'one', 'values' => { 'foo' => 'bar' } } dir_containing_instances([one]) end it "should unlink the right yaml file if it exists" do request = indirection.request(:destroy, "one", nil) terminus.destroy(request) expect(Puppet::FileSystem).to_not exist(path) end it "should not unlink the yaml file if it does not exists" do request = indirection.request(:destroy, "doesntexist", nil) terminus.destroy(request) expect(Puppet::FileSystem).to exist(path) 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/indirector/exec_spec.rb
spec/unit/indirector/exec_spec.rb
require 'spec_helper' require 'puppet/indirector/exec' describe Puppet::Indirector::Exec do before :all do class Puppet::ExecTestModel extend Puppet::Indirector indirects :exec_test_model end class Puppet::ExecTestModel::Exec < Puppet::Indirector::Exec attr_accessor :command end Puppet::ExecTestModel.indirection.terminus_class = :exec end after(:all) do Puppet::ExecTestModel.indirection.delete Puppet.send(:remove_const, :ExecTestModel) end let(:terminus) { Puppet::ExecTestModel.indirection.terminus(:exec) } let(:indirection) { Puppet::ExecTestModel.indirection } let(:model) { Puppet::ExecTestModel } let(:path) { File.expand_path('/echo') } let(:arguments) { {:failonfail => true, :combine => false } } before(:each) { terminus.command = [path] } it "should throw an exception if the command is not an array" do terminus.command = path expect { indirection.find('foo') }.to raise_error(Puppet::DevError) end it "should throw an exception if the command is not fully qualified" do terminus.command = ["mycommand"] expect { indirection.find('foo') }.to raise_error(ArgumentError) end it "should execute the command with the object name as the only argument" do expect(terminus).to receive(:execute).with([path, 'foo'], arguments) indirection.find('foo') end it "should return the output of the script" do expect(terminus).to receive(:execute).with([path, 'foo'], arguments).and_return("whatever") expect(indirection.find('foo')).to eq("whatever") end it "should return nil when the command produces no output" do expect(terminus).to receive(:execute).with([path, 'foo'], arguments).and_return(nil) expect(indirection.find('foo')).to be_nil end it "should raise an exception if there's an execution failure" do expect(terminus).to receive(:execute).with([path, 'foo'], arguments).and_raise(Puppet::ExecutionFailure.new("message")) expect { indirection.find('foo') }.to raise_exception(Puppet::Error, 'Failed to find foo via exec: message') 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/indirector/memory_spec.rb
spec/unit/indirector/memory_spec.rb
require 'spec_helper' require 'puppet/indirector/memory' require 'shared_behaviours/memory_terminus' describe Puppet::Indirector::Memory do it_should_behave_like "A Memory Terminus" before do allow(Puppet::Indirector::Terminus).to receive(:register_terminus_class) @model = double('model') @indirection = double('indirection', :name => :mystuff, :register_terminus_type => nil, :model => @model) allow(Puppet::Indirector::Indirection).to receive(:instance).and_return(@indirection) module Testing; end @memory_class = class Testing::MyMemory < Puppet::Indirector::Memory self end @searcher = @memory_class.new @name = "me" @instance = double('instance', :name => @name) @request = double('request', :key => @name, :instance => @instance) 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/indirector/catalog/rest_spec.rb
spec/unit/indirector/catalog/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/catalog/rest' describe Puppet::Resource::Catalog::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/catalog/ziggy} } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } let(:catalog) { Puppet::Resource::Catalog.new(certname) } before :each do Puppet[:server] = 'compiler.example.com' Puppet[:serverport] = 8140 described_class.indirection.terminus_class = :rest end def catalog_response(catalog) { body: formatter.render(catalog), headers: {'Content-Type' => formatter.mime } } end it 'finds a catalog' do stub_request(:post, uri).to_return(**catalog_response(catalog)) expect(described_class.indirection.find(certname)).to be_a(Puppet::Resource::Catalog) end it 'logs a notice when requesting a catalog' do expect(Puppet).to receive(:notice).with("Requesting catalog from compiler.example.com:8140") stub_request(:post, uri).to_return(**catalog_response(catalog)) described_class.indirection.find(certname) end it 'logs a notice when the IP address is resolvable when requesting a catalog' do allow(Resolv).to receive_message_chain(:getaddress).and_return('192.0.2.0') expect(Puppet).to receive(:notice).with("Requesting catalog from compiler.example.com:8140 (192.0.2.0)") stub_request(:post, uri).to_return(**catalog_response(catalog)) described_class.indirection.find(certname) end it "serializes the environment" do stub_request(:post, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(**catalog_response(catalog)) described_class.indirection.find(certname, environment: Puppet::Node::Environment.remote('outerspace')) end it "passes 'check_environment'" do stub_request(:post, uri) .with(body: hash_including('check_environment' => 'true')) .to_return(**catalog_response(catalog)) described_class.indirection.find(certname, check_environment: true) end it 'constructs a catalog environment_instance' do env = Puppet::Node::Environment.remote('outerspace') catalog = Puppet::Resource::Catalog.new(certname, env) stub_request(:post, uri).to_return(**catalog_response(catalog)) expect(described_class.indirection.find(certname).environment_instance).to eq(env) end it 'returns nil if the node does not exist' do stub_request(:post, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect(described_class.indirection.find(certname)).to be_nil end it 'raises if fail_on_404 is specified' do stub_request(:post, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect{ described_class.indirection.find(certname, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/catalog/ziggy resulted in 404 with the message: {}}) end it 'raises Net::HTTPError on 500' do stub_request(:post, uri).to_return(status: 500) expect{ described_class.indirection.find(certname) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) 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/indirector/catalog/msgpack_spec.rb
spec/unit/indirector/catalog/msgpack_spec.rb
require 'spec_helper' require 'puppet/resource/catalog' require 'puppet/indirector/catalog/msgpack' describe Puppet::Resource::Catalog::Msgpack, :if => Puppet.features.msgpack? do # This is it for local functionality: we don't *do* anything else. it "should be registered with the catalog store indirection" do expect(Puppet::Resource::Catalog.indirection.terminus(:msgpack)). to be_an_instance_of 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/indirector/catalog/store_configs_spec.rb
spec/unit/indirector/catalog/store_configs_spec.rb
require 'spec_helper' require 'puppet/node' require 'puppet/indirector/memory' require 'puppet/indirector/catalog/store_configs' class Puppet::Resource::Catalog::StoreConfigsTesting < Puppet::Indirector::Memory end describe Puppet::Resource::Catalog::StoreConfigs do after :each do Puppet::Resource::Catalog.indirection.reset_terminus_class Puppet::Resource::Catalog.indirection.cache_class = nil end it_should_behave_like "a StoreConfigs terminus" end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/catalog/json_spec.rb
spec/unit/indirector/catalog/json_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/resource/catalog' require 'puppet/indirector/catalog/json' describe Puppet::Resource::Catalog::Json do include PuppetSpec::Files # This is it for local functionality it "should be registered with the catalog store indirection" do expect(Puppet::Resource::Catalog.indirection.terminus(:json)). to be_an_instance_of described_class end describe "when handling requests" do let(:binary) { "\xC0\xFF".force_encoding(Encoding::BINARY) } let(:key) { 'foo' } let(:file) { subject.path(key) } let(:env) { Puppet::Node::Environment.create(:testing, []) } let(:catalog) do catalog = Puppet::Resource::Catalog.new(key, env) catalog.add_resource(Puppet::Resource.new(:file, '/tmp/a_file', :parameters => { :content => binary })) catalog end before :each do allow(Puppet.run_mode).to receive(:server?).and_return(true) Puppet[:server_datadir] = tmpdir('jsondir') FileUtils.mkdir_p(File.join(Puppet[:server_datadir], 'indirector_testing')) Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env)) end after :each do Puppet.pop_context() end it 'saves a catalog containing binary content' do request = subject.indirection.request(:save, key, catalog) subject.save(request) end it 'finds a catalog containing binary content' do request = subject.indirection.request(:save, key, catalog) subject.save(request) request = subject.indirection.request(:find, key, nil) parsed_catalog = subject.find(request) content = parsed_catalog.resource(:file, '/tmp/a_file')[:content] expect(content.binary_buffer.bytes.to_a).to eq(binary.bytes.to_a) end it 'searches for catalogs contains binary content' do request = subject.indirection.request(:save, key, catalog) subject.save(request) request = subject.indirection.request(:search, '*', nil) parsed_catalogs = subject.search(request) expect(parsed_catalogs.size).to eq(1) content = parsed_catalogs.first.resource(:file, '/tmp/a_file')[:content] expect(content.binary_buffer.bytes.to_a).to eq(binary.bytes.to_a) 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/indirector/catalog/yaml_spec.rb
spec/unit/indirector/catalog/yaml_spec.rb
require 'spec_helper' require 'puppet/resource/catalog' require 'puppet/indirector/catalog/yaml' describe Puppet::Resource::Catalog::Yaml do it "should be a subclass of the Yaml terminus" do expect(Puppet::Resource::Catalog::Yaml.superclass).to equal(Puppet::Indirector::Yaml) end it "should have documentation" do expect(Puppet::Resource::Catalog::Yaml.doc).not_to be_nil end it "should be registered with the catalog store indirection" do indirection = Puppet::Indirector::Indirection.instance(:catalog) expect(Puppet::Resource::Catalog::Yaml.indirection).to equal(indirection) end it "should have its name set to :yaml" do expect(Puppet::Resource::Catalog::Yaml.name).to eq(:yaml) 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/indirector/catalog/compiler_spec.rb
spec/unit/indirector/catalog/compiler_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'puppet/indirector/catalog/compiler' def set_facts(fact_hash) fact_hash.each do |key, value| allow(Facter).to receive(:value).with(key).and_return(value) end end describe Puppet::Resource::Catalog::Compiler do include Matchers::Resource include PuppetSpec::Files let(:compiler) { described_class.new } let(:node_name) { "foo" } let(:node) { Puppet::Node.new(node_name)} describe "when initializing" do before do allow(Puppet).to receive(:version).and_return(1) end it "should cache the server metadata and reuse it" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("node1")) Puppet::Node.indirection.save(Puppet::Node.new("node2")) allow(compiler).to receive(:compile) compiler.find(Puppet::Indirector::Request.new(:catalog, :find, 'node1', nil, :node => 'node1')) compiler.find(Puppet::Indirector::Request.new(:catalog, :find, 'node2', nil, :node => 'node2')) end end describe "when finding catalogs" do before do allow(node).to receive(:merge) allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request = Puppet::Indirector::Request.new(:catalog, :find, node_name, nil, :node => node_name) end it "should directly use provided nodes for a local request" do expect(Puppet::Node.indirection).not_to receive(:find) expect(compiler).to receive(:compile).with(node, anything) allow(@request).to receive(:options).and_return(:use_node => node) allow(@request).to receive(:remote?).and_return(false) compiler.find(@request) end it "rejects a provided node if the request is remote" do allow(@request).to receive(:options).and_return(:use_node => node) allow(@request).to receive(:remote?).and_return(true) expect { compiler.find(@request) }.to raise_error Puppet::Error, /invalid option use_node/i end it "should use the authenticated node name if no request key is provided" do allow(@request).to receive(:key).and_return(nil) expect(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) expect(compiler).to receive(:compile).with(node, anything) compiler.find(@request) end it "should use the provided node name by default" do expect(@request).to receive(:key).and_return("my_node") expect(Puppet::Node.indirection).to receive(:find).with("my_node", anything).and_return(node) expect(compiler).to receive(:compile).with(node, anything) compiler.find(@request) end it "should fail if no node is passed and none can be found" do allow(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(nil) expect { compiler.find(@request) }.to raise_error(ArgumentError) end it "should fail intelligently when searching for a node raises an exception" do allow(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_raise("eh") expect { compiler.find(@request) }.to raise_error(Puppet::Error) end it "should pass the found node to the compiler for compiling" do expect(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) expect(Puppet::Parser::Compiler).to receive(:compile).with(node, anything) compiler.find(@request) end it "should pass node containing percent character to the compiler" do node_with_percent_character = Puppet::Node.new "%6de" allow(Puppet::Node.indirection).to receive(:find).and_return(node_with_percent_character) expect(Puppet::Parser::Compiler).to receive(:compile).with(node_with_percent_character, anything) compiler.find(@request) end it "should extract any facts from the request" do expect(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) expect(compiler).to receive(:extract_facts_from_request).with(@request) allow(Puppet::Parser::Compiler).to receive(:compile) compiler.find(@request) end it "requires `facts_format` option if facts are passed in" do facts = Puppet::Node::Facts.new("mynode", :afact => "avalue") request = Puppet::Indirector::Request.new(:catalog, :find, "mynode", nil, :facts => facts) expect { compiler.find(request) }.to raise_error ArgumentError, /no fact format provided for mynode/ end it "rejects facts in the request from a different node" do facts = Puppet::Node::Facts.new("differentnode", :afact => "avalue") request = Puppet::Indirector::Request.new( :catalog, :find, "mynode", nil, :facts => facts, :facts_format => "unused" ) expect { compiler.find(request) }.to raise_error Puppet::Error, /fact definition for the wrong node/i end it "should return the results of compiling as the catalog" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) catalog = Puppet::Resource::Catalog.new(node.name) allow(Puppet::Parser::Compiler).to receive(:compile).and_return(catalog) expect(compiler.find(@request)).to equal(catalog) end it "passes the code_id from the request to the compiler" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) code_id = 'b59e5df0578ef411f773ee6c33d8073c50e7b8fe' @request.options[:code_id] = code_id expect(Puppet::Parser::Compiler).to receive(:compile).with(anything, code_id) compiler.find(@request) end it "returns a catalog with the code_id from the request" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) code_id = 'b59e5df0578ef411f773ee6c33d8073c50e7b8fe' @request.options[:code_id] = code_id catalog = Puppet::Resource::Catalog.new(node.name, node.environment, code_id) allow(Puppet::Parser::Compiler).to receive(:compile).and_return(catalog) expect(compiler.find(@request).code_id).to eq(code_id) end it "does not inline metadata when the static_catalog option is false" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.options[:static_catalog] = false @request.options[:code_id] = 'some_code_id' allow(node.environment).to receive(:static_catalogs?).and_return(true) catalog = Puppet::Resource::Catalog.new(node.name, node.environment) allow(Puppet::Parser::Compiler).to receive(:compile).and_return(catalog) expect(compiler).not_to receive(:inline_metadata) compiler.find(@request) end it "does not inline metadata when static_catalogs are disabled" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.options[:static_catalog] = true @request.options[:checksum_type] = 'md5' @request.options[:code_id] = 'some_code_id' allow(node.environment).to receive(:static_catalogs?).and_return(false) catalog = Puppet::Resource::Catalog.new(node.name, node.environment) allow(Puppet::Parser::Compiler).to receive(:compile).and_return(catalog) expect(compiler).not_to receive(:inline_metadata) compiler.find(@request) end it "does not inline metadata when code_id is not specified" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.options[:static_catalog] = true @request.options[:checksum_type] = 'md5' allow(node.environment).to receive(:static_catalogs?).and_return(true) catalog = Puppet::Resource::Catalog.new(node.name, node.environment) allow(Puppet::Parser::Compiler).to receive(:compile).and_return(catalog) expect(compiler).not_to receive(:inline_metadata) expect(compiler.find(@request)).to eq(catalog) end it "inlines metadata when the static_catalog option is true, static_catalogs are enabled, and a code_id is provided" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.options[:static_catalog] = true @request.options[:checksum_type] = 'sha256' @request.options[:code_id] = 'some_code_id' allow(node.environment).to receive(:static_catalogs?).and_return(true) catalog = Puppet::Resource::Catalog.new(node.name, node.environment) allow(Puppet::Parser::Compiler).to receive(:compile).and_return(catalog) expect(compiler).to receive(:inline_metadata).with(catalog, :sha256).and_return(catalog) compiler.find(@request) end it "inlines metadata with the first common checksum type" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.options[:static_catalog] = true @request.options[:checksum_type] = 'atime.md5.sha256.mtime' @request.options[:code_id] = 'some_code_id' allow(node.environment).to receive(:static_catalogs?).and_return(true) catalog = Puppet::Resource::Catalog.new(node.name, node.environment) allow(Puppet::Parser::Compiler).to receive(:compile).and_return(catalog) expect(compiler).to receive(:inline_metadata).with(catalog, :md5).and_return(catalog) compiler.find(@request) end it "errors if checksum_type contains no shared checksum types" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.options[:static_catalog] = true @request.options[:checksum_type] = 'atime.md2' @request.options[:code_id] = 'some_code_id' allow(node.environment).to receive(:static_catalogs?).and_return(true) expect { compiler.find(@request) }.to raise_error Puppet::Error, "Unable to find a common checksum type between agent 'atime.md2' and master '[:sha256, :sha256lite, :md5, :md5lite, :sha1, :sha1lite, :sha512, :sha384, :sha224, :mtime, :ctime, :none]'." end it "errors if checksum_type contains no shared checksum types" do allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.options[:static_catalog] = true @request.options[:checksum_type] = nil @request.options[:code_id] = 'some_code_id' allow(node.environment).to receive(:static_catalogs?).and_return(true) expect { compiler.find(@request) }.to raise_error Puppet::Error, "Unable to find a common checksum type between agent '' and master '[:sha256, :sha256lite, :md5, :md5lite, :sha1, :sha1lite, :sha512, :sha384, :sha224, :mtime, :ctime, :none]'." end it "prevents the environment from being evicted during compilation" do Puppet[:environment_timeout] = 0 envs = Puppet.lookup(:environments) expect(compiler).to receive(:compile) do # we should get the same object expect(envs.get!(:production)).to equal(envs.get!(:production)) end compiler.find(@request) end context 'when checking agent and server specified environments' do before :each do FileUtils.mkdir_p(File.join(Puppet[:environmentpath], 'env_server')) FileUtils.mkdir_p(File.join(Puppet[:environmentpath], 'env_agent')) node.environment = 'env_server' allow(Puppet::Node.indirection).to receive(:find).and_return(node) @request.environment = 'env_agent' end it 'ignores mismatched environments by default' do catalog = compiler.find(@request) expect(catalog.environment).to eq('env_server') expect(catalog).to have_resource('Stage[main]') end # versioned environment directories can cause this it 'allows environments with the same name but mismatched modulepaths' do envs = Puppet.lookup(:environments) env_server = envs.get!(:env_server) v1_env = env_server.override_with({ modulepath: ['/code-v1/env-v1/'] }) v2_env = env_server.override_with({ modulepath: ['/code-v2/env-v2/'] }) @request.options[:check_environment] = "true" @request.environment = v1_env node.environment = v2_env catalog = compiler.find(@request) expect(catalog.environment).to eq('env_server') expect(catalog).to have_resource('Stage[main]') end it 'returns an empty catalog if asked to check the environment and they are mismatched' do @request.options[:check_environment] = "true" catalog = compiler.find(@request) expect(catalog.environment).to eq('env_server') expect(catalog.resources).to be_empty end end end describe "when handling a request with facts" do before do allow(Facter).to receive(:value).and_return("something") facts = Puppet::Node::Facts.new('hostname', "fact" => "value", "architecture" => "i386") Puppet::Node::Facts.indirection.save(facts) end def a_legacy_request_that_contains(facts, format = :pson) request = Puppet::Indirector::Request.new(:catalog, :find, "hostname", nil) request.options[:facts_format] = format.to_s request.options[:facts] = Puppet::Util.uri_query_encode(facts.render(format)) request end def a_request_that_contains(facts) request = Puppet::Indirector::Request.new(:catalog, :find, "hostname", nil) request.options[:facts_format] = "application/json" request.options[:facts] = Puppet::Util.uri_query_encode(facts.render('json')) request end context "when extracting facts from the request" do let(:facts) { Puppet::Node::Facts.new("hostname") } it "should do nothing if no facts are provided" do request = Puppet::Indirector::Request.new(:catalog, :find, "hostname", nil) request.options[:facts] = nil expect(compiler.extract_facts_from_request(request)).to be_nil end it "should deserialize the facts without changing the timestamp" do time = Time.now facts.timestamp = time request = a_request_that_contains(facts) facts = compiler.extract_facts_from_request(request) expect(facts.timestamp).to eq(time) end it "accepts PSON facts from older agents", :if => Puppet.features.pson? do request = a_legacy_request_that_contains(facts) facts = compiler.extract_facts_from_request(request) expect(facts).to eq(facts) end it "rejects YAML facts" do request = a_legacy_request_that_contains(facts, :yaml) expect { compiler.extract_facts_from_request(request) }.to raise_error(ArgumentError, /Unsupported facts format/) end it "rejects unknown fact formats" do request = a_request_that_contains(facts) request.options[:facts_format] = 'unknown-format' expect { compiler.extract_facts_from_request(request) }.to raise_error(ArgumentError, /Unsupported facts format/) end end context "when saving facts from the request" do let(:facts) { Puppet::Node::Facts.new("hostname") } it "should save facts if they were issued by the request" do request = a_request_that_contains(facts) options = { :environment => request.environment, :transaction_uuid => request.options[:transaction_uuid], } expect(Puppet::Node::Facts.indirection).to receive(:save).with(facts, nil, options) compiler.find(request) end it "should skip saving facts if none were supplied" do request = Puppet::Indirector::Request.new(:catalog, :find, "hostname", nil) options = { :environment => request.environment, :transaction_uuid => request.options[:transaction_uuid], } expect(Puppet::Node::Facts.indirection).not_to receive(:save).with(facts, nil, options) compiler.find(request) end end end describe "when finding nodes" do it "should look node information up via the Node class with the provided key" do request = Puppet::Indirector::Request.new(:catalog, :find, node_name, nil) allow(compiler).to receive(:compile) expect(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) compiler.find(request) end it "should pass the transaction_uuid to the node indirection" do uuid = '793ff10d-89f8-4527-a645-3302cbc749f3' allow(compiler).to receive(:compile) request = Puppet::Indirector::Request.new(:catalog, :find, node_name, nil, :transaction_uuid => uuid) expect(Puppet::Node.indirection).to receive(:find).with( node_name, hash_including(:transaction_uuid => uuid) ).and_return(node) compiler.find(request) end it "should pass the configured_environment to the node indirection" do environment = 'foo' allow(compiler).to receive(:compile) request = Puppet::Indirector::Request.new(:catalog, :find, node_name, nil, :configured_environment => environment) expect(Puppet::Node.indirection).to receive(:find).with( node_name, hash_including(:configured_environment => environment) ).and_return(node) compiler.find(request) end it "should pass a facts object from the original request facts to the node indirection" do facts = Puppet::Node::Facts.new("hostname", :afact => "avalue") expect(compiler).to receive(:extract_facts_from_request).and_return(facts) expect(compiler).to receive(:save_facts_from_request) request = Puppet::Indirector::Request.new(:catalog, :find, "hostname", nil, :facts_format => "application/json", :facts => facts.render('json')) expect(Puppet::Node.indirection).to receive(:find).with("hostname", hash_including(:facts => facts)).and_return(node) compiler.find(request) end end describe "after finding nodes" do before do allow(Puppet).to receive(:version).and_return(1) set_facts({ 'networking.fqdn' => "my.server.com", 'networking.ip' => "my.ip.address", 'networking.ip6' => nil }) @request = Puppet::Indirector::Request.new(:catalog, :find, node_name, nil) allow(compiler).to receive(:compile) allow(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) end it "should add the server's Puppet version to the node's parameters as 'serverversion'" do expect(node).to receive(:merge).with(hash_including("serverversion" => "1")) compiler.find(@request) end it "should add the server's fqdn to the node's parameters as 'servername'" do expect(node).to receive(:merge).with(hash_including("servername" => "my.server.com")) compiler.find(@request) end it "should add the server's IP address to the node's parameters as 'serverip'" do expect(node).to receive(:merge).with(hash_including("serverip" => "my.ip.address")) compiler.find(@request) end it "shouldn't warn if there is at least one ip fact" do expect(node).to receive(:merge).with(hash_including("serverip" => "my.ip.address")) compiler.find(@request) expect(@logs).not_to be_any {|log| log.level == :warning and log.message =~ /Could not retrieve either serverip or serverip6 fact/} end end describe "in an IPv6 only environment" do before do |example| allow(Puppet).to receive(:version).and_return(1) set_facts({ 'networking.fqdn' => "my.server.com", 'networking.ip' => nil, }) if example.metadata[:nil_ipv6] set_facts({ 'networking.ip6' => nil }) else set_facts({ 'networking.ip6' => "my.ipv6.address" }) end @request = Puppet::Indirector::Request.new(:catalog, :find, node_name, nil) allow(compiler).to receive(:compile) allow(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) end it "should populate the :serverip6 fact" do expect(node).to receive(:merge).with(hash_including("serverip6" => "my.ipv6.address")) compiler.find(@request) end it "shouldn't warn if there is at least one ip fact" do expect(node).to receive(:merge).with(hash_including("serverip6" => "my.ipv6.address")) compiler.find(@request) expect(@logs).not_to be_any {|log| log.level == :warning and log.message =~ /Could not retrieve either serverip or serverip6 fact/} end it "should warn if there are no ip facts", :nil_ipv6 do expect(node).to receive(:merge) compiler.find(@request) expect(@logs).to be_any {|log| log.level == :warning and log.message =~ /Could not retrieve either serverip or serverip6 fact/} end end describe "after finding nodes when checking for a PE version" do include PuppetSpec::Compiler let(:pe_version_file) { '/opt/puppetlabs/server/pe_version' } let(:request) { Puppet::Indirector::Request.new(:catalog, :find, node_name, nil) } before :each do Puppet[:code] = 'notify { "PE Version: $pe_serverversion": }' end it "should not add 'pe_serverversion' when FOSS" do allow(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) expect { catalog = compiler.find(request) catalog.resource('notify', 'PE Version: 2019.2.0') }.to raise_error(/Evaluation Error: Unknown variable: 'pe_serverversion'./) end it "should add 'pe_serverversion' when PE" do allow(File).to receive(:readable?).and_call_original allow(File).to receive(:readable?).with(pe_version_file).and_return(true) allow(File).to receive(:zero?).with(pe_version_file).and_return(false) allow(File).to receive(:read).and_call_original allow(File).to receive(:read).with(pe_version_file).and_return('2019.2.0') allow(Puppet::Node.indirection).to receive(:find).with(node_name, anything).and_return(node) catalog = compiler.find(request) expect(catalog.resource('notify', 'PE Version: 2019.2.0')).to be end end describe "when filtering resources" do before :each do @catalog = double('catalog') allow(@catalog).to receive(:respond_to?).with(:filter).and_return(true) end it "should delegate to the catalog instance filtering" do expect(@catalog).to receive(:filter) compiler.filter(@catalog) end it "should filter out virtual resources" do resource = double('resource', :virtual? => true) allow(@catalog).to receive(:filter).and_yield(resource) compiler.filter(@catalog) end it "should return the same catalog if it doesn't support filtering" do allow(@catalog).to receive(:respond_to?).with(:filter).and_return(false) expect(compiler.filter(@catalog)).to eq(@catalog) end it "should return the filtered catalog" do catalog = double('filtered catalog') allow(@catalog).to receive(:filter).and_return(catalog) expect(compiler.filter(@catalog)).to eq(catalog) end end describe "when inlining metadata" do include PuppetSpec::Compiler let(:node) { Puppet::Node.new 'me' } let(:checksum_type) { 'md5' } let(:checksum_value) { 'b1946ac92492d2347c6235b4d2611184' } let(:path) { File.expand_path('/foo') } let(:source) { 'puppet:///modules/mymodule/config_file.txt' } def stubs_resource_metadata(ftype, relative_path, full_path = nil) full_path ||= File.join(Puppet[:environmentpath], 'production', relative_path) metadata = double('metadata') allow(metadata).to receive(:ftype).and_return(ftype) allow(metadata).to receive(:full_path).and_return(full_path) allow(metadata).to receive(:relative_path).and_return(relative_path) allow(metadata).to receive(:source).and_return("puppet:///#{relative_path}") allow(metadata).to receive(:source=) allow(metadata).to receive(:content_uri=) metadata end def stubs_file_metadata(checksum_type, sha, relative_path, full_path = nil) metadata = stubs_resource_metadata('file', relative_path, full_path) allow(metadata).to receive(:checksum).and_return("{#{checksum_type}}#{sha}") allow(metadata).to receive(:checksum_type).and_return(checksum_type) metadata end def stubs_link_metadata(relative_path, destination) metadata = stubs_resource_metadata('link', relative_path) allow(metadata).to receive(:destination).and_return(destination) metadata end def stubs_directory_metadata(relative_path) metadata = stubs_resource_metadata('directory', relative_path) allow(metadata).to receive(:relative_path).and_return('.') metadata end describe "and the environment is a symlink and versioned_environment_dirs is true" do let(:tmpdir) { Dir.mktmpdir } before(:each) do Puppet[:versioned_environment_dirs] = true prod_path = File.join(Puppet[:environmentpath], 'production') FileUtils.rm_rf(prod_path) FileUtils.symlink(tmpdir, prod_path) end it "inlines metadata for a file" do catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => file, source => '#{source}' } MANIFEST module_relative_path = 'modules/mymodule/files/config_file.txt' metadata = stubs_file_metadata(checksum_type, checksum_value, module_relative_path, File.join(tmpdir, module_relative_path) ) expect(metadata).to receive(:source=).with(source) expect(metadata).to receive(:content_uri=).with("puppet:///#{module_relative_path}") options = { :environment => catalog.environment_instance, :links => :manage, :checksum_type => checksum_type.to_sym, :source_permissions => :ignore } expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(source, options).and_return(metadata) compiler.send(:inline_metadata, catalog, checksum_type) expect(catalog.metadata[path]).to eq(metadata) expect(catalog.recursive_metadata).to be_empty end end it "inlines metadata for a file" do catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => file, source => '#{source}' } MANIFEST metadata = stubs_file_metadata(checksum_type, checksum_value, 'modules/mymodule/files/config_file.txt') expect(metadata).to receive(:source=).with(source) expect(metadata).to receive(:content_uri=).with('puppet:///modules/mymodule/files/config_file.txt') options = { :environment => catalog.environment_instance, :links => :manage, :checksum_type => checksum_type.to_sym, :source_permissions => :ignore } expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(source, options).and_return(metadata) compiler.send(:inline_metadata, catalog, checksum_type) expect(catalog.metadata[path]).to eq(metadata) expect(catalog.recursive_metadata).to be_empty end it "uses resource parameters when inlining metadata" do catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => link, source => '#{source}', links => follow, source_permissions => use, } MANIFEST metadata = stubs_link_metadata('modules/mymodule/files/config_file.txt', '/tmp/some/absolute/path') expect(metadata).to receive(:source=).with(source) expect(metadata).to receive(:content_uri=).with('puppet:///modules/mymodule/files/config_file.txt') options = { :environment => catalog.environment_instance, :links => :follow, :checksum_type => checksum_type.to_sym, :source_permissions => :use } expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(source, options).and_return(metadata) compiler.send(:inline_metadata, catalog, checksum_type) expect(catalog.metadata[path]).to eq(metadata) expect(catalog.recursive_metadata).to be_empty end it "uses file parameters which match the true file type defaults" do catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => file, source => '#{source}' } MANIFEST if Puppet::Util::Platform.windows? default_file = Puppet::Type.type(:file).new(:name => 'C:\defaults') else default_file = Puppet::Type.type(:file).new(:name => '/defaults') end metadata = stubs_file_metadata(checksum_type, checksum_value, 'modules/mymodule/files/config_file.txt') options = { :environment => catalog.environment_instance, :links => default_file[:links], :checksum_type => checksum_type.to_sym, :source_permissions => default_file[:source_permissions] } expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(source, options).and_return(metadata) compiler.send(:inline_metadata, catalog, checksum_type) end it "inlines metadata for the first source found" do alt_source = 'puppet:///modules/files/other.txt' catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => file, source => ['#{alt_source}', '#{source}'], } MANIFEST metadata = stubs_file_metadata(checksum_type, checksum_value, 'modules/mymodule/files/config_file.txt') expect(metadata).to receive(:source=).with(source) expect(metadata).to receive(:content_uri=).with('puppet:///modules/mymodule/files/config_file.txt') expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(source, anything).and_return(metadata) expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(alt_source, anything).and_return(nil) compiler.send(:inline_metadata, catalog, checksum_type) expect(catalog.metadata[path]).to eq(metadata) expect(catalog.recursive_metadata).to be_empty end [['md5', 'b1946ac92492d2347c6235b4d2611184'], ['sha256', '5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03']].each do |checksum_type, sha| describe "with agent requesting checksum_type #{checksum_type}" do it "sets checksum and checksum_value for resources with puppet:// source URIs" do catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => file, source => '#{source}' } MANIFEST metadata = stubs_file_metadata(checksum_type, sha, 'modules/mymodule/files/config_file.txt') options = { :environment => catalog.environment_instance, :links => :manage, :checksum_type => checksum_type.to_sym, :source_permissions => :ignore } expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(source, options).and_return(metadata) compiler.send(:inline_metadata, catalog, checksum_type) expect(catalog.metadata[path]).to eq(metadata) expect(catalog.recursive_metadata).to be_empty end end end it "preserves source host and port in the content_uri" do source = 'puppet://myhost:8888/modules/mymodule/config_file.txt' catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => file, source => '#{source}' } MANIFEST metadata = stubs_file_metadata(checksum_type, checksum_value, 'modules/mymodule/files/config_file.txt') allow(metadata).to receive(:source).and_return(source) expect(metadata).to receive(:content_uri=).with('puppet://myhost:8888/modules/mymodule/files/config_file.txt') expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(source, anything).and_return(metadata) compiler.send(:inline_metadata, catalog, checksum_type) end it "skips absent resources" do catalog = compile_to_catalog(<<-MANIFEST, node) file { '#{path}': ensure => absent, } MANIFEST compiler.send(:inline_metadata, catalog, checksum_type) expect(catalog.metadata).to be_empty
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/resource/ral_spec.rb
spec/unit/indirector/resource/ral_spec.rb
require 'spec_helper' require 'puppet/indirector/resource/ral' describe Puppet::Resource::Ral do let(:my_instance) { Puppet::Type.type(:user).new(:name => "root") } let(:wrong_instance) { Puppet::Type.type(:user).new(:name => "bob")} def stub_retrieve(*instances) instances.each do |i| allow(i).to receive(:retrieve).and_return(Puppet::Resource.new(i, nil)) end end before do described_class.indirection.terminus_class = :ral # make sure we don't try to retrieve current state allow_any_instance_of(Puppet::Type.type(:user)).to receive(:retrieve).never stub_retrieve(my_instance, wrong_instance) end it "disallows remote requests" do expect(Puppet::Resource::Ral.new.allow_remote_requests?).to eq(false) end describe "find" do it "should find an existing instance" do allow(Puppet::Type.type(:user)).to receive(:instances).and_return([ wrong_instance, my_instance, wrong_instance ]) actual_resource = described_class.indirection.find('user/root') expect(actual_resource.name).to eq('User/root') end it "should produce Puppet::Error instead of ArgumentError" do expect{described_class.indirection.find('thiswill/causeanerror')}.to raise_error(Puppet::Error) end it "if there is no instance, it should create one" do allow(Puppet::Type.type(:user)).to receive(:instances).and_return([wrong_instance]) expect(Puppet::Type.type(:user)).to receive(:new).with(hash_including(name: "root")).and_return(my_instance) expect(described_class.indirection.find('user/root')).to be end end describe "search" do it "should convert ral resources into regular resources" do allow(Puppet::Type.type(:user)).to receive(:instances).and_return([ my_instance ]) actual = described_class.indirection.search('user') expect(actual).to contain_exactly(an_instance_of(Puppet::Resource)) end it "should filter results by name if there's a name in the key" do allow(Puppet::Type.type(:user)).to receive(:instances).and_return([ my_instance, wrong_instance ]) actual = described_class.indirection.search('user/root') expect(actual).to contain_exactly(an_object_having_attributes(name: 'User/root')) end it "should filter results by query parameters" do allow(Puppet::Type.type(:user)).to receive(:instances).and_return([ my_instance, wrong_instance ]) actual = described_class.indirection.search('user', name: 'bob') expect(actual).to contain_exactly(an_object_having_attributes(name: 'User/bob')) end it "should return sorted results" do a_instance = Puppet::Type.type(:user).new(:name => "alice") b_instance = Puppet::Type.type(:user).new(:name => "bob") stub_retrieve(a_instance, b_instance) allow(Puppet::Type.type(:user)).to receive(:instances).and_return([ b_instance, a_instance ]) expect(described_class.indirection.search('user').map(&:title)).to eq(['alice', 'bob']) end end describe "save" do it "returns a report covering the application of the given resource to the system" do resource = Puppet::Resource.new(:notify, "the title") applied_resource, report = described_class.indirection.save(resource, nil, environment: Puppet::Node::Environment.remote(:testing)) expect(applied_resource.title).to eq("the title") expect(report.environment).to eq("testing") expect(report.resource_statuses["Notify[the title]"].changed).to eq(true) 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/indirector/resource/store_configs_spec.rb
spec/unit/indirector/resource/store_configs_spec.rb
require 'spec_helper' require 'puppet/resource' require 'puppet/indirector/memory' require 'puppet/indirector/resource/store_configs' class Puppet::Resource::StoreConfigsTesting < Puppet::Indirector::Memory end describe Puppet::Resource::StoreConfigs do it_should_behave_like "a StoreConfigs terminus" before :each do Puppet[:storeconfigs] = true Puppet[:storeconfigs_backend] = "store_configs_testing" end it "disallows remote requests" do expect(Puppet::Resource::StoreConfigs.new.allow_remote_requests?).to eq(false) 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/indirector/node/rest_spec.rb
spec/unit/indirector/node/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/node/rest' describe Puppet::Node::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/node/ziggy} } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } let(:node) { Puppet::Node.new(certname) } before :each do Puppet[:server] = 'compiler.example.com' Puppet[:serverport] = 8140 described_class.indirection.terminus_class = :rest end def node_response(node) { body: formatter.render(node), headers: {'Content-Type' => formatter.mime } } end it 'finds a node' do stub_request(:get, uri).to_return(**node_response(node)) expect(described_class.indirection.find(certname)).to be_a(Puppet::Node) end it "serializes the environment" do stub_request(:get, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(**node_response(node)) described_class.indirection.find(certname, environment: Puppet::Node::Environment.remote('outerspace')) end it 'preserves the node environment_name as a symbol' do env = Puppet::Node::Environment.remote('outerspace') node = Puppet::Node.new(certname, environment: env) stub_request(:get, uri).to_return(**node_response(node)) expect(described_class.indirection.find(certname).environment_name).to eq(:outerspace) end it 'returns nil if the node does not exist' do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect(described_class.indirection.find(certname)).to be_nil end it 'raises if fail_on_404 is specified' do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect{ described_class.indirection.find(certname, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/node/ziggy resulted in 404 with the message: {}}) end it 'raises Net::HTTPError on 500' do stub_request(:get, uri).to_return(status: 500) expect{ described_class.indirection.find(certname) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) 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/indirector/node/msgpack_spec.rb
spec/unit/indirector/node/msgpack_spec.rb
require 'spec_helper' require 'puppet/node' require 'puppet/indirector/node/msgpack' describe Puppet::Node::Msgpack, :if => Puppet.features.msgpack? do it "should be a subclass of the Msgpack terminus" do expect(Puppet::Node::Msgpack.superclass).to equal(Puppet::Indirector::Msgpack) end it "should have documentation" do expect(Puppet::Node::Msgpack.doc).not_to be_nil end it "should be registered with the configuration store indirection" do indirection = Puppet::Indirector::Indirection.instance(:node) expect(Puppet::Node::Msgpack.indirection).to equal(indirection) end it "should have its name set to :msgpack" do expect(Puppet::Node::Msgpack.name).to eq(:msgpack) 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/indirector/node/plain_spec.rb
spec/unit/indirector/node/plain_spec.rb
require 'spec_helper' require 'puppet/indirector/node/plain' describe Puppet::Node::Plain do let(:nodename) { "mynode" } let(:indirection_fact_values) { {:afact => "a value"} } let(:indirection_facts) { Puppet::Node::Facts.new(nodename, indirection_fact_values) } let(:request_fact_values) { {:foo => "bar" } } let(:request_facts) { Puppet::Node::Facts.new(nodename, request_fact_values)} let(:environment) { Puppet::Node::Environment.create(:myenv, []) } let(:request) { Puppet::Indirector::Request.new(:node, :find, nodename, nil, :environment => environment) } let(:node_indirection) { Puppet::Node::Plain.new } it "should merge facts from the request if supplied" do expect(Puppet::Node::Facts.indirection).not_to receive(:find) request.options[:facts] = request_facts node = node_indirection.find(request) expect(node.parameters).to include(request_fact_values) expect(node.facts).to eq(request_facts) end it "should find facts if none are supplied" do expect(Puppet::Node::Facts.indirection).to receive(:find).with(nodename, {:environment => environment}).and_return(indirection_facts) request.options.delete(:facts) node = node_indirection.find(request) expect(node.parameters).to include(indirection_fact_values) expect(node.facts).to eq(indirection_facts) end it "should set the node environment from the request" do expect(node_indirection.find(request).environment).to eq(environment) 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/indirector/node/store_configs_spec.rb
spec/unit/indirector/node/store_configs_spec.rb
require 'spec_helper' require 'puppet/node' require 'puppet/indirector/memory' require 'puppet/indirector/node/store_configs' class Puppet::Node::StoreConfigsTesting < Puppet::Indirector::Memory end describe Puppet::Node::StoreConfigs do after :each do Puppet::Node.indirection.reset_terminus_class Puppet::Node.indirection.cache_class = nil end it_should_behave_like "a StoreConfigs terminus" end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/node/json_spec.rb
spec/unit/indirector/node/json_spec.rb
require 'spec_helper' require 'puppet/node' require 'puppet/indirector/node/json' describe Puppet::Node::Json do describe '#save' do subject(:indirection) { described_class.indirection } let(:env) { Puppet::Node::Environment.create(:testing, []) } let(:node) { Puppet::Node.new('node_name', :environment => env) } let(:file) { File.join(Puppet[:client_datadir], "node", "node_name.json") } before do indirection.terminus_class = :json end it 'saves the instance of the node as JSON to disk' do indirection.save(node) json = Puppet::FileSystem.read(file, :encoding => 'bom|utf-8') content = Puppet::Util::Json.load(json) expect(content["name"]).to eq('node_name') end context 'when node cannot be saved' do it 'raises Errno::EISDIR' do FileUtils.mkdir_p(file) expect { indirection.save(node) }.to raise_error(Errno::EISDIR, /node_name.json/) 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/indirector/node/yaml_spec.rb
spec/unit/indirector/node/yaml_spec.rb
require 'spec_helper' require 'puppet/node' require 'puppet/indirector/node/yaml' describe Puppet::Node::Yaml do it "should be a subclass of the Yaml terminus" do expect(Puppet::Node::Yaml.superclass).to equal(Puppet::Indirector::Yaml) end it "should have documentation" do expect(Puppet::Node::Yaml.doc).not_to be_nil end it "should be registered with the configuration store indirection" do indirection = Puppet::Indirector::Indirection.instance(:node) expect(Puppet::Node::Yaml.indirection).to equal(indirection) end it "should have its name set to :node" do expect(Puppet::Node::Yaml.name).to eq(:yaml) 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/indirector/node/exec_spec.rb
spec/unit/indirector/node/exec_spec.rb
require 'spec_helper' require 'puppet/indirector/node/exec' require 'puppet/indirector/request' describe Puppet::Node::Exec do let(:indirection) { mock 'indirection' } let(:searcher) { Puppet::Node::Exec.new } before do Puppet.settings[:external_nodes] = File.expand_path("/echo") end describe "when constructing the command to run" do it "should use the external_node script as the command" do Puppet[:external_nodes] = "/bin/echo" expect(searcher.command).to eq(%w{/bin/echo}) end it "should throw an exception if no external node command is set" do Puppet[:external_nodes] = "none" expect { searcher.find(double('request', :key => "foo")) }.to raise_error(ArgumentError) end end describe "when handling the results of the command" do let(:testing_env) { Puppet::Node::Environment.create(:testing, []) } let(:other_env) { Puppet::Node::Environment.create(:other, []) } let(:request) { Puppet::Indirector::Request.new(:node, :find, name, environment: testing_env) } let(:name) { 'yay' } let(:facts) { Puppet::Node::Facts.new(name, {}) } before do allow(Puppet::Node::Facts.indirection).to receive(:find).and_return(facts) @result = {} # Use a local variable so the reference is usable in the execute definition. result = @result searcher.meta_def(:execute) do |command, arguments| return YAML.dump(result) end end around do |example| envs = Puppet::Environments::Static.new(testing_env, other_env) Puppet.override(:environments => envs) do example.run end end it "should translate the YAML into a Node instance" do @result = {} node = searcher.find(request) expect(node.name).to eq(name) expect(node.parameters).to include('environment') expect(node.facts).to eq(facts) expect(node.environment.name).to eq(:'*root*') # request env is ignored end it "should set the resulting parameters as the node parameters" do @result[:parameters] = {"a" => "b", "c" => "d"} node = searcher.find(request) expect(node.parameters).to eq({"a" => "b", "c" => "d", "environment" => "*root*"}) end it "accepts symbolic parameter names" do @result[:parameters] = {:name => "value"} node = searcher.find(request) expect(node.parameters).to include({:name => "value"}) end it "raises when deserializing unacceptable objects" do @result[:parameters] = {'name' => Object.new } expect { searcher.find(request) }.to raise_error(Puppet::Error, /Could not load external node results for yay: \(<unknown>\): Tried to load unspecified class: Object/) end it "should set the resulting classes as the node classes" do @result[:classes] = %w{one two} node = searcher.find(request) expect(node.classes).to eq([ 'one', 'two' ]) end it "should merge facts from the request if supplied" do facts = Puppet::Node::Facts.new('test', 'foo' => 'bar') request.options[:facts] = facts node = searcher.find(request) expect(node.facts).to eq(facts) end it "should set the node's environment if one is provided" do @result[:environment] = "testing" node = searcher.find(request) expect(node.environment.name).to eq(:testing) end it "should set the node's environment based on the request if not otherwise provided" do request.environment = "other" node = searcher.find(request) expect(node.environment.name).to eq(:other) 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/indirector/node/memory_spec.rb
spec/unit/indirector/node/memory_spec.rb
require 'spec_helper' require 'puppet/indirector/node/memory' require 'shared_behaviours/memory_terminus' describe Puppet::Node::Memory do before do @name = "me" @searcher = Puppet::Node::Memory.new @instance = double('instance', :name => @name) @request = double('request', :key => @name, :instance => @instance) end it_should_behave_like "A Memory Terminus" end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/file_content/file_spec.rb
spec/unit/indirector/file_content/file_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/file' describe Puppet::Indirector::FileContent::File do it "should be registered with the file_content indirection" do expect(Puppet::Indirector::Terminus.terminus_class(:file_content, :file)).to equal(Puppet::Indirector::FileContent::File) end it "should be a subclass of the DirectFileServer terminus" do expect(Puppet::Indirector::FileContent::File.superclass).to equal(Puppet::Indirector::DirectFileServer) 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/indirector/file_content/selector_spec.rb
spec/unit/indirector/file_content/selector_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/selector' describe Puppet::Indirector::FileContent::Selector do include PuppetSpec::Files it_should_behave_like "Puppet::FileServing::Files", :file_content end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/file_content/rest_spec.rb
spec/unit/indirector/file_content/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/rest' describe Puppet::Indirector::FileContent::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/file_content/:mount/path/to/file} } let(:key) { "puppet:///:mount/path/to/file" } before :each do described_class.indirection.terminus_class = :rest end def file_content_response {body: "some content", headers: { 'Content-Type' => 'application/octet-stream' } } end it "returns content as a binary string" do stub_request(:get, uri).to_return(status: 200, **file_content_response) file_content = described_class.indirection.find(key) expect(file_content.content.encoding).to eq(Encoding::BINARY) expect(file_content.content).to eq('some content') end it "URL encodes special characters" do stub_request(:get, %r{/puppet/v3/file_content/:mount/path%20to%20file}).to_return(status: 200, **file_content_response) described_class.indirection.find('puppet:///:mount/path to file') end it "returns nil if the content doesn't exist" do stub_request(:get, uri).to_return(status: 404) expect(described_class.indirection.find(key)).to be_nil end it "raises if fail_on_404 is true" do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { described_class.indirection.find(key, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/file_content/:mount/path/to/file resulted in 404 with the message: {}}) end it "raises an error on HTTP 500" do stub_request(:get, uri).to_return(status: 500, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { described_class.indirection.find(key) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end it "connects to a specific host" do stub_request(:get, %r{https://example.com:8140/puppet/v3/file_content/:mount/path/to/file}) .to_return(status: 200, **file_content_response) described_class.indirection.find("puppet://example.com:8140/:mount/path/to/file") 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/indirector/file_content/file_server_spec.rb
spec/unit/indirector/file_content/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/file_server' describe Puppet::Indirector::FileContent::FileServer do it "should be registered with the file_content indirection" do expect(Puppet::Indirector::Terminus.terminus_class(:file_content, :file_server)).to equal(Puppet::Indirector::FileContent::FileServer) end it "should be a subclass of the FileServer terminus" do expect(Puppet::Indirector::FileContent::FileServer.superclass).to equal(Puppet::Indirector::FileServer) 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/indirector/report/rest_spec.rb
spec/unit/indirector/report/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/report/rest' describe Puppet::Transaction::Report::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/report/ziggy} } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } let(:report) do report = Puppet::Transaction::Report.new report.host = certname report end before(:each) do described_class.indirection.terminus_class = :rest end def report_response { body: formatter.render(["store", "http"]), headers: {'Content-Type' => formatter.mime } } end it "saves a report " do stub_request(:put, uri) .to_return(status: 200, **report_response) described_class.indirection.save(report) end it "serializes the environment" do stub_request(:put, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(**report_response) described_class.indirection.save(report, nil, environment: Puppet::Node::Environment.remote('outerspace')) end it "deserializes the response as an array of report processor names" do stub_request(:put, %r{/puppet/v3/report}) .to_return(status: 200, **report_response) expect(described_class.indirection.save(report)).to eq(["store", "http"]) end it "returns nil if the node does not exist" do stub_request(:put, uri) .to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect(described_class.indirection.save(report)).to be_nil end it "parses charset from response content-type" do stub_request(:put, uri) .to_return(status: 200, body: JSON.dump(["store"]), headers: { 'Content-Type' => 'application/json;charset=utf-8' }) expect(described_class.indirection.save(report)).to eq(["store"]) 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/indirector/report/msgpack_spec.rb
spec/unit/indirector/report/msgpack_spec.rb
require 'spec_helper' require 'puppet/transaction/report' require 'puppet/indirector/report/msgpack' describe Puppet::Transaction::Report::Msgpack, :if => Puppet.features.msgpack? do it "should be a subclass of the Msgpack terminus" do expect(Puppet::Transaction::Report::Msgpack.superclass).to equal(Puppet::Indirector::Msgpack) end it "should have documentation" do expect(Puppet::Transaction::Report::Msgpack.doc).not_to be_nil end it "should be registered with the report indirection" do indirection = Puppet::Indirector::Indirection.instance(:report) expect(Puppet::Transaction::Report::Msgpack.indirection).to equal(indirection) end it "should have its name set to :msgpack" do expect(Puppet::Transaction::Report::Msgpack.name).to eq(:msgpack) end it "should unconditionally save/load from the --lastrunreport setting" do expect(subject.path(:me)).to eq(Puppet[:lastrunreport]) 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/indirector/report/processor_spec.rb
spec/unit/indirector/report/processor_spec.rb
require 'spec_helper' require 'puppet/indirector/report/processor' describe Puppet::Transaction::Report::Processor do before do allow(Puppet.settings).to receive(:use).and_return(true) end it "should provide a method for saving reports" do expect(Puppet::Transaction::Report::Processor.new).to respond_to(:save) end it "should provide a method for cleaning reports" do expect(Puppet::Transaction::Report::Processor.new).to respond_to(:destroy) end end describe Puppet::Transaction::Report::Processor, " when processing a report" do before do allow(Puppet.settings).to receive(:use) @reporter = Puppet::Transaction::Report::Processor.new @request = double('request', :instance => double("report", :host => 'hostname'), :key => 'node') end it "should not save the report if reports are set to 'none'" do expect(Puppet::Reports).not_to receive(:report) Puppet[:reports] = 'none' request = Puppet::Indirector::Request.new(:indirection_name, :head, "key", nil) report = Puppet::Transaction::Report.new request.instance = report @reporter.save(request) end it "should save the report with each configured report type" do Puppet[:reports] = "one,two" expect(@reporter.send(:reports)).to eq(%w{one two}) expect(Puppet::Reports).to receive(:report).with('one') expect(Puppet::Reports).to receive(:report).with('two') @reporter.save(@request) end it "should destroy reports for each processor that responds to destroy" do Puppet[:reports] = "http,store" http_report = double() store_report = double() expect(store_report).to receive(:destroy).with(@request.key) expect(Puppet::Reports).to receive(:report).with('http').and_return(http_report) expect(Puppet::Reports).to receive(:report).with('store').and_return(store_report) @reporter.destroy(@request) end end describe Puppet::Transaction::Report::Processor, " when processing a report" do before do Puppet[:reports] = "one" allow(Puppet.settings).to receive(:use) @reporter = Puppet::Transaction::Report::Processor.new @report_type = double('one') @dup_report = double('dupe report') allow(@dup_report).to receive(:process) @report = Puppet::Transaction::Report.new expect(@report).to receive(:dup).and_return(@dup_report) @request = double('request', :instance => @report) expect(Puppet::Reports).to receive(:report).with("one").and_return(@report_type) expect(@dup_report).to receive(:extend).with(@report_type) end # LAK:NOTE This is stupid, because the code is so short it doesn't # make sense to split it out, which means I just do the same test # three times so the spec looks right. it "should process a duplicate of the report, not the original" do @reporter.save(@request) end it "should extend the report with the report type's module" do @reporter.save(@request) end it "should call the report type's :process method" do expect(@dup_report).to receive(:process) @reporter.save(@request) end it "should not raise exceptions" do Puppet[:trace] = false expect(@dup_report).to receive(:process).and_raise(ArgumentError) expect { @reporter.save(@request) }.not_to raise_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/indirector/report/json_spec.rb
spec/unit/indirector/report/json_spec.rb
require 'spec_helper' require 'puppet/transaction/report' require 'puppet/indirector/report/json' describe Puppet::Transaction::Report::Json do include PuppetSpec::Files describe '#save' do subject(:indirection) { described_class.indirection } let(:request) { described_class.new } let(:certname) { 'ziggy' } let(:report) do report = Puppet::Transaction::Report.new report.host = certname report end let(:file) { request.path(:me) } before do Puppet[:lastrunreport] = File.join(Puppet[:statedir], "last_run_report.json") indirection.terminus_class = :json end it 'saves the instance of the report as JSON to disk' do indirection.save(report) json = Puppet::FileSystem.read(Puppet[:lastrunreport], :encoding => 'bom|utf-8') content = Puppet::Util::Json.load(json) expect(content["host"]).to eq(certname) end it 'allows mode overwrite' do Puppet.settings.setting(:lastrunreport).mode = '0644' indirection.save(report) if Puppet::Util::Platform.windows? mode = File.stat(file).mode else mode = Puppet::FileSystem.stat(file).mode end expect(mode & 07777).to eq(0644) end context 'when mode is invalid' do before do Puppet.settings.setting(:lastrunreport).mode = '9999' end after do Puppet.settings.setting(:lastrunreport).mode = '0644' end it 'raises Puppet::DevError ' do expect{ indirection.save(report) }.to raise_error(Puppet::DevError, "replace_file mode: 9999 is invalid") end end context 'when report cannot be saved' do it 'raises Error' do FileUtils.mkdir_p(file) expect { indirection.save(report) }.to raise_error(Errno::EISDIR, /last_run_report.json/) 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/indirector/report/yaml_spec.rb
spec/unit/indirector/report/yaml_spec.rb
require 'spec_helper' require 'puppet/transaction/report' require 'puppet/indirector/report/yaml' describe Puppet::Transaction::Report::Yaml do it "should be registered with the report indirection" do indirection = Puppet::Indirector::Indirection.instance(:report) expect(Puppet::Transaction::Report::Yaml.indirection).to equal(indirection) end it "should have its name set to :yaml" do expect(Puppet::Transaction::Report::Yaml.name).to eq(:yaml) end it "should unconditionally save/load from the --lastrunreport setting" do expect(subject.path(:me)).to eq(Puppet[:lastrunreport]) end describe '#save' do subject(:indirection) { described_class.indirection } let(:request) { described_class.new } let(:certname) { 'ziggy' } let(:report) do report = Puppet::Transaction::Report.new report.host = certname report end let(:file) { request.path(:me) } before do indirection.terminus_class = :yaml end it 'saves the instance of the report as YAML to disk' do indirection.save(report) content = Puppet::Util::Yaml.safe_load_file( Puppet[:lastrunreport], [Puppet::Transaction::Report] ) expect(content.host).to eq(certname) end it 'allows mode overwrite' do Puppet.settings.setting(:lastrunreport).mode = '0644' indirection.save(report) if Puppet::Util::Platform.windows? mode = File.stat(file).mode else mode = Puppet::FileSystem.stat(file).mode end expect(mode & 07777).to eq(0644) end context 'when mode is invalid' do before do Puppet.settings.setting(:lastrunreport).mode = '9999' end after do Puppet.settings.setting(:lastrunreport).mode = '0644' end it 'raises Puppet::DevError ' do expect{ indirection.save(report) }.to raise_error(Puppet::DevError, "replace_file mode: 9999 is invalid") end end context 'when repport is invalid' do it 'logs error' do expect(Puppet).to receive(:send_log).with(:err, /Could not save yaml ziggy: can't dump anonymous class/) report.configuration_version = Class.new indirection.save(report) end end context 'when report cannot be saved' do it 'raises Error' do FileUtils.mkdir_p(file) expect { indirection.save(report) }.to raise_error(Errno::EISDIR, /last_run_report.yaml/) 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/indirector/file_metadata/file_spec.rb
spec/unit/indirector/file_metadata/file_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/file' describe Puppet::Indirector::FileMetadata::File do it "should be registered with the file_metadata indirection" do expect(Puppet::Indirector::Terminus.terminus_class(:file_metadata, :file)).to equal(Puppet::Indirector::FileMetadata::File) end it "should be a subclass of the DirectFileServer terminus" do expect(Puppet::Indirector::FileMetadata::File.superclass).to equal(Puppet::Indirector::DirectFileServer) end describe "when creating the instance for a single found file" do before do @metadata = Puppet::Indirector::FileMetadata::File.new @path = File.expand_path('/my/local') @uri = Puppet::Util.path_to_uri(@path).to_s @data = double('metadata') allow(@data).to receive(:collect) expect(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true) @request = Puppet::Indirector::Request.new(:file_metadata, :find, @uri, nil) end it "should collect its attributes when a file is found" do expect(@data).to receive(:collect) expect(Puppet::FileServing::Metadata).to receive(:new).and_return(@data) expect(@metadata.find(@request)).to eq(@data) end end describe "when searching for multiple files" do before do @metadata = Puppet::Indirector::FileMetadata::File.new @path = File.expand_path('/my/local') @uri = Puppet::Util.path_to_uri(@path).to_s @request = Puppet::Indirector::Request.new(:file_metadata, :find, @uri, nil) end it "should collect the attributes of the instances returned" do expect(Puppet::FileSystem).to receive(:exist?).with(@path).and_return(true) expect(Puppet::FileServing::Fileset).to receive(:new).with(@path, @request).and_return(double("fileset")) expect(Puppet::FileServing::Fileset).to receive(:merge).and_return([["one", @path], ["two", @path]]) one = double("one", :collect => nil) expect(Puppet::FileServing::Metadata).to receive(:new).with(@path, {:relative_path => "one"}).and_return(one) two = double("two", :collect => nil) expect(Puppet::FileServing::Metadata).to receive(:new).with(@path, {:relative_path => "two"}).and_return(two) expect(@metadata.search(@request)).to eq([one, two]) 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/indirector/file_metadata/selector_spec.rb
spec/unit/indirector/file_metadata/selector_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/selector' describe Puppet::Indirector::FileMetadata::Selector do include PuppetSpec::Files it_should_behave_like "Puppet::FileServing::Files", :file_metadata end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/file_metadata/rest_spec.rb
spec/unit/indirector/file_metadata/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata' require 'puppet/indirector/file_metadata/rest' describe Puppet::Indirector::FileMetadata::Rest do let(:certname) { 'ziggy' } let(:formatter) { Puppet::Network::FormatHandler.format(:json) } let(:model) { described_class.model } before :each do described_class.indirection.terminus_class = :rest end def metadata_response(metadata) { body: formatter.render(metadata), headers: {'Content-Type' => formatter.mime } } end context "when finding" do let(:uri) { %r{/puppet/v3/file_metadata/:mount/path/to/file} } let(:key) { "puppet:///:mount/path/to/file" } let(:metadata) { model.new('/path/to/file') } it "returns file metadata" do stub_request(:get, uri) .to_return(status: 200, **metadata_response(metadata)) result = model.indirection.find(key) expect(result.path).to eq('/path/to/file') end it "URL encodes special characters" do stub_request(:get, %r{/puppet/v3/file_metadata/:mount/path%20to%20file}) .to_return(status: 200, **metadata_response(metadata)) model.indirection.find('puppet:///:mount/path to file') end it "returns nil if the content doesn't exist" do stub_request(:get, uri).to_return(status: 404) expect(model.indirection.find(key)).to be_nil end it "raises if fail_on_404 is true" do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { model.indirection.find(key, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/file_metadata/:mount/path/to/file resulted in 404 with the message: {}}) end it "raises an error on HTTP 500" do stub_request(:get, uri).to_return(status: 500, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { model.indirection.find(key) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end it "connects to a specific host" do stub_request(:get, %r{https://example.com:8140/puppet/v3/file_metadata/:mount/path/to/file}) .to_return(status: 200, **metadata_response(metadata)) model.indirection.find("puppet://example.com:8140/:mount/path/to/file") end end context "when searching" do let(:uri) { %r{/puppet/v3/file_metadatas/:mount/path/to/dir} } let(:key) { "puppet:///:mount/path/to/dir" } let(:metadatas) { [model.new('/path/to/dir')] } it "returns an array of file metadata" do stub_request(:get, uri) .to_return(status: 200, **metadata_response(metadatas)) result = model.indirection.search(key) expect(result.first.path).to eq('/path/to/dir') end it "URL encodes special characters" do stub_request(:get, %r{/puppet/v3/file_metadatas/:mount/path%20to%20dir}) .to_return(status: 200, **metadata_response(metadatas)) model.indirection.search('puppet:///:mount/path to dir') end it "returns an empty array if the metadata doesn't exist" do stub_request(:get, uri).to_return(status: 404) expect(model.indirection.search(key)).to eq([]) end it "returns an empty array if the metadata doesn't exist and fail_on_404 is true" do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect(model.indirection.search(key, fail_on_404: true)).to eq([]) end it "raises an error on HTTP 500" do stub_request(:get, uri).to_return(status: 500, headers: { 'Content-Type' => 'application/json'}, body: "{}") expect { model.indirection.search(key) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end it "connects to a specific host" do stub_request(:get, %r{https://example.com:8140/puppet/v3/file_metadatas/:mount/path/to/dir}) .to_return(status: 200, **metadata_response(metadatas)) model.indirection.search("puppet://example.com:8140/:mount/path/to/dir") 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/indirector/file_metadata/http_spec.rb
spec/unit/indirector/file_metadata/http_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata' require 'puppet/indirector/file_metadata/http' describe Puppet::Indirector::FileMetadata::Http do DEFAULT_HEADERS = { "Cache-Control" => "private, max-age=0", "Connection" => "close", "Content-Encoding" => "gzip", "Content-Type" => "text/html; charset=ISO-8859-1", "Date" => "Fri, 01 May 2020 17:16:00 GMT", "Expires" => "-1", "Server" => "gws" }.freeze let(:certname) { 'ziggy' } # The model is Puppet:FileServing::Metadata let(:model) { described_class.model } # The http terminus creates instances of HttpMetadata which subclass Metadata let(:metadata) { Puppet::FileServing::HttpMetadata.new(key) } let(:key) { "https://example.com/path/to/file" } # Digest::MD5.base64digest("") => "1B2M2Y8AsgTpgAmY7PhCfg==" let(:content_md5) { {"Content-MD5" => "1B2M2Y8AsgTpgAmY7PhCfg=="} } let(:last_modified) { {"Last-Modified" => "Wed, 01 Jan 2020 08:00:00 GMT"} } before :each do described_class.indirection.terminus_class = :http end context "when finding" do it "returns http file metadata" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS) result = model.indirection.find(key) expect(result.ftype).to eq('file') expect(result.path).to eq('/dev/null') expect(result.relative_path).to be_nil expect(result.destination).to be_nil expect(result.checksum).to match(%r{mtime}) expect(result.owner).to be_nil expect(result.group).to be_nil expect(result.mode).to be_nil end it "reports an md5 checksum if present in the response" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(content_md5)) result = model.indirection.find(key) expect(result.checksum_type).to eq(:md5) expect(result.checksum).to eq("{md5}d41d8cd98f00b204e9800998ecf8427e") end it "reports an mtime checksum if present in the response" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(last_modified)) result = model.indirection.find(key) expect(result.checksum_type).to eq(:mtime) expect(result.checksum).to eq("{mtime}2020-01-01 08:00:00 UTC") end it "prefers md5" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(content_md5).merge(last_modified)) result = model.indirection.find(key) expect(result.checksum_type).to eq(:md5) expect(result.checksum).to eq("{md5}d41d8cd98f00b204e9800998ecf8427e") end it "prefers mtime when explicitly requested" do stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge(content_md5).merge(last_modified)) result = model.indirection.find(key, checksum_type: :mtime) expect(result.checksum_type).to eq(:mtime) expect(result.checksum).to eq("{mtime}2020-01-01 08:00:00 UTC") end it "leniently parses base64" do # Content-MD5 header is missing '==' padding stub_request(:head, key) .to_return(status: 200, headers: DEFAULT_HEADERS.merge("Content-MD5" => "1B2M2Y8AsgTpgAmY7PhCfg")) result = model.indirection.find(key) expect(result.checksum_type).to eq(:md5) expect(result.checksum).to eq("{md5}d41d8cd98f00b204e9800998ecf8427e") end it "URL encodes special characters" do pending("HTTP terminus doesn't encode the URI before parsing") stub_request(:head, %r{/path%20to%20file}) model.indirection.find('https://example.com/path to file') end it "sends query parameters" do stub_request(:head, key).with(query: {'a' => 'b'}) model.indirection.find("#{key}?a=b") end it "returns nil if the content doesn't exist" do stub_request(:head, key).to_return(status: 404) expect(model.indirection.find(key)).to be_nil end it "returns nil if fail_on_404" do stub_request(:head, key).to_return(status: 404) expect(model.indirection.find(key, fail_on_404: true)).to be_nil end it "returns nil on HTTP 500" do stub_request(:head, key).to_return(status: 500) # this is kind of strange, but it does allow puppet to try # multiple `source => ["URL1", "URL2"]` and use the first # one based on sourceselect expect(model.indirection.find(key)).to be_nil end it "accepts all content types" do stub_request(:head, key).with(headers: {'Accept' => '*/*'}) model.indirection.find(key) end it "sets puppet user-agent" do stub_request(:head, key).with(headers: {'User-Agent' => Puppet[:http_user_agent]}) model.indirection.find(key) end it "tries to persist the connection" do # HTTP/1.1 defaults to persistent connections, so check for # the header's absence stub_request(:head, key).with do |request| expect(request.headers).to_not include('Connection') end model.indirection.find(key) end it "follows redirects" do new_url = "https://example.com/different/path" redirect = { status: 200, headers: { 'Location' => new_url }, body: ""} stub_request(:head, key).to_return(redirect) stub_request(:head, new_url) model.indirection.find(key) end it "falls back to partial GET if HEAD is not allowed" do stub_request(:head, key) .to_return(status: 405) stub_request(:get, key) .to_return(status: 200, headers: {'Range' => 'bytes=0-0'}) model.indirection.find(key) end it "falls back to partial GET if HEAD is forbidden" do stub_request(:head, key) .to_return(status: 403) stub_request(:get, key) .to_return(status: 200, headers: {'Range' => 'bytes=0-0'}) model.indirection.find(key) end it "returns nil if the partial GET fails" do stub_request(:head, key) .to_return(status: 403) stub_request(:get, key) .to_return(status: 403) expect(model.indirection.find(key)).to be_nil end end context "when searching" do it "raises an error" do expect { model.indirection.search(key) }.to raise_error(Puppet::Error, 'cannot lookup multiple files') 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/indirector/file_metadata/file_server_spec.rb
spec/unit/indirector/file_metadata/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/file_server' describe Puppet::Indirector::FileMetadata::FileServer do it "should be registered with the file_metadata indirection" do expect(Puppet::Indirector::Terminus.terminus_class(:file_metadata, :file_server)).to equal(Puppet::Indirector::FileMetadata::FileServer) end it "should be a subclass of the FileServer terminus" do expect(Puppet::Indirector::FileMetadata::FileServer.superclass).to equal(Puppet::Indirector::FileServer) 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/indirector/data_binding/hiera_spec.rb
spec/unit/indirector/data_binding/hiera_spec.rb
require 'spec_helper' require 'puppet/indirector/data_binding/hiera' describe Puppet::DataBinding::Hiera do it "should have documentation" do expect(Puppet::DataBinding::Hiera.doc).not_to be_nil end it "should be registered with the data_binding indirection" do indirection = Puppet::Indirector::Indirection.instance(:data_binding) expect(Puppet::DataBinding::Hiera.indirection).to equal(indirection) end it "should have its name set to :hiera" do expect(Puppet::DataBinding::Hiera.name).to eq(:hiera) end it_should_behave_like "Hiera indirection", Puppet::DataBinding::Hiera, my_fixture_dir end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/data_binding/none_spec.rb
spec/unit/indirector/data_binding/none_spec.rb
require 'spec_helper' require 'puppet/indirector/data_binding/none' describe Puppet::DataBinding::None do it "should be a subclass of the None terminus" do expect(Puppet::DataBinding::None.superclass).to equal(Puppet::Indirector::None) end it "should have documentation" do expect(Puppet::DataBinding::None.doc).not_to be_nil end it "should be registered with the data_binding indirection" do indirection = Puppet::Indirector::Indirection.instance(:data_binding) expect(Puppet::DataBinding::None.indirection).to equal(indirection) end it "should have its name set to :none" do expect(Puppet::DataBinding::None.name).to eq(:none) end describe "the behavior of the find method" do it "should just throw :no_such_key" do data_binding = Puppet::DataBinding::None.new expect { data_binding.find('fake_request') }.to throw_symbol(:no_such_key) 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/indirector/facts/facter_spec.rb
spec/unit/indirector/facts/facter_spec.rb
require 'spec_helper' require 'puppet/indirector/facts/facter' class Puppet::Node::Facts::Facter::MyCollection < Hash; end describe Puppet::Node::Facts::Facter do FS = Puppet::FileSystem it "should be a subclass of the Code terminus" do expect(Puppet::Node::Facts::Facter.superclass).to equal(Puppet::Indirector::Code) end it "should have documentation" do expect(Puppet::Node::Facts::Facter.doc).not_to be_nil end it "should be registered with the configuration store indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::Facter.indirection).to equal(indirection) end it "should have its name set to :facter" do expect(Puppet::Node::Facts::Facter.name).to eq(:facter) end before :each do @facter = Puppet::Node::Facts::Facter.new allow(Facter).to receive(:to_hash).and_return({}) @name = "me" @request = double('request', :key => @name) @environment = double('environment') allow(@request).to receive(:environment).and_return(@environment) allow(@request).to receive(:options).and_return({}) allow(@request.environment).to receive(:modules).and_return([]) allow(@request.environment).to receive(:modulepath).and_return([]) end describe 'when finding facts' do it 'should reset facts' do expect(Facter).to receive(:reset).ordered expect(Puppet::Node::Facts::Facter).to receive(:setup_search_paths).ordered @facter.find(@request) end it 'should add the puppetversion and agent_specified_environment facts' do expect(Facter).to receive(:reset).ordered expect(Facter).to receive(:add).with(:puppetversion) expect(Facter).to receive(:add).with(:agent_specified_environment) @facter.find(@request) end it 'should include external facts' do expect(Facter).to receive(:reset).ordered expect(Puppet::Node::Facts::Facter).to receive(:setup_external_search_paths).ordered expect(Puppet::Node::Facts::Facter).to receive(:setup_search_paths).ordered @facter.find(@request) end it "should return a Facts instance" do expect(@facter.find(@request)).to be_instance_of(Puppet::Node::Facts) end it "should return a Facts instance with the provided key as the name" do expect(@facter.find(@request).name).to eq(@name) end it "should return the Facter facts as the values in the Facts instance" do expect(Facter).to receive(:resolve).and_return("one" => "two") facts = @facter.find(@request) expect(facts.values["one"]).to eq("two") end it "should add local facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:add_local_facts) @facter.find(@request) end it "should sanitize facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:sanitize) @facter.find(@request) end it "can exclude legacy facts" do Puppet[:include_legacy_facts] = false expect(Puppet.runtime[:facter]).to receive(:resolve).with('') .and_return({'kernelversion' => '1.2.3'}) values = @facter.find(@request).values expect(values).to be_an_instance_of(Hash) expect(values).to include({'kernelversion' => '1.2.3'}) end it "can exclude legacy facts using buggy facter implementations that return a Hash subclass" do Puppet[:include_legacy_facts] = false collection = Puppet::Node::Facts::Facter::MyCollection["kernelversion" => '1.2.3'] expect(Puppet.runtime[:facter]).to receive(:resolve).with('') .and_return(collection) values = @facter.find(@request).values expect(values).to be_an_instance_of(Hash) expect(values).to include({'kernelversion' => '1.2.3'}) end end it 'should fail when saving facts' do expect { @facter.save(@facts) }.to raise_error(Puppet::DevError) end it 'should fail when destroying facts' do expect { @facter.destroy(@facts) }.to raise_error(Puppet::DevError) end describe 'when setting up search paths' do let(:factpath1) { File.expand_path 'one' } let(:factpath2) { File.expand_path 'two' } let(:factpath) { [factpath1, factpath2].join(File::PATH_SEPARATOR) } let(:modulepath) { File.expand_path 'module/foo' } let(:modulelibfacter) { File.expand_path 'module/foo/lib/facter' } let(:modulepluginsfacter) { File.expand_path 'module/foo/plugins/facter' } before :each do expect(FileTest).to receive(:directory?).with(factpath1).and_return(true) expect(FileTest).to receive(:directory?).with(factpath2).and_return(true) allow(@request.environment).to receive(:modulepath).and_return([modulepath]) allow(@request).to receive(:options).and_return({}) expect(Dir).to receive(:glob).with("#{modulepath}/*/lib/facter").and_return([modulelibfacter]) expect(Dir).to receive(:glob).with("#{modulepath}/*/plugins/facter").and_return([modulepluginsfacter]) Puppet[:factpath] = factpath end it 'should skip files' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(false) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(false) expect(Facter).to receive(:search).with(factpath1, factpath2) Puppet::Node::Facts::Facter.setup_search_paths @request end it 'should add directories' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(true) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(true) expect(Facter).to receive(:search).with(modulelibfacter, modulepluginsfacter, factpath1, factpath2) Puppet::Node::Facts::Facter.setup_search_paths @request end end describe 'when setting up external search paths' do let(:pluginfactdest) { File.expand_path 'plugin/dest' } let(:modulepath) { File.expand_path 'module/foo' } let(:modulefactsd) { File.expand_path 'module/foo/facts.d' } before :each do expect(FileTest).to receive(:directory?).with(pluginfactdest).and_return(true) mod = Puppet::Module.new('foo', modulepath, @request.environment) allow(@request.environment).to receive(:modules).and_return([mod]) Puppet[:pluginfactdest] = pluginfactdest end it 'should skip files' do expect(File).to receive(:directory?).with(modulefactsd).and_return(false) expect(Facter).to receive(:search_external).with([pluginfactdest]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end it 'should add directories' do expect(File).to receive(:directory?).with(modulefactsd).and_return(true) expect(Facter).to receive(:search_external).with([modulefactsd, pluginfactdest]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end end describe 'when :resolve_options is true' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"] } } let(:facts) { Puppet::Node::Facts.new("foo") } before :each do allow(@request).to receive(:options).and_return(options) allow(Puppet::Node::Facts).to receive(:new).and_return(facts) allow(facts).to receive(:add_local_facts) end it 'should call Facter.resolve method' do expect(Facter).to receive(:resolve).with("os timezone") @facter.find(@request) end it 'should NOT add local facts' do expect(facts).not_to receive(:add_local_facts) @facter.find(@request) end context 'when --show-legacy flag is present' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"], show_legacy: true } } it 'should call Facter.resolve method with show-legacy' do expect(Facter).to receive(:resolve).with("os timezone --show-legacy") @facter.find(@request) end end context 'when --timing flag is present' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"], timing: true } } it 'calls Facter.resolve with --timing' do expect(Facter).to receive(:resolve).with("os timezone --timing") @facter.find(@request) end end describe 'when Facter version is lower than 4.0.40' do before :each do allow(Facter).to receive(:respond_to?).and_return(false) allow(Facter).to receive(:respond_to?).with(:resolve).and_return(false) end it 'raises an error' do expect { @facter.find(@request) }.to raise_error(Puppet::Error, "puppet facts show requires version 4.0.40 or greater of Facter.") end end describe 'when setting up external search paths' do let(:options) { { resolve_options: true, user_query: ["os", "timezone"], external_dir: 'some/dir' } } let(:pluginfactdest) { File.expand_path 'plugin/dest' } let(:modulepath) { File.expand_path 'module/foo' } let(:modulefactsd) { File.expand_path 'module/foo/facts.d' } before :each do expect(FileTest).to receive(:directory?).with(pluginfactdest).and_return(true) mod = Puppet::Module.new('foo', modulepath, @request.environment) allow(@request.environment).to receive(:modules).and_return([mod]) Puppet[:pluginfactdest] = pluginfactdest end it 'should skip files' do expect(File).to receive(:directory?).with(modulefactsd).and_return(false) expect(Facter).to receive(:search_external).with([pluginfactdest, options[:external_dir]]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end it 'should add directories' do expect(File).to receive(:directory?).with(modulefactsd).and_return(true) expect(Facter).to receive(:search_external).with([modulefactsd, pluginfactdest, options[:external_dir]]) Puppet::Node::Facts::Facter.setup_external_search_paths @request end end describe 'when setting up search paths' do let(:factpath1) { File.expand_path 'one' } let(:factpath2) { File.expand_path 'two' } let(:factpath) { [factpath1, factpath2].join(File::PATH_SEPARATOR) } let(:modulepath) { File.expand_path 'module/foo' } let(:modulelibfacter) { File.expand_path 'module/foo/lib/facter' } let(:modulepluginsfacter) { File.expand_path 'module/foo/plugins/facter' } let(:options) { { resolve_options: true, custom_dir: 'some/dir' } } before :each do expect(FileTest).to receive(:directory?).with(factpath1).and_return(true) expect(FileTest).to receive(:directory?).with(factpath2).and_return(true) allow(@request.environment).to receive(:modulepath).and_return([modulepath]) expect(Dir).to receive(:glob).with("#{modulepath}/*/lib/facter").and_return([modulelibfacter]) expect(Dir).to receive(:glob).with("#{modulepath}/*/plugins/facter").and_return([modulepluginsfacter]) Puppet[:factpath] = factpath end it 'should skip files' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(false) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(false) expect(Facter).to receive(:search).with(factpath1, factpath2, options[:custom_dir]) Puppet::Node::Facts::Facter.setup_search_paths @request end it 'should add directories' do expect(FileTest).to receive(:directory?).with(modulelibfacter).and_return(true) expect(FileTest).to receive(:directory?).with(modulepluginsfacter).and_return(false) expect(Facter).to receive(:search).with(modulelibfacter, factpath1, factpath2, options[:custom_dir]) Puppet::Node::Facts::Facter.setup_search_paths @request 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/indirector/facts/network_device_spec.rb
spec/unit/indirector/facts/network_device_spec.rb
require 'spec_helper' require 'puppet/util/network_device' require 'puppet/indirector/facts/network_device' describe Puppet::Node::Facts::NetworkDevice do it "should be a subclass of the Code terminus" do expect(Puppet::Node::Facts::NetworkDevice.superclass).to equal(Puppet::Indirector::Code) end it "should have documentation" do expect(Puppet::Node::Facts::NetworkDevice.doc).not_to be_nil end it "should be registered with the configuration store indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::NetworkDevice.indirection).to equal(indirection) end it "should have its name set to :facter" do expect(Puppet::Node::Facts::NetworkDevice.name).to eq(:network_device) end end describe Puppet::Node::Facts::NetworkDevice do before :each do @remote_device = double('remote_device', :facts => {}) allow(Puppet::Util::NetworkDevice).to receive(:current).and_return(@remote_device) @device = Puppet::Node::Facts::NetworkDevice.new @name = "me" @request = double('request', :key => @name) end describe Puppet::Node::Facts::NetworkDevice, " when finding facts" do it "should return a Facts instance" do expect(@device.find(@request)).to be_instance_of(Puppet::Node::Facts) end it "should return a Facts instance with the provided key as the name" do expect(@device.find(@request).name).to eq(@name) end it "should return the device facts as the values in the Facts instance" do expect(@remote_device).to receive(:facts).and_return("one" => "two") facts = @device.find(@request) expect(facts.values["one"]).to eq("two") end it "should add local facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:add_local_facts) @device.find(@request) end it "should sanitize facts" do facts = Puppet::Node::Facts.new("foo") expect(Puppet::Node::Facts).to receive(:new).and_return(facts) expect(facts).to receive(:sanitize) @device.find(@request) end end describe Puppet::Node::Facts::NetworkDevice, " when saving facts" do it "should fail" do expect { @device.save(@facts) }.to raise_error(Puppet::DevError) end end describe Puppet::Node::Facts::NetworkDevice, " when destroying facts" do it "should fail" do expect { @device.destroy(@facts) }.to raise_error(Puppet::DevError) 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/indirector/facts/rest_spec.rb
spec/unit/indirector/facts/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/facts/rest' describe Puppet::Node::Facts::Rest do let(:certname) { 'ziggy' } let(:uri) { %r{/puppet/v3/facts/ziggy} } let(:facts) { Puppet::Node::Facts.new(certname, test_fact: 'test value') } before do Puppet[:server] = 'compiler.example.com' Puppet[:serverport] = 8140 described_class.indirection.terminus_class = :rest end describe '#find' do let(:formatter) { Puppet::Network::FormatHandler.format(:json) } def facts_response(facts) { body: formatter.render(facts), headers: {'Content-Type' => formatter.mime } } end it 'finds facts' do stub_request(:get, uri).to_return(**facts_response(facts)) expect(described_class.indirection.find(certname)).to be_a(Puppet::Node::Facts) end it "serializes the environment" do stub_request(:get, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(**facts_response(facts)) described_class.indirection.find(certname, environment: Puppet::Node::Environment.remote('outerspace')) end it 'returns nil if the facts do not exist' do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect(described_class.indirection.find(certname)).to be_nil end it 'raises if fail_on_404 is specified' do stub_request(:get, uri).to_return(status: 404, headers: { 'Content-Type' => 'application/json' }, body: "{}") expect{ described_class.indirection.find(certname, fail_on_404: true) }.to raise_error(Puppet::Error, %r{Find /puppet/v3/facts/ziggy resulted in 404 with the message: {}}) end it 'raises Net::HTTPError on 500' do stub_request(:get, uri).to_return(status: 500) expect{ described_class.indirection.find(certname) }.to raise_error(Net::HTTPError, %r{Error 500 on SERVER: }) end end describe '#save' do it 'returns nil on success' do stub_request(:put, %r{/puppet/v3/facts}) .to_return(status: 200, headers: { 'Content-Type' => 'application/json'}, body: '') expect(described_class.indirection.save(facts)).to be_nil end it "serializes the environment" do stub_request(:put, uri) .with(query: hash_including('environment' => 'outerspace')) .to_return(status: 200, headers: { 'Content-Type' => 'application/json'}, body: '') described_class.indirection.save(facts, nil, environment: Puppet::Node::Environment.remote('outerspace')) end it 'raises if options are specified' do expect { described_class.indirection.save(facts, nil, foo: :bar) }.to raise_error(ArgumentError, /PUT does not accept options/) end it 'raises with HTTP 404' do stub_request(:put, %r{/puppet/v3/facts}).to_return(status: 404) expect { described_class.indirection.save(facts) }.to raise_error(Net::HTTPError, /Error 404 on SERVER/) end it 'raises with HTTP 500' do stub_request(:put, %r{/puppet/v3/facts}).to_return(status: 500) expect { described_class.indirection.save(facts) }.to raise_error(Net::HTTPError, /Error 500 on SERVER/) 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/indirector/facts/store_configs_spec.rb
spec/unit/indirector/facts/store_configs_spec.rb
require 'spec_helper' require 'puppet/node' require 'puppet/indirector/memory' require 'puppet/indirector/facts/store_configs' class Puppet::Node::Facts::StoreConfigsTesting < Puppet::Indirector::Memory end describe Puppet::Node::Facts::StoreConfigs do after :all do Puppet::Node::Facts.indirection.reset_terminus_class Puppet::Node::Facts.indirection.cache_class = nil end it_should_behave_like "a StoreConfigs terminus" end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/facts/json_spec.rb
spec/unit/indirector/facts/json_spec.rb
require 'spec_helper' require 'puppet/node/facts' require 'puppet/indirector/facts/json' def dir_containing_json_facts(hash) jsondir = tmpdir('json_facts') Puppet[:client_datadir] = jsondir dir = File.join(jsondir, 'facts') Dir.mkdir(dir) hash.each_pair do |file, facts| File.open(File.join(dir, file), 'wb') do |f| f.write(JSON.dump(facts)) end end end describe Puppet::Node::Facts::Json do include PuppetSpec::Files it "should be a subclass of the Json terminus" do expect(Puppet::Node::Facts::Json.superclass).to equal(Puppet::Indirector::JSON) end it "should have documentation" do expect(Puppet::Node::Facts::Json.doc).not_to be_nil expect(Puppet::Node::Facts::Json.doc).not_to be_empty end it "should be registered with the facts indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::Json.indirection).to equal(indirection) end it "should have its name set to :json" do expect(Puppet::Node::Facts::Json.name).to eq(:json) end it "should allow network requests" do # Doesn't allow json as a network format, but allows `puppet facts upload` # to update the JSON cache on a master. expect(Puppet::Node::Facts::Json.new.allow_remote_requests?).to be(true) end describe "#search" do def assert_search_matches(matching, nonmatching, query) request = Puppet::Indirector::Request.new(:inventory, :search, nil, nil, query) dir_containing_json_facts(matching.merge(nonmatching)) results = Puppet::Node::Facts::Json.new.search(request) expect(results).to match_array(matching.values.map {|facts| facts.name}) end it "should return node names that match the search query options" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '4'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "i386", 'processor_count' => '4', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching1.json" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.architecture' => 'i386', 'facts.processor_count' => '4'} ) end it "should return empty array when no nodes match the search query options" do assert_search_matches({}, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '10'), "nonmatching1.json" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.processor_count.lt' => '4', 'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the greater than operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '10', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '3'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the less than operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '30', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '50' ), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '100'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.lt' => '50'} ) end it "should return node names that match the search query options with the less than or equal to operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '100' ), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5000'), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.le' => '50'} ) end it "should return node names that match the search query options with the greater than or equal to operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '100'), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '40'), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.ge' => '50'} ) end it "should return node names that match the search query options with the not equal operator" do assert_search_matches({ 'matching.json' => Puppet::Node::Facts.new("matchingnode", "architecture" => 'arm' ), 'matching1.json' => Puppet::Node::Facts.new("matchingnode1", "architecture" => 'powerpc', 'randomfact' => 'foo') }, { "nonmatching.json" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "i386" ), "nonmatching2.json" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.json" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.architecture.ne' => 'i386'} ) end def apply_timestamp(facts, timestamp) facts.timestamp = timestamp facts end it "should be able to query based on meta.timestamp.gt" do assert_search_matches({ '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, { '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.gt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.le" do assert_search_matches({ '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, {'meta.timestamp.le' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.lt" do assert_search_matches({ '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.lt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ge" do assert_search_matches({ '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.ge' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.eq" do assert_search_matches({ '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.eq' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp" do assert_search_matches({ '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ne" do assert_search_matches({ '2010-11-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-10-15.json' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.ne' => '2010-10-15'} ) 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/indirector/facts/yaml_spec.rb
spec/unit/indirector/facts/yaml_spec.rb
require 'spec_helper' require 'puppet/node/facts' require 'puppet/indirector/facts/yaml' def dir_containing_facts(hash) yamldir = tmpdir('yaml_facts') Puppet[:clientyamldir] = yamldir dir = File.join(yamldir, 'facts') Dir.mkdir(dir) hash.each_pair do |file, facts| File.open(File.join(dir, file), 'wb') do |f| f.write(YAML.dump(facts)) end end end describe Puppet::Node::Facts::Yaml do include PuppetSpec::Files it "should be a subclass of the Yaml terminus" do expect(Puppet::Node::Facts::Yaml.superclass).to equal(Puppet::Indirector::Yaml) end it "should have documentation" do expect(Puppet::Node::Facts::Yaml.doc).not_to be_nil expect(Puppet::Node::Facts::Yaml.doc).not_to be_empty end it "should be registered with the facts indirection" do indirection = Puppet::Indirector::Indirection.instance(:facts) expect(Puppet::Node::Facts::Yaml.indirection).to equal(indirection) end it "should have its name set to :yaml" do expect(Puppet::Node::Facts::Yaml.name).to eq(:yaml) end it "should allow network requests" do # Doesn't allow yaml as a network format, but allows `puppet facts upload` # to update the YAML cache on a master. expect(Puppet::Node::Facts::Yaml.new.allow_remote_requests?).to be(true) end describe "#search" do def assert_search_matches(matching, nonmatching, query) request = Puppet::Indirector::Request.new(:inventory, :search, nil, nil, query) dir_containing_facts(matching.merge(nonmatching)) results = Puppet::Node::Facts::Yaml.new.search(request) expect(results).to match_array(matching.values.map {|facts| facts.name}) end it "should return node names that match the search query options" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '4'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "i386", 'processor_count' => '4', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching1.yaml" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.architecture' => 'i386', 'facts.processor_count' => '4'} ) end it "should return empty array when no nodes match the search query options" do assert_search_matches({}, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '10'), "nonmatching1.yaml" => Puppet::Node::Facts.new("nonmatchingnode1", "architecture" => "powerpc", 'processor_count' => '5'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3", 'processor_count' => '4'), }, {'facts.processor_count.lt' => '4', 'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the greater than operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '10', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '4'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '3'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.gt' => '4'} ) end it "should return node names that match the search query options with the less than operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '30', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '50' ), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '100'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.lt' => '50'} ) end it "should return node names that match the search query options with the less than or equal to operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '5'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '100' ), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '5000'), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.le' => '50'} ) end it "should return node names that match the search query options with the greater than or equal to operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => "i386", 'processor_count' => '100'), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => "powerpc", 'processor_count' => '50', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "powerpc", 'processor_count' => '40'), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.processor_count.ge' => '50'} ) end it "should return node names that match the search query options with the not equal operator" do assert_search_matches({ 'matching.yaml' => Puppet::Node::Facts.new("matchingnode", "architecture" => 'arm' ), 'matching1.yaml' => Puppet::Node::Facts.new("matchingnode1", "architecture" => 'powerpc', 'randomfact' => 'foo') }, { "nonmatching.yaml" => Puppet::Node::Facts.new("nonmatchingnode", "architecture" => "i386" ), "nonmatching2.yaml" => Puppet::Node::Facts.new("nonmatchingnode2", "architecture" => "i386", 'processor_count' => '9' ), "nonmatching3.yaml" => Puppet::Node::Facts.new("nonmatchingnode3" ), }, {'facts.architecture.ne' => 'i386'} ) end def apply_timestamp(facts, timestamp) facts.timestamp = timestamp facts end it "should be able to query based on meta.timestamp.gt" do assert_search_matches({ '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, { '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.gt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.le" do assert_search_matches({ '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), }, {'meta.timestamp.le' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.lt" do assert_search_matches({ '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.lt' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ge" do assert_search_matches({ '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.ge' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.eq" do assert_search_matches({ '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp.eq' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp" do assert_search_matches({ '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, { '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, {'meta.timestamp' => '2010-10-15'} ) end it "should be able to query based on meta.timestamp.ne" do assert_search_matches({ '2010-11-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-01", {}), Time.parse("2010-11-01")), '2010-11-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-11-10", {}), Time.parse("2010-11-10")), '2010-10-01.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-01", {}), Time.parse("2010-10-01")), '2010-10-10.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-10", {}), Time.parse("2010-10-10")), }, { '2010-10-15.yaml' => apply_timestamp(Puppet::Node::Facts.new("2010-10-15", {}), Time.parse("2010-10-15")), }, {'meta.timestamp.ne' => '2010-10-15'} ) 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/indirector/file_bucket_file/file_spec.rb
spec/unit/indirector/file_bucket_file/file_spec.rb
require 'spec_helper' require 'puppet/indirector/file_bucket_file/file' require 'puppet/util/platform' describe Puppet::FileBucketFile::File, :uses_checksums => true do include PuppetSpec::Files describe "non-stubbing tests" do include PuppetSpec::Files def save_bucket_file(contents, path = "/who_cares") bucket_file = Puppet::FileBucket::File.new(contents) Puppet::FileBucket::File.indirection.save(bucket_file, "#{bucket_file.name}#{path}") bucket_file.checksum_data end describe "when servicing a save request" do it "should return a result whose content is empty" do bucket_file = Puppet::FileBucket::File.new('stuff') result = Puppet::FileBucket::File.indirection.save(bucket_file, "sha256/35bafb1ce99aef3ab068afbaabae8f21fd9b9f02d3a9442e364fa92c0b3eeef0") expect(result.contents).to be_empty end it "deals with multiple processes saving at the same time", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do bucket_file = Puppet::FileBucket::File.new("contents") children = [] 5.times do |count| children << Kernel.fork do save_bucket_file("contents", "/testing") exit(0) end end children.each { |child| Process.wait(child) } paths = File.read("#{Puppet[:bucketdir]}/d/1/b/2/a/5/9/f/d1b2a59fbea7e20077af9f91b27e95e865061b270be03ff539ab3b73587882e8/paths").lines.to_a expect(paths.length).to eq(1) expect(Puppet::FileBucket::File.indirection.head("#{bucket_file.checksum_type}/#{bucket_file.checksum_data}/testing")).to be_truthy end it "fails if the contents collide with existing contents" do Puppet[:digest_algorithm] = 'md5' # This is the shortest known MD5 collision (little endian). See https://eprint.iacr.org/2010/643.pdf first_contents = [0x6165300e,0x87a79a55,0xf7c60bd0,0x34febd0b, 0x6503cf04,0x854f709e,0xfb0fc034,0x874c9c65, 0x2f94cc40,0x15a12deb,0x5c15f4a3,0x490786bb, 0x6d658673,0xa4341f7d,0x8fd75920,0xefd18d5a].pack("V" * 16) collision_contents = [0x6165300e,0x87a79a55,0xf7c60bd0,0x34febd0b, 0x6503cf04,0x854f749e,0xfb0fc034,0x874c9c65, 0x2f94cc40,0x15a12deb,0xdc15f4a3,0x490786bb, 0x6d658673,0xa4341f7d,0x8fd75920,0xefd18d5a].pack("V" * 16) checksum_value = save_bucket_file(first_contents, "/foo/bar") # We expect Puppet to log an error with the path to the file expect(Puppet).to receive(:err).with(/Unable to verify existing FileBucket backup at '#{Puppet[:bucketdir]}.*#{checksum_value}\/contents'/) # But the exception should not contain it expect do save_bucket_file(collision_contents, "/foo/bar") end.to raise_error(Puppet::FileBucket::BucketError, /\AExisting backup and new file have different content but same checksum, {md5}#{checksum_value}\. Verify existing backup and remove if incorrect\.\Z/) end # See PUP-1334 context "when the contents file exists but is corrupted and does not match the expected checksum" do let(:original_contents) { "a file that will get corrupted" } let(:bucket_file) { Puppet::FileBucket::File.new(original_contents) } let(:contents_file) { "#{Puppet[:bucketdir]}/7/7/4/1/0/2/7/9/77410279bb789b799c2f38bf654b46a509dd27ddad6e47a6684805e9ba390bce/contents" } before(:each) do # Ensure we're starting with a clean slate - no pre-existing backup Puppet::FileSystem.unlink(contents_file) if Puppet::FileSystem.exist?(contents_file) # Create initial "correct" backup Puppet::FileBucket::File.indirection.save(bucket_file) # Modify the contents file so that it no longer matches the SHA, simulating a corrupt backup Puppet::FileSystem.unlink(contents_file) # bucket_files are read-only Puppet::Util.replace_file(contents_file, 0600) { |fh| fh.puts "now with corrupted content" } end it "issues a warning that the backup will be overwritten" do expect(Puppet).to receive(:warning).with(/Existing backup does not match its expected sum, #{bucket_file.checksum}/) Puppet::FileBucket::File.indirection.save(bucket_file) end it "overwrites the existing contents file (backup)" do Puppet::FileBucket::File.indirection.save(bucket_file) expect(Puppet::FileSystem.read(contents_file)).to eq(original_contents) end end describe "when supplying a path" do with_digest_algorithms do it "should store the path if not already stored" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else save_bucket_file(plaintext, "/foo/bar") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" contents_file = "#{dir_path}/contents" paths_file = "#{dir_path}/paths" expect(Puppet::FileSystem.binread(contents_file)).to eq(plaintext) expect(Puppet::FileSystem.read(paths_file)).to eq("foo/bar\n") end end it "should leave the paths file alone if the path is already stored" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else # save it twice save_bucket_file(plaintext, "/foo/bar") save_bucket_file(plaintext, "/foo/bar") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext) expect(File.read("#{dir_path}/paths")).to eq("foo/bar\n") end end it "should store an additional path if the new path differs from those already stored" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else save_bucket_file(plaintext, "/foo/bar") save_bucket_file(plaintext, "/foo/baz") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext) expect(File.read("#{dir_path}/paths")).to eq("foo/bar\nfoo/baz\n") end end # end end end describe "when not supplying a path" do with_digest_algorithms do it "should save the file and create an empty paths file" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else save_bucket_file(plaintext, "") dir_path = "#{Puppet[:bucketdir]}/#{bucket_dir}" expect(Puppet::FileSystem.binread("#{dir_path}/contents")).to eq(plaintext) expect(File.read("#{dir_path}/paths")).to eq("") end end end end end describe "when servicing a head/find request" do with_digest_algorithms do let(:not_bucketed_plaintext) { "other stuff" } let(:not_bucketed_checksum) { digest(not_bucketed_plaintext) } describe "when listing the filebucket" do it "should return false/nil when the bucket is empty" do expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar", :list_all => true)).to eq(nil) end it "raises when the request is remote" do Puppet[:bucketdir] = tmpdir('bucket') request = Puppet::Indirector::Request.new(:file_bucket_file, :find, "#{digest_algorithm}/#{checksum}/foo/bar", nil, :list_all => true) request.node = 'client.example.com' expect { Puppet::FileBucketFile::File.new.find(request) }.to raise_error(Puppet::Error, "Listing remote file buckets is not allowed") end it "should return the list of bucketed files in a human readable way" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum1 = save_bucket_file("I'm the contents of a file", '/foo/bar1') checksum2 = save_bucket_file("I'm the contents of another file", '/foo/bar2') checksum3 = save_bucket_file("I'm the modified content of a existing file", '/foo/bar1') # Use the first checksum as we know it's stored in the bucket find_result = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum1}/foo/bar1", :list_all => true) # The list is sort order from date and file name, so first and third checksums come before the second date_pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}' expect(find_result.to_s).to match(Regexp.new("^(#{checksum1}|#{checksum3}) #{date_pattern} foo/bar1\\n(#{checksum3}|#{checksum1}) #{date_pattern} foo/bar1\\n#{checksum2} #{date_pattern} foo/bar2\\n$")) end end it "should fail in an informative way when provided dates are not in the right format" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else contents = "I'm the contents of a file" save_bucket_file(contents, '/foo/bar1') expect { Puppet::FileBucket::File.indirection.find( "#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar", :list_all => true, :todate => "0:0:0 1-1-1970", :fromdate => "WEIRD" ) }.to raise_error(Puppet::Error, /fromdate/) expect { Puppet::FileBucket::File.indirection.find( "#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar", :list_all => true, :todate => "WEIRD", :fromdate => Time.now ) }.to raise_error(Puppet::Error, /todate/) end end end describe "when supplying a path" do it "should return false/nil if the file isn't bucketed" do expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar")).to eq(false) expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}/foo/bar")).to eq(nil) end it "should return false/nil if the file is bucketed but with a different path" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("I'm the contents of a file", '/foo/bar') expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}/foo/baz")).to eq(false) expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}/foo/baz")).to eq(nil) end end it "should return true/file if the file is already bucketed with the given path" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else contents = "I'm the contents of a file" checksum = save_bucket_file(contents, '/foo/bar') expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}/foo/bar")).to eq(true) find_result = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}/foo/bar") expect(find_result.checksum).to eq("{#{digest_algorithm}}#{checksum}") expect(find_result.to_s).to eq(contents) end end end describe "when not supplying a path" do [false, true].each do |trailing_slash| describe "#{trailing_slash ? 'with' : 'without'} a trailing slash" do trailing_string = trailing_slash ? '/' : '' it "should return false/nil if the file isn't bucketed" do expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{not_bucketed_checksum}#{trailing_string}")).to eq(false) expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}#{trailing_string}")).to eq(nil) end it "should return true/file if the file is already bucketed" do # this one replaces most of the lets in the "when # digest_digest_algorithm is set..." shared context, but it still needs digest_algorithm if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else contents = "I'm the contents of a file" checksum = save_bucket_file(contents, '/foo/bar') expect(Puppet::FileBucket::File.indirection.head("#{digest_algorithm}/#{checksum}#{trailing_string}")).to eq(true) find_result = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}#{trailing_string}") expect(find_result.checksum).to eq("{#{digest_algorithm}}#{checksum}") expect(find_result.to_s).to eq(contents) end end end end end end end describe "when diffing files", :unless => Puppet::Util::Platform.windows? do with_digest_algorithms do let(:not_bucketed_plaintext) { "other stuff" } let(:not_bucketed_checksum) { digest(not_bucketed_plaintext) } it "should generate an empty string if there is no diff" do skip("usage of fork(1) no supported on this platform") if RUBY_PLATFORM == 'java' if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("I'm the contents of a file") expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}", :diff_with => checksum)).to eq('') end end it "should generate a proper diff if there is a diff" do skip("usage of fork(1) no supported on this platform") if RUBY_PLATFORM == 'java' if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum1 = save_bucket_file("foo\nbar\nbaz") checksum2 = save_bucket_file("foo\nbiz\nbaz") diff = Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum1}", :diff_with => checksum2) expect(diff).to include("-bar\n+biz\n") end end it "should raise an exception if the hash to diff against isn't found" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("whatever") expect do Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{checksum}", :diff_with => not_bucketed_checksum) end.to raise_error "could not find diff_with #{not_bucketed_checksum}" end end it "should return nil if the hash to diff from isn't found" do if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" else checksum = save_bucket_file("whatever") expect(Puppet::FileBucket::File.indirection.find("#{digest_algorithm}/#{not_bucketed_checksum}", :diff_with => checksum)).to eq(nil) end end end end end [true, false].each do |override_bucket_path| describe "when bucket path #{override_bucket_path ? 'is' : 'is not'} overridden" do [true, false].each do |supply_path| describe "when #{supply_path ? 'supplying' : 'not supplying'} a path" do with_digest_algorithms do before :each do allow(Puppet.settings).to receive(:use) @store = Puppet::FileBucketFile::File.new @bucket_top_dir = tmpdir("bucket") if override_bucket_path Puppet[:bucketdir] = "/bogus/path" # should not be used else Puppet[:bucketdir] = @bucket_top_dir end @dir = "#{@bucket_top_dir}/#{bucket_dir}" @contents_path = "#{@dir}/contents" end describe "when retrieving files" do before :each do request_options = {} if override_bucket_path request_options[:bucket_path] = @bucket_top_dir end key = "#{digest_algorithm}/#{checksum}" if supply_path key += "/path/to/file" end @request = Puppet::Indirector::Request.new(:indirection_name, :find, key, nil, request_options) end def make_bucketed_file FileUtils.mkdir_p(@dir) File.open(@contents_path, 'wb') { |f| f.write plaintext } end it "should return an instance of Puppet::FileBucket::File created with the content if the file exists" do make_bucketed_file if supply_path expect(@store.find(@request)).to eq(nil) expect(@store.head(@request)).to eq(false) # because path didn't match else bucketfile = @store.find(@request) expect(bucketfile).to be_a(Puppet::FileBucket::File) expect(bucketfile.contents).to eq(plaintext) expect(@store.head(@request)).to eq(true) end end it "should return nil if no file is found" do expect(@store.find(@request)).to be_nil expect(@store.head(@request)).to eq(false) end end describe "when saving files" do it "should save the contents to the calculated path" do skip("Windows Long File Name support is incomplete PUP-8257, this doesn't fail reliably so it should be skipped.") if Puppet::Util::Platform.windows? && (['sha512', 'sha384'].include? digest_algorithm) options = {} if override_bucket_path options[:bucket_path] = @bucket_top_dir end key = "#{digest_algorithm}/#{checksum}" if supply_path key += "//path/to/file" end file_instance = Puppet::FileBucket::File.new(plaintext, options) request = Puppet::Indirector::Request.new(:indirection_name, :save, key, file_instance) @store.save(request) expect(Puppet::FileSystem.binread("#{@dir}/contents")).to eq(plaintext) end end end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector/file_bucket_file/selector_spec.rb
spec/unit/indirector/file_bucket_file/selector_spec.rb
require 'spec_helper' require 'puppet/indirector/file_bucket_file/selector' require 'puppet/indirector/file_bucket_file/file' require 'puppet/indirector/file_bucket_file/rest' describe Puppet::FileBucketFile::Selector do let(:model) { Puppet::FileBucket::File.new('') } let(:indirection) { Puppet::FileBucket::File.indirection } let(:terminus) { indirection.terminus(:selector) } %w[head find save search destroy].each do |method| describe "##{method}" do it "should proxy to rest terminus for https requests" do key = "https://example.com/path/to/file" expect(indirection.terminus(:rest)).to receive(method) if method == 'save' terminus.send(method, indirection.request(method, key, model)) else terminus.send(method, indirection.request(method, key, nil)) end end it "should proxy to file terminus for other requests" do key = "file:///path/to/file" case method when 'save' expect(indirection.terminus(:file)).to receive(method) terminus.send(method, indirection.request(method, key, model)) when 'find', 'head' expect(indirection.terminus(:file)).to receive(method) terminus.send(method, indirection.request(method, key, nil)) else # file terminus doesn't implement search or destroy expect { terminus.send(method, indirection.request(method, key, nil)) }.to raise_error(NoMethodError) 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/indirector/file_bucket_file/rest_spec.rb
spec/unit/indirector/file_bucket_file/rest_spec.rb
require 'spec_helper' require 'puppet/indirector/file_bucket_file/rest' describe Puppet::FileBucketFile::Rest do let(:rest_path) {"filebucket://xanadu:8141/"} let(:file_bucket_file) {Puppet::FileBucket::File.new('file contents', :bucket_path => '/some/random/path')} let(:files_original_path) {'/path/to/file'} let(:dest_path) {"#{rest_path}#{file_bucket_file.name}/#{files_original_path}"} let(:file_bucket_path) {"#{rest_path}#{file_bucket_file.checksum_type}/#{file_bucket_file.checksum_data}/#{files_original_path}"} let(:source_path) {"#{rest_path}#{file_bucket_file.checksum_type}/#{file_bucket_file.checksum_data}"} let(:uri) { %r{/puppet/v3/file_bucket_file} } describe '#head' do it 'includes the environment as a request parameter' do stub_request(:head, uri).with(query: hash_including(environment: 'outerspace')) described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path, environment: Puppet::Node::Environment.remote('outerspace')) end it 'includes bucket path in the request if bucket path is set' do stub_request(:head, uri).with(query: hash_including(bucket_path: '/some/random/path')) described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path) end it "returns nil on 404" do stub_request(:head, uri).to_return(status: 404) expect(described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path)).to be_falsy end it "raises for all other fail codes" do stub_request(:head, uri).to_return(status: [503, 'server unavailable']) expect{described_class.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path)}.to raise_error(Net::HTTPError, "Error 503 on SERVER: server unavailable") end end describe '#find' do it 'includes the environment as a request parameter' do stub_request(:get, uri).with(query: hash_including(environment: 'outerspace')).to_return(status: 200, headers: {'Content-Type' => 'application/octet-stream'}) described_class.indirection.find(source_path, :bucket_path => nil, environment: Puppet::Node::Environment.remote('outerspace')) end {bucket_path: 'path', diff_with: '4aabe1257043bd0', list_all: 'true', fromdate: '20200404', todate: '20200404'}.each do |param, val| it "includes #{param} as a parameter in the request if #{param} is set" do stub_request(:get, uri).with(query: hash_including(param => val)).to_return(status: 200, headers: {'Content-Type' => 'application/octet-stream'}) options = { param => val } described_class.indirection.find(source_path, **options) end end it 'raises if unsuccessful' do stub_request(:get, uri).to_return(status: [503, 'server unavailable']) expect{described_class.indirection.find(source_path, :bucket_path => nil)}.to raise_error(Net::HTTPError, "Error 503 on SERVER: server unavailable") end it 'raises if Content-Type is not included in the response' do stub_request(:get, uri).to_return(status: 200, headers: {}) expect{described_class.indirection.find(source_path, :bucket_path => nil)}.to raise_error(RuntimeError, "No content type in http response; cannot parse") end end describe '#save' do it 'includes the environment as a request parameter' do stub_request(:put, uri).with(query: hash_including(environment: 'outerspace')) described_class.indirection.save(file_bucket_file, dest_path, environment: Puppet::Node::Environment.remote('outerspace')) end it 'sends the contents of the file as the request body' do stub_request(:put, uri).with(body: file_bucket_file.contents) described_class.indirection.save(file_bucket_file, dest_path) end it 'raises if unsuccessful' do stub_request(:put, uri).to_return(status: [503, 'server unavailable']) expect{described_class.indirection.save(file_bucket_file, dest_path)}.to raise_error(Net::HTTPError, "Error 503 on SERVER: server unavailable") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/migration_spec.rb
spec/unit/pops/migration_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' require 'puppet/loaders' require 'puppet_spec/pops' require 'puppet_spec/scope' require 'puppet/parser/e4_parser_adapter' describe 'Puppet::Pops::MigrationMigrationChecker' do include PuppetSpec::Pops include PuppetSpec::Scope before(:each) do Puppet[:strict_variables] = true # Puppetx cannot be loaded until the correct parser has been set (injector is turned off otherwise) require 'puppet_x' # Tests needs a known configuration of node/scope/compiler since it parses and evaluates # snippets as the compiler will evaluate them, butwithout the overhead of compiling a complete # catalog for each tested expression. # @parser = Puppet::Pops::Parser::EvaluatingParser.new @node = Puppet::Node.new('node.example.com') @node.environment = Puppet::Node::Environment.create(:testing, []) @compiler = Puppet::Parser::Compiler.new(@node) @scope = Puppet::Parser::Scope.new(@compiler) @scope.source = Puppet::Resource::Type.new(:node, 'node.example.com') @scope.parent = @compiler.topscope end let(:scope) { @scope } describe "when there is no MigrationChecker in the PuppetContext" do it "a null implementation of the MigrationChecker gets created (once per impl that needs one)" do migration_checker = Puppet::Pops::Migration::MigrationChecker.new() expect(Puppet::Pops::Migration::MigrationChecker).to receive(:new).at_least(:once).and_return(migration_checker) expect(Puppet::Pops::Parser::EvaluatingParser.new.evaluate_string(scope, "1", __FILE__)).to eq(1) end end describe "when there is a MigrationChecker in the Puppet Context" do it "does not create any MigrationChecker instances when parsing and evaluating" do migration_checker = double() expect(Puppet::Pops::Migration::MigrationChecker).not_to receive(:new) Puppet.override({:migration_checker => migration_checker}, "test-context") do Puppet::Pops::Parser::EvaluatingParser.new.evaluate_string(scope, "true", __FILE__) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/visitor_spec.rb
spec/unit/pops/visitor_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::Visitor do describe "A visitor and a visitable in a configuration with min and max args set to 0" do class DuckProcessor def initialize @friend_visitor = Puppet::Pops::Visitor.new(self, "friend", 0, 0) end def hi(o, *args) @friend_visitor.visit(o, *args) end def friend_Duck(o) "Hi #{o.class}" end def friend_Numeric(o) "Howdy #{o.class}" end end class Duck include Puppet::Pops::Visitable end it "should select the expected method when there are no arguments" do duck = Duck.new duck_processor = DuckProcessor.new expect(duck_processor.hi(duck)).to eq("Hi Duck") end it "should fail if there are too many arguments" do duck = Duck.new duck_processor = DuckProcessor.new expect { duck_processor.hi(duck, "how are you?") }.to raise_error(/^Visitor Error: Too many.*/) end it "should select method for superclass" do duck_processor = DuckProcessor.new expect(duck_processor.hi(42)).to match(/Howdy Integer/) end it "should select method for superclass" do duck_processor = DuckProcessor.new expect(duck_processor.hi(42.0)).to eq("Howdy Float") end it "should fail if class not handled" do duck_processor = DuckProcessor.new expect { duck_processor.hi("wassup?") }.to raise_error(/Visitor Error: the configured.*/) end end describe "A visitor and a visitable in a configuration with min =1, and max args set to 2" do class DuckProcessor2 def initialize @friend_visitor = Puppet::Pops::Visitor.new(self, "friend", 1, 2) end def hi(o, *args) @friend_visitor.visit(o, *args) end def friend_Duck(o, drink, eat="grain") "Hi #{o.class}, drink=#{drink}, eat=#{eat}" end end class Duck include Puppet::Pops::Visitable end it "should select the expected method when there are is one arguments" do duck = Duck.new duck_processor = DuckProcessor2.new expect(duck_processor.hi(duck, "water")).to eq("Hi Duck, drink=water, eat=grain") end it "should fail if there are too many arguments" do duck = Duck.new duck_processor = DuckProcessor2.new expect { duck_processor.hi(duck, "scotch", "soda", "peanuts") }.to raise_error(/^Visitor Error: Too many.*/) end it "should fail if there are too few arguments" do duck = Duck.new duck_processor = DuckProcessor2.new expect { duck_processor.hi(duck) }.to raise_error(/^Visitor Error: Too few.*/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/factory_rspec_helper.rb
spec/unit/pops/factory_rspec_helper.rb
require 'puppet/pops' module FactoryRspecHelper def literal(x) Puppet::Pops::Model::Factory.literal(x) end def block(*args) Puppet::Pops::Model::Factory.block(*args) end def var(x) Puppet::Pops::Model::Factory.var(x) end def fqn(x) Puppet::Pops::Model::Factory.fqn(x) end def string(*args) Puppet::Pops::Model::Factory.string(*args) end def minus(x) Puppet::Pops::Model::Factory.minus(x) end def IF(test, then_expr, else_expr=nil) Puppet::Pops::Model::Factory.IF(test, then_expr, else_expr) end def UNLESS(test, then_expr, else_expr=nil) Puppet::Pops::Model::Factory.UNLESS(test, then_expr, else_expr) end def CASE(test, *options) Puppet::Pops::Model::Factory.CASE(test, *options) end def WHEN(values, block) Puppet::Pops::Model::Factory.WHEN(values, block) end def method_missing(method, *args, &block) if Puppet::Pops::Model::Factory.respond_to? method Puppet::Pops::Model::Factory.send(method, *args, &block) else super end end # i.e. Selector Entry 1 => 'hello' def MAP(match, value) Puppet::Pops::Model::Factory.MAP(match, value) end def dump(x) Puppet::Pops::Model::ModelTreeDumper.new.dump(x) end def unindent x x.gsub(/^#{x[/\A\s*/]}/, '').chomp end factory ||= Puppet::Pops::Model::Factory end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/issues_spec.rb
spec/unit/pops/issues_spec.rb
require 'spec_helper' require 'puppet/pops' describe "Puppet::Pops::Issues" do include Puppet::Pops::Issues it "should have an issue called NAME_WITH_HYPHEN" do x = Puppet::Pops::Issues::NAME_WITH_HYPHEN expect(x.class).to eq(Puppet::Pops::Issues::Issue) expect(x.issue_code).to eq(:NAME_WITH_HYPHEN) end it "should should format a message that requires an argument" do x = Puppet::Pops::Issues::NAME_WITH_HYPHEN expect(x.format(:name => 'Boo-Hoo', :label => Puppet::Pops::Model::ModelLabelProvider.new, :semantic => "dummy" )).to eq("A String may not have a name containing a hyphen. The name 'Boo-Hoo' is not legal") end it "should should format a message that does not require an argument" do x = Puppet::Pops::Issues::NOT_TOP_LEVEL expect(x.format()).to eq("Classes, definitions, and nodes may only appear at toplevel or inside other classes") end end describe "Puppet::Pops::IssueReporter" do let(:acceptor) { Puppet::Pops::Validation::Acceptor.new } def fake_positioned(number) double("positioned_#{number}", :line => number, :pos => number) end def diagnostic(severity, number, args) Puppet::Pops::Validation::Diagnostic.new( severity, Puppet::Pops::Issues::Issue.new(number) { "#{severity}#{number}" }, "#{severity}file", fake_positioned(number), args) end def warning(number, args = {}) diagnostic(:warning, number, args) end def deprecation(number, args = {}) diagnostic(:deprecation, number, args) end def error(number, args = {}) diagnostic(:error, number, args) end context "given warnings" do before(:each) do acceptor.accept( warning(1) ) acceptor.accept( deprecation(1) ) end it "emits warnings if told to emit them" do expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "does not emit warnings if not told to emit them" do expect(Puppet::Log).not_to receive(:create) Puppet::Pops::IssueReporter.assert_and_report(acceptor, {}) end it "emits no warnings if :max_warnings is 0" do acceptor.accept( warning(2) ) Puppet[:max_warnings] = 0 expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/deprecation1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "emits no more than 1 warning if :max_warnings is 1" do acceptor.accept( warning(2) ) acceptor.accept( warning(3) ) Puppet[:max_warnings] = 1 expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "does not emit more deprecations warnings than the max deprecation warnings" do acceptor.accept( deprecation(2) ) Puppet[:max_deprecations] = 0 expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/warning1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "does not emit deprecation warnings, but does emit regular warnings if disable_warnings includes deprecations" do Puppet[:disable_warnings] = 'deprecations' expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/warning1/))) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end it "includes diagnostic arguments in logged entry" do acceptor.accept( warning(2, :n => 'a') ) expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) expect(Puppet::Log).to receive(:create).once.with(hash_including(:level => :warning, :message => match(/warning2/), :arguments => {:n => 'a'})) Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end end context "given errors" do it "logs nothing, but raises the given :message if :emit_errors is repressing error logging" do acceptor.accept( error(1) ) expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_errors => false, :message => 'special'}) end.to raise_error(Puppet::ParseError, 'special') end it "prefixes :message if a single error is raised" do acceptor.accept( error(1) ) expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :message => 'special'}) end.to raise_error(Puppet::ParseError, /special error1/) end it "logs nothing and raises immediately if there is only one error" do acceptor.accept( error(1) ) expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /error1/) end it "logs nothing and raises immediately if there are multiple errors but max_errors is 0" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) Puppet[:max_errors] = 0 expect(Puppet::Log).not_to receive(:create) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /error1/) end it "logs the :message if there is more than one allowed error" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) expect(Puppet::Log).to receive(:create).exactly(3).times.with(hash_including(:level => :err, :message => match(/error1|error2|special/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :message => 'special'}) end.to raise_error(Puppet::ParseError, /Giving up/) end it "emits accumulated errors before raising a 'giving up' message if there are more errors than allowed" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) acceptor.accept( error(3) ) Puppet[:max_errors] = 2 expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :err, :message => match(/error1|error2/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /3 errors.*Giving up/) end it "emits accumulated errors before raising a 'giving up' message if there are multiple errors but fewer than limits" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) acceptor.accept( error(3) ) Puppet[:max_errors] = 4 expect(Puppet::Log).to receive(:create).exactly(3).times.with(hash_including(:level => :err, :message => match(/error[123]/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /3 errors.*Giving up/) end it "emits errors regardless of disable_warnings setting" do acceptor.accept( error(1) ) acceptor.accept( error(2) ) Puppet[:disable_warnings] = 'deprecations' expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :err, :message => match(/error1|error2/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseError, /Giving up/) end it "includes diagnostic arguments in raised error" do acceptor.accept( error(1, :n => 'a') ) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { }) end.to raise_error(Puppet::ParseErrorWithIssue, /error1/) { |ex| expect(ex.arguments).to eq(:n => 'a')} end end context "given both" do it "logs warnings and errors" do acceptor.accept( warning(1) ) acceptor.accept( error(1) ) acceptor.accept( error(2) ) acceptor.accept( error(3) ) acceptor.accept( deprecation(1) ) Puppet[:max_errors] = 2 expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :warning, :message => match(/warning1|deprecation1/))) expect(Puppet::Log).to receive(:create).twice.with(hash_including(:level => :err, :message => match(/error[123]/))) expect do Puppet::Pops::IssueReporter.assert_and_report(acceptor, { :emit_warnings => true }) end.to raise_error(Puppet::ParseError, /3 errors.*2 warnings.*Giving up/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/factory_spec.rb
spec/unit/pops/factory_spec.rb
require 'spec_helper' require 'puppet/pops' require File.join(File.dirname(__FILE__), '/factory_rspec_helper') # This file contains testing of the pops model factory # describe Puppet::Pops::Model::Factory do include FactoryRspecHelper context "When factory methods are invoked they should produce expected results" do it "tests #var should create a VariableExpression" do expect(var('a').model.class).to eq(Puppet::Pops::Model::VariableExpression) end it "tests #fqn should create a QualifiedName" do expect(fqn('a').model.class).to eq(Puppet::Pops::Model::QualifiedName) end it "tests #QNAME should create a QualifiedName" do expect(QNAME('a').model.class).to eq(Puppet::Pops::Model::QualifiedName) end it "tests #QREF should create a QualifiedReference" do expect(QREF('a').model.class).to eq(Puppet::Pops::Model::QualifiedReference) end it "tests #block should create a BlockExpression" do expect(block().model.is_a?(Puppet::Pops::Model::BlockExpression)).to eq(true) end it "should create a literal undef on :undef" do expect(literal(:undef).model.class).to eq(Puppet::Pops::Model::LiteralUndef) end it "should create a literal default on :default" do expect(literal(:default).model.class).to eq(Puppet::Pops::Model::LiteralDefault) end end context "When calling block_or_expression" do it "A single expression should produce identical output" do expect(block_or_expression([literal(1) + literal(2)]).model.is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) end it "Multiple expressions should produce a block expression" do braces = double('braces') allow(braces).to receive(:offset).and_return(0) allow(braces).to receive(:length).and_return(0) model = block_or_expression([literal(1) + literal(2), literal(2) + literal(3)], braces, braces).model expect(model.is_a?(Puppet::Pops::Model::BlockExpression)).to eq(true) expect(model.statements.size).to eq(2) end end context "When processing calls with CALL_NAMED" do it "Should be possible to state that r-value is required" do built = call_named('foo', true).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.rval_required).to eq(true) end it "Should produce a call expression without arguments" do built = call_named('foo', false).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName)).to eq(true) expect(built.functor_expr.value).to eq("foo") expect(built.rval_required).to eq(false) expect(built.arguments.size).to eq(0) end it "Should produce a call expression with one argument" do built = call_named('foo', false, literal(1) + literal(2)).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName)).to eq(true) expect(built.functor_expr.value).to eq("foo") expect(built.rval_required).to eq(false) expect(built.arguments.size).to eq(1) expect(built.arguments[0].is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) end it "Should produce a call expression with two arguments" do built = call_named('foo', false, literal(1) + literal(2), literal(1) + literal(2)).model expect(built.is_a?(Puppet::Pops::Model::CallNamedFunctionExpression)).to eq(true) expect(built.functor_expr.is_a?(Puppet::Pops::Model::QualifiedName)).to eq(true) expect(built.functor_expr.value).to eq("foo") expect(built.rval_required).to eq(false) expect(built.arguments.size).to eq(2) expect(built.arguments[0].is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) expect(built.arguments[1].is_a?(Puppet::Pops::Model::ArithmeticExpression)).to eq(true) end end context "When creating attribute operations" do it "Should produce an attribute operation for =>" do built = ATTRIBUTE_OP('aname', '=>', literal('x')).model built.is_a?(Puppet::Pops::Model::AttributeOperation) expect(built.operator).to eq('=>') expect(built.attribute_name).to eq("aname") expect(built.value_expr.is_a?(Puppet::Pops::Model::LiteralString)).to eq(true) end it "Should produce an attribute operation for +>" do built = ATTRIBUTE_OP('aname', '+>', literal('x')).model built.is_a?(Puppet::Pops::Model::AttributeOperation) expect(built.operator).to eq('+>') expect(built.attribute_name).to eq("aname") expect(built.value_expr.is_a?(Puppet::Pops::Model::LiteralString)).to eq(true) end end context "When processing RESOURCE" do it "Should create a Resource body" do built = RESOURCE_BODY(literal('title'), [ATTRIBUTE_OP('aname', '=>', literal('x'))]).model expect(built.is_a?(Puppet::Pops::Model::ResourceBody)).to eq(true) expect(built.title.is_a?(Puppet::Pops::Model::LiteralString)).to eq(true) expect(built.operations.size).to eq(1) expect(built.operations[0].class).to eq(Puppet::Pops::Model::AttributeOperation) expect(built.operations[0].attribute_name).to eq('aname') end it "Should create a RESOURCE without a resource body" do bodies = [] built = RESOURCE(literal('rtype'), bodies).model expect(built.class).to eq(Puppet::Pops::Model::ResourceExpression) expect(built.bodies.size).to eq(0) end it "Should create a RESOURCE with 1 resource body" do bodies = [] << RESOURCE_BODY(literal('title'), []) built = RESOURCE(literal('rtype'), bodies).model expect(built.class).to eq(Puppet::Pops::Model::ResourceExpression) expect(built.bodies.size).to eq(1) expect(built.bodies[0].title.value).to eq('title') end it "Should create a RESOURCE with 2 resource bodies" do bodies = [] << RESOURCE_BODY(literal('title'), []) << RESOURCE_BODY(literal('title2'), []) built = RESOURCE(literal('rtype'), bodies).model expect(built.class).to eq(Puppet::Pops::Model::ResourceExpression) expect(built.bodies.size).to eq(2) expect(built.bodies[0].title.value).to eq('title') expect(built.bodies[1].title.value).to eq('title2') end end context "When processing simple literals" do it "Should produce a literal boolean from a boolean" do model = literal(true).model expect(model.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(model.value).to eq(true) model = literal(false).model expect(model.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(model.value).to eq(false) end end context "When processing COLLECT" do it "should produce a virtual query" do model = VIRTUAL_QUERY(fqn('a').eq(literal(1))).model expect(model.class).to eq(Puppet::Pops::Model::VirtualQuery) expect(model.expr.class).to eq(Puppet::Pops::Model::ComparisonExpression) expect(model.expr.operator).to eq('==') end it "should produce an export query" do model = EXPORTED_QUERY(fqn('a').eq(literal(1))).model expect(model.class).to eq(Puppet::Pops::Model::ExportedQuery) expect(model.expr.class).to eq(Puppet::Pops::Model::ComparisonExpression) expect(model.expr.operator).to eq('==') end it "should produce a collect expression" do q = VIRTUAL_QUERY(fqn('a').eq(literal(1))) built = COLLECT(literal('t'), q, [ATTRIBUTE_OP('name', '=>', literal(3))]).model expect(built.class).to eq(Puppet::Pops::Model::CollectExpression) expect(built.operations.size).to eq(1) end it "should produce a collect expression without attribute operations" do q = VIRTUAL_QUERY(fqn('a').eq(literal(1))) built = COLLECT(literal('t'), q, []).model expect(built.class).to eq(Puppet::Pops::Model::CollectExpression) expect(built.operations.size).to eq(0) end end context "When processing concatenated string(iterpolation)" do it "should handle 'just a string'" do model = string('blah blah').model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(1) expect(model.segments[0].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[0].value).to eq("blah blah") end it "should handle one expression in the middle" do model = string('blah blah', TEXT(literal(1)+literal(2)), 'blah blah').model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(3) expect(model.segments[0].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[0].value).to eq("blah blah") expect(model.segments[1].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) expect(model.segments[2].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[2].value).to eq("blah blah") end it "should handle one expression at the end" do model = string('blah blah', TEXT(literal(1)+literal(2))).model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(2) expect(model.segments[0].class).to eq(Puppet::Pops::Model::LiteralString) expect(model.segments[0].value).to eq("blah blah") expect(model.segments[1].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) end it "should handle only one expression" do model = string(TEXT(literal(1)+literal(2))).model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(1) expect(model.segments[0].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[0].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) end it "should handle several expressions" do model = string(TEXT(literal(1)+literal(2)), TEXT(literal(1)+literal(2))).model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) expect(model.segments.size).to eq(2) expect(model.segments[0].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[0].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) expect(model.segments[1].class).to eq(Puppet::Pops::Model::TextExpression) expect(model.segments[1].expr.class).to eq(Puppet::Pops::Model::ArithmeticExpression) end it "should handle no expression" do model = string().model expect(model.class).to eq(Puppet::Pops::Model::ConcatenatedString) model.segments.size == 0 end end context "When processing UNLESS" do it "should create an UNLESS expression with then part" do built = UNLESS(literal(true), literal(1), literal(nil)).model expect(built.class).to eq(Puppet::Pops::Model::UnlessExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::Nop) end it "should create an UNLESS expression with then and else parts" do built = UNLESS(literal(true), literal(1), literal(2)).model expect(built.class).to eq(Puppet::Pops::Model::UnlessExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) end end context "When processing IF" do it "should create an IF expression with then part" do built = IF(literal(true), literal(1), literal(nil)).model expect(built.class).to eq(Puppet::Pops::Model::IfExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::Nop) end it "should create an IF expression with then and else parts" do built = IF(literal(true), literal(1), literal(2)).model expect(built.class).to eq(Puppet::Pops::Model::IfExpression) expect(built.test.class).to eq(Puppet::Pops::Model::LiteralBoolean) expect(built.then_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) expect(built.else_expr.class).to eq(Puppet::Pops::Model::LiteralInteger) end end context "When processing a Parameter" do it "should create a Parameter" do # PARAM(name, expr) # PARAM(name) # end end # LIST, HASH, KEY_ENTRY context "When processing Definition" do # DEFINITION(classname, arguments, statements) # should accept empty arguments, and no statements end context "When processing Hostclass" do # HOSTCLASS(classname, arguments, parent, statements) # parent may be passed as a nop /nil - check this works, should accept empty statements (nil) # should accept empty arguments end context "When processing Node" do end # Tested in the evaluator test already, but should be here to test factory assumptions # # TODO: CASE / WHEN # TODO: 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/pops/merge_strategy_spec.rb
spec/unit/pops/merge_strategy_spec.rb
require 'spec_helper' require 'puppet/pops' module Puppet::Pops describe 'MergeStrategy' do context 'deep merge' do it 'does not mutate the source of a merge' do a = { 'a' => { 'b' => 'va' }, 'c' => 2 } b = { 'a' => { 'b' => 'vb' }, 'b' => 3} c = MergeStrategy.strategy(:deep).merge(a, b); expect(a).to eql({ 'a' => { 'b' => 'va' }, 'c' => 2 }) expect(b).to eql({ 'a' => { 'b' => 'vb' }, 'b' => 3 }) expect(c).to eql({ 'a' => { 'b' => 'va' }, 'b' => 3, 'c' => 2 }) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/utils_spec.rb
spec/unit/pops/utils_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'pops utils' do context 'when converting strings to numbers' do it 'should convert "0" to 0' do expect(Puppet::Pops::Utils.to_n("0")).to eq(0) end it 'should convert "0" to 0 with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0")).to eq([0, 10]) end it 'should convert "0.0" to 0.0' do expect(Puppet::Pops::Utils.to_n("0.0")).to eq(0.0) end it 'should convert "0.0" to 0.0 with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0.0")).to eq([0.0, 10]) end it 'should convert "0.01e1" to 0.01e1' do expect(Puppet::Pops::Utils.to_n("0.01e1")).to eq(0.01e1) expect(Puppet::Pops::Utils.to_n("0.01E1")).to eq(0.01e1) end it 'should convert "0.01e1" to 0.01e1 with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0.01e1")).to eq([0.01e1, 10]) expect(Puppet::Pops::Utils.to_n_with_radix("0.01E1")).to eq([0.01e1, 10]) end it 'should not convert "0e1" to floating point' do expect(Puppet::Pops::Utils.to_n("0e1")).to be_nil expect(Puppet::Pops::Utils.to_n("0E1")).to be_nil end it 'should not convert "0e1" to floating point with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0e1")).to be_nil expect(Puppet::Pops::Utils.to_n_with_radix("0E1")).to be_nil end it 'should not convert "0.0e1" to floating point' do expect(Puppet::Pops::Utils.to_n("0.0e1")).to be_nil expect(Puppet::Pops::Utils.to_n("0.0E1")).to be_nil end it 'should not convert "0.0e1" to floating point with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("0.0e1")).to be_nil expect(Puppet::Pops::Utils.to_n_with_radix("0.0E1")).to be_nil end it 'should not convert "000000.0000e1" to floating point' do expect(Puppet::Pops::Utils.to_n("000000.0000e1")).to be_nil expect(Puppet::Pops::Utils.to_n("000000.0000E1")).to be_nil end it 'should not convert "000000.0000e1" to floating point with radix' do expect(Puppet::Pops::Utils.to_n_with_radix("000000.0000e1")).to be_nil expect(Puppet::Pops::Utils.to_n_with_radix("000000.0000E1")).to be_nil end it 'should not convert infinite values to floating point' do expect(Puppet::Pops::Utils.to_n("4e999")).to be_nil end it 'should not convert infinite values to floating point with_radix' do expect(Puppet::Pops::Utils.to_n_with_radix("4e999")).to be_nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/containment_spec.rb
spec/unit/pops/containment_spec.rb
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/pn_spec.rb
spec/unit/pops/pn_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/pn' module Puppet::Pops module PN describe 'Puppet::Pops::PN' do context 'Literal' do context 'containing the value' do it 'true produces the text "true"' do expect(lit(true).to_s).to eql('true') end it 'false produces the text "false"' do expect(lit(false).to_s).to eql('false') end it 'nil produces the text "nil"' do expect(lit(nil).to_s).to eql('nil') end it '34 produces the text "34"' do expect(lit(34).to_s).to eql('34') end it '3.0 produces the text "3.0"' do expect(lit(3.0).to_s).to eql('3.0') end end context 'produces a double quoted text from a string such that' do it '"plain" produces "plain"' do expect(lit('plain').to_s).to eql('"plain"') end it '"\t" produces a text containing a tab character' do expect(lit("\t").to_s).to eql('"\t"') end it '"\r" produces a text containing a return character' do expect(lit("\r").to_s).to eql('"\r"') end it '"\n" produces a text containing a newline character' do expect(lit("\n").to_s).to eql('"\n"') end it '"\"" produces a text containing a double quote' do expect(lit("\"").to_s).to eql('"\""') end it '"\\" produces a text containing a backslash' do expect(lit("\\").to_s).to eql('"\\\\"') end it '"\u{14}" produces "\o024"' do expect(lit("\u{14}").to_s).to eql('"\o024"') end end end context 'List' do it 'produces a text where its elements are enclosed in brackets' do expect(List.new([lit(3), lit('a'), lit(true)]).to_s).to eql('[3 "a" true]') end it 'produces a text where the elements of nested lists are enclosed in brackets' do expect(List.new([lit(3), lit('a'), List.new([lit(true), lit(false)])]).to_s).to eql('[3 "a" [true false]]') end context 'with indent' do it 'produces a text where the each element is on an indented line ' do s = '' List.new([lit(3), lit('a'), List.new([lit(true), lit(false)])]).format(Indent.new(' '), s) expect(s).to eql(<<-RESULT.unindent[0..-2]) # unindent and strip last newline [ 3 "a" [ true false]] RESULT end end end context 'Map' do it 'raises error when illegal keys are used' do expect { Map.new([Entry.new('123', lit(3))]) }.to raise_error(ArgumentError, /key 123 does not conform to pattern/) end it 'produces a text where entries are enclosed in curly braces' do expect(Map.new([Entry.new('a', lit(3))]).to_s).to eql('{:a 3}') end it 'produces a text where the entries of nested maps are enclosed in curly braces' do expect(Map.new([ Map.new([Entry.new('a', lit(3))]).with_name('o')]).to_s).to eql('{:o {:a 3}}') end context 'with indent' do it 'produces a text where the each element is on an indented line ' do s = '' Map.new([ Map.new([Entry.new('a', lit(3)), Entry.new('b', lit(5))]).with_name('o')]).format(Indent.new(' '), s) expect(s).to eql(<<-RESULT.unindent[0..-2]) # unindent and strip last newline { :o { :a 3 :b 5}} RESULT end end end context 'Call' do it 'produces a text where elements are enclosed in parenthesis' do expect(Call.new('+', lit(3), lit(5)).to_s).to eql('(+ 3 5)') end it 'produces a text where the elements of nested calls are enclosed in parenthesis' do expect(Map.new([ Call.new('+', lit(3), lit(5)).with_name('o')]).to_s).to eql('{:o (+ 3 5)}') end context 'with indent' do it 'produces a text where the each element is on an indented line ' do s = '' Call.new('+', lit(3), lit(Call.new('-', lit(10), lit(5)))).format(Indent.new(' '), s) expect(s).to eql(<<-RESULT.unindent[0..-2]) # unindent and strip last newline (+ 3 (- 10 5)) RESULT end end end def lit(v) v.is_a?(PN) ? v : Literal.new(v) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/adaptable_spec.rb
spec/unit/pops/adaptable_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::Adaptable::Adapter do class ValueAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :value end class OtherAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :value def OtherAdapter.create_adapter(o) x = new x.value="I am calling you Daffy." x end end module Farm class FarmAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :value end end class Duck include Puppet::Pops::Adaptable end it "should create specialized adapter instance on call to adapt" do d = Duck.new a = ValueAdapter.adapt(d) expect(a.class).to eq(ValueAdapter) end it "should produce the same instance on multiple adaptations" do d = Duck.new a = ValueAdapter.adapt(d) a.value = 10 b = ValueAdapter.adapt(d) expect(b.value).to eq(10) end it "should return the correct adapter if there are several" do d = Duck.new a = ValueAdapter.adapt(d) a.value = 10 b = ValueAdapter.adapt(d) expect(b.value).to eq(10) end it "should allow specialization to override creating" do d = Duck.new a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") end it "should create a new adapter overriding existing" do d = Duck.new a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") a.value = "Something different" expect(a.value).to eq("Something different") b = OtherAdapter.adapt(d) expect(b.value).to eq("Something different") b = OtherAdapter.adapt_new(d) expect(b.value).to eq("I am calling you Daffy.") end it "should not create adapter on get" do d = Duck.new a = OtherAdapter.get(d) expect(a).to eq(nil) end it "should return same adapter from get after adapt" do d = Duck.new a = OtherAdapter.get(d) expect(a).to eq(nil) a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") b = OtherAdapter.get(d) expect(b.value).to eq("I am calling you Daffy.") expect(a).to eq(b) end it "should handle adapters in nested namespaces" do d = Duck.new a = Farm::FarmAdapter.get(d) expect(a).to eq(nil) a = Farm::FarmAdapter.adapt(d) a.value = 10 b = Farm::FarmAdapter.get(d) expect(b.value).to eq(10) end it "should be able to clear the adapter" do d = Duck.new a = OtherAdapter.adapt(d) expect(a.value).to eq("I am calling you Daffy.") # The adapter cleared should be returned expect(OtherAdapter.clear(d).value).to eq("I am calling you Daffy.") expect(OtherAdapter.get(d)).to eq(nil) end context "When adapting with #adapt it" do it "should be possible to pass a block to configure the adapter" do d = Duck.new a = OtherAdapter.adapt(d) do |x| x.value = "Donald" end expect(a.value).to eq("Donald") end it "should be possible to pass a block to configure the adapter and get the adapted" do d = Duck.new a = OtherAdapter.adapt(d) do |x, o| x.value = "Donald, the #{o.class.name}" end expect(a.value).to eq("Donald, the Duck") end end context "When adapting with #adapt_new it" do it "should be possible to pass a block to configure the adapter" do d = Duck.new a = OtherAdapter.adapt_new(d) do |x| x.value = "Donald" end expect(a.value).to eq("Donald") end it "should be possible to pass a block to configure the adapter and get the adapted" do d = Duck.new a = OtherAdapter.adapt_new(d) do |x, o| x.value = "Donald, the #{o.class.name}" end expect(a.value).to eq("Donald, the Duck") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/benchmark_spec.rb
spec/unit/pops/benchmark_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/pops' require 'puppet_spec/scope' describe "Benchmark", :benchmark => true do include PuppetSpec::Pops include PuppetSpec::Scope def code 'if true { $a = 10 + 10 } else { $a = "interpolate ${foo} and stuff" } ' end class StringWriter < String alias write concat end def json_dump(model) output = StringWriter.new ser = Puppet::Pops::Serialization::Serializer.new(Puppet::Pops::Serialization::JSON.writer.new(output)) ser.write(model) ser.finish output end it "transformer", :profile => true do parser = Puppet::Pops::Parser::Parser.new() model = parser.parse_string(code).model transformer = Puppet::Pops::Model::AstTransformer.new() m = Benchmark.measure { 10000.times { transformer.transform(model) }} puts "Transformer: #{m}" end it "validator", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() model = parser.parse_string(code) m = Benchmark.measure { 100000.times { parser.assert_and_report(model) }} puts "Validator: #{m}" end it "parse transform", :profile => true do parser = Puppet::Pops::Parser::Parser.new() transformer = Puppet::Pops::Model::AstTransformer.new() m = Benchmark.measure { 10000.times { transformer.transform(parser.parse_string(code).model) }} puts "Parse and transform: #{m}" end it "parser0", :profile => true do parser = Puppet::Parser::Parser.new('test') m = Benchmark.measure { 10000.times { parser.parse(code) }} puts "Parser 0: #{m}" end it "parser1", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() m = Benchmark.measure { 10000.times { parser.parse_string(code) }} puts "Parser1: #{m}" end it "marshal1", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() model = parser.parse_string(code).model dumped = Marshal.dump(model) m = Benchmark.measure { 10000.times { Marshal.load(dumped) }} puts "Marshal1: #{m}" end it "rgenjson", :profile => true do parser = Puppet::Pops::Parser::EvaluatingParser.new() model = parser.parse_string(code).model dumped = json_dump(model) m = Benchmark.measure { 10000.times { json_load(dumped) }} puts "Pcore Json: #{m}" end it "lexer2", :profile => true do lexer = Puppet::Pops::Parser::Lexer2.new m = Benchmark.measure {10000.times {lexer.string = code; lexer.fullscan }} puts "Lexer2: #{m}" end it "lexer1", :profile => true do lexer = Puppet::Pops::Parser::Lexer.new m = Benchmark.measure {10000.times {lexer.string = code; lexer.fullscan }} puts "Pops Lexer: #{m}" end it "lexer0", :profile => true do lexer = Puppet::Parser::Lexer.new m = Benchmark.measure {10000.times {lexer.string = code; lexer.fullscan }} puts "Original Lexer: #{m}" end context "Measure Evaluator" do let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new } let(:node) { 'node.example.com' } let(:scope) { s = create_test_scope_for_node(node); s } it "evaluator", :profile => true do # Do the loop in puppet code since it otherwise drowns in setup puppet_loop = 'Integer[0, 1000].each |$i| { if true { $a = 10 + 10 } else { $a = "interpolate ${foo} and stuff" }} ' # parse once, only measure the evaluation model = parser.parse_string(puppet_loop, __FILE__) m = Benchmark.measure { parser.evaluate(create_test_scope_for_node(node), model) } puts("Evaluator: #{m}") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/puppet_stack_spec.rb
spec/unit/pops/puppet_stack_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'Puppet::Pops::PuppetStack' do class StackTraceTest def get_stacktrace Puppet::Pops::PuppetStack.stacktrace end def get_top_of_stack Puppet::Pops::PuppetStack.top_of_stack end def one_level Puppet::Pops::PuppetStack.stack("one_level.pp", 1234, self, :get_stacktrace, []) end def one_level_top Puppet::Pops::PuppetStack.stack("one_level.pp", 1234, self, :get_top_of_stack, []) end def two_levels Puppet::Pops::PuppetStack.stack("two_levels.pp", 1237, self, :level2, []) end def two_levels_top Puppet::Pops::PuppetStack.stack("two_levels.pp", 1237, self, :level2_top, []) end def level2 Puppet::Pops::PuppetStack.stack("level2.pp", 1240, self, :get_stacktrace, []) end def level2_top Puppet::Pops::PuppetStack.stack("level2.pp", 1240, self, :get_top_of_stack, []) end def gets_block(a, &block) block.call(a) end def gets_args_and_block(a, b, &block) block.call(a, b) end def with_nil_file Puppet::Pops::PuppetStack.stack(nil, 1250, self, :get_stacktrace, []) end def with_empty_string_file Puppet::Pops::PuppetStack.stack('', 1251, self, :get_stacktrace, []) end end it 'returns an empty array from stacktrace when there is nothing on the stack' do expect(Puppet::Pops::PuppetStack.stacktrace).to eql([]) end context 'full stacktrace' do it 'returns a one element array with file, line from stacktrace when there is one entry on the stack' do expect(StackTraceTest.new.one_level).to eql([['one_level.pp', 1234]]) end it 'returns an array from stacktrace with information about each level with oldest frame last' do expect(StackTraceTest.new.two_levels).to eql([['level2.pp', 1240], ['two_levels.pp', 1237]]) end it 'returns an empty array from top_of_stack when there is nothing on the stack' do expect(Puppet::Pops::PuppetStack.top_of_stack).to eql([]) end end context 'top of stack' do it 'returns a one element array with file, line from top_of_stack when there is one entry on the stack' do expect(StackTraceTest.new.one_level_top).to eql(['one_level.pp', 1234]) end it 'returns newest entry from top_of_stack' do expect(StackTraceTest.new.two_levels_top).to eql(['level2.pp', 1240]) end it 'accepts file to be nil' do expect(StackTraceTest.new.with_nil_file).to eql([['unknown', 1250]]) end end it 'accepts file to be empty_string' do expect(StackTraceTest.new.with_empty_string_file).to eql([['unknown', 1251]]) end it 'stacktrace is empty when call has returned' do StackTraceTest.new.two_levels expect(Puppet::Pops::PuppetStack.stacktrace).to eql([]) end it 'allows passing a block to the stack call' do expect(Puppet::Pops::PuppetStack.stack("test.pp", 1, StackTraceTest.new, :gets_block, ['got_it']) {|x| x }).to eql('got_it') end it 'allows passing multiple variables and a block' do expect( Puppet::Pops::PuppetStack.stack("test.pp", 1, StackTraceTest.new, :gets_args_and_block, ['got_it', 'again']) {|x, y| [x,y].join(' ')} ).to eql('got_it again') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/label_provider_spec.rb
spec/unit/pops/label_provider_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::LabelProvider do class TestLabelProvider include Puppet::Pops::LabelProvider end let(:labeler) { TestLabelProvider.new } it "prefixes words that start with a vowel with an 'an'" do expect(labeler.a_an('owl')).to eq('an owl') end it "prefixes words that start with a consonant with an 'a'" do expect(labeler.a_an('bear')).to eq('a bear') end it "prefixes non-word characters with an 'a'" do expect(labeler.a_an('[] expression')).to eq('a [] expression') end it "ignores a single quote leading the word" do expect(labeler.a_an("'owl'")).to eq("an 'owl'") end it "ignores a double quote leading the word" do expect(labeler.a_an('"owl"')).to eq('an "owl"') end it "capitalizes the indefinite article for a word when requested" do expect(labeler.a_an_uc('owl')).to eq('An owl') end it "raises an error when missing a character to work with" do expect { labeler.a_an('"') }.to raise_error(Puppet::DevError, /<"> does not appear to contain a word/) end it "raises an error when given an empty string" do expect { labeler.a_an('') }.to raise_error(Puppet::DevError, /<> does not appear to contain a word/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/validation_spec.rb
spec/unit/pops/validation_spec.rb
require 'spec_helper' require 'puppet/pops' describe 'Puppet::Pops::Validation::Diagnostic' do # Mocks a SourcePosAdapter as it is used in these use cases # of a Diagnostic # class MockSourcePos attr_reader :offset def initialize(offset) @offset = offset end end it "computes equal hash value ignoring arguments" do issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos = MockSourcePos.new(10) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos, {:foo => 10}) d2 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos.clone, {:bar => 20}) expect(d1.hash).to eql(d2.hash) end it "computes non equal hash value for different severities" do issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos = MockSourcePos.new(10) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos, {}) d2 = Puppet::Pops::Validation::Diagnostic.new(:error, issue, "foo", source_pos.clone, {}) expect(d1.hash).to_not eql(d2.hash) end it "computes non equal hash value for different offsets" do issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos1 = MockSourcePos.new(10) source_pos2 = MockSourcePos.new(11) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos1, {}) d2 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos2, {}) expect(d1.hash).to_not eql(d2.hash) end it "can be used in a set" do the_set = Set.new() issue = Puppet::Pops::Issues::DIV_BY_ZERO source_pos = MockSourcePos.new(10) d1 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos, {}) d2 = Puppet::Pops::Validation::Diagnostic.new(:warning, issue, "foo", source_pos.clone, {}) d3 = Puppet::Pops::Validation::Diagnostic.new(:error, issue, "foo", source_pos.clone, {}) expect(the_set.add?(d1)).to_not be_nil expect(the_set.add?(d2)).to be_nil expect(the_set.add?(d3)).to_not be_nil end end describe "Puppet::Pops::Validation::SeverityProducer" do it 'sets default severity given in initializer' do producer = Puppet::Pops::Validation::SeverityProducer.new(:warning) expect(producer.severity(Puppet::Pops::Issues::DIV_BY_ZERO)).to be(:warning) end it 'sets default severity to :error if not given' do producer = Puppet::Pops::Validation::SeverityProducer.new() expect(producer.severity(Puppet::Pops::Issues::DIV_BY_ZERO)).to be(: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/pops/resource/resource_type_impl_spec.rb
spec/unit/pops/resource/resource_type_impl_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet_spec/files' require 'puppet_spec/compiler' module Puppet::Pops module Resource describe "Puppet::Pops::Resource" do include PuppetSpec::Compiler let!(:pp_parser) { Parser::EvaluatingParser.new } let(:loader) { Loader::BaseLoader.new(nil, 'type_parser_unit_test_loader') } let(:factory) { TypeFactory } context 'when creating resources' do let!(:resource_type) { ResourceTypeImpl._pcore_type } it 'can create an instance of a ResourceType' do code = <<-CODE $rt = Puppet::Resource::ResourceType3.new('notify', [], [Puppet::Resource::Param.new(String, 'message')]) assert_type(Puppet::Resource::ResourceType3, $rt) notice('looks like we made it') CODE rt = nil notices = eval_and_collect_notices(code) do |scope, _| rt = scope['rt'] end expect(notices).to eq(['looks like we made it']) expect(rt).to be_a(ResourceTypeImpl) expect(rt.valid_parameter?(:nonesuch)).to be_falsey expect(rt.valid_parameter?(:message)).to be_truthy expect(rt.valid_parameter?(:loglevel)).to be_truthy end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/model/model_spec.rb
spec/unit/pops/model/model_spec.rb
require 'spec_helper' require 'puppet/pops' describe Puppet::Pops::Model do it "should be possible to create an instance of a model object" do nop = Puppet::Pops::Model::Nop.new(Puppet::Pops::Parser::Locator.locator('code', 'file'), 0, 0) expect(nop.class).to eq(Puppet::Pops::Model::Nop) end end describe Puppet::Pops::Model::Factory do Factory = Puppet::Pops::Model::Factory Model = Puppet::Pops::Model it "construct an arithmetic expression" do x = Factory.literal(10) + Factory.literal(20) expect(x.is_a?(Factory)).to eq(true) model = x.model expect(model.is_a?(Model::ArithmeticExpression)).to eq(true) expect(model.operator).to eq('+') expect(model.left_expr.class).to eq(Model::LiteralInteger) expect(model.right_expr.class).to eq(Model::LiteralInteger) expect(model.left_expr.value).to eq(10) expect(model.right_expr.value).to eq(20) end it "should be easy to compare using a model tree dumper" do x = Factory.literal(10) + Factory.literal(20) expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x.model)).to eq("(+ 10 20)") end it "builder should apply precedence" do x = Factory.literal(2) * Factory.literal(10) + Factory.literal(20) expect(Puppet::Pops::Model::ModelTreeDumper.new.dump(x.model)).to eq("(+ (* 2 10) 20)") end describe "should be describable with labels" it 'describes a PlanDefinition as "Plan Definition"' do expect(Puppet::Pops::Model::ModelLabelProvider.new.label(Factory.PLAN('test', [], nil))).to eq("Plan Definition") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/model/pn_transformer_spec.rb
spec/unit/pops/model/pn_transformer_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/pn' module Puppet::Pops module Model describe 'Puppet::Pops::Model::PNTransformer' do def call(name, *elements) PN::Call.new(name, *elements.map { |e| lit(e) }) end context 'transforms the expression' do it '"\'hello\'" into the corresponding literal' do x = Factory.literal('hello') expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(lit('hello')) end it '"32" into into the corresponding literal' do x = Factory.literal(32) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(lit(32)) end it '"true" into into the corresponding literal' do x = Factory.literal(true) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(lit(true)) end it '"10 + 20" into (+ 10 20)' do x = Factory.literal(10) + Factory.literal(20) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(call('+', 10, 20)) end it '"[10, 20]" into into (array 10 20)' do x = Factory.literal([10, 20]) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq(call('array', 10, 20)) end it '"{a => 1, b => 2}" into into (hash (=> ("a" 1)) (=> ("b" 2)))' do x = Factory.HASH([Factory.KEY_ENTRY(Factory.literal('a'), Factory.literal(1)), Factory.KEY_ENTRY(Factory.literal('b'), Factory.literal(2))]) expect(Puppet::Pops::Model::PNTransformer.transform(x.model)).to eq( call('hash', call('=>', 'a', 1), call('=>', 'b', 2))) end it 'replaces empty/nil body with a Nop' do expect(Puppet::Pops::Model::PNTransformer.transform(nil)).to eq(call('nop')) end end def lit(value) value.is_a?(PN) ? value : PN::Literal.new(value) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/lookup/context_spec.rb
spec/unit/pops/lookup/context_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' module Puppet::Pops module Lookup describe 'Puppet::Pops::Lookup::Context' do context 'an instance' do include PuppetSpec::Compiler it 'can be created' do code = "notice(type(Puppet::LookupContext.new('m')))" expect(eval_and_collect_notices(code)[0]).to match(/Object\[\{name => 'Puppet::LookupContext'/) end it 'returns its environment_name' do code = "notice(Puppet::LookupContext.new('m').environment_name)" expect(eval_and_collect_notices(code)[0]).to eql('production') end it 'returns its module_name' do code = "notice(Puppet::LookupContext.new('m').module_name)" expect(eval_and_collect_notices(code)[0]).to eql('m') end it 'can use an undef module_name' do code = "notice(type(Puppet::LookupContext.new(undef).module_name))" expect(eval_and_collect_notices(code)[0]).to eql('Undef') end it 'can store and retrieve a value using the cache' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache('ze_key', 'ze_value') notice($ctx.cached_value('ze_key')) PUPPET expect(eval_and_collect_notices(code)[0]).to eql('ze_value') end it 'the cache method returns the value that is cached' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') notice($ctx.cache('ze_key', 'ze_value')) PUPPET expect(eval_and_collect_notices(code)[0]).to eql('ze_value') end it 'can store and retrieve a hash using the cache' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second)) end it 'can use the cache to merge hashes' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cache_all({ 'v3' => 'third', 'v4' => 'fourth' }) $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second v3 third v4 fourth)) end it 'can use the cache to merge hashes and individual entries' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cache('v3', 'third') $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second v3 third)) end it 'can iterate the cache using one argument block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cached_entries |$entry| { notice($entry[0]); notice($entry[1]) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 second)) end it 'can replace individual cached entries' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $ctx.cache('v2', 'changed') $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 first v2 changed)) end it 'can replace multiple cached entries' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second', 'v3' => 'third' }) $ctx.cache_all({ 'v1' => 'one', 'v3' => 'three' }) $ctx.cached_entries |$key, $value| { notice($key); notice($value) } PUPPET expect(eval_and_collect_notices(code)).to eql(%w(v1 one v2 second v3 three)) end it 'cached_entries returns an Iterable when called without a block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.cache_all({ 'v1' => 'first', 'v2' => 'second' }) $iter = $ctx.cached_entries notice(type($iter, generalized)) $iter.each |$entry| { notice($entry[0]); notice($entry[1]) } PUPPET expect(eval_and_collect_notices(code)).to eql(['Iterator[Tuple[String, String, 2, 2]]', 'v1', 'first', 'v2', 'second']) end it 'will throw :no_such_key when not_found is called' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.not_found PUPPET expect { eval_and_collect_notices(code) }.to throw_symbol(:no_such_key) end context 'with cached_file_data' do include PuppetSpec::Files let(:code_dir) { Puppet[:environmentpath] } let(:env_name) { 'testing' } let(:env_dir) { File.join(code_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(:data_yaml) { 'data.yaml' } let(:data_path) { File.join(populated_env_dir, 'data', data_yaml) } let(:populated_env_dir) do dir_contained_in(code_dir, { env_name => { 'data' => { data_yaml => <<-YAML.unindent a: value a YAML } } } ) PuppetSpec::Files.record_tmp(File.join(env_dir)) env_dir end it 'can use cached_file_data without a block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') notice($yaml_data) PUPPET expect(eval_and_collect_notices(code, node)).to eql(["a: value a\n"]) end it 'can use cached_file_data with a block' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET expect(eval_and_collect_notices(code, node)).to eql(["{parsed => a: value a\n}"]) end context 'and multiple compilations' do before(:each) { Puppet.settings[:environment_timeout] = 'unlimited' } it 'will reuse cached_file_data and not call block again' do code1 = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET code2 = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => 'should not be called' } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code1 Puppet::Parser::Compiler.compile(node) Puppet[:code] = code2 Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs.uniq.size).to eql(1) end it 'will invalidate cache if file changes size' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code Puppet::Parser::Compiler.compile(node) # Change content size! File.write(data_path, "a: value is now A\n") Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs).to eql(["{parsed => a: value a\n}", "{parsed => a: value is now A\n}"]) end it 'will invalidate cache if file changes mtime' do old_mtime = Puppet::FileSystem.stat(data_path).mtime code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code Puppet::Parser::Compiler.compile(node) # Write content with the same size File.write(data_path, "a: value b\n") # Ensure mtime is at least 1 second ahead FileUtils.touch(data_path, mtime: old_mtime + 1) Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs).to eql(["{parsed => a: value a\n}", "{parsed => a: value b\n}"]) end it 'will invalidate cache if file changes inode' do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new(nil) $yaml_data = $ctx.cached_file_data('#{data_path}') |$content| { { 'parsed' => $content } } notice($yaml_data) PUPPET logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do Puppet[:code] = code Puppet::Parser::Compiler.compile(node) # Change inode! File.delete(data_path); # Write content with the same size File.write(data_path, "a: value b\n") Puppet::Parser::Compiler.compile(node) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } expect(logs).to eql(["{parsed => a: value a\n}", "{parsed => a: value b\n}"]) end end end context 'when used in an Invocation' do let(:node) { Puppet::Node.new('test') } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:invocation) { Invocation.new(compiler.topscope) } let(:invocation_with_explain) { Invocation.new(compiler.topscope, {}, {}, true) } def compile_and_get_notices(code, scope_vars = {}) Puppet[:code] = code scope = compiler.topscope scope_vars.each_pair { |k,v| scope.setvar(k, v) } node.environment.check_for_reparse logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } logs end it 'will not call explain unless explanations are active' do invocation.lookup('dummy', nil) do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.explain || { notice('stop calling'); 'bad' } PUPPET expect(compile_and_get_notices(code)).to be_empty end end it 'will call explain when explanations are active' do invocation_with_explain.lookup('dummy', nil) do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') $ctx.explain || { notice('called'); 'good' } PUPPET expect(compile_and_get_notices(code)).to eql(['called']) end expect(invocation_with_explain.explainer.explain).to eql("good\n") end it 'will call interpolate to resolve interpolation' do invocation.lookup('dummy', nil) do code = <<-PUPPET.unindent $ctx = Puppet::LookupContext.new('m') notice($ctx.interpolate('-- %{testing} --')) PUPPET expect(compile_and_get_notices(code, { 'testing' => 'called' })).to eql(['-- called --']) end end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/lookup/lookup_spec.rb
spec/unit/pops/lookup/lookup_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/pops' require 'deep_merge/core' module Puppet::Pops module Lookup describe 'The lookup API' do include PuppetSpec::Files let(:env_name) { 'spec' } let(:code_dir) { Puppet[:environmentpath] } let(:env_dir) { File.join(code_dir, env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } let(:compiler) { Puppet::Parser::Compiler.new(node) } let(:pal_compiler) { Puppet::Pal::ScriptCompiler.new(compiler) } let(:scope) { compiler.topscope } let(:invocation) { Invocation.new(scope) } let(:code_dir_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent a: a (from global) d: d (from global) mod::e: mod::e (from global) YAML } } end let(:env_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent b: b (from environment) d: d (from environment) mod::f: mod::f (from environment) YAML } } end let(:mod_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent mod::c: mod::c (from module) mod::e: mod::e (from module) mod::f: mod::f (from module) mod::g: :symbol: symbol key value key: string key value 6: integer key value -4: negative integer key value 2.7: float key value '6': string integer key value YAML } } end let(:populated_env_dir) do all_content = code_dir_content.merge(env_name => env_content.merge('modules' => { 'mod' => mod_content })) dir_contained_in(code_dir, all_content) all_content.keys.each { |key| PuppetSpec::Files.record_tmp(File.join(code_dir, key)) } env_dir end before(:each) do Puppet[:hiera_config] = File.join(code_dir, 'hiera.yaml') Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env)) end after(:each) do Puppet.pop_context end context 'when doing automatic parameter lookup' do let(:mod_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 YAML 'data' => { 'common.yaml' => <<-YAML.unindent mod::x: mod::x (from module) YAML }, 'manifests' => { 'init.pp' => <<-PUPPET.unindent class mod($x) { notify { $x: } } PUPPET } } end let(:logs) { [] } let(:debugs) { logs.select { |log| log.level == :debug }.map { |log| log.message } } it 'includes APL in explain output when debug is enabled' do Puppet[:log_level] = 'debug' Puppet[:code] = 'include mod' Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile end expect(debugs).to include(/Found key: "mod::x" value: "mod::x \(from module\)"/) end end context 'when hiera YAML data is corrupt' do let(:mod_content) do { 'hiera.yaml' => 'version: 5', 'data' => { 'common.yaml' => <<-YAML.unindent --- #mod::classes: - cls1 - cls2 mod::somevar: 1 YAML }, } end let(:msg) { /file does not contain a valid yaml hash/ } %w(off warning).each do |strict| it "logs a warning when --strict is '#{strict}'" do Puppet[:strict] = strict logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(Lookup.lookup('mod::somevar', nil, nil, true, nil, invocation)).to be_nil end expect(logs.map(&:message)).to contain_exactly(msg) end end it 'fails when --strict is "error"' do Puppet[:strict] = 'error' expect { Lookup.lookup('mod::somevar', nil, nil, true, nil, invocation) }.to raise_error(msg) end end context 'when hiera YAML data is empty' do let(:mod_content) do { 'hiera.yaml' => 'version: 5', 'data' => { 'common.yaml' => '' }, } end let(:msg) { /file does not contain a valid yaml hash/ } %w(off warning error).each do |strict| it "logs a warning when --strict is '#{strict}'" do Puppet[:strict] = strict logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do expect(Lookup.lookup('mod::somevar', nil, nil, true, nil, invocation)).to be_nil end expect(logs.map(&:message)).to contain_exactly(msg) end end end context 'when doing lookup' do it 'finds data in global layer' do expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'finds data in environment layer' do expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('b (from environment)') end it 'global layer wins over environment layer' do expect(Lookup.lookup('d', nil, 'not found', true, nil, invocation)).to eql('d (from global)') end it 'finds data in module layer' do expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('mod::c (from module)') end it 'global layer wins over module layer' do expect(Lookup.lookup('mod::e', nil, 'not found', true, nil, invocation)).to eql('mod::e (from global)') end it 'environment layer wins over module layer' do expect(Lookup.lookup('mod::f', nil, 'not found', true, nil, invocation)).to eql('mod::f (from environment)') end it 'returns the correct types for hash keys' do expect(Lookup.lookup('mod::g', nil, 'not found', true, nil, invocation)).to eql( { 'symbol' => 'symbol key value', 'key' => 'string key value', 6 => 'integer key value', -4 => 'negative integer key value', 2.7 => 'float key value', '6' => 'string integer key value' } ) end it 'can navigate a hash with an integer key using a dotted key' do expect(Lookup.lookup('mod::g.6', nil, 'not found', true, nil, invocation)).to eql('integer key value') end it 'can navigate a hash with a negative integer key using a dotted key' do expect(Lookup.lookup('mod::g.-4', nil, 'not found', true, nil, invocation)).to eql('negative integer key value') end it 'can navigate a hash with an string integer key using a dotted key with quoted integer' do expect(Lookup.lookup("mod::g.'6'", nil, 'not found', true, nil, invocation)).to eql('string integer key value') end context "with 'global_only' set to true in the invocation" do let(:invocation) { Invocation.new(scope).set_global_only } it 'finds data in global layer' do expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'does not find data in environment layer' do expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('not found') end it 'does not find data in module layer' do expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('not found') end end context "with 'global_only' set to true in the lookup adapter" do it 'finds data in global layer' do invocation.lookup_adapter.set_global_only expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'does not find data in environment layer' do invocation.lookup_adapter.set_global_only expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('not found') end it 'does not find data in module layer' do invocation.lookup_adapter.set_global_only expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('not found') end end context 'with subclassed lookup adpater' do let(:other_dir) { tmpdir('other') } let(:other_dir_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 hierarchy: - name: Common path: common.yaml - name: More path: more.yaml YAML 'data' => { 'common.yaml' => <<-YAML.unindent, a: a (from other global) d: d (from other global) mixed_adapter_hash: a: ab: value a.ab (from other common global) ad: value a.ad (from other common global) mod::e: mod::e (from other global) lookup_options: mixed_adapter_hash: merge: deep YAML 'more.yaml' => <<-YAML.unindent mixed_adapter_hash: a: aa: value a.aa (from other more global) ac: value a.ac (from other more global) YAML } } end let(:populated_other_dir) do dir_contained_in(other_dir, other_dir_content) other_dir end before(:each) do eval(<<-RUBY.unindent) class SpecialLookupAdapter < LookupAdapter def initialize(compiler) super set_global_only set_global_hiera_config_path(File.join('#{populated_other_dir}', 'hiera.yaml')) end end RUBY end after(:each) do Puppet::Pops::Lookup.send(:remove_const, :SpecialLookupAdapter) end let(:other_invocation) { Invocation.new(scope, EMPTY_HASH, EMPTY_HASH, nil, SpecialLookupAdapter) } it 'finds different data in global layer' do expect(Lookup.lookup('a', nil, nil, false, nil, other_invocation)).to eql('a (from other global)') expect(Lookup.lookup('a', nil, nil, false, nil, invocation)).to eql('a (from global)') end it 'does not find data in environment layer' do expect(Lookup.lookup('b', nil, 'not found', true, nil, other_invocation)).to eql('not found') expect(Lookup.lookup('b', nil, 'not found', true, nil, invocation)).to eql('b (from environment)') end it 'does not find data in module layer' do expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, other_invocation)).to eql('not found') expect(Lookup.lookup('mod::c', nil, 'not found', true, nil, invocation)).to eql('mod::c (from module)') end it 'resolves lookup options using the custom adapter' do expect(Lookup.lookup('mixed_adapter_hash', nil, 'not found', true, nil, other_invocation)).to eql( { 'a' => { 'aa' => 'value a.aa (from other more global)', 'ab' => 'value a.ab (from other common global)', 'ac' => 'value a.ac (from other more global)', 'ad' => 'value a.ad (from other common global)' } } ) end end end context 'when using plan_hierarchy' do let(:code_dir_content) do { 'hiera.yaml' => <<-YAML.unindent, version: 5 plan_hierarchy: - path: foo.yaml name: Common YAML 'data' => { 'foo.yaml' => <<-YAML.unindent pop: star YAML } } end it 'uses plan_hierarchy when using ScriptCompiler' do Puppet.override(pal_compiler: pal_compiler) do expect(Lookup.lookup('pop', nil, nil, true, nil, invocation)).to eq('star') end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/lookup/interpolation_spec.rb
spec/unit/pops/lookup/interpolation_spec.rb
require 'spec_helper' require 'puppet' module Puppet::Pops describe 'Puppet::Pops::Lookup::Interpolation' do include Lookup::SubLookup class InterpolationTestAdapter < Lookup::LookupAdapter include Lookup::SubLookup def initialize(data, interpolator) @data = data @interpolator = interpolator end def track(name) end def lookup(name, lookup_invocation, merge) track(name) segments = split_key(name) root_key = segments.shift found = @data[root_key] found = sub_lookup(name, lookup_invocation, segments, found) unless segments.empty? @interpolator.interpolate(found, lookup_invocation, true) end # ignore requests for lookup options when testing interpolation def lookup_lookup_options(_, _) nil end end let(:interpolator) { Class.new { include Lookup::Interpolation }.new } let(:scope) { {} } let(:data) { {} } let(:adapter) { InterpolationTestAdapter.new(data, interpolator) } let(:lookup_invocation) { Lookup::Invocation.new(scope, {}, {}, nil) } before(:each) do allow_any_instance_of(Lookup::Invocation).to receive(:lookup_adapter).and_return(adapter) end def expect_lookup(*keys) keys.each { |key| expect(adapter).to receive(:track).with(key) } end context 'when the invocation has a default falsey values' do let(:lookup_invocation) { Lookup::Invocation.new(scope, {}, {'key' => false, 'key2' => nil}, nil) } it 'converts boolean false to a "false" string in interpolation' do expect(interpolator.interpolate('%{key}', lookup_invocation, true)).to eq("false") end it 'converts nil to an empty string in interpolation' do expect(interpolator.interpolate('%{key2}', lookup_invocation, true)).to eq("") end end context 'when interpolating nested data' do let(:nested_hash) { {'a' => {'aa' => "%{alias('aaa')}"}} } let(:scope) { { 'ds1' => 'a', 'ds2' => 'b' } } let(:data) { { 'aaa' => {'b' => {'bb' => "%{alias('bbb')}"}}, 'bbb' => ["%{alias('ccc')}"], 'ccc' => 'text', 'ddd' => "%{literal('%')}{ds1}_%{literal('%')}{ds2}", } } it 'produces a nested hash with arrays from nested aliases with hashes and arrays' do expect_lookup('aaa', 'bbb', 'ccc') expect(interpolator.interpolate(nested_hash, lookup_invocation, true)).to eq('a' => {'aa' => {'b' => {'bb' => ['text']}}}) end it "'%{lookup('key')} will interpolate the returned value'" do expect_lookup('ddd') expect(interpolator.interpolate("%{lookup('ddd')}", lookup_invocation, true)).to eq('a_b') end it "'%{alias('key')} will not interpolate the returned value'" do expect_lookup('ddd') expect(interpolator.interpolate("%{alias('ddd')}", lookup_invocation, true)).to eq('%{ds1}_%{ds2}') end end context 'when interpolating boolean scope values' do let(:scope) { { 'yes' => true, 'no' => false } } it 'produces the string true' do expect(interpolator.interpolate('should yield %{yes}', lookup_invocation, true)).to eq('should yield true') end it 'produces the string false' do expect(interpolator.interpolate('should yield %{no}', lookup_invocation, true)).to eq('should yield false') end end context 'when there are empty interpolations %{} in data' do let(:empty_interpolation) { 'clown%{}shoe' } let(:empty_interpolation_as_escape) { 'clown%%{}{shoe}s' } let(:only_empty_interpolation) { '%{}' } let(:empty_namespace) { '%{::}' } let(:whitespace1) { '%{ :: }' } let(:whitespace2) { '%{ }' } it 'should produce an empty string for the interpolation' do expect(interpolator.interpolate(empty_interpolation, lookup_invocation, true)).to eq('clownshoe') end it 'the empty interpolation can be used as an escape mechanism' do expect(interpolator.interpolate(empty_interpolation_as_escape, lookup_invocation, true)).to eq('clown%{shoe}s') end it 'the value can consist of only an empty escape' do expect(interpolator.interpolate(only_empty_interpolation, lookup_invocation, true)).to eq('') end it 'the value can consist of an empty namespace %{::}' do expect(interpolator.interpolate(empty_namespace, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ :: }' do expect(interpolator.interpolate(whitespace1, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ }' do expect(interpolator.interpolate(whitespace2, lookup_invocation, true)).to eq('') end end context 'when there are quoted empty interpolations %{} in data' do let(:empty_interpolation) { 'clown%{""}shoe' } let(:empty_interpolation_as_escape) { 'clown%%{""}{shoe}s' } let(:only_empty_interpolation) { '%{""}' } let(:empty_namespace) { '%{"::"}' } let(:whitespace1) { '%{ "::" }' } let(:whitespace2) { '%{ "" }' } it 'should produce an empty string for the interpolation' do expect(interpolator.interpolate(empty_interpolation, lookup_invocation, true)).to eq('clownshoe') end it 'the empty interpolation can be used as an escape mechanism' do expect(interpolator.interpolate(empty_interpolation_as_escape, lookup_invocation, true)).to eq('clown%{shoe}s') end it 'the value can consist of only an empty escape' do expect(interpolator.interpolate(only_empty_interpolation, lookup_invocation, true)).to eq('') end it 'the value can consist of an empty namespace %{"::"}' do expect(interpolator.interpolate(empty_namespace, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ "::" }' do expect(interpolator.interpolate(whitespace1, lookup_invocation, true)).to eq('') end it 'the value can consist of whitespace %{ "" }' do expect(interpolator.interpolate(whitespace2, lookup_invocation, true)).to eq('') end end context 'when using dotted keys' do let(:data) { { 'a.b' => '(lookup) a dot b', 'a' => { 'd' => '(lookup) a dot d is a hash entry', 'd.x' => '(lookup) a dot d.x is a hash entry', 'd.z' => { 'g' => '(lookup) a dot d.z dot g is a hash entry'} }, 'a.x' => { 'd' => '(lookup) a.x dot d is a hash entry', 'd.x' => '(lookup) a.x dot d.x is a hash entry', 'd.z' => { 'g' => '(lookup) a.x dot d.z dot g is a hash entry' } }, 'x.1' => '(lookup) x dot 1', 'key' => 'subkey' } } let(:scope) { { 'a.b' => '(scope) a dot b', 'a' => { 'd' => '(scope) a dot d is a hash entry', 'd.x' => '(scope) a dot d.x is a hash entry', 'd.z' => { 'g' => '(scope) a dot d.z dot g is a hash entry'} }, 'a.x' => { 'd' => '(scope) a.x dot d is a hash entry', 'd.x' => '(scope) a.x dot d.x is a hash entry', 'd.z' => { 'g' => '(scope) a.x dot d.z dot g is a hash entry' } }, 'x.1' => '(scope) x dot 1', } } it 'should find an entry using a quoted interpolation' do expect(interpolator.interpolate("a dot c: %{'a.b'}", lookup_invocation, true)).to eq('a dot c: (scope) a dot b') end it 'should find an entry using a quoted interpolation with method lookup' do expect_lookup("'a.b'") expect(interpolator.interpolate("a dot c: %{lookup(\"'a.b'\")}", lookup_invocation, true)).to eq('a dot c: (lookup) a dot b') end it 'should find an entry using a quoted interpolation with method alias' do expect_lookup("'a.b'") expect(interpolator.interpolate("%{alias(\"'a.b'\")}", lookup_invocation, true)).to eq('(lookup) a dot b') end it 'should use a dotted key to navigate into a structure when it is not quoted' do expect(interpolator.interpolate('a dot e: %{a.d}', lookup_invocation, true)).to eq('a dot e: (scope) a dot d is a hash entry') end it 'should report a key missing and replace with empty string when a dotted key is used to navigate into a structure and then not found' do expect(interpolator.interpolate('a dot n: %{a.n}', lookup_invocation, true)).to eq('a dot n: ') end it 'should use a dotted key to navigate into a structure when it is not quoted with method lookup' do expect_lookup('a.d') expect(interpolator.interpolate("a dot e: %{lookup('a.d')}", lookup_invocation, true)).to eq('a dot e: (lookup) a dot d is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is last' do expect(interpolator.interpolate("a dot ex: %{a.'d.x'}", lookup_invocation, true)).to eq('a dot ex: (scope) a dot d.x is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is last and method is lookup' do expect_lookup("a.'d.x'") expect(interpolator.interpolate("a dot ex: %{lookup(\"a.'d.x'\")}", lookup_invocation, true)).to eq('a dot ex: (lookup) a dot d.x is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is first' do expect(interpolator.interpolate("a dot xe: %{'a.x'.d}", lookup_invocation, true)).to eq('a dot xe: (scope) a.x dot d is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is first and method is lookup' do expect_lookup("'a.x'.d") expect(interpolator.interpolate("a dot xe: %{lookup(\"'a.x'.d\")}", lookup_invocation, true)).to eq('a dot xe: (lookup) a.x dot d is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle' do expect(interpolator.interpolate("a dot xm: %{a.'d.z'.g}", lookup_invocation, true)).to eq('a dot xm: (scope) a dot d.z dot g is a hash entry') end it 'should use a mix of quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle and method is lookup' do expect_lookup("a.'d.z'.g") expect(interpolator.interpolate("a dot xm: %{lookup(\"a.'d.z'.g\")}", lookup_invocation, true)).to eq('a dot xm: (lookup) a dot d.z dot g is a hash entry') end it 'should use a mix of several quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle' do expect(interpolator.interpolate("a dot xx: %{'a.x'.'d.z'.g}", lookup_invocation, true)).to eq('a dot xx: (scope) a.x dot d.z dot g is a hash entry') end it 'should use a mix of several quoted and dotted keys to navigate into a structure containing dotted keys and quoted key is in the middle and method is lookup' do expect_lookup("'a.x'.'d.z'.g") expect(interpolator.interpolate("a dot xx: %{lookup(\"'a.x'.'d.z'.g\")}", lookup_invocation, true)).to eq('a dot xx: (lookup) a.x dot d.z dot g is a hash entry') end it 'should find an entry using using a quoted interpolation on dotted key containing numbers' do expect(interpolator.interpolate("x dot 2: %{'x.1'}", lookup_invocation, true)).to eq('x dot 2: (scope) x dot 1') end it 'should find an entry using using a quoted interpolation on dotted key containing numbers using method lookup' do expect_lookup("'x.1'") expect(interpolator.interpolate("x dot 2: %{lookup(\"'x.1'\")}", lookup_invocation, true)).to eq('x dot 2: (lookup) x dot 1') end it 'should not find a subkey when the dotted key is quoted' do expect(interpolator.interpolate("a dot f: %{'a.d'}", lookup_invocation, true)).to eq('a dot f: ') end it 'should not find a subkey when the dotted key is quoted with method lookup' do expect_lookup("'a.d'") expect(interpolator.interpolate("a dot f: %{lookup(\"'a.d'\")}", lookup_invocation, true)).to eq('a dot f: ') end it 'should not find a subkey that is matched within a string' do expect{ interpolator.interpolate("%{lookup('key.subkey')}", lookup_invocation, true) }.to raise_error( /Got String when a hash-like object was expected to access value using 'subkey' from key 'key.subkey'/) end end context 'when dealing with non alphanumeric characters' do let(:data) { { 'a key with whitespace' => 'value for a ws key', 'ws_key' => '%{alias("a key with whitespace")}', '\#@!&%|' => 'not happy', 'angry' => '%{alias("\#@!&%|")}', '!$\%!' => { '\#@!&%|' => 'not happy at all' }, 'very_angry' => '%{alias("!$\%!.\#@!&%|")}', 'a key with' => { 'nested whitespace' => 'value for nested ws key', ' untrimmed whitespace ' => 'value for untrimmed ws key' } } } it 'allows keys with white space' do expect_lookup('ws_key', 'a key with whitespace') expect(interpolator.interpolate("%{lookup('ws_key')}", lookup_invocation, true)).to eq('value for a ws key') end it 'allows keys with non alphanumeric characters' do expect_lookup('angry', '\#@!&%|') expect(interpolator.interpolate("%{lookup('angry')}", lookup_invocation, true)).to eq('not happy') end it 'allows dotted keys with non alphanumeric characters' do expect_lookup('very_angry', '!$\%!.\#@!&%|') expect(interpolator.interpolate("%{lookup('very_angry')}", lookup_invocation, true)).to eq('not happy at all') end it 'allows dotted keys with nested white space' do expect_lookup('a key with.nested whitespace') expect(interpolator.interpolate("%{lookup('a key with.nested whitespace')}", lookup_invocation, true)).to eq('value for nested ws key') end it 'will trim each key element' do expect_lookup(' a key with . nested whitespace ') expect(interpolator.interpolate("%{lookup(' a key with . nested whitespace ')}", lookup_invocation, true)).to eq('value for nested ws key') end it 'will not trim quoted key element' do expect_lookup(' a key with ." untrimmed whitespace "') expect(interpolator.interpolate("%{lookup(' a key with .\" untrimmed whitespace \"')}", lookup_invocation, true)).to eq('value for untrimmed ws key') end it 'will not trim spaces outside of quoted key element' do expect_lookup(' a key with . " untrimmed whitespace " ') expect(interpolator.interpolate("%{lookup(' a key with . \" untrimmed whitespace \" ')}", lookup_invocation, true)).to eq('value for untrimmed ws key') end end context 'when dealing with bad keys' do it 'should produce an error when different quotes are used on either side' do expect { interpolator.interpolate("%{'the.key\"}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{'the.key\"}") end it 'should produce an if there is only one quote' do expect { interpolator.interpolate("%{the.'key}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{the.'key}") end it 'should produce an error for an empty segment' do expect { interpolator.interpolate('%{the..key}', lookup_invocation, true)}.to raise_error("Syntax error in string: %{the..key}") end it 'should produce an error for an empty quoted segment' do expect { interpolator.interpolate("%{the.''.key}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{the.''.key}") end it 'should produce an error for an partly quoted segment' do expect { interpolator.interpolate("%{the.'pa'key}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{the.'pa'key}") end it 'should produce an error when different quotes are used on either side in a method argument' do expect { interpolator.interpolate("%{lookup('the.key\")}", lookup_invocation, true)}.to raise_error("Syntax error in string: %{lookup('the.key\")}") end it 'should produce an error unless a known interpolation method is used' do expect { interpolator.interpolate("%{flubber(\"hello\")}", lookup_invocation, true)}.to raise_error("Unknown interpolation method 'flubber'") end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/pops/evaluator/access_ops_spec.rb
spec/unit/pops/evaluator/access_ops_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/pops/evaluator/evaluator_impl' require 'puppet/pops/types/type_factory' require 'base64' # relative to this spec file (./) does not work as this file is loaded by rspec require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper') describe 'Puppet::Pops::Evaluator::EvaluatorImpl/AccessOperator' do include EvaluatorRspecHelper def range(from, to) Puppet::Pops::Types::TypeFactory.range(from, to) end def float_range(from, to) Puppet::Pops::Types::TypeFactory.float_range(from, to) end def binary(s) # Note that the factory is not aware of Binary and cannot operate on a # literal binary. Instead, it must create a call to Binary.new() with the base64 encoded # string as an argument CALL_NAMED(QREF("Binary"), true, [infer(Base64.strict_encode64(s))]) end context 'The evaluator when operating on a String' do it 'can get a single character using a single key index to []' do expect(evaluate(literal('abc').access_at(1))).to eql('b') end it 'can get the last character using the key -1 in []' do expect(evaluate(literal('abc').access_at(-1))).to eql('c') end it 'can get a substring by giving two keys' do expect(evaluate(literal('abcd').access_at(1,2))).to eql('bc') # flattens keys expect(evaluate(literal('abcd').access_at([1,2]))).to eql('bc') end it 'produces empty string for a substring out of range' do expect(evaluate(literal('abc').access_at(100))).to eql('') end it 'raises an error if arity is wrong for []' do expect{evaluate(literal('abc').access_at)}.to raise_error(/String supports \[\] with one or two arguments\. Got 0/) expect{evaluate(literal('abc').access_at(1,2,3))}.to raise_error(/String supports \[\] with one or two arguments\. Got 3/) end end context 'The evaluator when operating on a Binary' do it 'can get a single character using a single key index to []' do expect(evaluate(binary('abc').access_at(1)).binary_buffer).to eql('b') end it 'can get the last character using the key -1 in []' do expect(evaluate(binary('abc').access_at(-1)).binary_buffer).to eql('c') end it 'can get a substring by giving two keys' do expect(evaluate(binary('abcd').access_at(1,2)).binary_buffer).to eql('bc') # flattens keys expect(evaluate(binary('abcd').access_at([1,2])).binary_buffer).to eql('bc') end it 'produces empty string for a substring out of range' do expect(evaluate(binary('abc').access_at(100)).binary_buffer).to eql('') end it 'raises an error if arity is wrong for []' do expect{evaluate(binary('abc').access_at)}.to raise_error(/String supports \[\] with one or two arguments\. Got 0/) expect{evaluate(binary('abc').access_at(1,2,3))}.to raise_error(/String supports \[\] with one or two arguments\. Got 3/) end end context 'The evaluator when operating on an Array' do it 'is tested with the correct assumptions' do expect(literal([1,2,3]).access_at(1).model_class <= Puppet::Pops::Model::AccessExpression).to eql(true) end it 'can get an element using a single key index to []' do expect(evaluate(literal([1,2,3]).access_at(1))).to eql(2) end it 'can get the last element using the key -1 in []' do expect(evaluate(literal([1,2,3]).access_at(-1))).to eql(3) end it 'can get a slice of elements using two keys' do expect(evaluate(literal([1,2,3,4]).access_at(1,2))).to eql([2,3]) # flattens keys expect(evaluate(literal([1,2,3,4]).access_at([1,2]))).to eql([2,3]) end it 'produces nil for a missing entry' do expect(evaluate(literal([1,2,3]).access_at(100))).to eql(nil) end it 'raises an error if arity is wrong for []' do expect{evaluate(literal([1,2,3,4]).access_at)}.to raise_error(/Array supports \[\] with one or two arguments\. Got 0/) expect{evaluate(literal([1,2,3,4]).access_at(1,2,3))}.to raise_error(/Array supports \[\] with one or two arguments\. Got 3/) end end context 'The evaluator when operating on a Hash' do it 'can get a single element giving a single key to []' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3}).access_at('b'))).to eql(2) end it 'can lookup an array' do expect(evaluate(literal({[1]=>10,[2]=>20}).access_at([2]))).to eql(20) end it 'produces nil for a missing key' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3}).access_at('x'))).to eql(nil) end it 'can get multiple elements by giving multiple keys to []' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3, 'd'=>4}).access_at('b', 'd'))).to eql([2, 4]) end it 'compacts the result when using multiple keys' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3, 'd'=>4}).access_at('b', 'x'))).to eql([2]) end it 'produces an empty array if none of multiple given keys were missing' do expect(evaluate(literal({'a'=>1,'b'=>2,'c'=>3, 'd'=>4}).access_at('x', 'y'))).to eql([]) end it 'raises an error if arity is wrong for []' do expect{evaluate(literal({'a'=>1,'b'=>2,'c'=>3}).access_at)}.to raise_error(/Hash supports \[\] with one or more arguments\. Got 0/) end end context "When applied to a type it" do let(:types) { Puppet::Pops::Types::TypeFactory } # Integer # it 'produces an Integer[from, to]' do expr = fqr('Integer').access_at(1, 3) expect(evaluate(expr)).to eql(range(1,3)) # arguments are flattened expr = fqr('Integer').access_at([1, 3]) expect(evaluate(expr)).to eql(range(1,3)) end it 'produces an Integer[1]' do expr = fqr('Integer').access_at(1) expect(evaluate(expr)).to eql(range(1,:default)) end it 'gives an error for Integer[from, <from]' do expr = fqr('Integer').access_at(1,0) expect{evaluate(expr)}.to raise_error(/'from' must be less or equal to 'to'/) end it 'produces an error for Integer[] if there are more than 2 keys' do expr = fqr('Integer').access_at(1,2,3) expect { evaluate(expr)}.to raise_error(/with one or two arguments/) end # Float # it 'produces a Float[from, to]' do expr = fqr('Float').access_at(1, 3) expect(evaluate(expr)).to eql(float_range(1.0,3.0)) # arguments are flattened expr = fqr('Float').access_at([1, 3]) expect(evaluate(expr)).to eql(float_range(1.0,3.0)) end it 'produces a Float[1.0]' do expr = fqr('Float').access_at(1.0) expect(evaluate(expr)).to eql(float_range(1.0,:default)) end it 'produces a Float[1]' do expr = fqr('Float').access_at(1) expect(evaluate(expr)).to eql(float_range(1.0,:default)) end it 'gives an error for Float[from, <from]' do expr = fqr('Float').access_at(1.0,0.0) expect{evaluate(expr)}.to raise_error(/'from' must be less or equal to 'to'/) end it 'produces an error for Float[] if there are more than 2 keys' do expr = fqr('Float').access_at(1,2,3) expect { evaluate(expr)}.to raise_error(/with one or two arguments/) end # Hash Type # it 'produces a Hash[0, 0] from the expression Hash[0, 0]' do expr = fqr('Hash').access_at(0, 0) expect(evaluate(expr)).to be_the_type(types.hash_of(types.default, types.default, types.range(0, 0))) end it 'produces a Hash[Scalar,String] from the expression Hash[Scalar, String]' do expr = fqr('Hash').access_at(fqr('Scalar'), fqr('String')) expect(evaluate(expr)).to be_the_type(types.hash_of(types.string, types.scalar)) # arguments are flattened expr = fqr('Hash').access_at([fqr('Scalar'), fqr('String')]) expect(evaluate(expr)).to be_the_type(types.hash_of(types.string, types.scalar)) end it 'gives an error if only one type is specified ' do expr = fqr('Hash').access_at(fqr('String')) expect {evaluate(expr)}.to raise_error(/accepts 2 to 4 arguments/) end it 'produces a Hash[Scalar,String] from the expression Hash[Integer, Array][Integer, String]' do expr = fqr('Hash').access_at(fqr('Integer'), fqr('Array')).access_at(fqr('Integer'), fqr('String')) expect(evaluate(expr)).to be_the_type(types.hash_of(types.string, types.integer)) end it "gives an error if parameter is not a type" do expr = fqr('Hash').access_at('String') expect { evaluate(expr)}.to raise_error(/Hash-Type\[\] arguments must be types/) end # Array Type # it 'produces an Array[0, 0] from the expression Array[0, 0]' do expr = fqr('Array').access_at(0, 0) expect(evaluate(expr)).to be_the_type(types.array_of(types.default, types.range(0, 0))) # arguments are flattened expr = fqr('Array').access_at([fqr('String')]) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) end it 'produces an Array[String] from the expression Array[String]' do expr = fqr('Array').access_at(fqr('String')) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) # arguments are flattened expr = fqr('Array').access_at([fqr('String')]) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) end it 'produces an Array[String] from the expression Array[Integer][String]' do expr = fqr('Array').access_at(fqr('Integer')).access_at(fqr('String')) expect(evaluate(expr)).to be_the_type(types.array_of(types.string)) end it 'produces a size constrained Array when the last two arguments specify this' do expr = fqr('Array').access_at(fqr('String'), 1) expected_t = types.array_of(String, types.range(1, :default)) expect(evaluate(expr)).to be_the_type(expected_t) expr = fqr('Array').access_at(fqr('String'), 1, 2) expected_t = types.array_of(String, types.range(1, 2)) expect(evaluate(expr)).to be_the_type(expected_t) end it "Array parameterization gives an error if parameter is not a type" do expr = fqr('Array').access_at('String') expect { evaluate(expr)}.to raise_error(/Array-Type\[\] arguments must be types/) end # Timespan Type # it 'produdes a Timespan type with a lower bound' do expr = fqr('Timespan').access_at({fqn('hours') => literal(3)}) expect(evaluate(expr)).to be_the_type(types.timespan({'hours' => 3})) end it 'produdes a Timespan type with an upper bound' do expr = fqr('Timespan').access_at(literal(:default), {fqn('hours') => literal(9)}) expect(evaluate(expr)).to be_the_type(types.timespan(nil, {'hours' => 9})) end it 'produdes a Timespan type with both lower and upper bounds' do expr = fqr('Timespan').access_at({fqn('hours') => literal(3)}, {fqn('hours') => literal(9)}) expect(evaluate(expr)).to be_the_type(types.timespan({'hours' => 3}, {'hours' => 9})) end # Timestamp Type # it 'produdes a Timestamp type with a lower bound' do expr = fqr('Timestamp').access_at(literal('2014-12-12T13:14:15 CET')) expect(evaluate(expr)).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET')) end it 'produdes a Timestamp type with an upper bound' do expr = fqr('Timestamp').access_at(literal(:default), literal('2016-08-23T17:50:00 CET')) expect(evaluate(expr)).to be_the_type(types.timestamp(nil, '2016-08-23T17:50:00 CET')) end it 'produdes a Timestamp type with both lower and upper bounds' do expr = fqr('Timestamp').access_at(literal('2014-12-12T13:14:15 CET'), literal('2016-08-23T17:50:00 CET')) expect(evaluate(expr)).to be_the_type(types.timestamp('2014-12-12T13:14:15 CET', '2016-08-23T17:50:00 CET')) end # Tuple Type # it 'produces a Tuple[String] from the expression Tuple[String]' do expr = fqr('Tuple').access_at(fqr('String')) expect(evaluate(expr)).to be_the_type(types.tuple([String])) # arguments are flattened expr = fqr('Tuple').access_at([fqr('String')]) expect(evaluate(expr)).to be_the_type(types.tuple([String])) end it "Tuple parameterization gives an error if parameter is not a type" do expr = fqr('Tuple').access_at('String') expect { evaluate(expr)}.to raise_error(/Tuple-Type, Cannot use String where Any-Type is expected/) end it 'produces a varargs Tuple when the last two arguments specify size constraint' do expr = fqr('Tuple').access_at(fqr('String'), 1) expected_t = types.tuple([String], types.range(1, :default)) expect(evaluate(expr)).to be_the_type(expected_t) expr = fqr('Tuple').access_at(fqr('String'), 1, 2) expected_t = types.tuple([String], types.range(1, 2)) expect(evaluate(expr)).to be_the_type(expected_t) end # Pattern Type # it 'creates a PPatternType instance when applied to a Pattern' do regexp_expr = fqr('Pattern').access_at('foo') expect(evaluate(regexp_expr)).to eql(Puppet::Pops::Types::TypeFactory.pattern('foo')) end # Regexp Type # it 'creates a Regexp instance when applied to a Pattern' do regexp_expr = fqr('Regexp').access_at('foo') expect(evaluate(regexp_expr)).to eql(Puppet::Pops::Types::TypeFactory.regexp('foo')) # arguments are flattened regexp_expr = fqr('Regexp').access_at(['foo']) expect(evaluate(regexp_expr)).to eql(Puppet::Pops::Types::TypeFactory.regexp('foo')) end # Class # it 'produces a specific class from Class[classname]' do expr = fqr('Class').access_at(fqn('apache')) expect(evaluate(expr)).to be_the_type(types.host_class('apache')) expr = fqr('Class').access_at(literal('apache')) expect(evaluate(expr)).to be_the_type(types.host_class('apache')) end it 'produces an array of Class when args are in an array' do # arguments are flattened expr = fqr('Class').access_at([fqn('apache')]) expect(evaluate(expr)[0]).to be_the_type(types.host_class('apache')) end it 'produces undef for Class if arg is undef' do # arguments are flattened expr = fqr('Class').access_at(nil) expect(evaluate(expr)).to be_nil end it 'produces empty array for Class if arg is [undef]' do # arguments are flattened expr = fqr('Class').access_at([]) expect(evaluate(expr)).to be_eql([]) expr = fqr('Class').access_at([nil]) expect(evaluate(expr)).to be_eql([]) end it 'raises error if access is to no keys' do expr = fqr('Class').access_at(fqn('apache')).access_at expect { evaluate(expr) }.to raise_error(/Evaluation Error: Class\[apache\]\[\] accepts 1 or more arguments\. Got 0/) end it 'produces a collection of classes when multiple class names are given' do expr = fqr('Class').access_at(fqn('apache'), literal('nginx')) result = evaluate(expr) expect(result[0]).to be_the_type(types.host_class('apache')) expect(result[1]).to be_the_type(types.host_class('nginx')) end it 'removes leading :: in class name' do expr = fqr('Class').access_at('::evoe') expect(evaluate(expr)).to be_the_type(types.host_class('evoe')) end it 'raises error if the name is not a valid name' do expr = fqr('Class').access_at('fail-whale') expect { evaluate(expr) }.to raise_error(/Illegal name/) end it 'downcases capitalized class names' do expr = fqr('Class').access_at('My::Class') expect(evaluate(expr)).to be_the_type(types.host_class('my::class')) end it 'gives an error if no keys are given as argument' do expr = fqr('Class').access_at expect {evaluate(expr)}.to raise_error(/Evaluation Error: Class\[\] accepts 1 or more arguments. Got 0/) end it 'produces an empty array if the keys reduce to empty array' do expr = fqr('Class').access_at(literal([[],[]])) expect(evaluate(expr)).to be_eql([]) end # Resource it 'produces a specific resource type from Resource[type]' do expr = fqr('Resource').access_at(fqr('File')) expect(evaluate(expr)).to be_the_type(types.resource('File')) expr = fqr('Resource').access_at(literal('File')) expect(evaluate(expr)).to be_the_type(types.resource('File')) end it 'does not allow the type to be specified in an array' do # arguments are flattened expr = fqr('Resource').access_at([fqr('File')]) expect{evaluate(expr)}.to raise_error(Puppet::ParseError, /must be a resource type or a String/) end it 'produces a specific resource reference type from File[title]' do expr = fqr('File').access_at(literal('/tmp/x')) expect(evaluate(expr)).to be_the_type(types.resource('File', '/tmp/x')) end it 'produces a collection of specific resource references when multiple titles are used' do # Using a resource type expr = fqr('File').access_at(literal('x'),literal('y')) result = evaluate(expr) expect(result[0]).to be_the_type(types.resource('File', 'x')) expect(result[1]).to be_the_type(types.resource('File', 'y')) # Using generic resource expr = fqr('Resource').access_at(fqr('File'), literal('x'),literal('y')) result = evaluate(expr) expect(result[0]).to be_the_type(types.resource('File', 'x')) expect(result[1]).to be_the_type(types.resource('File', 'y')) end it 'produces undef for Resource if arg is undef' do # arguments are flattened expr = fqr('File').access_at(nil) expect(evaluate(expr)).to be_nil end it 'gives an error if no keys are given as argument to Resource' do expr = fqr('Resource').access_at expect {evaluate(expr)}.to raise_error(/Evaluation Error: Resource\[\] accepts 1 or more arguments. Got 0/) end it 'produces an empty array if the type is given, and keys reduce to empty array for Resource' do expr = fqr('Resource').access_at(fqr('File'),literal([[],[]])) expect(evaluate(expr)).to be_eql([]) end it 'gives an error i no keys are given as argument to a specific Resource type' do expr = fqr('File').access_at expect {evaluate(expr)}.to raise_error(/Evaluation Error: File\[\] accepts 1 or more arguments. Got 0/) end it 'produces an empty array if the keys reduce to empty array for a specific Resource tyoe' do expr = fqr('File').access_at(literal([[],[]])) expect(evaluate(expr)).to be_eql([]) end it 'gives an error if resource is not found' do expr = fqr('File').access_at(fqn('x')).access_at(fqn('y')) expect {evaluate(expr)}.to raise_error(/Resource not found: File\['x'\]/) end # NotUndef Type # it 'produces a NotUndef instance' do type_expr = fqr('NotUndef') expect(evaluate(type_expr)).to eql(Puppet::Pops::Types::TypeFactory.not_undef()) end it 'produces a NotUndef instance with contained type' do type_expr = fqr('NotUndef').access_at(fqr('Integer')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.not_undef(tf.integer)) end it 'produces a NotUndef instance with String type when given a literal String' do type_expr = fqr('NotUndef').access_at(literal('hey')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to be_the_type(tf.not_undef(tf.string('hey'))) end it 'Produces Optional instance with String type when using a String argument' do type_expr = fqr('Optional').access_at(literal('hey')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to be_the_type(tf.optional(tf.string('hey'))) end # Type Type # it 'creates a Type instance when applied to a Type' do type_expr = fqr('Type').access_at(fqr('Integer')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.type_type(tf.integer)) # arguments are flattened type_expr = fqr('Type').access_at([fqr('Integer')]) expect(evaluate(type_expr)).to eql(tf.type_type(tf.integer)) end # Ruby Type # it 'creates a Ruby Type instance when applied to a Ruby Type' do type_expr = fqr('Runtime').access_at('ruby','String') tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.ruby_type('String')) # arguments are flattened type_expr = fqr('Runtime').access_at(['ruby', 'String']) expect(evaluate(type_expr)).to eql(tf.ruby_type('String')) end # Callable Type # it 'produces Callable instance without return type' do type_expr = fqr('Callable').access_at(fqr('String')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.callable(String)) end it 'produces Callable instance with parameters and return type' do type_expr = fqr('Callable').access_at([fqr('String')], fqr('Integer')) tf = Puppet::Pops::Types::TypeFactory expect(evaluate(type_expr)).to eql(tf.callable([String], Integer)) end # Variant Type it 'does not allow Variant declarations with non-type arguments' do type_expr = fqr('Variant').access_at(fqr('Integer'), 'not a type') expect { evaluate(type_expr) }.to raise_error(/Cannot use String where Any-Type is expected/) end end matcher :be_the_type do |type| calc = Puppet::Pops::Types::TypeCalculator.new match do |actual| calc.assignable?(actual, type) && calc.assignable?(type, actual) end failure_message do |actual| "expected #{type.to_s}, but was #{actual.to_s}" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false