repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/tidy_spec.rb | spec/unit/type/tidy_spec.rb | require 'spec_helper'
require 'puppet/file_bucket/dipper'
tidy = Puppet::Type.type(:tidy)
describe tidy do
include PuppetSpec::Files
before do
@basepath = make_absolute("/what/ever")
allow(Puppet.settings).to receive(:use)
end
context "when normalizing 'path' on windows", :if => Puppet::Util::Platform.windows? do
it "replaces backslashes with forward slashes" do
resource = tidy.new(:path => 'c:\directory')
expect(resource[:path]).to eq('c:/directory')
end
end
it "should use :lstat when stating a file" do
path = '/foo/bar'
stat = double('stat')
expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stat)
resource = tidy.new :path => path, :age => "1d"
expect(resource.stat(path)).to eq(stat)
end
[:age, :size, :path, :matches, :type, :recurse, :rmdirs].each do |param|
it "should have a #{param} parameter" do
expect(Puppet::Type.type(:tidy).attrclass(param).ancestors).to be_include(Puppet::Parameter)
end
it "should have documentation for its #{param} param" do
expect(Puppet::Type.type(:tidy).attrclass(param).doc).to be_instance_of(String)
end
end
describe "when validating parameter values" do
describe "for 'recurse'" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => "/tmp", :age => "100d"
end
it "should allow 'true'" do
expect { @tidy[:recurse] = true }.not_to raise_error
end
it "should allow 'false'" do
expect { @tidy[:recurse] = false }.not_to raise_error
end
it "should allow integers" do
expect { @tidy[:recurse] = 10 }.not_to raise_error
end
it "should allow string representations of integers" do
expect { @tidy[:recurse] = "10" }.not_to raise_error
end
it "should allow 'inf'" do
expect { @tidy[:recurse] = "inf" }.not_to raise_error
end
it "should not allow arbitrary values" do
expect { @tidy[:recurse] = "whatever" }.to raise_error(Puppet::ResourceError, /Parameter recurse failed/)
end
end
describe "for 'matches'" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => "/tmp", :age => "100d"
end
it "should object if matches is given with recurse is not specified" do
expect { @tidy[:matches] = '*.doh' }.to raise_error(Puppet::ResourceError, /Parameter matches failed/)
end
it "should object if matches is given and recurse is 0" do
expect { @tidy[:recurse] = 0; @tidy[:matches] = '*.doh' }.to raise_error(Puppet::ResourceError, /Parameter matches failed/)
end
it "should object if matches is given and recurse is false" do
expect { @tidy[:recurse] = false; @tidy[:matches] = '*.doh' }.to raise_error(Puppet::ResourceError, /Parameter matches failed/)
end
it "should not object if matches is given and recurse is > 0" do
expect { @tidy[:recurse] = 1; @tidy[:matches] = '*.doh' }.not_to raise_error
end
it "should not object if matches is given and recurse is true" do
expect { @tidy[:recurse] = true; @tidy[:matches] = '*.doh' }.not_to raise_error
end
end
end
describe "when matching files by age" do
convertors = {
:second => 1,
:minute => 60
}
convertors[:hour] = convertors[:minute] * 60
convertors[:day] = convertors[:hour] * 24
convertors[:week] = convertors[:day] * 7
convertors.each do |unit, multiple|
it "should consider a #{unit} to be #{multiple} seconds" do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath, :age => "5#{unit.to_s[0..0]}"
expect(@tidy[:age]).to eq(5 * multiple)
end
end
end
describe "when matching files by size" do
convertors = {
:b => 0,
:kb => 1,
:mb => 2,
:gb => 3,
:tb => 4
}
convertors.each do |unit, multiple|
it "should consider a #{unit} to be 1024^#{multiple} bytes" do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath, :size => "5#{unit}"
total = 5
multiple.times { total *= 1024 }
expect(@tidy[:size]).to eq(total)
end
end
end
describe "when tidying" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@stat = double('stat', :ftype => "directory")
lstat_is(@basepath, @stat)
end
describe "and generating files" do
it "should set the backup on the file if backup is set on the tidy instance" do
@tidy[:backup] = "whatever"
expect(@tidy.mkfile(@basepath)[:backup]).to eq("whatever")
end
it "should set the file's path to the tidy's path" do
expect(@tidy.mkfile(@basepath)[:path]).to eq(@basepath)
end
it "should configure the file for deletion" do
expect(@tidy.mkfile(@basepath)[:ensure]).to eq(:absent)
end
it "should force deletion on the file" do
expect(@tidy.mkfile(@basepath)[:force]).to eq(true)
end
it "should do nothing if the targeted file does not exist" do
lstat_raises(@basepath, Errno::ENOENT)
expect(@tidy.generate).to eq([])
end
end
describe "and recursion is not used" do
it "should generate a file resource if the file should be tidied" do
expect(@tidy).to receive(:tidy?).with(@basepath).and_return(true)
file = Puppet::Type.type(:file).new(:path => @basepath+"/eh")
expect(@tidy).to receive(:mkfile).with(@basepath).and_return(file)
expect(@tidy.generate).to eq([file])
end
it "should do nothing if the file should not be tidied" do
expect(@tidy).to receive(:tidy?).with(@basepath).and_return(false)
expect(@tidy).not_to receive(:mkfile)
expect(@tidy.generate).to eq([])
end
end
describe "and recursion is used" do
before do
@tidy[:recurse] = true
@fileset = Puppet::FileServing::Fileset.new(@basepath)
allow(Puppet::FileServing::Fileset).to receive(:new).and_return(@fileset)
end
it "should use a Fileset with default max_files for infinite recursion" do
expect(Puppet::FileServing::Fileset).to receive(:new).with(@basepath, {:recurse => true, :max_files=>0}).and_return(@fileset)
expect(@fileset).to receive(:files).and_return(%w{. one two})
allow(@tidy).to receive(:tidy?).and_return(false)
@tidy.generate
end
it "should use a Fileset with default max_files for limited recursion" do
@tidy[:recurse] = 42
expect(Puppet::FileServing::Fileset).to receive(:new).with(@basepath, {:recurse => true, :recurselimit => 42, :max_files=>0}).and_return(@fileset)
expect(@fileset).to receive(:files).and_return(%w{. one two})
allow(@tidy).to receive(:tidy?).and_return(false)
@tidy.generate
end
it "should use a Fileset with max_files for limited recursion" do
@tidy[:recurse] = 42
@tidy[:max_files] = 9876
expect(Puppet::FileServing::Fileset).to receive(:new).with(@basepath, {:recurse => true, :recurselimit => 42, :max_files=>9876}).and_return(@fileset)
expect(@fileset).to receive(:files).and_return(%w{. one two})
allow(@tidy).to receive(:tidy?).and_return(false)
@tidy.generate
end
it "should generate a file resource for every file that should be tidied but not for files that should not be tidied" do
expect(@fileset).to receive(:files).and_return(%w{. one two})
expect(@tidy).to receive(:tidy?).with(@basepath).and_return(true)
expect(@tidy).to receive(:tidy?).with(@basepath+"/one").and_return(true)
expect(@tidy).to receive(:tidy?).with(@basepath+"/two").and_return(false)
file = Puppet::Type.type(:file).new(:path => @basepath+"/eh")
expect(@tidy).to receive(:mkfile).with(@basepath).and_return(file)
expect(@tidy).to receive(:mkfile).with(@basepath+"/one").and_return(file)
@tidy.generate
end
end
describe "and determining whether a file matches provided glob patterns" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath, :recurse => 1
@tidy[:matches] = %w{*foo* *bar*}
@stat = double('stat')
@matcher = @tidy.parameter(:matches)
end
it "should always convert the globs to an array" do
@matcher.value = "*foo*"
expect(@matcher.value).to eq(%w{*foo*})
end
it "should return true if any pattern matches the last part of the file" do
@matcher.value = %w{*foo* *bar*}
expect(@matcher).to be_tidy("/file/yaybarness", @stat)
end
it "should return false if no pattern matches the last part of the file" do
@matcher.value = %w{*foo* *bar*}
expect(@matcher).not_to be_tidy("/file/yayness", @stat)
end
end
describe "and determining whether a file is too old" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@stat = double('stat')
@tidy[:age] = "1s"
@tidy[:type] = "mtime"
@ager = @tidy.parameter(:age)
end
it "should use the age type specified" do
@tidy[:type] = :ctime
expect(@stat).to receive(:ctime).and_return(Time.now)
@ager.tidy?(@basepath, @stat)
end
it "should return true if the specified age is 0" do
@tidy[:age] = "0"
expect(@stat).to receive(:mtime).and_return(Time.now)
expect(@ager).to be_tidy(@basepath, @stat)
end
it "should return false if the file is more recent than the specified age" do
expect(@stat).to receive(:mtime).and_return(Time.now)
expect(@ager).not_to be_tidy(@basepath, @stat)
end
it "should return true if the file is older than the specified age" do
expect(@stat).to receive(:mtime).and_return(Time.now - 10)
expect(@ager).to be_tidy(@basepath, @stat)
end
end
describe "and determining whether a file is too large" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@stat = double('stat', :ftype => "file")
@tidy[:size] = "1kb"
@sizer = @tidy.parameter(:size)
end
it "should return false if the file is smaller than the specified size" do
expect(@stat).to receive(:size).and_return(4) # smaller than a kilobyte
expect(@sizer).not_to be_tidy(@basepath, @stat)
end
it "should return true if the file is larger than the specified size" do
expect(@stat).to receive(:size).and_return(1500) # larger than a kilobyte
expect(@sizer).to be_tidy(@basepath, @stat)
end
it "should return true if the file is equal to the specified size" do
expect(@stat).to receive(:size).and_return(1024)
expect(@sizer).to be_tidy(@basepath, @stat)
end
end
describe "and determining whether a file should be tidied" do
before do
@tidy = Puppet::Type.type(:tidy).new :path => @basepath
@catalog = Puppet::Resource::Catalog.new
@tidy.catalog = @catalog
@stat = double('stat', :ftype => "file")
lstat_is(@basepath, @stat)
end
it "should not try to recurse if the file does not exist" do
@tidy[:recurse] = true
lstat_is(@basepath, nil)
expect(@tidy.generate).to eq([])
end
it "should not be tidied if the file does not exist" do
lstat_raises(@basepath, Errno::ENOENT)
expect(@tidy).not_to be_tidy(@basepath)
end
it "should not be tidied if the user has no access to the file" do
lstat_raises(@basepath, Errno::EACCES)
expect(@tidy).not_to be_tidy(@basepath)
end
it "should not be tidied if it is a directory and rmdirs is set to false" do
stat = double('stat', :ftype => "directory")
lstat_is(@basepath, stat)
expect(@tidy).not_to be_tidy(@basepath)
end
it "should return false if it does not match any provided globs" do
@tidy[:recurse] = 1
@tidy[:matches] = "globs"
matches = @tidy.parameter(:matches)
expect(matches).to receive(:tidy?).with(@basepath, @stat).and_return(false)
expect(@tidy).not_to be_tidy(@basepath)
end
it "should return false if it does not match aging requirements" do
@tidy[:age] = "1d"
ager = @tidy.parameter(:age)
expect(ager).to receive(:tidy?).with(@basepath, @stat).and_return(false)
expect(@tidy).not_to be_tidy(@basepath)
end
it "should return false if it does not match size requirements" do
@tidy[:size] = "1b"
sizer = @tidy.parameter(:size)
expect(sizer).to receive(:tidy?).with(@basepath, @stat).and_return(false)
expect(@tidy).not_to be_tidy(@basepath)
end
it "should tidy a file if age and size are set but only size matches" do
@tidy[:size] = "1b"
@tidy[:age] = "1d"
allow(@tidy.parameter(:size)).to receive(:tidy?).and_return(true)
allow(@tidy.parameter(:age)).to receive(:tidy?).and_return(false)
expect(@tidy).to be_tidy(@basepath)
end
it "should tidy a file if age and size are set but only age matches" do
@tidy[:size] = "1b"
@tidy[:age] = "1d"
allow(@tidy.parameter(:size)).to receive(:tidy?).and_return(false)
allow(@tidy.parameter(:age)).to receive(:tidy?).and_return(true)
expect(@tidy).to be_tidy(@basepath)
end
it "should tidy all files if neither age nor size is set" do
expect(@tidy).to be_tidy(@basepath)
end
it "should sort the results inversely by path length, so files are added to the catalog before their directories" do
@tidy[:recurse] = true
@tidy[:rmdirs] = true
fileset = Puppet::FileServing::Fileset.new(@basepath)
expect(Puppet::FileServing::Fileset).to receive(:new).and_return(fileset)
expect(fileset).to receive(:files).and_return(%w{. one one/two})
allow(@tidy).to receive(:tidy?).and_return(true)
expect(@tidy.generate.collect { |r| r[:path] }).to eq([@basepath+"/one/two", @basepath+"/one", @basepath])
end
end
it "should configure directories to require their contained files if rmdirs is enabled, so the files will be deleted first" do
@tidy[:recurse] = true
@tidy[:rmdirs] = true
fileset = double('fileset')
expect(Puppet::FileServing::Fileset).to receive(:new).with(@basepath, {:recurse => true, :max_files=>0}).and_return(fileset)
expect(fileset).to receive(:files).and_return(%w{. one two one/subone two/subtwo one/subone/ssone})
allow(@tidy).to receive(:tidy?).and_return(true)
result = @tidy.generate.inject({}) { |hash, res| hash[res[:path]] = res; hash }
{
@basepath => [ @basepath+"/one", @basepath+"/two" ],
@basepath+"/one" => [@basepath+"/one/subone"],
@basepath+"/two" => [@basepath+"/two/subtwo"],
@basepath+"/one/subone" => [@basepath+"/one/subone/ssone"]
}.each do |parent, children|
children.each do |child|
ref = Puppet::Resource.new(:file, child)
expect(result[parent][:require].find { |req| req.to_s == ref.to_s }).not_to be_nil
end
end
end
it "should configure directories to require their contained files in sorted order" do
@tidy[:recurse] = true
@tidy[:rmdirs] = true
fileset = double('fileset')
expect(Puppet::FileServing::Fileset).to receive(:new).with(@basepath, {:recurse => true, :max_files=>0}).and_return(fileset)
expect(fileset).to receive(:files).and_return(%w{. a a/2 a/1 a/3})
allow(@tidy).to receive(:tidy?).and_return(true)
result = @tidy.generate.inject({}) { |hash, res| hash[res[:path]] = res; hash }
expect(result[@basepath + '/a'][:require].collect{|a| a.name[('File//a/' + @basepath).length..-1]}.join()).to eq('321')
end
it "generates resources whose noop parameter matches the managed resource's noop parameter" do
@tidy[:recurse] = true
@tidy[:noop] = true
fileset = double('fileset')
expect(Puppet::FileServing::Fileset).to receive(:new).with(@basepath, {:recurse => true, :max_files=>0}).and_return(fileset)
expect(fileset).to receive(:files).and_return(%w{. a a/2 a/1 a/3})
allow(@tidy).to receive(:tidy?).and_return(true)
result = @tidy.generate.inject({}) { |hash, res| hash[res[:path]] = res; hash }
expect(result.values).to all(be_noop)
end
it "generates resources whose schedule parameter matches the managed resource's schedule parameter" do
@tidy[:recurse] = true
@tidy[:schedule] = 'fake_schedule'
fileset = double('fileset')
expect(Puppet::FileServing::Fileset).to receive(:new).with(@basepath, {:recurse => true, :max_files=>0}).and_return(fileset)
expect(fileset).to receive(:files).and_return(%w{. a a/2 a/1 a/3})
allow(@tidy).to receive(:tidy?).and_return(true)
result = @tidy.generate.inject({}) { |hash, res| hash[res[:path]] = res; hash }
result.each do |file_resource|
expect(file_resource[1][:schedule]).to eq('fake_schedule')
end
end
end
def lstat_is(path, stat)
allow(Puppet::FileSystem).to receive(:lstat).with(path).and_return(stat)
end
def lstat_raises(path, error_class)
expect(Puppet::FileSystem).to receive(:lstat).with(path).and_raise(Errno::ENOENT)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/mtime_spec.rb | spec/unit/type/file/mtime_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:mtime) do
require 'puppet_spec/files'
include PuppetSpec::Files
before do
@filename = tmpfile('mtime')
@resource = Puppet::Type.type(:file).new({:name => @filename})
end
it "should be able to audit the file's mtime" do
File.open(@filename, "w"){ }
@resource[:audit] = [:mtime]
# this .to_resource audit behavior is magical :-(
expect(@resource.to_resource[:mtime]).to eq(Puppet::FileSystem.stat(@filename).mtime.to_s)
end
it "should return absent if auditing an absent file" do
@resource[:audit] = [:mtime]
expect(@resource.to_resource[:mtime]).to eq(:absent)
end
it "should prevent the user from trying to set the mtime" do
expect {
@resource[:mtime] = Time.now.to_s
}.to raise_error(Puppet::Error, /mtime is read-only/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/group_spec.rb | spec/unit/type/file/group_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:group) do
include PuppetSpec::Files
let(:path) { tmpfile('mode_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :group => 'users' }
let(:group) { resource.property(:group) }
before :each do
# If the provider was already loaded without root, it won't have the
# feature, so we have to add it here to test.
Puppet::Type.type(:file).defaultprovider.has_feature :manages_ownership
end
describe "#insync?" do
before :each do
resource[:group] = ['foos', 'bars']
allow(resource.provider).to receive(:name2gid).with('foos').and_return(1001)
allow(resource.provider).to receive(:name2gid).with('bars').and_return(1002)
end
it "should fail if a group's id can't be found by name" do
allow(resource.provider).to receive(:name2gid).and_return(nil)
expect { group.insync?(5) }.to raise_error(/Could not find group foos/)
end
it "should return false if a group's id can't be found by name in noop" do
Puppet[:noop] = true
allow(resource.provider).to receive(:name2gid).and_return(nil)
expect(group.insync?('notcreatedyet')).to eq(false)
end
it "should use the id for comparisons, not the name" do
expect(group.insync?('foos')).to be_falsey
end
it "should return true if the current group is one of the desired group" do
expect(group.insync?(1001)).to be_truthy
end
it "should return false if the current group is not one of the desired group" do
expect(group.insync?(1003)).to be_falsey
end
end
%w[is_to_s should_to_s].each do |prop_to_s|
describe "##{prop_to_s}" do
it "should use the name of the user if it can find it" do
allow(resource.provider).to receive(:gid2name).with(1001).and_return('foos')
expect(group.send(prop_to_s, 1001)).to eq("'foos'")
end
it "should use the id of the user if it can't" do
allow(resource.provider).to receive(:gid2name).with(1001).and_return(nil)
expect(group.send(prop_to_s, 1001)).to eq('1001')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/mode_spec.rb | spec/unit/type/file/mode_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:mode) do
include PuppetSpec::Files
let(:path) { tmpfile('mode_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :mode => '0644' }
let(:mode) { resource.property(:mode) }
describe "#validate" do
it "should reject non-string values" do
expect {
mode.value = 0755
}.to raise_error(Puppet::Error, /The file mode specification must be a string, not 'Integer'/)
end
it "should accept values specified as octal numbers in strings" do
expect { mode.value = '0755' }.not_to raise_error
end
it "should accept valid symbolic strings" do
expect { mode.value = 'g+w,u-x' }.not_to raise_error
end
it "should not accept strings other than octal numbers" do
expect do
mode.value = 'readable please!'
end.to raise_error(Puppet::Error, /The file mode specification is invalid/)
end
end
describe "#munge" do
# This is sort of a redundant test, but its spec is important.
it "should return the value as a string" do
expect(mode.munge('0644')).to be_a(String)
end
it "should accept strings as arguments" do
expect(mode.munge('0644')).to eq('644')
end
it "should accept symbolic strings as arguments and return them intact" do
expect(mode.munge('u=rw,go=r')).to eq('u=rw,go=r')
end
it "should accept integers are arguments" do
expect(mode.munge(0644)).to eq('644')
end
end
describe "#dirmask" do
before :each do
Dir.mkdir(path)
end
it "should add execute bits corresponding to read bits for directories" do
expect(mode.dirmask('0644')).to eq('755')
end
it "should not add an execute bit when there is no read bit" do
expect(mode.dirmask('0600')).to eq('700')
end
it "should not add execute bits for files that aren't directories" do
resource[:path] = tmpfile('other_file')
expect(mode.dirmask('0644')).to eq('0644')
end
end
describe "#insync?" do
it "should return true if the mode is correct" do
FileUtils.touch(path)
expect(mode).to be_insync('644')
end
it "should return false if the mode is incorrect" do
FileUtils.touch(path)
expect(mode).to_not be_insync('755')
end
it "should return true if the file is a link and we are managing links", :if => Puppet.features.manages_symlinks? do
Puppet::FileSystem.symlink('anything', path)
expect(mode).to be_insync('644')
end
describe "with a symbolic mode" do
let(:resource_sym) { Puppet::Type.type(:file).new :path => path, :mode => 'u+w,g-w' }
let(:mode_sym) { resource_sym.property(:mode) }
it "should return true if the mode matches, regardless of other bits" do
FileUtils.touch(path)
expect(mode_sym).to be_insync('644')
end
it "should return false if the mode requires 0's where there are 1's" do
FileUtils.touch(path)
expect(mode_sym).to_not be_insync('624')
end
it "should return false if the mode requires 1's where there are 0's" do
FileUtils.touch(path)
expect(mode_sym).to_not be_insync('044')
end
end
end
describe "#retrieve" do
it "should return absent if the resource doesn't exist" do
resource[:path] = File.expand_path("/does/not/exist")
expect(mode.retrieve).to eq(:absent)
end
it "should retrieve the directory mode from the provider" do
Dir.mkdir(path)
expect(mode).to receive(:dirmask).with('644').and_return('755')
expect(resource.provider).to receive(:mode).and_return('755')
expect(mode.retrieve).to eq('755')
end
it "should retrieve the file mode from the provider" do
FileUtils.touch(path)
expect(mode).to receive(:dirmask).with('644').and_return('644')
expect(resource.provider).to receive(:mode).and_return('644')
expect(mode.retrieve).to eq('644')
end
end
describe '#should_to_s' do
describe 'with a 3-digit mode' do
it 'returns a 4-digit mode with a leading zero' do
expect(mode.should_to_s('755')).to eq("'0755'")
end
end
describe 'with a 4-digit mode' do
it 'returns the 4-digit mode when the first digit is a zero' do
expect(mode.should_to_s('0755')).to eq("'0755'")
end
it 'returns the 4-digit mode when the first digit is not a zero' do
expect(mode.should_to_s('1755')).to eq("'1755'")
end
end
end
describe '#is_to_s' do
describe 'with a 3-digit mode' do
it 'returns a 4-digit mode with a leading zero' do
expect(mode.is_to_s('755')).to eq("'0755'")
end
end
describe 'with a 4-digit mode' do
it 'returns the 4-digit mode when the first digit is a zero' do
expect(mode.is_to_s('0755')).to eq("'0755'")
end
it 'returns the 4-digit mode when the first digit is not a zero' do
expect(mode.is_to_s('1755')).to eq("'1755'")
end
end
describe 'when passed :absent' do
it "returns 'absent'" do
expect(mode.is_to_s(:absent)).to eq("'absent'")
end
end
end
describe "#sync with a symbolic mode" do
let(:resource_sym) { Puppet::Type.type(:file).new :path => path, :mode => 'u+w,g-w' }
let(:mode_sym) { resource_sym.property(:mode) }
before { FileUtils.touch(path) }
it "changes only the requested bits" do
# lower nibble must be set to 4 for the sake of passing on Windows
Puppet::FileSystem.chmod(0464, path)
mode_sym.sync
stat = Puppet::FileSystem.stat(path)
expect((stat.mode & 0777).to_s(8)).to eq("644")
end
end
describe '#sync with a symbolic mode of +X for a file' do
let(:resource_sym) { Puppet::Type.type(:file).new :path => path, :mode => 'g+wX' }
let(:mode_sym) { resource_sym.property(:mode) }
before { FileUtils.touch(path) }
it 'does not change executable bit if no executable bit is set' do
Puppet::FileSystem.chmod(0644, path)
mode_sym.sync
stat = Puppet::FileSystem.stat(path)
expect((stat.mode & 0777).to_s(8)).to eq('664')
end
it 'does change executable bit if an executable bit is set' do
Puppet::FileSystem.chmod(0744, path)
mode_sym.sync
stat = Puppet::FileSystem.stat(path)
expect((stat.mode & 0777).to_s(8)).to eq('774')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/source_spec.rb | spec/unit/type/file/source_spec.rb | require 'spec_helper'
require 'uri'
require 'puppet/network/http_pool'
describe Puppet::Type.type(:file).attrclass(:source), :uses_checksums => true do
include PuppetSpec::Files
include_context 'with supported checksum types'
around :each do |example|
Puppet.override(:environments => Puppet::Environments::Static.new) do
example.run
end
end
let(:filename) { tmpfile('file_source_validate') }
let(:environment) { Puppet::Node::Environment.remote("myenv") }
let(:catalog) { Puppet::Resource::Catalog.new(:test, environment) }
let(:resource) { Puppet::Type.type(:file).new :path => filename, :catalog => catalog }
before do
@foobar = make_absolute("/foo/bar baz")
@feebooz = make_absolute("/fee/booz baz")
@foobar_uri = Puppet::Util.uri_unescape(Puppet::Util.path_to_uri(@foobar).to_s)
@feebooz_uri = Puppet::Util.uri_unescape(Puppet::Util.path_to_uri(@feebooz).to_s)
end
it "should be a subclass of Parameter" do
expect(described_class.superclass).to eq(Puppet::Parameter)
end
describe "#validate" do
it "should fail if the set values are not URLs" do
expect(URI).to receive(:parse).with('foo').and_raise(RuntimeError)
expect { resource[:source] = %w{foo} }.to raise_error(Puppet::Error)
end
it "should fail if the URI is not a local file, file URI, or puppet URI" do
expect { resource[:source] = %w{ftp://foo/bar} }.to raise_error(Puppet::Error, /Cannot use URLs of type 'ftp' as source for fileserving/)
end
it "should strip trailing forward slashes", :unless => Puppet::Util::Platform.windows? do
resource[:source] = "/foo/bar\\//"
expect(resource[:source].first).to match(%r{/foo/bar\\$})
end
it "should strip trailing forward and backslashes", :if => Puppet::Util::Platform.windows? do
resource[:source] = "X:/foo/bar\\//"
expect(resource[:source].first).to match(/(file\:|file\:\/\/)\/X:\/foo\/bar$/)
end
it "should accept an array of sources" do
resource[:source] = %w{file:///foo/bar puppet://host:8140/foo/bar}
expect(resource[:source]).to eq(%w{file:///foo/bar puppet://host:8140/foo/bar})
end
it "should accept file path characters that are not valid in URI" do
resource[:source] = 'file:///foo bar'
end
it "should reject relative URI sources" do
expect { resource[:source] = 'foo/bar' }.to raise_error(Puppet::Error)
end
it "should reject opaque sources" do
expect { resource[:source] = 'mailto:foo@com' }.to raise_error(Puppet::Error)
end
it "should accept URI authority component" do
resource[:source] = 'file://host/foo'
expect(resource[:source]).to eq(%w{file://host/foo})
end
it "should accept when URI authority is absent" do
resource[:source] = 'file:///foo/bar'
expect(resource[:source]).to eq(%w{file:///foo/bar})
end
end
describe "#munge" do
it "should prefix file scheme to absolute paths" do
resource[:source] = filename
expect(resource[:source]).to eq([Puppet::Util.uri_unescape(Puppet::Util.path_to_uri(filename).to_s)])
end
%w[file puppet].each do |scheme|
it "should not prefix valid #{scheme} URIs" do
resource[:source] = "#{scheme}:///foo bar"
expect(resource[:source]).to eq(["#{scheme}:///foo bar"])
end
end
end
describe "when returning the metadata" do
before do
@metadata = double('metadata', :source= => nil)
allow(resource).to receive(:[]).with(:links).and_return(:manage)
allow(resource).to receive(:[]).with(:source_permissions).and_return(:use)
allow(resource).to receive(:[]).with(:checksum).and_return(:checksum)
end
it "should return already-available metadata" do
@source = described_class.new(:resource => resource)
@source.metadata = "foo"
expect(@source.metadata).to eq("foo")
end
it "should return nil if no @should value is set and no metadata is available" do
@source = described_class.new(:resource => resource)
expect(@source.metadata).to be_nil
end
it "should collect its metadata using the Metadata class if it is not already set" do
@source = described_class.new(:resource => resource, :value => @foobar)
expect(Puppet::FileServing::Metadata.indirection).to receive(:find) do |uri, options|
expect(uri).to eq(@foobar_uri)
expect(options[:environment]).to eq(environment)
expect(options[:links]).to eq(:manage)
expect(options[:checksum_type]).to eq(:checksum)
@metadata
end
@source.metadata
end
it "should use the metadata from the first found source" do
metadata = double('metadata', :source= => nil)
@source = described_class.new(:resource => resource, :value => [@foobar, @feebooz])
options = {
:environment => environment,
:links => :manage,
:source_permissions => :use,
:checksum_type => :checksum
}
expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(@foobar_uri, options).and_return(nil)
expect(Puppet::FileServing::Metadata.indirection).to receive(:find).with(@feebooz_uri, options).and_return(metadata)
expect(@source.metadata).to equal(metadata)
end
it "should store the found source as the metadata's source" do
metadata = double('metadata')
@source = described_class.new(:resource => resource, :value => @foobar)
expect(Puppet::FileServing::Metadata.indirection).to receive(:find) do |uri, options|
expect(uri).to eq(@foobar_uri)
expect(options[:environment]).to eq(environment)
expect(options[:links]).to eq(:manage)
expect(options[:checksum_type]).to eq(:checksum)
metadata
end
expect(metadata).to receive(:source=).with(@foobar_uri)
@source.metadata
end
it "should fail intelligently if an exception is encountered while querying for metadata" do
@source = described_class.new(:resource => resource, :value => @foobar)
expect(Puppet::FileServing::Metadata.indirection).to receive(:find) do |uri, options|
expect(uri).to eq(@foobar_uri)
expect(options[:environment]).to eq(environment)
expect(options[:links]).to eq(:manage)
expect(options[:checksum_type]).to eq(:checksum)
end.and_raise(RuntimeError)
expect(@source).to receive(:fail).and_raise(ArgumentError)
expect { @source.metadata }.to raise_error(ArgumentError)
end
it "should fail if no specified sources can be found" do
@source = described_class.new(:resource => resource, :value => @foobar)
expect(Puppet::FileServing::Metadata.indirection).to receive(:find) do |uri, options|
expect(uri).to eq(@foobar_uri)
expect(options[:environment]).to eq(environment)
expect(options[:links]).to eq(:manage)
expect(options[:checksum_type]).to eq(:checksum)
nil
end
expect(@source).to receive(:fail).and_raise(RuntimeError)
expect { @source.metadata }.to raise_error(RuntimeError)
end
end
it "should have a method for setting the desired values on the resource" do
expect(described_class.new(:resource => resource)).to respond_to(:copy_source_values)
end
describe "when copying the source values" do
before do
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return('my/file.pp')
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(5)
end
before :each do
@resource = Puppet::Type.type(:file).new :path => @foobar
@source = described_class.new(:resource => @resource)
@metadata = double('metadata', :owner => 100, :group => 200, :mode => "173", :checksum => "{md5}asdfasdf", :checksum_type => "md5", :ftype => "file", :source => @foobar)
allow(@source).to receive(:metadata).and_return(@metadata)
allow(Puppet.features).to receive(:root?).and_return(true)
end
it "should not issue an error - except on Windows - if the source mode value is a Numeric" do
allow(@metadata).to receive(:mode).and_return(0173)
@resource[:source_permissions] = :use
if Puppet::Util::Platform.windows?
expect { @source.copy_source_values }.to raise_error("Should not have tried to use source owner/mode/group on Windows (file: my/file.pp, line: 5)")
else
expect { @source.copy_source_values }.not_to raise_error
end
end
it "should not issue an error - except on Windows - if the source mode value is a String" do
allow(@metadata).to receive(:mode).and_return("173")
@resource[:source_permissions] = :use
if Puppet::Util::Platform.windows?
expect { @source.copy_source_values }.to raise_error("Should not have tried to use source owner/mode/group on Windows (file: my/file.pp, line: 5)")
else
expect { @source.copy_source_values }.not_to raise_error
end
end
it "should fail if there is no metadata" do
allow(@source).to receive(:metadata).and_return(nil)
expect(@source).to receive(:devfail).and_raise(ArgumentError)
expect { @source.copy_source_values }.to raise_error(ArgumentError)
end
it "should set :ensure to the file type" do
allow(@metadata).to receive(:ftype).and_return("file")
@source.copy_source_values
expect(@resource[:ensure]).to eq(:file)
end
it "should not set 'ensure' if it is already set to 'absent'" do
allow(@metadata).to receive(:ftype).and_return("file")
@resource[:ensure] = :absent
@source.copy_source_values
expect(@resource[:ensure]).to eq(:absent)
end
describe "and the source is a file" do
before do
allow(@metadata).to receive(:ftype).and_return("file")
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
context "when source_permissions is `use`" do
before :each do
@resource[:source_permissions] = "use"
@resource[:checksum] = :sha256
end
it "should copy the metadata's owner, group, checksum, checksum_type, and mode to the resource if they are not set on the resource" do
@source.copy_source_values
expect(@resource[:owner]).to eq(100)
expect(@resource[:group]).to eq(200)
expect(@resource[:mode]).to eq("0173")
# Metadata calls it checksum and checksum_type, we call it content and checksum.
expect(@resource[:content]).to eq(@metadata.checksum)
expect(@resource[:checksum]).to eq(@metadata.checksum_type.to_sym)
end
it "should not copy the metadata's owner, group, checksum, checksum_type, and mode to the resource if they are already set" do
@resource[:owner] = 1
@resource[:group] = 2
@resource[:mode] = '173'
@resource[:content] = "foobar"
@source.copy_source_values
expect(@resource[:owner]).to eq(1)
expect(@resource[:group]).to eq(2)
expect(@resource[:mode]).to eq('0173')
expect(@resource[:content]).not_to eq(@metadata.checksum)
expect(@resource[:checksum]).not_to eq(@metadata.checksum_type.to_sym)
end
describe "and puppet is not running as root" do
before do
allow(Puppet.features).to receive(:root?).and_return(false)
end
it "should not try to set the owner" do
@source.copy_source_values
expect(@resource[:owner]).to be_nil
end
it "should not try to set the group" do
@source.copy_source_values
expect(@resource[:group]).to be_nil
end
end
end
context "when source_permissions is `use_when_creating`" do
before :each do
@resource[:source_permissions] = "use_when_creating"
expect(Puppet.features).to receive(:root?).and_return(true)
allow(@source).to receive(:local?).and_return(false)
end
context "when managing a new file" do
it "should copy owner and group from local sources" do
allow(@source).to receive(:local?).and_return(true)
@source.copy_source_values
expect(@resource[:owner]).to eq(100)
expect(@resource[:group]).to eq(200)
expect(@resource[:mode]).to eq("0173")
end
it "copies the remote owner" do
@source.copy_source_values
expect(@resource[:owner]).to eq(100)
end
it "copies the remote group" do
@source.copy_source_values
expect(@resource[:group]).to eq(200)
end
it "copies the remote mode" do
@source.copy_source_values
expect(@resource[:mode]).to eq("0173")
end
end
context "when managing an existing file" do
before :each do
allow(Puppet::FileSystem).to receive(:exist?).with(@resource[:path]).and_return(true)
end
it "should not copy owner, group or mode from local sources" do
allow(@source).to receive(:local?).and_return(true)
@source.copy_source_values
expect(@resource[:owner]).to be_nil
expect(@resource[:group]).to be_nil
expect(@resource[:mode]).to be_nil
end
it "preserves the local owner" do
@source.copy_source_values
expect(@resource[:owner]).to be_nil
end
it "preserves the local group" do
@source.copy_source_values
expect(@resource[:group]).to be_nil
end
it "preserves the local mode" do
@source.copy_source_values
expect(@resource[:mode]).to be_nil
end
end
end
context "when source_permissions is default" do
before :each do
allow(@source).to receive(:local?).and_return(false)
expect(Puppet.features).to receive(:root?).and_return(true)
end
it "should not copy owner, group or mode from local sources" do
allow(@source).to receive(:local?).and_return(true)
@source.copy_source_values
expect(@resource[:owner]).to be_nil
expect(@resource[:group]).to be_nil
expect(@resource[:mode]).to be_nil
end
it "preserves the local owner" do
@source.copy_source_values
expect(@resource[:owner]).to be_nil
end
it "preserves the local group" do
@source.copy_source_values
expect(@resource[:group]).to be_nil
end
it "preserves the local mode" do
@source.copy_source_values
expect(@resource[:mode]).to be_nil
end
end
end
describe "and the source is a link" do
before do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
it "should set the target to the link destination" do
allow(@metadata).to receive(:ftype).and_return("link")
allow(@metadata).to receive(:links).and_return("manage")
allow(@metadata).to receive(:checksum_type).and_return(nil)
allow(@resource).to receive(:[])
allow(@resource).to receive(:[]=)
expect(@metadata).to receive(:destination).and_return("/path/to/symlink")
expect(@resource).to receive(:[]=).with(:target, "/path/to/symlink")
@source.copy_source_values
end
end
end
it "should have a local? method" do
expect(described_class.new(:resource => resource)).to be_respond_to(:local?)
end
context "when accessing source properties" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:path) { tmpfile('file_resource') }
let(:resource) { Puppet::Type.type(:file).new(:path => path, :catalog => catalog) }
let(:sourcepath) { tmpfile('file_source') }
describe "for local sources" do
before :each do
FileUtils.touch(sourcepath)
end
describe "on POSIX systems", :if => Puppet.features.posix? do
['', "file:", "file://"].each do |prefix|
it "with prefix '#{prefix}' should be local" do
resource[:source] = "#{prefix}#{sourcepath}"
expect(resource.parameter(:source)).to be_local
end
it "should be able to return the metadata source full path" do
resource[:source] = "#{prefix}#{sourcepath}"
expect(resource.parameter(:source).full_path).to eq(sourcepath)
end
end
end
describe "on Windows systems", :if => Puppet::Util::Platform.windows? do
['', "file:/", "file:///"].each do |prefix|
it "should be local with prefix '#{prefix}'" do
resource[:source] = "#{prefix}#{sourcepath}"
expect(resource.parameter(:source)).to be_local
end
it "should be able to return the metadata source full path" do
resource[:source] = "#{prefix}#{sourcepath}"
expect(resource.parameter(:source).full_path).to eq(sourcepath)
end
it "should convert backslashes to forward slashes" do
resource[:source] = "#{prefix}#{sourcepath.gsub(/\\/, '/')}"
end
end
it "should be UNC with two slashes"
end
end
%w{puppet http}.each do |scheme|
describe "for remote (#{scheme}) sources" do
let(:sourcepath) { "/path/to/source" }
let(:uri) { URI::Generic.build(:scheme => scheme, :host => 'server', :port => 8192, :path => sourcepath).to_s }
before(:each) do
metadata = Puppet::FileServing::Metadata.new(path, :source => uri, 'type' => 'file')
allow(Puppet::FileServing::Metadata.indirection).to receive(:find).
with(uri, include(:environment, :links)).and_return(metadata)
allow(Puppet::FileServing::Metadata.indirection).to receive(:find).
with(uri, include(:environment, :links)).and_return(metadata)
resource[:source] = uri
end
it "should not be local" do
expect(resource.parameter(:source)).not_to be_local
end
it "should be able to return the metadata source full path" do
expect(resource.parameter(:source).full_path).to eq("/path/to/source")
end
it "should be able to return the source server" do
expect(resource.parameter(:source).server).to eq("server")
end
it "should be able to return the source port" do
expect(resource.parameter(:source).port).to eq(8192)
end
if scheme == 'puppet'
describe "which don't specify server or port" do
let(:uri) { "puppet:///path/to/source" }
it "should return the default source server" do
Puppet[:server] = "myserver"
expect(resource.parameter(:source).server).to eq("myserver")
end
it "should return the default source port" do
Puppet[:serverport] = 1234
expect(resource.parameter(:source).port).to eq(1234)
end
end
end
end
end
end
describe "when writing" do
describe "as puppet apply" do
let(:source_content) { "source file content\r\n"*10 }
let(:modulepath) { File.join(Puppet[:environmentpath], 'testing', 'modules') }
let(:env) { Puppet::Node::Environment.create(:testing, [modulepath]) }
let(:catalog) { Puppet::Resource::Catalog.new(:test, env) }
before do
Puppet[:default_file_terminus] = "file_server"
end
it "should copy content from the source to the file" do
resource = Puppet::Type.type(:file).new(path: filename, catalog: catalog, source: file_containing('apply', source_content))
source = resource.parameter(:source)
resource.write(source)
expect(Puppet::FileSystem.binread(filename)).to eq(source_content)
end
it 'should use the in-process fileserver if source starts with puppet:///' do
path = File.join(modulepath, 'mymodule', 'files', 'path')
Puppet::FileSystem.dir_mkpath(path)
File.open(path, 'wb') { |f| f.write(source_content) }
resource = Puppet::Type.type(:file).new(path: filename, catalog: catalog, source: 'puppet:///modules/mymodule/path')
source = resource.parameter(:source)
resource.write(source)
expect(Puppet::FileSystem.binread(filename)).to eq(source_content)
end
it 'follows symlinks when retrieving content from the in-process fileserver' do
# create a 'link' that points to 'target' in the 'mymodule' module
link = File.join(modulepath, 'mymodule', 'files', 'link')
target = File.join(modulepath, 'mymodule', 'files', 'target')
Puppet::FileSystem.dir_mkpath(target)
File.open(target, 'wb') { |f| f.write(source_content) }
Puppet::FileSystem.symlink(target, link)
resource = Puppet::Type.type(:file).new(path: filename, catalog: catalog, source: 'puppet:///modules/mymodule/link')
source = resource.parameter(:source)
resource.write(source)
# 'filename' should be a file containing the contents of the followed link
expect(Puppet::FileSystem.binread(filename)).to eq(source_content)
end
with_digest_algorithms do
it "should return the checksum computed" do
resource = Puppet::Type.type(:file).new(path: filename, catalog: catalog, source: file_containing('apply', source_content))
File.open(filename, 'wb') do |file|
source = resource.parameter(:source)
resource[:checksum] = digest_algorithm
expect(source.write(file)).to eq("{#{digest_algorithm}}#{digest(source_content)}")
end
end
end
end
describe "from local source" do
let(:source_content) { "source file content\r\n"*10 }
before do
resource[:backup] = false
resource[:source] = file_containing('source', source_content)
end
it "should copy content from the source to the file" do
source = resource.parameter(:source)
resource.write(source)
expect(Puppet::FileSystem.binread(filename)).to eq(source_content)
end
with_digest_algorithms do
it "should return the checksum computed" do
File.open(filename, 'wb') do |file|
source = resource.parameter(:source)
resource[:checksum] = digest_algorithm
expect(source.write(file)).to eq("{#{digest_algorithm}}#{digest(source_content)}")
end
end
end
end
describe 'from remote source' do
let(:source_content) { "source file content\n"*10 }
let(:source) {
attr = resource.newattr(:source)
attr.metadata = metadata
attr
}
let(:metadata) {
Puppet::FileServing::Metadata.new(
'/modules/:module/foo',
{
'type' => 'file',
'source' => 'puppet:///modules/:module/foo'
}
)
}
before do
resource[:backup] = false
end
it 'should use an explicit fileserver if source starts with puppet://' do
metadata.source = "puppet://somehostname:8140/modules/:module/foo"
stub_request(:get, %r{https://somehostname:8140/puppet/v3/file_content/modules/:module/foo})
.to_return(status: 200, body: metadata.to_json, headers: { 'Content-Type' => 'application/json' })
resource.write(source)
end
it 'should use the default fileserver if source starts with puppet:///' do
stub_request(:get, %r{https://#{Puppet[:server]}:8140/puppet/v3/file_content/modules/:module/foo})
.to_return(status: 200, body: metadata.to_json, headers: { 'Content-Type' => 'application/json' })
resource.write(source)
end
it 'should percent encode reserved characters' do
metadata.source = 'puppet:///modules/:module/foo bar'
stub_request(:get, %r{/puppet/v3/file_content/modules/:module/foo%20bar})
.to_return(status: 200, body: metadata.to_json, headers: { 'Content-Type' => 'application/json' })
resource.write(source)
end
it 'should request binary content' do
stub_request(:get, %r{/puppet/v3/file_content/modules/:module/foo}) do |request|
expect(request.headers).to include({'Accept' => 'application/octet-stream'})
end.to_return(status: 200, body: '', headers: { 'Content-Type' => 'application/octet-stream' })
resource.write(source)
end
it "should request file content from the catalog's environment" do
Puppet[:environment] = 'doesntexist'
stub_request(:get, %r{/puppet/v3/file_content})
.with(query: hash_including("environment" => "myenv"))
.to_return(status: 200, body: '', headers: { 'Content-Type' => 'application/octet-stream' })
resource.write(source)
end
it 'should request static file content' do
metadata.content_uri = "puppet://#{Puppet[:server]}:8140/path/to/file"
stub_request(:get, %r{/puppet/v3/static_file_content/path/to/file})
.to_return(status: 200, body: '', headers: { 'Content-Type' => 'application/octet-stream' })
resource.write(source)
end
describe 'when handling file_content responses' do
before do
File.open(filename, 'w') {|f| f.write "initial file content"}
end
it 'should not write anything if source is not found' do
stub_request(:get, %r{/puppet/v3/file_content/modules/:module/foo}).to_return(status: 404)
expect { resource.write(source) }.to raise_error(Net::HTTPError, /Error 404 on SERVER:/)
expect(File.read(filename)).to eq('initial file content')
end
it 'should raise an HTTP error in case of server error' do
stub_request(:get, %r{/puppet/v3/file_content/modules/:module/foo}).to_return(status: 500)
expect { resource.write(source) }.to raise_error(Net::HTTPError, /Error 500 on SERVER/)
end
context 'and the request was successful' do
before do
stub_request(:get, %r{/puppet/v3/file_content/modules/:module/foo}).to_return(status: 200, body: source_content)
end
it 'should write the contents to the file' do
resource.write(source)
expect(Puppet::FileSystem.binread(filename)).to eq(source_content)
end
with_digest_algorithms do
it 'should return the checksum computed' do
File.open(filename, 'w') do |file|
resource[:checksum] = digest_algorithm
expect(source.write(file)).to eq("{#{digest_algorithm}}#{digest(source_content)}")
end
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/checksum_value_spec.rb | spec/unit/type/file/checksum_value_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:checksum_value), :uses_checksums => true do
include PuppetSpec::Files
include_context 'with supported checksum types'
let(:path) { tmpfile('foo_bar') }
let(:source_file) { file_containing('temp_foo', 'nothing at all') }
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
let(:catalog) { Puppet::Resource::Catalog.new(:test, environment) }
let(:resource) { Puppet::Type.type(:file).new(:path => path, :catalog => catalog) }
it "should be a property" do
expect(described_class.superclass).to eq(Puppet::Property)
end
describe "when retrieving the current checksum_value" do
let(:checksum_value) { described_class.new(:resource => resource) }
it "should not compute a checksum if source is absent" do
expect(resource).not_to receive(:stat)
expect(checksum_value.retrieve).to be_nil
end
describe "when using a source" do
before do
resource[:source] = source_file
end
it "should return :absent if the target does not exist" do
expect(resource).to receive(:stat).and_return(nil)
expect(checksum_value.retrieve).to eq(:absent)
end
it "should not manage content on directories" do
stat = double('stat', :ftype => "directory")
expect(resource).to receive(:stat).and_return(stat)
expect(checksum_value.retrieve).to be_nil
end
it "should not manage content on links" do
stat = double('stat', :ftype => "link")
expect(resource).to receive(:stat).and_return(stat)
expect(checksum_value.retrieve).to be_nil
end
it "should always return the checksum as a string" do
resource[:checksum] = :mtime
stat = double('stat', :ftype => "file")
expect(resource).to receive(:stat).and_return(stat)
time = Time.now
expect(resource.parameter(:checksum)).to receive(:mtime_file).with(resource[:path]).and_return(time)
expect(checksum_value.retrieve).to eq(time.to_s)
end
end
with_digest_algorithms do
it "should return the checksum of the target if it exists and is a normal file" do
stat = double('stat', :ftype => "file")
expect(resource).to receive(:stat).and_return(stat)
expect(resource.parameter(:checksum)).to receive("#{digest_algorithm}_file".intern).with(resource[:path]).and_return("mysum")
resource[:source] = source_file
expect(checksum_value.retrieve).to eq("mysum")
end
end
end
describe "when testing whether the checksum_value is in sync" do
let(:checksum_value) { described_class.new(:resource => resource) }
before do
resource[:ensure] = :file
end
it "should return true if source is not specified" do
checksum_value.should = "foo"
expect(checksum_value).to be_safe_insync("whatever")
end
describe "when a source is provided" do
before do
resource[:source] = source_file
end
with_digest_algorithms do
before(:each) do
resource[:checksum] = digest_algorithm
end
it "should return true if the resource shouldn't be a regular file" do
expect(resource).to receive(:should_be_file?).and_return(false)
checksum_value.should = "foo"
expect(checksum_value).to be_safe_insync("whatever")
end
it "should return false if the current checksum_value is :absent" do
checksum_value.should = "foo"
expect(checksum_value).not_to be_safe_insync(:absent)
end
it "should return false if the file should be a file but is not present" do
expect(resource).to receive(:should_be_file?).and_return(true)
checksum_value.should = "foo"
expect(checksum_value).not_to be_safe_insync(:absent)
end
describe "and the file exists" do
before do
allow(resource).to receive(:stat).and_return(double("stat"))
checksum_value.should = "somechecksum"
end
it "should return false if the current checksum_value is different from the desired checksum_value" do
expect(checksum_value).not_to be_safe_insync("otherchecksum")
end
it "should return true if the current checksum_value is the same as the desired checksum_value" do
expect(checksum_value).to be_safe_insync("somechecksum")
end
it "should include the diff module" do
expect(checksum_value.respond_to?("diff")).to eq(false)
end
[true, false].product([true, false]).each do |cfg, param|
describe "and Puppet[:show_diff] is #{cfg} and show_diff => #{param}" do
before do
Puppet[:show_diff] = cfg
allow(resource).to receive(:show_diff?).and_return(param)
resource[:loglevel] = "debug"
end
if cfg and param
it "should display a diff" do
expect(checksum_value).to receive(:diff).and_return("my diff").once
expect(checksum_value).to receive(:debug).with("\nmy diff").once
expect(checksum_value).not_to be_safe_insync("otherchecksum")
end
else
it "should not display a diff" do
expect(checksum_value).not_to receive(:diff)
expect(checksum_value).not_to be_safe_insync("otherchecksum")
end
end
end
end
end
end
let(:saved_time) { Time.now }
[:ctime, :mtime].each do |time_stat|
[["older", -1, false], ["same", 0, true], ["newer", 1, true]].each do
|compare, target_time, success|
describe "with #{compare} target #{time_stat} compared to source" do
before do
resource[:checksum] = time_stat
checksum_value.should = saved_time.to_s
end
it "should return #{success}" do
if success
expect(checksum_value).to be_safe_insync((saved_time+target_time).to_s)
else
expect(checksum_value).not_to be_safe_insync((saved_time+target_time).to_s)
end
end
end
end
describe "with #{time_stat}" do
before do
resource[:checksum] = time_stat
end
it "should not be insync if trying to create it" do
checksum_value.should = saved_time.to_s
expect(checksum_value).not_to be_safe_insync(:absent)
end
it "should raise an error if checksum_value is not a checksum" do
checksum_value.should = "some content"
expect {
checksum_value.safe_insync?(saved_time.to_s)
}.to raise_error(/Resource with checksum_type #{time_stat} didn't contain a date in/)
end
it "should not be insync even if checksum_value is the absent symbol" do
checksum_value.should = :absent
expect(checksum_value).not_to be_safe_insync(:absent)
end
end
end
describe "and :replace is false" do
before do
allow(resource).to receive(:replace?).and_return(false)
end
it "should be insync if the file exists and the checksum_value is different" do
allow(resource).to receive(:stat).and_return(double('stat'))
expect(checksum_value).to be_safe_insync("whatever")
end
it "should be insync if the file exists and the checksum_value is right" do
allow(resource).to receive(:stat).and_return(double('stat'))
expect(checksum_value).to be_safe_insync("something")
end
it "should not be insync if the file does not exist" do
checksum_value.should = "foo"
expect(checksum_value).not_to be_safe_insync(:absent)
end
end
end
end
describe "when testing whether the checksum_value is initialized in the resource and in sync" do
CHECKSUM_TYPES_TO_TRY.each do |checksum_type, checksum|
describe "sync with checksum type #{checksum_type} and the file exists" do
before do
@new_resource = Puppet::Type.type(:file).new :ensure => :file, :path => path, :catalog => catalog,
:checksum_value => checksum, :checksum => checksum_type, :source => source_file
allow(@new_resource).to receive(:stat).and_return(double('stat'))
end
it "should return false if the current checksum_value is different from the desired checksum_value" do
expect(@new_resource.parameters[:checksum_value]).not_to be_safe_insync("abcdef")
end
it "should return true if the current checksum_value is the same as the desired checksum_value" do
expect(@new_resource.parameters[:checksum_value]).to be_safe_insync(checksum)
end
end
end
end
describe "when changing the checksum_value" do
let(:checksum_value) { described_class.new(:resource => resource) }
before do
allow(resource).to receive(:[]).with(:path).and_return("/boo")
allow(resource).to receive(:stat).and_return("eh")
end
it "should raise if source is absent" do
expect(resource).not_to receive(:write)
expect { checksum_value.sync }.to raise_error "checksum_value#sync should not be called without a source parameter"
end
describe "when using a source" do
before do
resource[:source] = source_file
end
it "should use the file's :write method to write the checksum_value" do
expect(resource).to receive(:write).with(resource.parameter(:source))
checksum_value.sync
end
it "should return :file_changed if the file already existed" do
expect(resource).to receive(:stat).and_return("something")
allow(resource).to receive(:write)
expect(checksum_value.sync).to eq(:file_changed)
end
it "should return :file_created if the file did not exist" do
expect(resource).to receive(:stat).and_return(nil)
allow(resource).to receive(:write)
expect(checksum_value.sync).to eq(:file_created)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/type_spec.rb | spec/unit/type/file/type_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:type) do
require 'puppet_spec/files'
include PuppetSpec::Files
before do
@filename = tmpfile('type')
@resource = Puppet::Type.type(:file).new({:name => @filename})
end
it "should prevent the user from trying to set the type" do
expect {
@resource[:type] = "fifo"
}.to raise_error(Puppet::Error, /type is read-only/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/selinux_spec.rb | spec/unit/type/file/selinux_spec.rb | require 'spec_helper'
[:seluser, :selrole, :seltype, :selrange].each do |param|
property = Puppet::Type.type(:file).attrclass(param)
describe property do
include PuppetSpec::Files
before do
@path = make_absolute("/my/file")
@resource = Puppet::Type.type(:file).new(:path => @path, :ensure => :file)
@sel = property.new :resource => @resource
end
it "retrieve on #{param} should return :absent if the file isn't statable" do
expect(@resource).to receive(:stat).and_return(nil)
expect(@sel.retrieve).to eq(:absent)
end
it "should retrieve nil for #{param} if there is no SELinux support" do
stat = double('stat', :ftype => "foo")
expect(@resource).to receive(:stat).and_return(stat)
expect(@sel).to receive(:get_selinux_current_context).with(@path).and_return(nil)
expect(@sel.retrieve).to be_nil
end
it "should retrieve #{param} if a SELinux context is found with a range" do
stat = double('stat', :ftype => "foo")
expect(@resource).to receive(:stat).and_return(stat)
expect(@sel).to receive(:get_selinux_current_context).with(@path).and_return("user_u:role_r:type_t:s0")
expectedresult = case param
when :seluser; "user_u"
when :selrole; "role_r"
when :seltype; "type_t"
when :selrange; "s0"
end
expect(@sel.retrieve).to eq(expectedresult)
end
it "should retrieve #{param} if a SELinux context is found without a range" do
stat = double('stat', :ftype => "foo")
expect(@resource).to receive(:stat).and_return(stat)
expect(@sel).to receive(:get_selinux_current_context).with(@path).and_return("user_u:role_r:type_t")
expectedresult = case param
when :seluser; "user_u"
when :selrole; "role_r"
when :seltype; "type_t"
when :selrange; nil
end
expect(@sel.retrieve).to eq(expectedresult)
end
it "should handle no default gracefully" do
skip if Puppet::Util::Platform.windows?
expect(@sel).to receive(:get_selinux_default_context_with_handle).with(@path, nil, :file).and_return(nil)
expect(@sel.default).to be_nil
end
it "should be able to detect default context on platforms other than Windows", unless: Puppet::Util::Platform.windows? do
allow(@sel).to receive(:debug)
hnd = double("SWIG::TYPE_p_selabel_handle")
allow(@sel.provider.class).to receive(:selinux_handle).and_return(hnd)
expect(@sel).to receive(:get_selinux_default_context_with_handle).with(@path, hnd, :file).and_return("user_u:role_r:type_t:s0")
expectedresult = case param
when :seluser; "user_u"
when :selrole; "role_r"
when :seltype; "type_t"
when :selrange; "s0"
end
expect(@sel.default).to eq(expectedresult)
end
it "returns nil default context on Windows", if: Puppet::Util::Platform.windows? do
expect(@sel).to receive(:retrieve_default_context)
expect(@sel.default).to be_nil
end
it "should return nil for defaults if selinux_ignore_defaults is true" do
@resource[:selinux_ignore_defaults] = :true
expect(@sel.default).to be_nil
end
it "should be able to set a new context" do
@sel.should = %w{newone}
expect(@sel).to receive(:set_selinux_context).with(@path, ["newone"], param)
@sel.sync
end
it "should do nothing for safe_insync? if no SELinux support" do
@sel.should = %{newcontext}
expect(@sel).to receive(:selinux_support?).and_return(false)
expect(@sel.safe_insync?("oldcontext")).to eq(true)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/owner_spec.rb | spec/unit/type/file/owner_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:owner) do
include PuppetSpec::Files
let(:path) { tmpfile('mode_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :owner => 'joeuser' }
let(:owner) { resource.property(:owner) }
before :each do
allow(Puppet.features).to receive(:root?).and_return(true)
end
describe "#insync?" do
before :each do
resource[:owner] = ['foo', 'bar']
allow(resource.provider).to receive(:name2uid).with('foo').and_return(1001)
allow(resource.provider).to receive(:name2uid).with('bar').and_return(1002)
end
it "should fail if an owner's id can't be found by name" do
allow(resource.provider).to receive(:name2uid).and_return(nil)
expect { owner.insync?(5) }.to raise_error(/Could not find user foo/)
end
it "should return false if an owner's id can't be found by name in noop" do
Puppet[:noop] = true
allow(resource.provider).to receive(:name2uid).and_return(nil)
expect(owner.insync?('notcreatedyet')).to eq(false)
end
it "should use the id for comparisons, not the name" do
expect(owner.insync?('foo')).to be_falsey
end
it "should return true if the current owner is one of the desired owners" do
expect(owner.insync?(1001)).to be_truthy
end
it "should return false if the current owner is not one of the desired owners" do
expect(owner.insync?(1003)).to be_falsey
end
end
%w[is_to_s should_to_s].each do |prop_to_s|
describe "##{prop_to_s}" do
it "should use the name of the user if it can find it" do
allow(resource.provider).to receive(:uid2name).with(1001).and_return('foo')
expect(owner.send(prop_to_s, 1001)).to eq("'foo'")
end
it "should use the id of the user if it can't" do
allow(resource.provider).to receive(:uid2name).with(1001).and_return(nil)
expect(owner.send(prop_to_s, 1001)).to eq('1001')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/ensure_spec.rb | spec/unit/type/file/ensure_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:ensure) do
include PuppetSpec::Files
let(:path) { tmpfile('file_ensure') }
let(:resource) { Puppet::Type.type(:file).new(:ensure => 'file', :path => path, :replace => true) }
let(:property) { resource.property(:ensure) }
it "should be a subclass of Ensure" do
expect(described_class.superclass).to eq(Puppet::Property::Ensure)
end
describe "when retrieving the current state" do
it "should return :absent if the file does not exist" do
expect(resource).to receive(:stat).and_return(nil)
expect(property.retrieve).to eq(:absent)
end
it "should return the current file type if the file exists" do
stat = double('stat', :ftype => "directory")
expect(resource).to receive(:stat).and_return(stat)
expect(property.retrieve).to eq(:directory)
end
end
describe "when testing whether :ensure is in sync" do
it "should always be in sync if replace is 'false' unless the file is missing" do
property.should = :file
expect(resource).to receive(:replace?).and_return(false)
expect(property.safe_insync?(:link)).to be_truthy
end
it "should be in sync if :ensure is set to :absent and the file does not exist" do
property.should = :absent
expect(property).to be_safe_insync(:absent)
end
it "should not be in sync if :ensure is set to :absent and the file exists" do
property.should = :absent
expect(property).not_to be_safe_insync(:file)
end
it "should be in sync if a normal file exists and :ensure is set to :present" do
property.should = :present
expect(property).to be_safe_insync(:file)
end
it "should be in sync if a directory exists and :ensure is set to :present" do
property.should = :present
expect(property).to be_safe_insync(:directory)
end
it "should be in sync if a symlink exists and :ensure is set to :present" do
property.should = :present
expect(property).to be_safe_insync(:link)
end
it "should not be in sync if :ensure is set to :file and a directory exists" do
property.should = :file
expect(property).not_to be_safe_insync(:directory)
end
end
describe "#sync" do
context "directory" do
before :each do
resource[:ensure] = :directory
end
it "should raise if the parent directory doesn't exist" do
newpath = File.join(path, 'nonexistentparent', 'newdir')
resource[:path] = newpath
expect {
property.sync
}.to raise_error(Puppet::Error, /Cannot create #{newpath}; parent directory #{File.dirname(newpath)} does not exist/)
end
it "should accept octal mode as integer" do
resource[:mode] = '0700'
expect(resource).to receive(:property_fix)
expect(Dir).to receive(:mkdir).with(path, 0700)
property.sync
end
it "should accept octal mode as string" do
resource[:mode] = "700"
expect(resource).to receive(:property_fix)
expect(Dir).to receive(:mkdir).with(path, 0700)
property.sync
end
it "should accept octal mode as string with leading zero" do
resource[:mode] = "0700"
expect(resource).to receive(:property_fix)
expect(Dir).to receive(:mkdir).with(path, 0700)
property.sync
end
it "should accept symbolic mode" do
resource[:mode] = "u=rwx,go=x"
expect(resource).to receive(:property_fix)
expect(Dir).to receive(:mkdir).with(path, 0711)
property.sync
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/content_spec.rb | spec/unit/type/file/content_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:content), :uses_checksums => true do
include PuppetSpec::Files
include_context 'with supported checksum types'
let(:filename) { tmpfile('testfile') }
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
let(:catalog) { Puppet::Resource::Catalog.new(:test, environment) }
let(:resource) { Puppet::Type.type(:file).new :path => filename, :catalog => catalog, :backup => 'puppet' }
before do
File.open(filename, 'w') {|f| f.write "initial file content"}
end
around do |example|
Puppet.override(:environments => Puppet::Environments::Static.new(environment)) do
example.run
end
end
describe "when determining the actual content to write" do
let(:content) { described_class.new(:resource => resource) }
it "should use the set content if available" do
content.should = "ehness"
expect(content.actual_content).to eq("ehness")
end
it "should not use the content from the source if the source is set" do
expect(resource).not_to receive(:parameter).with(:source)
expect(content.actual_content).to be_nil
end
end
describe "when setting the desired content" do
let(:content) { described_class.new(:resource => resource) }
before do
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return('my/file.pp')
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(5)
end
it "should make the actual content available via an attribute" do
content.should = "this is some content"
expect(content.actual_content).to eq("this is some content")
end
with_digest_algorithms do
it "should store the checksum as the desired content" do
d = digest("this is some content")
content.should = "this is some content"
expect(content.should).to eq("{#{digest_algorithm}}#{d}")
end
it "should not checksum 'absent'" do
content.should = :absent
expect(content.should).to eq(:absent)
end
it "should accept a checksum as the desired content" do
d = digest("this is some content")
string = "{#{digest_algorithm}}#{d}"
content.should = string
expect(content.should).to eq(string)
end
end
it "should convert the value to ASCII-8BIT" do
content.should= "Let's make a \u{2603}"
expect(content.actual_content).to eq("Let's make a \xE2\x98\x83".force_encoding(Encoding::ASCII_8BIT))
end
end
describe "when retrieving the current content" do
let(:content) { described_class.new(:resource => resource) }
it "should return :absent if the file does not exist" do
expect(resource).to receive(:stat).and_return(nil)
expect(content.retrieve).to eq(:absent)
end
it "should not manage content on directories" do
stat = double('stat', :ftype => "directory")
expect(resource).to receive(:stat).and_return(stat)
expect(content.retrieve).to be_nil
end
it "should not manage content on links" do
stat = double('stat', :ftype => "link")
expect(resource).to receive(:stat).and_return(stat)
expect(content.retrieve).to be_nil
end
it "should always return the checksum as a string" do
resource[:checksum] = :mtime
stat = double('stat', :ftype => "file")
expect(resource).to receive(:stat).and_return(stat)
time = Time.now
expect(resource.parameter(:checksum)).to receive(:mtime_file).with(resource[:path]).and_return(time)
expect(content.retrieve).to eq("{mtime}#{time}")
end
with_digest_algorithms do
it "should return the checksum of the file if it exists and is a normal file" do
stat = double('stat', :ftype => "file")
expect(resource).to receive(:stat).and_return(stat)
expect(resource.parameter(:checksum)).to receive("#{digest_algorithm}_file".intern).with(resource[:path]).and_return("mysum")
expect(content.retrieve).to eq("{#{digest_algorithm}}mysum")
end
end
end
describe "when testing whether the content is in sync" do
let(:content) { described_class.new(:resource => resource) }
before do
resource[:ensure] = :file
end
with_digest_algorithms do
before(:each) do
resource[:checksum] = digest_algorithm
end
it "should return true if the resource shouldn't be a regular file" do
expect(resource).to receive(:should_be_file?).and_return(false)
content.should = "foo"
expect(content).to be_safe_insync("whatever")
end
it "should warn that no content will be synced to links when ensure is :present" do
resource[:ensure] = :present
resource[:content] = 'foo'
allow(resource).to receive(:should_be_file?).and_return(false)
allow(resource).to receive(:stat).and_return(double("stat", :ftype => "link"))
expect(resource).to receive(:warning).with(/Ensure set to :present but file type is/)
content.insync? :present
end
it "should return false if the current content is :absent" do
content.should = "foo"
expect(content).not_to be_safe_insync(:absent)
end
it "should return false if the file should be a file but is not present" do
expect(resource).to receive(:should_be_file?).and_return(true)
content.should = "foo"
expect(content).not_to be_safe_insync(:absent)
end
describe "and the file exists" do
before do
allow(resource).to receive(:stat).and_return(double("stat"))
content.should = "some content"
end
it "should return false if the current contents are different from the desired content" do
expect(content).not_to be_safe_insync("other content")
end
it "should return true if the sum for the current contents is the same as the sum for the desired content" do
expect(content).to be_safe_insync("{#{digest_algorithm}}" + digest("some content"))
end
it "should include the diff module" do
expect(content.respond_to?("diff")).to eq(false)
end
describe "showing the diff" do
it "doesn't show the diff when #show_diff? is false" do
expect(content).to receive(:show_diff?).and_return(false)
expect(content).not_to receive(:diff)
expect(content).not_to be_safe_insync("other content")
end
describe "and #show_diff? is true" do
before do
expect(content).to receive(:show_diff?).and_return(true)
resource[:loglevel] = "debug"
end
it "prints the diff" do
expect(content).to receive(:diff).and_return("my diff")
expect(content).to receive(:debug).with("\nmy diff")
expect(content).not_to be_safe_insync("other content")
end
it "prints binary file notice if diff is not valid encoding" do
expect(content).to receive(:diff).and_return("\xc7\xd1\xfc\x84")
expect(content).to receive(:debug).with(/\nBinary files #{filename} and .* differ/)
expect(content).not_to be_safe_insync("other content")
end
it "redacts the diff when the property is sensitive" do
content.sensitive = true
expect(content).not_to receive(:diff)
expect(content).to receive(:debug).with("[diff redacted]")
expect(content).not_to be_safe_insync("other content")
end
end
end
end
end
let(:saved_time) { Time.now }
[:ctime, :mtime].each do |time_stat|
[["older", -1, false], ["same", 0, true], ["newer", 1, true]].each do
|compare, target_time, success|
describe "with #{compare} target #{time_stat} compared to source" do
before do
resource[:checksum] = time_stat
resource[:source] = make_absolute('/temp/foo')
content.should = "{#{time_stat}}#{saved_time}"
end
it "should return #{success}" do
if success
expect(content).to be_safe_insync("{#{time_stat}}#{saved_time+target_time}")
else
expect(content).not_to be_safe_insync("{#{time_stat}}#{saved_time+target_time}")
end
end
end
end
describe "with #{time_stat}" do
before do
resource[:checksum] = time_stat
resource[:source] = make_absolute('/temp/foo')
end
it "should not be insync if trying to create it" do
content.should = "{#{time_stat}}#{saved_time}"
expect(content).not_to be_safe_insync(:absent)
end
it "should raise an error if content is not a checksum" do
content.should = "some content"
expect {
content.safe_insync?("{#{time_stat}}#{saved_time}")
}.to raise_error(/Resource with checksum_type #{time_stat} didn't contain a date in/)
end
it "should not be insync even if content is the absent symbol" do
content.should = :absent
expect(content).not_to be_safe_insync(:absent)
end
it "should warn that no content will be synced to links when ensure is :present" do
resource[:ensure] = :present
resource[:content] = 'foo'
allow(resource).to receive(:should_be_file?).and_return(false)
allow(resource).to receive(:stat).and_return(double("stat", :ftype => "link"))
expect(resource).to receive(:warning).with(/Ensure set to :present but file type is/)
content.insync? :present
end
end
end
describe "and :replace is false" do
before do
allow(resource).to receive(:replace?).and_return(false)
end
it "should be insync if the file exists and the content is different" do
allow(resource).to receive(:stat).and_return(double('stat'))
expect(content).to be_safe_insync("whatever")
end
it "should be insync if the file exists and the content is right" do
allow(resource).to receive(:stat).and_return(double('stat'))
expect(content).to be_safe_insync("something")
end
it "should not be insync if the file does not exist" do
content.should = "foo"
expect(content).not_to be_safe_insync(:absent)
end
end
end
describe "when testing whether the content is initialized in the resource and in sync" do
CHECKSUM_TYPES_TO_TRY.each do |checksum_type, checksum|
describe "sync with checksum type #{checksum_type} and the file exists" do
before do
@new_resource = Puppet::Type.type(:file).new :ensure => :file, :path => filename, :catalog => catalog,
:content => CHECKSUM_PLAINTEXT, :checksum => checksum_type
allow(@new_resource).to receive(:stat).and_return(double('stat'))
end
it "should return false if the sum for the current contents are different from the desired content" do
expect(@new_resource.parameters[:content]).not_to be_safe_insync("other content")
end
it "should return true if the sum for the current contents is the same as the sum for the desired content" do
expect(@new_resource.parameters[:content]).to be_safe_insync("{#{checksum_type}}#{checksum}")
end
end
end
end
describe "determining if a diff should be shown" do
let(:content) { described_class.new(:resource => resource) }
before do
Puppet[:show_diff] = true
resource[:show_diff] = true
end
it "is true if there are changes and the global and per-resource show_diff settings are true" do
expect(content.show_diff?(true)).to be_truthy
end
it "is false if there are no changes" do
expect(content.show_diff?(false)).to be_falsey
end
it "is false if show_diff is globally disabled" do
Puppet[:show_diff] = false
expect(content.show_diff?(false)).to be_falsey
end
it "is false if show_diff is disabled on the resource" do
resource[:show_diff] = false
expect(content.show_diff?(false)).to be_falsey
end
end
describe "when changing the content" do
let(:content) { described_class.new(:resource => resource) }
before do
allow(resource).to receive(:[]).with(:path).and_return("/boo")
allow(resource).to receive(:stat).and_return("eh")
end
it "should use the file's :write method to write the content" do
expect(resource).to receive(:write).with(content)
content.sync
end
it "should return :file_changed if the file already existed" do
expect(resource).to receive(:stat).and_return("something")
allow(resource).to receive(:write)
expect(content.sync).to eq(:file_changed)
end
it "should return :file_created if the file did not exist" do
expect(resource).to receive(:stat).and_return(nil)
allow(resource).to receive(:write)
expect(content.sync).to eq(:file_created)
end
end
describe "when writing" do
let(:content) { described_class.new(:resource => resource) }
let(:fh) { File.open(filename, 'wb') }
before do
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return('my/file.pp')
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(5)
end
it "should attempt to read from the filebucket if no actual content nor source exists" do
content.should = "{md5}foo"
allow_any_instance_of(content.resource.bucket.class).to receive(:getfile).and_return("foo")
content.write(fh)
fh.close
end
describe "from actual content" do
before(:each) do
allow(content).to receive(:actual_content).and_return("this is content")
end
it "should write to the given file handle" do
fh = double('filehandle')
expect(fh).to receive(:print).with("this is content")
content.write(fh)
end
it "should return the current checksum value" do
expect(resource.parameter(:checksum)).to receive(:sum_stream).and_return("checksum")
expect(content.write(fh)).to eq("checksum")
end
end
describe "from a file bucket" do
it "should fail if a file bucket cannot be retrieved" do
content.should = "{md5}foo"
expect(content.resource).to receive(:bucket).and_return(nil)
expect { content.write(fh) }.to raise_error(Puppet::Error)
end
it "should fail if the file bucket cannot find any content" do
content.should = "{md5}foo"
bucket = double('bucket')
expect(content.resource).to receive(:bucket).and_return(bucket)
expect(bucket).to receive(:getfile).with("foo").and_raise("foobar")
expect { content.write(fh) }.to raise_error(Puppet::Error)
end
it "should write the returned content to the file" do
content.should = "{md5}foo"
bucket = double('bucket')
expect(content.resource).to receive(:bucket).and_return(bucket)
expect(bucket).to receive(:getfile).with("foo").and_return("mycontent")
fh = double('filehandle')
expect(fh).to receive(:print).with("mycontent")
content.write(fh)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/checksum_spec.rb | spec/unit/type/file/checksum_spec.rb | require 'spec_helper'
checksum = Puppet::Type.type(:file).attrclass(:checksum)
describe checksum do
before do
@path = Puppet::Util::Platform.windows? ? "c:/foo/bar" : "/foo/bar"
@resource = Puppet::Type.type(:file).new :path => @path
@checksum = @resource.parameter(:checksum)
end
it "should be a parameter" do
expect(checksum.superclass).to eq(Puppet::Parameter)
end
it "should use its current value when asked to sum content" do
@checksum.value = :md5lite
expect(@checksum).to receive(:md5lite).with("foobar").and_return("yay")
@checksum.sum("foobar")
end
it "should use :sha256 to sum when no value is set" do
expect(@checksum).to receive(:sha256).with("foobar").and_return("yay")
@checksum.sum("foobar")
end
it "should return the summed contents with a checksum label" do
sum = Digest::MD5.hexdigest("foobar")
@resource[:checksum] = :md5
expect(@checksum.sum("foobar")).to eq("{md5}#{sum}")
end
it "when using digest_algorithm 'sha256' should return the summed contents with a checksum label" do
sum = Digest::SHA256.hexdigest("foobar")
@resource[:checksum] = :sha256
expect(@checksum.sum("foobar")).to eq("{sha256}#{sum}")
end
it "when using digest_algorithm 'sha512' should return the summed contents with a checksum label" do
sum = Digest::SHA512.hexdigest("foobar")
@resource[:checksum] = :sha512
expect(@checksum.sum("foobar")).to eq("{sha512}#{sum}")
end
it "when using digest_algorithm 'sha384' should return the summed contents with a checksum label" do
sum = Digest::SHA384.hexdigest("foobar")
@resource[:checksum] = :sha384
expect(@checksum.sum("foobar")).to eq("{sha384}#{sum}")
end
it "should use :sha256 as its default type" do
expect(@checksum.default).to eq(:sha256)
end
it "should use its current value when asked to sum a file's content" do
@checksum.value = :md5lite
expect(@checksum).to receive(:md5lite_file).with(@path).and_return("yay")
@checksum.sum_file(@path)
end
it "should use :sha256 to sum a file when no value is set" do
expect(@checksum).to receive(:sha256_file).with(@path).and_return("yay")
@checksum.sum_file(@path)
end
it "should convert all sums to strings when summing files" do
@checksum.value = :mtime
expect(@checksum).to receive(:mtime_file).with(@path).and_return(Time.now)
expect { @checksum.sum_file(@path) }.not_to raise_error
end
it "should return the summed contents of a file with a checksum label" do
@resource[:checksum] = :md5
expect(@checksum).to receive(:md5_file).and_return("mysum")
expect(@checksum.sum_file(@path)).to eq("{md5}mysum")
end
it "should return the summed contents of a stream with a checksum label" do
@resource[:checksum] = :md5
expect(@checksum).to receive(:md5_stream).and_return("mysum")
expect(@checksum.sum_stream).to eq("{md5}mysum")
end
it "should yield the sum_stream block to the underlying checksum" do
@resource[:checksum] = :md5
expect(@checksum).to receive(:md5_stream).and_yield("something").and_return("mysum")
@checksum.sum_stream do |sum|
expect(sum).to eq("something")
end
end
it 'should use values allowed by the supported_checksum_types setting' do
values = checksum.value_collection.values.reject {|v| v == :none}.map {|v| v.to_s}
Puppet.settings[:supported_checksum_types] = values
expect(Puppet.settings[:supported_checksum_types]).to eq(values)
end
it 'rejects md5 checksums in FIPS mode' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect {
@resource[:checksum] = :md5
}.to raise_error(Puppet::ResourceError,
/Parameter checksum failed.* MD5 is not supported in FIPS mode/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file/ctime_spec.rb | spec/unit/type/file/ctime_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).attrclass(:ctime) do
require 'puppet_spec/files'
include PuppetSpec::Files
before do
@filename = tmpfile('ctime')
@resource = Puppet::Type.type(:file).new({:name => @filename})
end
it "should be able to audit the file's ctime" do
File.open(@filename, "w"){ }
@resource[:audit] = [:ctime]
# this .to_resource audit behavior is magical :-(
expect(@resource.to_resource[:ctime]).to eq(Puppet::FileSystem.stat(@filename).ctime.to_s)
end
it "should return absent if auditing an absent file" do
@resource[:audit] = [:ctime]
expect(@resource.to_resource[:ctime]).to eq(:absent)
end
it "should prevent the user from trying to set the ctime" do
expect {
@resource[:ctime] = Time.now.to_s
}.to raise_error(Puppet::Error, /ctime is read-only/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/package/package_settings_spec.rb | spec/unit/type/package/package_settings_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package) do
before do
allow(Puppet::Util::Storage).to receive(:store)
end
it "should have a :package_settings feature that requires :package_settings_insync?, :package_settings and :package_settings=" do
expect(described_class.provider_feature(:package_settings).methods).to eq([:package_settings_insync?, :package_settings, :package_settings=])
end
context "when validating attributes" do
it "should have a package_settings property" do
expect(described_class.attrtype(:package_settings)).to eq(:property)
end
end
context "when validating attribute values" do
let(:provider) do
double('provider',
:class => described_class.defaultprovider,
:clear => nil,
:validate_source => false)
end
before do
allow(provider.class).to receive(:supports_parameter?).and_return(true)
allow(described_class.defaultprovider).to receive(:new).and_return(provider)
end
describe 'package_settings' do
context "with a minimalistic provider supporting package_settings" do
context "and {:package_settings => :settings}" do
let(:resource) do
described_class.new :name => 'foo', :package_settings => :settings
end
it { expect { resource }.to_not raise_error }
it "should set package_settings to :settings" do
expect(resource.value(:package_settings)).to be :settings
end
end
end
context "with a provider that supports validation of the package_settings" do
context "and {:package_settings => :valid_value}" do
before do
expect(provider).to receive(:package_settings_validate).once.with(:valid_value).and_return(true)
end
let(:resource) do
described_class.new :name => 'foo', :package_settings => :valid_value
end
it { expect { resource }.to_not raise_error }
it "should set package_settings to :valid_value" do
expect(resource.value(:package_settings)).to eq(:valid_value)
end
end
context "and {:package_settings => :invalid_value}" do
before do
msg = "package_settings must be a Hash, not Symbol"
expect(provider).to receive(:package_settings_validate).once.
with(:invalid_value).and_raise(ArgumentError, msg)
end
let(:resource) do
described_class.new :name => 'foo', :package_settings => :invalid_value
end
it do
expect { resource }.to raise_error Puppet::Error,
/package_settings must be a Hash, not Symbol/
end
end
end
context "with a provider that supports munging of the package_settings" do
context "and {:package_settings => 'A'}" do
before do
expect(provider).to receive(:package_settings_munge).once.with('A').and_return(:a)
end
let(:resource) do
described_class.new :name => 'foo', :package_settings => 'A'
end
it do
expect { resource }.to_not raise_error
end
it "should set package_settings to :a" do
expect(resource.value(:package_settings)).to be :a
end
end
end
end
end
describe "package_settings property" do
let(:provider) do
double('provider',
:class => described_class.defaultprovider,
:clear => nil,
:validate_source => false)
end
before do
allow(provider.class).to receive(:supports_parameter?).and_return(true)
allow(described_class.defaultprovider).to receive(:new).and_return(provider)
end
context "with {package_settings => :should}" do
let(:resource) do
described_class.new :name => 'foo', :package_settings => :should
end
describe "#insync?(:is)" do
it "returns the result of provider.package_settings_insync?(:should,:is)" do
expect(resource.provider).to receive(:package_settings_insync?).once.with(:should,:is).and_return(:ok1)
expect(resource.property(:package_settings).insync?(:is)).to be :ok1
end
end
describe "#should_to_s(:newvalue)" do
it "returns the result of provider.package_settings_should_to_s(:should,:newvalue)" do
expect(resource.provider).to receive(:package_settings_should_to_s).once.with(:should,:newvalue).and_return(:ok2)
expect(resource.property(:package_settings).should_to_s(:newvalue)).to be :ok2
end
end
describe "#is_to_s(:currentvalue)" do
it "returns the result of provider.package_settings_is_to_s(:should,:currentvalue)" do
expect(resource.provider).to receive(:package_settings_is_to_s).once.with(:should,:currentvalue).and_return(:ok3)
expect(resource.property(:package_settings).is_to_s(:currentvalue)).to be :ok3
end
end
end
context "with any non-nil package_settings" do
describe "#change_to_s(:currentvalue,:newvalue)" do
let(:resource) do
described_class.new :name => 'foo', :package_settings => {}
end
it "returns the result of provider.package_settings_change_to_s(:currentvalue,:newvalue)" do
expect(resource.provider).to receive(:package_settings_change_to_s).once.with(:currentvalue,:newvalue).and_return(:ok4)
expect(resource.property(:package_settings).change_to_s(:currentvalue,:newvalue)).to be :ok4
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/resource/status_spec.rb | spec/unit/resource/status_spec.rb | require 'spec_helper'
require 'puppet/resource/status'
describe Puppet::Resource::Status do
include PuppetSpec::Files
let(:resource) { Puppet::Type.type(:file).new(:path => make_absolute("/my/file")) }
let(:containment_path) { ["foo", "bar", "baz"] }
let(:status) { Puppet::Resource::Status.new(resource) }
before do
allow(resource).to receive(:pathbuilder).and_return(containment_path)
end
it "should compute type and title correctly" do
expect(status.resource_type).to eq("File")
expect(status.title).to eq(make_absolute("/my/file"))
end
[:file, :line, :evaluation_time].each do |attr|
it "should support #{attr}" do
status.send(attr.to_s + "=", "foo")
expect(status.send(attr)).to eq("foo")
end
end
[:skipped, :failed, :restarted, :failed_to_restart, :changed, :out_of_sync, :scheduled].each do |attr|
it "should support #{attr}" do
status.send(attr.to_s + "=", "foo")
expect(status.send(attr)).to eq("foo")
end
it "should have a boolean method for determining whether it was #{attr}" do
status.send(attr.to_s + "=", "foo")
expect(status).to send("be_#{attr}")
end
end
it "should accept a resource at initialization" do
expect(Puppet::Resource::Status.new(resource).resource).not_to be_nil
end
it "should set its source description to the resource's path" do
expect(resource).to receive(:path).and_return("/my/path")
expect(Puppet::Resource::Status.new(resource).source_description).to eq("/my/path")
end
it "should set its containment path" do
expect(Puppet::Resource::Status.new(resource).containment_path).to eq(containment_path)
end
[:file, :line].each do |attr|
it "should copy the resource's #{attr}" do
expect(resource).to receive(attr).and_return("foo")
expect(Puppet::Resource::Status.new(resource).send(attr)).to eq("foo")
end
end
it "should copy the resource's tags" do
resource.tag('foo', 'bar')
status = Puppet::Resource::Status.new(resource)
expect(status).to be_tagged("foo")
expect(status).to be_tagged("bar")
end
it "should always convert the resource to a string" do
expect(resource).to receive(:to_s).and_return("foo")
expect(Puppet::Resource::Status.new(resource).resource).to eq("foo")
end
it 'should set the provider_used correctly' do
expected_name = if Puppet::Util::Platform.windows?
'windows'
else
'posix'
end
expect(status.provider_used).to eq(expected_name)
end
it "should support tags" do
expect(Puppet::Resource::Status.ancestors).to include(Puppet::Util::Tagging)
end
it "should create a timestamp at its creation time" do
expect(status.time).to be_instance_of(Time)
end
it "should support adding events" do
event = Puppet::Transaction::Event.new(:name => :foobar)
status.add_event(event)
expect(status.events).to eq([event])
end
it "should use '<<' to add events" do
event = Puppet::Transaction::Event.new(:name => :foobar)
expect(status << event).to equal(status)
expect(status.events).to eq([event])
end
it "fails and records a failure event with a given message" do
status.fail_with_event("foo fail")
event = status.events[0]
expect(event.message).to eq("foo fail")
expect(event.status).to eq("failure")
expect(event.name).to eq(:resource_error)
expect(status.failed?).to be_truthy
end
it "fails and records a failure event with a given exception" do
error = StandardError.new("the message")
expect(resource).to receive(:log_exception).with(error, "Could not evaluate: the message")
expect(status).to receive(:fail_with_event).with("the message")
status.failed_because(error)
end
it "should count the number of successful events and set changed" do
3.times{ status << Puppet::Transaction::Event.new(:status => 'success') }
expect(status.change_count).to eq(3)
expect(status.changed).to eq(true)
expect(status.out_of_sync).to eq(true)
end
it "should not start with any changes" do
expect(status.change_count).to eq(0)
expect(status.changed).to eq(false)
expect(status.out_of_sync).to eq(false)
end
it "should not treat failure, audit, or noop events as changed" do
['failure', 'audit', 'noop'].each do |s| status << Puppet::Transaction::Event.new(:status => s) end
expect(status.change_count).to eq(0)
expect(status.changed).to eq(false)
end
it "should not treat audit events as out of sync" do
status << Puppet::Transaction::Event.new(:status => 'audit')
expect(status.out_of_sync_count).to eq(0)
expect(status.out_of_sync).to eq(false)
end
['failure', 'noop', 'success'].each do |event_status|
it "should treat #{event_status} events as out of sync" do
3.times do status << Puppet::Transaction::Event.new(:status => event_status) end
expect(status.out_of_sync_count).to eq(3)
expect(status.out_of_sync).to eq(true)
end
end
context 'when serializing' do
let(:status) do
s = Puppet::Resource::Status.new(resource)
s.file = '/foo.rb'
s.line = 27
s.evaluation_time = 2.7
s.tags = %w{one two}
s << Puppet::Transaction::Event.new(:name => :mode_changed, :status => 'audit')
s.failed = false
s.changed = true
s.out_of_sync = true
s.skipped = false
s.provider_used = 'provider_used_class_name'
s.failed_to_restart = false
s
end
it 'should round trip through json' do
expect(status.containment_path).to eq(containment_path)
tripped = Puppet::Resource::Status.from_data_hash(JSON.parse(status.to_json))
expect(tripped.title).to eq(status.title)
expect(tripped.containment_path).to eq(status.containment_path)
expect(tripped.file).to eq(status.file)
expect(tripped.line).to eq(status.line)
expect(tripped.resource).to eq(status.resource)
expect(tripped.resource_type).to eq(status.resource_type)
expect(tripped.provider_used).to eq(status.provider_used)
expect(tripped.evaluation_time).to eq(status.evaluation_time)
expect(tripped.tags).to eq(status.tags)
expect(tripped.time).to eq(status.time)
expect(tripped.failed).to eq(status.failed)
expect(tripped.changed).to eq(status.changed)
expect(tripped.out_of_sync).to eq(status.out_of_sync)
expect(tripped.skipped).to eq(status.skipped)
expect(tripped.failed_to_restart).to eq(status.failed_to_restart)
expect(tripped.change_count).to eq(status.change_count)
expect(tripped.out_of_sync_count).to eq(status.out_of_sync_count)
expect(events_as_hashes(tripped)).to eq(events_as_hashes(status))
end
it 'to_data_hash returns value that is instance of to Data' do
expect(Puppet::Pops::Types::TypeFactory.data.instance?(status.to_data_hash)).to be_truthy
end
def events_as_hashes(report)
report.events.collect do |e|
{
:audited => e.audited,
:property => e.property,
:previous_value => e.previous_value,
:desired_value => e.desired_value,
:historical_value => e.historical_value,
:message => e.message,
:name => e.name,
:status => e.status,
:time => e.time,
}
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/resource/type_spec.rb | spec/unit/resource/type_spec.rb | require 'spec_helper'
require 'puppet/resource/type'
require 'puppet/pops'
require 'matchers/json'
describe Puppet::Resource::Type do
include JSONMatchers
it "should have a 'name' attribute" do
expect(Puppet::Resource::Type.new(:hostclass, "foo").name).to eq("foo")
end
[:code, :doc, :line, :file, :resource_type_collection].each do |attr|
it "should have a '#{attr}' attribute" do
type = Puppet::Resource::Type.new(:hostclass, "foo")
type.send(attr.to_s + "=", "yay")
expect(type.send(attr)).to eq("yay")
end
end
[:hostclass, :node, :definition].each do |type|
it "should know when it is a #{type}" do
expect(Puppet::Resource::Type.new(type, "foo").send("#{type}?")).to be_truthy
end
end
describe "when a node" do
it "should allow a regex as its name" do
expect { Puppet::Resource::Type.new(:node, /foo/) }.not_to raise_error
end
it "should allow an AST::HostName instance as its name" do
regex = Puppet::Parser::AST::Regex.new(:value => /foo/)
name = Puppet::Parser::AST::HostName.new(:value => regex)
expect { Puppet::Resource::Type.new(:node, name) }.not_to raise_error
end
it "should match against the regexp in the AST::HostName when a HostName instance is provided" do
regex = Puppet::Parser::AST::Regex.new(:value => /\w/)
name = Puppet::Parser::AST::HostName.new(:value => regex)
node = Puppet::Resource::Type.new(:node, name)
expect(node.match("foo")).to be_truthy
end
it "should return the value of the hostname if provided a string-form AST::HostName instance as the name" do
name = Puppet::Parser::AST::HostName.new(:value => "foo")
node = Puppet::Resource::Type.new(:node, name)
expect(node.name).to eq("foo")
end
describe "and the name is a regex" do
it "should have a method that indicates that this is the case" do
expect(Puppet::Resource::Type.new(:node, /w/)).to be_name_is_regex
end
it "should set its namespace to ''" do
expect(Puppet::Resource::Type.new(:node, /w/).namespace).to eq("")
end
it "should return the regex converted to a string when asked for its name" do
expect(Puppet::Resource::Type.new(:node, /ww/).name).to eq("__node_regexp__ww")
end
it "should downcase the regex when returning the name as a string" do
expect(Puppet::Resource::Type.new(:node, /W/).name).to eq("__node_regexp__w")
end
it "should remove non-alpha characters when returning the name as a string" do
expect(Puppet::Resource::Type.new(:node, /w*w/).name).not_to include("*")
end
it "should remove leading dots when returning the name as a string" do
expect(Puppet::Resource::Type.new(:node, /.ww/).name).not_to match(/^\./)
end
it "should have a method for matching its regex name against a provided name" do
expect(Puppet::Resource::Type.new(:node, /.ww/)).to respond_to(:match)
end
it "should return true when its regex matches the provided name" do
expect(Puppet::Resource::Type.new(:node, /\w/).match("foo")).to be_truthy
end
it "should return true when its regex matches the provided name" do
expect(Puppet::Resource::Type.new(:node, /\w/).match("foo")).to be_truthy
end
it "should return false when its regex does not match the provided name" do
expect(!!Puppet::Resource::Type.new(:node, /\d/).match("foo")).to be_falsey
end
it "should return true when its name, as a string, is matched against an equal string" do
expect(Puppet::Resource::Type.new(:node, "foo").match("foo")).to be_truthy
end
it "should return false when its name is matched against an unequal string" do
expect(Puppet::Resource::Type.new(:node, "foo").match("bar")).to be_falsey
end
it "should match names insensitive to case" do
expect(Puppet::Resource::Type.new(:node, "fOo").match("foO")).to be_truthy
end
end
end
describe "when initializing" do
it "should require a resource super type" do
expect(Puppet::Resource::Type.new(:hostclass, "foo").type).to eq(:hostclass)
end
it "should fail if provided an invalid resource super type" do
expect { Puppet::Resource::Type.new(:nope, "foo") }.to raise_error(ArgumentError)
end
it "should set its name to the downcased, stringified provided name" do
expect(Puppet::Resource::Type.new(:hostclass, "Foo::Bar".intern).name).to eq("foo::bar")
end
it "should set its namespace to the downcased, stringified qualified name for classes" do
expect(Puppet::Resource::Type.new(:hostclass, "Foo::Bar::Baz".intern).namespace).to eq("foo::bar::baz")
end
[:definition, :node].each do |type|
it "should set its namespace to the downcased, stringified qualified portion of the name for #{type}s" do
expect(Puppet::Resource::Type.new(type, "Foo::Bar::Baz".intern).namespace).to eq("foo::bar")
end
end
%w{code line file doc}.each do |arg|
it "should set #{arg} if provided" do
type = Puppet::Resource::Type.new(:hostclass, "foo", arg.to_sym => "something")
expect(type.send(arg)).to eq("something")
end
end
it "should set any provided arguments with the keys as symbols" do
type = Puppet::Resource::Type.new(:hostclass, "foo", :arguments => {:foo => "bar", :baz => "biz"})
expect(type).to be_valid_parameter("foo")
expect(type).to be_valid_parameter("baz")
end
it "should set any provided arguments with they keys as strings" do
type = Puppet::Resource::Type.new(:hostclass, "foo", :arguments => {"foo" => "bar", "baz" => "biz"})
expect(type).to be_valid_parameter(:foo)
expect(type).to be_valid_parameter(:baz)
end
it "should function if provided no arguments" do
type = Puppet::Resource::Type.new(:hostclass, "foo")
expect(type).not_to be_valid_parameter(:foo)
end
end
describe "when testing the validity of an attribute" do
it "should return true if the parameter was typed at initialization" do
expect(Puppet::Resource::Type.new(:hostclass, "foo", :arguments => {"foo" => "bar"})).to be_valid_parameter("foo")
end
it "should return true if it is a metaparam" do
expect(Puppet::Resource::Type.new(:hostclass, "foo")).to be_valid_parameter("require")
end
it "should return true if the parameter is named 'name'" do
expect(Puppet::Resource::Type.new(:hostclass, "foo")).to be_valid_parameter("name")
end
it "should return false if it is not a metaparam and was not provided at initialization" do
expect(Puppet::Resource::Type.new(:hostclass, "foo")).not_to be_valid_parameter("yayness")
end
end
describe "when setting its parameters in the scope" do
let(:parser) { Puppet::Pops::Parser::Parser.new() }
def wrap3x(expression)
Puppet::Parser::AST::PopsBridge::Expression.new(:value => expression.model)
end
def parse_expression(expr_string)
wrap3x(parser.parse_string(expr_string))
end
def number_expression(number)
wrap3x(Puppet::Pops::Model::Factory.NUMBER(number))
end
def variable_expression(name)
wrap3x(Puppet::Pops::Model::Factory.QNAME(name).var())
end
def matchref_expression(number)
wrap3x(Puppet::Pops::Model::Factory.NUMBER(number).var())
end
before(:each) do
compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
@scope = Puppet::Parser::Scope.new(compiler, :source => double("source"))
@resource = Puppet::Parser::Resource.new(:foo, "bar", :scope => @scope)
@type = Puppet::Resource::Type.new(:definition, "foo")
@resource.environment.known_resource_types.add @type
Puppet.push_context(:loaders => compiler.loaders)
end
after(:each) do
Puppet.pop_context
end
['module_name', 'name', 'title'].each do |variable|
it "should allow #{variable} to be evaluated as param default" do
@type.instance_eval { @module_name = "bar" }
@type.set_arguments :foo => variable_expression(variable)
@type.set_resource_parameters(@resource, @scope)
expect(@scope['foo']).to eq('bar')
end
end
# this test is to clarify a crazy edge case
# if you specify these special names as params, the resource
# will override the special variables
it "should allow the resource to override defaults" do
@type.set_arguments :name => nil
@resource[:name] = 'foobar'
@type.set_arguments :foo => variable_expression('name')
@type.set_resource_parameters(@resource, @scope)
expect(@scope['foo']).to eq('foobar')
end
context 'referencing a variable to the left of the default expression' do
it 'is possible when the referenced variable uses a default' do
@type.set_arguments({
:first => number_expression(10),
:second => variable_expression('first'),
})
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq(10)
expect(@scope['second']).to eq(10)
end
it 'is possible when the referenced variable is given a value' do
@type.set_arguments({
:first => number_expression(10),
:second => variable_expression('first'),
})
@resource[:first] = 2
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq(2)
expect(@scope['second']).to eq(2)
end
it 'is possible when the referenced variable is an array produced by match function' do
@type.set_arguments({
:first => parse_expression("'hello'.match(/(h)(.*)/)"),
:second => parse_expression('$first[0]'),
:third => parse_expression('$first[1]')
})
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq(['hello', 'h', 'ello'])
expect(@scope['second']).to eq('hello')
expect(@scope['third']).to eq('h')
end
it 'fails when the referenced variable is unassigned' do
@type.set_arguments({
:first => nil,
:second => variable_expression('first'),
})
expect { @type.set_resource_parameters(@resource, @scope) }.to raise_error(
Puppet::Error, 'Foo[bar]: expects a value for parameter $first')
end
it 'does not clobber a given value' do
@type.set_arguments({
:first => number_expression(10),
:second => variable_expression('first'),
})
@resource[:first] = 2
@resource[:second] = 5
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq(2)
expect(@scope['second']).to eq(5)
end
end
context 'referencing a variable to the right of the default expression' do
before :each do
@type.set_arguments({
:first => number_expression(10),
:second => variable_expression('third'),
:third => number_expression(20)
})
end
it 'no error is raised when no defaults are evaluated' do
@resource[:first] = 1
@resource[:second] = 2
@resource[:third] = 3
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq(1)
expect(@scope['second']).to eq(2)
expect(@scope['third']).to eq(3)
end
it 'no error is raised unless the referencing default expression is evaluated' do
@resource[:second] = 2
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq(10)
expect(@scope['second']).to eq(2)
expect(@scope['third']).to eq(20)
end
it 'fails when the default expression is evaluated' do
@resource[:first] = 1
expect { @type.set_resource_parameters(@resource, @scope) }.to raise_error(Puppet::Error, 'Foo[bar]: default expression for $second tries to illegally access not yet evaluated $third')
end
end
it 'does not allow a variable to be referenced from its own default expression' do
@type.set_arguments({
:first => variable_expression('first')
})
expect { @type.set_resource_parameters(@resource, @scope) }.to raise_error(Puppet::Error, 'Foo[bar]: default expression for $first tries to illegally access not yet evaluated $first')
end
context 'when using match scope' do
it '$n evaluates to undef at the top level' do
@type.set_arguments({
:first => matchref_expression('0'),
:second => matchref_expression('1'),
})
@type.set_resource_parameters(@resource, @scope)
expect(@scope).not_to include('first')
expect(@scope).not_to include('second')
end
it 'a match scope to the left of a parameter is not visible to it' do
@type.set_arguments({
:first => parse_expression("['hello' =~ /(h)(.*)/, $1, $2]"),
:second => matchref_expression('1'),
})
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq([true, 'h', 'ello'])
expect(@scope['second']).to be_nil
end
it 'match scopes nests per parameter' do
@type.set_arguments({
:first => parse_expression("['hi' =~ /(h)(.*)/, $1, if 'foo' =~ /f(oo)/ { $1 }, $1, $2]"),
:second => matchref_expression('0'),
})
@type.set_resource_parameters(@resource, @scope)
expect(@scope['first']).to eq([true, 'h', 'oo', 'h', 'i'])
expect(@scope['second']).to be_nil
end
end
it "should set each of the resource's parameters as variables in the scope" do
@type.set_arguments :foo => nil, :boo => nil
@resource[:foo] = "bar"
@resource[:boo] = "baz"
@type.set_resource_parameters(@resource, @scope)
expect(@scope['foo']).to eq("bar")
expect(@scope['boo']).to eq("baz")
end
it "should set the variables as strings" do
@type.set_arguments :foo => nil
@resource[:foo] = "bar"
@type.set_resource_parameters(@resource, @scope)
expect(@scope['foo']).to eq("bar")
end
it "should fail if any of the resource's parameters are not valid attributes" do
@type.set_arguments :foo => nil
@resource[:boo] = "baz"
expect { @type.set_resource_parameters(@resource, @scope) }.to raise_error(Puppet::ParseError)
end
it "should evaluate and set its default values as variables for parameters not provided by the resource" do
@type.set_arguments :foo => Puppet::Parser::AST::Leaf.new(:value => "something")
@type.set_resource_parameters(@resource, @scope)
expect(@scope['foo']).to eq("something")
end
it "should set all default values as parameters in the resource" do
@type.set_arguments :foo => Puppet::Parser::AST::Leaf.new(:value => "something")
@type.set_resource_parameters(@resource, @scope)
expect(@resource[:foo]).to eq("something")
end
it "should fail if the resource does not provide a value for a required argument" do
@type.set_arguments :foo => nil
expect { @type.set_resource_parameters(@resource, @scope) }.to raise_error(Puppet::ParseError)
end
it "should set the resource's title as a variable if not otherwise provided" do
@type.set_resource_parameters(@resource, @scope)
expect(@scope['title']).to eq("bar")
end
it "should set the resource's name as a variable if not otherwise provided" do
@type.set_resource_parameters(@resource, @scope)
expect(@scope['name']).to eq("bar")
end
it "should set its module name in the scope if available" do
@type.instance_eval { @module_name = "mymod" }
@type.set_resource_parameters(@resource, @scope)
expect(@scope["module_name"]).to eq("mymod")
end
it "should set its caller module name in the scope if available" do
expect(@scope).to receive(:parent_module_name).and_return("mycaller")
@type.set_resource_parameters(@resource, @scope)
expect(@scope["caller_module_name"]).to eq("mycaller")
end
end
describe "when describing and managing parent classes" do
before do
environment = Puppet::Node::Environment.create(:testing, [])
@krt = environment.known_resource_types
@parent = Puppet::Resource::Type.new(:hostclass, "bar")
@krt.add @parent
@child = Puppet::Resource::Type.new(:hostclass, "foo", :parent => "bar")
@krt.add @child
@scope = Puppet::Parser::Scope.new(Puppet::Parser::Compiler.new(Puppet::Node.new("foo", :environment => environment)))
end
it "should be able to define a parent" do
Puppet::Resource::Type.new(:hostclass, "foo", :parent => "bar")
end
it "should use the code collection to find the parent resource type" do
expect(@child.parent_type(@scope)).to equal(@parent)
end
it "should be able to find parent nodes" do
parent = Puppet::Resource::Type.new(:node, "node_bar")
@krt.add parent
child = Puppet::Resource::Type.new(:node, "node_foo", :parent => "node_bar")
@krt.add child
expect(child.parent_type(@scope)).to equal(parent)
end
it "should cache a reference to the parent type" do
allow(@krt).to receive(:hostclass).with("foo::bar").and_return(nil)
expect(@krt).to receive(:hostclass).with("bar").once.and_return(@parent)
@child.parent_type(@scope)
@child.parent_type
end
it "should correctly state when it is another type's child" do
@child.parent_type(@scope)
expect(@child).to be_child_of(@parent)
end
it "should be considered the child of a parent's parent" do
@grandchild = Puppet::Resource::Type.new(:hostclass, "baz", :parent => "foo")
@krt.add @grandchild
@child.parent_type(@scope)
@grandchild.parent_type(@scope)
expect(@grandchild).to be_child_of(@parent)
end
it "should correctly state when it is not another type's child" do
@notchild = Puppet::Resource::Type.new(:hostclass, "baz")
@krt.add @notchild
expect(@notchild).not_to be_child_of(@parent)
end
end
describe "when evaluating its code" do
before do
@compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("mynode"))
@scope = Puppet::Parser::Scope.new @compiler
@resource = Puppet::Parser::Resource.new(:class, "foo", :scope => @scope)
# This is so the internal resource lookup works, yo.
@compiler.catalog.add_resource @resource
@type = Puppet::Resource::Type.new(:hostclass, "foo")
@resource.environment.known_resource_types.add @type
end
it "should add node regex captures to its scope" do
@type = Puppet::Resource::Type.new(:node, /f(\w)o(.*)$/)
match = @type.match('foo')
code = double('code')
allow(@type).to receive(:code).and_return(code)
subscope = double('subscope', :compiler => @compiler)
expect(@scope).to receive(:newscope).with({:source => @type, :resource => @resource}).and_return(subscope)
expect(subscope).to receive(:with_guarded_scope).and_yield
expect(subscope).to receive(:ephemeral_from).with(match, nil, nil).and_return(subscope)
expect(code).to receive(:safeevaluate).with(subscope)
# Just to keep the stub quiet about intermediate calls
expect(@type).to receive(:set_resource_parameters).with(@resource, subscope)
@type.evaluate_code(@resource)
end
it "should add hostclass names to the classes list" do
@type.evaluate_code(@resource)
expect(@compiler.catalog.classes).to be_include("foo")
end
it "should not add defined resource names to the classes list" do
@type = Puppet::Resource::Type.new(:definition, "foo")
@type.evaluate_code(@resource)
expect(@compiler.catalog.classes).not_to be_include("foo")
end
it "should set all of its parameters in a subscope" do
subscope = double('subscope', :compiler => @compiler)
expect(@scope).to receive(:newscope).with({:source => @type, :resource => @resource}).and_return(subscope)
expect(@type).to receive(:set_resource_parameters).with(@resource, subscope)
@type.evaluate_code(@resource)
end
it "should not create a subscope for the :main class" do
allow(@resource).to receive(:title).and_return(:main)
expect(@scope).not_to receive(:newscope)
expect(@type).to receive(:set_resource_parameters).with(@resource, @scope)
@type.evaluate_code(@resource)
end
it "should store the class scope" do
@type.evaluate_code(@resource)
expect(@scope.class_scope(@type)).to be_instance_of(@scope.class)
end
it "should still create a scope but not store it if the type is a definition" do
@type = Puppet::Resource::Type.new(:definition, "foo")
@type.evaluate_code(@resource)
expect(@scope.class_scope(@type)).to be_nil
end
it "should evaluate the AST code if any is provided" do
code = double('code')
allow(@type).to receive(:code).and_return(code)
expect(code).to receive(:safeevaluate).with(kind_of(Puppet::Parser::Scope))
@type.evaluate_code(@resource)
end
it "should noop if there is no code" do
expect(@type).to receive(:code).and_return(nil)
@type.evaluate_code(@resource)
end
describe "and it has a parent class" do
before do
@parent_type = Puppet::Resource::Type.new(:hostclass, "parent")
@type.parent = "parent"
@parent_resource = Puppet::Parser::Resource.new(:class, "parent", :scope => @scope)
@compiler.add_resource @scope, @parent_resource
@type.resource_type_collection = @scope.environment.known_resource_types
@type.resource_type_collection.add @parent_type
end
it "should evaluate the parent's resource" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
expect(@scope.class_scope(@parent_type)).not_to be_nil
end
it "should not evaluate the parent's resource if it has already been evaluated" do
@parent_resource.evaluate
@type.parent_type(@scope)
expect(@parent_resource).not_to receive(:evaluate)
@type.evaluate_code(@resource)
end
it "should use the parent's scope as its base scope" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
expect(@scope.class_scope(@type).parent.object_id).to eq(@scope.class_scope(@parent_type).object_id)
end
end
describe "and it has a parent node" do
before do
@type = Puppet::Resource::Type.new(:node, "foo")
@parent_type = Puppet::Resource::Type.new(:node, "parent")
@type.parent = "parent"
@parent_resource = Puppet::Parser::Resource.new(:node, "parent", :scope => @scope)
@compiler.add_resource @scope, @parent_resource
@type.resource_type_collection = @scope.environment.known_resource_types
@type.resource_type_collection.add(@parent_type)
end
it "should evaluate the parent's resource" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
expect(@scope.class_scope(@parent_type)).not_to be_nil
end
it "should not evaluate the parent's resource if it has already been evaluated" do
@parent_resource.evaluate
@type.parent_type(@scope)
expect(@parent_resource).not_to receive(:evaluate)
@type.evaluate_code(@resource)
end
it "should use the parent's scope as its base scope" do
@type.parent_type(@scope)
@type.evaluate_code(@resource)
expect(@scope.class_scope(@type).parent.object_id).to eq(@scope.class_scope(@parent_type).object_id)
end
end
end
describe "when creating a resource" do
before do
env = Puppet::Node::Environment.create('env', [])
@node = Puppet::Node.new("foo", :environment => env)
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = Puppet::Parser::Scope.new(@compiler)
@top = Puppet::Resource::Type.new :hostclass, "top"
@middle = Puppet::Resource::Type.new :hostclass, "middle", :parent => "top"
@code = env.known_resource_types
@code.add @top
@code.add @middle
end
it "should create a resource instance" do
expect(@top.ensure_in_catalog(@scope)).to be_instance_of(Puppet::Parser::Resource)
end
it "should set its resource type to 'class' when it is a hostclass" do
expect(Puppet::Resource::Type.new(:hostclass, "top").ensure_in_catalog(@scope).type).to eq("Class")
end
it "should set its resource type to 'node' when it is a node" do
expect(Puppet::Resource::Type.new(:node, "top").ensure_in_catalog(@scope).type).to eq("Node")
end
it "should fail when it is a definition" do
expect { Puppet::Resource::Type.new(:definition, "top").ensure_in_catalog(@scope) }.to raise_error(ArgumentError)
end
it "should add the created resource to the scope's catalog" do
@top.ensure_in_catalog(@scope)
expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should add specified parameters to the resource" do
@top.ensure_in_catalog(@scope, {'one'=>'1', 'two'=>'2'})
expect(@compiler.catalog.resource(:class, "top")['one']).to eq('1')
expect(@compiler.catalog.resource(:class, "top")['two']).to eq('2')
end
it "should not require params for a param class" do
@top.ensure_in_catalog(@scope, {})
expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should evaluate the parent class if one exists" do
@middle.ensure_in_catalog(@scope)
expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should evaluate the parent class if one exists" do
@middle.ensure_in_catalog(@scope, {})
expect(@compiler.catalog.resource(:class, "top")).to be_instance_of(Puppet::Parser::Resource)
end
it "should fail if you try to create duplicate class resources" do
othertop = Puppet::Parser::Resource.new(:class, 'top',:source => @source, :scope => @scope )
# add the same class resource to the catalog
@compiler.catalog.add_resource(othertop)
expect { @top.ensure_in_catalog(@scope, {}) }.to raise_error(Puppet::Resource::Catalog::DuplicateResourceError)
end
it "should fail to evaluate if a parent class is defined but cannot be found" do
othertop = Puppet::Resource::Type.new :hostclass, "something", :parent => "yay"
@code.add othertop
expect { othertop.ensure_in_catalog(@scope) }.to raise_error(Puppet::ParseError)
end
it "should not create a new resource if one already exists" do
expect(@compiler.catalog).to receive(:resource).with(:class, "top").and_return("something")
expect(@compiler.catalog).not_to receive(:add_resource)
@top.ensure_in_catalog(@scope)
end
it "should return the existing resource when not creating a new one" do
expect(@compiler.catalog).to receive(:resource).with(:class, "top").and_return("something")
expect(@compiler.catalog).not_to receive(:add_resource)
expect(@top.ensure_in_catalog(@scope)).to eq("something")
end
it "should not create a new parent resource if one already exists and it has a parent class" do
@top.ensure_in_catalog(@scope)
top_resource = @compiler.catalog.resource(:class, "top")
@middle.ensure_in_catalog(@scope)
expect(@compiler.catalog.resource(:class, "top")).to equal(top_resource)
end
# #795 - tag before evaluation.
it "should tag the catalog with the resource tags when it is evaluated" do
@middle.ensure_in_catalog(@scope)
expect(@compiler.catalog).to be_tagged("middle")
end
it "should tag the catalog with the parent class tags when it is evaluated" do
@middle.ensure_in_catalog(@scope)
expect(@compiler.catalog).to be_tagged("top")
end
end
describe "when merging code from another instance" do
def code(str)
Puppet::Pops::Model::Factory.literal(str)
end
it "should fail unless it is a class" do
expect { Puppet::Resource::Type.new(:node, "bar").merge("foo") }.to raise_error(Puppet::Error)
end
it "should fail unless the source instance is a class" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
source = Puppet::Resource::Type.new(:node, "foo")
expect { dest.merge(source) }.to raise_error(Puppet::Error)
end
it "should fail if both classes have different parent classes" do
code = Puppet::Resource::TypeCollection.new("env")
{"a" => "b", "c" => "d"}.each do |parent, child|
code.add Puppet::Resource::Type.new(:hostclass, parent)
code.add Puppet::Resource::Type.new(:hostclass, child, :parent => parent)
end
expect { code.hostclass("b").merge(code.hostclass("d")) }.to raise_error(Puppet::Error)
end
context 'when "freeze_main" is enabled and a merge is done into the main class' do
it "an error is raised if there is something other than definitions in the merged class" do
Puppet.settings[:freeze_main] = true
code = Puppet::Resource::TypeCollection.new("env")
code.add Puppet::Resource::Type.new(:hostclass, "")
other = Puppet::Resource::Type.new(:hostclass, "")
mock = double()
expect(mock).to receive(:is_definitions_only?).and_return(false)
expect(other).to receive(:code).and_return(mock)
expect { code.hostclass("").merge(other) }.to raise_error(Puppet::Error)
end
it "an error is not raised if the merged class contains nothing but definitions" do
Puppet.settings[:freeze_main] = true
code = Puppet::Resource::TypeCollection.new("env")
code.add Puppet::Resource::Type.new(:hostclass, "")
other = Puppet::Resource::Type.new(:hostclass, "")
mock = double()
expect(mock).to receive(:is_definitions_only?).and_return(true)
expect(other).to receive(:code).at_least(:once).and_return(mock)
expect { code.hostclass("").merge(other) }.not_to raise_error
end
end
it "should copy the other class's parent if it has not parent" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
Puppet::Resource::Type.new(:hostclass, "parent")
source = Puppet::Resource::Type.new(:hostclass, "foo", :parent => "parent")
dest.merge(source)
expect(dest.parent).to eq("parent")
end
it "should copy the other class's documentation as its docs if it has no docs" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
source = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "yayness")
dest.merge(source)
expect(dest.doc).to eq("yayness")
end
it "should append the other class's docs to its docs if it has any" do
dest = Puppet::Resource::Type.new(:hostclass, "bar", :doc => "fooness")
source = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "yayness")
dest.merge(source)
expect(dest.doc).to eq("foonessyayness")
end
it "should set the other class's code as its code if it has none" do
dest = Puppet::Resource::Type.new(:hostclass, "bar")
source = Puppet::Resource::Type.new(:hostclass, "foo", :code => code("bar").model)
dest.merge(source)
expect(dest.code.value).to eq("bar")
end
it "should append the other class's code to its code if it has any" do
# PUP-3274, the code merging at the top still uses AST::BlockExpression
# But does not do mutating changes to code blocks, instead a new block is created
# with references to the two original blocks.
# TODO: fix this when the code merging is changed at the very top in 4x.
#
dcode = Puppet::Parser::AST::BlockExpression.new(:children => [code("dest")])
dest = Puppet::Resource::Type.new(:hostclass, "bar", :code => dcode)
scode = Puppet::Parser::AST::BlockExpression.new(:children => [code("source")])
source = Puppet::Resource::Type.new(:hostclass, "foo", :code => scode)
dest.merge(source)
expect(dest.code.children.map { |c| c.value }).to eq(%w{dest source})
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/resource/type_collection_spec.rb | spec/unit/resource/type_collection_spec.rb | require 'spec_helper'
require 'puppet/resource/type_collection'
require 'puppet/resource/type'
describe Puppet::Resource::TypeCollection do
include PuppetSpec::Files
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
before do
@instance = Puppet::Resource::Type.new(:hostclass, "foo")
@code = Puppet::Resource::TypeCollection.new(environment)
end
it "should consider '<<' to be an alias to 'add' but should return self" do
expect(@code).to receive(:add).with("foo")
expect(@code).to receive(:add).with("bar")
@code << "foo" << "bar"
end
it "should set itself as the code collection for added resource types" do
node = Puppet::Resource::Type.new(:node, "foo")
@code.add(node)
expect(@code.node("foo")).to equal(node)
expect(node.resource_type_collection).to equal(@code)
end
it "should store node resource types as nodes" do
node = Puppet::Resource::Type.new(:node, "foo")
@code.add(node)
expect(@code.node("foo")).to equal(node)
end
it "should fail if a duplicate node is added" do
@code.add(Puppet::Resource::Type.new(:node, "foo"))
expect do
@code.add(Puppet::Resource::Type.new(:node, "foo"))
end.to raise_error(Puppet::ParseError, /cannot redefine/)
end
it "should fail if a hostclass duplicates a node" do
@code.add(Puppet::Resource::Type.new(:node, "foo"))
expect do
@code.add(Puppet::Resource::Type.new(:hostclass, "foo"))
end.to raise_error(Puppet::ParseError, /Node 'foo' is already defined; cannot be redefined as a class/)
end
it "should store hostclasses as hostclasses" do
klass = Puppet::Resource::Type.new(:hostclass, "foo")
@code.add(klass)
expect(@code.hostclass("foo")).to equal(klass)
end
it "errors if an attempt is made to merge hostclasses of the same name" do
klass1 = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "first")
klass2 = Puppet::Resource::Type.new(:hostclass, "foo", :doc => "second")
expect {
@code.add(klass1)
@code.add(klass2)
}.to raise_error(/.*is already defined; cannot redefine/)
end
it "should fail if a node duplicates a hostclass" do
@code.add(Puppet::Resource::Type.new(:hostclass, "foo"))
expect do
@code.add(Puppet::Resource::Type.new(:node, "foo"))
end.to raise_error(Puppet::ParseError, /Class 'foo' is already defined; cannot be redefined as a node/)
end
it "should store definitions as definitions" do
define = Puppet::Resource::Type.new(:definition, "foo")
@code.add(define)
expect(@code.definition("foo")).to equal(define)
end
it "should fail if a duplicate definition is added" do
@code.add(Puppet::Resource::Type.new(:definition, "foo"))
expect do
@code.add(Puppet::Resource::Type.new(:definition, "foo"))
end.to raise_error(Puppet::ParseError, /cannot be redefined/)
end
it "should remove all nodes, classes and definitions when cleared" do
loader = Puppet::Resource::TypeCollection.new(environment)
loader.add Puppet::Resource::Type.new(:hostclass, "class")
loader.add Puppet::Resource::Type.new(:definition, "define")
loader.add Puppet::Resource::Type.new(:node, "node")
loader.clear
expect(loader.hostclass("class")).to be_nil
expect(loader.definition("define")).to be_nil
expect(loader.node("node")).to be_nil
end
describe "when looking up names" do
before do
@type = Puppet::Resource::Type.new(:hostclass, "ns::klass")
end
it "should not attempt to import anything when the type is already defined" do
@code.add @type
expect(@code.loader).not_to receive(:import)
expect(@code.find_hostclass("ns::klass")).to equal(@type)
end
describe "that need to be loaded" do
it "should use the loader to load the files" do
expect(@code.loader).to receive(:try_load_fqname).with(:hostclass, "klass")
@code.find_hostclass("klass")
end
it "should use the loader to load the files" do
expect(@code.loader).to receive(:try_load_fqname).with(:hostclass, "ns::klass")
@code.find_hostclass("ns::klass")
end
it "should downcase the name and downcase and array-fy the namespaces before passing to the loader" do
expect(@code.loader).to receive(:try_load_fqname).with(:hostclass, "ns::klass")
@code.find_hostclass("ns::klass")
end
it "should use the class returned by the loader" do
expect(@code.loader).to receive(:try_load_fqname).and_return(:klass)
expect(@code).to receive(:hostclass).with("ns::klass").and_return(false)
expect(@code.find_hostclass("ns::klass")).to eq(:klass)
end
it "should return nil if the name isn't found" do
allow(@code.loader).to receive(:try_load_fqname).and_return(nil)
expect(@code.find_hostclass("Ns::Klass")).to be_nil
end
it "already-loaded names at broader scopes should not shadow autoloaded names" do
@code.add Puppet::Resource::Type.new(:hostclass, "bar")
expect(@code.loader).to receive(:try_load_fqname).with(:hostclass, "foo::bar").and_return(:foobar)
expect(@code.find_hostclass("foo::bar")).to eq(:foobar)
end
context 'when debugging' do
# This test requires that debugging is on, it will otherwise not make a call to debug,
# which is the easiest way to detect that that a certain path has been taken.
before(:each) do
Puppet.debug = true
end
after (:each) do
Puppet.debug = false
end
it "should not try to autoload names that we couldn't autoload in a previous step if ignoremissingtypes is enabled" do
Puppet[:ignoremissingtypes] = true
expect(@code.loader).to receive(:try_load_fqname).with(:hostclass, "ns::klass").and_return(nil)
expect(@code.find_hostclass("ns::klass")).to be_nil
expect(Puppet).to receive(:debug).at_least(:once).with(/Not attempting to load hostclass/)
expect(@code.find_hostclass("ns::klass")).to be_nil
end
end
end
end
KINDS = %w{hostclass node definition}
KINDS.each do |data|
describe "behavior of add for #{data}" do
it "should return the added #{data}" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(data, "foo")
expect(loader.add(instance)).to equal(instance)
end
it "should retrieve #{data} insensitive to case" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(data, "Bar")
loader.add instance
expect(loader.send(data, "bAr")).to equal(instance)
end
it "should return nil when asked for a #{data} that has not been added" do
expect(Puppet::Resource::TypeCollection.new(environment).send(data, "foo")).to be_nil
end
end
end
describe "when finding a qualified instance" do
it "should return any found instance if the instance name is fully qualified" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo::bar")
loader.add instance
expect(loader.find_hostclass("::foo::bar")).to equal(instance)
end
it "should return nil if the instance name is fully qualified and no such instance exists" do
loader = Puppet::Resource::TypeCollection.new(environment)
expect(loader.find_hostclass("::foo::bar")).to be_nil
end
it "should be able to find classes in the base namespace" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo")
loader.add instance
expect(loader.find_hostclass("foo")).to equal(instance)
end
it "should return the unqualified object if it exists in a provided namespace" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo::bar")
loader.add instance
expect(loader.find_hostclass("foo::bar")).to equal(instance)
end
it "should return nil if the object cannot be found" do
loader = Puppet::Resource::TypeCollection.new(environment)
instance = Puppet::Resource::Type.new(:hostclass, "foo::bar::baz")
loader.add instance
expect(loader.find_hostclass("foo::bar::eh")).to be_nil
end
describe "when topscope has a class that has the same name as a local class" do
before do
@loader = Puppet::Resource::TypeCollection.new(environment)
[ "foo::bar", "bar" ].each do |name|
@loader.add Puppet::Resource::Type.new(:hostclass, name)
end
end
it "looks up the given name, no more, no less" do
expect(@loader.find_hostclass("bar").name).to eq('bar')
expect(@loader.find_hostclass("::bar").name).to eq('bar')
expect(@loader.find_hostclass("foo::bar").name).to eq('foo::bar')
expect(@loader.find_hostclass("::foo::bar").name).to eq('foo::bar')
end
end
it "should not look in the local scope for classes when the name is qualified" do
@loader = Puppet::Resource::TypeCollection.new(environment)
@loader.add Puppet::Resource::Type.new(:hostclass, "foo::bar")
expect(@loader.find_hostclass("::bar")).to eq(nil)
end
end
it "should be able to find nodes" do
node = Puppet::Resource::Type.new(:node, "bar")
loader = Puppet::Resource::TypeCollection.new(environment)
loader.add(node)
expect(loader.find_node("bar")).to eq(node)
end
it "should indicate whether any nodes are defined" do
loader = Puppet::Resource::TypeCollection.new(environment)
loader.add_node(Puppet::Resource::Type.new(:node, "foo"))
expect(loader).to be_nodes
end
it "should indicate whether no nodes are defined" do
expect(Puppet::Resource::TypeCollection.new(environment)).not_to be_nodes
end
describe "when finding nodes" do
before :each do
@loader = Puppet::Resource::TypeCollection.new(environment)
end
it "should return any node whose name exactly matches the provided node name" do
node = Puppet::Resource::Type.new(:node, "foo")
@loader << node
expect(@loader.node("foo")).to equal(node)
end
it "should return the first regex node whose regex matches the provided node name" do
node1 = Puppet::Resource::Type.new(:node, /\w/)
node2 = Puppet::Resource::Type.new(:node, /\d/)
@loader << node1 << node2
expect(@loader.node("foo10")).to equal(node1)
end
it "should preferentially return a node whose name is string-equal over returning a node whose regex matches a provided name" do
node1 = Puppet::Resource::Type.new(:node, /\w/)
node2 = Puppet::Resource::Type.new(:node, "foo")
@loader << node1 << node2
expect(@loader.node("foo")).to equal(node2)
end
end
describe "when determining the configuration version" do
before do
@code = Puppet::Resource::TypeCollection.new(environment)
end
it "should default to the current time" do
time = Time.now
allow(Time).to receive(:now).and_return(time)
expect(@code.version).to eq(time.to_i)
end
context "when config_version script is specified" do
let(:environment) { Puppet::Node::Environment.create(:testing, [], '', '/my/foo') }
it "should use the output of the environment's config_version setting if one is provided" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/my/foo"])
.and_return(Puppet::Util::Execution::ProcessOutput.new("output\n", 0))
expect(@code.version).to be_instance_of(String)
expect(@code.version).to eq("output")
end
it "should raise a puppet parser error if executing config_version fails" do
expect(Puppet::Util::Execution).to receive(:execute).and_raise(Puppet::ExecutionFailure.new("msg"))
expect { @code.version }.to raise_error(Puppet::ParseError)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/resource/catalog_spec.rb | spec/unit/resource/catalog_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/json'
describe Puppet::Resource::Catalog, "when compiling" do
include JSONMatchers
include PuppetSpec::Files
before do
@basepath = make_absolute("/somepath")
# stub this to not try to create state.yaml
allow(Puppet::Util::Storage).to receive(:store)
end
it "should support json, dot, yaml" do
# msgpack and pson are optional, so using include instead of eq
expect(Puppet::Resource::Catalog.supported_formats).to include(:json, :dot, :yaml)
end
# audit only resources are unmanaged
# as are resources without properties with should values
it "should write its managed resources' types, namevars" do
catalog = Puppet::Resource::Catalog.new("host")
resourcefile = tmpfile('resourcefile')
Puppet[:resourcefile] = resourcefile
res = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/sam'), :ensure => 'present')
res.file = 'site.pp'
res.line = 21
res2 = Puppet::Type.type('exec').new(:title => 'bob', :command => "#{File.expand_path('/bin/rm')} -rf /")
res2.file = File.expand_path('/modules/bob/manifests/bob.pp')
res2.line = 42
res3 = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/susan'), :audit => 'all')
res3.file = 'site.pp'
res3.line = 63
res4 = Puppet::Type.type('file').new(:title => File.expand_path('/tmp/lilly'))
res4.file = 'site.pp'
res4.line = 84
comp_res = Puppet::Type.type('component').new(:title => 'Class[Main]')
catalog.add_resource(res, res2, res3, res4, comp_res)
catalog.write_resource_file
expect(File.readlines(resourcefile).map(&:chomp)).to match_array([
"file[#{res.title.downcase}]",
"exec[#{res2.title.downcase}]"
])
end
it "should log an error if unable to write to the resource file" do
catalog = Puppet::Resource::Catalog.new("host")
Puppet[:resourcefile] = File.expand_path('/not/writable/file')
catalog.add_resource(Puppet::Type.type('file').new(:title => File.expand_path('/tmp/foo')))
catalog.write_resource_file
expect(@logs.size).to eq(1)
expect(@logs.first.message).to match(/Could not create resource file/)
expect(@logs.first.level).to eq(:err)
end
it "should be able to write its list of classes to the class file" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.add_class "foo", "bar"
Puppet[:classfile] = File.expand_path("/class/file")
fh = double('filehandle')
classfile = Puppet.settings.setting(:classfile)
expect(Puppet::FileSystem).to receive(:open).with(classfile.value, classfile.mode.to_i(8), "w:UTF-8").and_yield(fh)
expect(fh).to receive(:puts).with("foo\nbar")
@catalog.write_class_file
end
it "should have a client_version attribute" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.client_version = 5
expect(@catalog.client_version).to eq(5)
end
it "should have a server_version attribute" do
@catalog = Puppet::Resource::Catalog.new("host")
@catalog.server_version = 5
expect(@catalog.server_version).to eq(5)
end
it "defaults code_id to nil" do
catalog = Puppet::Resource::Catalog.new("host")
expect(catalog.code_id).to be_nil
end
it "should include a catalog_uuid" do
allow(SecureRandom).to receive(:uuid).and_return("827a74c8-cf98-44da-9ff7-18c5e4bee41e")
catalog = Puppet::Resource::Catalog.new("host")
expect(catalog.catalog_uuid).to eq("827a74c8-cf98-44da-9ff7-18c5e4bee41e")
end
it "should include the current catalog_format" do
catalog = Puppet::Resource::Catalog.new("host")
expect(catalog.catalog_format).to eq(2)
end
describe "when compiling" do
it "should accept tags" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one")
expect(config).to be_tagged("one")
end
it "should accept multiple tags at once" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one", "two")
expect(config).to be_tagged("one")
expect(config).to be_tagged("two")
end
it "should convert all tags to strings" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one", :two)
expect(config).to be_tagged("one")
expect(config).to be_tagged("two")
end
it "should tag with both the qualified name and the split name" do
config = Puppet::Resource::Catalog.new("mynode")
config.tag("one::two")
expect(config).to be_tagged("one")
expect(config).to be_tagged("one::two")
end
it "should accept classes" do
config = Puppet::Resource::Catalog.new("mynode")
config.add_class("one")
expect(config.classes).to eq(%w{one})
config.add_class("two", "three")
expect(config.classes).to eq(%w{one two three})
end
it "should tag itself with passed class names" do
config = Puppet::Resource::Catalog.new("mynode")
config.add_class("one")
expect(config).to be_tagged("one")
end
it "handles resource titles with brackets" do
config = Puppet::Resource::Catalog.new("mynode")
expect(config.title_key_for_ref("Notify[[foo]bar]")).to eql(["Notify", "[foo]bar"])
end
end
describe "when converting to a RAL catalog" do
before do
@original = Puppet::Resource::Catalog.new("mynode")
@original.tag(*%w{one two three})
@original.add_class(*%w{four five six})
@top = Puppet::Resource.new :class, 'top'
@topobject = Puppet::Resource.new :file, @basepath+'/topobject'
@middle = Puppet::Resource.new :class, 'middle'
@middleobject = Puppet::Resource.new :file, @basepath+'/middleobject'
@bottom = Puppet::Resource.new :class, 'bottom'
@bottomobject = Puppet::Resource.new :file, @basepath+'/bottomobject'
@resources = [@top, @topobject, @middle, @middleobject, @bottom, @bottomobject]
@original.add_resource(*@resources)
@original.add_edge(@top, @topobject)
@original.add_edge(@top, @middle)
@original.add_edge(@middle, @middleobject)
@original.add_edge(@middle, @bottom)
@original.add_edge(@bottom, @bottomobject)
@original.catalog_format = 1
@catalog = @original.to_ral
end
it "should add all resources as RAL instances" do
@resources.each do |resource|
# Warning: a failure here will result in "global resource iteration is
# deprecated" being raised, because the rspec rendering to get the
# result tries to call `each` on the resource, and that raises.
expect(@catalog.resource(resource.ref)).to be_a_kind_of(Puppet::Type)
end
end
it "should raise if an unknown resource is being converted" do
@new_res = Puppet::Resource.new "Unknown", "type", :kind => 'compilable_type'
@resource_array = [@new_res]
@original.add_resource(*@resource_array)
@original.add_edge(@bottomobject, @new_res)
@original.catalog_format = 2
expect { @original.to_ral }.to raise_error(Puppet::Error, "Resource type 'Unknown' was not found")
end
it "should copy the tag list to the new catalog" do
expect(@catalog.tags.sort).to eq(@original.tags.sort)
end
it "should copy the class list to the new catalog" do
expect(@catalog.classes).to eq(@original.classes)
end
it "should duplicate the original edges" do
@original.edges.each do |edge|
expect(@catalog.edge?(@catalog.resource(edge.source.ref), @catalog.resource(edge.target.ref))).to be_truthy
end
end
it "should set itself as the catalog for each converted resource" do
@catalog.vertices.each { |v| expect(v.catalog.object_id).to eql(@catalog.object_id) }
end
# This tests #931.
it "should not lose track of resources whose names vary" do
changer = Puppet::Resource.new :file, @basepath+'/test/', :parameters => {:ensure => :directory}
config = Puppet::Resource::Catalog.new('test')
config.add_resource(changer)
config.add_resource(@top)
config.add_edge(@top, changer)
catalog = config.to_ral
expect(catalog.resource("File[#{@basepath}/test/]")).to equal(catalog.resource("File[#{@basepath}/test]"))
end
after do
# Remove all resource instances.
@catalog.clear(true)
end
end
describe "when filtering" do
before :each do
@original = Puppet::Resource::Catalog.new("mynode")
@original.tag(*%w{one two three})
@original.add_class(*%w{four five six})
@r1 = double(
'r1',
:ref => "File[/a]",
:[] => nil,
:virtual => nil,
:catalog= => nil,
)
allow(@r1).to receive(:respond_to?)
allow(@r1).to receive(:respond_to?).with(:ref).and_return(true)
allow(@r1).to receive(:copy_as_resource).and_return(@r1)
allow(@r1).to receive(:is_a?).with(Puppet::Resource).and_return(true)
@r2 = double(
'r2',
:ref => "File[/b]",
:[] => nil,
:virtual => nil,
:catalog= => nil,
)
allow(@r2).to receive(:respond_to?)
allow(@r2).to receive(:respond_to?).with(:ref).and_return(true)
allow(@r2).to receive(:copy_as_resource).and_return(@r2)
allow(@r2).to receive(:is_a?).with(Puppet::Resource).and_return(true)
@resources = [@r1,@r2]
@original.add_resource(@r1,@r2)
end
it "should transform the catalog to a resource catalog" do
expect(@original).to receive(:to_catalog).with(:to_resource)
@original.filter
end
it "should scan each catalog resource in turn and apply filtering block" do
@resources.each { |r| expect(r).to receive(:test?) }
@original.filter do |r|
r.test?
end
end
it "should filter out resources which produce true when the filter block is evaluated" do
expect(@original.filter do |r|
r == @r1
end.resource("File[/a]")).to be_nil
end
it "should not consider edges against resources that were filtered out" do
@original.add_edge(@r1,@r2)
expect(@original.filter do |r|
r == @r1
end.edge?(@r1,@r2)).not_to be
end
it "copies the version" do
@original.version = '123'
expect(@original.filter.version).to eq(@original.version)
end
it 'copies the code_id' do
@original.code_id = 'b59e5df0578ef411f773ee6c33d8073c50e7b8fe'
expect(@original.filter.code_id).to eq(@original.code_id)
end
it 'copies the catalog_uuid' do
@original.catalog_uuid = '827a74c8-cf98-44da-9ff7-18c5e4bee41e'
expect(@original.filter.catalog_uuid).to eq(@original.catalog_uuid)
end
it 'copies the catalog_format' do
@original.catalog_format = 42
expect(@original.filter.catalog_format).to eq(@original.catalog_format)
end
end
describe "when functioning as a resource container" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
@one = Puppet::Type.type(:notify).new :name => "one"
@two = Puppet::Type.type(:notify).new :name => "two"
@three = Puppet::Type.type(:notify).new :name => "three"
@dupe = Puppet::Type.type(:notify).new :name => "one"
end
it "should provide a method to add one or more resources" do
@catalog.add_resource @one, @two
expect(@catalog.resource(@one.ref)).to equal(@one)
expect(@catalog.resource(@two.ref)).to equal(@two)
end
it "should add resources to the relationship graph if it exists" do
relgraph = @catalog.relationship_graph
@catalog.add_resource @one
expect(relgraph).to be_vertex(@one)
end
it "should set itself as the resource's catalog if it is not a relationship graph" do
expect(@one).to receive(:catalog=).with(@catalog)
@catalog.add_resource @one
end
it "should make all vertices available by resource reference" do
@catalog.add_resource(@one)
expect(@catalog.resource(@one.ref)).to equal(@one)
expect(@catalog.vertices.find { |r| r.ref == @one.ref }).to equal(@one)
end
it "tracks the container through edges" do
@catalog.add_resource(@two)
@catalog.add_resource(@one)
@catalog.add_edge(@one, @two)
expect(@catalog.container_of(@two)).to eq(@one)
end
it "a resource without a container is contained in nil" do
@catalog.add_resource(@one)
expect(@catalog.container_of(@one)).to be_nil
end
it "should canonize how resources are referred to during retrieval when both type and title are provided" do
@catalog.add_resource(@one)
expect(@catalog.resource("notify", "one")).to equal(@one)
end
it "should canonize how resources are referred to during retrieval when just the title is provided" do
@catalog.add_resource(@one)
expect(@catalog.resource("notify[one]", nil)).to equal(@one)
end
it "adds resources before an existing resource" do
@catalog.add_resource(@one)
@catalog.add_resource_before(@one, @two, @three)
expect(@catalog.resources).to eq([@two, @three, @one])
end
it "raises if adding a resource before a resource not in the catalog" do
expect {
@catalog.add_resource_before(@one, @two)
}.to raise_error(ArgumentError, "Cannot add resource Notify[two] before Notify[one] because Notify[one] is not yet in the catalog")
end
it "adds resources after an existing resource in reverse order" do
@catalog.add_resource(@one)
@catalog.add_resource_after(@one, @two, @three)
expect(@catalog.resources).to eq([@one, @three, @two])
end
it "raises if adding a resource after a resource not in the catalog" do
expect {
@catalog.add_resource_after(@one, @two)
}.to raise_error(ArgumentError, "Cannot add resource Notify[two] after Notify[one] because Notify[one] is not yet in the catalog")
end
describe 'with a duplicate resource' do
def resource_at(type, name, file, line)
resource = Puppet::Resource.new(type, name)
resource.file = file
resource.line = line
Puppet::Type.type(type).new(resource)
end
let(:orig) { resource_at(:notify, 'duplicate-title', '/path/to/orig/file', 42) }
let(:dupe) { resource_at(:notify, 'duplicate-title', '/path/to/dupe/file', 314) }
it "should print the locations of the original duplicated resource" do
@catalog.add_resource(orig)
expect { @catalog.add_resource(dupe) }.to raise_error { |error|
expect(error).to be_a Puppet::Resource::Catalog::DuplicateResourceError
expect(error.message).to match %r[Duplicate declaration: Notify\[duplicate-title\] is already declared]
expect(error.message).to match %r[at \(file: /path/to/orig/file, line: 42\)]
expect(error.message).to match %r[cannot redeclare]
expect(error.message).to match %r[\(file: /path/to/dupe/file, line: 314\)]
}
end
end
it "should remove all resources when asked" do
@catalog.add_resource @one
@catalog.add_resource @two
expect(@one).to receive(:remove)
expect(@two).to receive(:remove)
@catalog.clear(true)
end
it "should support a mechanism for finishing resources" do
expect(@one).to receive(:finish)
expect(@two).to receive(:finish)
@catalog.add_resource @one
@catalog.add_resource @two
@catalog.finalize
end
it "should make default resources when finalizing" do
expect(@catalog).to receive(:make_default_resources)
@catalog.finalize
end
it "should add default resources to the catalog upon creation" do
@catalog.make_default_resources
expect(@catalog.resource(:schedule, "daily")).not_to be_nil
end
it "should optionally support an initialization block and should finalize after such blocks" do
expect(@one).to receive(:finish)
expect(@two).to receive(:finish)
Puppet::Resource::Catalog.new("host") do |conf|
conf.add_resource @one
conf.add_resource @two
end
end
it "should inform the resource that it is the resource's catalog" do
expect(@one).to receive(:catalog=).with(@catalog)
@catalog.add_resource @one
end
it "should be able to find resources by reference" do
@catalog.add_resource @one
expect(@catalog.resource(@one.ref)).to equal(@one)
end
it "should be able to find resources by reference or by type/title tuple" do
@catalog.add_resource @one
expect(@catalog.resource("notify", "one")).to equal(@one)
end
it "should have a mechanism for removing resources" do
@catalog.add_resource(@one)
expect(@catalog.resource(@one.ref)).to be
expect(@catalog.vertex?(@one)).to be_truthy
@catalog.remove_resource(@one)
expect(@catalog.resource(@one.ref)).to be_nil
expect(@catalog.vertex?(@one)).to be_falsey
end
it "should have a method for creating aliases for resources" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
expect(@catalog.resource("notify", "other")).to equal(@one)
end
it "should ignore conflicting aliases that point to the aliased resource" do
@catalog.alias(@one, "other")
expect { @catalog.alias(@one, "other") }.not_to raise_error
end
it "should create aliases for isomorphic resources whose names do not match their titles" do
resource = Puppet::Type::File.new(:title => "testing", :path => @basepath+"/something")
@catalog.add_resource(resource)
expect(@catalog.resource(:file, @basepath+"/something")).to equal(resource)
end
it "should not create aliases for non-isomorphic resources whose names do not match their titles" do
resource = Puppet::Type.type(:exec).new(:title => "testing", :command => "echo", :path => %w{/bin /usr/bin /usr/local/bin})
@catalog.add_resource(resource)
# Yay, I've already got a 'should' method
expect(@catalog.resource(:exec, "echo").object_id).to eq(nil.object_id)
end
# This test is the same as the previous, but the behaviour should be explicit.
it "should alias using the class name from the resource reference, not the resource class name" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
expect(@catalog.resource("notify", "other")).to equal(@one)
end
it "should fail to add an alias if the aliased name already exists" do
@catalog.add_resource @one
expect { @catalog.alias @two, "one" }.to raise_error(ArgumentError)
end
it "should not fail when a resource has duplicate aliases created" do
@catalog.add_resource @one
expect { @catalog.alias @one, "one" }.not_to raise_error
end
it "should not create aliases that point back to the resource" do
@catalog.alias(@one, "one")
expect(@catalog.resource(:notify, "one")).to be_nil
end
it "should be able to look resources up by their aliases" do
@catalog.add_resource @one
@catalog.alias @one, "two"
expect(@catalog.resource(:notify, "two")).to equal(@one)
end
it "should remove resource aliases when the target resource is removed" do
@catalog.add_resource @one
@catalog.alias(@one, "other")
expect(@one).to receive(:remove)
@catalog.remove_resource(@one)
expect(@catalog.resource("notify", "other")).to be_nil
end
it "should add an alias for the namevar when the title and name differ on isomorphic resource types" do
resource = Puppet::Type.type(:file).new :path => @basepath+"/something", :title => "other", :content => "blah"
expect(resource).to receive(:isomorphic?).and_return(true)
@catalog.add_resource(resource)
expect(@catalog.resource(:file, "other")).to equal(resource)
expect(@catalog.resource(:file, @basepath+"/something").ref).to eq(resource.ref)
end
it "should not add an alias for the namevar when the title and name differ on non-isomorphic resource types" do
resource = Puppet::Type.type(:file).new :path => @basepath+"/something", :title => "other", :content => "blah"
expect(resource).to receive(:isomorphic?).and_return(false)
@catalog.add_resource(resource)
expect(@catalog.resource(:file, resource.title)).to equal(resource)
# We can't use .should here, because the resources respond to that method.
raise "Aliased non-isomorphic resource" if @catalog.resource(:file, resource.name)
end
it "should provide a method to create additional resources that also registers the resource" do
args = {:name => "/yay", :ensure => :file}
resource = double('file', :ref => "File[/yay]", :catalog= => @catalog, :title => "/yay", :[] => "/yay")
expect(Puppet::Type.type(:file)).to receive(:new).with(args).and_return(resource)
@catalog.create_resource :file, args
expect(@catalog.resource("File[/yay]")).to equal(resource)
end
describe "when adding resources with multiple namevars" do
before :each do
Puppet::Type.newtype(:multiple) do
newparam(:color, :namevar => true)
newparam(:designation, :namevar => true)
def self.title_patterns
[ [
/^(\w+) (\w+)$/,
[
[:color, lambda{|x| x}],
[:designation, lambda{|x| x}]
]
] ]
end
end
end
it "should add an alias using the uniqueness key" do
@resource = Puppet::Type.type(:multiple).new(:title => "some resource", :color => "red", :designation => "5")
@catalog.add_resource(@resource)
expect(@catalog.resource(:multiple, "some resource")).to eq(@resource)
expect(@catalog.resource("Multiple[some resource]")).to eq(@resource)
expect(@catalog.resource("Multiple[red 5]")).to eq(@resource)
end
it "should conflict with a resource with the same uniqueness key" do
@resource = Puppet::Type.type(:multiple).new(:title => "some resource", :color => "red", :designation => "5")
@other = Puppet::Type.type(:multiple).new(:title => "another resource", :color => "red", :designation => "5")
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias Multiple\[another resource\] to \["red", "5"\].*resource \["Multiple", "red", "5"\] already declared/)
end
it "should conflict when its uniqueness key matches another resource's title" do
path = make_absolute("/tmp/foo")
@resource = Puppet::Type.type(:file).new(:title => path)
@other = Puppet::Type.type(:file).new(:title => "another file", :path => path)
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias File\[another file\] to \["#{Regexp.escape(path)}"\].*resource \["File", "#{Regexp.escape(path)}"\] already declared/)
end
it "should conflict when its uniqueness key matches the uniqueness key derived from another resource's title" do
@resource = Puppet::Type.type(:multiple).new(:title => "red leader")
@other = Puppet::Type.type(:multiple).new(:title => "another resource", :color => "red", :designation => "leader")
@catalog.add_resource(@resource)
expect { @catalog.add_resource(@other) }.to raise_error(ArgumentError, /Cannot alias Multiple\[another resource\] to \["red", "leader"\].*resource \["Multiple", "red", "leader"\] already declared/)
end
end
end
describe "when applying" do
before :each do
@catalog = Puppet::Resource::Catalog.new("host")
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
allow(Puppet::Transaction).to receive(:new).and_return(@transaction)
allow(@transaction).to receive(:evaluate)
allow(@transaction).to receive(:for_network_device=)
allow(Puppet.settings).to receive(:use)
end
it "should create and evaluate a transaction" do
expect(@transaction).to receive(:evaluate)
@catalog.apply
end
it "should add a transaction evalution time to the report" do
expect(@transaction.report).to receive(:add_times).with(:transaction_evaluation, kind_of(Numeric))
@catalog.apply
end
it "should return the transaction" do
expect(@catalog.apply).to equal(@transaction)
end
it "should yield the transaction if a block is provided" do
@catalog.apply do |trans|
expect(trans).to equal(@transaction)
end
end
it "should default to being a host catalog" do
expect(@catalog.host_config).to be_truthy
end
it "should be able to be set to a non-host_config" do
@catalog.host_config = false
expect(@catalog.host_config).to be_falsey
end
it "should pass supplied tags on to the transaction" do
expect(@transaction).to receive(:tags=).with(%w{one two})
@catalog.apply(:tags => %w{one two})
end
it "should set ignoreschedules on the transaction if specified in apply()" do
expect(@transaction).to receive(:ignoreschedules=).with(true)
@catalog.apply(:ignoreschedules => true)
end
it "should detect transaction failure and report it" do
allow(@transaction).to receive(:evaluate).and_raise(RuntimeError, 'transaction failed.')
report = Puppet::Transaction::Report.new('apply')
expect { @catalog.apply(:report => report) }.to raise_error(RuntimeError)
report.finalize_report
expect(report.status).to eq('failed')
end
describe "host catalogs" do
# super() doesn't work in the setup method for some reason
before do
@catalog.host_config = true
allow(Puppet::Util::Storage).to receive(:store)
end
it "should initialize the state database before applying a catalog" do
expect(Puppet::Util::Storage).to receive(:load)
# Short-circuit the apply, so we know we're loading before the transaction
expect(Puppet::Transaction).to receive(:new).and_raise(ArgumentError)
expect { @catalog.apply }.to raise_error(ArgumentError)
end
it "should sync the state database after applying" do
expect(Puppet::Util::Storage).to receive(:store)
allow(@transaction).to receive(:any_failed?).and_return(false)
@catalog.apply
end
end
describe "non-host catalogs" do
before do
@catalog.host_config = false
end
it "should never send reports" do
Puppet[:report] = true
Puppet[:summarize] = true
@catalog.apply
end
it "should never modify the state database" do
expect(Puppet::Util::Storage).not_to receive(:load)
expect(Puppet::Util::Storage).not_to receive(:store)
@catalog.apply
end
end
end
describe "when creating a relationship graph" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
end
it "should get removed when the catalog is cleaned up" do
expect(@catalog.relationship_graph).to receive(:clear)
@catalog.clear
expect(@catalog.instance_variable_get("@relationship_graph")).to be_nil
end
end
describe "when writing dot files" do
before do
@catalog = Puppet::Resource::Catalog.new("host")
@name = :test
@file = File.join(Puppet[:graphdir], @name.to_s + ".dot")
end
it "should only write when it is a host catalog" do
expect(Puppet::FileSystem).not_to receive(:open).with(@file, 0640, "w:UTF-8")
@catalog.host_config = false
Puppet[:graph] = true
@catalog.write_graph(@name)
end
end
describe "when indirecting" do
before do
@real_indirection = Puppet::Resource::Catalog.indirection
@indirection = double('indirection', :name => :catalog)
end
it "should use the value of the 'catalog_terminus' setting to determine its terminus class" do
# Puppet only checks the terminus setting the first time you ask
# so this returns the object to the clean state
# at the expense of making this test less pure
Puppet::Resource::Catalog.indirection.reset_terminus_class
Puppet.settings[:catalog_terminus] = "rest"
expect(Puppet::Resource::Catalog.indirection.terminus_class).to eq(:rest)
end
it "should allow the terminus class to be set manually" do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
expect(Puppet::Resource::Catalog.indirection.terminus_class).to eq(:rest)
end
after do
@real_indirection.reset_terminus_class
end
end
describe "when converting to yaml" do
before do
@catalog = Puppet::Resource::Catalog.new("me")
@catalog.add_edge("one", "two")
end
it "should be able to be dumped to yaml" do
expect(YAML.dump(@catalog)).to be_instance_of(String)
end
end
describe "when converting from yaml" do
before do
@catalog = Puppet::Resource::Catalog.new("me")
@catalog.add_edge("one", "two")
text = YAML.dump(@catalog)
@newcatalog = Puppet::Util::Yaml.safe_load(text, [Puppet::Resource::Catalog])
end
it "should get converted back to a catalog" do
expect(@newcatalog).to be_instance_of(Puppet::Resource::Catalog)
end
it "should have all vertices" do
expect(@newcatalog.vertex?("one")).to be_truthy
expect(@newcatalog.vertex?("two")).to be_truthy
end
it "should have all edges" do
expect(@newcatalog.edge?("one", "two")).to be_truthy
end
end
end
describe Puppet::Resource::Catalog, "when converting a resource catalog to json" do
include JSONMatchers
include PuppetSpec::Compiler
it "should validate an empty catalog against the schema" do
empty_catalog = compile_to_catalog("")
expect(empty_catalog.to_json).to validate_against('api/schemas/catalog.json')
end
it "should validate a noop catalog against the schema" do
noop_catalog = compile_to_catalog("create_resources('file', {})")
expect(noop_catalog.to_json).to validate_against('api/schemas/catalog.json')
end
it "should validate a single resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present'}})")
expect(catalog.to_json).to validate_against('api/schemas/catalog.json')
end
it "should validate a virtual resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('@file', {'/etc/foo'=>{'ensure'=>'present'}})\nrealize(File['/etc/foo'])")
expect(catalog.to_json).to validate_against('api/schemas/catalog.json')
end
it "should validate a single exported resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('@@file', {'/etc/foo'=>{'ensure'=>'present'}})")
expect(catalog.to_json).to validate_against('api/schemas/catalog.json')
end
it "should validate a single sensitive parameter resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('file', {'/etc/foo'=>{'ensure'=>'present','content'=>Sensitive('hunter2')}})")
expect(catalog.to_json).to validate_against('api/schemas/catalog.json')
end
it "should validate a two resource catalog against the schema" do
catalog = compile_to_catalog("create_resources('notify', {'foo'=>{'message'=>'one'}, 'bar'=>{'message'=>'two'}})")
expect(catalog.to_json).to validate_against('api/schemas/catalog.json')
end
it "should validate a two parameter class catalog against the schema" do
catalog = compile_to_catalog(<<-MANIFEST)
class multi_param_class ($one, $two) {
notify {'foo':
message => "One is $one, two is $two",
}
}
class {'multi_param_class':
one => 'hello',
two => 'world',
}
MANIFEST
expect(catalog.to_json).to validate_against('api/schemas/catalog.json')
end
context 'when dealing with parameters that have non-Data values' do
context 'and rich_data is enabled' do
before(:each) do
Puppet.push_context(
:loaders => Puppet::Pops::Loaders.new(Puppet.lookup(:environments).get(Puppet[:environment])),
:rich_data => true)
end
after(:each) do
Puppet.pop_context
end
let(:catalog_w_regexp) { compile_to_catalog("notify {'foo': message => /[a-z]+/ }") }
it 'should generate rich value hash for parameter values that are not Data' do
s = catalog_w_regexp.to_json
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/node/facts_spec.rb | spec/unit/node/facts_spec.rb | require 'spec_helper'
require 'puppet/node/facts'
require 'matchers/json'
describe Puppet::Node::Facts, "when indirecting" do
include JSONMatchers
before do
@facts = Puppet::Node::Facts.new("me")
end
describe "adding local facts" do
it "should add the node's certificate name as the 'clientcert' fact" do
@facts.add_local_facts
expect(@facts.values["clientcert"]).to eq(Puppet.settings[:certname])
end
it "adds the Puppet version as a 'clientversion' fact" do
@facts.add_local_facts
expect(@facts.values["clientversion"]).to eq(Puppet.version.to_s)
end
it "adds the agent side noop setting as 'clientnoop'" do
@facts.add_local_facts
expect(@facts.values["clientnoop"]).to eq(Puppet.settings[:noop])
end
it "doesn't add the current environment" do
@facts.add_local_facts
expect(@facts.values).not_to include("environment")
end
it "doesn't replace any existing environment fact when adding local facts" do
@facts.values["environment"] = "foo"
@facts.add_local_facts
expect(@facts.values["environment"]).to eq("foo")
end
it "adds the implementation fact" do
@facts.add_local_facts
expect(@facts.values).to include("implementation")
expect(@facts.values["implementation"]).to eq("openvox")
end
end
describe "when sanitizing facts" do
it "should convert fact values if needed" do
@facts.values["test"] = /foo/
@facts.sanitize
expect(@facts.values["test"]).to eq("(?-mix:foo)")
end
it "should convert hash keys if needed" do
@facts.values["test"] = {/foo/ => "bar"}
@facts.sanitize
expect(@facts.values["test"]).to eq({"(?-mix:foo)" => "bar"})
end
it "should convert hash values if needed" do
@facts.values["test"] = {"foo" => /bar/}
@facts.sanitize
expect(@facts.values["test"]).to eq({"foo" => "(?-mix:bar)"})
end
it "should convert array elements if needed" do
@facts.values["test"] = [1, "foo", /bar/]
@facts.sanitize
expect(@facts.values["test"]).to eq([1, "foo", "(?-mix:bar)"])
end
it "should handle nested arrays" do
@facts.values["test"] = [1, "foo", [/bar/]]
@facts.sanitize
expect(@facts.values["test"]).to eq([1, "foo", ["(?-mix:bar)"]])
end
it "should handle nested hashes" do
@facts.values["test"] = {/foo/ => {"bar" => /baz/}}
@facts.sanitize
expect(@facts.values["test"]).to eq({"(?-mix:foo)" => {"bar" => "(?-mix:baz)"}})
end
it "should handle nester arrays and hashes" do
@facts.values["test"] = {/foo/ => ["bar", /baz/]}
@facts.sanitize
expect(@facts.values["test"]).to eq({"(?-mix:foo)" => ["bar", "(?-mix:baz)"]})
end
it "should handle alien values having a to_s that returns ascii-8bit" do
class Alien
end
an_alien = Alien.new
@facts.values["test"] = an_alien
@facts.sanitize
fact_value = @facts.values['test']
expect(fact_value).to eq(an_alien.to_s)
# JRuby 9.2.8 reports US-ASCII which is a subset of UTF-8
expect(fact_value.encoding).to eq(Encoding::UTF_8).or eq(Encoding::US_ASCII)
end
end
describe "when indirecting" do
before do
@indirection = double('indirection', :request => double('request'), :name => :facts)
@facts = Puppet::Node::Facts.new("me", "one" => "two")
end
it "should redirect to the specified fact store for storage" do
allow(Puppet::Node::Facts).to receive(:indirection).and_return(@indirection)
expect(@indirection).to receive(:save)
Puppet::Node::Facts.indirection.save(@facts)
end
describe "when the Puppet application is 'master'" do
it "should default to the 'yaml' terminus" do
pending "Cannot test the behavior of defaults in defaults.rb"
expect(Puppet::Node::Facts.indirection.terminus_class).to eq(:yaml)
end
end
describe "when the Puppet application is not 'master'" do
it "should default to the 'facter' terminus" do
pending "Cannot test the behavior of defaults in defaults.rb"
expect(Puppet::Node::Facts.indirection.terminus_class).to eq(:facter)
end
end
end
describe "when storing and retrieving" do
it "doesn't manufacture a `_timestamp` fact value" do
values = {"one" => "two", "three" => "four"}
facts = Puppet::Node::Facts.new("mynode", values)
expect(facts.values).to eq(values)
end
describe "when deserializing from yaml" do
let(:timestamp) { Time.parse("Thu Oct 28 11:16:31 -0700 2010") }
let(:expiration) { Time.parse("Thu Oct 28 11:21:31 -0700 2010") }
def create_facts(values = {})
Puppet::Node::Facts.new('mynode', values)
end
def deserialize_yaml_facts(facts)
facts.sanitize
format = Puppet::Network::FormatHandler.format('yaml')
format.intern(Puppet::Node::Facts, YAML.dump(facts.to_data_hash))
end
it 'preserves `_timestamp` value' do
facts = deserialize_yaml_facts(create_facts('_timestamp' => timestamp))
expect(facts.timestamp).to eq(timestamp)
end
it "doesn't preserve the `_timestamp` fact" do
facts = deserialize_yaml_facts(create_facts('_timestamp' => timestamp))
expect(facts.values['_timestamp']).to be_nil
end
it 'preserves expiration time if present' do
old_facts = create_facts
old_facts.expiration = expiration
facts = deserialize_yaml_facts(old_facts)
expect(facts.expiration).to eq(expiration)
end
it 'ignores expiration time if absent' do
facts = deserialize_yaml_facts(create_facts)
expect(facts.expiration).to be_nil
end
end
describe "using json" do
before :each do
@timestamp = Time.parse("Thu Oct 28 11:16:31 -0700 2010")
@expiration = Time.parse("Thu Oct 28 11:21:31 -0700 2010")
end
it "should accept properly formatted json" do
json = %Q({"name": "foo", "expiration": "#{@expiration}", "timestamp": "#{@timestamp}", "values": {"a": "1", "b": "2", "c": "3"}})
format = Puppet::Network::FormatHandler.format('json')
facts = format.intern(Puppet::Node::Facts, json)
expect(facts.name).to eq('foo')
expect(facts.expiration).to eq(@expiration)
expect(facts.timestamp).to eq(@timestamp)
expect(facts.values).to eq({'a' => '1', 'b' => '2', 'c' => '3'})
end
it "should generate properly formatted json" do
allow(Time).to receive(:now).and_return(@timestamp)
facts = Puppet::Node::Facts.new("foo", {'a' => 1, 'b' => 2, 'c' => 3})
facts.expiration = @expiration
result = JSON.parse(facts.to_json)
expect(result['name']).to eq(facts.name)
expect(result['values']).to eq(facts.values)
expect(result['timestamp']).to eq(facts.timestamp.iso8601(9))
expect(result['expiration']).to eq(facts.expiration.iso8601(9))
end
it "should generate valid facts data against the facts schema" do
allow(Time).to receive(:now).and_return(@timestamp)
facts = Puppet::Node::Facts.new("foo", {'a' => 1, 'b' => 2, 'c' => 3})
facts.expiration = @expiration
expect(facts.to_json).to validate_against('api/schemas/facts.json')
end
it "should not include nil values" do
facts = Puppet::Node::Facts.new("foo", {'a' => 1, 'b' => 2, 'c' => 3})
json= JSON.parse(facts.to_json)
expect(json).not_to be_include("expiration")
end
it "should be able to handle nil values" do
json = %Q({"name": "foo", "values": {"a": "1", "b": "2", "c": "3"}})
format = Puppet::Network::FormatHandler.format('json')
facts = format.intern(Puppet::Node::Facts, json)
expect(facts.name).to eq('foo')
expect(facts.expiration).to be_nil
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/node/environment_spec.rb | spec/unit/node/environment_spec.rb | require 'spec_helper'
require 'tmpdir'
require 'puppet/node/environment'
require 'puppet/util/execution'
require 'puppet_spec/modules'
require 'puppet/parser/parser_factory'
describe Puppet::Node::Environment do
let(:env) { Puppet::Node::Environment.create("testing", []) }
include PuppetSpec::Files
context 'the environment' do
it "converts an environment to string when converting to YAML" do
expect(env.to_yaml).to match(/--- testing/)
end
describe ".create" do
it "creates equivalent environments whether specifying name as a symbol or a string" do
expect(Puppet::Node::Environment.create(:one, [])).to eq(Puppet::Node::Environment.create("one", []))
end
it "interns name" do
expect(Puppet::Node::Environment.create("one", []).name).to equal(:one)
end
it "does not produce environment singletons" do
expect(Puppet::Node::Environment.create("one", [])).to_not equal(Puppet::Node::Environment.create("one", []))
end
end
it "returns its name when converted to a string" do
expect(env.to_s).to eq("testing")
end
it "has an inspect method for debugging" do
e = Puppet::Node::Environment.create(:test, ['/modules/path', '/other/modules'], '/manifests/path')
expect("a #{e} env").to eq("a test env")
expect(e.inspect).to match(%r{<Puppet::Node::Environment:\w* @name="test" @manifest="#{File.expand_path('/manifests/path')}" @modulepath="#{File.expand_path('/modules/path')}:#{File.expand_path('/other/modules')}" >})
end
describe "externalizing filepaths" do
before(:each) do
env.resolved_path = "/opt/puppetlabs/envs/prod_123"
env.configured_path = "/etc/puppetlabs/envs/prod"
@vendored_manifest = "/opt/puppetlabs/vendored/modules/foo/manifests/init.pp"
@production_manifest = "/opt/puppetlabs/envs/prod_123/modules/foo/manifests/init.pp"
end
it "leaves paths alone if they do not match the resolved path" do
expect(env.externalize_path(@vendored_manifest)).to eq(@vendored_manifest)
end
it "leaves paths alone if resolved or configured paths are not set" do
env.resolved_path = nil
env.configured_path = nil
expect(env.externalize_path(@production_manifest)).to eq(@production_manifest)
end
it "replaces resolved paths with configured paths" do
externalized_path = env.externalize_path(@production_manifest)
expect(externalized_path).to eq("/etc/puppetlabs/envs/prod/modules/foo/manifests/init.pp")
end
it "handles nil" do
externalized_path = env.externalize_path(nil)
expect(externalized_path).to eq(nil)
end
it "appropriately handles mismatched trailing slashes" do
env.resolved_path = "/opt/puppetlabs/envs/prod_123/"
externalized_path = env.externalize_path(@production_manifest)
expect(externalized_path).to eq("/etc/puppetlabs/envs/prod/modules/foo/manifests/init.pp")
end
it "can be disabled with the `report_configured_environmentpath` setting" do
Puppet[:report_configured_environmentpath] = false
expect(env.externalize_path(@production_manifest)).to eq(@production_manifest)
end
end
describe "equality" do
it "works as a hash key" do
base = Puppet::Node::Environment.create(:first, ["modules"], "manifests")
same = Puppet::Node::Environment.create(:first, ["modules"], "manifests")
different = Puppet::Node::Environment.create(:first, ["different"], "manifests")
hash = {}
hash[base] = "base env"
hash[same] = "same env"
hash[different] = "different env"
expect(hash[base]).to eq("same env")
expect(hash[different]).to eq("different env")
expect(hash.count).to eq 2
end
it "is equal when name, modules, and manifests are the same" do
base = Puppet::Node::Environment.create(:base, ["modules"], "manifests")
different_name = Puppet::Node::Environment.create(:different, base.full_modulepath, base.manifest)
expect(base).to_not eq("not an environment")
expect(base).to eq(base)
expect(base.hash).to eq(base.hash)
expect(base.override_with(:modulepath => ["different"])).to_not eq(base)
expect(base.override_with(:modulepath => ["different"]).hash).to_not eq(base.hash)
expect(base.override_with(:manifest => "different")).to_not eq(base)
expect(base.override_with(:manifest => "different").hash).to_not eq(base.hash)
expect(different_name).to_not eq(base)
expect(different_name.hash).to_not eq(base.hash)
end
end
describe "overriding an existing environment" do
let(:original_path) { [tmpdir('original')] }
let(:new_path) { [tmpdir('new')] }
let(:environment) { Puppet::Node::Environment.create(:overridden, original_path, 'orig.pp', '/config/script') }
it "overrides modulepath" do
overridden = environment.override_with(:modulepath => new_path)
expect(overridden).to_not be_equal(environment)
expect(overridden.name).to eq(:overridden)
expect(overridden.manifest).to eq(File.expand_path('orig.pp'))
expect(overridden.modulepath).to eq(new_path)
expect(overridden.config_version).to eq('/config/script')
end
it "overrides manifest" do
overridden = environment.override_with(:manifest => 'new.pp')
expect(overridden).to_not be_equal(environment)
expect(overridden.name).to eq(:overridden)
expect(overridden.manifest).to eq(File.expand_path('new.pp'))
expect(overridden.modulepath).to eq(original_path)
expect(overridden.config_version).to eq('/config/script')
end
it "overrides config_version" do
overridden = environment.override_with(:config_version => '/new/script')
expect(overridden).to_not be_equal(environment)
expect(overridden.name).to eq(:overridden)
expect(overridden.manifest).to eq(File.expand_path('orig.pp'))
expect(overridden.modulepath).to eq(original_path)
expect(overridden.config_version).to eq('/new/script')
end
end
describe "when managing known resource types" do
before do
allow(env).to receive(:perform_initial_import).and_return(Puppet::Parser::AST::Hostclass.new(''))
end
it "creates a resource type collection if none exists" do
expect(env.known_resource_types).to be_kind_of(Puppet::Resource::TypeCollection)
end
it "memoizes resource type collection" do
expect(env.known_resource_types).to equal(env.known_resource_types)
end
it "performs the initial import when creating a new collection" do
expect(env).to receive(:perform_initial_import).and_return(Puppet::Parser::AST::Hostclass.new(''))
env.known_resource_types
end
it "generates a new TypeCollection if the current one requires reparsing" do
old_type_collection = env.known_resource_types
allow(old_type_collection).to receive(:parse_failed?).and_return(true)
env.check_for_reparse
new_type_collection = env.known_resource_types
expect(new_type_collection).to be_a Puppet::Resource::TypeCollection
expect(new_type_collection).to_not equal(old_type_collection)
end
end
it "validates the modulepath directories" do
real_file = tmpdir('moduledir')
path = ['/one', '/two', real_file]
env = Puppet::Node::Environment.create(:test, path)
expect(env.modulepath).to eq([real_file])
end
it "prefixes the value of the 'PUPPETLIB' environment variable to the module path if present" do
first_puppetlib = tmpdir('puppetlib1')
second_puppetlib = tmpdir('puppetlib2')
first_moduledir = tmpdir('moduledir1')
second_moduledir = tmpdir('moduledir2')
Puppet::Util.withenv("PUPPETLIB" => [first_puppetlib, second_puppetlib].join(File::PATH_SEPARATOR)) do
env = Puppet::Node::Environment.create(:testing, [first_moduledir, second_moduledir])
expect(env.modulepath).to eq([first_puppetlib, second_puppetlib, first_moduledir, second_moduledir])
end
end
describe "validating manifest settings" do
before(:each) do
Puppet[:default_manifest] = "/default/manifests/site.pp"
end
it "has no validation errors when disable_per_environment_manifest is false" do
expect(Puppet::Node::Environment.create(:directory, [], '/some/non/default/manifest.pp').validation_errors).to be_empty
end
context "when disable_per_environment_manifest is true" do
let(:config) { double('config') }
let(:global_modulepath) { ["/global/modulepath"] }
let(:envconf) { Puppet::Settings::EnvironmentConf.new("/some/direnv", config, global_modulepath) }
before(:each) do
Puppet[:disable_per_environment_manifest] = true
end
def assert_manifest_conflict(expectation, envconf_manifest_value)
expect(config).to receive(:setting).with(:manifest).and_return(
double('setting', :value => envconf_manifest_value)
)
environment = Puppet::Node::Environment.create(:directory, [], '/default/manifests/site.pp')
loader = Puppet::Environments::Static.new(environment)
allow(loader).to receive(:get_conf).and_return(envconf)
Puppet.override(:environments => loader) do
if expectation
expect(environment.validation_errors).to have_matching_element(/The 'disable_per_environment_manifest' setting is true.*and the.*environment.*conflicts/)
else
expect(environment.validation_errors).to be_empty
end
end
end
it "has conflicting_manifest_settings when environment.conf manifest was set" do
assert_manifest_conflict(true, '/some/envconf/manifest/site.pp')
end
it "does not have conflicting_manifest_settings when environment.conf manifest is empty" do
assert_manifest_conflict(false, '')
end
it "does not have conflicting_manifest_settings when environment.conf manifest is nil" do
assert_manifest_conflict(false, nil)
end
it "does not have conflicting_manifest_settings when environment.conf manifest is an exact, uninterpolated match of default_manifest" do
assert_manifest_conflict(false, '/default/manifests/site.pp')
end
end
end
describe "when modeling a specific environment" do
let(:first_modulepath) { tmpdir('firstmodules') }
let(:second_modulepath) { tmpdir('secondmodules') }
let(:env) { Puppet::Node::Environment.create(:modules_test, [first_modulepath, second_modulepath]) }
let(:module_options) {
{
:environment => env,
:metadata => {
:author => 'puppetlabs',
},
}
}
describe "module data" do
describe ".module" do
it "returns an individual module that exists in its module path" do
one = PuppetSpec::Modules.create('one', first_modulepath, module_options)
expect(env.module('one')).to eq(one)
end
it "returns nil if asked for a module that does not exist in its path" do
expect(env.module("doesnotexist")).to be_nil
end
end
describe "#modules_by_path" do
it "returns an empty list if there are no modules" do
expect(env.modules_by_path).to eq({
first_modulepath => [],
second_modulepath => []
})
end
it "includes modules even if they exist in multiple dirs in the modulepath" do
one = PuppetSpec::Modules.create('one', first_modulepath, module_options)
two = PuppetSpec::Modules.create('two', second_modulepath, module_options)
expect(env.modules_by_path).to eq({
first_modulepath => [one],
second_modulepath => [two],
})
end
it "ignores modules with invalid names" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('.foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo2', first_modulepath)
PuppetSpec::Modules.generate_files('foo-bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo_bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo=bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo.bar', first_modulepath)
PuppetSpec::Modules.generate_files('-foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo-', first_modulepath)
PuppetSpec::Modules.generate_files('foo--bar', first_modulepath)
expect(env.modules_by_path[first_modulepath].collect{|mod| mod.name}.sort).to eq(%w{foo foo2 foo_bar})
end
end
describe "#module_requirements" do
it "returns a list of what modules depend on other modules" do
PuppetSpec::Modules.create(
'foo',
first_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs/bar', "version_requirement" => ">= 1.0.0" }]
}
)
PuppetSpec::Modules.create(
'bar',
second_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs/foo', "version_requirement" => "<= 2.0.0" }]
}
)
PuppetSpec::Modules.create(
'baz',
first_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs-bar', "version_requirement" => "3.0.0" }]
}
)
PuppetSpec::Modules.create(
'alpha',
first_modulepath,
:metadata => {
:author => 'puppetlabs',
:dependencies => [{ 'name' => 'puppetlabs/bar', "version_requirement" => "~3.0.0" }]
}
)
expect(env.module_requirements).to eq({
'puppetlabs/alpha' => [],
'puppetlabs/foo' => [
{
"name" => "puppetlabs/bar",
"version" => "9.9.9",
"version_requirement" => "<= 2.0.0"
}
],
'puppetlabs/bar' => [
{
"name" => "puppetlabs/alpha",
"version" => "9.9.9",
"version_requirement" => "~3.0.0"
},
{
"name" => "puppetlabs/baz",
"version" => "9.9.9",
"version_requirement" => "3.0.0"
},
{
"name" => "puppetlabs/foo",
"version" => "9.9.9",
"version_requirement" => ">= 1.0.0"
}
],
'puppetlabs/baz' => []
})
end
end
describe ".module_by_forge_name" do
it "finds modules by forge_name" do
mod = PuppetSpec::Modules.create(
'baz',
first_modulepath,
module_options
)
expect(env.module_by_forge_name('puppetlabs/baz')).to eq(mod)
end
it "does not find modules with same name by the wrong author" do
PuppetSpec::Modules.create(
'baz',
first_modulepath,
:metadata => {:author => 'sneakylabs'},
:environment => env
)
expect(env.module_by_forge_name('puppetlabs/baz')).to eq(nil)
end
it "returns nil when the module can't be found" do
expect(env.module_by_forge_name('ima/nothere')).to be_nil
end
end
describe ".modules" do
it "returns an empty list if there are no modules" do
expect(env.modules).to eq([])
end
it "returns a module named for every directory in each module path" do
%w{foo bar}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, first_modulepath)
end
%w{bee baz}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, second_modulepath)
end
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{foo bar bee baz}.sort)
end
it "removes duplicates" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo', second_modulepath)
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{foo})
end
it "ignores modules with invalid names" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('.foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo2', first_modulepath)
PuppetSpec::Modules.generate_files('foo-bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo_bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo=bar', first_modulepath)
PuppetSpec::Modules.generate_files('foo bar', first_modulepath)
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{foo foo2 foo_bar})
end
it "creates modules with the correct environment" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
env.modules.each do |mod|
expect(mod.environment).to eq(env)
end
end
it "logs an exception if a module contains invalid metadata" do
PuppetSpec::Modules.generate_files(
'foo',
first_modulepath,
:metadata => {
:author => 'puppetlabs'
# missing source, version, etc
}
)
expect(Puppet).to receive(:log_exception).with(be_a(Puppet::Module::MissingMetadata))
env.modules
end
it "includes the Bolt project in modules if it's defined" do
path = tmpdir('project')
PuppetSpec::Modules.generate_files('bolt_project', path)
project = Struct.new("Project", :name, :path, :load_as_module?).new('bolt_project', path, true)
Puppet.override(bolt_project: project) do
%w{foo bar}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, first_modulepath)
end
%w{bee baz}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, second_modulepath)
end
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{bolt_project foo bar bee baz}.sort)
end
end
it "does not include the Bolt project in modules if load_as_module? is false" do
path = tmpdir('project')
PuppetSpec::Modules.generate_files('bolt_project', path)
project = Struct.new("Project", :name, :path, :load_as_module?).new('bolt_project', path, false)
Puppet.override(bolt_project: project) do
%w{foo bar}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, first_modulepath)
end
%w{bee baz}.each do |mod_name|
PuppetSpec::Modules.generate_files(mod_name, second_modulepath)
end
expect(env.modules.collect{|mod| mod.name}.sort).to eq(%w{foo bar bee baz}.sort)
end
end
end
end
end
describe "when performing initial import" do
let(:loaders) { Puppet::Pops::Loaders.new(env) }
before(:each) do
allow_any_instance_of(Puppet::Parser::Compiler).to receive(:loaders).and_return(loaders)
Puppet.push_context({:loaders => loaders, :current_environment => env})
end
after(:each) do
Puppet.pop_context()
end
it "loads from Puppet[:code]" do
Puppet[:code] = "define foo {}"
krt = env.known_resource_types
expect(krt.find_definition('foo')).to be_kind_of(Puppet::Resource::Type)
end
it "parses from the environment's manifests if Puppet[:code] is not set" do
filename = tmpfile('a_manifest.pp')
File.open(filename, 'w') do |f|
f.puts("define from_manifest {}")
end
env = Puppet::Node::Environment.create(:testing, [], filename)
krt = env.known_resource_types
expect(krt.find_definition('from_manifest')).to be_kind_of(Puppet::Resource::Type)
end
it "prefers Puppet[:code] over manifest files" do
Puppet[:code] = "define from_code_setting {}"
filename = tmpfile('a_manifest.pp')
File.open(filename, 'w') do |f|
f.puts("define from_manifest {}")
end
env = Puppet::Node::Environment.create(:testing, [], filename)
krt = env.known_resource_types
expect(krt.find_definition('from_code_setting')).to be_kind_of(Puppet::Resource::Type)
end
it "initial import proceeds even if manifest file does not exist on disk" do
filename = tmpfile('a_manifest.pp')
env = Puppet::Node::Environment.create(:testing, [], filename)
expect(env.known_resource_types).to be_kind_of(Puppet::Resource::TypeCollection)
end
it "returns an empty TypeCollection if neither code nor manifests is present" do
expect(env.known_resource_types).to be_kind_of(Puppet::Resource::TypeCollection)
end
it "fails helpfully if there is an error importing" do
Puppet[:code] = "oops {"
expect do
env.known_resource_types
end.to raise_error(Puppet::Error, /Could not parse for environment #{env.name}/)
end
it "should mark the type collection as needing a reparse when there is an error parsing" do
Puppet[:code] = "oops {"
expect do
env.known_resource_types
end.to raise_error(Puppet::Error, /Syntax error at .../)
expect(env.known_resource_types.parse_failed?).to be_truthy
end
end
end
describe "managing module translations" do
context "when i18n is enabled" do
before(:each) do
Puppet[:disable_i18n] = false
end
it "yields block results" do
ran = false
expect(env.with_text_domain { ran = true; :result }).to eq(:result)
expect(ran).to eq(true)
end
it "creates a new text domain the first time we try to use the text domain" do
expect(Puppet::GettextConfig).to receive(:reset_text_domain).with(env.name)
expect(Puppet::ModuleTranslations).to receive(:load_from_modulepath)
expect(Puppet::GettextConfig).to receive(:clear_text_domain)
env.with_text_domain do; end
end
it "uses the existing text domain once it has been created" do
env.with_text_domain do; end
expect(Puppet::GettextConfig).to receive(:use_text_domain).with(env.name)
env.with_text_domain do; end
end
end
context "when i18n is disabled" do
it "yields block results" do
ran = false
expect(env.with_text_domain { ran = true; :result }).to eq(:result)
expect(ran).to eq(true)
end
it "does not create a new text domain the first time we try to use the text domain" do
expect(Puppet::GettextConfig).not_to receive(:reset_text_domain)
expect(Puppet::ModuleTranslations).not_to receive(:load_from_modulepath)
env.with_text_domain do; end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/transaction/resource_harness_spec.rb | spec/unit/transaction/resource_harness_spec.rb | require 'spec_helper'
require 'puppet/transaction/resource_harness'
describe Puppet::Transaction::ResourceHarness do
include PuppetSpec::Files
before do
@mode_750 = Puppet::Util::Platform.windows? ? '644' : '750'
@mode_755 = Puppet::Util::Platform.windows? ? '644' : '755'
path = make_absolute("/my/file")
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
@resource = Puppet::Type.type(:file).new :path => path
@harness = Puppet::Transaction::ResourceHarness.new(@transaction)
@current_state = Puppet::Resource.new(:file, path)
allow(@resource).to receive(:retrieve).and_return(@current_state)
end
it "should accept a transaction at initialization" do
harness = Puppet::Transaction::ResourceHarness.new(@transaction)
expect(harness.transaction).to equal(@transaction)
end
it "should delegate to the transaction for its relationship graph" do
expect(@transaction).to receive(:relationship_graph).and_return("relgraph")
expect(Puppet::Transaction::ResourceHarness.new(@transaction).relationship_graph).to eq("relgraph")
end
describe "when evaluating a resource" do
it "produces a resource state that describes what happened with the resource" do
status = @harness.evaluate(@resource)
expect(status.resource).to eq(@resource.ref)
expect(status).not_to be_failed
expect(status.events).to be_empty
end
it "retrieves the current state of the resource" do
expect(@resource).to receive(:retrieve).and_return(@current_state)
@harness.evaluate(@resource)
end
it "produces a failure status for the resource when an error occurs" do
the_message = "retrieve failed in testing"
expect(@resource).to receive(:retrieve).and_raise(ArgumentError.new(the_message))
status = @harness.evaluate(@resource)
expect(status).to be_failed
expect(events_to_hash(status.events).collect do |event|
{ :@status => event[:@status], :@message => event[:@message] }
end).to eq([{ :@status => "failure", :@message => the_message }])
end
it "records the time it took to evaluate the resource" do
before = Time.now
status = @harness.evaluate(@resource)
after = Time.now
expect(status.evaluation_time).to be <= after - before
end
end
def events_to_hash(events)
events.map do |event|
hash = {}
event.instance_variables.each do |varname|
hash[varname.to_sym] = event.instance_variable_get(varname)
end
hash
end
end
def make_stub_provider
stubProvider = Class.new(Puppet::Type)
stubProvider.instance_eval do
initvars
newparam(:name) do
desc "The name var"
isnamevar
end
newproperty(:foo) do
desc "A property that can be changed successfully"
def sync
end
def retrieve
:absent
end
def insync?(reference_value)
false
end
end
newproperty(:bar) do
desc "A property that raises an exception when you try to change it"
def sync
raise ZeroDivisionError.new('bar')
end
def retrieve
:absent
end
def insync?(reference_value)
false
end
end
newproperty(:baz) do
desc "A property that raises an Exception (not StandardError) when you try to change it"
def sync
raise Exception.new('baz')
end
def retrieve
:absent
end
def insync?(reference_value)
false
end
end
newproperty(:brillig) do
desc "A property that raises a StandardError exception when you test if it's insync?"
def sync
end
def retrieve
:absent
end
def insync?(reference_value)
raise ZeroDivisionError.new('brillig')
end
end
newproperty(:slithy) do
desc "A property that raises an Exception when you test if it's insync?"
def sync
end
def retrieve
:absent
end
def insync?(reference_value)
raise Exception.new('slithy')
end
end
end
stubProvider
end
context "interaction of ensure with other properties" do
def an_ensurable_resource_reacting_as(behaviors)
stub_type = Class.new(Puppet::Type)
stub_type.class_eval do
initvars
ensurable do
def sync
(@resource.behaviors[:on_ensure] || proc {}).call
end
def insync?(value)
@resource.behaviors[:ensure_insync?]
end
def should_to_s(value)
(@resource.behaviors[:on_should_to_s] || proc { "'#{value}'" }).call
end
def change_to_s(value, should)
"some custom insync message"
end
end
newparam(:name) do
desc "The name var"
isnamevar
end
newproperty(:prop) do
newvalue("new") do
#noop
end
def retrieve
"old"
end
end
attr_reader :behaviors
def initialize(options)
@behaviors = options.delete(:behaviors)
super
end
def exists?
@behaviors[:present?]
end
def present?(resource)
@behaviors[:present?]
end
def self.name
"Testing"
end
end
stub_type.new(:behaviors => behaviors,
:ensure => :present,
:name => "testing",
:prop => "new")
end
it "ensure errors means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => false, :on_ensure => proc { raise StandardError }, :present? => true)
status = @harness.evaluate(resource)
expect(status.events.length).to eq(1)
expect(status.events[0].property).to eq('ensure')
expect(status.events[0].name.to_s).to eq('Testing_created')
expect(status.events[0].status).to eq('failure')
end
it "ensure fails completely means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => false, :on_ensure => proc { raise Exception }, :present? => false)
expect do
@harness.evaluate(resource)
end.to raise_error(Exception)
expect(@logs.first.message).to eq("change from 'absent' to 'present' failed: Exception")
expect(@logs.first.level).to eq(:err)
end
it "ensure succeeds means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => false, :on_ensure => proc { }, :present? => true)
status = @harness.evaluate(resource)
expect(status.events.length).to eq(1)
expect(status.events[0].property).to eq('ensure')
expect(status.events[0].name.to_s).to eq('Testing_created')
expect(status.events[0].status).to eq('success')
expect(status.events[0].message).to eq 'some custom insync message'
end
it "ensure is in sync means that the rest *does* happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => true, :present? => true)
status = @harness.evaluate(resource)
expect(status.events.length).to eq(1)
expect(status.events[0].property).to eq('prop')
expect(status.events[0].name.to_s).to eq('prop_changed')
expect(status.events[0].status).to eq('success')
end
it "ensure is in sync but resource not present, means that the rest doesn't happen" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => true, :present? => false)
status = @harness.evaluate(resource)
expect(status.events).to be_empty
end
it "ensure errors in message still get a log entry" do
resource = an_ensurable_resource_reacting_as(:ensure_insync? => false, :on_ensure => proc { raise StandardError }, :on_should_to_s => proc { raise StandardError }, :present? => true)
status = @harness.evaluate(resource)
expect(status.events.length).to eq(2)
testing_errors = status.events.find_all { |x| x.name.to_s == "Testing_created" }
resource_errors = status.events.find_all { |x| x.name.to_s == "resource_error" }
expect(testing_errors.length).to eq(1)
expect(resource_errors.length).to eq(1)
expect(testing_errors[0].message).not_to be_nil
expect(resource_errors[0].message).not_to eq("Puppet::Util::Log requires a message")
end
it "displays custom insync message in noop" do
resource = an_ensurable_resource_reacting_as(:present? => true)
resource[:noop] = true
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).to eq 'some custom insync message (noop)'
end
end
describe "when a caught error occurs" do
before :each do
stub_provider = make_stub_provider
resource = stub_provider.new :name => 'name', :foo => 1, :bar => 2
expect(resource).not_to receive(:err)
@status = @harness.evaluate(resource)
end
it "should record previous successful events" do
expect(@status.events[0].property).to eq('foo')
expect(@status.events[0].status).to eq('success')
end
it "should record a failure event" do
expect(@status.events[1].property).to eq('bar')
expect(@status.events[1].status).to eq('failure')
end
end
describe "when an Exception occurs during sync" do
before :each do
stub_provider = make_stub_provider
@resource = stub_provider.new :name => 'name', :baz => 1
expect(@resource).not_to receive(:err)
end
it "should log and pass the exception through" do
expect { @harness.evaluate(@resource) }.to raise_error(Exception, /baz/)
expect(@logs.first.message).to eq("change from 'absent' to 1 failed: baz")
expect(@logs.first.level).to eq(:err)
end
end
describe "when a StandardError exception occurs during insync?" do
before :each do
stub_provider = make_stub_provider
@resource = stub_provider.new :name => 'name', :brillig => 1
expect(@resource).not_to receive(:err)
end
it "should record a failure event" do
@status = @harness.evaluate(@resource)
expect(@status.events[0].name.to_s).to eq('brillig_changed')
expect(@status.events[0].property).to eq('brillig')
expect(@status.events[0].status).to eq('failure')
end
end
describe "when an Exception occurs during insync?" do
before :each do
stub_provider = make_stub_provider
@resource = stub_provider.new :name => 'name', :slithy => 1
expect(@resource).not_to receive(:err)
end
it "should log and pass the exception through" do
expect { @harness.evaluate(@resource) }.to raise_error(Exception, /slithy/)
expect(@logs.first.message).to eq("change from 'absent' to 1 failed: slithy")
expect(@logs.first.level).to eq(:err)
end
end
describe "when auditing" do
it "should not call insync? on parameters that are merely audited" do
stub_provider = make_stub_provider
resource = stub_provider.new :name => 'name', :audit => ['foo']
expect(resource.property(:foo)).not_to receive(:insync?)
status = @harness.evaluate(resource)
expect(status.events).to be_empty
end
it "should be able to audit a file's group" do # see bug #5710
test_file = tmpfile('foo')
File.open(test_file, 'w').close
resource = Puppet::Type.type(:file).new :path => test_file, :audit => ['group'], :backup => false
expect(resource).not_to receive(:err) # make sure no exceptions get swallowed
status = @harness.evaluate(resource)
status.events.each do |event|
expect(event.status).to != 'failure'
end
end
it "should not ignore microseconds when auditing a file's mtime" do
test_file = tmpfile('foo')
File.open(test_file, 'w').close
resource = Puppet::Type.type(:file).new :path => test_file, :audit => ['mtime'], :backup => false
# construct a property hash with nanosecond resolution as would be
# found on an ext4 file system
time_with_nsec_resolution = Time.at(1000, 123456.999)
current_from_filesystem = {:mtime => time_with_nsec_resolution}
# construct a property hash with a 1 microsecond difference from above
time_with_usec_resolution = Time.at(1000, 123457.000)
historical_from_state_yaml = {:mtime => time_with_usec_resolution}
# set up the sequence of stubs; yeah, this is pretty
# brittle, so this might need to be adjusted if the
# resource_harness logic changes
expect(resource).to receive(:retrieve).and_return(current_from_filesystem)
allow(Puppet::Util::Storage).to receive(:cache).with(resource).
and_return(historical_from_state_yaml, current_from_filesystem, current_from_filesystem)
# there should be an audit change recorded, since the two
# timestamps differ by at least 1 microsecond
status = @harness.evaluate(resource)
expect(status.events).not_to be_empty
status.events.each do |event|
expect(event.message).to match(/audit change: previously recorded/)
end
end
it "should ignore nanoseconds when auditing a file's mtime" do
test_file = tmpfile('foo')
File.open(test_file, 'w').close
resource = Puppet::Type.type(:file).new :path => test_file, :audit => ['mtime'], :backup => false
# construct a property hash with nanosecond resolution as would be
# found on an ext4 file system
time_with_nsec_resolution = Time.at(1000, 123456.789)
current_from_filesystem = {:mtime => time_with_nsec_resolution}
# construct a property hash with the same timestamp as above,
# truncated to microseconds, as would be read back from state.yaml
time_with_usec_resolution = Time.at(1000, 123456.000)
historical_from_state_yaml = {:mtime => time_with_usec_resolution}
# set up the sequence of stubs; yeah, this is pretty
# brittle, so this might need to be adjusted if the
# resource_harness logic changes
expect(resource).to receive(:retrieve).and_return(current_from_filesystem)
allow(Puppet::Util::Storage).to receive(:cache).with(resource).
and_return(historical_from_state_yaml, current_from_filesystem, current_from_filesystem)
# there should be no audit change recorded, despite the
# slight difference in the two timestamps
status = @harness.evaluate(resource)
status.events.each do |event|
expect(event.message).not_to match(/audit change: previously recorded/)
end
end
end
describe "handling sensitive properties" do
describe 'when syncing' do
let(:test_file) do
tmpfile('foo').tap do |path|
File.open(path, 'w') { |fh| fh.write("goodbye world") }
end
end
let(:resource) do
Puppet::Type.type(:file).new(:path => test_file, :backup => false, :content => "hello world").tap do |r|
r.parameter(:content).sensitive = true
end
end
it "redacts event messages for sensitive properties" do
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).to eq 'changed [redacted] to [redacted]'
end
it "redacts event contents for sensitive properties" do
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.previous_value).to eq '[redacted]'
expect(sync_event.desired_value).to eq '[redacted]'
end
it "redacts event messages for sensitive properties when simulating noop changes" do
resource[:noop] = true
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).to eq 'current_value [redacted], should be [redacted] (noop)'
end
describe 'auditing' do
before do
resource[:audit] = ['content']
end
it "redacts notices when a parameter is newly audited" do
expect(resource.property(:content)).to receive(:notice).with("audit change: newly-recorded value [redacted]")
@harness.evaluate(resource)
end
it "redacts event messages for sensitive properties" do
allow(Puppet::Util::Storage).to receive(:cache).with(resource).and_return({:content => "historical world"})
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).to eq 'changed [redacted] to [redacted] (previously recorded value was [redacted])'
end
it "redacts audit event messages for sensitive properties when simulating noop changes" do
allow(Puppet::Util::Storage).to receive(:cache).with(resource).and_return({:content => "historical world"})
resource[:noop] = true
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).to eq 'current_value [redacted], should be [redacted] (noop) (previously recorded value was [redacted])'
end
it "redacts event contents for sensitive properties" do
allow(Puppet::Util::Storage).to receive(:cache).with(resource).and_return({:content => "historical world"})
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.historical_value).to eq '[redacted]'
end
end
end
describe 'handling errors' do
it "redacts event messages generated when syncing a param raises a StandardError" do
stub_provider = make_stub_provider
resource = stub_provider.new :name => 'name', :bar => 1
resource.parameter(:bar).sensitive = true
status = @harness.evaluate(resource)
error_event = status.events[0]
expect(error_event.message).to eq "change from [redacted] to [redacted] failed: bar"
end
it "redacts event messages generated when syncing a param raises an Exception" do
stub_provider = make_stub_provider
resource = stub_provider.new :name => 'name', :baz => 1
resource.parameter(:baz).sensitive = true
expect { @harness.evaluate(resource) }.to raise_error(Exception, 'baz')
expect(@logs.first.message).to eq "change from [redacted] to [redacted] failed: baz"
end
end
end
describe "when finding the schedule" do
before do
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
end
it "should warn and return nil if the resource has no catalog" do
@resource.catalog = nil
expect(@resource).to receive(:warning)
expect(@harness.schedule(@resource)).to be_nil
end
it "should return nil if the resource specifies no schedule" do
expect(@harness.schedule(@resource)).to be_nil
end
it "should fail if the named schedule cannot be found" do
@resource[:schedule] = "whatever"
expect(@resource).to receive(:fail)
@harness.schedule(@resource)
end
it "should return the named schedule if it exists" do
sched = Puppet::Type.type(:schedule).new(:name => "sched")
@catalog.add_resource(sched)
@resource[:schedule] = "sched"
expect(@harness.schedule(@resource).to_s).to eq(sched.to_s)
end
end
describe "when determining if a resource is scheduled" do
before do
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
end
it "should return true if 'ignoreschedules' is set" do
Puppet[:ignoreschedules] = true
@resource[:schedule] = "meh"
expect(@harness).to be_scheduled(@resource)
end
it "should return true if the resource has no schedule set" do
expect(@harness).to be_scheduled(@resource)
end
it "should return the result of matching the schedule with the cached 'checked' time if a schedule is set" do
t = Time.now
expect(@harness).to receive(:cached).with(@resource, :checked).and_return(t)
sched = Puppet::Type.type(:schedule).new(:name => "sched")
@catalog.add_resource(sched)
@resource[:schedule] = "sched"
expect(sched).to receive(:match?).with(t.to_i).and_return("feh")
expect(@harness.scheduled?(@resource)).to eq("feh")
end
end
it "should be able to cache data in the Storage module" do
data = {}
expect(Puppet::Util::Storage).to receive(:cache).with(@resource).and_return(data)
@harness.cache(@resource, :foo, "something")
expect(data[:foo]).to eq("something")
end
it "should be able to retrieve data from the cache" do
data = {:foo => "other"}
expect(Puppet::Util::Storage).to receive(:cache).with(@resource).and_return(data)
expect(@harness.cached(@resource, :foo)).to eq("other")
end
describe "successful event message" do
let(:test_file) do
tmpfile('foo').tap do |path|
File.open(path, 'w') { |fh| fh.write("old contents") }
end
end
let(:resource) do
Puppet::Type.type(:file).new(:path => test_file, :backup => false, :content => "hello world")
end
it "contains (corrective) when corrective change" do
allow_any_instance_of(Puppet::Transaction::Event).to receive(:corrective_change).and_return(true)
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).to match(/content changed '{sha256}[0-9a-f]+' to '{sha256}[0-9a-f]+' \(corrective\)/)
end
it "contains no modifier when intentional change" do
allow_any_instance_of(Puppet::Transaction::Event).to receive(:corrective_change).and_return(false)
status = @harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).to match(/content changed '{sha256}[0-9a-f]+' to '{sha256}[0-9a-f]+'$/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/transaction/report_spec.rb | spec/unit/transaction/report_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet'
require 'puppet/transaction/report'
require 'matchers/json'
describe Puppet::Transaction::Report do
include JSONMatchers
include PuppetSpec::Files
include PuppetSpec::Compiler
before do
allow(Puppet::Util::Storage).to receive(:store)
end
it "should set its host name to the node_name_value" do
Puppet[:node_name_value] = 'mynode'
expect(Puppet::Transaction::Report.new.host).to eq("mynode")
end
it "should return its host name as its name" do
r = Puppet::Transaction::Report.new
expect(r.name).to eq(r.host)
end
it "should create an initialization timestamp" do
expect(Time).to receive(:now).and_return("mytime")
expect(Puppet::Transaction::Report.new.time).to eq("mytime")
end
it "should take a 'configuration_version' as an argument" do
expect(Puppet::Transaction::Report.new("some configuration version", "some environment").configuration_version).to eq("some configuration version")
end
it "should take a 'transaction_uuid' as an argument" do
expect(Puppet::Transaction::Report.new("some configuration version", "some environment", "some transaction uuid").transaction_uuid).to eq("some transaction uuid")
end
it "should take a 'job_id' as an argument" do
expect(Puppet::Transaction::Report.new('cv', 'env', 'tid', 'some job id').job_id).to eq('some job id')
end
it "should take a 'start_time' as an argument" do
expect(Puppet::Transaction::Report.new('cv', 'env', 'tid', 'some job id', 'my start time').time).to eq('my start time')
end
it "should be able to set configuration_version" do
report = Puppet::Transaction::Report.new
report.configuration_version = "some version"
expect(report.configuration_version).to eq("some version")
end
it "should be able to set transaction_uuid" do
report = Puppet::Transaction::Report.new
report.transaction_uuid = "some transaction uuid"
expect(report.transaction_uuid).to eq("some transaction uuid")
end
it "should be able to set job_id" do
report = Puppet::Transaction::Report.new
report.job_id = "some job id"
expect(report.job_id).to eq("some job id")
end
it "should be able to set code_id" do
report = Puppet::Transaction::Report.new
report.code_id = "some code id"
expect(report.code_id).to eq("some code id")
end
it "should be able to set catalog_uuid" do
report = Puppet::Transaction::Report.new
report.catalog_uuid = "some catalog uuid"
expect(report.catalog_uuid).to eq("some catalog uuid")
end
it "should be able to set cached_catalog_status" do
report = Puppet::Transaction::Report.new
report.cached_catalog_status = "explicitly_requested"
expect(report.cached_catalog_status).to eq("explicitly_requested")
end
it "should set noop to true if Puppet[:noop] is true" do
Puppet[:noop] = true
report = Puppet::Transaction::Report.new
expect(report.noop).to be_truthy
end
it "should set noop to false if Puppet[:noop] is false" do
Puppet[:noop] = false
report = Puppet::Transaction::Report.new
expect(report.noop).to be_falsey
end
it "should set noop to false if Puppet[:noop] is unset" do
Puppet[:noop] = nil
report = Puppet::Transaction::Report.new
expect(report.noop).to be_falsey
end
it "should take 'environment' as an argument" do
expect(Puppet::Transaction::Report.new("some configuration version", "some environment").environment).to eq("some environment")
end
it "should be able to set environment" do
report = Puppet::Transaction::Report.new
report.environment = "some environment"
expect(report.environment).to eq("some environment")
end
it "should be able to set resources_failed_to_generate" do
report = Puppet::Transaction::Report.new
report.resources_failed_to_generate = true
expect(report.resources_failed_to_generate).to be_truthy
end
it "resources_failed_to_generate should not be true by default" do
report = Puppet::Transaction::Report.new
expect(report.resources_failed_to_generate).to be_falsey
end
it "should not include whits" do
allow(Puppet::FileBucket::File.indirection).to receive(:save)
filename = tmpfile('whit_test')
file = Puppet::Type.type(:file).new(:path => filename)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(file)
report = Puppet::Transaction::Report.new
catalog.apply(:report => report)
report.finalize_report
expect(report.resource_statuses.values.any? {|res| res.resource_type =~ /whit/i}).to be_falsey
expect(report.metrics['time'].values.any? {|metric| metric.first =~ /whit/i}).to be_falsey
end
describe "when exclude_unchanged_resources is true" do
let(:test_dir) { tmpdir('unchanged_resources') }
let(:test_dir2) { tmpdir('unchanged_resources') }
let(:test_file) { tmpfile('some_path')}
it 'should still list "changed" resource statuses but remove "unchanged"' do
transaction = apply_compiled_manifest(<<-END)
notify { "hi": } ~>
exec { "/bin/this_command_does_not_exist":
command => "#{make_absolute('/bin/this_command_does_not_exist')}",
refreshonly => true,
}
file { '#{test_dir}':
ensure => directory
}
file { 'failing_file':
path => '#{test_dir2}',
ensure => file
}
file { 'skipped_file':
path => '#{test_file}',
require => File[failing_file]
}
END
rs = transaction.report.to_data_hash['resource_statuses']
expect(rs["Notify[hi]"]['out_of_sync']).to be true
expect(rs["Exec[/bin/this_command_does_not_exist]"]['failed_to_restart']).to be true
expect(rs["File[failing_file]"]['failed']).to be true
expect(rs["File[skipped_file]"]['skipped']).to be true
expect(rs).to_not have_key(["File[#{test_dir}]"])
end
end
describe"when exclude_unchanged_resources is false" do
before do
Puppet[:exclude_unchanged_resources] = false
end
let(:test_dir) { tmpdir('unchanged_resources') }
let(:test_dir2) { tmpdir('unchanged_resources') }
let(:test_file) { tmpfile('some_path')}
it 'should list all resource statuses' do
transaction = apply_compiled_manifest(<<-END)
notify { "hi": } ~>
exec { "/bin/this_command_does_not_exist":
command => "#{make_absolute('/bin/this_command_does_not_exist')}",
refreshonly => true,
}
file { '#{test_dir}':
ensure => directory
}
file { 'failing_file':
path => '#{test_dir2}',
ensure => file
}
file { 'skipped_file':
path => '#{test_file}',
require => File[failing_file]
}
END
rs = transaction.report.to_data_hash['resource_statuses']
expect(rs["Notify[hi]"]['out_of_sync']).to be true
expect(rs["Exec[/bin/this_command_does_not_exist]"]['failed_to_restart']).to be true
expect(rs["File[failing_file]"]['failed']).to be true
expect(rs["File[skipped_file]"]['skipped']).to be true
expect(rs["File[#{test_dir}]"]['changed']).to be false
end
end
describe "when accepting logs" do
before do
@report = Puppet::Transaction::Report.new
end
it "should add new logs to the log list" do
@report << "log"
expect(@report.logs[-1]).to eq("log")
end
it "should return self" do
r = @report << "log"
expect(r).to equal(@report)
end
end
describe "#as_logging_destination" do
it "makes the report collect logs during the block " do
log_string = 'Hello test report!'
report = Puppet::Transaction::Report.new
report.as_logging_destination do
Puppet.err(log_string)
end
expect(report.logs.collect(&:message)).to include(log_string)
end
end
describe "when accepting resource statuses" do
before do
@report = Puppet::Transaction::Report.new
end
it "should add each status to its status list" do
status = double('status', :resource => "foo")
@report.add_resource_status status
expect(@report.resource_statuses["foo"]).to equal(status)
end
end
describe "when using the indirector" do
it "should redirect :save to the indirection" do
allow(Facter).to receive(:value).and_return("eh")
@indirection = double('indirection', :name => :report)
allow(Puppet::Transaction::Report).to receive(:indirection).and_return(@indirection)
report = Puppet::Transaction::Report.new
expect(@indirection).to receive(:save)
Puppet::Transaction::Report.indirection.save(report)
end
it "should default to the 'processor' terminus" do
expect(Puppet::Transaction::Report.indirection.terminus_class).to eq(:processor)
end
it "should delegate its name attribute to its host method" do
report = Puppet::Transaction::Report.new
expect(report).to receive(:host).and_return("me")
expect(report.name).to eq("me")
end
end
describe "when computing exit status" do
it "should produce -1 if no metrics are present" do
report = Puppet::Transaction::Report.new("apply")
expect(report.exit_status).to eq(-1)
end
it "should produce 2 if changes are present" do
report = Puppet::Transaction::Report.new
report.add_metric("changes", {"total" => 1})
report.add_metric("resources", {"failed" => 0})
expect(report.exit_status).to eq(2)
end
it "should produce 4 if failures are present" do
report = Puppet::Transaction::Report.new
report.add_metric("changes", {"total" => 0})
report.add_metric("resources", {"failed" => 1})
expect(report.exit_status).to eq(4)
end
it "should produce 4 if failures to restart are present" do
report = Puppet::Transaction::Report.new
report.add_metric("changes", {"total" => 0})
report.add_metric("resources", {"failed" => 0})
report.add_metric("resources", {"failed_to_restart" => 1})
expect(report.exit_status).to eq(4)
end
it "should produce 6 if both changes and failures are present" do
report = Puppet::Transaction::Report.new
report.add_metric("changes", {"total" => 1})
report.add_metric("resources", {"failed" => 1})
expect(report.exit_status).to eq(6)
end
end
describe "before finalizing the report" do
it "should have a status of 'failed'" do
report = Puppet::Transaction::Report.new
expect(report.status).to eq('failed')
end
end
describe "when finalizing the report" do
before do
@report = Puppet::Transaction::Report.new
end
def metric(name, value)
if metric = @report.metrics[name.to_s]
metric[value]
else
nil
end
end
def add_statuses(count, type = :file)
count.times do |i|
status = Puppet::Resource::Status.new(Puppet::Type.type(type).new(:title => make_absolute("/my/path#{i}")))
yield status if block_given?
@report.add_resource_status status
end
end
it "should be unchanged if there are no other failures or changes and the transaction completed" do
@report.transaction_completed = true
@report.finalize_report
expect(@report.status).to eq("unchanged")
end
it "should be failed if there are no other failures or changes and the transaction did not complete" do
@report.finalize_report
expect(@report.status).to eq("failed")
end
[:time, :resources, :changes, :events].each do |type|
it "should add #{type} metrics" do
@report.finalize_report
expect(@report.metrics[type.to_s]).to be_instance_of(Puppet::Transaction::Metric)
end
end
describe "for resources" do
it "should provide the total number of resources" do
add_statuses(3)
@report.finalize_report
expect(metric(:resources, "total")).to eq(3)
end
Puppet::Resource::Status::STATES.each do |state|
it "should provide the number of #{state} resources as determined by the status objects" do
add_statuses(3) { |status| status.send(state.to_s + "=", true) }
@report.finalize_report
expect(metric(:resources, state.to_s)).to eq(3)
end
it "should provide 0 for states not in status" do
@report.finalize_report
expect(metric(:resources, state.to_s)).to eq(0)
end
end
it "should mark the report as 'failed' if there are failing resources" do
add_statuses(1) { |status| status.failed = true }
@report.transaction_completed = true
@report.finalize_report
expect(@report.status).to eq('failed')
end
it "should mark the report as 'failed' if resources failed to restart" do
add_statuses(1) { |status| status.failed_to_restart = true }
@report.finalize_report
expect(@report.status).to eq('failed')
end
it "should mark the report as 'failed' if resources_failed_to_generate" do
@report.resources_failed_to_generate = true
@report.transaction_completed = true
@report.finalize_report
expect(@report.status).to eq('failed')
end
end
describe "for changes" do
it "should provide the number of changes from the resource statuses and mark the report as 'changed'" do
add_statuses(3) { |status| 3.times { status << Puppet::Transaction::Event.new(:status => 'success') } }
@report.transaction_completed = true
@report.finalize_report
expect(metric(:changes, "total")).to eq(9)
expect(@report.status).to eq('changed')
end
it "should provide a total even if there are no changes, and mark the report as 'unchanged'" do
@report.transaction_completed = true
@report.finalize_report
expect(metric(:changes, "total")).to eq(0)
expect(@report.status).to eq('unchanged')
end
end
describe "for times" do
it "should provide the total amount of time for each resource type" do
add_statuses(3, :file) do |status|
status.evaluation_time = 1
end
add_statuses(3, :exec) do |status|
status.evaluation_time = 2
end
add_statuses(3, :tidy) do |status|
status.evaluation_time = 3
end
@report.finalize_report
expect(metric(:time, "file")).to eq(3)
expect(metric(:time, "exec")).to eq(6)
expect(metric(:time, "tidy")).to eq(9)
end
it "should accrue times when called for one resource more than once" do
@report.add_times :foobar, 50
@report.add_times :foobar, 30
@report.finalize_report
expect(metric(:time, "foobar")).to eq(80)
end
it "should not accrue times when called for one resource more than once when set" do
@report.add_times :foobar, 50, false
@report.add_times :foobar, 30, false
@report.finalize_report
expect(metric(:time, "foobar")).to eq(30)
end
it "should add any provided times from external sources" do
@report.add_times :foobar, 50
@report.finalize_report
expect(metric(:time, "foobar")).to eq(50)
end
end
describe "for events" do
it "should provide the total number of events" do
add_statuses(3) do |status|
3.times { |i| status.add_event(Puppet::Transaction::Event.new :status => 'success') }
end
@report.finalize_report
expect(metric(:events, "total")).to eq(9)
end
it "should provide the total even if there are no events" do
@report.finalize_report
expect(metric(:events, "total")).to eq(0)
end
Puppet::Transaction::Event::EVENT_STATUSES.each do |status_name|
it "should provide the number of #{status_name} events" do
add_statuses(3) do |status|
3.times do |i|
event = Puppet::Transaction::Event.new
event.status = status_name
status.add_event(event)
end
end
@report.finalize_report
expect(metric(:events, status_name)).to eq(9)
end
end
end
describe "for noop events" do
it "should have 'noop_pending == false' when no events are available" do
add_statuses(3)
@report.finalize_report
expect(@report.noop_pending).to be_falsey
end
it "should have 'noop_pending == false' when no 'noop' events are available" do
add_statuses(3) do |status|
['success', 'audit'].each do |status_name|
event = Puppet::Transaction::Event.new
event.status = status_name
status.add_event(event)
end
end
@report.finalize_report
expect(@report.noop_pending).to be_falsey
end
it "should have 'noop_pending == true' when 'noop' events are available" do
add_statuses(3) do |status|
['success', 'audit', 'noop'].each do |status_name|
event = Puppet::Transaction::Event.new
event.status = status_name
status.add_event(event)
end
end
@report.finalize_report
expect(@report.noop_pending).to be_truthy
end
it "should have 'noop_pending == true' when 'noop' and 'failure' events are available" do
add_statuses(3) do |status|
['success', 'failure', 'audit', 'noop'].each do |status_name|
event = Puppet::Transaction::Event.new
event.status = status_name
status.add_event(event)
end
end
@report.finalize_report
expect(@report.noop_pending).to be_truthy
end
end
end
describe "when producing a summary" do
before do
allow(Benchmark).to receive(:realtime).and_return(5.05683418)
resource = Puppet::Type.type(:notify).new(:name => "testing")
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.version = 1234567
trans = catalog.apply
@report = trans.report
@report.add_times(:total, "8675") #Report total is now measured, not calculated.
@report.finalize_report
end
%w{changes time resources events version}.each do |main|
it "should include the key #{main} in the raw summary hash" do
expect(@report.raw_summary).to be_key main
end
end
it "should include the last run time in the raw summary hash" do
allow(Time).to receive(:now).and_return(Time.utc(2010,11,10,12,0,24))
expect(@report.raw_summary["time"]["last_run"]).to eq(1289390424)
end
it "should include all resource statuses" do
resources_report = @report.raw_summary["resources"]
Puppet::Resource::Status::STATES.each do |state|
expect(resources_report).to be_include(state.to_s)
end
end
%w{total failure success}.each do |r|
it "should include event #{r}" do
events_report = @report.raw_summary["events"]
expect(events_report).to be_include(r)
end
end
it "should include config version" do
expect(@report.raw_summary["version"]["config"]).to eq(1234567)
end
it "should include puppet version" do
expect(@report.raw_summary["version"]["puppet"]).to eq(Puppet.version)
end
%w{Changes Total Resources Time Events}.each do |main|
it "should include information on #{main} in the textual summary" do
expect(@report.summary).to be_include(main)
end
end
it 'should sort total at the very end of the time metrics' do
expect(@report.summary).to match(/
Last run: \d+
Transaction evaluation: \d+.\d{2}
Total: \d+.\d{2}
Version:
/)
end
end
describe "when outputting yaml" do
it "should not include @external_times" do
report = Puppet::Transaction::Report.new
report.add_times('config_retrieval', 1.0)
expect(report.to_data_hash.keys).not_to include('external_times')
end
it "should not include @resources_failed_to_generate" do
report = Puppet::Transaction::Report.new
report.resources_failed_to_generate = true
expect(report.to_data_hash.keys).not_to include('resources_failed_to_generate')
end
it 'to_data_hash returns value that is instance of to Data' do
expect(Puppet::Pops::Types::TypeFactory.data.instance?(generate_report.to_data_hash)).to be_truthy
end
end
it "defaults to serializing to json" do
expect(Puppet::Transaction::Report.default_format).to eq(:json)
end
it "supports both json and yaml" do
# msgpack and pson are optional, so using include instead of eq
expect(Puppet::Transaction::Report.supported_formats).to include(:json, :yaml)
end
context 'can make a round trip through' do
before(:each) do
Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(Puppet.lookup(:current_environment)))
end
after(:each) { Puppet.pop_context }
it 'pson', if: Puppet.features.pson? do
report = generate_report
tripped = Puppet::Transaction::Report.convert_from(:pson, report.render)
expect_equivalent_reports(tripped, report)
end
it 'json' do
report = generate_report
tripped = Puppet::Transaction::Report.convert_from(:json, report.render)
expect_equivalent_reports(tripped, report)
end
it 'yaml' do
report = generate_report
yaml_output = report.render(:yaml)
tripped = Puppet::Transaction::Report.convert_from(:yaml, yaml_output)
expect(yaml_output).to match(/^--- /)
expect_equivalent_reports(tripped, report)
end
end
it "generates json which validates against the report schema" do
report = generate_report
expect(report.render).to validate_against('api/schemas/report.json')
end
it "generates json for error report which validates against the report schema" do
error_report = generate_report_with_error
expect(error_report.render).to validate_against('api/schemas/report.json')
end
def expect_equivalent_reports(tripped, report)
expect(tripped.host).to eq(report.host)
expect(tripped.time.to_i).to eq(report.time.to_i)
expect(tripped.configuration_version).to eq(report.configuration_version)
expect(tripped.transaction_uuid).to eq(report.transaction_uuid)
expect(tripped.job_id).to eq(report.job_id)
expect(tripped.code_id).to eq(report.code_id)
expect(tripped.catalog_uuid).to eq(report.catalog_uuid)
expect(tripped.cached_catalog_status).to eq(report.cached_catalog_status)
expect(tripped.report_format).to eq(report.report_format)
expect(tripped.puppet_version).to eq(report.puppet_version)
expect(tripped.status).to eq(report.status)
expect(tripped.transaction_completed).to eq(report.transaction_completed)
expect(tripped.environment).to eq(report.environment)
expect(tripped.corrective_change).to eq(report.corrective_change)
expect(logs_as_strings(tripped)).to eq(logs_as_strings(report))
expect(metrics_as_hashes(tripped)).to eq(metrics_as_hashes(report))
expect_equivalent_resource_statuses(tripped.resource_statuses, report.resource_statuses)
end
def logs_as_strings(report)
report.logs.map(&:to_report)
end
def metrics_as_hashes(report)
Hash[*report.metrics.collect do |name, m|
[name, { :name => m.name, :label => m.label, :value => m.value }]
end.flatten]
end
def expect_equivalent_resource_statuses(tripped, report)
expect(tripped.keys.sort).to eq(report.keys.sort)
tripped.each_pair do |name, status|
expected = report[name]
expect(status.title).to eq(expected.title)
expect(status.file).to eq(expected.file)
expect(status.line).to eq(expected.line)
expect(status.resource).to eq(expected.resource)
expect(status.resource_type).to eq(expected.resource_type)
expect(status.provider_used).to eq(expected.provider_used)
expect(status.containment_path).to eq(expected.containment_path)
expect(status.evaluation_time).to eq(expected.evaluation_time)
expect(status.tags).to eq(expected.tags)
expect(status.time.to_i).to eq(expected.time.to_i)
expect(status.failed).to eq(expected.failed)
expect(status.changed).to eq(expected.changed)
expect(status.out_of_sync).to eq(expected.out_of_sync)
expect(status.skipped).to eq(expected.skipped)
expect(status.change_count).to eq(expected.change_count)
expect(status.out_of_sync_count).to eq(expected.out_of_sync_count)
expect(status.events).to eq(expected.events)
end
end
def generate_report
# An Event cannot contain rich data - thus its "to_data_hash" stringifies the result.
# (This means it cannot be deserialized with intact data types).
# Here it is simulated that the values are after stringification.
stringifier = Puppet::Pops::Serialization::ToStringifiedConverter
event_hash = {
:audited => false,
:property => stringifier.convert('message'),
:previous_value => stringifier.convert(SemanticPuppet::VersionRange.parse('>=1.0.0')),
:desired_value => stringifier.convert(SemanticPuppet::VersionRange.parse('>=1.2.0')),
:historical_value => stringifier.convert(nil),
:message => stringifier.convert("defined 'message' as 'a resource'"),
:name => :message_changed, # the name
:status => stringifier.convert('success'),
}
event = Puppet::Transaction::Event.new(**event_hash)
status = Puppet::Resource::Status.new(Puppet::Type.type(:notify).new(:title => "a resource"))
status.changed = true
status.add_event(event)
report = Puppet::Transaction::Report.new(1357986, 'test_environment', "df34516e-4050-402d-a166-05b03b940749", '42')
report << Puppet::Util::Log.new(:level => :warning, :message => "log message")
report.add_times("timing", 4)
report.code_id = "some code id"
report.catalog_uuid = "some catalog uuid"
report.cached_catalog_status = "not_used"
report.server_used = "test:000"
report.add_resource_status(status)
report.transaction_completed = true
report.finalize_report
report
end
def generate_report_with_error
status = Puppet::Resource::Status.new(Puppet::Type.type(:notify).new(:title => "a resource"))
status.changed = true
status.failed_because("bad stuff happened")
report = Puppet::Transaction::Report.new(1357986, 'test_environment', "df34516e-4050-402d-a166-05b03b940749", '42')
report << Puppet::Util::Log.new(:level => :warning, :message => "log message")
report.add_times("timing", 4)
report.code_id = "some code id"
report.catalog_uuid = "some catalog uuid"
report.cached_catalog_status = "not_used"
report.server_used = "test:000"
report.add_resource_status(status)
report.transaction_completed = true
report.finalize_report
report
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/transaction/additional_resource_generator_spec.rb | spec/unit/transaction/additional_resource_generator_spec.rb | require 'spec_helper'
require 'puppet/transaction'
require 'puppet_spec/compiler'
require 'matchers/relationship_graph_matchers'
require 'matchers/include_in_order'
require 'matchers/resource'
describe Puppet::Transaction::AdditionalResourceGenerator do
include PuppetSpec::Compiler
include PuppetSpec::Files
include RelationshipGraphMatchers
include Matchers::Resource
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:node) { Puppet::Node.new('test', :environment => env) }
let(:loaders) { Puppet::Pops::Loaders.new(env) }
before(:each) do
allow_any_instance_of(Puppet::Parser::Compiler).to receive(:loaders).and_return(loaders)
Puppet.push_context({:loaders => loaders, :current_environment => env})
Puppet::Type.newtype(:generator) do
include PuppetSpec::Compiler
newparam(:name) do
isnamevar
end
newparam(:kind) do
defaultto :eval_generate
newvalues(:eval_generate, :generate)
end
newparam(:code)
def eval_generate
eval_code
end
def generate
eval_code
end
def eval_code
if self[:code]
compile_to_ral(self[:code]).resources.select { |r| r.ref =~ /Notify/ }
else
[]
end
end
end
Puppet::Type.newtype(:autorequire) do
newparam(:name) do
isnamevar
end
autorequire(:notify) do
self[:name]
end
end
Puppet::Type.newtype(:gen_auto) do
newparam(:name) do
isnamevar
end
newparam(:eval_after) do
end
def generate()
[ Puppet::Type.type(:autorequire).new(:name => self[:eval_after]) ]
end
end
Puppet::Type.newtype(:empty) do
newparam(:name) do
isnamevar
end
end
Puppet::Type.newtype(:gen_empty) do
newparam(:name) do
isnamevar
end
newparam(:eval_after) do
end
def generate()
[ Puppet::Type.type(:empty).new(:name => self[:eval_after], :require => "Notify[#{self[:eval_after]}]") ]
end
end
end
after(:each) do
Puppet::Type.rmtype(:gen_empty)
Puppet::Type.rmtype(:eval_after)
Puppet::Type.rmtype(:autorequire)
Puppet::Type.rmtype(:generator)
Puppet.pop_context()
end
def find_vertex(graph, type, title)
graph.vertices.find {|v| v.type == type and v.title == title}
end
context "when applying eval_generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should add a sentinel whit for the resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
expect(find_vertex(graph, :whit, "completed_thing")).to be_a(Puppet::Type.type(:whit))
end
it "should replace dependencies on the resource with dependencies on the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
notify { last: require => Generator['thing'] }
MANIFEST
expect(graph).to enforce_order_with_edge(
'Whit[completed_thing]', 'Notify[last]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "should add an edge from each generated resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Notify[hello]', 'Whit[completed_thing]')
expect(graph).to enforce_order_with_edge(
'Notify[goodbye]', 'Whit[completed_thing]')
end
it "should add an edge from the resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Whit[completed_thing]')
end
it "should tag the sentinel with the tags of the resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }',
tag => 'foo',
}
MANIFEST
whit = find_vertex(graph, :whit, "completed_thing")
expect(whit.tags).to be_superset(['thing', 'foo', 'generator'].to_set)
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
code => 'notify { hello: }'
}
}
include container
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should return false if an error occurred when generating resources" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'fail("not a good generation")'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
end
it "should return true if resources were generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(true)
end
it "should not add a sentinel if no resources are generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing: }
MANIFEST
relationship_graph = relationship_graph_for(catalog)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
expect(find_vertex(relationship_graph, :whit, "completed_thing")).to be_nil
end
it "orders generated resources with the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
it "sets resources_failed_to_generate to true if resource#eval_generate raises an exception" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing: }
MANIFEST
allow(catalog.resource("Generator[thing]")).to receive(:eval_generate).and_raise(RuntimeError)
relationship_graph = relationship_graph_for(catalog)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.eval_generate(catalog.resource("Generator[thing]"))
expect(generator.resources_failed_to_generate).to be_truthy
end
def relationships_after_eval_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
relationship_graph = relationship_graph_for(catalog)
eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
relationship_graph
end
def eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.eval_generate(catalog.resource(resource_to_generate))
end
end
context "when applying generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
}
include container
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "orders generated resources with the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
kind => generate,
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
it "runs autorequire on the generated resource" do
graph = relationships_after_generating(<<-MANIFEST, 'Gen_auto[thing]')
gen_auto { thing:
eval_after => hello,
}
notify { hello: }
notify { goodbye: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Gen_auto[thing]",
"Notify[hello]",
"Autorequire[hello]",
"Notify[goodbye]"))
end
it "evaluates metaparameters on the generated resource" do
graph = relationships_after_generating(<<-MANIFEST, 'Gen_empty[thing]')
gen_empty { thing:
eval_after => hello,
}
notify { hello: }
notify { goodbye: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Gen_empty[thing]",
"Notify[hello]",
"Empty[hello]",
"Notify[goodbye]"))
end
it "sets resources_failed_to_generate to true if resource#generate raises an exception" do
catalog = compile_to_ral(<<-MANIFEST)
user { 'foo':
ensure => present,
}
MANIFEST
allow(catalog.resource("User[foo]")).to receive(:generate).and_raise(RuntimeError)
relationship_graph = relationship_graph_for(catalog)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.generate_additional_resources(catalog.resource("User[foo]"))
expect(generator.resources_failed_to_generate).to be_truthy
end
def relationships_after_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
generate_resources_in(catalog, nil, resource_to_generate)
relationship_graph_for(catalog)
end
def generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.generate_additional_resources(catalog.resource(resource_to_generate))
end
end
def relationship_graph_for(catalog)
relationship_graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
relationship_graph.populate_from(catalog)
relationship_graph
end
def order_resources_traversed_in(relationships)
order_seen = []
relationships.traverse { |resource| order_seen << resource.ref }
order_seen
end
RSpec::Matchers.define :contain_resources_equally do |*resource_refs|
match do |catalog|
@containers = resource_refs.collect do |resource_ref|
catalog.container_of(catalog.resource(resource_ref)).ref
end
@containers.all? { |resource_ref| resource_ref == @containers[0] }
end
def failure_message
"expected #{@expected.join(', ')} to all be contained in the same resource but the containment was #{@expected.zip(@containers).collect { |(res, container)| res + ' => ' + container }.join(', ')}"
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/transaction/event_spec.rb | spec/unit/transaction/event_spec.rb | require 'spec_helper'
require 'puppet/transaction/event'
class TestResource
def to_s
"Foo[bar]"
end
def [](v)
nil
end
end
describe Puppet::Transaction::Event do
include PuppetSpec::Files
it "should support resource" do
event = Puppet::Transaction::Event.new
event.resource = TestResource.new
expect(event.resource).to eq("Foo[bar]")
end
it "should always convert the property to a string" do
expect(Puppet::Transaction::Event.new(:property => :foo).property).to eq("foo")
end
it "should always convert the resource to a string" do
expect(Puppet::Transaction::Event.new(:resource => TestResource.new).resource).to eq("Foo[bar]")
end
it "should produce the message when converted to a string" do
event = Puppet::Transaction::Event.new
expect(event).to receive(:message).and_return("my message")
expect(event.to_s).to eq("my message")
end
it "should support 'status'" do
event = Puppet::Transaction::Event.new
event.status = "success"
expect(event.status).to eq("success")
end
it "should fail if the status is not to 'audit', 'noop', 'success', or 'failure" do
event = Puppet::Transaction::Event.new
expect { event.status = "foo" }.to raise_error(ArgumentError)
end
it "should support tags" do
expect(Puppet::Transaction::Event.ancestors).to include(Puppet::Util::Tagging)
end
it "should create a timestamp at its creation time" do
expect(Puppet::Transaction::Event.new.time).to be_instance_of(Time)
end
describe "audit property" do
it "should default to false" do
expect(Puppet::Transaction::Event.new.audited).to eq(false)
end
end
describe "when sending logs" do
before do
allow(Puppet::Util::Log).to receive(:new)
end
it "should set the level to the resources's log level if the event status is 'success' and a resource is available" do
resource = double('resource')
expect(resource).to receive(:[]).with(:loglevel).and_return(:myloglevel)
expect(Puppet::Util::Log).to receive(:create).with(hash_including(level: :myloglevel))
Puppet::Transaction::Event.new(:status => "success", :resource => resource).send_log
end
it "should set the level to 'notice' if the event status is 'success' and no resource is available" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(level: :notice))
Puppet::Transaction::Event.new(:status => "success").send_log
end
it "should set the level to 'notice' if the event status is 'noop'" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(level: :notice))
Puppet::Transaction::Event.new(:status => "noop").send_log
end
it "should set the level to 'err' if the event status is 'failure'" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(level: :err))
Puppet::Transaction::Event.new(:status => "failure").send_log
end
it "should set the 'message' to the event log" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(message: "my message"))
Puppet::Transaction::Event.new(:message => "my message").send_log
end
it "should set the tags to the event tags" do
expect(Puppet::Util::Log).to receive(:new) do |args|
expect(args[:tags].to_a).to match_array(%w{one two})
end
Puppet::Transaction::Event.new(:tags => %w{one two}).send_log
end
[:file, :line].each do |attr|
it "should pass the #{attr}" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(attr => "my val"))
Puppet::Transaction::Event.new(attr => "my val").send_log
end
end
it "should use the source description as the source if one is set" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(source: "/my/param"))
Puppet::Transaction::Event.new(:source_description => "/my/param", :resource => TestResource.new, :property => "foo").send_log
end
it "should use the property as the source if one is available and no source description is set" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(source: "foo"))
Puppet::Transaction::Event.new(:resource => TestResource.new, :property => "foo").send_log
end
it "should use the property as the source if one is available and no property or source description is set" do
expect(Puppet::Util::Log).to receive(:new).with(hash_including(source: "Foo[bar]"))
Puppet::Transaction::Event.new(:resource => TestResource.new).send_log
end
end
describe "When converting to YAML" do
let(:resource) { Puppet::Type.type(:file).new(:title => make_absolute('/tmp/foo')) }
let(:event) do
Puppet::Transaction::Event.new(:source_description => "/my/param", :resource => resource,
:file => "/foo.rb", :line => 27, :tags => %w{one two},
:desired_value => 7, :historical_value => 'Brazil',
:message => "Help I'm trapped in a spec test",
:name => :mode_changed, :previous_value => 6, :property => :mode,
:status => 'success',
:redacted => false,
:corrective_change => false)
end
it 'to_data_hash returns value that is instance of to Data' do
expect(Puppet::Pops::Types::TypeFactory.data.instance?(event.to_data_hash)).to be_truthy
end
end
it "should round trip through json" do
resource = Puppet::Type.type(:file).new(:title => make_absolute("/tmp/foo"))
event = Puppet::Transaction::Event.new(
:source_description => "/my/param",
:resource => resource,
:file => "/foo.rb",
:line => 27,
:tags => %w{one two},
:desired_value => 7,
:historical_value => 'Brazil',
:message => "Help I'm trapped in a spec test",
:name => :mode_changed,
:previous_value => 6,
:property => :mode,
:status => 'success')
tripped = Puppet::Transaction::Event.from_data_hash(JSON.parse(event.to_json))
expect(tripped.audited).to eq(event.audited)
expect(tripped.property).to eq(event.property)
expect(tripped.previous_value).to eq(event.previous_value)
expect(tripped.desired_value).to eq(event.desired_value)
expect(tripped.historical_value).to eq(event.historical_value)
expect(tripped.message).to eq(event.message)
expect(tripped.name).to eq(event.name)
expect(tripped.status).to eq(event.status)
expect(tripped.time).to eq(event.time)
end
it "should round trip an event for an inspect report through json" do
resource = Puppet::Type.type(:file).new(:title => make_absolute("/tmp/foo"))
event = Puppet::Transaction::Event.new(
:audited => true,
:source_description => "/my/param",
:resource => resource,
:file => "/foo.rb",
:line => 27,
:tags => %w{one two},
:message => "Help I'm trapped in a spec test",
:previous_value => 6,
:property => :mode,
:status => 'success')
tripped = Puppet::Transaction::Event.from_data_hash(JSON.parse(event.to_json))
expect(tripped.desired_value).to be_nil
expect(tripped.historical_value).to be_nil
expect(tripped.name).to be_nil
expect(tripped.audited).to eq(event.audited)
expect(tripped.property).to eq(event.property)
expect(tripped.previous_value).to eq(event.previous_value)
expect(tripped.message).to eq(event.message)
expect(tripped.status).to eq(event.status)
expect(tripped.time).to eq(event.time)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/transaction/event_manager_spec.rb | spec/unit/transaction/event_manager_spec.rb | require 'spec_helper'
require 'puppet/transaction/event_manager'
describe Puppet::Transaction::EventManager do
include PuppetSpec::Files
describe "at initialization" do
it "should require a transaction" do
expect(Puppet::Transaction::EventManager.new("trans").transaction).to eq("trans")
end
end
it "should delegate its relationship graph to the transaction" do
transaction = double('transaction')
manager = Puppet::Transaction::EventManager.new(transaction)
expect(transaction).to receive(:relationship_graph).and_return("mygraph")
expect(manager.relationship_graph).to eq("mygraph")
end
describe "when queueing events" do
before do
@manager = Puppet::Transaction::EventManager.new(@transaction)
@resource = Puppet::Type.type(:file).new :path => make_absolute("/my/file")
@graph = double('graph', :matching_edges => [], :resource => @resource)
allow(@manager).to receive(:relationship_graph).and_return(@graph)
@event = Puppet::Transaction::Event.new(:name => :foo, :resource => @resource)
end
it "should store all of the events in its event list" do
@event2 = Puppet::Transaction::Event.new(:name => :bar, :resource => @resource)
@manager.queue_events(@resource, [@event, @event2])
expect(@manager.events).to include(@event)
expect(@manager.events).to include(@event2)
end
it "should queue events for the target and callback of any matching edges" do
edge1 = double("edge1", :callback => :c1, :source => double("s1"), :target => double("t1", :c1 => nil))
edge2 = double("edge2", :callback => :c2, :source => double("s2"), :target => double("t2", :c2 => nil))
expect(@graph).to receive(:matching_edges).with(@event, anything).and_return([edge1, edge2])
expect(@manager).to receive(:queue_events_for_resource).with(@resource, edge1.target, edge1.callback, [@event])
expect(@manager).to receive(:queue_events_for_resource).with(@resource, edge2.target, edge2.callback, [@event])
@manager.queue_events(@resource, [@event])
end
it "should queue events for the changed resource if the resource is self-refreshing and not being deleted" do
allow(@graph).to receive(:matching_edges).and_return([])
expect(@resource).to receive(:self_refresh?).and_return(true)
expect(@resource).to receive(:deleting?).and_return(false)
expect(@manager).to receive(:queue_events_for_resource).with(@resource, @resource, :refresh, [@event])
@manager.queue_events(@resource, [@event])
end
it "should not queue events for the changed resource if the resource is not self-refreshing" do
allow(@graph).to receive(:matching_edges).and_return([])
expect(@resource).to receive(:self_refresh?).and_return(false)
allow(@resource).to receive(:deleting?).and_return(false)
expect(@manager).not_to receive(:queue_events_for_resource)
@manager.queue_events(@resource, [@event])
end
it "should not queue events for the changed resource if the resource is being deleted" do
allow(@graph).to receive(:matching_edges).and_return([])
expect(@resource).to receive(:self_refresh?).and_return(true)
expect(@resource).to receive(:deleting?).and_return(true)
expect(@manager).not_to receive(:queue_events_for_resource)
@manager.queue_events(@resource, [@event])
end
it "should ignore edges that don't have a callback" do
edge1 = double("edge1", :callback => :nil, :source => double("s1"), :target => double("t1", :c1 => nil))
expect(@graph).to receive(:matching_edges).and_return([edge1])
expect(@manager).not_to receive(:queue_events_for_resource)
@manager.queue_events(@resource, [@event])
end
it "should ignore targets that don't respond to the callback" do
edge1 = double("edge1", :callback => :c1, :source => double("s1"), :target => double("t1"))
expect(@graph).to receive(:matching_edges).and_return([edge1])
expect(@manager).not_to receive(:queue_events_for_resource)
@manager.queue_events(@resource, [@event])
end
it "should dequeue events for the changed resource if an event with invalidate_refreshes is processed" do
@event2 = Puppet::Transaction::Event.new(:name => :foo, :resource => @resource, :invalidate_refreshes => true)
allow(@graph).to receive(:matching_edges).and_return([])
expect(@manager).to receive(:dequeue_events_for_resource).with(@resource, :refresh)
@manager.queue_events(@resource, [@event, @event2])
end
end
describe "when queueing events for a resource" do
before do
@transaction = double('transaction')
@manager = Puppet::Transaction::EventManager.new(@transaction)
end
it "should do nothing if no events are queued" do
@manager.queued_events(double("target")) { |callback, events| raise "should never reach this" }
end
it "should yield the callback and events for each callback" do
target = double("target")
2.times do |i|
@manager.queue_events_for_resource(double("source", :info => nil), target, "callback#{i}", ["event#{i}"])
end
@manager.queued_events(target) { |callback, events| }
end
it "should use the source to log that it's scheduling a refresh of the target" do
target = double("target")
source = double('source')
expect(source).to receive(:info)
@manager.queue_events_for_resource(source, target, "callback", ["event"])
@manager.queued_events(target) { |callback, events| }
end
end
describe "when processing events for a given resource" do
before do
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
@manager = Puppet::Transaction::EventManager.new(@transaction)
allow(@manager).to receive(:queue_events)
@resource = Puppet::Type.type(:file).new :path => make_absolute("/my/file")
@event = Puppet::Transaction::Event.new(:name => :event, :resource => @resource)
@resource.class.send(:define_method, :callback1) {}
@resource.class.send(:define_method, :callback2) {}
end
it "should call the required callback once for each set of associated events" do
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event]).and_yield(:callback2, [@event])
expect(@resource).to receive(:callback1)
expect(@resource).to receive(:callback2)
@manager.process_events(@resource)
end
it "should set the 'restarted' state on the resource status" do
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event])
allow(@resource).to receive(:callback1)
@manager.process_events(@resource)
expect(@transaction.resource_status(@resource)).to be_restarted
end
it "should have an event on the resource status" do
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event])
allow(@resource).to receive(:callback1)
@manager.process_events(@resource)
expect(@transaction.resource_status(@resource).events.length).to eq(1)
end
it "should queue a 'restarted' event generated by the resource" do
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event])
allow(@resource).to receive(:callback1)
expect(@resource).to receive(:event).with({:message => "Triggered 'callback1' from 1 event", :status => 'success', :name => 'callback1'})
expect(@resource).to receive(:event).with({:name => :restarted, :status => "success"}).and_return("myevent")
expect(@manager).to receive(:queue_events).with(@resource, ["myevent"])
@manager.process_events(@resource)
end
it "should log that it restarted" do
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event])
allow(@resource).to receive(:callback1)
expect(@resource).to receive(:notice).with(/Triggered 'callback1'/)
@manager.process_events(@resource)
end
describe "and the events include a noop event and at least one non-noop event" do
before do
allow(@event).to receive(:status).and_return("noop")
@event2 = Puppet::Transaction::Event.new(:name => :event, :resource => @resource)
@event2.status = "success"
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event, @event2])
@resource.class.send(:define_method, :callback1) {}
end
it "should call the callback" do
expect(@resource).to receive(:callback1)
@manager.process_events(@resource)
end
end
describe "and the events are all noop events" do
before do
allow(@event).to receive(:status).and_return("noop")
allow(@resource).to receive(:event).and_return(Puppet::Transaction::Event.new)
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event])
@resource.class.send(:define_method, :callback1) {}
end
it "should log" do
expect(@resource).to receive(:notice).with(/Would have triggered 'callback1'/)
@manager.process_events(@resource)
end
it "should not call the callback" do
expect(@resource).not_to receive(:callback1)
@manager.process_events(@resource)
end
it "should queue a new noop event generated from the resource" do
event = Puppet::Transaction::Event.new
expect(@resource).to receive(:event).with({:status => "noop", :name => :noop_restart}).and_return(event)
expect(@manager).to receive(:queue_events).with(@resource, [event])
@manager.process_events(@resource)
end
end
describe "and the resource has noop set to true" do
before do
allow(@event).to receive(:status).and_return("success")
allow(@resource).to receive(:event).and_return(Puppet::Transaction::Event.new)
allow(@resource).to receive(:noop?).and_return(true)
expect(@manager).to receive(:queued_events).with(@resource).and_yield(:callback1, [@event])
@resource.class.send(:define_method, :callback1) {}
end
it "should log" do
expect(@resource).to receive(:notice).with(/Would have triggered 'callback1'/)
@manager.process_events(@resource)
end
it "should not call the callback" do
expect(@resource).not_to receive(:callback1)
@manager.process_events(@resource)
end
it "should queue a new noop event generated from the resource" do
event = Puppet::Transaction::Event.new
expect(@resource).to receive(:event).with({:status => "noop", :name => :noop_restart}).and_return(event)
expect(@manager).to receive(:queue_events).with(@resource, [event])
@manager.process_events(@resource)
end
end
describe "and the callback fails" do
before do
@resource.class.send(:define_method, :callback1) { raise "a failure" }
expect(@manager).to receive(:queued_events).and_yield(:callback1, [@event])
end
it "should emit an error and log but not fail" do
expect(@resource).to receive(:err).with('Failed to call callback1: a failure').and_call_original
@manager.process_events(@resource)
expect(@logs).to include(an_object_having_attributes(level: :err, message: 'a failure'))
end
it "should set the 'failed_restarts' state on the resource status" do
@manager.process_events(@resource)
expect(@transaction.resource_status(@resource)).to be_failed_to_restart
end
it "should set the 'failed' state on the resource status" do
@manager.process_events(@resource)
expect(@transaction.resource_status(@resource)).to be_failed
end
it "should record a failed event on the resource status" do
@manager.process_events(@resource)
expect(@transaction.resource_status(@resource).events.length).to eq(1)
expect(@transaction.resource_status(@resource).events[0].status).to eq('failure')
end
it "should not queue a 'restarted' event" do
expect(@manager).not_to receive(:queue_events)
@manager.process_events(@resource)
end
it "should set the 'restarted' state on the resource status" do
@manager.process_events(@resource)
expect(@transaction.resource_status(@resource)).not_to be_restarted
end
end
end
describe "when queueing then processing events for a given resource" do
before do
@catalog = Puppet::Resource::Catalog.new
@target = Puppet::Type.type(:exec).new(name: 'target', path: ENV['PATH'])
@resource = Puppet::Type.type(:exec).new(name: 'resource', path: ENV['PATH'], notify: @target)
@catalog.add_resource(@resource, @target)
@manager = Puppet::Transaction::EventManager.new(Puppet::Transaction.new(@catalog, nil, nil))
@event = Puppet::Transaction::Event.new(:name => :notify, :resource => @target)
@event2 = Puppet::Transaction::Event.new(:name => :service_start, :resource => @target, :invalidate_refreshes => true)
end
it "should succeed when there's no invalidated event" do
@manager.queue_events(@target, [@event2])
end
describe "and the events were dequeued/invalidated" do
before do
expect(@resource).to receive(:info).with(/Scheduling refresh/)
expect(@target).to receive(:info).with(/Unscheduling/)
end
it "should not run an event or log" do
expect(@target).not_to receive(:notice).with(/Would have triggered 'refresh'/)
expect(@target).not_to receive(:refresh)
@manager.queue_events(@resource, [@event])
@manager.queue_events(@target, [@event2])
@manager.process_events(@resource)
@manager.process_events(@target)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/transaction/persistence_spec.rb | spec/unit/transaction/persistence_spec.rb | require 'spec_helper'
require 'yaml'
require 'fileutils'
require 'puppet/transaction/persistence'
describe Puppet::Transaction::Persistence do
include PuppetSpec::Files
before(:each) do
@basepath = File.expand_path("/somepath")
end
describe "when loading from file" do
before do
allow(Puppet.settings).to receive(:use).and_return(true)
end
describe "when the file/directory does not exist" do
before(:each) do
@path = tmpfile('storage_test')
end
it "should not fail to load" do
expect(Puppet::FileSystem.exist?(@path)).to be_falsey
Puppet[:statedir] = @path
persistence = Puppet::Transaction::Persistence.new
persistence.load
Puppet[:transactionstorefile] = @path
persistence = Puppet::Transaction::Persistence.new
persistence.load
end
end
describe "when the file/directory exists" do
before(:each) do
@tmpfile = tmpfile('storage_test')
Puppet[:transactionstorefile] = @tmpfile
end
def write_state_file(contents)
File.open(@tmpfile, 'w') { |f| f.write(contents) }
end
it "should overwrite its internal state if load() is called" do
resource = "Foo[bar]"
property = "my"
value = "something"
expect(Puppet).not_to receive(:err)
persistence = Puppet::Transaction::Persistence.new
persistence.set_system_value(resource, property, value)
persistence.load
expect(persistence.get_system_value(resource, property)).to eq(nil)
end
it "should restore its internal state if the file contains valid YAML" do
test_yaml = {"resources"=>{"a"=>"b"}}
write_state_file(test_yaml.to_yaml)
expect(Puppet).not_to receive(:err)
persistence = Puppet::Transaction::Persistence.new
persistence.load
expect(persistence.data).to eq(test_yaml)
end
it "should initialize with a clear internal state if the file does not contain valid YAML" do
write_state_file('{ invalid')
expect(Puppet).to receive(:send_log).with(:err, /Transaction store file .* is corrupt/)
persistence = Puppet::Transaction::Persistence.new
persistence.load
expect(persistence.data).to eq({})
end
it "should initialize with a clear internal state if the file does not contain a hash of data" do
write_state_file("not_a_hash")
expect(Puppet).to receive(:err).with(/Transaction store file .* is valid YAML but not returning a hash/)
persistence = Puppet::Transaction::Persistence.new
persistence.load
expect(persistence.data).to eq({})
end
it "should raise an error if the file does not contain valid YAML and cannot be renamed" do
write_state_file('{ invalid')
expect(File).to receive(:rename).and_raise(SystemCallError)
expect(Puppet).to receive(:send_log).with(:err, /Transaction store file .* is corrupt/)
expect(Puppet).to receive(:send_log).with(:err, /Unable to rename/)
persistence = Puppet::Transaction::Persistence.new
expect { persistence.load }.to raise_error(Puppet::Error, /Could not rename/)
end
it "should attempt to rename the file if the file is corrupted" do
write_state_file('{ invalid')
expect(File).to receive(:rename).at_least(:once)
expect(Puppet).to receive(:send_log).with(:err, /Transaction store file .* is corrupt/)
persistence = Puppet::Transaction::Persistence.new
persistence.load
end
it "should fail gracefully on load() if the file is not a regular file" do
FileUtils.rm_f(@tmpfile)
Dir.mkdir(@tmpfile)
expect(Puppet).to receive(:warning).with(/Transaction store file .* is not a file/)
persistence = Puppet::Transaction::Persistence.new
persistence.load
end
it 'should load Time and Symbols' do
write_state_file(<<~END)
File[/tmp/audit]:
parameters:
mtime:
system_value:
- 2020-07-15 05:38:12.427678398 +00:00
ensure:
system_value:
END
persistence = Puppet::Transaction::Persistence.new
expect(persistence.load.dig("File[/tmp/audit]", "parameters", "mtime", "system_value")).to contain_exactly(be_a(Time))
end
it 'should load Regexp' do
write_state_file(<<~END)
system_value:
- !ruby/regexp /regexp/
END
persistence = Puppet::Transaction::Persistence.new
expect(persistence.load.dig("system_value")).to contain_exactly(be_a(Regexp))
end
it 'should load semantic puppet version' do
write_state_file(<<~END)
system_value:
- !ruby/object:SemanticPuppet::Version
major: 1
minor: 0
patch: 0
prerelease:
build:
END
persistence = Puppet::Transaction::Persistence.new
expect(persistence.load.dig("system_value")).to contain_exactly(be_a(SemanticPuppet::Version))
end
it 'should load puppet time related objects' do
write_state_file(<<~END)
system_value:
- !ruby/object:Puppet::Pops::Time::Timestamp
nsecs: 1638316135955087259
- !ruby/object:Puppet::Pops::Time::TimeData
nsecs: 1495789430910161286
- !ruby/object:Puppet::Pops::Time::Timespan
nsecs: 1495789430910161286
END
persistence = Puppet::Transaction::Persistence.new
expect(persistence.load.dig("system_value")).to contain_exactly(be_a(Puppet::Pops::Time::Timestamp), be_a(Puppet::Pops::Time::TimeData), be_a(Puppet::Pops::Time::Timespan))
end
it 'should load binary objects' do
write_state_file(<<~END)
system_value:
- !ruby/object:Puppet::Pops::Types::PBinaryType::Binary
binary_buffer: ''
END
persistence = Puppet::Transaction::Persistence.new
expect(persistence.load.dig("system_value")).to contain_exactly(be_a(Puppet::Pops::Types::PBinaryType::Binary))
end
end
end
describe "when storing to the file" do
before(:each) do
@tmpfile = tmpfile('persistence_test')
@saved = Puppet[:transactionstorefile]
Puppet[:transactionstorefile] = @tmpfile
end
it "should create the file if it does not exist" do
expect(Puppet::FileSystem.exist?(Puppet[:transactionstorefile])).to be_falsey
persistence = Puppet::Transaction::Persistence.new
persistence.save
expect(Puppet::FileSystem.exist?(Puppet[:transactionstorefile])).to be_truthy
end
it "should raise an exception if the file is not a regular file" do
Dir.mkdir(Puppet[:transactionstorefile])
persistence = Puppet::Transaction::Persistence.new
expect { persistence.save }.to raise_error(Errno::EISDIR, /Is a directory/)
Dir.rmdir(Puppet[:transactionstorefile])
end
it "should load the same information that it saves" do
resource = "File[/tmp/foo]"
property = "content"
value = "foo"
persistence = Puppet::Transaction::Persistence.new
persistence.set_system_value(resource, property, value)
persistence.save
persistence.load
expect(persistence.get_system_value(resource, property)).to eq(value)
end
end
describe "when checking if persistence is enabled" do
let(:mock_catalog) do
double()
end
let (:persistence) do
Puppet::Transaction::Persistence.new
end
before :all do
@preferred_run_mode = Puppet.settings.preferred_run_mode
end
after :all do
Puppet.settings.preferred_run_mode = @preferred_run_mode
end
it "should not be enabled when not running in agent mode" do
Puppet.settings.preferred_run_mode = :user
allow(mock_catalog).to receive(:host_config?).and_return(true)
expect(persistence.enabled?(mock_catalog)).to be false
end
it "should not be enabled when the catalog is not the host catalog" do
Puppet.settings.preferred_run_mode = :agent
allow(mock_catalog).to receive(:host_config?).and_return(false)
expect(persistence.enabled?(mock_catalog)).to be false
end
it "should not be enabled outside of agent mode and the catalog is not the host catalog" do
Puppet.settings.preferred_run_mode = :user
allow(mock_catalog).to receive(:host_config?).and_return(false)
expect(persistence.enabled?(mock_catalog)).to be false
end
it "should be enabled in agent mode and when the catalog is the host catalog" do
Puppet.settings.preferred_run_mode = :agent
allow(mock_catalog).to receive(:host_config?).and_return(true)
expect(persistence.enabled?(mock_catalog)).to be true
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface/action_spec.rb | spec/unit/interface/action_spec.rb | require 'spec_helper'
require 'puppet/interface'
describe Puppet::Interface::Action do
describe "when validating the action name" do
[nil, '', 'foo bar', '-foobar'].each do |input|
it "should treat #{input.inspect} as an invalid name" do
expect {
Puppet::Interface::Action.new(nil, input)
}.to raise_error(/is an invalid action name/)
end
end
end
describe "#when_invoked=" do
it "should fail if the block has arity 0" do
expect {
Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked { }
end
end
}.to raise_error ArgumentError, /foo/
end
it "should work with arity 1 blocks" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|one| }
end
end
# -1, because we use option defaulting. :(
expect(face.method(:foo).arity).to eq(-1)
end
it "should work with arity 2 blocks" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|one, two| }
end
end
# -2, because we use option defaulting. :(
expect(face.method(:foo).arity).to eq(-2)
end
it "should work with arity 1 blocks that collect arguments" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|*one| }
end
end
# -1, because we use only varargs
expect(face.method(:foo).arity).to eq(-1)
end
it "should work with arity 2 blocks that collect arguments" do
face = Puppet::Interface.new(:action_when_invoked, '1.0.0') do
action :foo do
when_invoked {|one, *two| }
end
end
# -2, because we take one mandatory argument, and one varargs
expect(face.method(:foo).arity).to eq(-2)
end
end
describe "when invoking" do
it "should be able to call other actions on the same object" do
face = Puppet::Interface.new(:my_face, '0.0.1') do
action(:foo) do
when_invoked { |options| 25 }
end
action(:bar) do
when_invoked { |options| "the value of foo is '#{foo}'" }
end
end
expect(face.foo).to eq(25)
expect(face.bar).to eq("the value of foo is '25'")
end
# bar is a class action calling a class action
# quux is a class action calling an instance action
# baz is an instance action calling a class action
# qux is an instance action calling an instance action
it "should be able to call other actions on the same object when defined on a class" do
class Puppet::Interface::MyInterfaceBaseClass < Puppet::Interface
action(:foo) do
when_invoked { |options| 25 }
end
action(:bar) do
when_invoked { |options| "the value of foo is '#{foo}'" }
end
action(:quux) do
when_invoked { |options| "qux told me #{qux}" }
end
end
face = Puppet::Interface::MyInterfaceBaseClass.new(:my_inherited_face, '0.0.1') do
action(:baz) do
when_invoked { |options| "the value of foo in baz is '#{foo}'" }
end
action(:qux) do
when_invoked { |options| baz }
end
end
expect(face.foo).to eq(25)
expect(face.bar).to eq("the value of foo is '25'")
expect(face.quux).to eq("qux told me the value of foo in baz is '25'")
expect(face.baz).to eq("the value of foo in baz is '25'")
expect(face.qux).to eq("the value of foo in baz is '25'")
end
context "when calling the Ruby API" do
let :face do
Puppet::Interface.new(:ruby_api, '1.0.0') do
action :bar do
option "--bar"
when_invoked do |*args|
args.last
end
end
end
end
it "should work when no options are supplied" do
options = face.bar
expect(options).to eq({})
end
it "should work when options are supplied" do
options = face.bar(:bar => "beer")
expect(options).to eq({ :bar => "beer" })
end
it "should call #validate_and_clean on the action when invoked" do
expect(face.get_action(:bar)).to receive(:validate_and_clean).with({}).and_return({})
face.bar 1, :two, 'three'
end
end
end
describe "with action-level options" do
it "should support options with an empty block" do
face = Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do
when_invoked do |options| true end
option "--bar" do
# this line left deliberately blank
end
end
end
expect(face).not_to be_option :bar
expect(face.get_action(:foo)).to be_option :bar
end
it "should return only action level options when there are no face options" do
face = Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do
when_invoked do |options| true end
option "--bar"
end
end
expect(face.get_action(:foo).options).to match_array([:bar])
end
describe "option aliases" do
let :option do action.get_option :bar end
let :action do face.get_action :foo end
let :face do
Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do
when_invoked do |options| options end
option "--bar", "--foo", "-b"
end
end
end
it "should only list options and not aliases" do
expect(action.options).to match_array([:bar])
end
it "should use the canonical option name when passed aliases" do
name = option.name
option.aliases.each do |input|
expect(face.foo(input => 1)).to eq({ name => 1 })
end
end
end
describe "with both face and action options" do
let :face do
Puppet::Interface.new(:action_level_options, '0.0.1') do
action :foo do when_invoked do |options| true end ; option "--bar" end
action :baz do when_invoked do |options| true end ; option "--bim" end
option "--quux"
end
end
it "should return combined face and action options" do
expect(face.get_action(:foo).options).to match_array([:bar, :quux])
end
it "should fetch options that the face inherited" do
parent = Class.new(Puppet::Interface)
parent.option "--foo"
child = parent.new(:inherited_options, '0.0.1') do
option "--bar"
action :action do
when_invoked do |options| true end
option "--baz"
end
end
action = child.get_action(:action)
expect(action).to be
[:baz, :bar, :foo].each do |name|
expect(action.get_option(name)).to be_an_instance_of Puppet::Interface::Option
end
end
it "should get an action option when asked" do
expect(face.get_action(:foo).get_option(:bar)).
to be_an_instance_of Puppet::Interface::Option
end
it "should get a face option when asked" do
expect(face.get_action(:foo).get_option(:quux)).
to be_an_instance_of Puppet::Interface::Option
end
it "should return options only for this action" do
expect(face.get_action(:baz).options).to match_array([:bim, :quux])
end
end
it_should_behave_like "things that declare options" do
def add_options_to(&block)
face = Puppet::Interface.new(:with_options, '0.0.1') do
action(:foo) do
when_invoked do |options| true end
self.instance_eval(&block)
end
end
face.get_action(:foo)
end
end
it "should fail when a face option duplicates an action option" do
expect {
Puppet::Interface.new(:action_level_options, '0.0.1') do
option "--foo"
action :bar do option "--foo" end
end
}.to raise_error ArgumentError, /Option foo conflicts with existing option foo/i
end
it "should fail when a required action option is not provided" do
face = Puppet::Interface.new(:required_action_option, '0.0.1') do
action(:bar) do
option('--foo') { required }
when_invoked {|options| }
end
end
expect { face.bar }.to raise_error ArgumentError, /The following options are required: foo/
end
it "should fail when a required face option is not provided" do
face = Puppet::Interface.new(:required_face_option, '0.0.1') do
option('--foo') { required }
action(:bar) { when_invoked {|options| } }
end
expect { face.bar }.to raise_error ArgumentError, /The following options are required: foo/
end
end
context "with decorators" do
context "declared locally" do
let :face do
Puppet::Interface.new(:action_decorators, '0.0.1') do
action :bar do when_invoked do |options| true end end
def reported; @reported; end
def report(arg)
(@reported ||= []) << arg
end
end
end
it "should execute before advice on action options in declaration order" do
face.action(:boo) do
option("--foo") { before_action { |_,_,_| report :foo } }
option("--bar", '-b') { before_action { |_,_,_| report :bar } }
option("-q", "--quux") { before_action { |_,_,_| report :quux } }
option("-f") { before_action { |_,_,_| report :f } }
option("--baz") { before_action { |_,_,_| report :baz } }
when_invoked {|options| }
end
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ])
end
it "should execute after advice on action options in declaration order" do
face.action(:boo) do
option("--foo") { after_action { |_,_,_| report :foo } }
option("--bar", '-b') { after_action { |_,_,_| report :bar } }
option("-q", "--quux") { after_action { |_,_,_| report :quux } }
option("-f") { after_action { |_,_,_| report :f } }
option("--baz") { after_action { |_,_,_| report :baz } }
when_invoked {|options| }
end
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ].reverse)
end
it "should execute before advice on face options in declaration order" do
face.instance_eval do
option("--foo") { before_action { |_,_,_| report :foo } }
option("--bar", '-b') { before_action { |_,_,_| report :bar } }
option("-q", "--quux") { before_action { |_,_,_| report :quux } }
option("-f") { before_action { |_,_,_| report :f } }
option("--baz") { before_action { |_,_,_| report :baz } }
end
face.action(:boo) { when_invoked { |options| } }
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ])
end
it "should execute after advice on face options in declaration order" do
face.instance_eval do
option("--foo") { after_action { |_,_,_| report :foo } }
option("--bar", '-b') { after_action { |_,_,_| report :bar } }
option("-q", "--quux") { after_action { |_,_,_| report :quux } }
option("-f") { after_action { |_,_,_| report :f } }
option("--baz") { after_action { |_,_,_| report :baz } }
end
face.action(:boo) { when_invoked { |options| } }
face.boo :foo => 1, :bar => 1, :quux => 1, :f => 1, :baz => 1
expect(face.reported).to eq([ :foo, :bar, :quux, :f, :baz ].reverse)
end
it "should execute before advice on face options before action options" do
face.instance_eval do
option("--face-foo") { before_action { |_,_,_| report :face_foo } }
option("--face-bar", '-r') { before_action { |_,_,_| report :face_bar } }
action(:boo) do
option("--action-foo") { before_action { |_,_,_| report :action_foo } }
option("--action-bar", '-b') { before_action { |_,_,_| report :action_bar } }
option("-q", "--action-quux") { before_action { |_,_,_| report :action_quux } }
option("-a") { before_action { |_,_,_| report :a } }
option("--action-baz") { before_action { |_,_,_| report :action_baz } }
when_invoked {|options| }
end
option("-u", "--face-quux") { before_action { |_,_,_| report :face_quux } }
option("-f") { before_action { |_,_,_| report :f } }
option("--face-baz") { before_action { |_,_,_| report :face_baz } }
end
expected_calls = [ :face_foo, :face_bar, :face_quux, :f, :face_baz,
:action_foo, :action_bar, :action_quux, :a, :action_baz ]
face.boo Hash[ *expected_calls.zip([]).flatten ]
expect(face.reported).to eq(expected_calls)
end
it "should execute after advice on face options in declaration order" do
face.instance_eval do
option("--face-foo") { after_action { |_,_,_| report :face_foo } }
option("--face-bar", '-r') { after_action { |_,_,_| report :face_bar } }
action(:boo) do
option("--action-foo") { after_action { |_,_,_| report :action_foo } }
option("--action-bar", '-b') { after_action { |_,_,_| report :action_bar } }
option("-q", "--action-quux") { after_action { |_,_,_| report :action_quux } }
option("-a") { after_action { |_,_,_| report :a } }
option("--action-baz") { after_action { |_,_,_| report :action_baz } }
when_invoked {|options| }
end
option("-u", "--face-quux") { after_action { |_,_,_| report :face_quux } }
option("-f") { after_action { |_,_,_| report :f } }
option("--face-baz") { after_action { |_,_,_| report :face_baz } }
end
expected_calls = [ :face_foo, :face_bar, :face_quux, :f, :face_baz,
:action_foo, :action_bar, :action_quux, :a, :action_baz ]
face.boo Hash[ *expected_calls.zip([]).flatten ]
expect(face.reported).to eq(expected_calls.reverse)
end
it "should not invoke a decorator if the options are empty" do
face.option("--foo FOO") { before_action { |_,_,_| report :before_action } }
expect(face).not_to receive(:report)
face.bar
end
context "passing a subset of the options" do
before :each do
face.option("--foo") { before_action { |_,_,_| report :foo } }
face.option("--bar") { before_action { |_,_,_| report :bar } }
end
it "should invoke only foo's advice when passed only 'foo'" do
face.bar(:foo => true)
expect(face.reported).to eq([ :foo ])
end
it "should invoke only bar's advice when passed only 'bar'" do
face.bar(:bar => true)
expect(face.reported).to eq([ :bar ])
end
it "should invoke advice for all passed options" do
face.bar(:foo => true, :bar => true)
expect(face.reported).to eq([ :foo, :bar ])
end
end
end
context "and inheritance" do
let :parent do
Class.new(Puppet::Interface) do
action(:on_parent) { when_invoked { |options| :on_parent } }
def reported; @reported; end
def report(arg)
(@reported ||= []) << arg
end
end
end
let :child do
parent.new(:inherited_decorators, '0.0.1') do
action(:on_child) { when_invoked { |options| :on_child } }
end
end
context "locally declared face options" do
subject do
child.option("--foo=") { before_action { |_,_,_| report :child_before } }
child
end
it "should be invoked when calling a child action" do
expect(subject.on_child(:foo => true)).to eq(:on_child)
expect(subject.reported).to eq([ :child_before ])
end
it "should be invoked when calling a parent action" do
expect(subject.on_parent(:foo => true)).to eq(:on_parent)
expect(subject.reported).to eq([ :child_before ])
end
end
context "inherited face option decorators" do
subject do
parent.option("--foo=") { before_action { |_,_,_| report :parent_before } }
child
end
it "should be invoked when calling a child action" do
expect(subject.on_child(:foo => true)).to eq(:on_child)
expect(subject.reported).to eq([ :parent_before ])
end
it "should be invoked when calling a parent action" do
expect(subject.on_parent(:foo => true)).to eq(:on_parent)
expect(subject.reported).to eq([ :parent_before ])
end
end
context "with both inherited and local face options" do
# Decorations should be invoked in declaration order, according to
# inheritance (e.g. parent class options should be handled before
# subclass options).
subject do
child.option "-c" do
before_action { |action, args, options| report :c_before }
after_action { |action, args, options| report :c_after }
end
parent.option "-a" do
before_action { |action, args, options| report :a_before }
after_action { |action, args, options| report :a_after }
end
child.option "-d" do
before_action { |action, args, options| report :d_before }
after_action { |action, args, options| report :d_after }
end
parent.option "-b" do
before_action { |action, args, options| report :b_before }
after_action { |action, args, options| report :b_after }
end
child.action(:decorations) { when_invoked { |options| report :invoked } }
child
end
it "should invoke all decorations when calling a child action" do
subject.decorations(:a => 1, :b => 1, :c => 1, :d => 1)
expect(subject.reported).to eq([
:a_before, :b_before, :c_before, :d_before,
:invoked,
:d_after, :c_after, :b_after, :a_after
])
end
it "should invoke all decorations when calling a parent action" do
subject.decorations(:a => 1, :b => 1, :c => 1, :d => 1)
expect(subject.reported).to eq([
:a_before, :b_before, :c_before, :d_before,
:invoked,
:d_after, :c_after, :b_after, :a_after
])
end
end
end
end
it_should_behave_like "documentation on faces" do
subject do
face = Puppet::Interface.new(:action_documentation, '0.0.1') do
action :documentation do
when_invoked do |options| true end
end
end
face.get_action(:documentation)
end
end
context "#validate_and_clean" do
subject do
Puppet::Interface.new(:validate_args, '1.0.0') do
action(:test) { when_invoked { |options| options } }
end
end
it "should fail if a required option is not passed" do
subject.option "--foo" do required end
expect { subject.test }.to raise_error ArgumentError, /options are required/
end
it "should fail if two aliases to one option are passed" do
subject.option "--foo", "-f"
expect { subject.test :foo => true, :f => true }.
to raise_error ArgumentError, /Multiple aliases for the same option/
end
it "should fail if an unknown option is passed" do
expect { subject.test :unknown => true }.
to raise_error ArgumentError, /Unknown options passed: unknown/
end
it "should report all the unknown options passed" do
expect { subject.test :unknown => true, :unseen => false }.
to raise_error ArgumentError, /Unknown options passed: unknown, unseen/
end
it "should accept 'global' options from settings" do
expect {
expect(subject.test(:certname => "true")).to eq({ :certname => "true" })
}.not_to raise_error
end
end
context "default option values" do
subject do
Puppet::Interface.new(:default_option_values, '1.0.0') do
action :foo do
option "--foo" do end
option "--bar" do end
when_invoked do |options| options end
end
end
end
let :action do subject.get_action :foo end
let :option do action.get_option :foo end
it "should not add options without defaults" do
expect(subject.foo).to eq({})
end
it "should not add options without defaults, if options are given" do
expect(subject.foo(:bar => 1)).to eq({ :bar => 1 })
end
it "should add the option default value when set" do
option.default = proc { 12 }
expect(subject.foo).to eq({ :foo => 12 })
end
it "should add the option default value when set, if other options are given" do
option.default = proc { 12 }
expect(subject.foo(:bar => 1)).to eq({ :foo => 12, :bar => 1 })
end
it "should invoke the same default proc every time called" do
option.default = proc { @foo ||= {} }
expect(subject.foo[:foo].object_id).to eq(subject.foo[:foo].object_id)
end
[nil, 0, 1, true, false, {}, []].each do |input|
it "should not override a passed option (#{input.inspect})" do
option.default = proc { :fail }
expect(subject.foo(:foo => input)).to eq({ :foo => input })
end
end
end
context "runtime manipulations" do
subject do
Puppet::Interface.new(:runtime_manipulations, '1.0.0') do
action :foo do
when_invoked do |options| options end
end
end
end
let :action do subject.get_action :foo end
it "should be the face default action if default is set true" do
expect(subject.get_default_action).to be_nil
action.default = true
expect(subject.get_default_action).to eq(action)
end
end
context "when deprecating a face action" do
let :face do
Puppet::Interface.new(:foo, '1.0.0') do
action :bar do
option "--bar"
when_invoked do |options| options end
end
end
end
let :action do face.get_action :bar end
describe "#deprecate" do
it "should set the deprecated value to true" do
expect(action).not_to be_deprecated
action.deprecate
expect(action).to be_deprecated
end
end
describe "#deprecated?" do
it "should return a nil (falsey) value by default" do
expect(action.deprecated?).to be_falsey
end
it "should return true if the action has been deprecated" do
expect(action).not_to be_deprecated
action.deprecate
expect(action).to be_deprecated
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface/documentation_spec.rb | spec/unit/interface/documentation_spec.rb | require 'spec_helper'
require 'puppet/interface'
class Puppet::Interface::TinyDocs::Test
include Puppet::Interface::TinyDocs
attr_accessor :name, :options, :display_global_options
def initialize
self.name = "tinydoc-test"
self.options = []
self.display_global_options = []
end
def get_option(name)
Puppet::Interface::Option.new(nil, "--#{name}")
end
end
describe Puppet::Interface::TinyDocs do
subject { Puppet::Interface::TinyDocs::Test.new }
context "#build_synopsis" do
before :each do
subject.options = [:foo, :bar]
end
it { is_expected.to respond_to :build_synopsis }
it "should put a space between options (#7828)" do
expect(subject.build_synopsis('baz')).to match(/#{Regexp.quote('[--foo] [--bar]')}/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface/action_builder_spec.rb | spec/unit/interface/action_builder_spec.rb | require 'spec_helper'
require 'puppet/interface'
require 'puppet/network/format_handler'
describe Puppet::Interface::ActionBuilder do
let :face do Puppet::Interface.new(:puppet_interface_actionbuilder, '0.0.1') end
it "should build an action" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
end
expect(action).to be_a(Puppet::Interface::Action)
expect(action.name).to eq(:foo)
end
it "should define a method on the face which invokes the action" do
face = Puppet::Interface.new(:action_builder_test_interface, '0.0.1') do
action(:foo) { when_invoked { |options| "invoked the method" } }
end
expect(face.foo).to eq("invoked the method")
end
it "should require a block" do
expect {
Puppet::Interface::ActionBuilder.build(nil, :foo)
}.to raise_error("Action :foo must specify a block")
end
it "should require an invocation block" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) {}
}.to raise_error(/actions need to know what to do when_invoked; please add the block/)
end
describe "when handling options" do
it "should have a #option DSL function" do
method = nil
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
method = self.method(:option)
end
expect(method).to be_an_instance_of Method
end
it "should define an option without a block" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
option "--bar"
end
expect(action).to be_option :bar
end
it "should accept an empty block" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
option "--bar" do
# This space left deliberately blank.
end
end
expect(action).to be_option :bar
end
end
context "inline documentation" do
it "should set the summary" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
summary "this is some text"
end
expect(action.summary).to eq("this is some text")
end
end
context "action defaulting" do
it "should set the default to true" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
default
end
expect(action.default).to be_truthy
end
it "should not be default by, er, default. *cough*" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
end
expect(action.default).to be_falsey
end
end
context "#when_rendering" do
it "should fail if no rendering format is given" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering do true end
end
}.to raise_error ArgumentError, /must give a rendering format to when_rendering/
end
it "should fail if no block is given" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json
end
}.to raise_error ArgumentError, /must give a block to when_rendering/
end
it "should fail if the block takes no arguments" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do true end
end
}.to raise_error ArgumentError,
/the puppet_interface_actionbuilder face foo action takes .* not/
end
it "should fail if the when_rendering block takes a different number of arguments than when_invoked" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a, b, c| true end
end
}.to raise_error ArgumentError,
/the puppet_interface_actionbuilder face foo action takes .* not 3/
end
it "should fail if the block takes a variable number of arguments" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |*args| true end
end
}.to raise_error ArgumentError,
/the puppet_interface_actionbuilder face foo action takes .* not/
end
it "should stash a rendering block" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| true end
end
expect(action.when_rendering(:json)).to be_an_instance_of Method
end
it "should fail if you try to set the same rendering twice" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| true end
when_rendering :json do |a| true end
end
}.to raise_error ArgumentError, /You can't define a rendering method for json twice/
end
it "should work if you set two different renderings" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| true end
when_rendering :yaml do |a| true end
end
expect(action.when_rendering(:json)).to be_an_instance_of Method
expect(action.when_rendering(:yaml)).to be_an_instance_of Method
end
it "should be bound to the face when called" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
when_rendering :json do |a| self end
end
expect(action.when_rendering(:json).call(true)).to eq(face)
end
end
context "#render_as" do
it "should default to nil (eg: based on context)" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
end
expect(action.render_as).to be_nil
end
it "should fail if not rendering format is given" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
render_as
end
}.to raise_error ArgumentError, /must give a rendering format to render_as/
end
Puppet::Network::FormatHandler.formats.each do |name|
it "should accept #{name.inspect} format" do
action = Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
render_as name
end
expect(action.render_as).to eq(name)
end
end
[:if_you_define_this_format_you_frighten_me, "json", 12].each do |input|
it "should fail if given #{input.inspect}" do
expect {
Puppet::Interface::ActionBuilder.build(face, :foo) do
when_invoked do |options| true end
render_as input
end
}.to raise_error ArgumentError, /#{input.inspect} is not a valid rendering format/
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface/option_spec.rb | spec/unit/interface/option_spec.rb | require 'spec_helper'
require 'puppet/interface'
describe Puppet::Interface::Option do
let :face do Puppet::Interface.new(:option_testing, '0.0.1') end
describe "#optparse_to_name" do
["", "=BAR", " BAR", "=bar", " bar"].each do |postfix|
{ "--foo" => :foo, "-f" => :f }.each do |base, expect|
input = base + postfix
it "should map #{input.inspect} to #{expect.inspect}" do
option = Puppet::Interface::Option.new(face, input)
expect(option.name).to eq(expect)
end
end
end
[:foo, 12, nil, {}, []].each do |input|
it "should fail sensible when given #{input.inspect}" do
expect {
Puppet::Interface::Option.new(face, input)
}.to raise_error ArgumentError, /is not valid for an option argument/
end
end
["-foo", "-foo=BAR", "-foo BAR"].each do |input|
it "should fail with a single dash for long option #{input.inspect}" do
expect {
Puppet::Interface::Option.new(face, input)
}.to raise_error ArgumentError, /long options need two dashes \(--\)/
end
end
end
it "requires a face when created" do
expect {
Puppet::Interface::Option.new
}.to raise_error ArgumentError, /wrong number of arguments/
end
it "also requires some declaration arguments when created" do
expect {
Puppet::Interface::Option.new(face)
}.to raise_error ArgumentError, /No option declarations found/
end
it "should infer the name from an optparse string" do
option = Puppet::Interface::Option.new(face, "--foo")
expect(option.name).to eq(:foo)
end
it "should infer the name when multiple optparse string are given" do
option = Puppet::Interface::Option.new(face, "--foo", "-f")
expect(option.name).to eq(:foo)
end
it "should prefer the first long option name over a short option name" do
option = Puppet::Interface::Option.new(face, "-f", "--foo")
expect(option.name).to eq(:foo)
end
it "should create an instance when given a face and name" do
expect(Puppet::Interface::Option.new(face, "--foo")).
to be_instance_of Puppet::Interface::Option
end
Puppet.settings.each do |name, value|
it "should fail when option #{name.inspect} already exists in puppet core" do
expect do
Puppet::Interface::Option.new(face, "--#{name}")
end.to raise_error ArgumentError, /already defined/
end
end
describe "#to_s" do
it "should transform a symbol into a string" do
option = Puppet::Interface::Option.new(face, "--foo")
expect(option.name).to eq(:foo)
expect(option.to_s).to eq("foo")
end
it "should use - rather than _ to separate words in strings but not symbols" do
option = Puppet::Interface::Option.new(face, "--foo-bar")
expect(option.name).to eq(:foo_bar)
expect(option.to_s).to eq("foo-bar")
end
end
%w{before after}.each do |side|
describe "#{side} hooks" do
subject { Puppet::Interface::Option.new(face, "--foo") }
let :proc do Proc.new do :from_proc end end
it { is_expected.to respond_to "#{side}_action" }
it { is_expected.to respond_to "#{side}_action=" }
it "should set the #{side}_action hook" do
expect(subject.send("#{side}_action")).to be_nil
subject.send("#{side}_action=", proc)
expect(subject.send("#{side}_action")).to be_an_instance_of UnboundMethod
end
data = [1, "foo", :foo, Object.new, method(:hash), method(:hash).unbind]
data.each do |input|
it "should fail if a #{input.class} is added to the #{side} hooks" do
expect { subject.send("#{side}_action=", input) }.
to raise_error ArgumentError, /not a proc/
end
end
end
end
context "defaults" do
subject { Puppet::Interface::Option.new(face, "--foo") }
it "should work sanely if member variables are used for state" do
subject.default = proc { @foo ||= 0; @foo += 1 }
expect(subject.default).to eq(1)
expect(subject.default).to eq(2)
expect(subject.default).to eq(3)
end
context "with no default" do
it { is_expected.not_to be_has_default }
its :default do should be_nil end
it "should set a proc as default" do
expect { subject.default = proc { 12 } }.to_not raise_error
end
[1, {}, [], Object.new, "foo"].each do |input|
it "should reject anything but a proc (#{input.class})" do
expect { subject.default = input }.to raise_error ArgumentError, /not a proc/
end
end
end
context "with a default" do
before :each do subject.default = proc { [:foo] } end
it { is_expected.to be_has_default }
its :default do should == [:foo] end
it "should invoke the block every time" do
expect(subject.default.object_id).not_to eq(subject.default.object_id)
expect(subject.default).to eq(subject.default)
end
it "should allow replacing the default proc" do
expect(subject.default).to eq([:foo])
subject.default = proc { :bar }
expect(subject.default).to eq(:bar)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface/face_collection_spec.rb | spec/unit/interface/face_collection_spec.rb | require 'spec_helper'
require 'tmpdir'
require 'puppet/interface'
describe Puppet::Interface::FaceCollection do
# To prevent conflicts with other specs that use faces, we must save and restore global state.
# Because there are specs that do 'describe Puppet::Face[...]', we must restore the same objects otherwise
# the 'subject' of the specs will differ.
before :all do
# Save FaceCollection's global state
faces = described_class.instance_variable_get(:@faces)
@faces = faces.dup
faces.each do |k, v|
@faces[k] = v.dup
end
@faces_loaded = described_class.instance_variable_get(:@loaded)
# Save the already required face files
@required = []
$".each do |path|
@required << path if path =~ /face\/.*\.rb$/
end
# Save Autoload's global state
@loaded = Puppet::Util::Autoload.instance_variable_get(:@loaded).dup
end
after :all do
# Restore global state
described_class.instance_variable_set :@faces, @faces
described_class.instance_variable_set :@loaded, @faces_loaded
$".delete_if { |path| path =~ /face\/.*\.rb$/ }
@required.each { |path| $".push path unless $".include? path }
Puppet::Util::Autoload.instance_variable_set(:@loaded, @loaded)
end
before :each do
# Before each test, clear the faces
subject.instance_variable_get(:@faces).clear
subject.instance_variable_set(:@loaded, false)
Puppet::Util::Autoload.instance_variable_get(:@loaded).clear
$".delete_if { |path| path =~ /face\/.*\.rb$/ }
end
describe "::[]" do
before :each do
subject.instance_variable_get("@faces")[:foo][SemanticPuppet::Version.parse('0.0.1')] = 10
end
it "should return the face with the given name" do
expect(subject["foo", '0.0.1']).to eq(10)
end
it "should attempt to load the face if it isn't found" do
expect(subject).to receive(:require).once.with('puppet/face/bar')
expect(subject).to receive(:require).once.with('puppet/face/0.0.1/bar')
subject["bar", '0.0.1']
end
it "should attempt to load the default face for the specified version :current" do
expect(subject).to receive(:require).with('puppet/face/fozzie')
subject['fozzie', :current]
end
it "should return true if the face specified is registered" do
subject.instance_variable_get("@faces")[:foo][SemanticPuppet::Version.parse('0.0.1')] = 10
expect(subject["foo", '0.0.1']).to eq(10)
end
it "should attempt to require the face if it is not registered" do
expect(subject).to receive(:require) do |file|
subject.instance_variable_get("@faces")[:bar][SemanticPuppet::Version.parse('0.0.1')] = true
expect(file).to eq('puppet/face/bar')
end
expect(subject["bar", '0.0.1']).to be_truthy
end
it "should return false if the face is not registered" do
allow(subject).to receive(:require).and_return(true)
expect(subject["bar", '0.0.1']).to be_falsey
end
it "should return false if the face file itself is missing" do
num_calls = 0
allow(subject).to receive(:require) do
num_calls += 1
if num_calls == 1
raise LoadError.new('no such file to load -- puppet/face/bar')
else
raise LoadError.new('no such file to load -- puppet/face/0.0.1/bar')
end
end
expect(subject["bar", '0.0.1']).to be_falsey
end
it "should register the version loaded by `:current` as `:current`" do
expect(subject).to receive(:require) do |file|
subject.instance_variable_get("@faces")[:huzzah]['2.0.1'] = :huzzah_face
expect(file).to eq('puppet/face/huzzah')
end
subject["huzzah", :current]
expect(subject.instance_variable_get("@faces")[:huzzah][:current]).to eq(:huzzah_face)
end
context "with something on disk" do
it "should register the version loaded from `puppet/face/{name}` as `:current`" do
expect(subject["huzzah", '2.0.1']).to be
expect(subject["huzzah", :current]).to be
expect(Puppet::Face[:huzzah, '2.0.1']).to eq(Puppet::Face[:huzzah, :current])
end
it "should index :current when the code was pre-required" do
expect(subject.instance_variable_get("@faces")[:huzzah]).not_to be_key :current
require 'puppet/face/huzzah'
expect(subject[:huzzah, :current]).to be_truthy
end
end
it "should not cause an invalid face to be enumerated later" do
expect(subject[:there_is_no_face, :current]).to be_falsey
expect(subject.faces).not_to include :there_is_no_face
end
end
describe "::get_action_for_face" do
it "should return an action on the current face" do
expect(Puppet::Face::FaceCollection.get_action_for_face(:huzzah, :bar, :current)).
to be_an_instance_of Puppet::Interface::Action
end
it "should return an action on an older version of a face" do
action = Puppet::Face::FaceCollection.
get_action_for_face(:huzzah, :obsolete, :current)
expect(action).to be_an_instance_of Puppet::Interface::Action
expect(action.face.version).to eq(SemanticPuppet::Version.parse('1.0.0'))
end
it "should load the full older version of a face" do
action = Puppet::Face::FaceCollection.
get_action_for_face(:huzzah, :obsolete, :current)
expect(action.face.version).to eq(SemanticPuppet::Version.parse('1.0.0'))
expect(action.face).to be_action :obsolete_in_core
end
it "should not add obsolete actions to the current version" do
action = Puppet::Face::FaceCollection.
get_action_for_face(:huzzah, :obsolete, :current)
expect(action.face.version).to eq(SemanticPuppet::Version.parse('1.0.0'))
expect(action.face).to be_action :obsolete_in_core
current = Puppet::Face[:huzzah, :current]
expect(current.version).to eq(SemanticPuppet::Version.parse('2.0.1'))
expect(current).not_to be_action :obsolete_in_core
expect(current).not_to be_action :obsolete
end
end
describe "::register" do
it "should store the face by name" do
face = Puppet::Face.new(:my_face, '0.0.1')
subject.register(face)
expect(subject.instance_variable_get("@faces")).to eq({
:my_face => { face.version => face }
})
end
end
describe "::underscorize" do
faulty = [1, "23foo", "#foo", "$bar", "sturm und drang", :"sturm und drang"]
valid = {
"Foo" => :foo,
:Foo => :foo,
"foo_bar" => :foo_bar,
:foo_bar => :foo_bar,
"foo-bar" => :foo_bar,
:"foo-bar" => :foo_bar,
"foo_bar23" => :foo_bar23,
:foo_bar23 => :foo_bar23,
}
valid.each do |input, expect|
it "should map #{input.inspect} to #{expect.inspect}" do
result = subject.underscorize(input)
expect(result).to eq(expect)
end
end
faulty.each do |input|
it "should fail when presented with #{input.inspect} (#{input.class})" do
expect { subject.underscorize(input) }.
to raise_error ArgumentError, /not a valid face name/
end
end
end
context "faulty faces" do
before :each do
$:.unshift "#{PuppetSpec::FIXTURE_DIR}/faulty_face"
end
after :each do
$:.delete_if {|x| x == "#{PuppetSpec::FIXTURE_DIR}/faulty_face"}
end
it "should not die if a face has a syntax error" do
expect(subject.faces).to be_include :help
expect(subject.faces).not_to be_include :syntax
expect(@logs).not_to be_empty
expect(@logs.first.message).to match(/syntax error/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface/option_builder_spec.rb | spec/unit/interface/option_builder_spec.rb | require 'spec_helper'
require 'puppet/interface'
describe Puppet::Interface::OptionBuilder do
let :face do Puppet::Interface.new(:option_builder_testing, '0.0.1') end
it "should be able to construct an option without a block" do
expect(Puppet::Interface::OptionBuilder.build(face, "--foo")).
to be_an_instance_of Puppet::Interface::Option
end
Puppet.settings.each do |name, value|
it "should fail when option #{name.inspect} already exists in puppet core" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--#{name}")
end.to raise_error ArgumentError, /already defined/
end
end
it "should work with an empty block" do
option = Puppet::Interface::OptionBuilder.build(face, "--foo") do
# This block deliberately left blank.
end
expect(option).to be_an_instance_of Puppet::Interface::Option
end
[:description, :summary].each do |doc|
it "should support #{doc} declarations" do
text = "this is the #{doc}"
option = Puppet::Interface::OptionBuilder.build(face, "--foo") do
self.send doc, text
end
expect(option).to be_an_instance_of Puppet::Interface::Option
expect(option.send(doc)).to eq(text)
end
end
context "before_action hook" do
it "should support a before_action hook" do
option = Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |a,b,c| :whatever end
end
expect(option.before_action).to be_an_instance_of UnboundMethod
end
it "should fail if the hook block takes too few arguments" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |one, two| true end
end
end.to raise_error ArgumentError, /takes three arguments/
end
it "should fail if the hook block takes too many arguments" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |one, two, three, four| true end
end
end.to raise_error ArgumentError, /takes three arguments/
end
it "should fail if the hook block takes a variable number of arguments" do
expect do
Puppet::Interface::OptionBuilder.build(face, "--foo") do
before_action do |*blah| true end
end
end.to raise_error ArgumentError, /takes three arguments/
end
it "should support simple required declarations" do
opt = Puppet::Interface::OptionBuilder.build(face, "--foo") do
required
end
expect(opt).to be_required
end
it "should support arguments to the required property" do
opt = Puppet::Interface::OptionBuilder.build(face, "--foo") do
required(false)
end
expect(opt).not_to be_required
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface/action_manager_spec.rb | spec/unit/interface/action_manager_spec.rb | require 'spec_helper'
require 'puppet/interface'
class ActionManagerTester
include Puppet::Interface::ActionManager
end
describe Puppet::Interface::ActionManager do
subject { ActionManagerTester.new }
describe "when included in a class" do
it "should be able to define an action" do
subject.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should be able to list defined actions" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
subject.action(:bar) do
when_invoked { |options| "something" }
end
expect(subject.actions).to match_array([:foo, :bar])
end
it "should be able to indicate when an action is defined" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
expect(subject).to be_action(:foo)
end
it "should correctly treat action names specified as strings" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
expect(subject).to be_action("foo")
end
end
describe "when used to extend a class" do
subject { Class.new.extend(Puppet::Interface::ActionManager) }
it "should be able to define an action" do
subject.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should be able to list defined actions" do
subject.action(:foo) do
when_invoked { |options| "something" }
end
subject.action(:bar) do
when_invoked { |options| "something" }
end
expect(subject.actions).to include(:bar)
expect(subject.actions).to include(:foo)
end
it "should be able to indicate when an action is defined" do
subject.action(:foo) { when_invoked do |options| true end }
expect(subject).to be_action(:foo)
end
end
describe "when used both at the class and instance level" do
before do
@klass = Class.new do
include Puppet::Interface::ActionManager
extend Puppet::Interface::ActionManager
def __invoke_decorations(*args) true end
def options() [] end
end
@instance = @klass.new
end
it "should be able to define an action at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should create an instance method when an action is defined at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
expect(@instance.foo).to eq("something")
end
it "should be able to define an action at the instance level" do
@instance.action(:foo) do
when_invoked { |options| "something "}
end
end
it "should create an instance method when an action is defined at the instance level" do
@instance.action(:foo) do
when_invoked { |options| "something" }
end
expect(@instance.foo).to eq("something")
end
it "should be able to list actions defined at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
@klass.action(:bar) do
when_invoked { |options| "something" }
end
expect(@klass.actions).to include(:bar)
expect(@klass.actions).to include(:foo)
end
it "should be able to list actions defined at the instance level" do
@instance.action(:foo) do
when_invoked { |options| "something" }
end
@instance.action(:bar) do
when_invoked { |options| "something" }
end
expect(@instance.actions).to include(:bar)
expect(@instance.actions).to include(:foo)
end
it "should be able to list actions defined at both instance and class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
@instance.action(:bar) do
when_invoked { |options| "something" }
end
expect(@instance.actions).to include(:bar)
expect(@instance.actions).to include(:foo)
end
it "should be able to indicate when an action is defined at the class level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
expect(@instance).to be_action(:foo)
end
it "should be able to indicate when an action is defined at the instance level" do
@klass.action(:foo) do
when_invoked { |options| "something" }
end
expect(@instance).to be_action(:foo)
end
context "with actions defined in superclass" do
before :each do
@subclass = Class.new(@klass)
@instance = @subclass.new
@klass.action(:parent) do
when_invoked { |options| "a" }
end
@subclass.action(:sub) do
when_invoked { |options| "a" }
end
@instance.action(:instance) do
when_invoked { |options| "a" }
end
end
it "should list actions defined in superclasses" do
expect(@instance).to be_action(:parent)
expect(@instance).to be_action(:sub)
expect(@instance).to be_action(:instance)
end
it "should list inherited actions" do
expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
it "should not duplicate instance actions after fetching them (#7699)" do
expect(@instance.actions).to match_array([:instance, :parent, :sub])
@instance.get_action(:instance)
expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
it "should not duplicate subclass actions after fetching them (#7699)" do
expect(@instance.actions).to match_array([:instance, :parent, :sub])
@instance.get_action(:sub)
expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
it "should not duplicate superclass actions after fetching them (#7699)" do
expect(@instance.actions).to match_array([:instance, :parent, :sub])
@instance.get_action(:parent)
expect(@instance.actions).to match_array([:instance, :parent, :sub])
end
end
it "should create an instance method when an action is defined in a superclass" do
@subclass = Class.new(@klass)
@instance = @subclass.new
@klass.action(:foo) do
when_invoked { |options| "something" }
end
expect(@instance.foo).to eq("something")
end
end
describe "#action" do
it 'should add an action' do
subject.action(:foo) { when_invoked do |options| true end }
expect(subject.get_action(:foo)).to be_a Puppet::Interface::Action
end
it 'should support default actions' do
subject.action(:foo) { when_invoked do |options| true end; default }
expect(subject.get_default_action).to eq(subject.get_action(:foo))
end
it 'should not support more than one default action' do
subject.action(:foo) { when_invoked do |options| true end; default }
expect { subject.action(:bar) {
when_invoked do |options| true end
default
}
}.to raise_error(/cannot both be default/)
end
end
describe "#get_action" do
let :parent_class do
parent_class = Class.new(Puppet::Interface)
parent_class.action(:foo) { when_invoked do |options| true end }
parent_class
end
it "should check that we can find inherited actions when we are a class" do
expect(Class.new(parent_class).get_action(:foo).name).to eq(:foo)
end
it "should check that we can find inherited actions when we are an instance" do
instance = parent_class.new(:foo, '0.0.0')
expect(instance.get_action(:foo).name).to eq(:foo)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/graph/key_spec.rb | spec/unit/graph/key_spec.rb | require 'spec_helper'
require 'puppet/graph'
describe Puppet::Graph::Key do
it "produces the next in the sequence" do
key = Puppet::Graph::Key.new
expect(key.next).to be > key
end
it "produces a key after itself but before next" do
key = Puppet::Graph::Key.new
expect(key.down).to be > key
expect(key.down).to be < key.next
end
it "downward keys of the same group are in sequence" do
key = Puppet::Graph::Key.new
first = key.down
middle = key.down.next
last = key.down.next.next
expect(first).to be < middle
expect(middle).to be < last
expect(last).to be < key.next
end
it "downward keys in sequential groups are in sequence" do
key = Puppet::Graph::Key.new
first = key.down
middle = key.next
last = key.next.down
expect(first).to be < middle
expect(middle).to be < last
expect(last).to be < key.next.next
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/graph/simple_graph_spec.rb | spec/unit/graph/simple_graph_spec.rb | require 'spec_helper'
require 'puppet/graph'
describe Puppet::Graph::SimpleGraph do
it "should return the number of its vertices as its length" do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_vertex("one")
@graph.add_vertex("two")
expect(@graph.size).to eq(2)
end
it "should consider itself a directed graph" do
expect(Puppet::Graph::SimpleGraph.new.directed?).to be_truthy
end
it "should provide a method for reversing the graph" do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_edge(:one, :two)
expect(@graph.reversal.edge?(:two, :one)).to be_truthy
end
it "should be able to produce a dot graph" do
@graph = Puppet::Graph::SimpleGraph.new
class FauxVertex
def ref
"never mind"
end
end
v1 = FauxVertex.new
v2 = FauxVertex.new
@graph.add_edge(v1, v2)
expect { @graph.to_dot_graph }.to_not raise_error
end
describe "when managing vertices" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should provide a method to add a vertex" do
@graph.add_vertex(:test)
expect(@graph.vertex?(:test)).to be_truthy
end
it "should reset its reversed graph when vertices are added" do
rev = @graph.reversal
@graph.add_vertex(:test)
expect(@graph.reversal).not_to equal(rev)
end
it "should ignore already-present vertices when asked to add a vertex" do
@graph.add_vertex(:test)
expect { @graph.add_vertex(:test) }.to_not raise_error
end
it "should return true when asked if a vertex is present" do
@graph.add_vertex(:test)
expect(@graph.vertex?(:test)).to be_truthy
end
it "should return false when asked if a non-vertex is present" do
expect(@graph.vertex?(:test)).to be_falsey
end
it "should return all set vertices when asked" do
@graph.add_vertex(:one)
@graph.add_vertex(:two)
expect(@graph.vertices.length).to eq(2)
expect(@graph.vertices).to include(:one)
expect(@graph.vertices).to include(:two)
end
it "should remove a given vertex when asked" do
@graph.add_vertex(:one)
@graph.remove_vertex!(:one)
expect(@graph.vertex?(:one)).to be_falsey
end
it "should do nothing when a non-vertex is asked to be removed" do
expect { @graph.remove_vertex!(:one) }.to_not raise_error
end
describe "when managing resources with quotes in their title" do
subject do
v = Puppet::Type.type(:notify).new(:name => 'GRANT ALL ON DATABASE "puppetdb" TO "puppetdb"')
@graph.add_vertex(v)
@graph.to_dot
end
it "should escape quotes in node name" do
expect(subject).to match(/^[[:space:]]{4}"Notify\[GRANT ALL ON DATABASE \\"puppetdb\\" TO \\"puppetdb\\"\]" \[$/)
end
it "should escape quotes in node label" do
expect(subject).to match(/^[[:space:]]{8}label = "Notify\[GRANT ALL ON DATABASE \\"puppetdb\\" TO \\"puppetdb\\"\]"$/)
end
end
end
describe "when managing edges" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should provide a method to test whether a given vertex pair is an edge" do
expect(@graph).to respond_to(:edge?)
end
it "should reset its reversed graph when edges are added" do
rev = @graph.reversal
@graph.add_edge(:one, :two)
expect(@graph.reversal).not_to equal(rev)
end
it "should provide a method to add an edge as an instance of the edge class" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
expect(@graph.edge?(:one, :two)).to be_truthy
end
it "should provide a method to add an edge by specifying the two vertices" do
@graph.add_edge(:one, :two)
expect(@graph.edge?(:one, :two)).to be_truthy
end
it "should provide a method to add an edge by specifying the two vertices and a label" do
@graph.add_edge(:one, :two, :callback => :awesome)
expect(@graph.edge?(:one, :two)).to be_truthy
end
describe "when managing edges between nodes with quotes in their title" do
let(:vertex) do
Hash.new do |hash, key|
hash[key] = Puppet::Type.type(:notify).new(:name => key.to_s)
end
end
subject do
@graph.add_edge(vertex['Postgresql_psql[CREATE DATABASE "ejabberd"]'], vertex['Postgresql_psql[REVOKE CONNECT ON DATABASE "ejabberd" FROM public]'])
@graph.to_dot
end
it "should escape quotes in edge" do
expect(subject).to match(/^[[:space:]]{4}"Notify\[Postgresql_psql\[CREATE DATABASE \\"ejabberd\\"\]\]" -> "Notify\[Postgresql_psql\[REVOKE CONNECT ON DATABASE \\"ejabberd\\" FROM public\]\]" \[$/)
end
end
describe "when retrieving edges between two nodes" do
it "should handle the case of nodes not in the graph" do
expect(@graph.edges_between(:one, :two)).to eq([])
end
it "should handle the case of nodes with no edges between them" do
@graph.add_vertex(:one)
@graph.add_vertex(:two)
expect(@graph.edges_between(:one, :two)).to eq([])
end
it "should handle the case of nodes connected by a single edge" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
expect(@graph.edges_between(:one, :two).length).to eq(1)
expect(@graph.edges_between(:one, :two)[0]).to equal(edge)
end
it "should handle the case of nodes connected by multiple edges" do
edge1 = Puppet::Relationship.new(:one, :two, :callback => :foo)
edge2 = Puppet::Relationship.new(:one, :two, :callback => :bar)
@graph.add_edge(edge1)
@graph.add_edge(edge2)
expect(Set.new(@graph.edges_between(:one, :two))).to eq(Set.new([edge1, edge2]))
end
end
it "should add the edge source as a vertex if it is not already" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
expect(@graph.vertex?(:one)).to be_truthy
end
it "should add the edge target as a vertex if it is not already" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
expect(@graph.vertex?(:two)).to be_truthy
end
it "should return all edges as edge instances when asked" do
one = Puppet::Relationship.new(:one, :two)
two = Puppet::Relationship.new(:two, :three)
@graph.add_edge(one)
@graph.add_edge(two)
edges = @graph.edges
expect(edges).to be_instance_of(Array)
expect(edges.length).to eq(2)
expect(edges).to include(one)
expect(edges).to include(two)
end
it "should remove an edge when asked" do
edge = Puppet::Relationship.new(:one, :two)
@graph.add_edge(edge)
@graph.remove_edge!(edge)
expect(@graph.edge?(edge.source, edge.target)).to be_falsey
end
it "should remove all related edges when a vertex is removed" do
one = Puppet::Relationship.new(:one, :two)
two = Puppet::Relationship.new(:two, :three)
@graph.add_edge(one)
@graph.add_edge(two)
@graph.remove_vertex!(:two)
expect(@graph.edge?(:one, :two)).to be_falsey
expect(@graph.edge?(:two, :three)).to be_falsey
expect(@graph.edges.length).to eq(0)
end
end
describe "when finding adjacent vertices" do
before do
@graph = Puppet::Graph::SimpleGraph.new
@one_two = Puppet::Relationship.new(:one, :two)
@two_three = Puppet::Relationship.new(:two, :three)
@one_three = Puppet::Relationship.new(:one, :three)
@graph.add_edge(@one_two)
@graph.add_edge(@one_three)
@graph.add_edge(@two_three)
end
it "should return adjacent vertices" do
adj = @graph.adjacent(:one)
expect(adj).to be_include(:three)
expect(adj).to be_include(:two)
end
it "should default to finding :out vertices" do
expect(@graph.adjacent(:two)).to eq([:three])
end
it "should support selecting :in vertices" do
expect(@graph.adjacent(:two, :direction => :in)).to eq([:one])
end
it "should default to returning the matching vertices as an array of vertices" do
expect(@graph.adjacent(:two)).to eq([:three])
end
it "should support returning an array of matching edges" do
expect(@graph.adjacent(:two, :type => :edges)).to eq([@two_three])
end
# Bug #2111
it "should not consider a vertex adjacent just because it was asked about previously" do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_vertex("a")
@graph.add_vertex("b")
@graph.edge?("a", "b")
expect(@graph.adjacent("a")).to eq([])
end
end
describe "when clearing" do
before do
@graph = Puppet::Graph::SimpleGraph.new
one = Puppet::Relationship.new(:one, :two)
two = Puppet::Relationship.new(:two, :three)
@graph.add_edge(one)
@graph.add_edge(two)
@graph.clear
end
it "should remove all vertices" do
expect(@graph.vertices).to be_empty
end
it "should remove all edges" do
expect(@graph.edges).to be_empty
end
end
describe "when reversing graphs" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should provide a method for reversing the graph" do
@graph.add_edge(:one, :two)
expect(@graph.reversal.edge?(:two, :one)).to be_truthy
end
it "should add all vertices to the reversed graph" do
@graph.add_edge(:one, :two)
expect(@graph.vertex?(:one)).to be_truthy
expect(@graph.vertex?(:two)).to be_truthy
end
it "should retain labels on edges" do
@graph.add_edge(:one, :two, :callback => :awesome)
edge = @graph.reversal.edges_between(:two, :one)[0]
expect(edge.label).to eq({:callback => :awesome})
end
end
describe "when reporting cycles in the graph" do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
# This works with `add_edges` to auto-vivify the resource instances.
let :vertex do
Hash.new do |hash, key|
hash[key] = Puppet::Type.type(:notify).new(:name => key.to_s)
end
end
def add_edges(hash)
hash.each do |a,b|
@graph.add_edge(vertex[a], vertex[b])
end
end
def simplify(cycles)
cycles.map do |cycle|
cycle.map do |resource|
resource.name
end
end
end
def expect_cycle_to_include(cycle, *resource_names)
resource_names.each_with_index do |resource, index|
expect(cycle[index].ref).to eq("Notify[#{resource}]")
end
end
it "should report one-vertex loops" do
add_edges :a => :a
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:\n\(Notify\[a\] => Notify\[a\]\)/)
cycle = @graph.report_cycles_in_graph.first
expect_cycle_to_include(cycle, :a)
end
it "should report two-vertex loops" do
add_edges :a => :b, :b => :a
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:\n\(Notify\[a\] => Notify\[b\] => Notify\[a\]\)/)
cycle = @graph.report_cycles_in_graph.first
expect_cycle_to_include(cycle, :a, :b)
end
it "should report multi-vertex loops" do
add_edges :a => :b, :b => :c, :c => :a
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:\n\(Notify\[a\] => Notify\[b\] => Notify\[c\] => Notify\[a\]\)/)
cycle = @graph.report_cycles_in_graph.first
expect_cycle_to_include(cycle, :a, :b, :c)
end
it "should report when a larger tree contains a small cycle" do
add_edges :a => :b, :b => :a, :c => :a, :d => :c
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:\n\(Notify\[a\] => Notify\[b\] => Notify\[a\]\)/)
cycle = @graph.report_cycles_in_graph.first
expect_cycle_to_include(cycle, :a, :b)
end
it "should succeed on trees with no cycles" do
add_edges :a => :b, :b => :e, :c => :a, :d => :c
expect(Puppet).not_to receive(:err)
expect(@graph.report_cycles_in_graph).to be_nil
end
it "cycle discovery should be the minimum cycle for a simple graph" do
add_edges "a" => "b"
add_edges "b" => "a"
add_edges "b" => "c"
expect(simplify(@graph.find_cycles_in_graph)).to eq([["a", "b"]])
end
it "cycle discovery handles a self-loop cycle" do
add_edges :a => :a
expect(simplify(@graph.find_cycles_in_graph)).to eq([["a"]])
end
it "cycle discovery should handle two distinct cycles" do
add_edges "a" => "a1", "a1" => "a"
add_edges "b" => "b1", "b1" => "b"
expect(simplify(@graph.find_cycles_in_graph)).to eq([["a1", "a"], ["b1", "b"]])
end
it "cycle discovery should handle two cycles in a connected graph" do
add_edges "a" => "b", "b" => "c", "c" => "d"
add_edges "a" => "a1", "a1" => "a"
add_edges "c" => "c1", "c1" => "c2", "c2" => "c3", "c3" => "c"
expect(simplify(@graph.find_cycles_in_graph)).to eq([%w{a1 a}, %w{c1 c2 c3 c}])
end
it "cycle discovery should handle a complicated cycle" do
add_edges "a" => "b", "b" => "c"
add_edges "a" => "c"
add_edges "c" => "c1", "c1" => "a"
add_edges "c" => "c2", "c2" => "b"
expect(simplify(@graph.find_cycles_in_graph)).to eq([%w{a b c1 c2 c}])
end
it "cycle discovery should not fail with large data sets" do
limit = 3000
(1..(limit - 1)).each do |n| add_edges n.to_s => (n+1).to_s end
expect(simplify(@graph.find_cycles_in_graph)).to eq([])
end
it "path finding should work with a simple cycle" do
add_edges "a" => "b", "b" => "c", "c" => "a"
cycles = @graph.find_cycles_in_graph
paths = @graph.paths_in_cycle(cycles.first, 100)
expect(simplify(paths)).to eq([%w{a b c a}])
end
it "path finding should work with two independent cycles" do
add_edges "a" => "b1"
add_edges "a" => "b2"
add_edges "b1" => "a", "b2" => "a"
cycles = @graph.find_cycles_in_graph
expect(cycles.length).to eq(1)
paths = @graph.paths_in_cycle(cycles.first, 100)
expect(simplify(paths)).to eq([%w{a b1 a}, %w{a b2 a}])
end
it "path finding should prefer shorter paths in cycles" do
add_edges "a" => "b", "b" => "c", "c" => "a"
add_edges "b" => "a"
cycles = @graph.find_cycles_in_graph
expect(cycles.length).to eq(1)
paths = @graph.paths_in_cycle(cycles.first, 100)
expect(simplify(paths)).to eq([%w{a b a}, %w{a b c a}])
end
it "path finding should respect the max_path value" do
(1..20).each do |n| add_edges "a" => "b#{n}", "b#{n}" => "a" end
cycles = @graph.find_cycles_in_graph
expect(cycles.length).to eq(1)
(1..20).each do |n|
paths = @graph.paths_in_cycle(cycles.first, n)
expect(paths.length).to eq(n)
end
paths = @graph.paths_in_cycle(cycles.first, 21)
expect(paths.length).to eq(20)
end
end
describe "when writing dot files" do
before do
@graph = Puppet::Graph::SimpleGraph.new
@name = :test
@file = File.join(Puppet[:graphdir], @name.to_s + ".dot")
end
it "should only write when graphing is enabled" do
expect(File).not_to receive(:open).with(@file)
Puppet[:graph] = false
@graph.write_graph(@name)
end
it "should write a dot file based on the passed name" do
expect(File).to receive(:open).with(@file, "w:UTF-8").and_yield(double("file", :puts => nil))
expect(@graph).to receive(:to_dot).with({"name" => @name.to_s.capitalize})
Puppet[:graph] = true
@graph.write_graph(@name)
end
end
describe Puppet::Graph::SimpleGraph do
before do
@graph = Puppet::Graph::SimpleGraph.new
end
it "should correctly clear vertices and edges when asked" do
@graph.add_edge("a", "b")
@graph.add_vertex "c"
@graph.clear
expect(@graph.vertices).to be_empty
expect(@graph.edges).to be_empty
end
end
describe "when matching edges" do
before do
@graph = Puppet::Graph::SimpleGraph.new
# Resource is a String here although not for realz. Stub [] to always return nil
# because indexing a String with a non-Integer throws an exception (and none of
# these tests need anything meaningful from []).
resource = "a"
allow(resource).to receive(:[])
@event = Puppet::Transaction::Event.new(:name => :yay, :resource => resource)
@none = Puppet::Transaction::Event.new(:name => :NONE, :resource => resource)
@edges = {}
@edges["a/b"] = Puppet::Relationship.new("a", "b", {:event => :yay, :callback => :refresh})
@edges["a/c"] = Puppet::Relationship.new("a", "c", {:event => :yay, :callback => :refresh})
@graph.add_edge(@edges["a/b"])
end
it "should match edges whose source matches the source of the event" do
expect(@graph.matching_edges(@event)).to eq([@edges["a/b"]])
end
it "should match always match nothing when the event is :NONE" do
expect(@graph.matching_edges(@none)).to be_empty
end
it "should match multiple edges" do
@graph.add_edge(@edges["a/c"])
edges = @graph.matching_edges(@event)
expect(edges).to be_include(@edges["a/b"])
expect(edges).to be_include(@edges["a/c"])
end
end
describe "when determining dependencies" do
before do
@graph = Puppet::Graph::SimpleGraph.new
@graph.add_edge("a", "b")
@graph.add_edge("a", "c")
@graph.add_edge("b", "d")
end
it "should find all dependents when they are on multiple levels" do
expect(@graph.dependents("a").sort).to eq(%w{b c d}.sort)
end
it "should find single dependents" do
expect(@graph.dependents("b").sort).to eq(%w{d}.sort)
end
it "should return an empty array when there are no dependents" do
expect(@graph.dependents("c").sort).to eq([].sort)
end
it "should find all dependencies when they are on multiple levels" do
expect(@graph.dependencies("d").sort).to eq(%w{a b})
end
it "should find single dependencies" do
expect(@graph.dependencies("c").sort).to eq(%w{a})
end
it "should return an empty array when there are no dependencies" do
expect(@graph.dependencies("a").sort).to eq([])
end
end
it "should serialize to YAML using the old format by default" do
expect(Puppet::Graph::SimpleGraph.use_new_yaml_format).to eq(false)
end
describe "(yaml tests)" do
def empty_graph(graph)
end
def one_vertex_graph(graph)
graph.add_vertex('a')
end
def graph_without_edges(graph)
['a', 'b', 'c'].each { |x| graph.add_vertex(x) }
end
def one_edge_graph(graph)
graph.add_edge('a', 'b')
end
def many_edge_graph(graph)
graph.add_edge('a', 'b')
graph.add_edge('a', 'c')
graph.add_edge('b', 'd')
graph.add_edge('c', 'd')
end
def labeled_edge_graph(graph)
graph.add_edge('a', 'b', :callback => :foo, :event => :bar)
end
def overlapping_edge_graph(graph)
graph.add_edge('a', 'b', :callback => :foo, :event => :bar)
graph.add_edge('a', 'b', :callback => :biz, :event => :baz)
end
def self.all_test_graphs
[:empty_graph, :one_vertex_graph, :graph_without_edges, :one_edge_graph, :many_edge_graph, :labeled_edge_graph,
:overlapping_edge_graph]
end
def object_ids(enumerable)
# Return a sorted list of the object id's of the elements of an
# enumerable.
enumerable.collect { |x| x.object_id }.sort
end
def graph_to_yaml(graph, which_format)
previous_use_new_yaml_format = Puppet::Graph::SimpleGraph.use_new_yaml_format
Puppet::Graph::SimpleGraph.use_new_yaml_format = (which_format == :new)
if block_given?
yield
else
YAML.dump(graph)
end
ensure
Puppet::Graph::SimpleGraph.use_new_yaml_format = previous_use_new_yaml_format
end
# Test serialization of graph to YAML.
[:old, :new].each do |which_format|
all_test_graphs.each do |graph_to_test|
it "should be able to serialize #{graph_to_test} to YAML (#{which_format} format)" do
graph = Puppet::Graph::SimpleGraph.new
send(graph_to_test, graph)
yaml_form = graph_to_yaml(graph, which_format)
# Hack the YAML so that objects in the Puppet namespace get
# changed to YAML::DomainType objects. This lets us inspect
# the serialized objects easily without invoking any
# yaml_initialize hooks.
yaml_form.gsub!('!ruby/object:Puppet::', '!hack/object:Puppet::')
serialized_object = Puppet::Util::Yaml.safe_load(yaml_form, [Symbol,Puppet::Graph::SimpleGraph])
# Check that the object contains instance variables @edges and
# @vertices only. @reversal is also permitted, but we don't
# check it, because it is going to be phased out.
expect(serialized_object.keys.reject { |x| x == 'reversal' }.sort).to eq(['edges', 'vertices'])
# Check edges by forming a set of tuples (source, target,
# callback, event) based on the graph and the YAML and make sure
# they match.
edges = serialized_object['edges']
expect(edges).to be_a(Array)
expected_edge_tuples = graph.edges.collect { |edge| [edge.source, edge.target, edge.callback, edge.event] }
actual_edge_tuples = edges.collect do |edge|
%w{source target}.each { |x| expect(edge.keys).to include(x) }
edge.keys.each { |x| expect(['source', 'target', 'callback', 'event']).to include(x) }
%w{source target callback event}.collect { |x| edge[x] }
end
expect(Set.new(actual_edge_tuples)).to eq(Set.new(expected_edge_tuples.map { |tuple| tuple.map {|e| e.nil? ? nil : e.to_s }}))
expect(actual_edge_tuples.length).to eq(expected_edge_tuples.length)
# Check vertices one by one.
vertices = serialized_object['vertices']
if which_format == :old
expect(vertices).to be_a(Hash)
expect(Set.new(vertices.keys)).to eq(Set.new(graph.vertices))
vertices.each do |key, value|
expect(value.keys.sort).to eq(%w{adjacencies vertex})
expect(value['vertex']).to eq(key)
adjacencies = value['adjacencies']
expect(adjacencies).to be_a(Hash)
expect(Set.new(adjacencies.keys)).to eq(Set.new(['in', 'out']))
[:in, :out].each do |direction|
direction_hash = adjacencies[direction.to_s]
expect(direction_hash).to be_a(Hash)
expected_adjacent_vertices = Set.new(graph.adjacent(key, :direction => direction, :type => :vertices))
expect(Set.new(direction_hash.keys)).to eq(expected_adjacent_vertices)
direction_hash.each do |adj_key, adj_value|
# Since we already checked edges, just check consistency
# with edges.
desired_source = direction == :in ? adj_key : key
desired_target = direction == :in ? key : adj_key
expected_edges = edges.select do |edge|
edge['source'] == desired_source && edge['target'] == desired_target
end
expect(adj_value).to be_a(Array)
if adj_value != expected_edges
raise "For vertex #{key.inspect}, direction #{direction.inspect}: expected adjacencies #{expected_edges.inspect} but got #{adj_value.inspect}"
end
end
end
end
else
expect(vertices).to be_a(Array)
expect(Set.new(vertices)).to eq(Set.new(graph.vertices))
expect(vertices.length).to eq(graph.vertices.length)
end
end
end
# Test deserialization of graph from YAML. This presumes the
# correctness of serialization to YAML, which has already been
# tested.
all_test_graphs.each do |graph_to_test|
it "should be able to deserialize #{graph_to_test} from YAML (#{which_format} format)" do
reference_graph = Puppet::Graph::SimpleGraph.new
send(graph_to_test, reference_graph)
yaml_form = graph_to_yaml(reference_graph, which_format)
recovered_graph = Puppet::Util::Yaml.safe_load(yaml_form, [Symbol,Puppet::Graph::SimpleGraph])
# Test that the recovered vertices match the vertices in the
# reference graph.
expected_vertices = reference_graph.vertices.to_a
recovered_vertices = recovered_graph.vertices.to_a
expect(Set.new(recovered_vertices)).to eq(Set.new(expected_vertices))
expect(recovered_vertices.length).to eq(expected_vertices.length)
# Test that the recovered edges match the edges in the
# reference graph.
expected_edge_tuples = reference_graph.edges.collect do |edge|
[edge.source, edge.target, edge.callback, edge.event]
end
recovered_edge_tuples = recovered_graph.edges.collect do |edge|
[edge.source, edge.target, edge.callback, edge.event]
end
expect(Set.new(recovered_edge_tuples)).to eq(Set.new(expected_edge_tuples))
expect(recovered_edge_tuples.length).to eq(expected_edge_tuples.length)
# We ought to test that the recovered graph is self-consistent
# too. But we're not going to bother with that yet because
# the internal representation of the graph is about to change.
end
end
end
it "should serialize properly when used as a base class" do
class Puppet::TestDerivedClass < Puppet::Graph::SimpleGraph
attr_accessor :foo
def initialize_from_hash(hash)
super(hash)
@foo = hash['foo']
end
def to_data_hash
super.merge('foo' => @foo)
end
end
derived = Puppet::TestDerivedClass.new
derived.add_edge('a', 'b')
derived.foo = 1234
yaml = YAML.dump(derived)
recovered_derived = Puppet::Util::Yaml.safe_load(yaml, [Puppet::TestDerivedClass])
expect(recovered_derived.class).to equal(Puppet::TestDerivedClass)
expect(recovered_derived.edges.length).to eq(1)
expect(recovered_derived.edges[0].source).to eq('a')
expect(recovered_derived.edges[0].target).to eq('b')
expect(recovered_derived.vertices.length).to eq(2)
expect(recovered_derived.foo).to eq(1234)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/graph/rb_tree_map_spec.rb | spec/unit/graph/rb_tree_map_spec.rb | require 'spec_helper'
require 'puppet/graph'
describe Puppet::Graph::RbTreeMap do
describe "#push" do
it "should allow a new element to be added" do
subject[5] = 'foo'
expect(subject.size).to eq(1)
expect(subject[5]).to eq('foo')
end
it "should replace the old value if the key is in tree already" do
subject[0] = 10
subject[0] = 20
expect(subject[0]).to eq(20)
expect(subject.size).to eq(1)
end
it "should be able to add a large number of elements" do
(1..1000).each {|i| subject[i] = i.to_s}
expect(subject.size).to eq(1000)
end
it "should create a root node if the tree was empty" do
expect(subject.instance_variable_get(:@root)).to be_nil
subject[5] = 'foo'
expect(subject.instance_variable_get(:@root)).to be_a(Puppet::Graph::RbTreeMap::Node)
end
end
describe "#size" do
it "should be 0 for en empty tree" do
expect(subject.size).to eq(0)
end
it "should correctly report the size for a non-empty tree" do
(1..10).each {|i| subject[i] = i.to_s}
expect(subject.size).to eq(10)
end
end
describe "#has_key?" do
it "should be true if the tree contains the key" do
subject[1] = 2
expect(subject).to be_has_key(1)
end
it "should be true if the tree contains the key and its value is nil" do
subject[0] = nil
expect(subject).to be_has_key(0)
end
it "should be false if the tree does not contain the key" do
subject[1] = 2
expect(subject).not_to be_has_key(2)
end
it "should be false if the tree is empty" do
expect(subject).not_to be_has_key(5)
end
end
describe "#get" do
it "should return the value at the key" do
subject[1] = 2
subject[3] = 4
expect(subject.get(1)).to eq(2)
expect(subject.get(3)).to eq(4)
end
it "should return nil if the tree is empty" do
expect(subject[1]).to be_nil
end
it "should return nil if the key is not in the tree" do
subject[1] = 2
expect(subject[3]).to be_nil
end
it "should return nil if the value at the key is nil" do
subject[1] = nil
expect(subject[1]).to be_nil
end
end
describe "#min_key" do
it "should return the smallest key in the tree" do
[4,8,12,3,6,2,-4,7].each do |i|
subject[i] = i.to_s
end
expect(subject.min_key).to eq(-4)
end
it "should return nil if the tree is empty" do
expect(subject.min_key).to be_nil
end
end
describe "#max_key" do
it "should return the largest key in the tree" do
[4,8,12,3,6,2,-4,7].each do |i|
subject[i] = i.to_s
end
expect(subject.max_key).to eq(12)
end
it "should return nil if the tree is empty" do
expect(subject.max_key).to be_nil
end
end
describe "#delete" do
before :each do
subject[1] = '1'
subject[0] = '0'
subject[2] = '2'
end
it "should return the value at the key deleted" do
expect(subject.delete(0)).to eq('0')
expect(subject.delete(1)).to eq('1')
expect(subject.delete(2)).to eq('2')
expect(subject.size).to eq(0)
end
it "should be able to delete the last node" do
tree = described_class.new
tree[1] = '1'
expect(tree.delete(1)).to eq('1')
expect(tree).to be_empty
end
it "should be able to delete the root node" do
expect(subject.delete(1)).to eq('1')
expect(subject.size).to eq(2)
expect(subject.to_hash).to eq({
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :red,
}
}
})
end
it "should be able to delete the left child" do
expect(subject.delete(0)).to eq('0')
expect(subject.size).to eq(2)
expect(subject.to_hash).to eq({
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :red,
}
}
})
end
it "should be able to delete the right child" do
expect(subject.delete(2)).to eq('2')
expect(subject.size).to eq(2)
expect(subject.to_hash).to eq({
:node => {
:key => 1,
:value => '1',
:color => :black,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :red,
}
}
})
end
it "should be able to delete the left child if it is a subtree" do
(3..6).each {|i| subject[i] = i.to_s}
expect(subject.delete(1)).to eq('1')
expect(subject.to_hash).to eq({
:node => {
:key => 5,
:value => '5',
:color => :black,
},
:left => {
:node => {
:key => 3,
:value => '3',
:color => :red,
},
:left => {
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :red,
},
},
},
:right => {
:node => {
:key => 4,
:value => '4',
:color => :black,
},
},
},
:right => {
:node => {
:key => 6,
:value => '6',
:color => :black,
},
},
})
end
it "should be able to delete the right child if it is a subtree" do
(3..6).each {|i| subject[i] = i.to_s}
expect(subject.delete(5)).to eq('5')
expect(subject.to_hash).to eq({
:node => {
:key => 3,
:value => '3',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :red,
},
:left => {
:node => {
:key => 0,
:value => '0',
:color => :black,
},
},
:right => {
:node => {
:key => 2,
:value => '2',
:color => :black,
},
},
},
:right => {
:node => {
:key => 6,
:value => '6',
:color => :black,
},
:left => {
:node => {
:key => 4,
:value => '4',
:color => :red,
},
},
},
})
end
it "should return nil if the tree is empty" do
tree = described_class.new
expect(tree.delete(14)).to be_nil
expect(tree.size).to eq(0)
end
it "should return nil if the key is not in the tree" do
(0..4).each {|i| subject[i] = i.to_s}
expect(subject.delete(2.5)).to be_nil
expect(subject.size).to eq(5)
end
it "should return nil if the key is larger than the maximum key" do
expect(subject.delete(100)).to be_nil
expect(subject.size).to eq(3)
end
it "should return nil if the key is smaller than the minimum key" do
expect(subject.delete(-1)).to be_nil
expect(subject.size).to eq(3)
end
end
describe "#empty?" do
it "should return true if the tree is empty" do
expect(subject).to be_empty
end
it "should return false if the tree is not empty" do
subject[5] = 10
expect(subject).not_to be_empty
end
end
describe "#delete_min" do
it "should delete the smallest element of the tree" do
(1..15).each {|i| subject[i] = i.to_s}
expect(subject.delete_min).to eq('1')
expect(subject.size).to eq(14)
end
it "should return nil if the tree is empty" do
expect(subject.delete_min).to be_nil
end
end
describe "#delete_max" do
it "should delete the largest element of the tree" do
(1..15).each {|i| subject[i] = i.to_s}
expect(subject.delete_max).to eq('15')
expect(subject.size).to eq(14)
end
it "should return nil if the tree is empty" do
expect(subject.delete_max).to be_nil
end
end
describe "#each" do
it "should yield each pair in the tree in order if a block is provided" do
# Insert in reverse to demonstrate they aren't being yielded in insertion order
(1..5).to_a.reverse_each {|i| subject[i] = i.to_s}
nodes = []
subject.each do |key,value|
nodes << [key,value]
end
expect(nodes).to eq((1..5).map {|i| [i, i.to_s]})
end
it "should do nothing if the tree is empty" do
subject.each do |key,value|
raise "each on an empty tree incorrectly yielded #{key}, #{value}"
end
end
end
describe "#isred" do
it "should return true if the node is red" do
node = Puppet::Graph::RbTreeMap::Node.new(1,2)
node.color = :red
expect(subject.send(:isred, node)).to eq(true)
end
it "should return false if the node is black" do
node = Puppet::Graph::RbTreeMap::Node.new(1,2)
node.color = :black
expect(subject.send(:isred, node)).to eq(false)
end
it "should return false if the node is nil" do
expect(subject.send(:isred, nil)).to eq(false)
end
end
end
describe Puppet::Graph::RbTreeMap::Node do
let(:tree) { Puppet::Graph::RbTreeMap.new }
let(:subject) { tree.instance_variable_get(:@root) }
before :each do
(1..3).each {|i| tree[i] = i.to_s}
end
describe "#red?" do
it "should return true if the node is red" do
subject.color = :red
expect(subject).to be_red
end
it "should return false if the node is black" do
subject.color = :black
expect(subject).not_to be_red
end
end
describe "#colorflip" do
it "should switch the color of the node and its children" do
expect(subject.color).to eq(:black)
expect(subject.left.color).to eq(:black)
expect(subject.right.color).to eq(:black)
subject.colorflip
expect(subject.color).to eq(:red)
expect(subject.left.color).to eq(:red)
expect(subject.right.color).to eq(:red)
end
end
describe "#rotate_left" do
it "should rotate the tree once to the left" do
(4..7).each {|i| tree[i] = i.to_s}
root = tree.instance_variable_get(:@root)
root.rotate_left
expect(tree.to_hash).to eq({
:node => {
:key => 6,
:value => '6',
:color => :black,
},
:left => {
:node => {
:key => 4,
:value => '4',
:color => :red,
},
:left => {
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :black,
},
},
:right => {
:node => {
:key => 3,
:value => '3',
:color => :black,
},
},
},
:right => {
:node => {
:key => 5,
:value => '5',
:color => :black,
},
},
},
:right => {
:node => {
:key => 7,
:value => '7',
:color => :black,
},
},
})
end
end
describe "#rotate_right" do
it "should rotate the tree once to the right" do
(4..7).each {|i| tree[i] = i.to_s}
root = tree.instance_variable_get(:@root)
root.rotate_right
expect(tree.to_hash).to eq({
:node => {
:key => 2,
:value => '2',
:color => :black,
},
:left => {
:node => {
:key => 1,
:value => '1',
:color => :black,
},
},
:right => {
:node => {
:key => 4,
:value => '4',
:color => :red,
},
:left => {
:node => {
:key => 3,
:value => '3',
:color => :black,
},
},
:right => {
:node => {
:key => 6,
:value => '6',
:color => :black,
},
:left => {
:node => {
:key => 5,
:value => '5',
:color => :black,
},
},
:right => {
:node => {
:key => 7,
:value => '7',
:color => :black,
},
},
},
},
})
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/graph/sequential_prioritizer_spec.rb | spec/unit/graph/sequential_prioritizer_spec.rb | require 'spec_helper'
require 'puppet/graph'
describe Puppet::Graph::SequentialPrioritizer do
let(:priorities) { Puppet::Graph::SequentialPrioritizer.new }
it "generates priorities that maintain the sequence" do
first = priorities.generate_priority_for("one")
second = priorities.generate_priority_for("two")
third = priorities.generate_priority_for("three")
expect(first).to be < second
expect(second).to be < third
end
it "prioritizes contained keys after the container" do
parent = priorities.generate_priority_for("one")
child = priorities.generate_priority_contained_in("one", "child 1")
sibling = priorities.generate_priority_contained_in("one", "child 2")
uncle = priorities.generate_priority_for("two")
expect(parent).to be < child
expect(child).to be < sibling
expect(sibling).to be < uncle
end
it "fails to prioritize a key contained in an unknown container" do
expect do
priorities.generate_priority_contained_in("unknown", "child 1")
end.to raise_error(NoMethodError, /undefined method .*down' for nil/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/graph/relationship_graph_spec.rb | spec/unit/graph/relationship_graph_spec.rb | require 'spec_helper'
require 'puppet/graph'
require 'puppet_spec/compiler'
require 'matchers/include_in_order'
require 'matchers/relationship_graph_matchers'
describe Puppet::Graph::RelationshipGraph do
include PuppetSpec::Files
include PuppetSpec::Compiler
include RelationshipGraphMatchers
let(:graph) { Puppet::Graph::RelationshipGraph.new(Puppet::Graph::SequentialPrioritizer.new) }
it "allows adding a new vertex with a specific priority" do
vertex = stub_vertex('something')
graph.add_vertex(vertex, 2)
expect(graph.resource_priority(vertex)).to eq(2)
end
it "returns resource priority based on the order added" do
# strings chosen so the old hex digest method would put these in the
# wrong order
first = stub_vertex('aa')
second = stub_vertex('b')
graph.add_vertex(first)
graph.add_vertex(second)
expect(graph.resource_priority(first)).to be < graph.resource_priority(second)
end
it "retains the first priority when a resource is added more than once" do
first = stub_vertex(1)
second = stub_vertex(2)
graph.add_vertex(first)
graph.add_vertex(second)
graph.add_vertex(first)
expect(graph.resource_priority(first)).to be < graph.resource_priority(second)
end
it "forgets the priority of a removed resource" do
vertex = stub_vertex(1)
graph.add_vertex(vertex)
graph.remove_vertex!(vertex)
expect(graph.resource_priority(vertex)).to be_nil
end
it "does not give two resources the same priority" do
first = stub_vertex(1)
second = stub_vertex(2)
third = stub_vertex(3)
graph.add_vertex(first)
graph.add_vertex(second)
graph.remove_vertex!(first)
graph.add_vertex(third)
expect(graph.resource_priority(second)).to be < graph.resource_priority(third)
end
context "order of traversal" do
it "traverses independent resources in the order they are added" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "first": }
notify { "second": }
notify { "third": }
notify { "fourth": }
notify { "fifth": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[first]",
"Notify[second]",
"Notify[third]",
"Notify[fourth]",
"Notify[fifth]"))
end
it "traverses resources generated during catalog creation in the order inserted" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
create_resources(notify, { "first" => {} })
create_resources(notify, { "second" => {} })
notify{ "third": }
create_resources(notify, { "fourth" => {} })
create_resources(notify, { "fifth" => {} })
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[first]",
"Notify[second]",
"Notify[third]",
"Notify[fourth]",
"Notify[fifth]"))
end
it "traverses all independent resources before traversing dependent ones" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "first": require => Notify[third] }
notify { "second": }
notify { "third": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[second]", "Notify[third]", "Notify[first]"))
end
it "traverses all independent resources before traversing dependent ones (with a backwards require)" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "first": }
notify { "second": }
notify { "third": require => Notify[second] }
notify { "fourth": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[first]", "Notify[second]", "Notify[third]", "Notify[fourth]"))
end
it "traverses resources in classes in the order they are added" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
class c1 {
notify { "a": }
notify { "b": }
}
class c2 {
notify { "c": require => Notify[b] }
}
class c3 {
notify { "d": }
}
include c2
include c1
include c3
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[a]", "Notify[b]", "Notify[c]", "Notify[d]"))
end
it "traverses resources in defines in the order they are added" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
define d1() {
notify { "a": }
notify { "b": }
}
define d2() {
notify { "c": require => Notify[b]}
}
define d3() {
notify { "d": }
}
d2 { "c": }
d1 { "d": }
d3 { "e": }
MANIFEST
expect(order_resources_traversed_in(relationships)).to(
include_in_order("Notify[a]", "Notify[b]", "Notify[c]", "Notify[d]"))
end
end
describe "when interrupting traversal" do
def collect_canceled_resources(relationships, trigger_on)
continue = true
continue_while = lambda { continue }
canceled_resources = []
canceled_resource_handler = lambda { |resource| canceled_resources << resource.ref }
relationships.traverse(:while => continue_while,
:canceled_resource_handler => canceled_resource_handler) do |resource|
if resource.ref == trigger_on
continue = false
end
end
canceled_resources
end
it "enumerates the remaining resources" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "a": }
notify { "b": }
notify { "c": }
MANIFEST
resources = collect_canceled_resources(relationships, 'Notify[b]')
expect(resources).to include('Notify[c]')
end
it "enumerates the remaining blocked resources" do
relationships = compile_to_relationship_graph(<<-MANIFEST)
notify { "a": }
notify { "b": }
notify { "c": }
notify { "d": require => Notify["c"] }
MANIFEST
resources = collect_canceled_resources(relationships, 'Notify[b]')
expect(resources).to include('Notify[d]')
end
end
describe "when constructing dependencies" do
let(:child) { make_absolute('/a/b') }
let(:parent) { make_absolute('/a') }
it "does not create an automatic relationship that would interfere with a manual relationship" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
file { "#{child}": }
file { "#{parent}": require => File["#{child}"] }
MANIFEST
expect(relationship_graph).to enforce_order_with_edge("File[#{child}]", "File[#{parent}]")
end
it "creates automatic relationships defined by the type" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
file { "#{child}": }
file { "#{parent}": }
MANIFEST
expect(relationship_graph).to enforce_order_with_edge("File[#{parent}]", "File[#{child}]")
end
end
describe "when reconstructing containment relationships" do
def admissible_sentinel_of(ref)
"Admissible_#{ref}"
end
def completed_sentinel_of(ref)
"Completed_#{ref}"
end
it "an empty container's completed sentinel should depend on its admissible sentinel" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a { }
include a
MANIFEST
expect(relationship_graph).to enforce_order_with_edge(
admissible_sentinel_of("class[A]"),
completed_sentinel_of("class[A]"))
end
it "a container with children does not directly connect the completed sentinel to its admissible sentinel" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a { notify { "a": } }
include a
MANIFEST
expect(relationship_graph).not_to enforce_order_with_edge(
admissible_sentinel_of("class[A]"),
completed_sentinel_of("class[A]"))
end
it "all contained objects should depend on their container's admissible sentinel" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
include a
MANIFEST
expect(relationship_graph).to enforce_order_with_edge(
admissible_sentinel_of("class[A]"),
"Notify[class a]")
end
it "completed sentinels should depend on their container's contents" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
include a
MANIFEST
expect(relationship_graph).to enforce_order_with_edge(
"Notify[class a]",
completed_sentinel_of("class[A]"))
end
it "admissible and completed sentinels should inherit the same tags" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
tag "test_tag"
}
include a
MANIFEST
expect(vertex_called(relationship_graph, admissible_sentinel_of("class[A]")).tagged?("test_tag")).
to eq(true)
expect(vertex_called(relationship_graph, completed_sentinel_of("class[A]")).tagged?("test_tag")).
to eq(true)
end
it "should remove all Component objects from the dependency graph" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
b { "testing": }
MANIFEST
expect(relationship_graph.vertices.find_all { |v| v.is_a?(Puppet::Type.type(:component)) }).to be_empty
end
it "should remove all Stage resources from the dependency graph" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
notify { "class a": }
MANIFEST
expect(relationship_graph.vertices.find_all { |v| v.is_a?(Puppet::Type.type(:stage)) }).to be_empty
end
it "should retain labels on non-containment edges" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
Class[a] ~> b { "testing": }
MANIFEST
expect(relationship_graph.edges_between(
vertex_called(relationship_graph, completed_sentinel_of("class[A]")),
vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")))[0].label).
to eq({:callback => :refresh, :event => :ALL_EVENTS})
end
it "should not add labels to edges that have none" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
Class[a] -> b { "testing": }
MANIFEST
expect(relationship_graph.edges_between(
vertex_called(relationship_graph, completed_sentinel_of("class[A]")),
vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")))[0].label).
to be_empty
end
it "should copy notification labels to all created edges" do
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
class a {
notify { "class a": }
}
define b() {
notify { "define b": }
}
include a
Class[a] ~> b { "testing": }
MANIFEST
expect(relationship_graph.edges_between(
vertex_called(relationship_graph, admissible_sentinel_of("b[testing]")),
vertex_called(relationship_graph, "Notify[define b]"))[0].label).
to eq({:callback => :refresh, :event => :ALL_EVENTS})
end
end
def vertex_called(graph, name)
graph.vertices.find { |v| v.ref =~ /#{Regexp.escape(name)}/ }
end
def stub_vertex(name)
double("vertex #{name}", :ref => name)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings/port_setting_spec.rb | spec/unit/settings/port_setting_spec.rb | require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/port_setting'
describe Puppet::Settings::PortSetting do
let(:setting) { described_class.new(:settings => double('settings'), :desc => "test") }
it "is of type :port" do
expect(setting.type).to eq(:port)
end
describe "when munging the setting" do
it "returns the same value if given a valid port as integer" do
expect(setting.munge(5)).to eq(5)
end
it "returns an integer if given valid port as string" do
expect(setting.munge('12')).to eq(12)
end
it "raises if given a negative port number" do
expect { setting.munge('-5') }.to raise_error(Puppet::Settings::ValidationError)
end
it "raises if the port number is too high" do
expect { setting.munge(65536) }.to raise_error(Puppet::Settings::ValidationError)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings/directory_setting_spec.rb | spec/unit/settings/directory_setting_spec.rb | require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/directory_setting'
describe Puppet::Settings::DirectorySetting do
DirectorySetting = Puppet::Settings::DirectorySetting
include PuppetSpec::Files
before do
@basepath = make_absolute("/somepath")
end
describe "when being converted to a resource" do
before do
@settings = double('settings')
@dir = Puppet::Settings::DirectorySetting.new(
:settings => @settings, :desc => "eh", :name => :mydir, :section => "mysect")
allow(@settings).to receive(:value).with(:mydir).and_return(@basepath)
end
it "should return :directory as its type" do
expect(@dir.type).to eq(:directory)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings/integer_setting_spec.rb | spec/unit/settings/integer_setting_spec.rb | require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/integer_setting'
describe Puppet::Settings::IntegerSetting do
let(:setting) { described_class.new(:settings => double('settings'), :desc => "test") }
it "is of type :integer" do
expect(setting.type).to eq(:integer)
end
describe "when munging the setting" do
it "returns the same value if given a positive integer" do
expect(setting.munge(5)).to eq(5)
end
it "returns the same value if given a negative integer" do
expect(setting.munge(-25)).to eq(-25)
end
it "returns an integer if given a valid integer as string" do
expect(setting.munge('12')).to eq(12)
end
it "returns an integer if given a valid negative integer as string" do
expect(setting.munge('-12')).to eq(-12)
end
it "returns an integer if given a valid positive integer as string" do
expect(setting.munge('+12')).to eq(12)
end
it "raises if given an invalid value" do
expect { setting.munge('a5') }.to raise_error(Puppet::Settings::ValidationError)
end
it "raises if given nil" do
expect { setting.munge(nil) }.to raise_error(Puppet::Settings::ValidationError)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings/http_extra_headers_spec.rb | spec/unit/settings/http_extra_headers_spec.rb | require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/http_extra_headers_setting'
describe Puppet::Settings::HttpExtraHeadersSetting do
subject { described_class.new(:settings => double('settings'), :desc => "test") }
it "is of type :http_extra_headers" do
expect(subject.type).to eq :http_extra_headers
end
describe "munging the value" do
let(:final_value) { [['header1', 'foo'], ['header2', 'bar']] }
describe "when given a string" do
it "splits multiple values into an array" do
expect(subject.munge("header1:foo,header2:bar")).to match_array(final_value)
end
it "strips whitespace between elements" do
expect(subject.munge("header1:foo , header2:bar")).to match_array(final_value)
end
it "creates an array when one item is given" do
expect(subject.munge("header1:foo")).to match_array([['header1', 'foo']])
end
end
describe "when given an array of strings" do
it "returns an array of arrays" do
expect(subject.munge(['header1:foo', 'header2:bar'])).to match_array(final_value)
end
end
describe "when given an array of arrays" do
it "returns an array of arrays" do
expect(subject.munge([['header1', 'foo'], ['header2', 'bar']])).to match_array(final_value)
end
end
describe "when given a hash" do
it "returns the hash" do
expect(subject.munge({'header1' => 'foo', 'header2' => 'bar'})).to match_array(final_value)
end
end
describe 'raises an error when' do
it 'is given an unexpected object type' do
expect {
subject.munge(65)
}.to raise_error(ArgumentError, /^Expected an Array, String, or Hash, got a Integer/)
end
it 'is given an array of unexpected object types' do
expect {
subject.munge([65, 82])
}.to raise_error(ArgumentError, /^Expected an Array or String, got a Integer/)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings/file_setting_spec.rb | spec/unit/settings/file_setting_spec.rb | require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/file_setting'
describe Puppet::Settings::FileSetting do
FileSetting = Puppet::Settings::FileSetting
include PuppetSpec::Files
describe "when controlling permissions" do
def settings(wanted_values = {})
real_values = {
:user => 'root',
:group => 'root',
:mkusers => false,
:service_user_available? => false,
:service_group_available? => false
}.merge(wanted_values)
settings = double("settings")
allow(settings).to receive(:[]).with(:user).and_return(real_values[:user])
allow(settings).to receive(:[]).with(:group).and_return(real_values[:group])
allow(settings).to receive(:[]).with(:mkusers).and_return(real_values[:mkusers])
allow(settings).to receive(:service_user_available?).and_return(real_values[:service_user_available?])
allow(settings).to receive(:service_group_available?).and_return(real_values[:service_group_available?])
settings
end
context "owner" do
it "can always be root" do
settings = settings(:user => "the_service", :mkusers => true)
setting = FileSetting.new(:settings => settings, :owner => "root", :desc => "a setting")
expect(setting.owner).to eq("root")
end
it "is the service user if we are making users" do
settings = settings(:user => "the_service", :mkusers => true, :service_user_available? => false)
setting = FileSetting.new(:settings => settings, :owner => "service", :desc => "a setting")
expect(setting.owner).to eq("the_service")
end
it "is the service user if the user is available on the system" do
settings = settings(:user => "the_service", :mkusers => false, :service_user_available? => true)
setting = FileSetting.new(:settings => settings, :owner => "service", :desc => "a setting")
expect(setting.owner).to eq("the_service")
end
it "is root when the setting specifies service and the user is not available on the system" do
settings = settings(:user => "the_service", :mkusers => false, :service_user_available? => false)
setting = FileSetting.new(:settings => settings, :owner => "service", :desc => "a setting")
expect(setting.owner).to eq("root")
end
it "is unspecified when no specific owner is wanted" do
expect(FileSetting.new(:settings => settings(), :desc => "a setting").owner).to be_nil
end
it "does not allow other owners" do
expect { FileSetting.new(:settings => settings(), :desc => "a setting", :name => "testing", :default => "the default", :owner => "invalid") }.
to raise_error(FileSetting::SettingError, /The :owner parameter for the setting 'testing' must be either 'root' or 'service'/)
end
end
context "group" do
it "is unspecified when no specific group is wanted" do
setting = FileSetting.new(:settings => settings(), :desc => "a setting")
expect(setting.group).to be_nil
end
it "is root if root is requested" do
settings = settings(:group => "the_group")
setting = FileSetting.new(:settings => settings, :group => "root", :desc => "a setting")
expect(setting.group).to eq("root")
end
it "is the service group if we are making users" do
settings = settings(:group => "the_service", :mkusers => true)
setting = FileSetting.new(:settings => settings, :group => "service", :desc => "a setting")
expect(setting.group).to eq("the_service")
end
it "is the service user if the group is available on the system" do
settings = settings(:group => "the_service", :mkusers => false, :service_group_available? => true)
setting = FileSetting.new(:settings => settings, :group => "service", :desc => "a setting")
expect(setting.group).to eq("the_service")
end
it "is unspecified when the setting specifies service and the group is not available on the system" do
settings = settings(:group => "the_service", :mkusers => false, :service_group_available? => false)
setting = FileSetting.new(:settings => settings, :group => "service", :desc => "a setting")
expect(setting.group).to be_nil
end
it "does not allow other groups" do
expect { FileSetting.new(:settings => settings(), :group => "invalid", :name => 'testing', :desc => "a setting") }.
to raise_error(FileSetting::SettingError, /The :group parameter for the setting 'testing' must be either 'root' or 'service'/)
end
end
end
it "should be able to be converted into a resource" do
expect(FileSetting.new(:settings => double("settings"), :desc => "eh")).to respond_to(:to_resource)
end
describe "when being converted to a resource" do
before do
@basepath = make_absolute("/somepath")
allow(Puppet::FileSystem).to receive(:exist?).and_call_original
allow(Puppet::FileSystem).to receive(:exist?).with(@basepath).and_return(true)
@settings = double('settings')
@file = Puppet::Settings::FileSetting.new(:settings => @settings, :desc => "eh", :name => :myfile, :section => "mysect")
allow(@settings).to receive(:value).with(:myfile, nil, false).and_return(@basepath)
end
it "should return :file as its type" do
expect(@file.type).to eq(:file)
end
it "skips non-existent files" do
expect(@file).to receive(:type).and_return(:file)
expect(Puppet::FileSystem).to receive(:exist?).with(@basepath).and_return(false)
expect(@file.to_resource).to be_nil
end
it "manages existing files" do
expect(@file).to receive(:type).and_return(:file)
expect(@file.to_resource).to be_instance_of(Puppet::Resource)
end
it "always manages directories" do
expect(@file).to receive(:type).and_return(:directory)
expect(@file.to_resource).to be_instance_of(Puppet::Resource)
end
describe "on POSIX systems", :if => Puppet.features.posix? do
it "should skip files in /dev" do
allow(@settings).to receive(:value).with(:myfile, nil, false).and_return("/dev/file")
expect(@file.to_resource).to be_nil
end
end
it "should skip files whose paths are not strings" do
allow(@settings).to receive(:value).with(:myfile, nil, false).and_return(:foo)
expect(@file.to_resource).to be_nil
end
it "should return a file resource with the path set appropriately" do
resource = @file.to_resource
expect(resource.type).to eq("File")
expect(resource.title).to eq(@basepath)
end
it "should have a working directory with a root directory not called dev", :if => Puppet::Util::Platform.windows? do
# Although C:\Dev\.... is a valid path on Windows, some other code may regard it as a path to be ignored. e.g. /dev/null resolves to C:\dev\null on Windows.
path = File.expand_path('somefile')
expect(path).to_not match(/^[A-Z]:\/dev/i)
end
it "should fully qualified returned files if necessary (#795)" do
allow(@settings).to receive(:value).with(:myfile, nil, false).and_return("myfile")
path = File.expand_path('myfile')
allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect(@file.to_resource.title).to eq(path)
end
it "should set the mode on the file if a mode is provided as an octal number" do
Puppet[:manage_internal_file_permissions] = true
@file.mode = 0755
expect(@file.to_resource[:mode]).to eq('755')
end
it "should set the mode on the file if a mode is provided as a string" do
Puppet[:manage_internal_file_permissions] = true
@file.mode = '0755'
expect(@file.to_resource[:mode]).to eq('755')
end
it "should not set the mode on a the file if manage_internal_file_permissions is disabled" do
Puppet[:manage_internal_file_permissions] = false
allow(@file).to receive(:mode).and_return(0755)
expect(@file.to_resource[:mode]).to eq(nil)
end
it "should set the owner if running as root and the owner is provided" do
Puppet[:manage_internal_file_permissions] = true
expect(Puppet.features).to receive(:root?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
allow(@file).to receive(:owner).and_return("foo")
expect(@file.to_resource[:owner]).to eq("foo")
end
it "should not set the owner if manage_internal_file_permissions is disabled" do
Puppet[:manage_internal_file_permissions] = false
allow(Puppet.features).to receive(:root?).and_return(true)
allow(@file).to receive(:owner).and_return("foo")
expect(@file.to_resource[:owner]).to eq(nil)
end
it "should set the group if running as root and the group is provided" do
Puppet[:manage_internal_file_permissions] = true
expect(Puppet.features).to receive(:root?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
allow(@file).to receive(:group).and_return("foo")
expect(@file.to_resource[:group]).to eq("foo")
end
it "should not set the group if manage_internal_file_permissions is disabled" do
Puppet[:manage_internal_file_permissions] = false
allow(Puppet.features).to receive(:root?).and_return(true)
allow(@file).to receive(:group).and_return("foo")
expect(@file.to_resource[:group]).to eq(nil)
end
it "should not set owner if not running as root" do
Puppet[:manage_internal_file_permissions] = true
expect(Puppet.features).to receive(:root?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
allow(@file).to receive(:owner).and_return("foo")
expect(@file.to_resource[:owner]).to be_nil
end
it "should not set group if not running as root" do
Puppet[:manage_internal_file_permissions] = true
expect(Puppet.features).to receive(:root?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
allow(@file).to receive(:group).and_return("foo")
expect(@file.to_resource[:group]).to be_nil
end
describe "on Microsoft Windows systems" do
before :each do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
it "should not set owner" do
allow(@file).to receive(:owner).and_return("foo")
expect(@file.to_resource[:owner]).to be_nil
end
it "should not set group" do
allow(@file).to receive(:group).and_return("foo")
expect(@file.to_resource[:group]).to be_nil
end
end
it "should set :ensure to the file type" do
expect(@file).to receive(:type).and_return(:directory)
expect(@file.to_resource[:ensure]).to eq(:directory)
end
it "should set the loglevel to :debug" do
expect(@file.to_resource[:loglevel]).to eq(:debug)
end
it "should set the backup to false" do
expect(@file.to_resource[:backup]).to be_falsey
end
it "should tag the resource with the settings section" do
expect(@file).to receive(:section).and_return("mysect")
expect(@file.to_resource).to be_tagged("mysect")
end
it "should tag the resource with the setting name" do
expect(@file.to_resource).to be_tagged("myfile")
end
it "should tag the resource with 'settings'" do
expect(@file.to_resource).to be_tagged("settings")
end
it "should set links to 'follow'" do
expect(@file.to_resource[:links]).to eq(:follow)
end
end
describe "#munge" do
it 'does not expand the path of the special value :memory: so we can set dblocation to an in-memory database' do
filesetting = FileSetting.new(:settings => double("settings"), :desc => "eh")
expect(filesetting.munge(':memory:')).to eq(':memory:')
end
end
context "when opening", :unless => Puppet::Util::Platform.windows? do
let(:path) do
tmpfile('file_setting_spec')
end
let(:setting) do
settings = double("settings", :value => path)
FileSetting.new(:name => :mysetting, :desc => "creates a file", :settings => settings)
end
it "creates a file with mode 0640" do
setting.mode = '0640'
expect(File).to_not be_exist(path)
setting.open('w')
expect(File).to be_exist(path)
expect(Puppet::FileSystem.stat(path).mode & 0777).to eq(0640)
end
it "preserves the mode of an existing file" do
setting.mode = '0640'
Puppet::FileSystem.touch(path)
Puppet::FileSystem.chmod(0644, path)
setting.open('w')
expect(Puppet::FileSystem.stat(path).mode & 0777).to eq(0644)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings/config_file_spec.rb | spec/unit/settings/config_file_spec.rb | require 'spec_helper'
require 'puppet/settings/config_file'
describe Puppet::Settings::ConfigFile do
NOTHING = {}
def the_parse_of(*lines)
config.parse_file(filename, lines.join("\n"))
end
let(:identity_transformer) { Proc.new { |value| value } }
let(:config) { Puppet::Settings::ConfigFile.new(identity_transformer) }
let(:filename) { "a/fake/filename.conf" }
Conf = Puppet::Settings::ConfigFile::Conf
Section = Puppet::Settings::ConfigFile::Section
Meta = Puppet::Settings::ConfigFile::Meta
NO_META = Puppet::Settings::ConfigFile::NO_META
it "interprets an empty file to contain a main section with no entries" do
result = the_parse_of("")
expect(result).to eq(Conf.new.with_section(Section.new(:main)))
end
it "interprets an empty main section the same as an empty file" do
expect(the_parse_of("")).to eq(config.parse_file(filename, "[main]"))
end
it "places an entry in no section in main" do
result = the_parse_of("var = value")
expect(result).to eq(Conf.new.with_section(Section.new(:main).with_setting(:var, "value", NO_META)))
end
it "places an entry after a section header in that section" do
result = the_parse_of("[agent]", "var = value")
expect(result).to eq(Conf.new.
with_section(Section.new(:main)).
with_section(Section.new(:agent).
with_setting(:var, "value", NO_META)))
end
it "does not include trailing whitespace in the value" do
result = the_parse_of("var = value\t ")
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:var, "value", NO_META)))
end
it "does not include leading whitespace in the name" do
result = the_parse_of(" \t var=value")
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:var, "value", NO_META)))
end
it "skips lines that are commented out" do
result = the_parse_of("#var = value")
expect(result).to eq(Conf.new.with_section(Section.new(:main)))
end
it "skips lines that are entirely whitespace" do
result = the_parse_of(" \t ")
expect(result).to eq(Conf.new.with_section(Section.new(:main)))
end
it "errors when a line is not a known form" do
expect { the_parse_of("unknown") }.to raise_error Puppet::Settings::ParseError, /Could not match line/
end
it "errors providing correct line number when line is not a known form" do
multi_line_config = <<-EOF
[main]
foo=bar
badline
EOF
expect { the_parse_of(multi_line_config) }.to(
raise_error(Puppet::Settings::ParseError, /Could not match line/) do |exception|
expect(exception.line).to eq(3)
end
)
end
it "stores file meta information in the _meta section" do
result = the_parse_of("var = value { owner = me, group = you, mode = 0666 }")
expect(result).to eq(Conf.new.with_section(Section.new(:main).
with_setting(:var, "value",
Meta.new("me", "you", "0666"))))
end
it "errors when there is unknown meta information" do
expect { the_parse_of("var = value { unknown = no }") }.
to raise_error ArgumentError, /Invalid file option 'unknown'/
end
it "errors when the mode is not numeric" do
expect { the_parse_of("var = value { mode = no }") }.
to raise_error ArgumentError, "File modes must be numbers"
end
it "errors when the options are not key-value pairs" do
expect { the_parse_of("var = value { mode }") }.
to raise_error ArgumentError, "Could not parse 'value { mode }'"
end
it "may specify legal sections" do
text = <<-EOF
[legal]
a = 'b'
[illegal]
one = 'e'
two = 'f'
EOF
expect { config.parse_file(filename, text, [:legal]) }.
to raise_error Puppet::Error,
/Illegal section 'legal' in config file at \(file: #{filename}, line: 1\)/
end
it "transforms values with the given function" do
config = Puppet::Settings::ConfigFile.new(Proc.new { |value| value + " changed" })
result = config.parse_file(filename, "var = value")
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:var, "value changed", NO_META)))
end
it "accepts non-UTF8 encoded text" do
result = the_parse_of("var = value".encode("UTF-16LE"))
expect(result).to eq(Conf.new.
with_section(Section.new(:main).
with_setting(:var, "value", NO_META)))
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings/string_setting_spec.rb | spec/unit/settings/string_setting_spec.rb | require 'spec_helper'
require 'puppet/settings'
require 'puppet/settings/string_setting'
describe Puppet::Settings::StringSetting do
StringSetting = Puppet::Settings::StringSetting
before(:each) do
@test_setting_name = :test_setting
@test_setting_default = "my_crazy_default/$var"
@application_setting = "application/$var"
@application_defaults = { }
Puppet::Settings::REQUIRED_APP_SETTINGS.each do |key|
@application_defaults[key] = "foo"
end
@application_defaults[:run_mode] = :user
@settings = Puppet::Settings.new
@application_defaults.each { |k,v| @settings.define_settings :main, k => {:default=>"", :desc => "blah"} }
@settings.define_settings :main, :var => { :default => "interpolate!",
:type => :string,
:desc => "my var desc" },
@test_setting_name => { :default => @test_setting_default,
:type => :string,
:desc => "my test desc" }
@test_setting = @settings.setting(@test_setting_name)
end
describe "#default" do
describe "with no arguments" do
it "should return the setting default" do
expect(@test_setting.default).to eq(@test_setting_default)
end
it "should be uninterpolated" do
expect(@test_setting.default).not_to match(/interpolate/)
end
end
describe "checking application defaults first" do
describe "if application defaults set" do
before(:each) do
@settings.initialize_app_defaults @application_defaults.merge @test_setting_name => @application_setting
end
it "should return the application-set default" do
expect(@test_setting.default(true)).to eq(@application_setting)
end
it "should be uninterpolated" do
expect(@test_setting.default(true)).not_to match(/interpolate/)
end
end
describe "if application defaults not set" do
it "should return the regular default" do
expect(@test_setting.default(true)).to eq(@test_setting_default)
end
it "should be uninterpolated" do
expect(@test_setting.default(true)).not_to match(/interpolate/)
end
end
end
end
describe "#value" do
it "should be interpolated" do
expect(@test_setting.value).to match(/interpolate/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.