repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/lockfile_spec.rb
spec/unit/util/lockfile_spec.rb
require 'spec_helper' require 'puppet/util/lockfile' module LockfileSpecHelper def self.run_in_forks(count, &blk) forks = {} results = [] count.times do |i| forks[i] = {} forks[i][:read], forks[i][:write] = IO.pipe forks[i][:pid] = fork do forks[i][:read].close res = yield Marshal.dump(res, forks[i][:write]) exit! end end count.times do |i| forks[i][:write].close result = forks[i][:read].read forks[i][:read].close Process.wait2(forks[i][:pid]) results << Marshal.load(result) end results end end describe Puppet::Util::Lockfile do require 'puppet_spec/files' include PuppetSpec::Files before(:each) do @lockfile = tmpfile("lock") @lock = Puppet::Util::Lockfile.new(@lockfile) end describe "#lock" do it "should return true if it successfully locked" do expect(@lock.lock).to be_truthy end it "should return false if already locked" do @lock.lock expect(@lock.lock).to be_falsey end it "should create a lock file" do @lock.lock expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy end # We test simultaneous locks using fork which isn't supported on Windows. it "should not be acquired by another process", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do 30.times do forks = 3 results = LockfileSpecHelper.run_in_forks(forks) do @lock.lock(Process.pid) end @lock.unlock # Confirm one fork returned true and everyone else false. expect((results - [true]).size).to eq(forks - 1) expect((results - [false]).size).to eq(1) end end it "should create a lock file containing a string" do data = "foofoo barbar" @lock.lock(data) expect(File.read(@lockfile)).to eq(data) end end describe "#unlock" do it "should return true when unlocking" do @lock.lock expect(@lock.unlock).to be_truthy end it "should return false when not locked" do expect(@lock.unlock).to be_falsey end it "should clear the lock file" do File.open(@lockfile, 'w') { |fd| fd.print("locked") } @lock.unlock expect(Puppet::FileSystem.exist?(@lockfile)).to be_falsey end end it "should be locked when locked" do @lock.lock expect(@lock).to be_locked end it "should not be locked when not locked" do expect(@lock).not_to be_locked end it "should not be locked when unlocked" do @lock.lock @lock.unlock expect(@lock).not_to be_locked end it "should return the lock data" do data = "foofoo barbar" @lock.lock(data) expect(@lock.lock_data).to eq(data) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/filetype_spec.rb
spec/unit/util/filetype_spec.rb
require 'spec_helper' require 'puppet/util/filetype' # XXX Import all of the tests into this file. describe Puppet::Util::FileType do describe "the flat filetype" do let(:path) { '/my/file' } let(:type) { Puppet::Util::FileType.filetype(:flat) } let(:file) { type.new(path) } it "should exist" do expect(type).not_to be_nil end describe "when the file already exists" do it "should return the file's contents when asked to read it" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding.default_external}).and_return("my text") expect(file.read).to eq("my text") end it "should unlink the file when asked to remove it" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) expect(Puppet::FileSystem).to receive(:unlink).with(path) file.remove end end describe "when the file does not exist" do it "should return an empty string when asked to read the file" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false) expect(file.read).to eq("") end end describe "when writing the file" do let(:tempfile) { double('tempfile', :print => nil, :close => nil, :flush => nil, :path => "/other/file") } before do allow(FileUtils).to receive(:cp) allow(Tempfile).to receive(:new).and_return(tempfile) end it "should first create a temp file and copy its contents over to the file location" do expect(Tempfile).to receive(:new).with("puppet", {:encoding => Encoding.default_external}).and_return(tempfile) expect(tempfile).to receive(:print).with("my text") expect(tempfile).to receive(:flush) expect(tempfile).to receive(:close) expect(FileUtils).to receive(:cp).with(tempfile.path, path) file.write "my text" end it "should set the selinux default context on the file" do expect(file).to receive(:set_selinux_default_context).with(path) file.write "eh" end end describe "when backing up a file" do it "should do nothing if the file does not exist" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false) expect(file).not_to receive(:bucket) file.backup end it "should use its filebucket to backup the file if it exists" do expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true) bucket = double('bucket') expect(bucket).to receive(:backup).with(path) expect(file).to receive(:bucket).and_return(bucket) file.backup end it "should use the default filebucket" do bucket = double('bucket') expect(bucket).to receive(:bucket).and_return("mybucket") expect(Puppet::Type.type(:filebucket)).to receive(:mkdefaultbucket).and_return(bucket) expect(file.bucket).to eq("mybucket") end end end shared_examples_for "crontab provider" do let(:cron) { type.new('no_such_user') } let(:crontab) { File.read(my_fixture(crontab_output)) } let(:options) { { :failonfail => true, :combine => true } } let(:uid) { 'no_such_user' } let(:user_options) { options.merge({:uid => uid}) } it "should exist" do expect(type).not_to be_nil end # make Puppet::Util::SUIDManager return something deterministic, not the # uid of the user running the tests, except where overridden below. before :each do allow(Puppet::Util::SUIDManager).to receive(:uid).and_return(1234) end describe "#read" do before(:each) do allow(Puppet::Util).to receive(:uid).with(uid).and_return(9000) end it "should run crontab -l as the target user" do expect(Puppet::Util::Execution).to receive(:execute) .with(['crontab', '-l'], user_options) .and_return(Puppet::Util::Execution::ProcessOutput.new(crontab, 0)) expect(cron.read).to eq(crontab) end it "should not switch user if current user is the target user" do expect(Puppet::Util).to receive(:uid).with(uid).twice.and_return(9000) expect(Puppet::Util::SUIDManager).to receive(:uid).and_return(9000) expect(Puppet::Util::Execution).to receive(:execute) .with(['crontab', '-l'], options) .and_return(Puppet::Util::Execution::ProcessOutput.new(crontab, 0)) expect(cron.read).to eq(crontab) end it "should treat an absent crontab as empty" do expect(Puppet::Util::Execution).to receive(:execute).with(['crontab', '-l'], user_options).and_raise(Puppet::ExecutionFailure, absent_crontab) expect(cron.read).to eq('') end it "should treat a nonexistent user's crontab as empty" do expect(Puppet::Util).to receive(:uid).with(uid).and_return(nil) expect(cron.read).to eq('') end it "should return empty if the user is not authorized to use cron" do expect(Puppet::Util::Execution).to receive(:execute).with(['crontab', '-l'], user_options).and_raise(Puppet::ExecutionFailure, unauthorized_crontab) expect(cron.read).to eq('') end end describe "#remove" do it "should run crontab -r as the target user" do expect(Puppet::Util::Execution).to receive(:execute).with(['crontab', '-r'], user_options) cron.remove end it "should not switch user if current user is the target user" do expect(Puppet::Util).to receive(:uid).with(uid).and_return(9000) expect(Puppet::Util::SUIDManager).to receive(:uid).and_return(9000) expect(Puppet::Util::Execution).to receive(:execute).with(['crontab','-r'], options) cron.remove end end describe "#write" do before :each do @tmp_cron = Tempfile.new("puppet_crontab_spec") @tmp_cron_path = @tmp_cron.path allow(Puppet::Util).to receive(:uid).with(uid).and_return(9000) expect(Tempfile).to receive(:new).with("puppet_#{name}", {:encoding => Encoding.default_external}).and_return(@tmp_cron) end after :each do expect(Puppet::FileSystem.exist?(@tmp_cron_path)).to be_falsey end it "should run crontab as the target user on a temporary file" do expect(File).to receive(:chown).with(9000, nil, @tmp_cron_path) expect(Puppet::Util::Execution).to receive(:execute).with(["crontab", @tmp_cron_path], user_options) expect(@tmp_cron).to receive(:print).with("foo\n") cron.write "foo\n" end it "should not switch user if current user is the target user" do expect(Puppet::Util::SUIDManager).to receive(:uid).and_return(9000) expect(File).to receive(:chown).with(9000, nil, @tmp_cron_path) expect(Puppet::Util::Execution).to receive(:execute).with(["crontab", @tmp_cron_path], options) expect(@tmp_cron).to receive(:print).with("foo\n") cron.write "foo\n" end end end describe "the suntab filetype", :unless => Puppet::Util::Platform.windows? do let(:type) { Puppet::Util::FileType.filetype(:suntab) } let(:name) { type.name } let(:crontab_output) { 'suntab_output' } # possible crontab output was taken from here: # https://docs.oracle.com/cd/E19082-01/819-2380/sysrescron-60/index.html let(:absent_crontab) do 'crontab: can\'t open your crontab file' end let(:unauthorized_crontab) do 'crontab: you are not authorized to use cron. Sorry.' end it_should_behave_like "crontab provider" end describe "the aixtab filetype", :unless => Puppet::Util::Platform.windows? do let(:type) { Puppet::Util::FileType.filetype(:aixtab) } let(:name) { type.name } let(:crontab_output) { 'aixtab_output' } let(:absent_crontab) do '0481-103 Cannot open a file in the /var/spool/cron/crontabs directory.' end let(:unauthorized_crontab) do '0481-109 You are not authorized to use the cron command.' end it_should_behave_like "crontab provider" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/json_spec.rb
spec/unit/util/json_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet/util/json' describe Puppet::Util::Json do include PuppetSpec::Files shared_examples_for 'json file loader' do |load_method| it 'reads a JSON file from disk' do file_path = file_containing('input', JSON.dump({ "my" => "data" })) expect(load_method.call(file_path)).to eq({ "my" => "data" }) end it 'reads JSON as UTF-8' do file_path = file_containing('input', JSON.dump({ "my" => "𠜎" })) expect(load_method.call(file_path)).to eq({ "my" => "𠜎" }) end end context "#load" do it 'raises an error if JSON is invalid' do expect { Puppet::Util::Json.load('{ invalid') }.to raise_error(Puppet::Util::Json::ParseError, /unexpected token at '{ invalid'/) end it 'raises an error if the content is empty' do expect { Puppet::Util::Json.load('') }.to raise_error(Puppet::Util::Json::ParseError) end it 'loads true' do expect(Puppet::Util::Json.load('true')).to eq(true) end it 'loads false' do expect(Puppet::Util::Json.load('false')).to eq(false) end it 'loads a numeric' do expect(Puppet::Util::Json.load('42')).to eq(42) end it 'loads a string' do expect(Puppet::Util::Json.load('"puppet"')).to eq('puppet') end it 'loads an array' do expect(Puppet::Util::Json.load(<<~JSON)).to eq([1, 2]) [1, 2] JSON end it 'loads a hash' do expect(Puppet::Util::Json.load(<<~JSON)).to eq('a' => 1, 'b' => 2) { "a": 1, "b": 2 } JSON end end context "load_file_if_valid" do before do Puppet[:log_level] = 'debug' end it_should_behave_like 'json file loader', Puppet::Util::Json.method(:load_file_if_valid) it 'returns nil when the file is invalid JSON and debug logs about it' do file_path = file_containing('input', '{ invalid') expect(Puppet).to receive(:debug) .with(/Could not retrieve JSON content .+: unexpected token at '{ invalid'/).and_call_original expect(Puppet::Util::Json.load_file_if_valid(file_path)).to eql(nil) end it 'returns nil when the filename is illegal and debug logs about it' do expect(Puppet).to receive(:debug) .with(/Could not retrieve JSON content .+: pathname contains null byte/).and_call_original expect(Puppet::Util::Json.load_file_if_valid("not\0allowed")).to eql(nil) end it 'returns nil when the file does not exist and debug logs about it' do expect(Puppet).to receive(:debug) .with(/Could not retrieve JSON content .+: No such file or directory/).and_call_original expect(Puppet::Util::Json.load_file_if_valid('does/not/exist.json')).to eql(nil) end end context '#load_file' do it_should_behave_like 'json file loader', Puppet::Util::Json.method(:load_file) it 'raises an error when the file is invalid JSON' do file_path = file_containing('input', '{ invalid') expect { Puppet::Util::Json.load_file(file_path) }.to raise_error(Puppet::Util::Json::ParseError, /unexpected token at '{ invalid'/) end it 'raises an error when the filename is illegal' do expect { Puppet::Util::Json.load_file("not\0allowed") }.to raise_error(ArgumentError, /null byte/) end it 'raises an error when the file does not exist' do expect { Puppet::Util::Json.load_file('does/not/exist.json') }.to raise_error(Errno::ENOENT, /No such file or directory/) end it 'writes data formatted as JSON to disk' do file_path = file_containing('input', Puppet::Util::Json.dump({ "my" => "data" })) expect(Puppet::Util::Json.load_file(file_path)).to eq({ "my" => "data" }) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/checksums_spec.rb
spec/unit/util/checksums_spec.rb
require 'spec_helper' require 'puppet/util/checksums' describe Puppet::Util::Checksums do include PuppetSpec::Files before do @summer = Puppet::Util::Checksums end content_sums = [:md5, :md5lite, :sha1, :sha1lite, :sha256, :sha256lite, :sha512, :sha384, :sha224] file_only = [:ctime, :mtime, :none] content_sums.each do |sumtype| it "should be able to calculate #{sumtype} sums from strings" do expect(@summer).to be_respond_to(sumtype) end end content_sums.each do |sumtype| it "should know the expected length of #{sumtype} sums" do expect(@summer).to be_respond_to(sumtype.to_s + "_hex_length") end end [content_sums, file_only].flatten.each do |sumtype| it "should be able to calculate #{sumtype} sums from files" do expect(@summer).to be_respond_to(sumtype.to_s + "_file") end end [content_sums, file_only].flatten.each do |sumtype| it "should be able to calculate #{sumtype} sums from stream" do expect(@summer).to be_respond_to(sumtype.to_s + "_stream") end end it "should have a method for determining whether a given string is a checksum" do expect(@summer).to respond_to(:checksum?) end %w{{md5}asdfasdf {sha1}asdfasdf {ctime}asdasdf {mtime}asdfasdf {sha256}asdfasdf {sha256lite}asdfasdf {sha512}asdfasdf {sha384}asdfasdf {sha224}asdfasdf}.each do |sum| it "should consider #{sum} to be a checksum" do expect(@summer).to be_checksum(sum) end end %w{{nosuchsumthislong}asdfasdf {a}asdfasdf {ctime}}.each do |sum| it "should not consider #{sum} to be a checksum" do expect(@summer).not_to be_checksum(sum) end end it "should have a method for stripping a sum type from an existing checksum" do expect(@summer.sumtype("{md5}asdfasdfa")).to eq("md5") end it "should have a method for stripping the data from a checksum" do expect(@summer.sumdata("{md5}asdfasdfa")).to eq("asdfasdfa") end it "should return a nil sumtype if the checksum does not mention a checksum type" do expect(@summer.sumtype("asdfasdfa")).to be_nil end it "has a list of known checksum types" do expect(@summer.known_checksum_types).to match_array(content_sums + file_only) end it "returns true if the checksum is valid" do expect(@summer).to be_valid_checksum('sha1', 'fcc1715b22278a9dae322b0a34935f10d1608b9f') end it "returns false if the checksum is known but invalid" do expect(@summer).to_not be_valid_checksum('sha1', 'wronglength') end it "returns false if the checksum type is unknown" do expect(@summer).to_not be_valid_checksum('rot13', 'doesntmatter') end {:md5 => Digest::MD5, :sha1 => Digest::SHA1, :sha256 => Digest::SHA256, :sha512 => Digest::SHA512, :sha384 => Digest::SHA384}.each do |sum, klass| describe("when using #{sum}") do it "should use #{klass} to calculate string checksums" do expect(klass).to receive(:hexdigest).with("mycontent").and_return("whatever") expect(@summer.send(sum, "mycontent")).to eq("whatever") end it "should use incremental #{klass} sums to calculate file checksums" do digest = double('digest') expect(klass).to receive(:new).and_return(digest) file = "/path/to/my/file" fh = double('filehandle') expect(fh).to receive(:read).with(4096).exactly(3).times().and_return("firstline", "secondline", nil) expect(File).to receive(:open).with(file, "rb").and_yield(fh) expect(digest).to receive(:<<).with("firstline") expect(digest).to receive(:<<).with("secondline") expect(digest).to receive(:hexdigest).and_return(:mydigest) expect(@summer.send(sum.to_s + "_file", file)).to eq(:mydigest) end it "should behave like #{klass} to calculate stream checksums" do digest = double('digest') expect(klass).to receive(:new).and_return(digest) expect(digest).to receive(:<<).with "firstline" expect(digest).to receive(:<<).with "secondline" expect(digest).to receive(:hexdigest).and_return(:mydigest) expect(@summer.send(sum.to_s + "_stream") do |checksum| checksum << "firstline" checksum << "secondline" end).to eq(:mydigest) end end end {:md5lite => Digest::MD5, :sha1lite => Digest::SHA1, :sha256lite => Digest::SHA256}.each do |sum, klass| describe("when using #{sum}") do it "should use #{klass} to calculate string checksums from the first 512 characters of the string" do content = "this is a test" * 100 expect(klass).to receive(:hexdigest).with(content[0..511]).and_return("whatever") expect(@summer.send(sum, content)).to eq("whatever") end it "should use #{klass} to calculate a sum from the first 512 characters in the file" do digest = double('digest') expect(klass).to receive(:new).and_return(digest) file = "/path/to/my/file" fh = double('filehandle') expect(fh).to receive(:read).with(512).and_return('my content') expect(File).to receive(:open).with(file, "rb").and_yield(fh) expect(digest).to receive(:<<).with("my content") expect(digest).to receive(:hexdigest).and_return(:mydigest) expect(@summer.send(sum.to_s + "_file", file)).to eq(:mydigest) end it "should use #{klass} to calculate a sum from the first 512 characters in a stream" do digest = double('digest') content = "this is a test" * 100 expect(klass).to receive(:new).and_return(digest) expect(digest).to receive(:<<).with(content[0..511]) expect(digest).to receive(:hexdigest).and_return(:mydigest) expect(@summer.send(sum.to_s + "_stream") do |checksum| checksum << content end).to eq(:mydigest) end it "should use #{klass} to calculate a sum from the first 512 characters in a multi-part stream" do digest = double('digest') content = "this is a test" * 100 expect(klass).to receive(:new).and_return(digest) expect(digest).to receive(:<<).with(content[0..5]) expect(digest).to receive(:<<).with(content[6..510]) expect(digest).to receive(:<<).with(content[511..511]) expect(digest).to receive(:hexdigest).and_return(:mydigest) expect(@summer.send(sum.to_s + "_stream") do |checksum| checksum << content[0..5] checksum << content[6..510] checksum << content[511..-1] end).to eq(:mydigest) end end end [:ctime, :mtime].each do |sum| describe("when using #{sum}") do it "should use the '#{sum}' on the file to determine the ctime" do file = "/my/file" stat = double('stat', sum => "mysum") expect(Puppet::FileSystem).to receive(:stat).with(file).and_return(stat) expect(@summer.send(sum.to_s + "_file", file)).to eq("mysum") end it "should return nil for streams" do expectation = double("expectation") expect(expectation).to receive(:do_something!).at_least(:once) expect(@summer.send(sum.to_s + "_stream"){ |checksum| checksum << "anything" ; expectation.do_something! }).to be_nil end end end describe "when using the none checksum" do it "should return an empty string" do expect(@summer.none_file("/my/file")).to eq("") end it "should return an empty string for streams" do expectation = double("expectation") expect(expectation).to receive(:do_something!).at_least(:once) expect(@summer.none_stream{ |checksum| checksum << "anything" ; expectation.do_something! }).to eq("") end end {:md5 => Digest::MD5, :sha1 => Digest::SHA1}.each do |sum, klass| describe "when using #{sum}" do let(:content) { "hello\r\nworld" } let(:path) do path = tmpfile("checksum_#{sum}") File.open(path, 'wb') {|f| f.write(content)} path end it "should preserve nl/cr sequences" do expect(@summer.send(sum.to_s + "_file", path)).to eq(klass.hexdigest(content)) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/watched_file_spec.rb
spec/unit/util/watched_file_spec.rb
require 'spec_helper' require 'puppet/util/watched_file' require 'puppet/util/watcher' describe Puppet::Util::WatchedFile do let(:an_absurdly_long_timeout) { Puppet::Util::Watcher::Timer.new(100000) } let(:an_immediate_timeout) { Puppet::Util::Watcher::Timer.new(0) } it "acts like a string so that it can be used as a filename" do watched = Puppet::Util::WatchedFile.new("foo") expect(watched.to_str).to eq("foo") end it "considers the file to be unchanged before the timeout expires" do watched = Puppet::Util::WatchedFile.new(a_file_that_doesnt_exist, an_absurdly_long_timeout) expect(watched).to_not be_changed end it "considers a file that is created to be changed" do watched_filename = a_file_that_doesnt_exist watched = Puppet::Util::WatchedFile.new(watched_filename, an_immediate_timeout) create_file(watched_filename) expect(watched).to be_changed end it "considers a missing file to remain unchanged" do watched = Puppet::Util::WatchedFile.new(a_file_that_doesnt_exist, an_immediate_timeout) expect(watched).to_not be_changed end it "considers a file that has changed but the timeout is not expired to still be unchanged" do watched_filename = a_file_that_doesnt_exist watched = Puppet::Util::WatchedFile.new(watched_filename, an_absurdly_long_timeout) create_file(watched_filename) expect(watched).to_not be_changed end def create_file(name) File.open(name, "wb") { |file| file.puts("contents") } end def a_file_that_doesnt_exist PuppetSpec::Files.tmpfile("watched_file") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/resource_template_spec.rb
spec/unit/util/resource_template_spec.rb
require 'spec_helper' require 'puppet/util/resource_template' describe Puppet::Util::ResourceTemplate do describe "when initializing" do it "should fail if the template does not exist" do expect(Puppet::FileSystem).to receive(:exist?).with("/my/template").and_return(false) expect { Puppet::Util::ResourceTemplate.new("/my/template", double('resource')) }.to raise_error(ArgumentError) end it "should not create the ERB template" do expect(ERB).not_to receive(:new) expect(Puppet::FileSystem).to receive(:exist?).with("/my/template").and_return(true) Puppet::Util::ResourceTemplate.new("/my/template", double('resource')) end end describe "when evaluating" do before do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(Puppet::FileSystem).to receive(:read).and_return("eh") @template = double('template', :result => nil) allow(ERB).to receive(:new).and_return(@template) @resource = double('resource') @wrapper = Puppet::Util::ResourceTemplate.new("/my/template", @resource) end it "should set all of the resource's parameters as instance variables" do expect(@resource).to receive(:to_hash).and_return(:one => "uno", :two => "dos") expect(@template).to receive(:result) do |bind| expect(eval("@one", bind)).to eq("uno") expect(eval("@two", bind)).to eq("dos") end @wrapper.evaluate end it "should create a template instance with the contents of the file" do expect(Puppet::FileSystem).to receive(:read).with("/my/template", {:encoding => 'utf-8'}).and_return("yay") expect(Puppet::Util).to receive(:create_erb).with("yay").and_return(@template) allow(@wrapper).to receive(:set_resource_variables) @wrapper.evaluate end it "should return the result of the template" do allow(@wrapper).to receive(:set_resource_variables) expect(@wrapper).to receive(:binding).and_return("mybinding") expect(@template).to receive(:result).with("mybinding").and_return("myresult") expect(@wrapper.evaluate).to eq("myresult") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/skip_tags_spec.rb
spec/unit/util/skip_tags_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet/util/skip_tags' describe Puppet::Util::SkipTags do let(:tagger) { Puppet::Util::SkipTags.new([]) } it "should add qualified classes as single tags" do tagger.tag("one::two::three") expect(tagger.tags).to include("one::two::three") expect(tagger.tags).not_to include("one", "two", "three") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/yaml_spec.rb
spec/unit/util/yaml_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet/util/yaml' describe Puppet::Util::Yaml do include PuppetSpec::Files let(:filename) { tmpfile("yaml") } shared_examples_for 'yaml file loader' do |load_method| it 'returns false when the file is empty' do file_path = file_containing('input', '') expect(load_method.call(file_path)).to eq(false) end it 'reads a YAML file from disk' do file_path = file_containing('input', YAML.dump({ "my" => "data" })) expect(load_method.call(file_path)).to eq({ "my" => "data" }) end it 'reads YAML as UTF-8' do file_path = file_containing('input', YAML.dump({ "my" => "𠜎" })) expect(load_method.call(file_path)).to eq({ "my" => "𠜎" }) end end context "#safe_load" do it 'raises an error if YAML is invalid' do expect { Puppet::Util::Yaml.safe_load('{ invalid') }.to raise_error(Puppet::Util::Yaml::YamlLoadError, %r[\(<unknown>\): .* at line \d+ column \d+]) end it 'raises if YAML contains classes not in the list' do expect { Puppet::Util::Yaml.safe_load(<<FACTS, []) --- !ruby/object:Puppet::Node::Facts name: localhost FACTS }.to raise_error(Puppet::Util::Yaml::YamlLoadError, "(<unknown>): Tried to load unspecified class: Puppet::Node::Facts") end it 'includes the filename if YAML contains classes not in the list' do expect { Puppet::Util::Yaml.safe_load(<<FACTS, [], 'foo.yaml') --- !ruby/object:Puppet::Node::Facts name: localhost FACTS }.to raise_error(Puppet::Util::Yaml::YamlLoadError, "(foo.yaml): Tried to load unspecified class: Puppet::Node::Facts") end it 'allows classes to be loaded' do facts = Puppet::Util::Yaml.safe_load(<<FACTS, [Puppet::Node::Facts]) --- !ruby/object:Puppet::Node::Facts name: localhost values: puppetversion: 6.0.0 FACTS expect(facts.name).to eq('localhost') end it 'returns false if the content is empty' do expect(Puppet::Util::Yaml.safe_load('')).to eq(false) end it 'loads true' do expect(Puppet::Util::Yaml.safe_load('true')).to eq(true) end it 'loads false' do expect(Puppet::Util::Yaml.safe_load('false')).to eq(false) end it 'loads nil' do expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq('a' => nil) --- a: null YAML end it 'loads a numeric' do expect(Puppet::Util::Yaml.safe_load('42')).to eq(42) end it 'loads a string' do expect(Puppet::Util::Yaml.safe_load('puppet')).to eq('puppet') end it 'loads an array' do expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq([1, 2]) --- - 1 - 2 YAML end it 'loads a hash' do expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq('a' => 1, 'b' => 2) --- a: 1 b: 2 YAML end it 'loads an alias' do expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq('a' => [], 'b' => []) --- a: &1 [] b: *1 YAML end end context "#safe_load_file" do it_should_behave_like 'yaml file loader', Puppet::Util::Yaml.method(:safe_load_file) it 'raises an error when the file is invalid YAML' do file_path = file_containing('input', '{ invalid') expect { Puppet::Util::Yaml.safe_load_file(file_path) }.to raise_error(Puppet::Util::Yaml::YamlLoadError, %r[\(#{file_path}\): .* at line \d+ column \d+]) end it 'raises an error when the filename is illegal' do expect { Puppet::Util::Yaml.safe_load_file("not\0allowed") }.to raise_error(ArgumentError, /pathname contains null byte/) end it 'raises an error when the file does not exist' do expect { Puppet::Util::Yaml.safe_load_file('does/not/exist.yaml') }.to raise_error(Errno::ENOENT, /No such file or directory/) end end context "#safe_load_file_if_valid" do before do Puppet[:log_level] = 'debug' end it_should_behave_like 'yaml file loader', Puppet::Util::Yaml.method(:safe_load_file_if_valid) it 'returns nil when the file is invalid YAML and debug logs about it' do file_path = file_containing('input', '{ invalid') expect(Puppet).to receive(:debug) .with(/Could not retrieve YAML content .+ expected ',' or '}'/).and_call_original expect(Puppet::Util::Yaml.safe_load_file_if_valid(file_path)).to eql(nil) end it 'returns nil when the filename is illegal and debug logs about it' do expect(Puppet).to receive(:debug) .with(/Could not retrieve YAML content .+: pathname contains null byte/).and_call_original expect(Puppet::Util::Yaml.safe_load_file_if_valid("not\0allowed")).to eql(nil) end it 'returns nil when the file does not exist and debug logs about it' do expect(Puppet).to receive(:debug) .with(/Could not retrieve YAML content .+: No such file or directory/).and_call_original expect(Puppet::Util::Yaml.safe_load_file_if_valid('does/not/exist.yaml')).to eql(nil) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/feature_spec.rb
spec/unit/util/feature_spec.rb
require 'spec_helper' require 'puppet/util/feature' describe Puppet::Util::Feature do before do @features = Puppet::Util::Feature.new("features") allow(@features).to receive(:warn) end it "should not call associated code when adding a feature" do $loaded_feature = false @features.add(:myfeature) { $loaded_feature = true} expect($loaded_feature).to eq(false) end it "should consider a feature absent when the feature load fails" do @features.add(:failer) { raise "foo" } expect(@features.failer?).to eq(false) end it "should consider a feature to be absent when the feature load returns false" do @features.add(:failer) { false } expect(@features.failer?).to eq(false) end it "should consider a feature to be absent when the feature load returns nil" do @features.add(:failer) { nil } expect(@features.failer?).to eq(false) end it "should consider a feature to be present when the feature load returns true" do @features.add(:available) { true } expect(@features.available?).to eq(true) end it "should consider a feature to be present when the feature load returns truthy" do @features.add(:available) { "yes" } expect(@features.available?).to eq(true) end it "should cache the results of a feature load via code block when the block returns true" do $loaded_feature = 0 @features.add(:myfeature) { $loaded_feature += 1; true } @features.myfeature? @features.myfeature? expect($loaded_feature).to eq(1) end it "should cache the results of a feature load via code block when the block returns false" do $loaded_feature = 0 @features.add(:myfeature) { $loaded_feature += 1; false } @features.myfeature? @features.myfeature? expect($loaded_feature).to eq(1) end it "should not cache the results of a feature load via code block when the block returns nil" do $loaded_feature = 0 @features.add(:myfeature) { $loaded_feature += 1; nil } @features.myfeature? @features.myfeature? expect($loaded_feature).to eq(2) end it "should invalidate the cache for the feature when loading" do @features.add(:myfeature) { false } expect(@features).not_to be_myfeature @features.add(:myfeature) expect(@features).to be_myfeature end it "should support features with libraries" do expect { @features.add(:puppet, :libs => %w{puppet}) }.not_to raise_error end it "should consider a feature to be present if all of its libraries are present" do @features.add(:myfeature, :libs => %w{foo bar}) expect(@features).to receive(:require).with("foo") expect(@features).to receive(:require).with("bar") expect(@features).to be_myfeature end it "should log and consider a feature to be absent if any of its libraries are absent" do @features.add(:myfeature, :libs => %w{foo bar}) expect(@features).to receive(:require).with("foo").and_raise(LoadError) allow(@features).to receive(:require).with("bar") expect(@features).to receive(:debug_once) expect(@features).not_to be_myfeature end it "should change the feature to be present when its libraries become available" do @features.add(:myfeature, :libs => %w{foo bar}) times_feature_require_called = 0 expect(@features).to receive(:require).twice().with("foo") do times_feature_require_called += 1 if times_feature_require_called == 1 raise LoadError else nil end end allow(@features).to receive(:require).with("bar") allow(Puppet::Util::RubyGems::Source).to receive(:source).and_return(Puppet::Util::RubyGems::Gems18Source) times_clear_paths_called = 0 allow_any_instance_of(Puppet::Util::RubyGems::Gems18Source).to receive(:clear_paths) { times_clear_paths_called += 1 } expect(@features).to receive(:debug_once) expect(@features).not_to be_myfeature expect(@features).to be_myfeature expect(times_clear_paths_called).to eq(3) end it "should cache load failures when configured to do so" do Puppet[:always_retry_plugins] = false @features.add(:myfeature, :libs => %w{foo bar}) expect(@features).to receive(:require).with("foo").and_raise(LoadError) expect(@features).not_to be_myfeature # second call would cause an expectation exception if 'require' was # called a second time expect(@features).not_to be_myfeature end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/errors_spec.rb
spec/unit/util/errors_spec.rb
require 'spec_helper' require 'puppet/util/errors' class ErrorTester include Puppet::Util::Errors attr_accessor :line, :file end describe Puppet::Util::Errors do before do @tester = ErrorTester.new end it "should provide a 'fail' method" do expect(@tester).to respond_to(:fail) end it "should provide a 'devfail' method" do expect(@tester).to respond_to(:devfail) end it "should raise any provided error when failing" do expect { @tester.fail(Puppet::ParseError, "stuff") }.to raise_error(Puppet::ParseError) end it "should default to Puppet::Error when failing" do expect { @tester.fail("stuff") }.to raise_error(Puppet::Error) end it "should have a method for converting error context into a string" do @tester.file = "/my/file" @tester.line = 50 expect(@tester.error_context).to eq(" (file: /my/file, line: 50)") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/log_spec.rb
spec/unit/util/log_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet/util/log' describe Puppet::Util::Log do include PuppetSpec::Files def log_notice(message) Puppet::Util::Log.new(:level => :notice, :message => message) end it "should write a given message to the specified destination" do arraydest = [] Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(arraydest)) Puppet::Util::Log.new(:level => :notice, :message => "foo") message = arraydest.last.message expect(message).to eq("foo") end context "given a message with invalid encoding" do let(:logs) { [] } let(:invalid_message) { "\xFD\xFBfoo".force_encoding(Encoding::Shift_JIS) } before do Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs)) Puppet::Util::Log.new(:level => :notice, :message => invalid_message) end it "does not raise an error" do expect { Puppet::Util::Log.new(:level => :notice, :message => invalid_message) }.not_to raise_error end it "includes a backtrace in the log" do expect(logs.last.message).to match(/Backtrace:\n.*in `newmessage'\n.*in `initialize'/ ) end it "warns that message included invalid encoding" do expect(logs.last.message).to match(/Received a Log attribute with invalid encoding/) end it "includes the 'dump' of the invalid message" do expect(logs.last.message).to match(/\"\\xFD\\xFBfoo\"/) end end # need a string that cannot be converted to US-ASCII or other encodings easily # 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 "converts a given non-UTF-8 message to UTF-8" do logs = [] Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs)) Puppet::Util::Log.newdestination(:console) # HIRAGANA LETTER SO # In Windows_31J: \x82 \xbb - 130 187 # In Unicode: \u305d - \xe3 \x81 \x9d - 227 129 157 win_31j_msg = [130, 187].pack('C*').force_encoding(Encoding::Windows_31J) utf_8_msg = "\u305d" expect($stdout).to receive(:puts).with("\e[mNotice: #{mixed_utf8}: #{utf_8_msg}\e[0m") # most handlers do special things with a :source => 'Puppet', so use something else Puppet::Util::Log.new(:level => :notice, :message => win_31j_msg, :source => mixed_utf8) expect(logs.last.message).to eq(utf_8_msg) end it "converts a given non-UTF-8 source to UTF-8" do logs = [] Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs)) Puppet::Util::Log.newdestination(:console) # HIRAGANA LETTER SO # In Windows_31J: \x82 \xbb - 130 187 # In Unicode: \u305d - \xe3 \x81 \x9d - 227 129 157 win_31j_msg = [130, 187].pack('C*').force_encoding(Encoding::Windows_31J) utf_8_msg = "\u305d" expect($stdout).to receive(:puts).with("\e[mNotice: #{utf_8_msg}: #{mixed_utf8}\e[0m") Puppet::Util::Log.new(:level => :notice, :message => mixed_utf8, :source => win_31j_msg) expect(logs.last.source).to eq(utf_8_msg) end require 'puppet/util/log/destinations' it "raises an error when it has no successful logging destinations" do # spec_helper.rb redirects log output away from the console, # so we have to stop that here, or else the logic we are testing # will not be reached. allow(Puppet::Util::Log).to receive(:destinations).and_return({}) our_exception = Puppet::DevError.new("test exception") expect(Puppet::FileSystem).to receive(:dir).and_raise(our_exception) bad_file = tmpfile("bad_file") expect { Puppet::Util::Log.newdestination(bad_file) }.to raise_error(Puppet::DevError) end describe ".setup_default" do it "should default to :syslog" do allow(Puppet.features).to receive(:syslog?).and_return(true) expect(Puppet::Util::Log).to receive(:newdestination).with(:syslog) Puppet::Util::Log.setup_default end it "should fall back to :eventlog" do without_partial_double_verification do allow(Puppet.features).to receive(:syslog?).and_return(false) allow(Puppet.features).to receive(:eventlog?).and_return(true) end expect(Puppet::Util::Log).to receive(:newdestination).with(:eventlog) Puppet::Util::Log.setup_default end it "should fall back to :file" do without_partial_double_verification do allow(Puppet.features).to receive(:syslog?).and_return(false) allow(Puppet.features).to receive(:eventlog?).and_return(false) end expect(Puppet::Util::Log).to receive(:newdestination).with(Puppet[:puppetdlog]) Puppet::Util::Log.setup_default end end describe "#with_destination" do it "does nothing when nested" do logs = [] destination = Puppet::Test::LogCollector.new(logs) Puppet::Util::Log.with_destination(destination) do Puppet::Util::Log.with_destination(destination) do log_notice("Inner block") end log_notice("Outer block") end log_notice("Outside") expect(logs.collect(&:message)).to include("Inner block", "Outer block") expect(logs.collect(&:message)).not_to include("Outside") end it "logs when called a second time" do logs = [] destination = Puppet::Test::LogCollector.new(logs) Puppet::Util::Log.with_destination(destination) do log_notice("First block") end log_notice("Between blocks") Puppet::Util::Log.with_destination(destination) do log_notice("Second block") end expect(logs.collect(&:message)).to include("First block", "Second block") expect(logs.collect(&:message)).not_to include("Between blocks") end it "doesn't close the destination if already set manually" do logs = [] destination = Puppet::Test::LogCollector.new(logs) Puppet::Util::Log.newdestination(destination) Puppet::Util::Log.with_destination(destination) do log_notice "Inner block" end log_notice "Outer block" Puppet::Util::Log.close(destination) expect(logs.collect(&:message)).to include("Inner block", "Outer block") end end describe Puppet::Util::Log::DestConsole do before do @console = Puppet::Util::Log::DestConsole.new end it "should colorize if Puppet[:color] is :ansi" do Puppet[:color] = :ansi expect(@console.colorize(:alert, "abc")).to eq("\e[0;31mabc\e[0m") end it "should colorize if Puppet[:color] is 'yes'" do Puppet[:color] = "yes" expect(@console.colorize(:alert, "abc")).to eq("\e[0;31mabc\e[0m") end it "should htmlize if Puppet[:color] is :html" do Puppet[:color] = :html expect(@console.colorize(:alert, "abc")).to eq("<span style=\"color: #FFA0A0\">abc</span>") end it "should do nothing if Puppet[:color] is false" do Puppet[:color] = false expect(@console.colorize(:alert, "abc")).to eq("abc") end it "should do nothing if Puppet[:color] is invalid" do Puppet[:color] = "invalid option" expect(@console.colorize(:alert, "abc")).to eq("abc") end end describe Puppet::Util::Log::DestSyslog do before do @syslog = Puppet::Util::Log::DestSyslog.new end end describe Puppet::Util::Log::DestEventlog, :if => Puppet.features.eventlog? do before :each do allow(Puppet::Util::Windows::EventLog).to receive(:open).and_return(double('mylog', :close => nil)) end it "should restrict its suitability to Windows" do allow(Puppet::Util::Platform).to receive(:windows?).and_return(false) expect(Puppet::Util::Log::DestEventlog.suitable?('whatever')).to eq(false) end it "should open the 'Puppet' event log" do expect(Puppet::Util::Windows::EventLog).to receive(:open).with('Puppet') Puppet::Util::Log.newdestination(:eventlog) end it "should close the event log" do log = double('myeventlog') expect(log).to receive(:close) expect(Puppet::Util::Windows::EventLog).to receive(:open).and_return(log) Puppet::Util::Log.newdestination(:eventlog) Puppet::Util::Log.close(:eventlog) end it "should handle each puppet log level" do log = Puppet::Util::Log::DestEventlog.new Puppet::Util::Log.eachlevel do |level| expect(log.to_native(level)).to be_is_a(Array) end end end describe "instances" do before do allow(Puppet::Util::Log).to receive(:newmessage) end [:level, :message, :time, :remote].each do |attr| it "should have a #{attr} attribute" do log = Puppet::Util::Log.new :level => :notice, :message => "A test message" expect(log).to respond_to(attr) expect(log).to respond_to(attr.to_s + "=") end end it "should fail if created without a level" do expect { Puppet::Util::Log.new(:message => "A test message") }.to raise_error(ArgumentError) end it "should fail if created without a message" do expect { Puppet::Util::Log.new(:level => :notice) }.to raise_error(ArgumentError) end it "should make available the level passed in at initialization" do expect(Puppet::Util::Log.new(:level => :notice, :message => "A test message").level).to eq(:notice) end it "should make available the message passed in at initialization" do expect(Puppet::Util::Log.new(:level => :notice, :message => "A test message").message).to eq("A test message") end # LAK:NOTE I don't know why this behavior is here, I'm just testing what's in the code, # at least at first. it "should always convert messages to strings" do expect(Puppet::Util::Log.new(:level => :notice, :message => :foo).message).to eq("foo") end it "should flush the log queue when the first destination is specified" do Puppet::Util::Log.close_all expect(Puppet::Util::Log).to receive(:flushqueue) Puppet::Util::Log.newdestination(:console) end it "should convert the level to a symbol if it's passed in as a string" do expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).level).to eq(:notice) end it "should fail if the level is not a symbol or string" do expect { Puppet::Util::Log.new(:level => 50, :message => :foo) }.to raise_error(ArgumentError) end it "should fail if the provided level is not valid" do expect(Puppet::Util::Log).to receive(:validlevel?).with(:notice).and_return(false) expect { Puppet::Util::Log.new(:level => :notice, :message => :foo) }.to raise_error(ArgumentError) end it "should set its time to the initialization time" do time = double('time') expect(Time).to receive(:now).and_return(time) expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).time).to equal(time) end it "should make available any passed-in tags" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{foo bar}) expect(log.tags).to be_include("foo") expect(log.tags).to be_include("bar") end it "should use a passed-in source" do expect_any_instance_of(Puppet::Util::Log).to receive(:source=).with("foo") Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => "foo") end [:file, :line].each do |attr| it "should use #{attr} if provided" do expect_any_instance_of(Puppet::Util::Log).to receive(attr.to_s + "=").with("foo") Puppet::Util::Log.new(:level => "notice", :message => :foo, attr => "foo") end end it "should default to 'Puppet' as its source" do expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).source).to eq("Puppet") end it "should register itself with Log" do expect(Puppet::Util::Log).to receive(:newmessage) Puppet::Util::Log.new(:level => "notice", :message => :foo) end it "should update Log autoflush when Puppet[:autoflush] is set" do expect(Puppet::Util::Log).to receive(:autoflush=).once.with(true) Puppet[:autoflush] = true end it "should have a method for determining if a tag is present" do expect(Puppet::Util::Log.new(:level => "notice", :message => :foo)).to respond_to(:tagged?) end it "should match a tag if any of the tags are equivalent to the passed tag as a string" do expect(Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{one two})).to be_tagged(:one) end it "should tag itself with its log level" do expect(Puppet::Util::Log.new(:level => "notice", :message => :foo)).to be_tagged(:notice) end it "should return its message when converted to a string" do expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).to_s).to eq("foo") end it "should include its time, source, level, and message when prepared for reporting" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo) report = log.to_report expect(report).to be_include("notice") expect(report).to be_include("foo") expect(report).to be_include(log.source) expect(report).to be_include(log.time.to_s) end it "should not create unsuitable log destinations" do allow(Puppet.features).to receive(:syslog?).and_return(false) expect(Puppet::Util::Log::DestSyslog).to receive(:suitable?) expect(Puppet::Util::Log::DestSyslog).not_to receive(:new) Puppet::Util::Log.newdestination(:syslog) end describe "when setting the source as a RAL object" do let(:path) { File.expand_path('/foo/bar') } it "should tag itself with any tags the source has" do source = Puppet::Type.type(:file).new :path => path log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source) source.tags.each do |tag| expect(log.tags).to be_include(tag) end end it "should set the source to a type's 'path', when available" do source = Puppet::Type.type(:file).new :path => path source.tags = ["tag", "tag2"] log = Puppet::Util::Log.new(:level => "notice", :message => :foo) log.source = source expect(log).to be_tagged('file') expect(log).to be_tagged('tag') expect(log).to be_tagged('tag2') expect(log.source).to eq("/File[#{path}]") end it "should set the source to a provider's type's 'path', when available" do source = Puppet::Type.type(:file).new :path => path source.tags = ["tag", "tag2"] log = Puppet::Util::Log.new(:level => "notice", :message => :foo) log.source = source.provider expect(log.source).to match Regexp.quote("File\[#{path}\]\(provider=") end it "should copy over any file and line information" do source = Puppet::Type.type(:file).new :path => path source.file = "/my/file" source.line = 50 log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source) expect(log.line).to eq(50) expect(log.file).to eq("/my/file") end end describe "when setting the source as a non-RAL object" do it "should not try to copy over file, version, line, or tag information" do source = double('source') expect(source).not_to receive(:file) Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source) end end end describe "to_yaml" do it "should not include the @version attribute" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100) expect(log.to_data_hash.keys).not_to include('version') end it "should include attributes 'file', 'line', 'level', 'message', 'source', 'tags', and 'time'" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100) expect(log.to_data_hash.keys).to match_array(%w(file line level message source tags time)) end it "should include attributes 'file' and 'line' if specified" do log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :file => "foo", :line => 35) expect(log.to_data_hash.keys).to include('file') expect(log.to_data_hash.keys).to include('line') end end let(:log) { Puppet::Util::Log.new(:level => 'notice', :message => 'hooray', :file => 'thefile', :line => 1729, :source => 'specs', :tags => ['a', 'b', 'c']) } it "should round trip through json" do tripped = Puppet::Util::Log.from_data_hash(JSON.parse(log.to_json)) expect(tripped.file).to eq(log.file) expect(tripped.line).to eq(log.line) expect(tripped.level).to eq(log.level) expect(tripped.message).to eq(log.message) expect(tripped.source).to eq(log.source) expect(tripped.tags).to eq(log.tags) expect(tripped.time).to eq(log.time) end it 'to_data_hash returns value that is instance of to Data' do expect(Puppet::Pops::Types::TypeFactory.data.instance?(log.to_data_hash)).to be_truthy end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/storage_spec.rb
spec/unit/util/storage_spec.rb
require 'spec_helper' require 'yaml' require 'fileutils' require 'puppet/util/storage' describe Puppet::Util::Storage do include PuppetSpec::Files before(:each) do @basepath = File.expand_path("/somepath") end describe "when caching a symbol" do it "should return an empty hash" do expect(Puppet::Util::Storage.cache(:yayness)).to eq({}) expect(Puppet::Util::Storage.cache(:more_yayness)).to eq({}) end it "should add the symbol to its internal state" do Puppet::Util::Storage.cache(:yayness) expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) end it "should not clobber existing state when caching additional objects" do Puppet::Util::Storage.cache(:yayness) expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) Puppet::Util::Storage.cache(:bubblyness) expect(Puppet::Util::Storage.state).to eq({:yayness=>{},:bubblyness=>{}}) end end describe "when caching a Puppet::Type" do before(:each) do @file_test = Puppet::Type.type(:file).new(:name => @basepath+"/yayness", :audit => %w{checksum type}) @exec_test = Puppet::Type.type(:exec).new(:name => @basepath+"/bin/ls /yayness") end it "should return an empty hash" do expect(Puppet::Util::Storage.cache(@file_test)).to eq({}) expect(Puppet::Util::Storage.cache(@exec_test)).to eq({}) end it "should add the resource ref to its internal state" do expect(Puppet::Util::Storage.state).to eq({}) Puppet::Util::Storage.cache(@file_test) expect(Puppet::Util::Storage.state).to eq({"File[#{@basepath}/yayness]"=>{}}) Puppet::Util::Storage.cache(@exec_test) expect(Puppet::Util::Storage.state).to eq({"File[#{@basepath}/yayness]"=>{}, "Exec[#{@basepath}/bin/ls /yayness]"=>{}}) end end describe "when caching something other than a resource or symbol" do it "should cache by converting to a string" do data = Puppet::Util::Storage.cache(42) data[:yay] = true expect(Puppet::Util::Storage.cache("42")[:yay]).to be_truthy end end it "should clear its internal state when clear() is called" do Puppet::Util::Storage.cache(:yayness) expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) Puppet::Util::Storage.clear expect(Puppet::Util::Storage.state).to eq({}) end describe "when loading from the state file" do before do allow(Puppet.settings).to receive(:use).and_return(true) end describe "when the state 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 Puppet::Util::Storage.load Puppet[:statefile] = @path Puppet::Util::Storage.load end it "should not lose its internal state when load() is called" do expect(Puppet::FileSystem.exist?(@path)).to be_falsey Puppet::Util::Storage.cache(:yayness) expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) Puppet[:statefile] = @path Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) end end describe "when the state file/directory exists" do before(:each) do @state_file = tmpfile('storage_test') FileUtils.touch(@state_file) Puppet[:statefile] = @state_file end def write_state_file(contents) File.open(@state_file, 'w') { |f| f.write(contents) } end it "should overwrite its internal state if load() is called" do # Should the state be overwritten even if Puppet[:statefile] is not valid YAML? Puppet::Util::Storage.cache(:yayness) expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to eq({}) end it "should restore its internal state if the state file contains valid YAML" do test_yaml = {'File["/yayness"]'=>{"name"=>{:a=>:b,:c=>:d}}} write_state_file(test_yaml.to_yaml) Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to eq(test_yaml) end it "should initialize with a clear internal state if the state file does not contain valid YAML" do write_state_file('{ invalid') Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to eq({}) end it "should initialize with a clear internal state if the state file does not contain a hash of data" do write_state_file("not_a_hash") Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to eq({}) end it "should raise an error if the state file does not contain valid YAML and cannot be renamed" do allow(File).to receive(:rename).and_call_original write_state_file('{ invalid') expect(File).to receive(:rename).with(@state_file, "#{@state_file}.bad").and_raise(SystemCallError) expect { Puppet::Util::Storage.load }.to raise_error(Puppet::Error, /Could not rename/) end it "should attempt to rename the state file if the file is corrupted" do write_state_file('{ invalid') expect(File).to receive(:rename).at_least(:once) Puppet::Util::Storage.load end it "should fail gracefully on load() if the state file is not a regular file" do FileUtils.rm_f(@state_file) Dir.mkdir(@state_file) Puppet::Util::Storage.load end it 'should load Time and Symbols' do state = { 'File[/etc/puppetlabs/puppet]' => { :checked => Time.new(2018, 8, 8, 15, 28, 25, "-07:00") } } write_state_file(YAML.dump(state)) Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to eq(state.dup) end end end describe "when storing to the state file" do A_SMALL_AMOUNT_OF_TIME = 0.001 #Seconds before(:each) do @state_file = tmpfile('storage_test') @saved_statefile = Puppet[:statefile] Puppet[:statefile] = @state_file end it "should create the state file if it does not exist" do expect(Puppet::FileSystem.exist?(Puppet[:statefile])).to be_falsey Puppet::Util::Storage.cache(:yayness) Puppet::Util::Storage.store expect(Puppet::FileSystem.exist?(Puppet[:statefile])).to be_truthy end it "should raise an exception if the state file is not a regular file" do Dir.mkdir(Puppet[:statefile]) Puppet::Util::Storage.cache(:yayness) expect { Puppet::Util::Storage.store }.to raise_error(Errno::EISDIR, /Is a directory/) Dir.rmdir(Puppet[:statefile]) end it "should load() the same information that it store()s" do Puppet::Util::Storage.cache(:yayness) expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) Puppet::Util::Storage.store Puppet::Util::Storage.clear expect(Puppet::Util::Storage.state).to eq({}) Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to eq({:yayness=>{}}) end it "expires entries with a :checked older than statettl seconds ago" do Puppet[:statettl] = '1d' recent_checked = Time.now.round stale_checked = recent_checked - (Puppet[:statettl] + 10) Puppet::Util::Storage.cache(:yayness)[:checked] = recent_checked Puppet::Util::Storage.cache(:stale)[:checked] = stale_checked expect(Puppet::Util::Storage.state).to match( { :yayness => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked) }, :stale => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(stale_checked) } } ) Puppet::Util::Storage.store Puppet::Util::Storage.clear expect(Puppet::Util::Storage.state).to eq({}) Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to match( { :yayness => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked) } } ) end it "does not expire entries when statettl is 0" do Puppet[:statettl] = '0' recent_checked = Time.now.round older_checked = recent_checked - 10_000_000 Puppet::Util::Storage.cache(:yayness)[:checked] = recent_checked Puppet::Util::Storage.cache(:older)[:checked] = older_checked expect(Puppet::Util::Storage.state).to match( { :yayness => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked) }, :older => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked) } } ) Puppet::Util::Storage.store Puppet::Util::Storage.clear expect(Puppet::Util::Storage.state).to eq({}) Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to match( { :yayness => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked) }, :older => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked) } } ) end it "does not expire entries when statettl is 'unlimited'" do Puppet[:statettl] = 'unlimited' recent_checked = Time.now older_checked = Time.now - 10_000_000 Puppet::Util::Storage.cache(:yayness)[:checked] = recent_checked Puppet::Util::Storage.cache(:older)[:checked] = older_checked expect(Puppet::Util::Storage.state).to match( { :yayness => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked) }, :older => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked) } } ) Puppet::Util::Storage.store Puppet::Util::Storage.clear expect(Puppet::Util::Storage.state).to eq({}) Puppet::Util::Storage.load expect(Puppet::Util::Storage.state).to match( { :yayness => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked) }, :older => { :checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked) } } ) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/command_line_spec.rb
spec/unit/util/command_line_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet/util/command_line' describe Puppet::Util::CommandLine do include PuppetSpec::Files context "#initialize" do it "should pull off the first argument if it looks like a subcommand" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ client --help whatever.pp }) expect(command_line.subcommand_name).to eq("client") expect(command_line.args).to eq(%w{ --help whatever.pp }) end it "should return nil if the first argument looks like a .pp file" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ whatever.pp }) expect(command_line.subcommand_name).to eq(nil) expect(command_line.args).to eq(%w{ whatever.pp }) end it "should return nil if the first argument looks like a flag" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ --debug }) expect(command_line.subcommand_name).to eq(nil) expect(command_line.args).to eq(%w{ --debug }) end it "should return nil if the first argument is -" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ - }) expect(command_line.subcommand_name).to eq(nil) expect(command_line.args).to eq(%w{ - }) end it "should return nil if the first argument is --help" do command_line = Puppet::Util::CommandLine.new("puppet", %w{ --help }) expect(command_line.subcommand_name).to eq(nil) end it "should return nil if there are no arguments" do command_line = Puppet::Util::CommandLine.new("puppet", []) expect(command_line.subcommand_name).to eq(nil) expect(command_line.args).to eq([]) end it "should pick up changes to the array of arguments" do args = %w{subcommand} command_line = Puppet::Util::CommandLine.new("puppet", args) args[0] = 'different_subcommand' expect(command_line.subcommand_name).to eq('different_subcommand') end end context "#execute" do %w{--version -V}.each do |arg| it "should print the version and exit if #{arg} is given" do expect do described_class.new("puppet", [arg]).execute end.to output(/^#{Regexp.escape(Puppet.version)}$/).to_stdout end end %w{--help -h help}.each do|arg| it "should print help and exit if #{arg} is given" do commandline = Puppet::Util::CommandLine.new("puppet", [arg]) expect(commandline).not_to receive(:exec) expect { commandline.execute }.to exit_with(0) .and output(/Usage: puppet <subcommand> \[options\] <action> \[options\]/).to_stdout end end it "should fail if the config file isn't readable and we're running a subcommand that requires a readable config file" do allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:config]).and_return(true) allow_any_instance_of(Puppet::Settings).to receive(:read_file).and_return('') expect_any_instance_of(Puppet::Settings).to receive(:read_file).with(Puppet[:config]).and_raise('Permission denied') expect{ described_class.new("puppet", ['config']).execute }.to raise_error(SystemExit) end it "should not fail if the config file isn't readable and we're running a subcommand that does not require a readable config file" do allow(Puppet::FileSystem).to receive(:exist?) allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:config]).and_return(true) allow_any_instance_of(Puppet::Settings).to receive(:read_file).and_return('') expect_any_instance_of(Puppet::Settings).to receive(:read_file).with(Puppet[:config]).and_raise('Permission denied') commandline = described_class.new("puppet", ['help']) expect { commandline.execute }.to exit_with(0) .and output(/Usage: puppet <subcommand> \[options\] <action> \[options\]/).to_stdout end end describe "when dealing with puppet commands" do it "should return the executable name if it is not puppet" do command_line = Puppet::Util::CommandLine.new("puppetmasterd", []) expect(command_line.subcommand_name).to eq("puppetmasterd") end describe "when the subcommand is not implemented" do it "should find and invoke an executable with a hyphenated name" do commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument']) expect(Puppet::Util).to receive(:which).with('puppet-whatever'). and_return('/dev/null/puppet-whatever') expect(Kernel).to receive(:exec).with('/dev/null/puppet-whatever', 'argument') commandline.execute end describe "and an external implementation cannot be found" do it "should abort and show the usage message" do expect(Puppet::Util).to receive(:which).with('puppet-whatever').and_return(nil) commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument']) expect(commandline).not_to receive(:exec) expect { commandline.execute }.to exit_with(1) .and output(/Unknown Puppet subcommand 'whatever'/).to_stdout end it "should abort and show the help message" do expect(Puppet::Util).to receive(:which).with('puppet-whatever').and_return(nil) commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument']) expect(commandline).not_to receive(:exec) expect { commandline.execute }.to exit_with(1) .and output(/See 'puppet help' for help on available puppet subcommands/).to_stdout end %w{--version -V}.each do |arg| it "should abort and display #{arg} information" do expect(Puppet::Util).to receive(:which).with('puppet-whatever').and_return(nil) commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', arg]) expect(commandline).not_to receive(:exec) expect { commandline.execute }.to exit_with(1) .and output(%r[^#{Regexp.escape(Puppet.version)}$]).to_stdout end end end end describe 'when setting process priority' do let(:command_line) do Puppet::Util::CommandLine.new("puppet", %w{ agent }) end before :each do allow_any_instance_of(Puppet::Util::CommandLine::ApplicationSubcommand).to receive(:run) end it 'should never set priority by default' do expect(Process).not_to receive(:setpriority) command_line.execute end it 'should lower the process priority if one has been specified' do Puppet[:priority] = 10 expect(Process).to receive(:setpriority).with(0, Process.pid, 10) command_line.execute end it 'should warn if trying to raise priority, but not privileged user' do Puppet[:priority] = -10 expect(Process).to receive(:setpriority).and_raise(Errno::EACCES, 'Permission denied') expect(Puppet).to receive(:warning).with("Failed to set process priority to '-10'") command_line.execute end it "should warn if the platform doesn't support `Process.setpriority`" do Puppet[:priority] = 15 expect(Process).to receive(:setpriority).and_raise(NotImplementedError, 'NotImplementedError: setpriority() function is unimplemented on this machine') expect(Puppet).to receive(:warning).with("Failed to set process priority to '15'") command_line.execute end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/rubygems_spec.rb
spec/unit/util/rubygems_spec.rb
require 'spec_helper' require 'puppet/util/rubygems' describe Puppet::Util::RubyGems::Source do let(:gem_path) { File.expand_path('/foo/gems') } let(:gem_lib) { File.join(gem_path, 'lib') } let(:fake_gem) { double(:full_gem_path => gem_path) } describe "::new" do it "returns NoGemsSource if rubygems is not present" do expect(described_class).to receive(:has_rubygems?).and_return(false) expect(described_class.new).to be_kind_of(Puppet::Util::RubyGems::NoGemsSource) end it "returns Gems18Source if Gem::Specification responds to latest_specs" do expect(described_class).to receive(:has_rubygems?).and_return(true) expect(described_class.new).to be_kind_of(Puppet::Util::RubyGems::Gems18Source) end end describe '::NoGemsSource' do before(:each) { allow(described_class).to receive(:source).and_return(Puppet::Util::RubyGems::NoGemsSource) } it "#directories returns an empty list" do expect(described_class.new.directories).to eq([]) end it "#clear_paths returns nil" do expect(described_class.new.clear_paths).to be_nil end end describe '::Gems18Source' do before(:each) { allow(described_class).to receive(:source).and_return(Puppet::Util::RubyGems::Gems18Source) } it "#directories returns the lib subdirs of Gem::Specification.stubs" do expect(Gem::Specification).to receive(:stubs).and_return([fake_gem]) expect(described_class.new.directories).to eq([gem_lib]) end it "#clear_paths calls Gem.clear_paths" do expect(Gem).to receive(:clear_paths) described_class.new.clear_paths end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/profiler/wall_clock_spec.rb
spec/unit/util/profiler/wall_clock_spec.rb
require 'spec_helper' require 'puppet/util/profiler' describe Puppet::Util::Profiler::WallClock do it "logs the number of seconds it took to execute the segment" do profiler = Puppet::Util::Profiler::WallClock.new(nil, nil) message = profiler.do_finish(profiler.start(["foo", "bar"], "Testing"), ["foo", "bar"], "Testing")[:msg] expect(message).to match(/took \d\.\d{4} seconds/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/profiler/logging_spec.rb
spec/unit/util/profiler/logging_spec.rb
require 'spec_helper' require 'puppet/util/profiler' describe Puppet::Util::Profiler::Logging do let(:logger) { SimpleLog.new } let(:identifier) { "Profiling ID" } let(:logging_profiler) { TestLoggingProfiler.new(logger, identifier) } let(:profiler) do p = Puppet::Util::Profiler::AroundProfiler.new p.add_profiler(logging_profiler) p end it "logs the explanation of the profile results" do profiler.profile("Testing", ["test"]) { } expect(logger.messages.first).to match(/the explanation/) end it "describes the profiled segment" do profiler.profile("Tested measurement", ["test"]) { } expect(logger.messages.first).to match(/PROFILE \[#{identifier}\] \d Tested measurement/) end it "indicates the order in which segments are profiled" do profiler.profile("Measurement", ["measurement"]) { } profiler.profile("Another measurement", ["measurement"]) { } expect(logger.messages[0]).to match(/1 Measurement/) expect(logger.messages[1]).to match(/2 Another measurement/) end it "indicates the nesting of profiled segments" do profiler.profile("Measurement", ["measurement1"]) do profiler.profile("Nested measurement", ["measurement2"]) { } end profiler.profile("Another measurement", ["measurement1"]) do profiler.profile("Another nested measurement", ["measurement2"]) { } end expect(logger.messages[0]).to match(/1.1 Nested measurement/) expect(logger.messages[1]).to match(/1 Measurement/) expect(logger.messages[2]).to match(/2.1 Another nested measurement/) expect(logger.messages[3]).to match(/2 Another measurement/) end class TestLoggingProfiler < Puppet::Util::Profiler::Logging def do_start(metric, description) "the start" end def do_finish(context, metric, description) {:msg => "the explanation of #{context}"} end end class SimpleLog attr_reader :messages def initialize @messages = [] end def call(msg) @messages << msg end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/profiler/aggregate_spec.rb
spec/unit/util/profiler/aggregate_spec.rb
require 'spec_helper' require 'puppet/util/profiler' require 'puppet/util/profiler/around_profiler' require 'puppet/util/profiler/aggregate' describe Puppet::Util::Profiler::Aggregate do let(:logger) { AggregateSimpleLog.new } let(:profiler) { Puppet::Util::Profiler::Aggregate.new(logger, nil) } let(:profiler_mgr) do p = Puppet::Util::Profiler::AroundProfiler.new p.add_profiler(profiler) p end it "tracks the aggregate counts and time for the hierarchy of metrics" do profiler_mgr.profile("Looking up hiera data in production environment", ["function", "hiera_lookup", "production"]) { sleep 0.01 } profiler_mgr.profile("Looking up hiera data in test environment", ["function", "hiera_lookup", "test"]) {} profiler_mgr.profile("looking up stuff for compilation", ["compiler", "lookup"]) { sleep 0.01 } profiler_mgr.profile("COMPILING ALL OF THE THINGS!", ["compiler", "compiling"]) {} expect(profiler.values["function"].count).to eq(2) expect(profiler.values["function"].time).to be > 0 expect(profiler.values["function"]["hiera_lookup"].count).to eq(2) expect(profiler.values["function"]["hiera_lookup"]["production"].count).to eq(1) expect(profiler.values["function"]["hiera_lookup"]["test"].count).to eq(1) expect(profiler.values["function"].time).to be >= profiler.values["function"]["hiera_lookup"]["test"].time expect(profiler.values["compiler"].count).to eq(2) expect(profiler.values["compiler"].time).to be > 0 expect(profiler.values["compiler"]["lookup"].count).to eq(1) expect(profiler.values["compiler"]["compiling"].count).to eq(1) expect(profiler.values["compiler"].time).to be >= profiler.values["compiler"]["lookup"].time profiler.shutdown expect(logger.output).to match(/function -> hiera_lookup: .*\(2 calls\)\nfunction -> hiera_lookup ->.*\(1 calls\)/) expect(logger.output).to match(/compiler: .*\(2 calls\)\ncompiler ->.*\(1 calls\)/) end it "supports both symbols and strings as components of a metric id" do profiler_mgr.profile("yo", [:foo, "bar"]) {} end class AggregateSimpleLog attr_reader :output def initialize @output = "" end def call(msg) @output << msg << "\n" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/profiler/object_counts_spec.rb
spec/unit/util/profiler/object_counts_spec.rb
require 'spec_helper' require 'puppet/util/profiler' describe Puppet::Util::Profiler::ObjectCounts, unless: Puppet::Util::Platform.jruby? do # ObjectSpace is not enabled by default on JRuby it "reports the changes in the system object counts" do profiler = Puppet::Util::Profiler::ObjectCounts.new(nil, nil) message = profiler.finish(profiler.start) expect(message).to match(/ T_STRING: \d+, /) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/profiler/around_profiler_spec.rb
spec/unit/util/profiler/around_profiler_spec.rb
require 'spec_helper' require 'puppet/util/profiler' describe Puppet::Util::Profiler::AroundProfiler do let(:child) { TestAroundProfiler.new() } let(:profiler) { Puppet::Util::Profiler::AroundProfiler.new } before :each do profiler.add_profiler(child) end it "returns the value of the profiled segment" do retval = profiler.profile("Testing", ["testing"]) { "the return value" } expect(retval).to eq("the return value") end it "propagates any errors raised in the profiled segment" do expect do profiler.profile("Testing", ["testing"]) { raise "a problem" } end.to raise_error("a problem") end it "makes the description and the context available to the `start` and `finish` methods" do profiler.profile("Testing", ["testing"]) { } expect(child.context).to eq("Testing") expect(child.description).to eq("Testing") end it "calls finish even when an error is raised" do begin profiler.profile("Testing", ["testing"]) { raise "a problem" } rescue expect(child.context).to eq("Testing") end end it "supports multiple profilers" do profiler2 = TestAroundProfiler.new profiler.add_profiler(profiler2) profiler.profile("Testing", ["testing"]) {} expect(child.context).to eq("Testing") expect(profiler2.context).to eq("Testing") end class TestAroundProfiler attr_accessor :context, :description def start(description, metric_id) description end def finish(context, description, metric_id) @context = context @description = description end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/watcher/periodic_watcher_spec.rb
spec/unit/util/watcher/periodic_watcher_spec.rb
require 'spec_helper' require 'puppet/util/watcher' describe Puppet::Util::Watcher::PeriodicWatcher do let(:enabled_timeout) { 1 } let(:disabled_timeout) { -1 } let(:a_value) { 15 } let(:a_different_value) { 16 } let(:unused_watcher) { double('unused watcher') } let(:unchanged_watcher) { a_watcher_reporting(a_value) } let(:changed_watcher) { a_watcher_reporting(a_value, a_different_value) } it 'reads only the initial change state when the timeout has not yet expired' do watcher = Puppet::Util::Watcher::PeriodicWatcher.new(unchanged_watcher, an_unexpired_timer(enabled_timeout)) expect(watcher).to_not be_changed end it 'reads enough values to determine change when the timeout has expired' do watcher = Puppet::Util::Watcher::PeriodicWatcher.new(changed_watcher, an_expired_timer(enabled_timeout)) expect(watcher).to be_changed end it 'is always marked as changed when the timeout is disabled' do watcher = Puppet::Util::Watcher::PeriodicWatcher.new(unused_watcher, an_expired_timer(disabled_timeout)) expect(watcher).to be_changed end def a_watcher_reporting(*observed_values) Puppet::Util::Watcher::ChangeWatcher.watch(proc do observed_values.shift or raise "No more observed values to report!" end) end def an_expired_timer(timeout) a_time_that_reports_expired_as(true, timeout) end def an_unexpired_timer(timeout) a_time_that_reports_expired_as(false, timeout) end def a_time_that_reports_expired_as(expired, timeout) timer = Puppet::Util::Watcher::Timer.new(timeout) allow(timer).to receive(:expired?).and_return(expired) timer end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/ldap/connection_spec.rb
spec/unit/util/ldap/connection_spec.rb
require 'spec_helper' require 'puppet/util/ldap/connection' # So our mocks and such all work, even when ldap isn't available. unless Puppet.features.ldap? class LDAP class Conn def initialize(*args) end end class SSLConn < Conn; end LDAP_OPT_PROTOCOL_VERSION = 1 LDAP_OPT_REFERRALS = 2 LDAP_OPT_ON = 3 end end describe Puppet::Util::Ldap::Connection do before do allow(Puppet.features).to receive(:ldap?).and_return(true) @ldapconn = double( 'ldap', set_option: nil, simple_bind: nil, ) allow(LDAP::Conn).to receive(:new).and_return(@ldapconn) allow(LDAP::SSLConn).to receive(:new).and_return(@ldapconn) @connection = Puppet::Util::Ldap::Connection.new("host", 1234) end describe "when creating connections" do it "should require the host and port" do expect { Puppet::Util::Ldap::Connection.new("myhost") }.to raise_error(ArgumentError) end it "should allow specification of a user and password" do expect { Puppet::Util::Ldap::Connection.new("myhost", 1234, :user => "blah", :password => "boo") }.not_to raise_error end it "should allow specification of ssl" do expect { Puppet::Util::Ldap::Connection.new("myhost", 1234, :ssl => :tsl) }.not_to raise_error end it "should support requiring a new connection" do expect { Puppet::Util::Ldap::Connection.new("myhost", 1234, :reset => true) }.not_to raise_error end it "should fail if ldap is unavailable" do expect(Puppet.features).to receive(:ldap?).and_return(false) expect { Puppet::Util::Ldap::Connection.new("host", 1234) }.to raise_error(Puppet::Error) end it "should use neither ssl nor tls by default" do expect(LDAP::Conn).to receive(:new).with("host", 1234).and_return(@ldapconn) @connection.start end it "should use LDAP::SSLConn if ssl is requested" do expect(LDAP::SSLConn).to receive(:new).with("host", 1234).and_return(@ldapconn) @connection.ssl = true @connection.start end it "should use LDAP::SSLConn and tls if tls is requested" do expect(LDAP::SSLConn).to receive(:new).with("host", 1234, true).and_return(@ldapconn) @connection.ssl = :tls @connection.start end it "should set the protocol version to 3 and enable referrals" do expect(@ldapconn).to receive(:set_option).with(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3) expect(@ldapconn).to receive(:set_option).with(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON) @connection.start end it "should bind with the provided user and password" do @connection.user = "myuser" @connection.password = "mypassword" expect(@ldapconn).to receive(:simple_bind).with("myuser", "mypassword") @connection.start end it "should bind with no user and password if none has been provided" do expect(@ldapconn).to receive(:simple_bind).with(nil, nil) @connection.start end end describe "when closing connections" do it "should not close connections that are not open" do allow(@connection).to receive(:connection).and_return(@ldapconn) expect(@ldapconn).to receive(:bound?).and_return(false) expect(@ldapconn).not_to receive(:unbind) @connection.close end end it "should have a class-level method for creating a default connection" do expect(Puppet::Util::Ldap::Connection).to respond_to(:instance) end describe "when creating a default connection" do it "should use the :ldapserver setting to determine the host" do Puppet[:ldapserver] = "myserv" expect(Puppet::Util::Ldap::Connection).to receive(:new).with("myserv", anything, anything) Puppet::Util::Ldap::Connection.instance end it "should use the :ldapport setting to determine the port" do Puppet[:ldapport] = 456 expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, 456, anything) Puppet::Util::Ldap::Connection.instance end it "should set ssl to :tls if tls is enabled" do Puppet[:ldaptls] = true expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: :tls)) Puppet::Util::Ldap::Connection.instance end it "should set ssl to 'true' if ssl is enabled and tls is not" do Puppet[:ldaptls] = false Puppet[:ldapssl] = true expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: true)) Puppet::Util::Ldap::Connection.instance end it "should set ssl to false if neither ssl nor tls are enabled" do Puppet[:ldaptls] = false Puppet[:ldapssl] = false expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: false)) Puppet::Util::Ldap::Connection.instance end it "should set the ldapuser if one is set" do Puppet[:ldapuser] = "foo" expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(user: "foo")) Puppet::Util::Ldap::Connection.instance end it "should set the ldapuser and ldappassword if both is set" do Puppet[:ldapuser] = "foo" Puppet[:ldappassword] = "bar" expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(user: "foo", password: "bar")) Puppet::Util::Ldap::Connection.instance end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/ldap/manager_spec.rb
spec/unit/util/ldap/manager_spec.rb
require 'spec_helper' require 'puppet/util/ldap/manager' describe Puppet::Util::Ldap::Manager, :if => Puppet.features.ldap? do before do @manager = Puppet::Util::Ldap::Manager.new end it "should return self when specifying objectclasses" do expect(@manager.manages(:one, :two)).to equal(@manager) end it "should allow specification of what objectclasses are managed" do expect(@manager.manages(:one, :two).objectclasses).to eq([:one, :two]) end it "should return self when specifying the relative base" do expect(@manager.at("yay")).to equal(@manager) end it "should allow specification of the relative base" do expect(@manager.at("yay").location).to eq("yay") end it "should return self when specifying the attribute map" do expect(@manager.maps(:one => :two)).to equal(@manager) end it "should allow specification of the rdn attribute" do expect(@manager.named_by(:uid).rdn).to eq(:uid) end it "should allow specification of the attribute map" do expect(@manager.maps(:one => :two).puppet2ldap).to eq({:one => :two}) end it "should have a no-op 'and' method that just returns self" do expect(@manager.and).to equal(@manager) end it "should allow specification of generated attributes" do expect(@manager.generates(:thing)).to be_instance_of(Puppet::Util::Ldap::Generator) end describe "when generating attributes" do before do @generator = double('generator', :source => "one", :name => "myparam") allow(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(@generator) end it "should create a generator to do the parameter generation" do expect(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(@generator) @manager.generates(:myparam) end it "should return the generator from the :generates method" do expect(@manager.generates(:myparam)).to equal(@generator) end it "should not replace already present values" do @manager.generates(:myparam) attrs = {"myparam" => "testing"} expect(@generator).not_to receive(:generate) @manager.generate attrs expect(attrs["myparam"]).to eq("testing") end it "should look for the parameter as a string, not a symbol" do @manager.generates(:myparam) expect(@generator).to receive(:generate).with("yay").and_return(%w{double yay}) attrs = {"one" => "yay"} @manager.generate attrs expect(attrs["myparam"]).to eq(%w{double yay}) end it "should fail if a source is specified and no source value is not defined" do @manager.generates(:myparam) expect { @manager.generate "two" => "yay" }.to raise_error(ArgumentError) end it "should use the source value to generate the new value if a source attribute is specified" do @manager.generates(:myparam) expect(@generator).to receive(:generate).with("yay").and_return(%w{double yay}) @manager.generate "one" => "yay" end it "should not pass in any value if no source attribute is specified" do allow(@generator).to receive(:source).and_return(nil) @manager.generates(:myparam) expect(@generator).to receive(:generate).and_return(%w{double yay}) @manager.generate "one" => "yay" end it "should convert any results to arrays of strings if necessary" do expect(@generator).to receive(:generate).and_return(:test) @manager.generates(:myparam) attrs = {"one" => "two"} @manager.generate(attrs) expect(attrs["myparam"]).to eq(["test"]) end it "should add the result to the passed-in attribute hash" do expect(@generator).to receive(:generate).and_return(%w{test}) @manager.generates(:myparam) attrs = {"one" => "two"} @manager.generate(attrs) expect(attrs["myparam"]).to eq(%w{test}) end end it "should be considered invalid if it is missing a location" do @manager.manages :me @manager.maps :me => :you expect(@manager).not_to be_valid end it "should be considered invalid if it is missing an objectclass list" do @manager.maps :me => :you @manager.at "ou=yayness" expect(@manager).not_to be_valid end it "should be considered invalid if it is missing an attribute map" do @manager.manages :me @manager.at "ou=yayness" expect(@manager).not_to be_valid end it "should be considered valid if it has an attribute map, location, and objectclass list" do @manager.maps :me => :you @manager.manages :me @manager.at "ou=yayness" expect(@manager).to be_valid end it "should calculate an instance's dn using the :ldapbase setting and the relative base" do Puppet[:ldapbase] = "dc=testing" @manager.at "ou=mybase" expect(@manager.dn("me")).to eq("cn=me,ou=mybase,dc=testing") end it "should use the specified rdn when calculating an instance's dn" do Puppet[:ldapbase] = "dc=testing" @manager.named_by :uid @manager.at "ou=mybase" expect(@manager.dn("me")).to match(/^uid=me/) end it "should calculate its base using the :ldapbase setting and the relative base" do Puppet[:ldapbase] = "dc=testing" @manager.at "ou=mybase" expect(@manager.base).to eq("ou=mybase,dc=testing") end describe "when generating its search filter" do it "should using a single 'objectclass=<name>' filter if a single objectclass is specified" do @manager.manages("testing") expect(@manager.filter).to eq("objectclass=testing") end it "should create an LDAP AND filter if multiple objectclasses are specified" do @manager.manages "testing", "okay", "done" expect(@manager.filter).to eq("(&(objectclass=testing)(objectclass=okay)(objectclass=done))") end end it "should have a method for converting a Puppet attribute name to an LDAP attribute name as a string" do @manager.maps :puppet_attr => :ldap_attr expect(@manager.ldap_name(:puppet_attr)).to eq("ldap_attr") end it "should have a method for converting an LDAP attribute name to a Puppet attribute name" do @manager.maps :puppet_attr => :ldap_attr expect(@manager.puppet_name(:ldap_attr)).to eq(:puppet_attr) end it "should have a :create method for creating ldap entries" do expect(@manager).to respond_to(:create) end it "should have a :delete method for deleting ldap entries" do expect(@manager).to respond_to(:delete) end it "should have a :modify method for modifying ldap entries" do expect(@manager).to respond_to(:modify) end it "should have a method for finding an entry by name in ldap" do expect(@manager).to respond_to(:find) end describe "when converting ldap entries to hashes for providers" do before do @manager.maps :uno => :one, :dos => :two @result = @manager.entry2provider("dn" => ["cn=one,ou=people,dc=madstop"], "one" => ["two"], "three" => %w{four}, "objectclass" => %w{yay ness}) end it "should set the name to the short portion of the dn" do expect(@result[:name]).to eq("one") end it "should remove the objectclasses" do expect(@result["objectclass"]).to be_nil end it "should remove any attributes that are not mentioned in the map" do expect(@result["three"]).to be_nil end it "should rename convert to symbols all attributes to their puppet names" do expect(@result[:uno]).to eq(%w{two}) end it "should set the value of all unset puppet attributes as :absent" do expect(@result[:dos]).to eq(:absent) end end describe "when using an ldap connection" do before do @ldapconn = double('ldapconn') @conn = double('connection', :connection => @ldapconn, :start => nil, :close => nil) allow(Puppet::Util::Ldap::Connection).to receive(:new).and_return(@conn) end it "should fail unless a block is given" do expect { @manager.connect }.to raise_error(ArgumentError, /must pass a block/) end it "should open the connection with its server set to :ldapserver" do Puppet[:ldapserver] = "myserver" expect(Puppet::Util::Ldap::Connection).to receive(:new).with("myserver", anything, anything).and_return(@conn) @manager.connect { |c| } end it "should open the connection with its port set to the :ldapport" do Puppet[:ldapport] = 28 expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, 28, anything).and_return(@conn) @manager.connect { |c| } end it "should open the connection with no user if :ldapuser is not set" do Puppet[:ldapuser] = "" expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_excluding(:user)).and_return(@conn) @manager.connect { |c| } end it "should open the connection with its user set to the :ldapuser if it is set" do Puppet[:ldapuser] = "mypass" expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(user: "mypass")).and_return(@conn) @manager.connect { |c| } end it "should open the connection with no password if :ldappassword is not set" do Puppet[:ldappassword] = "" expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_excluding(:password)).and_return(@conn) @manager.connect { |c| } end it "should open the connection with its password set to the :ldappassword if it is set" do Puppet[:ldappassword] = "mypass" expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(password: "mypass")).and_return(@conn) @manager.connect { |c| } end it "should set ssl to :tls if ldaptls is enabled" do Puppet[:ldaptls] = true expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: :tls)).and_return(@conn) @manager.connect { |c| } end it "should set ssl to true if ldapssl is enabled" do Puppet[:ldapssl] = true expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: true)).and_return(@conn) @manager.connect { |c| } end it "should set ssl to false if neither ldaptls nor ldapssl is enabled" do Puppet[:ldapssl] = false expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: false)).and_return(@conn) @manager.connect { |c| } end it "should open, yield, and then close the connection" do expect(@conn).to receive(:start) expect(@conn).to receive(:close) expect(Puppet::Util::Ldap::Connection).to receive(:new).and_return(@conn) expect(@ldapconn).to receive(:test) @manager.connect { |c| c.test } end it "should close the connection even if there's an exception in the passed block" do expect(@conn).to receive(:close) expect { @manager.connect { |c| raise ArgumentError } }.to raise_error(ArgumentError) end end describe "when using ldap" do before do @conn = double('connection') allow(@manager).to receive(:connect).and_yield(@conn) allow(@manager).to receive(:objectclasses).and_return([:oc1, :oc2]) @manager.maps :one => :uno, :two => :dos, :three => :tres, :four => :quatro end describe "to create entries" do it "should convert the first argument to its :create method to a full dn and pass the resulting argument list to its connection" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:add).with("mydn", anything) @manager.create("myname", {"attr" => "myattrs"}) end it "should add the objectclasses to the attributes" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:add) do |_, attrs| expect(attrs["objectClass"]).to include("oc1", "oc2") end @manager.create("myname", {:one => :testing}) end it "should add the rdn to the attributes" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:add).with(anything, hash_including("cn" => %w{myname})) @manager.create("myname", {:one => :testing}) end it "should add 'top' to the objectclasses if it is not listed" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:add) do |_, attrs| expect(attrs["objectClass"]).to include("top") end @manager.create("myname", {:one => :testing}) end it "should add any generated values that are defined" do generator = double('generator', :source => :one, :name => "myparam") expect(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(generator) @manager.generates(:myparam) allow(@manager).to receive(:dn).with("myname").and_return("mydn") expect(generator).to receive(:generate).with(:testing).and_return(["generated value"]) expect(@conn).to receive(:add).with(anything, hash_including("myparam" => ["generated value"])) @manager.create("myname", {:one => :testing}) end it "should convert any generated values to arrays of strings if necessary" do generator = double('generator', :source => :one, :name => "myparam") expect(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(generator) @manager.generates(:myparam) allow(@manager).to receive(:dn).and_return("mydn") expect(generator).to receive(:generate).and_return(:generated) expect(@conn).to receive(:add).with(anything, hash_including("myparam" => ["generated"])) @manager.create("myname", {:one => :testing}) end end describe "do delete entries" do it "should convert the first argument to its :delete method to a full dn and pass the resulting argument list to its connection" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:delete).with("mydn") @manager.delete("myname") end end describe "to modify entries" do it "should convert the first argument to its :modify method to a full dn and pass the resulting argument list to its connection" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:modify).with("mydn", :mymods) @manager.modify("myname", :mymods) end end describe "to find a single entry" do it "should use the dn of the provided name as the search base, a scope of 0, and 'objectclass=*' as the filter for a search2 call" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:search2).with("mydn", 0, "objectclass=*") @manager.find("myname") end it "should return nil if an exception is thrown because no result is found" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") expect(@conn).to receive(:search2).and_raise(LDAP::ResultError) expect(@manager.find("myname")).to be_nil end it "should return a converted provider hash if the result is found" do expect(@manager).to receive(:dn).with("myname").and_return("mydn") result = {"one" => "two"} expect(@conn).to receive(:search2).and_yield(result) expect(@manager).to receive(:entry2provider).with(result).and_return("myprovider") expect(@manager.find("myname")).to eq("myprovider") end end describe "to search for multiple entries" do before do allow(@manager).to receive(:filter).and_return("myfilter") end it "should use the manager's search base as the dn of the provided name as the search base" do expect(@manager).to receive(:base).and_return("mybase") expect(@conn).to receive(:search2).with("mybase", anything, anything) @manager.search end it "should use a scope of 1" do expect(@conn).to receive(:search2).with(anything, 1, anything) @manager.search end it "should use any specified search filter" do expect(@manager).not_to receive(:filter) expect(@conn).to receive(:search2).with(anything, anything, "boo") @manager.search("boo") end it "should turn its objectclass list into its search filter if one is not specified" do expect(@manager).to receive(:filter).and_return("yay") expect(@conn).to receive(:search2).with(anything, anything, "yay") @manager.search end it "should return nil if no result is found" do expect(@conn).to receive(:search2) expect(@manager.search).to be_nil end it "should return an array of the found results converted to provider hashes" do # LAK: AFAICT, it's impossible to yield multiple times in an expectation. one = {"dn" => "cn=one,dc=madstop,dc=com", "one" => "two"} expect(@conn).to receive(:search2).and_yield(one) expect(@manager).to receive(:entry2provider).with(one).and_return("myprov") expect(@manager.search).to eq(["myprov"]) end end end describe "when an instance" do before do @name = "myname" @manager.maps :one => :uno, :two => :dos, :three => :tres, :four => :quatro end describe "is being updated" do it "should get created if the current attribute list is empty and the desired attribute list has :ensure == :present" do expect(@manager).to receive(:create) @manager.update(@name, {}, {:ensure => :present}) end it "should get created if the current attribute list has :ensure == :absent and the desired attribute list has :ensure == :present" do expect(@manager).to receive(:create) @manager.update(@name, {:ensure => :absent}, {:ensure => :present}) end it "should get deleted if the current attribute list has :ensure == :present and the desired attribute list has :ensure == :absent" do expect(@manager).to receive(:delete) @manager.update(@name, {:ensure => :present}, {:ensure => :absent}) end it "should get modified if both attribute lists have :ensure == :present" do expect(@manager).to receive(:modify) @manager.update(@name, {:ensure => :present, :one => :two}, {:ensure => :present, :one => :three}) end end describe "is being deleted" do it "should call the :delete method with its name and manager" do expect(@manager).to receive(:delete).with(@name) @manager.update(@name, {}, {:ensure => :absent}) end end describe "is being created" do before do @is = {} @should = {:ensure => :present, :one => :yay, :two => :absent} end it "should call the :create method with its name" do expect(@manager).to receive(:create).with(@name, anything) @manager.update(@name, @is, @should) end it "should call the :create method with its property hash converted to ldap attribute names" do expect(@manager).to receive(:create).with(anything, hash_including("uno" => ["yay"])) @manager.update(@name, @is, @should) end it "should not include :ensure in the properties sent" do expect(@manager).to receive(:create).with(anything, hash_excluding(:ensure)) @manager.update(@name, @is, @should) end it "should not include attributes set to :absent in the properties sent" do expect(@manager).to receive(:create).with(anything, hash_excluding(:dos)) @manager.update(@name, @is, @should) end end describe "is being modified" do it "should call the :modify method with its name and an array of LDAP::Mod instances" do allow(LDAP::Mod).to receive(:new).and_return("whatever") @is = {:one => :yay} @should = {:one => :yay, :two => :foo} expect(@manager).to receive(:modify).with(@name, anything) @manager.update(@name, @is, @should) end it "should create the LDAP::Mod with the property name converted to the ldap name as a string" do @is = {:one => :yay} @should = {:one => :yay, :two => :foo} mod = double('module') expect(LDAP::Mod).to receive(:new).with(anything, "dos", anything).and_return(mod) allow(@manager).to receive(:modify) @manager.update(@name, @is, @should) end it "should create an LDAP::Mod instance of type LDAP_MOD_ADD for each attribute being added, with the attribute value converted to a string of arrays" do @is = {:one => :yay} @should = {:one => :yay, :two => :foo} mod = double('module') expect(LDAP::Mod).to receive(:new).with(LDAP::LDAP_MOD_ADD, "dos", ["foo"]).and_return(mod) allow(@manager).to receive(:modify) @manager.update(@name, @is, @should) end it "should create an LDAP::Mod instance of type LDAP_MOD_DELETE for each attribute being deleted" do @is = {:one => :yay, :two => :foo} @should = {:one => :yay, :two => :absent} mod = double('module') expect(LDAP::Mod).to receive(:new).with(LDAP::LDAP_MOD_DELETE, "dos", []).and_return(mod) allow(@manager).to receive(:modify) @manager.update(@name, @is, @should) end it "should create an LDAP::Mod instance of type LDAP_MOD_REPLACE for each attribute being modified, with the attribute converted to a string of arrays" do @is = {:one => :yay, :two => :four} @should = {:one => :yay, :two => :five} mod = double('module') expect(LDAP::Mod).to receive(:new).with(LDAP::LDAP_MOD_REPLACE, "dos", ["five"]).and_return(mod) allow(@manager).to receive(:modify) @manager.update(@name, @is, @should) end it "should pass all created Mod instances to the modify method" do @is = {:one => :yay, :two => :foo, :three => :absent} @should = {:one => :yay, :two => :foe, :three => :fee, :four => :fie} expect(LDAP::Mod).to receive(:new).exactly(3).times().and_return("mod1", "mod2", "mod3") expect(@manager).to receive(:modify).with(anything, contain_exactly(*%w{mod1 mod2 mod3})) @manager.update(@name, @is, @should) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/ldap/generator_spec.rb
spec/unit/util/ldap/generator_spec.rb
require 'spec_helper' require 'puppet/util/ldap/generator' describe Puppet::Util::Ldap::Generator do before do @generator = Puppet::Util::Ldap::Generator.new(:uno) end it "should require a parameter name at initialization" do expect { Puppet::Util::Ldap::Generator.new }.to raise_error(ArgumentError, /wrong number of arguments/) end it "should always return its name as a string" do g = Puppet::Util::Ldap::Generator.new(:myname) expect(g.name).to eq("myname") end it "should provide a method for declaring the source parameter" do @generator.from(:dos) end it "should always return a set source as a string" do @generator.from(:dos) expect(@generator.source).to eq("dos") end it "should return the source as nil if there is no source" do expect(@generator.source).to be_nil end it "should return itself when declaring the source" do expect(@generator.from(:dos)).to equal(@generator) end it "should run the provided block when asked to generate the value" do @generator.with { "yayness" } expect(@generator.generate).to eq("yayness") end it "should pass in any provided value to the block" do @generator.with { |value| value.upcase } expect(@generator.generate("myval")).to eq("MYVAL") end it "should return itself when declaring the code used for generating" do expect(@generator.with { |value| value.upcase }).to equal(@generator) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/network_device/config_spec.rb
spec/unit/util/network_device/config_spec.rb
require 'spec_helper' require 'puppet/util/network_device/config' describe Puppet::Util::NetworkDevice::Config do include PuppetSpec::Files before(:each) do Puppet[:deviceconfig] = tmpfile('deviceconfig') end describe "when parsing device" do let(:config) { Puppet::Util::NetworkDevice::Config.new } def write_device_config(*lines) File.open(Puppet[:deviceconfig], 'w') {|f| f.puts lines} end it "should skip comments" do write_device_config(' # comment') expect(config.devices).to be_empty end it "should increment line number even on commented lines" do write_device_config(' # comment','[router.puppetlabs.com]') expect(config.devices).to be_include('router.puppetlabs.com') end it "should skip blank lines" do write_device_config(' ') expect(config.devices).to be_empty end it "should produce the correct line number" do write_device_config(' ', '[router.puppetlabs.com]') expect(config.devices['router.puppetlabs.com'].line).to eq(2) end it "should throw an error if the current device already exists" do write_device_config('[router.puppetlabs.com]', '[router.puppetlabs.com]') end it "should accept device certname containing dashes" do write_device_config('[router-1.puppetlabs.com]') expect(config.devices).to include('router-1.puppetlabs.com') end it "should create a new device for each found device line" do write_device_config('[router.puppetlabs.com]', '[swith.puppetlabs.com]') expect(config.devices.size).to eq(2) end it "should parse the device type" do write_device_config('[router.puppetlabs.com]', 'type cisco') expect(config.devices['router.puppetlabs.com'].provider).to eq('cisco') end it "should parse the device url" do write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/') expect(config.devices['router.puppetlabs.com'].url).to eq('ssh://test/') end it "should error with a malformed device url" do write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test node/') expect { config.devices['router.puppetlabs.com'] }.to raise_error Puppet::Error end it "should parse the debug mode" do write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/', 'debug') expect(config.devices['router.puppetlabs.com'].options).to eq({ :debug => true }) end it "should set the debug mode to false by default" do write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/') expect(config.devices['router.puppetlabs.com'].options).to eq({ :debug => false }) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/network_device/transport/base_spec.rb
spec/unit/util/network_device/transport/base_spec.rb
require 'spec_helper' require 'puppet/util/network_device/transport/base' describe Puppet::Util::NetworkDevice::Transport::Base do class TestTransport < Puppet::Util::NetworkDevice::Transport::Base end before(:each) do @transport = TestTransport.new end describe "when sending commands" do it "should send the command to the telnet session" do expect(@transport).to receive(:send).with("line") @transport.command("line") end it "should expect an output matching the given prompt" do expect(@transport).to receive(:expect).with(/prompt/) @transport.command("line", :prompt => /prompt/) end it "should expect an output matching the default prompt" do @transport.default_prompt = /defprompt/ expect(@transport).to receive(:expect).with(/defprompt/) @transport.command("line") end it "should yield telnet output to the given block" do expect(@transport).to receive(:expect).and_yield("output") @transport.command("line") { |out| expect(out).to eq("output") } end it "should return telnet output to the caller" do expect(@transport).to receive(:expect).and_return("output") expect(@transport.command("line")).to eq("output") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/command_line_utils/puppet_option_parser_spec.rb
spec/unit/util/command_line_utils/puppet_option_parser_spec.rb
require 'spec_helper' require 'puppet/util/command_line/puppet_option_parser' describe Puppet::Util::CommandLine::PuppetOptionParser do let(:option_parser) { described_class.new } describe "an option with a value" do it "parses a 'long' option with a value" do parses( :option => ["--angry", "Angry", :REQUIRED], :from_arguments => ["--angry", "foo"], :expects => "foo" ) expect(@logs).to be_empty end it "parses a 'long' option with a value and converts '-' to '_' & warns" do parses( :option => ["--an_gry", "Angry", :REQUIRED], :from_arguments => ["--an-gry", "foo"], :expects => "foo" ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an_gry, got --an-gry. Partial argument matching is deprecated and will be removed in a future release./) end it "parses a 'long' option with a value and converts '_' to '-' & warns" do parses( :option => ["--an-gry", "Angry", :REQUIRED], :from_arguments => ["--an_gry", "foo"], :expects => "foo" ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an-gry, got --an_gry. Partial argument matching is deprecated and will be removed in a future release./) end it "parses a 'short' option with a value" do parses( :option => ["--angry", "-a", "Angry", :REQUIRED], :from_arguments => ["-a", "foo"], :expects => "foo" ) expect(@logs).to be_empty end it "overrides a previous argument with a later one" do parses( :option => ["--later", "Later", :REQUIRED], :from_arguments => ["--later", "tomorrow", "--later", "morgen"], :expects => "morgen" ) expect(@logs).to be_empty end end describe "an option without a value" do it "parses a 'long' option" do parses( :option => ["--angry", "Angry", :NONE], :from_arguments => ["--angry"], :expects => true ) end it "converts '_' to '-' with a 'long' option & warns" do parses( :option => ["--an-gry", "Angry", :NONE], :from_arguments => ["--an_gry"], :expects => true ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an-gry, got --an_gry. Partial argument matching is deprecated and will be removed in a future release./) end it "converts '-' to '_' with a 'long' option & warns" do parses( :option => ["--an_gry", "Angry", :NONE], :from_arguments => ["--an-gry"], :expects => true ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an_gry, got --an-gry. Partial argument matching is deprecated and will be removed in a future release./) end it "parses a 'short' option" do parses( :option => ["--angry", "-a", "Angry", :NONE], :from_arguments => ["-a"], :expects => true ) end it "supports the '--no-blah' syntax" do parses( :option => ["--[no-]rage", "Rage", :NONE], :from_arguments => ["--no-rage"], :expects => false ) expect(@logs).to be_empty end it "resolves '-' to '_' with '--no-blah' syntax" do parses( :option => ["--[no-]an_gry", "Angry", :NONE], :from_arguments => ["--no-an-gry"], :expects => false ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]an_gry, got --no-an-gry. Partial argument matching is deprecated and will be removed in a future release./) end it "resolves '_' to '-' with '--no-blah' syntax" do parses( :option => ["--[no-]an-gry", "Angry", :NONE], :from_arguments => ["--no-an_gry"], :expects => false ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]an-gry, got --no-an_gry. Partial argument matching is deprecated and will be removed in a future release./) end it "resolves '-' to '_' & warns when option is defined with '--no-blah syntax' but argument is given in '--option' syntax" do parses( :option => ["--[no-]rag-e", "Rage", :NONE], :from_arguments => ["--rag_e"], :expects => true ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]rag-e, got --rag_e. Partial argument matching is deprecated and will be removed in a future release./) end it "resolves '_' to '-' & warns when option is defined with '--no-blah syntax' but argument is given in '--option' syntax" do parses( :option => ["--[no-]rag_e", "Rage", :NONE], :from_arguments => ["--rag-e"], :expects => true ) expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]rag_e, got --rag-e. Partial argument matching is deprecated and will be removed in a future release./) end it "overrides a previous argument with a later one" do parses( :option => ["--[no-]rage", "Rage", :NONE], :from_arguments => ["--rage", "--no-rage"], :expects => false ) expect(@logs).to be_empty end end it "does not accept an unknown option specification" do expect { option_parser.on("not", "enough") }.to raise_error(ArgumentError, /this method only takes 3 or 4 arguments/) end it "does not modify the original argument array" do option_parser.on("--foo", "Foo", :NONE) { |val| } args = ["--foo"] option_parser.parse(args) expect(args.length).to eq(1) end # The ruby stdlib OptionParser has an awesome "feature" that you cannot disable, whereby if # it sees a short option that you haven't specifically registered with it (e.g., "-r"), it # will automatically attempt to expand it out to whatever long options that you might have # registered. Since we need to do our option parsing in two passes (one pass against only # the global/puppet-wide settings definitions, and then a second pass that includes the # application or face settings--because we can't load the app/face until we've determined # the libdir), it is entirely possible that we intend to define our "short" option as part # of the second pass. Therefore, if the option parser attempts to expand it out into a # long option during the first pass, terrible things will happen. # # A long story short: we need to have the ability to control this kind of behavior in our # option parser, and this test simply affirms that we do. it "does not try to expand short options that weren't explicitly registered" do [ ["--ridiculous", "This is ridiculous", :REQUIRED], ["--rage-inducing", "This is rage-inducing", :REQUIRED] ].each do |option| option_parser.on(*option) {} end expect { option_parser.parse(["-r"]) }.to raise_error(Puppet::Util::CommandLine::PuppetOptionError) end it "respects :ignore_invalid_options" do option_parser.ignore_invalid_options = true expect { option_parser.parse(["--unknown-option"]) }.not_to raise_error end it "raises if there is an invalid option and :ignore_invalid_options is not set" do expect { option_parser.parse(["--unknown-option"]) }.to raise_error(Puppet::Util::CommandLine::PuppetOptionError) end def parses(option_case) option = option_case[:option] expected_value = option_case[:expects] arguments = option_case[:from_arguments] seen_value = nil option_parser.on(*option) do |val| seen_value = val end option_parser.parse(arguments) expect(seen_value).to eq(expected_value) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/file_spec.rb
spec/unit/util/windows/file_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe Puppet::Util::Windows::File, :if => Puppet::Util::Platform.windows? do include PuppetSpec::Files let(:nonexist_file) { 'C:\foo.bar' } let(:nonexist_path) { 'C:\somefile\that\wont\ever\exist' } let(:invalid_file_attributes) { 0xFFFFFFFF } #define INVALID_FILE_ATTRIBUTES (DWORD (-1)) describe "get_attributes" do it "should raise an error for files that do not exist by default" do expect { described_class.get_attributes(nonexist_file) }.to raise_error(Puppet::Error, /GetFileAttributes/) end it "should raise an error for files that do not exist when specified" do expect { described_class.get_attributes(nonexist_file, true) }.to raise_error(Puppet::Error, /GetFileAttributes/) end it "should not raise an error for files that do not exist when specified" do expect { described_class.get_attributes(nonexist_file, false) }.not_to raise_error end it "should return INVALID_FILE_ATTRIBUTES for files that do not exist when specified" do expect(described_class.get_attributes(nonexist_file, false)).to eq(invalid_file_attributes) end end describe "get_long_pathname" do it "should raise an ERROR_FILE_NOT_FOUND for a file that does not exist in a valid path" do expect { described_class.get_long_pathname(nonexist_file) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_FILE_NOT_FOUND) end end it "should raise an ERROR_PATH_NOT_FOUND for a path that does not exist" do expect { described_class.get_long_pathname(nonexist_path) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_PATH_NOT_FOUND) end end it "should return the fully expanded path 'Program Files' given 'Progra~1'" do # this test could be resolve some of these values at runtime rather than hard-coding shortened = ENV['SystemDrive'] + '\\Progra~1' expanded = ENV['SystemDrive'] + '\\Program Files' expect(described_class.get_long_pathname(shortened)).to eq (expanded) end end describe "get_short_pathname" do it "should raise an ERROR_FILE_NOT_FOUND for a file that does not exist in a valid path" do expect { described_class.get_short_pathname(nonexist_file) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_FILE_NOT_FOUND) end end it "should raise an ERROR_PATH_NOT_FOUND for a path that does not exist" do expect { described_class.get_short_pathname(nonexist_path) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_PATH_NOT_FOUND) end end it "should return the shortened 'PROGRA~1' given fully expanded path 'Program Files'" do # this test could be resolve some of these values at runtime rather than hard-coding expanded = ENV['SystemDrive'] + '\\Program Files' shortened = ENV['SystemDrive'] + '\\PROGRA~1' expect(described_class.get_short_pathname(expanded)).to eq (shortened) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/string_spec.rb
spec/unit/util/windows/string_spec.rb
# encoding: UTF-8 require 'spec_helper' require 'puppet/util/windows' describe "Puppet::Util::Windows::String", :if => Puppet::Util::Platform.windows? do def wide_string(str) Puppet::Util::Windows::String.wide_string(str) end def converts_to_wide_string(string_value) expected = string_value.encode(Encoding::UTF_16LE) expected_bytes = expected.bytes.to_a expect(wide_string(string_value).bytes.to_a).to eq(expected_bytes) end context "wide_string" do it "should return encoding of UTF-16LE" do expect(wide_string("bob").encoding).to eq(Encoding::UTF_16LE) end it "should return valid encoding" do expect(wide_string("bob").valid_encoding?).to be_truthy end it "should convert an ASCII string" do converts_to_wide_string("bob".encode(Encoding::US_ASCII)) end it "should convert a UTF-8 string" do converts_to_wide_string("bob".encode(Encoding::UTF_8)) end it "should convert a UTF-16LE string" do converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_16LE)) end it "should convert a UTF-16BE string" do converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_16BE)) end it "should convert an UTF-32LE string" do converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_32LE)) end it "should convert an UTF-32BE string" do converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_32BE)) end it "should return a nil when given a nil" do expect(wide_string(nil)).to eq(nil) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/adsi_spec.rb
spec/unit/util/windows/adsi_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe Puppet::Util::Windows::ADSI, :if => Puppet::Util::Platform.windows? do let(:connection) { double('connection') } let(:builtin_localized) { Puppet::Util::Windows::SID.sid_to_name('S-1-5-32') } # SYSTEM is special as English can retrieve it via Windows API # but will return localized names let(:ntauthority_localized) { Puppet::Util::Windows::SID::Principal.lookup_account_name('SYSTEM').domain } before(:each) do Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, 'testcomputername') allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(connection) end after(:each) do Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, nil) end it "should generate the correct URI for a resource" do expect(Puppet::Util::Windows::ADSI.uri('test', 'user')).to eq("WinNT://./test,user") end it "should be able to get the name of the computer" do expect(Puppet::Util::Windows::ADSI.computer_name).to eq('testcomputername') end it "should be able to provide the correct WinNT base URI for the computer" do expect(Puppet::Util::Windows::ADSI.computer_uri).to eq("WinNT://.") end it "should generate a fully qualified WinNT URI" do expect(Puppet::Util::Windows::ADSI.computer_uri('testcomputername')).to eq("WinNT://testcomputername") end describe ".computer_name" do it "should return a non-empty ComputerName string" do Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, nil) expect(Puppet::Util::Windows::ADSI.computer_name).not_to be_empty end end describe ".domain_role" do DOMAIN_ROLES = Puppet::Util::Platform.windows? ? Puppet::Util::Windows::ADSI::DOMAIN_ROLES : {} DOMAIN_ROLES.each do |id, role| it "should be able to return #{role} as the domain role of the computer" do Puppet::Util::Windows::ADSI.instance_variable_set(:@domain_role, nil) domain_role = [double('WMI', :DomainRole => id)] allow(Puppet::Util::Windows::ADSI).to receive(:execquery).with('select DomainRole from Win32_ComputerSystem').and_return(domain_role) expect(Puppet::Util::Windows::ADSI.domain_role).to eq(role) end end end describe ".sid_uri" do it "should raise an error when the input is not a SID Principal" do [Object.new, {}, 1, :symbol, '', nil].each do |input| expect { Puppet::Util::Windows::ADSI.sid_uri(input) }.to raise_error(Puppet::Error, /Must use a valid SID::Principal/) end end it "should return a SID uri for a well-known SID (SYSTEM)" do sid = Puppet::Util::Windows::SID::Principal.lookup_account_name('SYSTEM') expect(Puppet::Util::Windows::ADSI.sid_uri(sid)).to eq('WinNT://S-1-5-18') end end shared_examples 'a local only resource query' do |klass, account_type| before(:each) do allow(Puppet::Util::Windows::ADSI).to receive(:domain_role).and_return(:MEMBER_SERVER) end it "should be able to check for a local resource" do local_domain = 'testcomputername' principal = double('Principal', :account => resource_name, :domain => local_domain, :account_type => account_type) allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(resource_name).and_return(principal) expect(klass.exists?(resource_name)).to eq(true) end it "should be case insensitive when comparing the domain with the computer name" do local_domain = 'TESTCOMPUTERNAME' principal = double('Principal', :account => resource_name, :domain => local_domain, :account_type => account_type) allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(resource_name).and_return(principal) expect(klass.exists?(resource_name)).to eq(true) end it "should return false if no local resource exists" do principal = double('Principal', :account => resource_name, :domain => 'AD_DOMAIN', :account_type => account_type) allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(resource_name).and_return(principal) expect(klass.exists?(resource_name)).to eq(false) end end describe '.get_sids' do it 'returns an array of SIDs given two an array of ADSI children' do child1 = double('child1', name: 'Administrator', sid: 'S-1-5-21-3882680660-671291151-3888264257-500') child2 = double('child2', name: 'Guest', sid: 'S-1-5-21-3882680660-671291151-3888264257-501') allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child1).and_return('Administrator') allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child2).and_return('Guest') sids = Puppet::Util::Windows::ADSI::ADSIObject.get_sids([child1, child2]) expect(sids).to eq(['Administrator', 'Guest']) end it 'returns an array of SIDs given an ADSI child and ads_to_principal returning domain failure' do child = double('child1', name: 'Administrator', sid: 'S-1-5-21-3882680660-671291151-3888264257-500') allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child).and_raise(Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::SID::ERROR_TRUSTED_DOMAIN_FAILURE)) sids = Puppet::Util::Windows::ADSI::ADSIObject.get_sids([child]) expect(sids[0]).to eq(Puppet::Util::Windows::SID::Principal.new(child.name, child.sid, child.name, nil, :SidTypeUnknown)) end it 'returns an array of SIDs given an ADSI child and ads_to_principal returning relationship failure' do child = double('child1', name: 'Administrator', sid: 'S-1-5-21-3882680660-671291151-3888264257-500') allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child).and_raise(Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::SID::ERROR_TRUSTED_RELATIONSHIP_FAILURE)) sids = Puppet::Util::Windows::ADSI::ADSIObject.get_sids([child]) expect(sids[0]).to eq(Puppet::Util::Windows::SID::Principal.new(child.name, child.sid, child.name, nil, :SidTypeUnknown)) end end describe Puppet::Util::Windows::ADSI::User do let(:username) { 'testuser' } let(:domain) { 'DOMAIN' } let(:domain_username) { "#{domain}\\#{username}"} it "should generate the correct URI" do expect(Puppet::Util::Windows::ADSI::User.uri(username)).to eq("WinNT://./#{username},user") end it "should generate the correct URI for a user with a domain" do expect(Puppet::Util::Windows::ADSI::User.uri(username, domain)).to eq("WinNT://#{domain}/#{username},user") end it "should generate the correct URI for a BUILTIN user" do expect(Puppet::Util::Windows::ADSI::User.uri(username, builtin_localized)).to eq("WinNT://./#{username},user") end it "should generate the correct URI for a NT AUTHORITY user" do expect(Puppet::Util::Windows::ADSI::User.uri(username, ntauthority_localized)).to eq("WinNT://./#{username},user") end it "should be able to parse a username without a domain" do expect(Puppet::Util::Windows::ADSI::User.parse_name(username)).to eq([username, '.']) end it "should be able to parse a username with a domain" do expect(Puppet::Util::Windows::ADSI::User.parse_name(domain_username)).to eq([username, domain]) end it "should raise an error with a username that contains a /" do expect { Puppet::Util::Windows::ADSI::User.parse_name("#{domain}/#{username}") }.to raise_error(Puppet::Error, /Value must be in DOMAIN\\user style syntax/) end it "should be able to create a user" do adsi_user = double('adsi') expect(connection).to receive(:Create).with('user', username).and_return(adsi_user) expect(Puppet::Util::Windows::ADSI::Group).to receive(:exists?).with(username).and_return(false) user = Puppet::Util::Windows::ADSI::User.create(username) expect(user).to be_a(Puppet::Util::Windows::ADSI::User) expect(user.native_object).to eq(adsi_user) end context "when domain-joined" do it_should_behave_like 'a local only resource query', Puppet::Util::Windows::ADSI::User, :SidTypeUser do let(:resource_name) { username } end end it "should be able to check the existence of a user" do expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(username).and_return(nil) expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{username},user").and_return(connection) expect(connection).to receive(:Class).and_return('User') expect(Puppet::Util::Windows::ADSI::User.exists?(username)).to be_truthy end it "should be able to check the existence of a domain user" do expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with("#{domain}\\#{username}").and_return(nil) expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://#{domain}/#{username},user").and_return(connection) expect(connection).to receive(:Class).and_return('User') expect(Puppet::Util::Windows::ADSI::User.exists?(domain_username)).to be_truthy end it "should be able to confirm the existence of a user with a well-known SID" do system_user = Puppet::Util::Windows::SID::LocalSystem # ensure that the underlying OS is queried here allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original() expect(Puppet::Util::Windows::ADSI::User.exists?(system_user)).to be_truthy end it "should return false with a well-known Group SID" do group = Puppet::Util::Windows::SID::BuiltinAdministrators # ensure that the underlying OS is queried here allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original() expect(Puppet::Util::Windows::ADSI::User.exists?(group)).to be_falsey end it "should return nil with an unknown SID" do bogus_sid = 'S-1-2-3-4' # ensure that the underlying OS is queried here allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original() expect(Puppet::Util::Windows::ADSI::User.exists?(bogus_sid)).to be_falsey end it "should be able to delete a user" do expect(connection).to receive(:Delete).with('user', username) Puppet::Util::Windows::ADSI::User.delete(username) end it "should return an enumeration of IADsUser wrapped objects" do name = 'Administrator' wmi_users = [double('WMI', :name => name)] expect(Puppet::Util::Windows::ADSI).to receive(:execquery).with('select name from win32_useraccount where localaccount = "TRUE"').and_return(wmi_users) native_object = double('IADsUser') homedir = "C:\\Users\\#{name}" expect(native_object).to receive(:Get).with('HomeDirectory').and_return(homedir) expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{name},user").and_return(native_object) users = Puppet::Util::Windows::ADSI::User.to_a expect(users.length).to eq(1) expect(users[0].name).to eq(name) expect(users[0]['HomeDirectory']).to eq(homedir) end describe "an instance" do let(:adsi_user) { double('user', :objectSID => []) } let(:sid) { double(:account => username, :domain => 'testcomputername') } let(:user) { Puppet::Util::Windows::ADSI::User.new(username, adsi_user) } it "should provide its groups as a list of names" do names = ["group1", "group2"] groups = names.map { |name| double('group', :Name => name) } expect(adsi_user).to receive(:Groups).and_return(groups) expect(user.groups).to match(names) end it "should be able to test whether a given password is correct" do expect(Puppet::Util::Windows::ADSI::User).to receive(:logon).with(username, 'pwdwrong').and_return(false) expect(Puppet::Util::Windows::ADSI::User).to receive(:logon).with(username, 'pwdright').and_return(true) expect(user.password_is?('pwdwrong')).to be_falsey expect(user.password_is?('pwdright')).to be_truthy end it "should be able to set a password" do expect(adsi_user).to receive(:SetPassword).with('pwd') expect(adsi_user).to receive(:SetInfo).at_least(:once) flagname = "UserFlags" fADS_UF_DONT_EXPIRE_PASSWD = 0x10000 expect(adsi_user).to receive(:Get).with(flagname).and_return(0) expect(adsi_user).to receive(:Put).with(flagname, fADS_UF_DONT_EXPIRE_PASSWD) user.password = 'pwd' end it "should be able manage a user without a password" do expect(adsi_user).not_to receive(:SetPassword).with('pwd') expect(adsi_user).to receive(:SetInfo).at_least(:once) flagname = "UserFlags" fADS_UF_DONT_EXPIRE_PASSWD = 0x10000 expect(adsi_user).to receive(:Get).with(flagname).and_return(0) expect(adsi_user).to receive(:Put).with(flagname, fADS_UF_DONT_EXPIRE_PASSWD) user.password = nil end it "should generate the correct URI" do allow(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).and_return(sid) expect(user.uri).to eq("WinNT://testcomputername/#{username},user") end describe "when given a set of groups to which to add the user" do let(:existing_groups) { ['group2','group3'] } let(:group_sids) { existing_groups.each_with_index.map{|n,i| double(:Name => n, :objectSID => double(:sid => i))} } let(:groups_to_set) { 'group1,group2' } let(:desired_sids) { groups_to_set.split(',').each_with_index.map{|n,i| double(:Name => n, :objectSID => double(:sid => i-1))} } before(:each) do expect(user).to receive(:group_sids).and_return(group_sids.map {|s| s.objectSID }) end describe "if membership is specified as inclusive" do it "should add the user to those groups, and remove it from groups not in the list" do expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return(Hash[ desired_sids.map { |s| [s.objectSID.sid, s.objectSID] }]) expect(user).to receive(:add_group_sids) { |value| expect(value.sid).to eq(-1) } expect(user).to receive(:remove_group_sids) { |value| expect(value.sid).to eq(1) } user.set_groups(groups_to_set, false) end it "should remove all users from a group if desired is empty" do expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return({}) expect(user).not_to receive(:add_group_sids) expect(user).to receive(:remove_group_sids) do |user1, user2| expect(user1.sid).to eq(0) expect(user2.sid).to eq(1) end user.set_groups('', false) end end describe "if membership is specified as minimum" do it "should add the user to the specified groups without affecting its other memberships" do expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return(Hash[ desired_sids.map { |s| [s.objectSID.sid, s.objectSID] }]) expect(user).to receive(:add_group_sids) { |value| expect(value.sid).to eq(-1) } expect(user).not_to receive(:remove_group_sids) user.set_groups(groups_to_set, true) end it "should do nothing if desired is empty" do expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return({}) expect(user).not_to receive(:remove_group_sids) expect(user).not_to receive(:add_group_sids) user.set_groups('', true) end end end describe 'userflags' do # Avoid having to type out the constant everytime we want to # retrieve a userflag's value. def ads_userflags(flag) Puppet::Util::Windows::ADSI::User::ADS_USERFLAGS[flag] end before(:each) do userflags = [ :ADS_UF_SCRIPT, :ADS_UF_ACCOUNTDISABLE, :ADS_UF_HOMEDIR_REQUIRED, :ADS_UF_LOCKOUT ].inject(0) do |flags, flag| flags | ads_userflags(flag) end allow(user).to receive(:[]).with('UserFlags').and_return(userflags) end describe '#userflag_set?' do it 'returns true if the specified userflag is set' do expect(user.userflag_set?(:ADS_UF_SCRIPT)).to be true end it 'returns false if the specified userflag is not set' do expect(user.userflag_set?(:ADS_UF_PASSWD_NOTREQD)).to be false end it 'returns false if the specified userflag is an unrecognized userflag' do expect(user.userflag_set?(:ADS_UF_UNRECOGNIZED_FLAG)).to be false end end shared_examples 'set/unset common tests' do |method| it 'raises an ArgumentError for any unrecognized userflags' do unrecognized_flags = [ :ADS_UF_UNRECOGNIZED_FLAG_ONE, :ADS_UF_UNRECOGNIZED_FLAG_TWO ] input_flags = unrecognized_flags + [ :ADS_UF_PASSWORD_EXPIRED, :ADS_UF_DONT_EXPIRE_PASSWD ] expect { user.send(method, *input_flags) }.to raise_error( ArgumentError, /#{unrecognized_flags.join(', ')}/ ) end it 'noops if no userflags are passed-in' do expect(user).not_to receive(:[]=) expect(user).not_to receive(:commit) user.send(method) end end describe '#set_userflags' do include_examples 'set/unset common tests', :set_userflags it 'should add the passed-in flags to the current set of userflags' do input_flags = [ :ADS_UF_PASSWORD_EXPIRED, :ADS_UF_DONT_EXPIRE_PASSWD ] userflags = user['UserFlags'] expected_userflags = userflags | ads_userflags(input_flags[0]) | ads_userflags(input_flags[1]) expect(user).to receive(:[]=).with('UserFlags', expected_userflags) user.set_userflags(*input_flags) end end describe '#unset_userflags' do include_examples 'set/unset common tests', :unset_userflags it 'should remove the passed-in flags from the current set of userflags' do input_flags = [ :ADS_UF_SCRIPT, :ADS_UF_ACCOUNTDISABLE ] # ADS_UF_HOMEDIR_REQUIRED and ADS_UF_LOCKOUT should be the only flags set. expected_userflags = 0 | ads_userflags(:ADS_UF_HOMEDIR_REQUIRED) | ads_userflags(:ADS_UF_LOCKOUT) expect(user).to receive(:[]=).with('UserFlags', expected_userflags) user.unset_userflags(*input_flags) end end end end end describe Puppet::Util::Windows::ADSI::Group do let(:groupname) { 'testgroup' } describe "an instance" do let(:adsi_group) { double('group') } let(:group) { Puppet::Util::Windows::ADSI::Group.new(groupname, adsi_group) } let(:someone_sid){ double(:account => 'someone', :domain => 'testcomputername')} describe "should be able to use SID objects" do let(:system) { Puppet::Util::Windows::SID.name_to_principal('SYSTEM') } let(:invalid) { Puppet::Util::Windows::SID.name_to_principal('foobar') } it "to add a member" do expect(adsi_group).to receive(:Add).with("WinNT://S-1-5-18") group.add_member_sids(system) end it "and raise when passed a non-SID object to add" do expect{ group.add_member_sids(invalid)}.to raise_error(Puppet::Error, /Must use a valid SID::Principal/) end it "to remove a member" do expect(adsi_group).to receive(:Remove).with("WinNT://S-1-5-18") group.remove_member_sids(system) end it "and raise when passed a non-SID object to remove" do expect{ group.remove_member_sids(invalid)}.to raise_error(Puppet::Error, /Must use a valid SID::Principal/) end end it "should provide its groups as a list of names" do names = ['user1', 'user2'] users = names.map { |name| double('user', :Name => name, :objectSID => name, :ole_respond_to? => true) } expect(adsi_group).to receive(:Members).and_return(users) expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with('user1').and_return(double(:domain_account => 'HOSTNAME\user1')) expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with('user2').and_return(double(:domain_account => 'HOSTNAME\user2')) expect(group.members.map(&:domain_account)).to match(['HOSTNAME\user1', 'HOSTNAME\user2']) end context "calling .set_members" do it "should set the members of a group to only desired_members when inclusive" do names = ['DOMAIN\user1', 'user2'] sids = [ double(:account => 'user1', :domain => 'DOMAIN', :sid => 1), double(:account => 'user2', :domain => 'testcomputername', :sid => 2), double(:account => 'user3', :domain => 'DOMAIN2', :sid => 3), ] # use stubbed objectSid on member to return stubbed SID expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0]) expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1]) expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user2', false).and_return(sids[1]) expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('DOMAIN2\user3', false).and_return(sids[2]) expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[0]).and_return("WinNT://DOMAIN/user1,user") expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[2]).and_return("WinNT://DOMAIN2/user3,user") members = names.each_with_index.map{|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)} expect(adsi_group).to receive(:Members).and_return(members) expect(adsi_group).to receive(:Remove).with('WinNT://DOMAIN/user1,user') expect(adsi_group).to receive(:Add).with('WinNT://DOMAIN2/user3,user') group.set_members(['user2', 'DOMAIN2\user3']) end it "should add the desired_members to an existing group when not inclusive" do names = ['DOMAIN\user1', 'user2'] sids = [ double(:account => 'user1', :domain => 'DOMAIN', :sid => 1), double(:account => 'user2', :domain => 'testcomputername', :sid => 2), double(:account => 'user3', :domain => 'DOMAIN2', :sid => 3), ] # use stubbed objectSid on member to return stubbed SID expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0]) expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1]) expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user2', any_args).and_return(sids[1]) expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('DOMAIN2\user3', any_args).and_return(sids[2]) expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[2]).and_return("WinNT://DOMAIN2/user3,user") members = names.each_with_index.map {|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)} expect(adsi_group).to receive(:Members).and_return(members) expect(adsi_group).not_to receive(:Remove).with('WinNT://DOMAIN/user1,user') expect(adsi_group).to receive(:Add).with('WinNT://DOMAIN2/user3,user') group.set_members(['user2', 'DOMAIN2\user3'],false) end it "should return immediately when desired_members is nil" do expect(adsi_group).not_to receive(:Members) expect(adsi_group).not_to receive(:Remove) expect(adsi_group).not_to receive(:Add) group.set_members(nil) end it "should remove all members when desired_members is empty and inclusive" do names = ['DOMAIN\user1', 'user2'] sids = [ double(:account => 'user1', :domain => 'DOMAIN', :sid => 1 ), double(:account => 'user2', :domain => 'testcomputername', :sid => 2 ), ] # use stubbed objectSid on member to return stubbed SID expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0]) expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1]) expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[0]).and_return("WinNT://DOMAIN/user1,user") expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[1]).and_return("WinNT://testcomputername/user2,user") members = names.each_with_index.map{|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)} expect(adsi_group).to receive(:Members).and_return(members) expect(adsi_group).to receive(:Remove).with('WinNT://DOMAIN/user1,user') expect(adsi_group).to receive(:Remove).with('WinNT://testcomputername/user2,user') group.set_members([]) end it "should do nothing when desired_members is empty and not inclusive" do names = ['DOMAIN\user1', 'user2'] sids = [ double(:account => 'user1', :domain => 'DOMAIN', :sid => 1 ), double(:account => 'user2', :domain => 'testcomputername', :sid => 2 ), ] # use stubbed objectSid on member to return stubbed SID expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0]) expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1]) members = names.each_with_index.map{|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)} expect(adsi_group).to receive(:Members).and_return(members) expect(adsi_group).not_to receive(:Remove) expect(adsi_group).not_to receive(:Add) group.set_members([],false) end it "should raise an error when a username does not resolve to a SID" do expect { expect(adsi_group).to receive(:Members).and_return([]) group.set_members(['foobar']) }.to raise_error(Puppet::Error, /Could not resolve name: foobar/) end end it "should generate the correct URI" do expect(adsi_group).to receive(:objectSID).and_return([0]) expect(Socket).to receive(:gethostname).and_return('TESTcomputerNAME') computer_sid = double(:account => groupname,:domain => 'testcomputername') expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(computer_sid) expect(group.uri).to eq("WinNT://./#{groupname},group") end end it "should generate the correct URI" do expect(Puppet::Util::Windows::ADSI::Group.uri("people")).to eq("WinNT://./people,group") end it "should generate the correct URI for a BUILTIN group" do expect(Puppet::Util::Windows::ADSI::Group.uri(groupname, builtin_localized)).to eq("WinNT://./#{groupname},group") end it "should generate the correct URI for a NT AUTHORITY group" do expect(Puppet::Util::Windows::ADSI::Group.uri(groupname, ntauthority_localized)).to eq("WinNT://./#{groupname},group") end context "when domain-joined" do it_should_behave_like 'a local only resource query', Puppet::Util::Windows::ADSI::Group, :SidTypeGroup do let(:resource_name) { groupname } end end it "should be able to create a group" do adsi_group = double("adsi") expect(connection).to receive(:Create).with('group', groupname).and_return(adsi_group) expect(Puppet::Util::Windows::ADSI::User).to receive(:exists?).with(groupname).and_return(false) group = Puppet::Util::Windows::ADSI::Group.create(groupname) expect(group).to be_a(Puppet::Util::Windows::ADSI::Group) expect(group.native_object).to eq(adsi_group) end it "should be able to confirm the existence of a group" do expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(groupname).and_return(nil) expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{groupname},group").and_return(connection) expect(connection).to receive(:Class).and_return('Group') expect(Puppet::Util::Windows::ADSI::Group.exists?(groupname)).to be_truthy end it "should be able to confirm the existence of a group with a well-known SID" do service_group = Puppet::Util::Windows::SID::Service # ensure that the underlying OS is queried here allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original() expect(Puppet::Util::Windows::ADSI::Group.exists?(service_group)).to be_truthy end it "will return true with a well-known User SID, as there is no way to resolve it with a WinNT:// style moniker" do user = Puppet::Util::Windows::SID::NtLocal # ensure that the underlying OS is queried here allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original() expect(Puppet::Util::Windows::ADSI::Group.exists?(user)).to be_truthy end it "should return nil with an unknown SID" do bogus_sid = 'S-1-2-3-4' # ensure that the underlying OS is queried here allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original() expect(Puppet::Util::Windows::ADSI::Group.exists?(bogus_sid)).to be_falsey end it "should be able to delete a group" do expect(connection).to receive(:Delete).with('group', groupname) Puppet::Util::Windows::ADSI::Group.delete(groupname) end it "should return an enumeration of IADsGroup wrapped objects" do name = 'Administrators' wmi_groups = [double('WMI', :name => name)] expect(Puppet::Util::Windows::ADSI).to receive(:execquery).with('select name from win32_group where localaccount = "TRUE"').and_return(wmi_groups) native_object = double('IADsGroup') expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([]).and_return(double(:domain_account => '.\Administrator')) expect(native_object).to receive(:Members).and_return([double(:Name => 'Administrator', :objectSID => [], :ole_respond_to? => true)]) expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{name},group").and_return(native_object) groups = Puppet::Util::Windows::ADSI::Group.to_a expect(groups.length).to eq(1) expect(groups[0].name).to eq(name) expect(groups[0].members.map(&:domain_account)).to eq(['.\Administrator']) end end describe Puppet::Util::Windows::ADSI::UserProfile do it "should be able to delete a user profile" do expect(connection).to receive(:Delete).with("Win32_UserProfile.SID='S-A-B-C'") Puppet::Util::Windows::ADSI::UserProfile.delete('S-A-B-C') end it "should warn on 2003" do expect(connection).to receive(:Delete).and_raise(WIN32OLERuntimeError, "Delete (WIN32OLERuntimeError) OLE error code:80041010 in SWbemServicesEx Invalid class HRESULT error code:0x80020009 Exception occurred.") expect(Puppet).to receive(:warning).with("Cannot delete user profile for 'S-A-B-C' prior to Vista SP1") Puppet::Util::Windows::ADSI::UserProfile.delete('S-A-B-C') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/access_control_list_spec.rb
spec/unit/util/windows/access_control_list_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe "Puppet::Util::Windows::AccessControlList", :if => Puppet::Util::Platform.windows? do let(:klass) { Puppet::Util::Windows::AccessControlList } let(:system_sid) { 'S-1-5-18' } let(:admins_sid) { 'S-1-5-544' } let(:none_sid) { 'S-1-0-0' } let(:system_ace) do Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1) end let(:admins_ace) do Puppet::Util::Windows::AccessControlEntry.new(admins_sid, 0x2) end let(:none_ace) do Puppet::Util::Windows::AccessControlEntry.new(none_sid, 0x3) end it "constructs an empty list" do acl = klass.new expect(acl.to_a).to be_empty end it "supports copy constructor" do aces = klass.new([system_ace]).to_a expect(aces.to_a).to eq([system_ace]) end context "appending" do it "appends an allow ace" do acl = klass.new acl.allow(system_sid, 0x1, 0x2) expect(acl.first.type).to eq(klass::ACCESS_ALLOWED_ACE_TYPE) end it "appends a deny ace" do acl = klass.new acl.deny(system_sid, 0x1, 0x2) expect(acl.first.type).to eq(klass::ACCESS_DENIED_ACE_TYPE) end it "always appends, never overwrites an ACE" do acl = klass.new([system_ace]) acl.allow(admins_sid, admins_ace.mask, admins_ace.flags) aces = acl.to_a expect(aces.size).to eq(2) expect(aces[0]).to eq(system_ace) expect(aces[1].sid).to eq(admins_sid) expect(aces[1].mask).to eq(admins_ace.mask) expect(aces[1].flags).to eq(admins_ace.flags) end end context "reassigning" do it "preserves the mask from the old sid when reassigning to the new sid" do dacl = klass.new([system_ace]) dacl.reassign!(system_ace.sid, admins_ace.sid) # we removed system, so ignore prepended ace ace = dacl.to_a[1] expect(ace.sid).to eq(admins_sid) expect(ace.mask).to eq(system_ace.mask) end it "matches multiple sids" do dacl = klass.new([system_ace, system_ace]) dacl.reassign!(system_ace.sid, admins_ace.sid) # we removed system, so ignore prepended ace aces = dacl.to_a expect(aces.size).to eq(3) aces.to_a[1,2].each do |ace| expect(ace.sid).to eq(admins_ace.sid) end end it "preserves aces for sids that don't match, in their original order" do dacl = klass.new([system_ace, admins_ace]) dacl.reassign!(system_sid, none_sid) aces = dacl.to_a aces[1].sid == admins_ace.sid end it "preserves inherited aces, even if the sids match" do flags = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE inherited_ace = Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1, flags) dacl = klass.new([inherited_ace, system_ace]) dacl.reassign!(system_sid, none_sid) aces = dacl.to_a expect(aces[0].sid).to eq(system_sid) end it "prepends an explicit ace for the new sid with the same mask and basic inheritance as the inherited ace" do expected_flags = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE flags = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE | expected_flags inherited_ace = Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1, flags) dacl = klass.new([inherited_ace]) dacl.reassign!(system_sid, none_sid) aces = dacl.to_a expect(aces.size).to eq(2) expect(aces[0].sid).to eq(none_sid) expect(aces[0]).not_to be_inherited expect(aces[0].flags).to eq(expected_flags) expect(aces[1].sid).to eq(system_sid) expect(aces[1]).to be_inherited end it "makes a copy of the ace prior to modifying it" do arr = [system_ace] acl = klass.new(arr) acl.reassign!(system_sid, none_sid) expect(arr[0].sid).to eq(system_sid) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/sid_spec.rb
spec/unit/util/windows/sid_spec.rb
require 'spec_helper' describe "Puppet::Util::Windows::SID", :if => Puppet::Util::Platform.windows? do if Puppet::Util::Platform.windows? require 'puppet/util/windows' end let(:subject) { Puppet::Util::Windows::SID } let(:sid) { Puppet::Util::Windows::SID::LocalSystem } let(:invalid_sid) { 'bogus' } let(:unknown_sid) { 'S-0-0-0' } let(:null_sid) { 'S-1-0-0' } let(:unknown_name) { 'chewbacca' } context "#octet_string_to_principal" do it "should properly convert an array of bytes for a well-known non-localized SID" do bytes = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] converted = subject.octet_string_to_principal(bytes) expect(converted).to be_an_instance_of Puppet::Util::Windows::SID::Principal expect(converted.sid_bytes).to eq(bytes) expect(converted.sid).to eq(null_sid) # carefully select a SID here that is not localized on international Windows expect(converted.account).to eq('NULL SID') end it "should raise an error for non-array input" do expect { subject.octet_string_to_principal(invalid_sid) }.to raise_error(Puppet::Error, /Octet string must be an array of bytes/) end it "should raise an error for an empty byte array" do expect { subject.octet_string_to_principal([]) }.to raise_error(Puppet::Error, /Octet string must be an array of bytes/) end it "should raise an error for a valid byte array with no mapping to a user" do expect { # S-1-1-1 which is not a valid account valid_octet_invalid_user =[1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0] subject.octet_string_to_principal(valid_octet_invalid_user) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1332) # ERROR_NONE_MAPPED end end it "should raise an error for a malformed byte array" do expect { invalid_octet = [2] subject.octet_string_to_principal(invalid_octet) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(87) # ERROR_INVALID_PARAMETER end end end context "#name_to_sid" do it "should return nil if the account does not exist" do expect(subject.name_to_sid(unknown_name)).to be_nil end it "should accept unqualified account name" do # NOTE: lookup by name works in localized environments only for a few instances # this works in French Windows, even though the account is really Syst\u00E8me expect(subject.name_to_sid('SYSTEM')).to eq(sid) end it "should return a SID for a passed user or group name" do expect(subject).to receive(:name_to_principal).with('testers').and_return(double(:sid => 'S-1-5-32-547')) expect(subject.name_to_sid('testers')).to eq('S-1-5-32-547') end it "should return a SID for a passed fully-qualified user or group name" do expect(subject).to receive(:name_to_principal).with('MACHINE\testers').and_return(double(:sid => 'S-1-5-32-547')) expect(subject.name_to_sid('MACHINE\testers')).to eq('S-1-5-32-547') end it "should be case-insensitive" do expect(subject.name_to_sid('SYSTEM')).to eq(subject.name_to_sid('system')) end it "should be leading and trailing whitespace-insensitive" do expect(subject.name_to_sid('SYSTEM')).to eq(subject.name_to_sid(' SYSTEM ')) end it "should accept domain qualified account names" do # NOTE: lookup by name works in localized environments only for a few instances # this works in French Windows, even though the account is really AUTORITE NT\\Syst\u00E8me expect(subject.name_to_sid('NT AUTHORITY\SYSTEM')).to eq(sid) end it "should be the identity function for any sid" do expect(subject.name_to_sid(sid)).to eq(sid) end describe "with non-US languages" do UMLAUT = [195, 164].pack('c*').force_encoding(Encoding::UTF_8) let(:username) { SecureRandom.uuid.to_s.gsub(/\-/, '')[0..13] + UMLAUT } after(:each) { Puppet::Util::Windows::ADSI::User.delete(username) } it "should properly resolve a username with an umlaut" do # Ruby seems to use the local codepage when making COM calls # if this fails, might want to use Windows API directly instead to ensure bytes user = Puppet::Util::Windows::ADSI.create(username, 'user') user.SetPassword('PUPPET_RULeZ_123!') user.SetInfo() # compare the new SID to the name_to_sid result sid_bytes = user.objectSID.to_a sid_string = '' FFI::MemoryPointer.new(:byte, sid_bytes.length) do |sid_byte_ptr| sid_byte_ptr.write_array_of_uchar(sid_bytes) sid_string = Puppet::Util::Windows::SID.sid_ptr_to_string(sid_byte_ptr) end expect(subject.name_to_sid(username)).to eq(sid_string) end end end context "#name_to_principal" do it "should return nil if the account does not exist" do expect(subject.name_to_principal(unknown_name)).to be_nil end it "should print a debug message if the account does not exist" do expect(Puppet).to receive(:debug).with(/No mapping between account names and security IDs was done/) subject.name_to_principal(unknown_name) end it "should return a Puppet::Util::Windows::SID::Principal instance for any valid sid" do expect(subject.name_to_principal(sid)).to be_an_instance_of(Puppet::Util::Windows::SID::Principal) end it "should not print debug messages for valid sid" do expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/) expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/) subject.name_to_principal(sid) end it "should print a debug message for invalid sid" do expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/) expect(Puppet).to receive(:debug).with(/No mapping between account names and security IDs was done/) subject.name_to_principal('S-1-5-21-INVALID-SID') end it "should accept unqualified account name" do # NOTE: lookup by name works in localized environments only for a few instances # this works in French Windows, even though the account is really Syst\u00E8me expect(subject.name_to_principal('SYSTEM').sid).to eq(sid) end it "should not print debug messages for unqualified account name" do expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/) expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/) subject.name_to_principal('SYSTEM') end it "should be case-insensitive" do # NOTE: lookup by name works in localized environments only for a few instances # this works in French Windows, even though the account is really Syst\u00E8me expect(subject.name_to_principal('SYSTEM')).to eq(subject.name_to_principal('system')) end it "should not print debug messages for wrongly cased account name" do expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/) expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/) subject.name_to_principal('system') end it "should be leading and trailing whitespace-insensitive" do # NOTE: lookup by name works in localized environments only for a few instances # this works in French Windows, even though the account is really Syst\u00E8me expect(subject.name_to_principal('SYSTEM')).to eq(subject.name_to_principal(' SYSTEM ')) end it "should not print debug messages for account name with leading and trailing whitespace" do expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/) expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/) subject.name_to_principal(' SYSTEM ') end it "should accept domain qualified account names" do # NOTE: lookup by name works in localized environments only for a few instances # this works in French Windows, even though the account is really AUTORITE NT\\Syst\u00E8me expect(subject.name_to_principal('NT AUTHORITY\SYSTEM').sid).to eq(sid) end it "should not print debug messages for domain qualified account names" do expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/) expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/) subject.name_to_principal('NT AUTHORITY\SYSTEM') end end context "#ads_to_principal" do it "should raise an error for non-WIN32OLE input" do expect { subject.ads_to_principal(double('WIN32OLE', { :Name => 'foo' })) }.to raise_error(Puppet::Error, /ads_object must be an IAdsUser or IAdsGroup instance/) end it "should raise an error for an empty byte array in the objectSID property" do expect { subject.ads_to_principal(double('WIN32OLE', { :objectSID => [], :Name => '', :ole_respond_to? => true })) }.to raise_error(Puppet::Error, /Octet string must be an array of bytes/) end it "should raise an error for a malformed byte array" do expect { invalid_octet = [2] subject.ads_to_principal(double('WIN32OLE', { :objectSID => invalid_octet, :Name => '', :ole_respond_to? => true })) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(87) # ERROR_INVALID_PARAMETER end end it "should raise an error when a valid byte array for SID is unresolvable and its Name does not match" do expect { # S-1-1-1 is a valid SID that will not resolve valid_octet_invalid_user = [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0] subject.ads_to_principal(double('WIN32OLE', { :objectSID => valid_octet_invalid_user, :Name => unknown_name, :ole_respond_to? => true })) }.to raise_error do |error| expect(error).to be_a(Puppet::Error) expect(error.cause.code).to eq(1332) # ERROR_NONE_MAPPED end end it "should return a Principal object even when the SID is unresolvable, as long as the Name matches" do # S-1-1-1 is a valid SID that will not resolve valid_octet_invalid_user = [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0] unresolvable_user = double('WIN32OLE', { :objectSID => valid_octet_invalid_user, :Name => 'S-1-1-1', :ole_respond_to? => true }) principal = subject.ads_to_principal(unresolvable_user) expect(principal).to be_an_instance_of(Puppet::Util::Windows::SID::Principal) expect(principal.account).to eq('S-1-1-1') expect(principal.domain).to eq(nil) expect(principal.domain_account).to eq('S-1-1-1') expect(principal.sid).to eq('S-1-1-1') expect(principal.sid_bytes).to eq(valid_octet_invalid_user) expect(principal.account_type).to eq(:SidTypeUnknown) end it "should return a Puppet::Util::Windows::SID::Principal instance for any valid sid" do system_bytes = [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0] adsuser = double('WIN32OLE', { :objectSID => system_bytes, :Name => 'SYSTEM', :ole_respond_to? => true }) expect(subject.ads_to_principal(adsuser)).to be_an_instance_of(Puppet::Util::Windows::SID::Principal) end it "should properly convert an array of bytes for a well-known non-localized SID, ignoring the Name from the WIN32OLE object" do bytes = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] adsuser = double('WIN32OLE', { :objectSID => bytes, :Name => unknown_name, :ole_respond_to? => true }) converted = subject.ads_to_principal(adsuser) expect(converted).to be_an_instance_of Puppet::Util::Windows::SID::Principal expect(converted.sid_bytes).to eq(bytes) expect(converted.sid).to eq(null_sid) # carefully select a SID here that is not localized on international Windows expect(converted.account).to eq('NULL SID') # garbage name supplied does not carry forward as SID is looked up again expect(converted.account).to_not eq(adsuser.Name) end end context "#sid_to_name" do it "should return nil if given a sid for an account that doesn't exist" do expect(subject.sid_to_name(unknown_sid)).to be_nil end it "should accept a sid" do # choose a value that is not localized, for instance # S-1-5-18 can be NT AUTHORITY\\SYSTEM or AUTORITE NT\\Syst\u00E8me # but NULL SID appears universal expect(subject.sid_to_name(null_sid)).to eq('NULL SID') end end context "#sid_ptr_to_string" do it "should raise if given an invalid sid" do expect { subject.sid_ptr_to_string(nil) }.to raise_error(Puppet::Error, /Invalid SID/) end it "should yield a valid sid pointer" do string = nil subject.string_to_sid_ptr(sid) do |ptr| string = subject.sid_ptr_to_string(ptr) end expect(string).to eq(sid) end end context "#string_to_sid_ptr" do it "should yield sid_ptr" do ptr = nil subject.string_to_sid_ptr(sid) do |p| ptr = p end expect(ptr).not_to be_nil end it "should raise on an invalid sid" do expect { subject.string_to_sid_ptr(invalid_sid) }.to raise_error(Puppet::Error, /Failed to convert string SID/) end end context "#valid_sid?" do it "should return true for a valid SID" do expect(subject.valid_sid?(sid)).to be_truthy end it "should return false for an invalid SID" do expect(subject.valid_sid?(invalid_sid)).to be_falsey end it "should raise if the conversion fails" do expect(subject).to receive(:string_to_sid_ptr).with(sid). and_raise(Puppet::Util::Windows::Error.new("Failed to convert string SID: #{sid}", Puppet::Util::Windows::Error::ERROR_ACCESS_DENIED)) expect { subject.string_to_sid_ptr(sid) {|ptr| } }.to raise_error(Puppet::Util::Windows::Error, /Failed to convert string SID: #{sid}/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/root_certs_spec.rb
spec/unit/util/windows/root_certs_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe "Puppet::Util::Windows::RootCerts", :if => Puppet::Util::Platform.windows? do let(:x509_store) { Puppet::Util::Windows::RootCerts.instance.to_a } it "should return at least one X509 certificate" do expect(x509_store.to_a.size).to be >= 1 end it "should return an X509 certificate with a subject" do x509 = x509_store.first expect(x509.subject.to_utf8).to match(/CN=.*/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/service_spec.rb
spec/unit/util/windows/service_spec.rb
require 'spec_helper' describe "Puppet::Util::Windows::Service", :if => Puppet.features.microsoft_windows? do require 'puppet/util/windows' before(:each) do allow(Puppet::Util::Windows::Error).to receive(:format_error_code) .with(anything) .and_return("fake error!") end def service_state_str(state) Puppet::Util::Windows::Service::SERVICE_STATES[state].to_s end # The following should emulate a successful call to the private function # query_status that returns the value of query_return. This should give # us a way to mock changes in service status. # # Everything else is stubbed, the emulation of the successful call is really # just an expectation of subject::SERVICE_STATUS_PROCESS.new in sequence that # returns the value passed in as a param def expect_successful_status_query_and_return(query_return) expect(subject::SERVICE_STATUS_PROCESS).to receive(:new).and_return(query_return) end def expect_successful_status_queries_and_return(*query_returns) query_returns.each do |query_return| expect_successful_status_query_and_return(query_return) end end # The following should emulate a successful call to the private function # query_config that returns the value of query_return. This should give # us a way to mock changes in service configuration. # # Everything else is stubbed, the emulation of the successful call is really # just an expectation of subject::QUERY_SERVICE_CONFIGW.new in sequence that # returns the value passed in as a param def expect_successful_config_query_and_return(query_return) expect(subject::QUERY_SERVICE_CONFIGW).to receive(:new).and_return(query_return) end def expect_successful_config_query2_and_return(param, query_return) expect(param).to receive(:new).and_return(query_return) end let(:subject) { Puppet::Util::Windows::Service } let(:pointer) { double() } let(:mock_service_name) { double() } let(:service) { double() } let(:scm) { double() } let(:timeout) { 30 } before do allow(subject).to receive(:QueryServiceStatusEx).and_return(1) allow(subject).to receive(:QueryServiceConfigW).and_return(1) allow(subject).to receive(:QueryServiceConfig2W).and_return(1) allow(subject).to receive(:ChangeServiceConfigW).and_return(1) allow(subject).to receive(:ChangeServiceConfig2W).and_return(1) allow(subject).to receive(:OpenSCManagerW).and_return(scm) allow(subject).to receive(:OpenServiceW).and_return(service) allow(subject).to receive(:CloseServiceHandle) allow(subject).to receive(:EnumServicesStatusExW).and_return(1) allow(subject).to receive(:wide_string) allow(subject::SERVICE_STATUS_PROCESS).to receive(:new) allow(subject::QUERY_SERVICE_CONFIGW).to receive(:new) allow(subject::SERVICE_STATUS).to receive(:new).and_return({:dwCurrentState => subject::SERVICE_RUNNING}) allow(FFI).to receive(:errno).and_return(0) allow(FFI::MemoryPointer).to receive(:new).and_yield(pointer) allow(pointer).to receive(:read_dword) allow(pointer).to receive(:write_dword) allow(pointer).to receive(:size) allow(subject).to receive(:sleep) end describe "#exists?" do context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.exists?(mock_service_name) }.to raise_error(Puppet::Error) end end context "when the service cannot be opened" do let(:service) { FFI::Pointer::NULL_HANDLE } it "returns false if it fails to open because the service does not exist" do allow(FFI).to receive(:errno).and_return(Puppet::Util::Windows::Service::ERROR_SERVICE_DOES_NOT_EXIST) expect(subject.exists?(mock_service_name)).to be false end it "raises a puppet error if it fails to open for some other reason" do expect{ subject.exists?(mock_service_name) }.to raise_error(Puppet::Error) end end context "when the service can be opened" do it "returns true" do expect(subject.exists?(mock_service_name)).to be true end end end # This shared example contains the unit tests for the wait_on_pending_state # helper as used by service actions like #start and #stop. Before including # this shared example, be sure to mock out any intermediate calls prior to # the pending transition, and make sure that the post-condition _after_ those # intermediate calls leaves the service in the pending state. Before including # this example in your tests, be sure to define the following variables in a `let` # context: # * action -- The service action shared_examples "a service action waiting on a pending transition" do |pending_state| pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[pending_state].to_s final_state = Puppet::Util::Windows::Service::FINAL_STATES[pending_state] final_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[final_state].to_s it "raises a Puppet::Error if the service query fails" do expect(subject).to receive(:QueryServiceStatusEx).and_return(FFI::WIN32_FALSE) expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end it "raises a Puppet::Error if the service unexpectedly transitions to a state other than #{pending_state_str} or #{final_state_str}" do invalid_state = (subject::SERVICE_STATES.keys - [pending_state, final_state]).first expect_successful_status_query_and_return(dwCurrentState: invalid_state) expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end it "waits for at least 1 second if the wait_hint/10 is < 1 second" do expect_successful_status_queries_and_return( { :dwCurrentState => pending_state, :dwWaitHint => 0, :dwCheckPoint => 1 }, { :dwCurrentState => final_state } ) expect(subject).to receive(:sleep).with(1) subject.send(action, mock_service_name, timeout: timeout) end it "waits for at most 10 seconds if wait_hint/10 is > 10 seconds" do expect_successful_status_queries_and_return( { :dwCurrentState => pending_state, :dwWaitHint => 1000000, :dwCheckPoint => 1 }, { :dwCurrentState => final_state } ) expect(subject).to receive(:sleep).with(10) subject.send(action, mock_service_name, timeout: timeout) end it "does not raise an error if the service makes any progress while transitioning to #{final_state_str}" do expect_successful_status_queries_and_return( # The three "pending_state" statuses simulate the scenario where the service # makes some progress during the transition right when Puppet's about to # time out. { :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 1 }, { :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 1 }, { :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 2 }, { :dwCurrentState => final_state } ) expect { subject.send(action, mock_service_name, timeout: timeout) }.to_not raise_error end it "raises a Puppet::Error if it times out while waiting for the transition to #{final_state_str}" do 31.times do expect_successful_status_query_and_return( dwCurrentState: pending_state, dwWaitHint: 10000, dwCheckPoint: 1 ) end expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end # This shared example contains the unit tests for the transition_service_state # helper, which is the helper that all of our service actions like #start, #stop # delegate to. Including these tests under a shared example lets us include them in each of # those service action's unit tests. Before including this example in your tests, be # sure to define the following variables in a `let` context: # * initial_state -- The initial state of the service prior to performing the state # transition # # * mock_state_transition -- A lambda that mocks the state transition. This should mock # any code in the block that's passed to the # transition_service_state helper # # See the unit tests for the #start method to see how this shared example's # included. # shared_examples "a service action that transitions the service state" do |action, valid_initial_states, pending_state, final_state| valid_initial_states_str = valid_initial_states.map do |state| Puppet::Util::Windows::Service::SERVICE_STATES[state] end.join(', ') pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[pending_state].to_s final_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[final_state].to_s it "noops if the service is already in the #{final_state} state" do expect_successful_status_query_and_return(dwCurrentState: final_state) expect { subject.send(action, mock_service_name, timeout: timeout) }.to_not raise_error end # invalid_initial_states will be empty for the #stop action invalid_initial_states = Puppet::Util::Windows::Service::SERVICE_STATES.keys - valid_initial_states - [final_state] unless invalid_initial_states.empty? it "raises a Puppet::Error if the service's initial state is not one of #{valid_initial_states_str}" do invalid_initial_state = invalid_initial_states.first expect_successful_status_query_and_return(dwCurrentState: invalid_initial_state) expect{ subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end context "when there's a pending transition to the #{final_state} state" do before(:each) do expect_successful_status_query_and_return(dwCurrentState: pending_state) end include_examples "a service action waiting on a pending transition", pending_state do let(:action) { action } end end # If the service action accepts an unsafe pending state as one of the service's # initial states, then we need to test that the action waits for the service to # transition from that unsafe pending state before doing anything else. unsafe_pending_states = valid_initial_states & Puppet::Util::Windows::Service::UNSAFE_PENDING_STATES unless unsafe_pending_states.empty? unsafe_pending_state = unsafe_pending_states.first unsafe_pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[unsafe_pending_state] context "waiting for a service with #{unsafe_pending_state_str} as its initial state" do before(:each) do # This mocks the status query to return the 'final_state' by default. Otherwise, # we will fail the tests in the latter parts of the code where we wait for the # service to finish transitioning to the 'final_state'. allow(subject::SERVICE_STATUS_PROCESS).to receive(:new).and_return(dwCurrentState: final_state) # Set our service's initial state expect_successful_status_query_and_return(dwCurrentState: unsafe_pending_state) mock_state_transition.call end include_examples "a service action waiting on a pending transition", unsafe_pending_state do let(:action) { action } end end end # reads e.g. "waiting for the service to transition to the SERVICE_RUNNING state after executing the 'start' action" # # NOTE: This is really unit testing the wait_on_state_transition helper context "waiting for the service to transition to the #{final_state_str} state after executing the '#{action}' action" do before(:each) do # Set our service's initial state prior to performing the state transition expect_successful_status_query_and_return(dwCurrentState: initial_state) mock_state_transition.call end it "raises a Puppet::Error if the service query fails" do expect(subject).to receive(:QueryServiceStatusEx).and_return(FFI::WIN32_FALSE) expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end it "waits, then queries again until it transitions to #{final_state_str}" do expect_successful_status_queries_and_return( { :dwCurrentState => initial_state }, { :dwCurrentState => initial_state }, { :dwCurrentState => final_state } ) expect(subject).to receive(:sleep).with(1).twice subject.send(action, mock_service_name, timeout: timeout) end context "when it transitions to the #{pending_state_str} state" do before(:each) do expect_successful_status_query_and_return(dwCurrentState: pending_state) end include_examples "a service action waiting on a pending transition", pending_state do let(:action) { action } end end it "raises a Puppet::Error if it times out while waiting for the transition to #{final_state_str}" do 31.times do expect_successful_status_query_and_return(dwCurrentState: initial_state) end expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end end describe "#start" do # rspec will still try to load the tests even though # the :if => Puppet.features.microsoft_windows? filter # is passed-in to the top-level describe block on # non-Windows platforms; it just won't run them. However # on these platforms, the loading will fail because this # test uses a shared example that references variables # from the Windows::Service module when building the unit # tests, which is only available on Windows platforms. # Thus, we add the next here to ensure that rspec does not # attempt to load our test code. This is OK for us to do # because we do not want to run these tests on non-Windows # platforms. next unless Puppet.features.microsoft_windows? context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end context "when the service cannot be opened" do let(:service) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end context "when the service can be opened" do # Can't use rspec's subject here because that # can only be referenced inside an 'it' block. service = Puppet::Util::Windows::Service valid_initial_states = [ service::SERVICE_STOP_PENDING, service::SERVICE_STOPPED, service::SERVICE_START_PENDING ] final_state = service::SERVICE_RUNNING include_examples "a service action that transitions the service state", :start, valid_initial_states, service::SERVICE_START_PENDING, final_state do let(:initial_state) { subject::SERVICE_STOPPED } let(:mock_state_transition) do lambda do allow(subject).to receive(:StartServiceW).and_return(1) end end end it "raises a Puppet::Error if StartServiceW returns false" do expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_STOPPED) expect(subject).to receive(:StartServiceW).and_return(FFI::WIN32_FALSE) expect { subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end it "starts the service" do expect_successful_status_queries_and_return( { dwCurrentState: subject::SERVICE_STOPPED }, { dwCurrentState: subject::SERVICE_RUNNING } ) expect(subject).to receive(:StartServiceW).and_return(1) subject.start(mock_service_name, timeout: timeout) end end end describe "#stop" do next unless Puppet.features.microsoft_windows? context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end context "when the service cannot be opened" do let(:service) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end context "when the service can be opened" do service = Puppet::Util::Windows::Service valid_initial_states = service::SERVICE_STATES.keys - [service::SERVICE_STOPPED] final_state = service::SERVICE_STOPPED include_examples "a service action that transitions the service state", :stop, valid_initial_states, service::SERVICE_STOP_PENDING, final_state do let(:initial_state) { subject::SERVICE_RUNNING } let(:mock_state_transition) do lambda do allow(subject).to receive(:ControlService).and_return(1) end end end it "raises a Puppet::Error if ControlService returns false" do expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_RUNNING) allow(subject).to receive(:ControlService).and_return(FFI::WIN32_FALSE) expect { subject.stop(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end it "stops the service" do expect_successful_status_queries_and_return( { dwCurrentState: subject::SERVICE_RUNNING }, { dwCurrentState: subject::SERVICE_STOPPED } ) expect(subject).to receive(:ControlService).and_return(1) subject.stop(mock_service_name, timeout: timeout) end end end describe "#resume" do next unless Puppet.features.microsoft_windows? context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end context "when the service cannot be opened" do let(:service) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end end context "when the service can be opened" do service = Puppet::Util::Windows::Service valid_initial_states = [ service::SERVICE_PAUSE_PENDING, service::SERVICE_PAUSED, service::SERVICE_CONTINUE_PENDING ] final_state = service::SERVICE_RUNNING include_examples "a service action that transitions the service state", :resume, valid_initial_states, service::SERVICE_CONTINUE_PENDING, final_state do let(:initial_state) { service::SERVICE_PAUSED } let(:mock_state_transition) do lambda do # We need to mock the status query because in the block for #resume, we # wait for the service to enter the SERVICE_PAUSED state prior to # performing the transition (in case it is in SERVICE_PAUSE_PENDING). expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED) allow(subject).to receive(:ControlService).and_return(1) end end end context "waiting for the SERVICE_PAUSE_PENDING => SERVICE_PAUSED transition to finish before resuming it" do before(:each) do # This mocks the status query to return the SERVICE_RUNNING state by default. # Otherwise, we will fail the tests in the latter parts of the code where we # wait for the service to finish transitioning to the 'SERVICE_RUNNING' state. allow(subject::SERVICE_STATUS_PROCESS).to receive(:new).and_return(dwCurrentState: subject::SERVICE_RUNNING) expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSE_PENDING) allow(subject).to receive(:ControlService).and_return(1) end include_examples "a service action waiting on a pending transition", service::SERVICE_PAUSE_PENDING do let(:action) { :resume } end end it "raises a Puppet::Error if ControlService returns false" do expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED) expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED) allow(subject).to receive(:ControlService).and_return(FFI::WIN32_FALSE) expect { subject.resume(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error) end it "resumes the service" do expect_successful_status_queries_and_return( { dwCurrentState: subject::SERVICE_PAUSED }, { dwCurrentState: subject::SERVICE_PAUSED }, { dwCurrentState: subject::SERVICE_RUNNING } ) expect(subject).to receive(:ControlService).and_return(1) subject.resume(mock_service_name, timeout: timeout) end end end describe "#service_state" do context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.service_state(mock_service_name) }.to raise_error(Puppet::Error) end end context "when the service cannot be opened" do let(:service) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.service_state(mock_service_name) }.to raise_error(Puppet::Error) end end context "when the service can be opened" do it "raises Puppet::Error if the result of the query is empty" do expect_successful_status_query_and_return({}) expect{subject.service_state(mock_service_name)}.to raise_error(Puppet::Error) end it "raises Puppet::Error if the result of the query is an unknown state" do expect_successful_status_query_and_return({:dwCurrentState => 999}) expect{subject.service_state(mock_service_name)}.to raise_error(Puppet::Error) end # We need to guard this section explicitly since rspec will always # construct all examples, even if it isn't going to run them. if Puppet.features.microsoft_windows? { :SERVICE_STOPPED => Puppet::Util::Windows::Service::SERVICE_STOPPED, :SERVICE_PAUSED => Puppet::Util::Windows::Service::SERVICE_PAUSED, :SERVICE_STOP_PENDING => Puppet::Util::Windows::Service::SERVICE_STOP_PENDING, :SERVICE_PAUSE_PENDING => Puppet::Util::Windows::Service::SERVICE_PAUSE_PENDING, :SERVICE_RUNNING => Puppet::Util::Windows::Service::SERVICE_RUNNING, :SERVICE_CONTINUE_PENDING => Puppet::Util::Windows::Service::SERVICE_CONTINUE_PENDING, :SERVICE_START_PENDING => Puppet::Util::Windows::Service::SERVICE_START_PENDING, }.each do |state_name, state| it "queries the service and returns #{state_name}" do expect_successful_status_query_and_return({:dwCurrentState => state}) expect(subject.service_state(mock_service_name)).to eq(state_name) end end end end end describe "#service_start_type" do context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error) end end context "when the service cannot be opened" do let(:service) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error) end end context "when the service can be opened" do # We need to guard this section explicitly since rspec will always # construct all examples, even if it isn't going to run them. if Puppet.features.microsoft_windows? { :SERVICE_AUTO_START => Puppet::Util::Windows::Service::SERVICE_AUTO_START, :SERVICE_BOOT_START => Puppet::Util::Windows::Service::SERVICE_BOOT_START, :SERVICE_SYSTEM_START => Puppet::Util::Windows::Service::SERVICE_SYSTEM_START, :SERVICE_DEMAND_START => Puppet::Util::Windows::Service::SERVICE_DEMAND_START, :SERVICE_DISABLED => Puppet::Util::Windows::Service::SERVICE_DISABLED, }.each do |start_type_name, start_type| it "queries the service and returns the service start type #{start_type_name}" do expect_successful_config_query_and_return({:dwStartType => start_type}) if start_type_name == :SERVICE_AUTO_START expect_successful_config_query2_and_return(subject::SERVICE_DELAYED_AUTO_START_INFO, {:fDelayedAutostart => 0}) end expect(subject.service_start_type(mock_service_name)).to eq(start_type_name) end end end it "raises a puppet error if the service query fails" do expect(subject).to receive(:QueryServiceConfigW) expect(subject).to receive(:QueryServiceConfigW).and_return(FFI::WIN32_FALSE) expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error) end end end describe "#set_startup_configuration" do let(:status_checks) { sequence('status_checks') } context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.set_startup_configuration(mock_service_name, options: {startup_type: :SERVICE_DEMAND_START}) }.to raise_error(Puppet::Error) end end context "when the service cannot be opened" do let(:service) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.set_startup_configuration(mock_service_name, options: {startup_type: :SERVICE_DEMAND_START}) }.to raise_error(Puppet::Error) end end context "when the service can be opened" do it "Raises an error on an unsuccessful change" do expect(subject).to receive(:ChangeServiceConfigW).and_return(FFI::WIN32_FALSE) expect{ subject.set_startup_configuration(mock_service_name, options: {startup_type: :SERVICE_DEMAND_START}) }.to raise_error(Puppet::Error) end end end describe "#services" do let(:pointer_sequence) { sequence('pointer_sequence') } context "when the service control manager cannot be opened" do let(:scm) { FFI::Pointer::NULL_HANDLE } it "raises a puppet error" do expect{ subject.services }.to raise_error(Puppet::Error) end end context "when the service control manager is open" do let(:cursor) { [ 'svc1', 'svc2', 'svc3' ] } let(:svc1name_ptr) { double() } let(:svc2name_ptr) { double() } let(:svc3name_ptr) { double() } let(:svc1displayname_ptr) { double() } let(:svc2displayname_ptr) { double() } let(:svc3displayname_ptr) { double() } let(:svc1) { { :lpServiceName => svc1name_ptr, :lpDisplayName => svc1displayname_ptr, :ServiceStatusProcess => 'foo' } } let(:svc2) { { :lpServiceName => svc2name_ptr, :lpDisplayName => svc2displayname_ptr, :ServiceStatusProcess => 'foo' } } let(:svc3) { { :lpServiceName => svc3name_ptr, :lpDisplayName => svc3displayname_ptr, :ServiceStatusProcess => 'foo' } } it "Raises an error if EnumServicesStatusExW fails" do expect(subject).to receive(:EnumServicesStatusExW) expect(subject).to receive(:EnumServicesStatusExW).and_return(FFI::WIN32_FALSE) expect{ subject.services }.to raise_error(Puppet::Error) end it "Reads the buffer using pointer arithmetic to create a hash of service entries" do # the first read_dword is for reading the bytes required, let that return 3 too. # the second read_dword will actually read the number of services returned expect(pointer).to receive(:read_dword).twice.and_return(3) expect(FFI::Pointer).to receive(:new).with(subject::ENUM_SERVICE_STATUS_PROCESSW, pointer).and_return(cursor) expect(subject::ENUM_SERVICE_STATUS_PROCESSW).to receive(:new).with('svc1').and_return(svc1) expect(subject::ENUM_SERVICE_STATUS_PROCESSW).to receive(:new).with('svc2').and_return(svc2) expect(subject::ENUM_SERVICE_STATUS_PROCESSW).to receive(:new).with('svc3').and_return(svc3) expect(svc1name_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('svc1') expect(svc2name_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('svc2') expect(svc3name_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('svc3') expect(svc1displayname_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('service 1') expect(svc2displayname_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('service 2') expect(svc3displayname_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('service 3') expect(subject.services).to eq({ 'svc1' => { :display_name => 'service 1', :service_status_process => 'foo' }, 'svc2' => { :display_name => 'service 2', :service_status_process => 'foo' }, 'svc3' => { :display_name => 'service 3', :service_status_process => 'foo' } }) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/api_types_spec.rb
spec/unit/util/windows/api_types_spec.rb
# encoding: UTF-8 require 'spec_helper' describe "FFI::MemoryPointer", :if => Puppet::Util::Platform.windows? do # use 2 bad bytes at end so we have even number of bytes / characters let(:bad_string) { "hello invalid world".encode(Encoding::UTF_16LE) + "\xDD\xDD".force_encoding(Encoding::UTF_16LE) } let(:bad_string_bytes) { bad_string.bytes.to_a } let(:a_wide_bytes) { "A".encode(Encoding::UTF_16LE).bytes.to_a } let(:b_wide_bytes) { "B".encode(Encoding::UTF_16LE).bytes.to_a } context "read_wide_string" do let (:string) { "foo_bar" } it "should properly roundtrip a given string" do FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr| expect(ptr.read_wide_string(string.length)).to eq(string) end end it "should return a given string in UTF-8" do FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr| read_string = ptr.read_wide_string(string.length) expect(read_string.encoding).to eq(Encoding::UTF_8) end end it "should raise an error and emit a debug message when receiving a string containing invalid bytes in the destination encoding" do Puppet[:log_level] = 'debug' expect { FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, bad_string_bytes) ptr.read_wide_string(bad_string.length) end }.to raise_error(Encoding::InvalidByteSequenceError) expect(@logs.last.message).to eq("Unable to convert value #{bad_string.dump} to encoding UTF-8 due to #<Encoding::InvalidByteSequenceError: \"\\xDD\\xDD\" on UTF-16LE>") end it "should not raise an error when receiving a string containing invalid bytes in the destination encoding, when specifying :invalid => :replace" do FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, bad_string_bytes) read_string = ptr.read_wide_string(bad_string.length, Encoding::UTF_8, false, :invalid => :replace) expect(read_string).to eq("hello invalid world\uFFFD") end end it "raises an IndexError if asked to read more characters than there are bytes allocated" do expect { FFI::MemoryPointer.new(:byte, 1) do |ptr| ptr.read_wide_string(1) # 1 wchar = 2 bytes end }.to raise_error(IndexError, /out of bounds/) end it "raises an IndexError if asked to read a negative number of characters" do expect { FFI::MemoryPointer.new(:byte, 1) do |ptr| ptr.read_wide_string(-1) end }.to raise_error(IndexError, /out of bounds/) end it "returns an empty string if asked to read 0 characters" do FFI::MemoryPointer.new(:byte, 1) do |ptr| expect(ptr.read_wide_string(0)).to eq("") end end it "returns a substring if asked to read fewer characters than are in the byte array" do FFI::MemoryPointer.new(:byte, 4) do |ptr| ptr.write_array_of_uint8("AB".encode('UTF-16LE').bytes.to_a) expect(ptr.read_wide_string(1)).to eq("A") end end it "preserves wide null characters in the string" do FFI::MemoryPointer.new(:byte, 6) do |ptr| ptr.write_array_of_uint8(a_wide_bytes + [0, 0] + b_wide_bytes) expect(ptr.read_wide_string(3)).to eq("A\x00B") end end end context "read_arbitrary_wide_string_up_to" do let (:string) { "foo_bar" } let (:single_null_string) { string + "\x00" } let (:double_null_string) { string + "\x00\x00" } it "should read a short single null terminated string" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to).to eq(string) end end it "should read a short double null terminated string" do FFI::MemoryPointer.from_string_to_wide_string(double_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to(512, :double_null)).to eq(string) end end it "detects trailing single null wchar" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr).to receive(:read_wide_string).with(string.length, anything, anything, anything).and_call_original expect(ptr.read_arbitrary_wide_string_up_to).to eq(string) end end it "detects trailing double null wchar" do FFI::MemoryPointer.from_string_to_wide_string(double_null_string) do |ptr| expect(ptr).to receive(:read_wide_string).with(string.length, anything, anything, anything).and_call_original expect(ptr.read_arbitrary_wide_string_up_to(512, :double_null)).to eq(string) end end it "should raises an IndexError if max_length is negative" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect { ptr.read_arbitrary_wide_string_up_to(-1) }.to raise_error(IndexError, /out of bounds/) end end it "should return an empty string when the max_length is 0" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to(0)).to eq("") end end it "should return a string of max_length characters when specified" do FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr| expect(ptr.read_arbitrary_wide_string_up_to(3)).to eq(string[0..2]) end end it "should return wide strings in UTF-8" do FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr| read_string = ptr.read_arbitrary_wide_string_up_to expect(read_string.encoding).to eq(Encoding::UTF_8) end end it "should not raise an error when receiving a string containing invalid bytes in the destination encoding, when specifying :invalid => :replace" do FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, bad_string_bytes) read_string = ptr.read_arbitrary_wide_string_up_to(ptr.size / 2, :single_null, :invalid => :replace) expect(read_string).to eq("hello invalid world\uFFFD") end end it "should raise an IndexError if there isn't a null terminator" do # This only works when using a memory pointer with a known number of cells # and size per cell, but not arbitrary Pointers FFI::MemoryPointer.new(:wchar, 1) do |ptr| ptr.write_array_of_uint8(a_wide_bytes) expect { ptr.read_arbitrary_wide_string_up_to(42) }.to raise_error(IndexError, /out of bounds/) end end it "should raise an IndexError if there isn't a double null terminator" do # This only works when using a memory pointer with a known number of cells # and size per cell, but not arbitrary Pointers FFI::MemoryPointer.new(:wchar, 1) do |ptr| ptr.write_array_of_uint8(a_wide_bytes) expect { ptr.read_arbitrary_wide_string_up_to(42, :double_null) }.to raise_error(IndexError, /out of bounds/) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/access_control_entry_spec.rb
spec/unit/util/windows/access_control_entry_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe "Puppet::Util::Windows::AccessControlEntry", :if => Puppet::Util::Platform.windows? do let(:klass) { Puppet::Util::Windows::AccessControlEntry } let(:sid) { 'S-1-5-18' } let(:mask) { Puppet::Util::Windows::File::FILE_ALL_ACCESS } it "creates an access allowed ace" do ace = klass.new(sid, mask) expect(ace.type).to eq(klass::ACCESS_ALLOWED_ACE_TYPE) end it "creates an access denied ace" do ace = klass.new(sid, mask, 0, klass::ACCESS_DENIED_ACE_TYPE) expect(ace.type).to eq(klass::ACCESS_DENIED_ACE_TYPE) end it "creates a non-inherited ace by default" do ace = klass.new(sid, mask) expect(ace).not_to be_inherited end it "creates an inherited ace" do ace = klass.new(sid, mask, klass::INHERITED_ACE) expect(ace).to be_inherited end it "creates a non-inherit-only ace by default" do ace = klass.new(sid, mask) expect(ace).not_to be_inherit_only end it "creates an inherit-only ace" do ace = klass.new(sid, mask, klass::INHERIT_ONLY_ACE) expect(ace).to be_inherit_only end context "when comparing aces" do let(:ace1) { klass.new(sid, mask, klass::INHERIT_ONLY_ACE, klass::ACCESS_DENIED_ACE_TYPE) } let(:ace2) { klass.new(sid, mask, klass::INHERIT_ONLY_ACE, klass::ACCESS_DENIED_ACE_TYPE) } it "returns true if different objects have the same set of values" do expect(ace1).to eq(ace2) end it "returns false if different objects have different sets of values" do ace = klass.new(sid, mask) expect(ace).not_to eq(ace1) end it "returns true when testing if two objects are eql?" do ace1.eql?(ace2) end it "returns false when comparing object identity" do expect(ace1).not_to be_equal(ace2) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/eventlog_spec.rb
spec/unit/util/windows/eventlog_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe Puppet::Util::Windows::EventLog, :if => Puppet::Util::Platform.windows? do before(:each) { @event_log = Puppet::Util::Windows::EventLog.new } after(:each) { @event_log.close } describe "class constants" do it "should define NULL_HANDLE as 0" do expect(Puppet::Util::Windows::EventLog::NULL_HANDLE).to eq(0) end it "should define WIN32_FALSE as 0" do expect(Puppet::Util::Windows::EventLog::WIN32_FALSE).to eq(0) end end describe "self.open" do it "sets a handle to the event log" do default_name = Puppet::Util::Windows::String.wide_string('Puppet') # return nil explicitly just to reinforce that we're not leaking eventlog handle expect_any_instance_of(Puppet::Util::Windows::EventLog).to receive(:RegisterEventSourceW).with(anything, default_name).and_return(nil) Puppet::Util::Windows::EventLog.new end context "when it fails to open the event log" do before do # RegisterEventSourceW will return NULL on failure # Stubbing prevents leaking eventlog handle allow_any_instance_of(Puppet::Util::Windows::EventLog).to receive(:RegisterEventSourceW).and_return(Puppet::Util::Windows::EventLog::NULL_HANDLE) end it "raises an exception warning that the event log failed to open" do expect { Puppet::Util::Windows::EventLog.open('foo') }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError, /failed to open Windows eventlog/) end it "passes the exit code to the exception constructor" do fake_error = Puppet::Util::Windows::EventLog::EventLogError.new('foo', 87) allow(FFI).to receive(:errno).and_return(87) # All we're testing here is that the constructor actually receives the exit code from FFI.errno (87) # We do so because `expect to...raise_error` doesn't support multiple parameter match arguments # We return fake_error just because `raise` expects an exception class expect(Puppet::Util::Windows::EventLog::EventLogError).to receive(:new).with(/failed to open Windows eventlog/, 87).and_return(fake_error) expect { Puppet::Util::Windows::EventLog.open('foo') }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError) end end end describe "#close" do it "closes the handle to the event log" do @handle = "12345" allow_any_instance_of(Puppet::Util::Windows::EventLog).to receive(:RegisterEventSourceW).and_return(@handle) event_log = Puppet::Util::Windows::EventLog.new expect(event_log).to receive(:DeregisterEventSource).with(@handle).and_return(1) event_log.close end end describe "#report_event" do it "raises an exception if the message passed is not a string" do expect { @event_log.report_event(:data => 123, :event_type => nil, :event_id => nil) }.to raise_error(ArgumentError, /data must be a string/) end context "when an event report fails" do before do # ReportEventW returns 0 on failure, which is mapped to WIN32_FALSE allow(@event_log).to receive(:ReportEventW).and_return(Puppet::Util::Windows::EventLog::WIN32_FALSE) end it "raises an exception warning that the event report failed" do expect { @event_log.report_event(:data => 'foo', :event_type => Puppet::Util::Windows::EventLog::EVENTLOG_ERROR_TYPE, :event_id => 0x03) }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError, /failed to report event/) end it "passes the exit code to the exception constructor" do fake_error = Puppet::Util::Windows::EventLog::EventLogError.new('foo', 5) allow(FFI).to receive(:errno).and_return(5) # All we're testing here is that the constructor actually receives the exit code from FFI.errno (5) # We do so because `expect to...raise_error` doesn't support multiple parameter match arguments # We return fake_error just because `raise` expects an exception class expect(Puppet::Util::Windows::EventLog::EventLogError).to receive(:new).with(/failed to report event/, 5).and_return(fake_error) expect { @event_log.report_event(:data => 'foo', :event_type => Puppet::Util::Windows::EventLog::EVENTLOG_ERROR_TYPE, :event_id => 0x03) }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError) end end end describe "self.to_native" do it "raises an exception if the log level is not supported" do expect { Puppet::Util::Windows::EventLog.to_native(:foo) }.to raise_error(ArgumentError) end # This is effectively duplicating the data assigned to the constants in # Puppet::Util::Windows::EventLog but since these are public constants we # ensure their values don't change lightly. log_levels_to_type_and_id = { :debug => [0x0004, 0x01], :info => [0x0004, 0x01], :notice => [0x0004, 0x01], :warning => [0x0002, 0x02], :err => [0x0001, 0x03], :alert => [0x0001, 0x03], :emerg => [0x0001, 0x03], :crit => [0x0001, 0x03], } shared_examples_for "#to_native" do |level| it "should return the correct INFORMATION_TYPE and ID" do result = Puppet::Util::Windows::EventLog.to_native(level) expect(result).to eq(log_levels_to_type_and_id[level]) end end log_levels_to_type_and_id.each_key do |level| describe "logging at #{level}" do it_should_behave_like "#to_native", level end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows/security_descriptor_spec.rb
spec/unit/util/windows/security_descriptor_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe "Puppet::Util::Windows::SecurityDescriptor", :if => Puppet::Util::Platform.windows? do let(:system_sid) { Puppet::Util::Windows::SID::LocalSystem } let(:admins_sid) { Puppet::Util::Windows::SID::BuiltinAdministrators } let(:group_sid) { Puppet::Util::Windows::SID::Nobody } let(:new_sid) { 'S-1-5-32-500-1-2-3' } def empty_dacl Puppet::Util::Windows::AccessControlList.new end def system_ace_dacl dacl = Puppet::Util::Windows::AccessControlList.new dacl.allow(system_sid, 0x1) dacl end context "owner" do it "changes the owner" do sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl) sd.owner = new_sid expect(sd.owner).to eq(new_sid) end it "performs a noop if the new owner is the same as the old one" do dacl = system_ace_dacl sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, dacl) sd.owner = sd.owner expect(sd.dacl.object_id).to eq(dacl.object_id) end it "prepends SYSTEM when security descriptor owner is no longer SYSTEM" do sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl) sd.owner = new_sid aces = sd.dacl.to_a expect(aces.size).to eq(2) expect(aces[0].sid).to eq(system_sid) expect(aces[1].sid).to eq(new_sid) end it "does not prepend SYSTEM when DACL already contains inherited SYSTEM ace" do sd = Puppet::Util::Windows::SecurityDescriptor.new(admins_sid, system_sid, empty_dacl) sd.dacl.allow(admins_sid, 0x1) sd.dacl.allow(system_sid, 0x1, Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE) sd.owner = new_sid aces = sd.dacl.to_a expect(aces.size).to eq(2) expect(aces[0].sid).to eq(new_sid) end it "does not prepend SYSTEM when security descriptor owner wasn't SYSTEM" do sd = Puppet::Util::Windows::SecurityDescriptor.new(group_sid, group_sid, empty_dacl) sd.dacl.allow(group_sid, 0x1) sd.owner = new_sid aces = sd.dacl.to_a expect(aces.size).to eq(1) expect(aces[0].sid).to eq(new_sid) end end context "group" do it "changes the group" do sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl) sd.group = new_sid expect(sd.group).to eq(new_sid) end it "performs a noop if the new group is the same as the old one" do dacl = system_ace_dacl sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, dacl) sd.group = sd.group expect(sd.dacl.object_id).to eq(dacl.object_id) end it "prepends SYSTEM when security descriptor group is no longer SYSTEM" do sd = Puppet::Util::Windows::SecurityDescriptor.new(new_sid, system_sid, system_ace_dacl) sd.group = new_sid aces = sd.dacl.to_a expect(aces.size).to eq(2) expect(aces[0].sid).to eq(system_sid) expect(aces[1].sid).to eq(new_sid) end it "does not prepend SYSTEM when DACL already contains inherited SYSTEM ace" do sd = Puppet::Util::Windows::SecurityDescriptor.new(admins_sid, admins_sid, empty_dacl) sd.dacl.allow(admins_sid, 0x1) sd.dacl.allow(system_sid, 0x1, Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE) sd.group = new_sid aces = sd.dacl.to_a expect(aces.size).to eq(2) expect(aces[0].sid).to eq(new_sid) end it "does not prepend SYSTEM when security descriptor group wasn't SYSTEM" do sd = Puppet::Util::Windows::SecurityDescriptor.new(group_sid, group_sid, empty_dacl) sd.dacl.allow(group_sid, 0x1) sd.group = new_sid aces = sd.dacl.to_a expect(aces.size).to eq(1) expect(aces[0].sid).to eq(new_sid) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/package/version/pip_spec.rb
spec/unit/util/package/version/pip_spec.rb
require 'spec_helper' require 'puppet/util/package/version/pip' describe Puppet::Util::Package::Version::Pip do describe "initialization" do shared_examples_for 'a valid version' do |input_version, output = input_version| [input_version, input_version.swapcase].each do |input| it "transforms #{input} back to string(#{output}) succesfully" do version = described_class.parse(input) expect(version.to_s).to eq(output) end end describe "comparison" do version = described_class.parse(input_version) # rubocop:disable UselessComparison it "#{input_version} shouldn't be lesser than itself" do expect(version < version).to eq(false) end it "#{input_version} shouldn't be greater than itself" do expect(version > version).to eq(false) end it "#{input_version} shouldn't be equal with itself" do expect(version != version).to eq(false) end it "#{input_version} should be equal to itself" do expect(version == version).to eq(true) end end end shared_examples_for 'an invalid version' do |invalid_input| [invalid_input, invalid_input.swapcase].each do |input| it "should not be able to transform #{invalid_input} to string" do expect{ described_class.parse(input) }.to raise_error(described_class::ValidationFailure) end end describe "comparison" do valid_version = described_class.parse("1.0") it "should raise error when checking if #{invalid_input} is lesser than a valid version" do expect{ valid_version < invalid_input }.to raise_error(described_class::ValidationFailure) end it "should raise error when checking if #{invalid_input} is greater than a valid version" do expect{ valid_version > invalid_input }.to raise_error(described_class::ValidationFailure) end it "should raise error when checking if #{invalid_input} is greater or equal than a valid version" do expect{ valid_version >= invalid_input }.to raise_error(described_class::ValidationFailure) end it "should raise error when checking if #{invalid_input} is lesser or equal than a valid version" do expect{ valid_version <= invalid_input }.to raise_error(described_class::ValidationFailure) end end end describe "when only release segment is present in provided version" do context "should work with any number of integer elements" do context "when it has 1 element" do it_should_behave_like 'a valid version', "1" end context "when it has 2 elements" do it_should_behave_like 'a valid version', "1.1" end context "when it has 3 elements" do it_should_behave_like 'a valid version', "1.1.1" end context "when it has 4 elements" do it_should_behave_like 'a valid version', "1.1.1.1" end context "when it has 10 elements" do it_should_behave_like 'a valid version', "1.1.1.1.1.1.1.1.1.1" end end describe "should work with elements which are zero" do context "when it ends with 1 zero" do it_should_behave_like 'a valid version', "1.0" end context "when it ends with 2 zeros" do it_should_behave_like 'a valid version', "1.0.0" end context "when it ends with 3 zeros" do it_should_behave_like 'a valid version', "1.0.0.0" end context "when it starts with 1 zero" do it_should_behave_like 'a valid version', "0.1" end context "when it starts with 2 zeros" do it_should_behave_like 'a valid version', "0.0.1" end context "when it starts with 3 zeros" do it_should_behave_like 'a valid version', "0.0.0.1" end context "when it is just a zero" do it_should_behave_like 'a valid version', "0" end context "when it is full of just zeros" do it_should_behave_like 'a valid version', "0.0.0" end end describe "should work with elements containing multiple digits" do context "when it has two digit elements" do it_should_behave_like 'a valid version', "1.10.1" end context "when it has three digit elements" do it_should_behave_like 'a valid version', "1.101.1.11" end context "when it has four digit elements" do it_should_behave_like 'a valid version', "2019.0.11" end context "when it has a numerical element starting with zero" do # the zero will dissapear it_should_behave_like 'a valid version', "1.09.10", "1.9.10" end context "when it starts with multiple zeros" do # the zeros will dissapear it_should_behave_like 'a valid version', "0010.0000.0011", "10.0.11" end end context "should fail because of misplaced letters" do context "when it starts with letters" do it_should_behave_like 'an invalid version', "d.2" it_should_behave_like 'an invalid version', "ee.2" end context "when it has only letters" do it_should_behave_like 'an invalid version', "d.c" it_should_behave_like 'an invalid version', "dd.c" end end end describe "when the epoch segment is present in provided version" do context "should work when epoch is an integer" do context "when epoch has 1 digit" do it_should_behave_like 'a valid version', "1!1.0.0" end context "when epoch has 2 digits" do it_should_behave_like 'a valid version', "10!1.0.0" end context "when epoch is zero" do # versions without epoch specified are considered to have epoch 0 # it is accepted as input but it should be ignored at output it_should_behave_like 'a valid version', "0!1.0.0", "1.0.0" end end context "should fail when epoch contains letters" do context "when epoch starts with a letter" do it_should_behave_like 'an invalid version', "a9!1.0.0" end context "when epoch ends with a letter" do it_should_behave_like 'an invalid version', "9a!1.0.0" end end end describe "when the pre-release segment is present in provided version" do context "when pre-release contains the letter a" do it_should_behave_like 'a valid version', "1.0a", "1.0a0" it_should_behave_like 'a valid version', "1.0a0" end context "when pre-release contains the letter b" do it_should_behave_like 'a valid version', "1.0b", "1.0b0" it_should_behave_like 'a valid version', "1.0b0" end context "when pre-release contains the letter c" do it_should_behave_like 'a valid version', "1.0c", "1.0rc0" it_should_behave_like 'a valid version', "1.0c0", "1.0rc0" end context "when pre-release contains the string alpha" do it_should_behave_like 'a valid version', "1.0alpha", "1.0a0" it_should_behave_like 'a valid version', "1.0alpha0", "1.0a0" end context "when pre-release contains the string beta" do it_should_behave_like 'a valid version', "1.0beta", "1.0b0" it_should_behave_like 'a valid version', "1.0beta0", "1.0b0" end context "when pre-release contains the string rc" do it_should_behave_like 'a valid version', "1.0rc", "1.0rc0" it_should_behave_like 'a valid version', "1.0rc0", "1.0rc0" end context "when pre-release contains the string pre" do it_should_behave_like 'a valid version', "1.0pre", "1.0rc0" it_should_behave_like 'a valid version', "1.0pre0", "1.0rc0" end context "when pre-release contains the string preview" do it_should_behave_like 'a valid version', "1.0preview", "1.0rc0" it_should_behave_like 'a valid version', "1.0preview0", "1.0rc0" end context "when pre-release contains multiple zeros at the beginning" do it_should_behave_like 'a valid version', "1.0.beta.00", "1.0b0" it_should_behave_like 'a valid version', "1.0.beta.002", "1.0b2" end context "when pre-release elements are separated by dots" do it_should_behave_like 'a valid version', "1.0.alpha", "1.0a0" it_should_behave_like 'a valid version', "1.0.alpha.0", "1.0a0" it_should_behave_like 'a valid version', "1.0.alpha.2", "1.0a2" end context "when pre-release elements are separated by dashes" do it_should_behave_like 'a valid version', "1.0-alpha", "1.0a0" it_should_behave_like 'a valid version', "1.0-alpha-0", "1.0a0" it_should_behave_like 'a valid version', "1.0-alpha-2", "1.0a2" end context "when pre-release elements are separated by underscores" do it_should_behave_like 'a valid version', "1.0_alpha", "1.0a0" it_should_behave_like 'a valid version', "1.0_alpha_0", "1.0a0" it_should_behave_like 'a valid version', "1.0_alpha_2", "1.0a2" end context "when pre-release elements are separated by mixed symbols" do it_should_behave_like 'a valid version', "1.0-alpha_5", "1.0a5" it_should_behave_like 'a valid version', "1.0-alpha.5", "1.0a5" it_should_behave_like 'a valid version', "1.0_alpha-5", "1.0a5" it_should_behave_like 'a valid version', "1.0_alpha.5", "1.0a5" it_should_behave_like 'a valid version', "1.0.alpha-5", "1.0a5" it_should_behave_like 'a valid version', "1.0.alpha_5", "1.0a5" end end describe "when the post-release segment is present in provided version" do context "when post-release is just an integer" do it_should_behave_like 'a valid version', "1.0-9", "1.0.post9" it_should_behave_like 'a valid version', "1.0-10", "1.0.post10" end context "when post-release is just an integer and starts with zero" do it_should_behave_like 'a valid version', "1.0-09", "1.0.post9" it_should_behave_like 'a valid version', "1.0-009", "1.0.post9" end context "when post-release contains the string post" do it_should_behave_like 'a valid version', "1.0post", "1.0.post0" it_should_behave_like 'a valid version', "1.0post0", "1.0.post0" it_should_behave_like 'a valid version', "1.0post1", "1.0.post1" it_should_behave_like 'an invalid version', "1.0-0.post1" end context "when post-release contains the string rev" do it_should_behave_like 'a valid version', "1.0rev", "1.0.post0" it_should_behave_like 'a valid version', "1.0rev0", "1.0.post0" it_should_behave_like 'a valid version', "1.0rev1", "1.0.post1" it_should_behave_like 'an invalid version', "1.0-0.rev1" end context "when post-release contains the letter r" do it_should_behave_like 'a valid version', "1.0r", "1.0.post0" it_should_behave_like 'a valid version', "1.0r0", "1.0.post0" it_should_behave_like 'a valid version', "1.0r1", "1.0.post1" it_should_behave_like 'an invalid version', "1.0-0.r1" end context "when post-release elements are separated by dashes" do it_should_behave_like 'a valid version', "1.0-post-22", "1.0.post22" it_should_behave_like 'a valid version', "1.0-rev-22", "1.0.post22" it_should_behave_like 'a valid version', "1.0-r-22", "1.0.post22" end context "when post-release elements are separated by underscores" do it_should_behave_like 'a valid version', "1.0_post_22", "1.0.post22" it_should_behave_like 'a valid version', "1.0_rev_22", "1.0.post22" it_should_behave_like 'a valid version', "1.0_r_22", "1.0.post22" end context "when post-release elements are separated by dots" do it_should_behave_like 'a valid version', "1.0.post.22", "1.0.post22" it_should_behave_like 'a valid version', "1.0.rev.22", "1.0.post22" it_should_behave_like 'a valid version', "1.0.r.22", "1.0.post22" end context "when post-release elements are separated by mixed symbols" do it_should_behave_like 'a valid version', "1.0-r_5", "1.0.post5" it_should_behave_like 'a valid version', "1.0-r.5", "1.0.post5" it_should_behave_like 'a valid version', "1.0_r-5", "1.0.post5" it_should_behave_like 'a valid version', "1.0_r.5", "1.0.post5" it_should_behave_like 'a valid version', "1.0.r-5", "1.0.post5" it_should_behave_like 'a valid version', "1.0.r_5", "1.0.post5" end end describe "when the dev release segment is present in provided version" do context "when dev release is only the keyword dev" do it_should_behave_like 'a valid version', "1.0dev", "1.0.dev0" it_should_behave_like 'a valid version', "1.0-dev", "1.0.dev0" it_should_behave_like 'a valid version', "1.0_dev", "1.0.dev0" it_should_behave_like 'a valid version', "1.0.dev", "1.0.dev0" end context "when dev release contains the keyword dev and a number" do it_should_behave_like 'a valid version', "1.0dev2", "1.0.dev2" it_should_behave_like 'a valid version', "1.0-dev33", "1.0.dev33" it_should_behave_like 'a valid version', "1.0.dev11", "1.0.dev11" it_should_behave_like 'a valid version', "1.0_dev101", "1.0.dev101" end context "when dev release's number element starts with 0" do it_should_behave_like 'a valid version', "1.0dev02", "1.0.dev2" it_should_behave_like 'a valid version', "1.0-dev033", "1.0.dev33" it_should_behave_like 'a valid version', "1.0_dev0101", "1.0.dev101" it_should_behave_like 'a valid version', "1.0.dev00011", "1.0.dev11" end context "when dev release elements are separated by dashes" do it_should_behave_like 'a valid version', "1.0-dev", "1.0.dev0" it_should_behave_like 'a valid version', "1.0-dev-2", "1.0.dev2" it_should_behave_like 'a valid version', "1.0-dev-22", "1.0.dev22" end context "when dev release elements are separated by underscores" do it_should_behave_like 'a valid version', "1.0_dev", "1.0.dev0" it_should_behave_like 'a valid version', "1.0_dev_2", "1.0.dev2" it_should_behave_like 'a valid version', "1.0_dev_22", "1.0.dev22" end context "when dev release elements are separated by dots" do it_should_behave_like 'a valid version', "1.0.dev", "1.0.dev0" it_should_behave_like 'a valid version', "1.0.dev.2", "1.0.dev2" it_should_behave_like 'a valid version', "1.0.dev.22", "1.0.dev22" end context "when dev release elements are separated by mixed symbols" do it_should_behave_like 'a valid version', "1.0-dev_5", "1.0.dev5" it_should_behave_like 'a valid version', "1.0-dev.5", "1.0.dev5" it_should_behave_like 'a valid version', "1.0_dev-5", "1.0.dev5" it_should_behave_like 'a valid version', "1.0_dev.5", "1.0.dev5" it_should_behave_like 'a valid version', "1.0.dev-5", "1.0.dev5" it_should_behave_like 'a valid version', "1.0.dev_5", "1.0.dev5" end end describe "when the local version segment is present in provided version" do it_should_behave_like 'an invalid version', "1.0+" context "when local version is just letters" do it_should_behave_like 'a valid version', "1.0+local" it_should_behave_like 'a valid version', "1.0+Local", "1.0+local" end context "when local version contains numbers" do it_should_behave_like 'a valid version', "1.0+10" it_should_behave_like 'a valid version', "1.0+01", "1.0+1" it_should_behave_like 'a valid version', "1.0+01L", "1.0+01l" it_should_behave_like 'a valid version', "1.0+L101L", "1.0+l101l" end context "when local version contains multiple elements" do it_should_behave_like 'a valid version', "1.0+10.local" it_should_behave_like 'a valid version', "1.0+abc.def.ghi" it_should_behave_like 'a valid version', "1.0+01.abc", "1.0+1.abc" it_should_behave_like 'a valid version', "1.0+01L.0001", "1.0+01l.1" it_should_behave_like 'a valid version', "1.0+L101L.local", "1.0+l101l.local" it_should_behave_like 'a valid version', "1.0+dash-undrsc_dot.5", "1.0+dash.undrsc.dot.5" end end end describe "comparison of versions" do # This array must remain sorted (smallest to highest version). versions = [ "0.1", "0.10", "0.10.1", "0.10.1.0.1", "1.0.dev456", "1.0a1", "1.0a2.dev456", "1.0a12.dev456", "1.0a12", "1.0b1.dev456", "1.0b2", "1.0b2.post345.dev456", "1.0b2.post345", "1.0b2-346", "1.0c1.dev456", "1.0c1", "1.0rc2", "1.0c3", "1.0", "1.0.post456.dev34", "1.0.post456", "1.1.dev1", "1.2", "1.2+123abc", "1.2+123abc456", "1.2+abc", "1.2+abc123", "1.2+abc123-def2", "1.2+abc123-def2-0", "1.2+abc123def", "1.2+1234.abc", "1.2+123456", "1.2.r32+123456", "1.2.rev33+123456", "1!1.0b2.post345.dev456", "1!1.0", "1!1.0.post456.dev34", "1!1.0.post456", "1!1.2.rev33+123456", "2!2.3.4.alpha5.rev6.dev7+abc89" ] it "should find versions list to be already sorted" do sorted_versions = versions.sort do |x,y| described_class.compare(x, y) end expect(versions).to eq(sorted_versions) end versions.combination(2).to_a.each do |version_pair| lower_version = described_class.parse(version_pair.first) greater_version = described_class.parse(version_pair.last) it "#{lower_version} should be equal to #{lower_version}" do expect(lower_version == lower_version).to eq(true) end it "#{lower_version} should not be equal to #{greater_version}" do expect(lower_version != greater_version).to eq(true) end it "#{lower_version} should be lower than #{greater_version}" do expect(lower_version < greater_version).to eq(true) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/package/version/debian_spec.rb
spec/unit/util/package/version/debian_spec.rb
require 'spec_helper' require 'puppet/util/package/version/debian' describe Puppet::Util::Package::Version::Debian do context "when creating new version should fail" do it "if is parsing symbols" do expect { described_class.parse(:absent) }.to raise_error(described_class::ValidationFailure) end end context "when creating new version" do it "is parsing basic version" do v = described_class.parse('1:20191210.1-0ubuntu0.19.04.2') expect(v.epoch).to eql(1) expect(v.upstream_version).to eql('20191210.1') expect(v.debian_revision).to eql('0ubuntu0.19.04.2') end it "is parsing no epoch basic version" do v = described_class.parse('20191210.1-0ubuntu0.19.04.2') expect(v.epoch).to eql(0) expect(v.upstream_version).to eql('20191210.1') expect(v.debian_revision).to eql('0ubuntu0.19.04.2') end it "is parsing no debian revision basic version" do v = described_class.parse('2.42.1+19.04') expect(v.epoch).to eql(0) expect(v.upstream_version).to eql('2.42.1+19.04') expect(v.debian_revision).to eql(nil) end it "is parsing no epoch complex version" do v = described_class.parse('3.32.2+git20190711-2ubuntu1~19.04.1') expect(v.epoch).to eql(0) expect(v.upstream_version).to eql('3.32.2+git20190711') expect(v.debian_revision).to eql('2ubuntu1~19.04.1') end it "is parsing even more complex version" do v = described_class.parse('5:1.0.0+git-20190109.133f4c4-0ubuntu2') expect(v.epoch).to eql(5) expect(v.upstream_version).to eql('1.0.0+git-20190109.133f4c4') expect(v.debian_revision).to eql('0ubuntu2') end end context "when comparing two versions" do it "epoch has precedence" do first = described_class.parse('9:99-99') second = described_class.parse('10:01-01') expect(first < second).to eql(true) end it "handles equals letters-only versions" do lower = described_class.parse('abd-def') higher = described_class.parse('abd-def') expect(lower == higher).to eql(true) end it "shorter version is smaller" do lower = described_class.parse('abd-de') higher = described_class.parse('abd-def') expect(lower < higher).to eql(true) end it "shorter version is smaller even with digits" do lower = described_class.parse('a1b2d-d3e') higher = described_class.parse('a1b2d-d3ef') expect(lower < higher).to eql(true) end it "shorter version is smaller when number is less" do lower = described_class.parse('a1b2d-d9') higher = described_class.parse('a1b2d-d13') expect(lower < higher).to eql(true) end it "handles ~ version" do lower = described_class.parse('a1b2d-d10~') higher = described_class.parse('a1b2d-d10') expect(lower < higher).to eql(true) end it "handles letters versus -" do lower = described_class.parse('a1b2d-d1a') higher = described_class.parse('a1b2d-d1-') expect(lower < higher).to eql(true) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/package/version/rpm_spec.rb
spec/unit/util/package/version/rpm_spec.rb
require 'spec_helper' require 'puppet/util/package/version/rpm' describe Puppet::Util::Package::Version::Rpm do context "when parsing an invalid version" do it "raises ArgumentError" do expect { described_class.parse(:absent)}.to raise_error(ArgumentError) end end context "when creating new version" do it "is parsing basic version" do v = described_class.parse('1:2.8.8-1.el6') expect([v.epoch, v.version, v.release, v.arch ]).to eq(['1', '2.8.8', '1.el6' , nil]) end it "is parsing no epoch basic version" do v = described_class.parse('2.8.8-1.el6') expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '2.8.8', '1.el6', nil]) end it "is parsing no epoch basic short version" do v = described_class.parse('7.15-8.fc29') expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '7.15', '8.fc29', nil]) end it "is parsing no epoch and no release basic version" do v = described_class.parse('2.8.8') expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '2.8.8', nil, nil]) end it "is parsing no epoch complex version" do v = described_class.parse('1.4-0.24.20120830CVS.fc31') expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '1.4', '0.24.20120830CVS.fc31', nil]) end end context "when comparing two versions" do context 'with invalid version' do it 'raises ArgumentError' do version = described_class.parse('0:1.5.3-3.el6') invalid = 'invalid' expect { version < invalid }.to \ raise_error(ArgumentError, 'Cannot compare, as invalid is not a Rpm Version') end end context 'with valid versions' do it "epoch has precedence" do lower = described_class.parse('0:1.5.3-3.el6') higher = described_class.parse('1:1.7.0-15.fc29') expect(lower).to be < higher end it 'handles no epoch as 0 epoch' do lower = described_class.parse('1.5.3-3.el6') higher = described_class.parse('1:1.7.0-15.fc29') expect(lower).to be < higher end it "handles equals letters-only versions" do first = described_class.parse('abd-def') second = described_class.parse('abd-def') expect(first).to eq(second) end it "shorter version is smaller letters-only versions" do lower = described_class.parse('ab') higher = described_class.parse('abd') expect(lower).to be < higher end it "shorter version is smaller even with digits" do lower = described_class.parse('1.7') higher = described_class.parse('1.7.0') expect(lower).to be < higher end it "shorter version is smaller when number is less" do lower = described_class.parse('1.7.0') higher = described_class.parse('1.7.1') expect(lower).to be < higher end it "shorter release is smaller " do lower = described_class.parse('1.7.0-11.fc26') higher = described_class.parse('1.7.0-11.fc27') expect(lower).to be < higher end it "release letters are smaller letters-only" do lower = described_class.parse('1.7.0-abc') higher = described_class.parse('1.7.0-abd') expect(lower).to be < higher end it "shorter release is smaller" do lower = described_class.parse('1.7.0-11.fc2') higher = described_class.parse('1.7.0-11.fc17') expect(lower).to be < higher end it "handles equal release" do first = described_class.parse('1.7.0-11.fc27') second = described_class.parse('1.7.0-11.fc27') expect(first).to eq(second) end end context 'when one has no epoch' do it 'handles no epoch as zero' do version1 = described_class.parse('1:1.2') version2 = described_class.parse('1.4') expect(version1).to be > version2 expect(version2).to be < version1 end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/package/version/range_spec.rb
spec/unit/util/package/version/range_spec.rb
require 'spec_helper' require 'puppet/util/package/version/range' class IntegerVersion class ValidationFailure < ArgumentError; end include Comparable REGEX_FULL = '(\d+)'.freeze REGEX_FULL_RX = /\A#{REGEX_FULL}\Z/.freeze def self.parse(ver) match, version = *ver.match(REGEX_FULL_RX) raise ValidationFailure, "Unable to parse '#{ver}' as a version identifier" unless match new(version).freeze end attr_reader :version def initialize(version) @version = version.to_i end def <=>(other) @version <=> other.version end end describe Puppet::Util::Package::Version::Range do context 'when creating new version range' do it 'should raise unless String is passed' do expect { Puppet::Util::Package::Version::Range.parse(:abc, IntegerVersion) }.to raise_error(Puppet::Util::Package::Version::Range::ValidationFailure) end it 'should raise if operator is not implemented' do expect { Puppet::Util::Package::Version::Range.parse('=a', IntegerVersion) }.to raise_error(Puppet::Util::Package::Version::Range::ValidationFailure) end it 'should raise if operator cannot be parsed' do expect { Puppet::Util::Package::Version::Range.parse('~=a', IntegerVersion) }.to raise_error(IntegerVersion::ValidationFailure) end it 'should raise if version cannot be parsed' do expect { Puppet::Util::Package::Version::Range.parse('>=a', IntegerVersion) }.to raise_error(IntegerVersion::ValidationFailure) end end context 'when creating new version range with regular version' do it 'it does not include greater version' do vr = Puppet::Util::Package::Version::Range.parse('3', IntegerVersion) v = IntegerVersion.parse('4') expect(vr.include?(v)).to eql(false) end it 'it includes specified version' do vr = Puppet::Util::Package::Version::Range.parse('3', IntegerVersion) v = IntegerVersion.parse('3') expect(vr.include?(v)).to eql(true) end it 'it does not include lower version' do vr = Puppet::Util::Package::Version::Range.parse('3', IntegerVersion) v = IntegerVersion.parse('2') expect(vr.include?(v)).to eql(false) end end context 'when creating new version range with greater or equal operator' do it 'it includes greater version' do vr = Puppet::Util::Package::Version::Range.parse('>=3', IntegerVersion) v = IntegerVersion.parse('4') expect(vr.include?(v)).to eql(true) end it 'it includes specified version' do vr = Puppet::Util::Package::Version::Range.parse('>=3', IntegerVersion) v = IntegerVersion.parse('3') expect(vr.include?(v)).to eql(true) end it 'it does not include lower version' do vr = Puppet::Util::Package::Version::Range.parse('>=3', IntegerVersion) v = IntegerVersion.parse('2') expect(vr.include?(v)).to eql(false) end end context 'when creating new version range with greater operator' do it 'it includes greater version' do vr = Puppet::Util::Package::Version::Range.parse('>3', IntegerVersion) v = IntegerVersion.parse('10') expect(vr.include?(v)).to eql(true) end it 'it does not include specified version' do vr = Puppet::Util::Package::Version::Range.parse('>3', IntegerVersion) v = IntegerVersion.parse('3') expect(vr.include?(v)).to eql(false) end it 'it does not include lower version' do vr = Puppet::Util::Package::Version::Range.parse('>3', IntegerVersion) v = IntegerVersion.parse('1') expect(vr.include?(v)).to eql(false) end end context 'when creating new version range with lower or equal operator' do it 'it does not include greater version' do vr = Puppet::Util::Package::Version::Range.parse('<=3', IntegerVersion) v = IntegerVersion.parse('5') expect(vr.include?(v)).to eql(false) end it 'it includes specified version' do vr = Puppet::Util::Package::Version::Range.parse('<=3', IntegerVersion) v = IntegerVersion.parse('3') expect(vr.include?(v)).to eql(true) end it 'it includes lower version' do vr = Puppet::Util::Package::Version::Range.parse('<=3', IntegerVersion) v = IntegerVersion.parse('1') expect(vr.include?(v)).to eql(true) end end context 'when creating new version range with lower operator' do it 'it does not include greater version' do vr = Puppet::Util::Package::Version::Range.parse('<3', IntegerVersion) v = IntegerVersion.parse('8') expect(vr.include?(v)).to eql(false) end it 'it does not include specified version' do vr = Puppet::Util::Package::Version::Range.parse('<3', IntegerVersion) v = IntegerVersion.parse('3') expect(vr.include?(v)).to eql(false) end it 'it includes lower version' do vr = Puppet::Util::Package::Version::Range.parse('<3', IntegerVersion) v = IntegerVersion.parse('2') expect(vr.include?(v)).to eql(true) end end context 'when creating new version range with interval' do it 'it does not include greater version' do vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion) v = IntegerVersion.parse('7') expect(vr.include?(v)).to eql(false) end it 'it includes specified max interval value' do vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion) v = IntegerVersion.parse('5') expect(vr.include?(v)).to eql(true) end it 'it includes in interval version' do vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion) v = IntegerVersion.parse('4') expect(vr.include?(v)).to eql(true) end it 'it does not include min interval value ' do vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion) v = IntegerVersion.parse('3') expect(vr.include?(v)).to eql(false) end it 'it does not include lower value ' do vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion) v = IntegerVersion.parse('2') expect(vr.include?(v)).to eql(false) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/log/destinations_spec.rb
spec/unit/util/log/destinations_spec.rb
require 'spec_helper' require 'puppet/util/json' require 'puppet/util/log' describe Puppet::Util::Log.desttypes[:report] do before do @dest = Puppet::Util::Log.desttypes[:report] end it "should require a report at initialization" do expect(@dest.new("foo").report).to eq("foo") end it "should send new messages to the report" do report = double('report') dest = @dest.new(report) expect(report).to receive(:<<).with("my log") dest.handle "my log" end end describe Puppet::Util::Log.desttypes[:file] do include PuppetSpec::Files before do @class = Puppet::Util::Log.desttypes[:file] end it "should default to autoflush false" do expect(@class.new(tmpfile('log')).autoflush).to eq(true) end describe "when matching" do shared_examples_for "file destination" do it "should match an absolute path" do expect(@class.match?(abspath)).to be_truthy end it "should not match a relative path" do expect(@class.match?(relpath)).to be_falsey end end describe "on POSIX systems", :unless => Puppet::Util::Platform.windows? do describe "with a normal file" do let (:parent) { Pathname.new('/tmp') } let (:abspath) { '/tmp/log' } let (:relpath) { 'log' } it_behaves_like "file destination" end describe "with a JSON file" do let (:abspath) { '/tmp/log.json' } let (:relpath) { 'log.json' } it_behaves_like "file destination" it "should log messages as JSON" do msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic") dest = @class.new(abspath) dest.handle(msg) expect(JSON.parse(File.read(abspath) + ']')).to include(a_hash_including({"message" => "don't panic"})) end end describe "with a JSON lines file" do let (:abspath) { '/tmp/log.jsonl' } let (:relpath) { 'log.jsonl' } it_behaves_like "file destination" it "should log messages as JSON lines" do msg1 = Puppet::Util::Log.new(:level => :info, :message => "don't panic") msg2 = Puppet::Util::Log.new(:level => :err, :message => "panic!") dest = @class.new(abspath) dest.handle(msg1) dest.handle(msg2) lines = IO.readlines(abspath) expect(JSON.parse(lines[-2])).to include("level" => "info", "message" => "don't panic") expect(JSON.parse(lines[-1])).to include("level" => "err", "message" => "panic!") end end end describe "on Windows systems", :if => Puppet::Util::Platform.windows? do let (:abspath) { 'C:\\temp\\log.txt' } let (:relpath) { 'log.txt' } it_behaves_like "file destination" end end end describe Puppet::Util::Log.desttypes[:syslog] do let (:klass) { Puppet::Util::Log.desttypes[:syslog] } # these tests can only be run when syslog is present, because # we can't stub the top-level Syslog module describe "when syslog is available", :if => Puppet.features.syslog? do before :each do allow(Syslog).to receive(:opened?).and_return(false) allow(Syslog).to receive(:const_get).and_return("LOG_KERN", 0) allow(Syslog).to receive(:open) end it "should open syslog" do expect(Syslog).to receive(:open) klass.new end it "should close syslog" do expect(Syslog).to receive(:close) dest = klass.new dest.close end it "should send messages to syslog" do syslog = double('syslog') expect(syslog).to receive(:info).with("don't panic") allow(Syslog).to receive(:open).and_return(syslog) msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic") dest = klass.new dest.handle(msg) end end describe "when syslog is unavailable" do it "should not be a suitable log destination" do allow(Puppet.features).to receive(:syslog?).and_return(false) expect(klass.suitable?(:syslog)).to be_falsey end end end describe Puppet::Util::Log.desttypes[:logstash_event] do describe "when using structured log format with logstash_event schema" do before :each do @msg = Puppet::Util::Log.new(:level => :info, :message => "So long, and thanks for all the fish.", :source => "a dolphin") end it "format should fix the hash to have the correct structure" do dest = described_class.new result = dest.format(@msg) expect(result["version"]).to eq(1) expect(result["level"]).to eq('info') expect(result["message"]).to eq("So long, and thanks for all the fish.") expect(result["source"]).to eq("a dolphin") # timestamp should be within 10 seconds expect(Time.parse(result["@timestamp"])).to be >= ( Time.now - 10 ) end it "format returns a structure that can be converted to json" do dest = described_class.new hash = dest.format(@msg) Puppet::Util::Json.load(hash.to_json) end it "handle should send the output to stdout" do expect($stdout).to receive(:puts).once dest = described_class.new dest.handle(@msg) end end end describe Puppet::Util::Log.desttypes[:console] do let (:klass) { Puppet::Util::Log.desttypes[:console] } it "should support color output" do Puppet[:color] = true expect(subject.colorize(:red, 'version')).to eq("\e[0;31mversion\e[0m") end it "should withhold color output when not appropriate" do Puppet[:color] = false expect(subject.colorize(:red, 'version')).to eq("version") end it "should handle multiple overlapping colors in a stack-like way" do Puppet[:color] = true vstring = subject.colorize(:red, 'version') expect(subject.colorize(:green, "(#{vstring})")).to eq("\e[0;32m(\e[0;31mversion\e[0;32m)\e[0m") end it "should handle resets in a stack-like way" do Puppet[:color] = true vstring = subject.colorize(:reset, 'version') expect(subject.colorize(:green, "(#{vstring})")).to eq("\e[0;32m(\e[mversion\e[0;32m)\e[0m") end it "should include the log message's source/context in the output when available" do Puppet[:color] = false expect($stdout).to receive(:puts).with("Info: a hitchhiker: don't panic") msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic", :source => "a hitchhiker") dest = klass.new dest.handle(msg) end end describe ":eventlog", :if => Puppet::Util::Platform.windows? do let(:klass) { Puppet::Util::Log.desttypes[:eventlog] } def expects_message_with_type(klass, level, eventlog_type, eventlog_id) eventlog = double('eventlog') expect(eventlog).to receive(:report_event).with(hash_including(:event_type => eventlog_type, :event_id => eventlog_id, :data => "a hitchhiker: don't panic")) allow(Puppet::Util::Windows::EventLog).to receive(:open).and_return(eventlog) msg = Puppet::Util::Log.new(:level => level, :message => "don't panic", :source => "a hitchhiker") dest = klass.new dest.handle(msg) end it "supports the eventlog feature" do expect(Puppet.features.eventlog?).to be_truthy end it "should truncate extremely long log messages" do long_msg = "x" * 32000 expected_truncated_msg = "#{'x' * 31785}...Message exceeds character length limit, truncating." expected_data = "a vogon ship: " + expected_truncated_msg eventlog = double('eventlog') expect(eventlog).to receive(:report_event).with(hash_including(:event_type => 2, :event_id => 2, :data => expected_data)) msg = Puppet::Util::Log.new(:level => :warning, :message => long_msg, :source => "a vogon ship") allow(Puppet::Util::Windows::EventLog).to receive(:open).and_return(eventlog) dest = klass.new dest.handle(msg) end it "logs to the Puppet Application event log" do expect(Puppet::Util::Windows::EventLog).to receive(:open).with('Puppet').and_return(double('eventlog')) klass.new end it "logs :debug level as an information type event" do expects_message_with_type(klass, :debug, klass::EVENTLOG_INFORMATION_TYPE, 0x1) end it "logs :warning level as an warning type event" do expects_message_with_type(klass, :warning, klass::EVENTLOG_WARNING_TYPE, 0x2) end it "logs :err level as an error type event" do expects_message_with_type(klass, :err, klass::EVENTLOG_ERROR_TYPE, 0x3) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/file_spec.rb
spec/unit/type/file_spec.rb
# coding: utf-8 require 'spec_helper' describe Puppet::Type.type(:file) do include PuppetSpec::Files # precomputed checksum values for FILE_CONTENT FILE_CONTENT = 'file content'.freeze CHECKSUM_VALUES = { md5: 'd10b4c3ff123b26dc068d43a8bef2d23', md5lite: 'd10b4c3ff123b26dc068d43a8bef2d23', sha256: 'e0ac3601005dfa1864f5392aabaf7d898b1b5bab854f1acb4491bcd806b76b0c', sha256lite: 'e0ac3601005dfa1864f5392aabaf7d898b1b5bab854f1acb4491bcd806b76b0c', sha1: '87758871f598e1a3b4679953589ae2f57a0bb43c', sha1lite: '87758871f598e1a3b4679953589ae2f57a0bb43c', sha224: '2aefaaa5f4d8f17f82f3e1bb407e190cede9aa1311fa4533ce505531', sha384: '61c7783501ebd90233650357fefbe5a141b7618f907b8f043bbaa92c0f610c785a641ddd479fa81d650cd86e29aa6858', sha512: '2fb1877301854ac92dd518018f97407a0a88bb696bfef0a51e9efbd39917353500009e15bd72c3f0e4bf690115870bfab926565d5ad97269d922dbbb41261221', mtime: 'Jan 26 13:59:49 2016', ctime: 'Jan 26 13:59:49 2016' }.freeze INVALID_CHECKSUM_VALUES = { md5: '00000000000000000000000000000000', md5lite: '00000000000000000000000000000000', sha256: '0000000000000000000000000000000000000000000000000000000000000000', sha256lite: '0000000000000000000000000000000000000000000000000000000000000000', sha1: '0000000000000000000000000000000000000000', sha1lite: '0000000000000000000000000000000000000000', sha224: '00000000000000000000000000000000000000000000000000000000', sha384: '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', sha512: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' }.freeze let(:path) { tmpfile('file_testing') } let(:file) { described_class.new(:path => path, :catalog => catalog) } let(:provider) { file.provider } let(:catalog) { Puppet::Resource::Catalog.new } before do allow(Puppet.features).to receive("posix?").and_return(true) end describe "the path parameter" do describe "on POSIX systems", :if => Puppet.features.posix? do it "should remove trailing slashes" do file[:path] = "/foo/bar/baz/" expect(file[:path]).to eq("/foo/bar/baz") end it "should remove double slashes" do file[:path] = "/foo/bar//baz" expect(file[:path]).to eq("/foo/bar/baz") end it "should remove triple slashes" do file[:path] = "/foo/bar///baz" expect(file[:path]).to eq("/foo/bar/baz") end it "should remove trailing double slashes" do file[:path] = "/foo/bar/baz//" expect(file[:path]).to eq("/foo/bar/baz") end it "should leave a single slash alone" do file[:path] = "/" expect(file[:path]).to eq("/") end it "should accept and collapse a double-slash at the start of the path" do file[:path] = "//tmp/xxx" expect(file[:path]).to eq('/tmp/xxx') end it "should accept and collapse a triple-slash at the start of the path" do file[:path] = "///tmp/xxx" expect(file[:path]).to eq('/tmp/xxx') end end describe "on Windows systems", :if => Puppet::Util::Platform.windows? do it "should remove trailing slashes" do file[:path] = "X:/foo/bar/baz/" expect(file[:path]).to eq("X:/foo/bar/baz") end it "should remove double slashes" do file[:path] = "X:/foo/bar//baz" expect(file[:path]).to eq("X:/foo/bar/baz") end it "should remove trailing double slashes" do file[:path] = "X:/foo/bar/baz//" expect(file[:path]).to eq("X:/foo/bar/baz") end it "should leave a drive letter with a slash alone" do file[:path] = "X:/" expect(file[:path]).to eq("X:/") end it "should not accept a drive letter without a slash" do expect { file[:path] = "X:" }.to raise_error(/File paths must be fully qualified/) end describe "when using UNC filenames", :if => Puppet::Util::Platform.windows? do it "should remove trailing slashes" do file[:path] = "//localhost/foo/bar/baz/" expect(file[:path]).to eq("//localhost/foo/bar/baz") end it "should remove double slashes" do file[:path] = "//localhost/foo/bar//baz" expect(file[:path]).to eq("//localhost/foo/bar/baz") end it "should remove trailing double slashes" do file[:path] = "//localhost/foo/bar/baz//" expect(file[:path]).to eq("//localhost/foo/bar/baz") end it "should remove a trailing slash from a sharename" do file[:path] = "//localhost/foo/" expect(file[:path]).to eq("//localhost/foo") end it "should not modify a sharename" do file[:path] = "//localhost/foo" expect(file[:path]).to eq("//localhost/foo") end end end end describe "the backup parameter" do it 'should be disabled by default' do expect(file[:backup]).to eq(nil) end [false, 'false', :false].each do |value| it "should disable backup if the value is #{value.inspect}" do file[:backup] = value expect(file[:backup]).to eq(false) end end [true, 'true', '.puppet-bak'].each do |value| it "should use .puppet-bak if the value is #{value.inspect}" do file[:backup] = value expect(file[:backup]).to eq('.puppet-bak') end end it "should use the provided value if it's any other string" do file[:backup] = "over there" expect(file[:backup]).to eq("over there") end it "should fail if backup is set to anything else" do expect do file[:backup] = 97 end.to raise_error(Puppet::Error, /Invalid backup type 97/) end end describe "the recurse parameter" do it "should default to recursion being disabled" do expect(file[:recurse]).to be_falsey end [true, "true", "remote"].each do |value| it "should consider #{value} to enable recursion" do file[:recurse] = value expect(file[:recurse]).to be_truthy end end it "should not allow numbers" do expect { file[:recurse] = 10 }.to raise_error( Puppet::Error, /Parameter recurse failed on File\[[^\]]+\]: Invalid recurse value 10/) end [false, "false"].each do |value| it "should consider #{value} to disable recursion" do file[:recurse] = value expect(file[:recurse]).to be_falsey end end end describe "the recurselimit parameter" do it "should accept integers" do file[:recurselimit] = 12 expect(file[:recurselimit]).to eq(12) end it "should munge string numbers to number numbers" do file[:recurselimit] = '12' expect(file[:recurselimit]).to eq(12) end it "should fail if given a non-number" do expect do file[:recurselimit] = 'twelve' end.to raise_error(Puppet::Error, /Invalid value "twelve"/) end end describe "the replace parameter" do [true, :true, :yes].each do |value| it "should consider #{value} to be true" do file[:replace] = value expect(file[:replace]).to be_truthy end end [false, :false, :no].each do |value| it "should consider #{value} to be false" do file[:replace] = value expect(file[:replace]).to be_falsey end end end describe ".instances" do it "should return an empty array" do expect(described_class.instances).to eq([]) end end describe "#bucket" do it "should return nil if backup is off" do file[:backup] = false expect(file.bucket).to eq(nil) end it "should not return a bucket if using a file extension for backup" do file[:backup] = '.backup' expect(file.bucket).to eq(nil) end it "should return the default filebucket if using the 'puppet' filebucket" do file[:backup] = 'puppet' bucket = double('bucket') allow(file).to receive(:default_bucket).and_return(bucket) expect(file.bucket).to eq(bucket) end it "should fail if using a remote filebucket and no catalog exists" do file.catalog = nil file[:backup] = 'my_bucket' expect { file.bucket }.to raise_error(Puppet::Error, "Can not find filebucket for backups without a catalog") end it "should fail if the specified filebucket isn't in the catalog" do file[:backup] = 'my_bucket' expect { file.bucket }.to raise_error(Puppet::Error, "Could not find filebucket my_bucket specified in backup") end it "should use the specified filebucket if it is in the catalog" do file[:backup] = 'my_bucket' filebucket = Puppet::Type.type(:filebucket).new(:name => 'my_bucket') catalog.add_resource(filebucket) expect(file.bucket).to eq(filebucket.bucket) end end describe "#asuser" do before :each do # Mocha won't let me just stub SUIDManager.asuser to yield and return, # but it will do exactly that if we're not root. allow(Puppet::Util::SUIDManager).to receive(:root?).and_return(false) end it "should return the desired owner if they can write to the parent directory" do file[:owner] = 1001 allow(FileTest).to receive(:writable?).with(File.dirname file[:path]).and_return(true) expect(file.asuser).to eq(1001) end it "should return nil if the desired owner can't write to the parent directory" do file[:owner] = 1001 allow(FileTest).to receive(:writable?).with(File.dirname file[:path]).and_return(false) expect(file.asuser).to eq(nil) end it "should return nil if not managing owner" do expect(file.asuser).to eq(nil) end end describe "#exist?" do it "should be considered existent if it can be stat'ed" do expect(file).to receive(:stat).and_return(double('stat')) expect(file).to be_exist end it "should be considered nonexistent if it can not be stat'ed" do expect(file).to receive(:stat).and_return(nil) expect(file).to_not be_exist end end describe "#eval_generate" do before do @graph = double('graph', :add_edge => nil) allow(catalog).to receive(:relationship_graph).and_return(@graph) end it "should recurse if recursion is enabled" do resource = double('resource', :[] => 'resource') expect(file).to receive(:recurse).and_return([resource]) file[:recurse] = true expect(file.eval_generate).to eq([resource]) end it "should not recurse if recursion is disabled" do expect(file).not_to receive(:recurse) file[:recurse] = false expect(file.eval_generate).to eq([]) end end describe "#ancestors" do it "should return the ancestors of the file, in ascending order" do file = described_class.new(:path => make_absolute("/tmp/foo/bar/baz/qux")) pieces = %W[#{make_absolute('/')} tmp foo bar baz] ancestors = file.ancestors expect(ancestors).not_to be_empty ancestors.reverse.each_with_index do |path,i| expect(path).to eq(File.join(*pieces[0..i])) end end end describe "#flush" do it "should reset its stat reference" do FileUtils.touch(path) stat1 = file.stat expect(file.stat).to equal(stat1) file.flush expect(file.stat).not_to equal(stat1) end end describe "#initialize" do it "should remove a trailing slash from the title to create the path" do title = File.expand_path("/abc/\n\tdef/") file = described_class.new(:title => title) expect(file[:path]).to eq(title) end it "should allow a single slash for a title and create the path" do title = File.expand_path("/") file = described_class.new(:title => title) expect(file[:path]).to eq(title) end it "should allow multiple slashes for a title and create the path" do title = File.expand_path("/") + "//" file = described_class.new(:title => title) expect(file[:path]).to eq(File.expand_path("/")) end it "should set a desired 'ensure' value if none is set and 'content' is set" do file = described_class.new(:path => path, :content => "/foo/bar") expect(file[:ensure]).to eq(:file) end it "should set a desired 'ensure' value if none is set and 'target' is set", :if => described_class.defaultprovider.feature?(:manages_symlinks) do file = described_class.new(:path => path, :target => File.expand_path(__FILE__)) expect(file[:ensure]).to eq(:link) end describe "marking parameters as sensitive" do it "marks sensitive, content, and ensure as sensitive when source is sensitive" do resource = Puppet::Resource.new(:file, make_absolute("/tmp/foo"), :parameters => {:source => make_absolute('/tmp/bar')}, :sensitive_parameters => [:source]) file = described_class.new(resource) expect(file.parameter(:source).sensitive).to eq true expect(file.property(:content).sensitive).to eq true expect(file.property(:ensure).sensitive).to eq true end it "marks ensure as sensitive when content is sensitive" do resource = Puppet::Resource.new(:file, make_absolute("/tmp/foo"), :parameters => {:content => 'hello world!'}, :sensitive_parameters => [:content]) file = described_class.new(resource) expect(file.property(:ensure).sensitive).to eq true end end end describe "#mark_children_for_purging" do it "should set each child's ensure to absent" do paths = %w[foo bar baz] children = {} paths.each do |child| children[child] = described_class.new(:path => File.join(path, child), :ensure => :present) end file.mark_children_for_purging(children) expect(children.length).to eq(3) children.values.each do |child| expect(child[:ensure]).to eq(:absent) end end it "should skip children which have a source" do child = described_class.new(:path => path, :ensure => :present, :source => File.expand_path(__FILE__)) file.mark_children_for_purging('foo' => child) expect(child[:ensure]).to eq(:present) end end describe "#newchild" do it "should create a new resource relative to the parent" do child = file.newchild('bar') expect(child).to be_a(described_class) expect(child[:path]).to eq(File.join(file[:path], 'bar')) end { :ensure => :present, :recurse => true, :recurselimit => 5, :target => "some_target", :source => File.expand_path("some_source"), }.each do |param, value| it "should omit the #{param} parameter", :if => described_class.defaultprovider.feature?(:manages_symlinks) do # Make a new file, because we have to set the param at initialization # or it wouldn't be copied regardless. file = described_class.new(:path => path, param => value) child = file.newchild('bar') expect(child[param]).not_to eq(value) end end it "should copy all of the parent resource's 'should' values that were set at initialization" do parent = described_class.new(:path => path, :owner => 'root', :group => 'wheel') child = parent.newchild("my/path") expect(child[:owner]).to eq('root') expect(child[:group]).to eq('wheel') end it "should not copy default values to the new child" do child = file.newchild("my/path") expect(child.original_parameters).not_to include(:backup) end it "should not copy values to the child which were set by the source" do source = File.expand_path(__FILE__) file[:source] = source metadata = double('metadata', :owner => "root", :group => "root", :mode => '0755', :ftype => "file", :checksum => "{md5}whatever", :checksum_type => "md5", :source => source) allow(file.parameter(:source)).to receive(:metadata).and_return(metadata) file.parameter(:source).copy_source_values expect(file.class).to receive(:new) do |arg| expect(arg[:group]).to be_nil end file.newchild("my/path") end end describe "#purge?" do it "should return false if purge is not set" do expect(file).to_not be_purge end it "should return true if purge is set to true" do file[:purge] = true expect(file).to be_purge end it "should return false if purge is set to false" do file[:purge] = false expect(file).to_not be_purge end end describe "#recurse" do let(:name) { 'bar' } let(:child) { double('puppet_type_file') } before do file[:recurse] = true @metadata = Puppet::FileServing::Metadata end describe "and a source is set" do it "should pass the already-discovered resources to recurse_remote" do file[:source] = File.expand_path(__FILE__) allow(child).to receive(:[]).with(:path).and_return(name) allow(file).to receive(:recurse_local).and_return({name => child}) expect(file).to receive(:recurse_remote).with({name => child}).and_return([]) file.recurse end end describe "and a target is set" do it "should use recurse_link" do file[:target] = File.expand_path(__FILE__) allow(child).to receive(:[]).with(:path).and_return(name) allow(file).to receive(:recurse_local).and_return({name => child}) expect(file).to receive(:recurse_link).with({name => child}).and_return([]) file.recurse end end it "should use recurse_local if recurse is not remote" do expect(file).to receive(:recurse_local).and_return({}) file.recurse end it "should not use recurse_local if recurse is remote" do file[:recurse] = :remote expect(file).not_to receive(:recurse_local) file.recurse end it "should return the generated resources as an array sorted by file path" do one = double('one', :[] => "/one") two = double('two', :[] => "/one/two") three = double('three', :[] => "/three") expect(file).to receive(:recurse_local).and_return(:one => one, :two => two, :three => three) expect(file.recurse).to eq([one, two, three]) end describe "and purging is enabled" do before do file[:purge] = true end it "should mark each file for removal" do local = described_class.new(:path => path, :ensure => :present) expect(file).to receive(:recurse_local).and_return("local" => local) file.recurse expect(local[:ensure]).to eq(:absent) end it "should not remove files that exist in the remote repository" do pending("FIXME: This test has been broken since it was introduced in c189b46e3f1 because of = vs ==") file[:source] = File.expand_path(__FILE__) expect(file).to receive(:recurse_local).and_return({}) remote = described_class.new(:path => path, :source => File.expand_path(__FILE__), :ensure => :present) expect(file).to receive(:recurse_remote).with(hash_including("remote" => remote)) file.recurse expect(remote[:ensure]).not_to eq(:absent) end end end describe "#remove_less_specific_files" do it "should remove any nested files that are already in the catalog" do foo = described_class.new :path => File.join(file[:path], 'foo') bar = described_class.new :path => File.join(file[:path], 'bar') baz = described_class.new :path => File.join(file[:path], 'baz') catalog.add_resource(foo) catalog.add_resource(bar) expect(file.remove_less_specific_files([foo, bar, baz])).to eq([baz]) end end describe "#recurse?" do it "should be true if recurse is true" do file[:recurse] = true expect(file).to be_recurse end it "should be true if recurse is remote" do file[:recurse] = :remote expect(file).to be_recurse end it "should be false if recurse is false" do file[:recurse] = false expect(file).to_not be_recurse end end describe "#recurse_link" do before do @first = double('first', :relative_path => "first", :full_path => "/my/first", :ftype => "directory") @second = double('second', :relative_path => "second", :full_path => "/my/second", :ftype => "file") @resource = double('file', :[]= => nil) end it "should pass its target to the :perform_recursion method" do file[:target] = "mylinks" expect(file).to receive(:perform_recursion).with("mylinks").and_return([@first]) allow(file).to receive(:newchild).and_return(@resource) file.recurse_link({}) end it "should ignore the recursively-found '.' file and configure the top-level file to create a directory" do allow(@first).to receive(:relative_path).and_return(".") file[:target] = "mylinks" expect(file).to receive(:perform_recursion).with("mylinks").and_return([@first]) expect(file).not_to receive(:newchild) expect(file).to receive(:[]=).with(:ensure, :directory) file.recurse_link({}) end it "should create a new child resource for each generated metadata instance's relative path that doesn't already exist in the children hash" do expect(file).to receive(:perform_recursion).and_return([@first, @second]) expect(file).to receive(:newchild).with(@first.relative_path).and_return(@resource) file.recurse_link("second" => @resource) end it "should not create a new child resource for paths that already exist in the children hash" do expect(file).to receive(:perform_recursion).and_return([@first]) expect(file).not_to receive(:newchild) file.recurse_link("first" => @resource) end it "should set the target to the full path of discovered file and set :ensure to :link if the file is not a directory", :if => described_class.defaultprovider.feature?(:manages_symlinks) do allow(file).to receive(:perform_recursion).and_return([@first, @second]) file.recurse_link("first" => @resource, "second" => file) expect(file[:ensure]).to eq(:link) expect(file[:target]).to eq("/my/second") end it "should :ensure to :directory if the file is a directory" do allow(file).to receive(:perform_recursion).and_return([@first, @second]) file.recurse_link("first" => file, "second" => @resource) expect(file[:ensure]).to eq(:directory) end it "should return a hash with both created and existing resources with the relative paths as the hash keys" do expect(file).to receive(:perform_recursion).and_return([@first, @second]) allow(file).to receive(:newchild).and_return(file) expect(file.recurse_link("second" => @resource)).to eq({"second" => @resource, "first" => file}) end end describe "#recurse_local" do before do @metadata = double('metadata', :relative_path => "my/file") end it "should pass its path to the :perform_recursion method" do expect(file).to receive(:perform_recursion).with(file[:path]).and_return([@metadata]) allow(file).to receive(:newchild) file.recurse_local end it "should return an empty hash if the recursion returns nothing" do expect(file).to receive(:perform_recursion).and_return(nil) expect(file.recurse_local).to eq({}) end it "should create a new child resource with each generated metadata instance's relative path" do expect(file).to receive(:perform_recursion).and_return([@metadata]) expect(file).to receive(:newchild).with(@metadata.relative_path).and_return("fiebar") file.recurse_local end it "should not create a new child resource for the '.' directory" do allow(@metadata).to receive(:relative_path).and_return(".") expect(file).to receive(:perform_recursion).and_return([@metadata]) expect(file).not_to receive(:newchild) file.recurse_local end it "should return a hash of the created resources with the relative paths as the hash keys" do expect(file).to receive(:perform_recursion).and_return([@metadata]) expect(file).to receive(:newchild).with("my/file").and_return("fiebar") expect(file.recurse_local).to eq({"my/file" => "fiebar"}) end it "should set checksum_type to none if this file checksum is none" do file[:checksum] = :none expect(Puppet::FileServing::Metadata.indirection).to receive(:search).with(anything, hash_including(checksum_type: :none)).and_return([@metadata]) expect(file).to receive(:newchild).with("my/file").and_return("fiebar") file.recurse_local end end describe "#recurse_remote" do let(:my) { File.expand_path('/my') } before do file[:source] = "puppet://foo/bar" @first = Puppet::FileServing::Metadata.new(my, :relative_path => "first") @second = Puppet::FileServing::Metadata.new(my, :relative_path => "second") allow(@first).to receive(:ftype).and_return("directory") allow(@second).to receive(:ftype).and_return("directory") @parameter = double('property', :metadata= => nil) @resource = double('file', :[]= => nil, :parameter => @parameter) end it "should pass its source to the :perform_recursion method" do data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => "foobar") expect(file).to receive(:perform_recursion).with("puppet://foo/bar").and_return([data]) allow(file).to receive(:newchild).and_return(@resource) file.recurse_remote({}) end it "should not recurse when the remote file is not a directory" do data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => ".") allow(data).to receive(:ftype).and_return("file") expect(file).to receive(:perform_recursion).with("puppet://foo/bar").and_return([data]) expect(file).not_to receive(:newchild) file.recurse_remote({}) end it "should set the source of each returned file to the searched-for URI plus the found relative path" do expect(@first).to receive(:source=).with(File.join("puppet://foo/bar", @first.relative_path)) expect(file).to receive(:perform_recursion).and_return([@first]) allow(file).to receive(:newchild).and_return(@resource) file.recurse_remote({}) end it "should create a new resource for any relative file paths that do not already have a resource" do allow(file).to receive(:perform_recursion).and_return([@first]) expect(file).to receive(:newchild).with("first").and_return(@resource) expect(file.recurse_remote({})).to eq({"first" => @resource}) end it "should not create a new resource for any relative file paths that do already have a resource" do allow(file).to receive(:perform_recursion).and_return([@first]) expect(file).not_to receive(:newchild) file.recurse_remote("first" => @resource) end it "should set the source of each resource to the source of the metadata" do allow(file).to receive(:perform_recursion).and_return([@first]) allow(@resource).to receive(:[]=) expect(@resource).to receive(:[]=).with(:source, File.join("puppet://foo/bar", @first.relative_path)) file.recurse_remote("first" => @resource) end it "should set the checksum parameter based on the metadata" do allow(file).to receive(:perform_recursion).and_return([@first]) allow(@resource).to receive(:[]=) expect(@resource).to receive(:[]=).with(:checksum, "sha256") file.recurse_remote("first" => @resource) end it "should store the metadata in the source property for each resource so the source does not have to requery the metadata" do allow(file).to receive(:perform_recursion).and_return([@first]) expect(@resource).to receive(:parameter).with(:source).and_return(@parameter) expect(@parameter).to receive(:metadata=).with(@first) file.recurse_remote("first" => @resource) end it "should not create a new resource for the '.' file" do allow(@first).to receive(:relative_path).and_return(".") allow(file).to receive(:perform_recursion).and_return([@first]) expect(file).not_to receive(:newchild) file.recurse_remote({}) end it "should store the metadata in the main file's source property if the relative path is '.'" do allow(@first).to receive(:relative_path).and_return(".") allow(file).to receive(:perform_recursion).and_return([@first]) expect(file.parameter(:source)).to receive(:metadata=).with(@first) file.recurse_remote("first" => @resource) end it "should update the main file's checksum parameter if the relative path is '.'" do allow(@first).to receive(:relative_path).and_return(".") allow(file).to receive(:perform_recursion).and_return([@first]) allow(file).to receive(:[]=) expect(file). to receive(:[]=).with(:checksum, "sha256") file.recurse_remote("first" => @resource) end describe "and multiple sources are provided" do let(:sources) do h = {} %w{/a /b /c /d}.each do |key| h[key] = Puppet::Util.uri_unescape(Puppet::Util.path_to_uri(File.expand_path(key)).to_s) end h end describe "and :sourceselect is set to :first" do it "should create file instances for the results for the first source to return any values" do data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => "foobar") file[:source] = sources.keys.sort.map { |key| File.expand_path(key) } expect(file).to receive(:perform_recursion).with(sources['/a']).and_return(nil) expect(file).to receive(:perform_recursion).with(sources['/b']).and_return([]) expect(file).to receive(:perform_recursion).with(sources['/c']).and_return([data]) expect(file).not_to receive(:perform_recursion).with(sources['/d']) expect(file).to receive(:newchild).with("foobar").and_return(@resource) file.recurse_remote({}) end end describe "and :sourceselect is set to :all" do before do file[:sourceselect] = :all end it "should return every found file that is not in a previous source" do klass = Puppet::FileServing::Metadata file[:source] = abs_path = %w{/a /b /c /d}.map {|f| File.expand_path(f) } allow(file).to receive(:newchild).and_return(@resource) one = [klass.new(abs_path[0], :relative_path => "a")] expect(file).to receive(:perform_recursion).with(sources['/a']).and_return(one) expect(file).to receive(:newchild).with("a").and_return(@resource) two = [klass.new(abs_path[1], :relative_path => "a"), klass.new(abs_path[1], :relative_path => "b")] expect(file).to receive(:perform_recursion).with(sources['/b']).and_return(two) expect(file).to receive(:newchild).with("b").and_return(@resource) three = [klass.new(abs_path[2], :relative_path => "a"), klass.new(abs_path[2], :relative_path => "c")] expect(file).to receive(:perform_recursion).with(sources['/c']).and_return(three) expect(file).to receive(:newchild).with("c").and_return(@resource) expect(file).to receive(:perform_recursion).with(sources['/d']).and_return([]) file.recurse_remote({}) end end end end describe "#perform_recursion", :uses_checksums => true do it "should use Metadata to do its recursion" do expect(Puppet::FileServing::Metadata.indirection).to receive(:search) file.perform_recursion(file[:path]) end it "should use the provided path as the key to the search" do expect(Puppet::FileServing::Metadata.indirection).to receive(:search).with("/foo", anything) file.perform_recursion("/foo") end it "should return the results of the metadata search" do expect(Puppet::FileServing::Metadata.indirection).to receive(:search).and_return("foobar") expect(file.perform_recursion(file[:path])).to eq("foobar") end it "should pass its recursion value to the search" do file[:recurse] = true expect(Puppet::FileServing::Metadata.indirection).to receive(:search).with(anything, hash_including(recurse: true)) file.perform_recursion(file[:path]) end it "should pass true if recursion is remote" do file[:recurse] = :remote
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/group_spec.rb
spec/unit/type/group_spec.rb
require 'spec_helper' describe Puppet::Type.type(:group) do before do @class = Puppet::Type.type(:group) end it "should have a system_groups feature" do expect(@class.provider_feature(:system_groups)).not_to be_nil end it 'should default to `present`' do expect(@class.new(:name => "foo")[:ensure]).to eq(:present) end it 'should set ensure to whatever is passed in' do expect(@class.new(:name => "foo", :ensure => 'absent')[:ensure]).to eq(:absent) end describe "when validating attributes" do [:name, :allowdupe].each do |param| it "should have a #{param} parameter" do expect(@class.attrtype(param)).to eq(:param) end end [:ensure, :gid].each do |param| it "should have a #{param} property" do expect(@class.attrtype(param)).to eq(:property) end end it "should convert gids provided as strings into integers" do expect(@class.new(:name => "foo", :gid => "15")[:gid]).to eq(15) end it "should accepts gids provided as integers" do expect(@class.new(:name => "foo", :gid => 15)[:gid]).to eq(15) end end it "should have a boolean method for determining if duplicates are allowed" do expect(@class.new(:name => "foo")).to respond_to "allowdupe?" end it "should have a boolean method for determining if system groups are allowed" do expect(@class.new(:name => "foo")).to respond_to "system?" end it "should call 'create' to create the group" do group = @class.new(:name => "foo", :ensure => :present) expect(group.provider).to receive(:create) group.parameter(:ensure).sync end it "should call 'delete' to remove the group" do group = @class.new(:name => "foo", :ensure => :absent) expect(group.provider).to receive(:delete) group.parameter(:ensure).sync end it "delegates the existence check to its provider" do provider = @class.provide(:testing) do def exists? true end end provider_instance = provider.new type = @class.new(:name => "group", :provider => provider_instance) expect(type.exists?).to eq(true) end describe "should delegate :members implementation to the provider:" do let (:provider) do @class.provide(:testing) do has_features :manages_members def members [] end def members_insync?(current, should) current == should end def members_to_s(values) values.map { |v| "#{v} ()" }.join(', ') end end end let (:provider_instance) { provider.new } let (:type) { @class.new(:name => "group", :provider => provider_instance, :members => ['user1']) } it "insync? calls members_insync?" do expect(type.property(:members).insync?(['user1'])).to be_truthy end it "is_to_s and should_to_s call members_to_s" do expect(type.property(:members).is_to_s('user1')).to eq('user1 ()') expect(type.property(:members).should_to_s('user1,user2')).to eq('user1 (), user2 ()') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/filebucket_spec.rb
spec/unit/type/filebucket_spec.rb
require 'spec_helper' describe Puppet::Type.type(:filebucket) do include PuppetSpec::Files describe "when validating attributes" do %w{name server port path}.each do |attr| it "should have a '#{attr}' parameter" do expect(Puppet::Type.type(:filebucket).attrtype(attr.intern)).to eq(:param) end end it "should have its 'name' attribute set as its namevar" do expect(Puppet::Type.type(:filebucket).key_attributes).to eq([:name]) end end it "should use the clientbucketdir as the path by default path" do Puppet.settings[:clientbucketdir] = "/my/bucket" expect(Puppet::Type.type(:filebucket).new(:name => "main")[:path]).to eq(Puppet[:clientbucketdir]) end it "should not have a default port" do Puppet.settings[:serverport] = 50 expect(Puppet::Type.type(:filebucket).new(:name => "main")[:port]).to eq(nil) end it "should not have a default server" do Puppet.settings[:server] = "myserver" expect(Puppet::Type.type(:filebucket).new(:name => "main")[:server]).to eq(nil) end it "be local by default" do bucket = Puppet::Type.type(:filebucket).new :name => "main" expect(bucket.bucket).to be_local end describe "path" do def bucket(hash) Puppet::Type.type(:filebucket).new({:name => 'main'}.merge(hash)) end it "should accept false as a value" do expect { bucket(:path => false) }.not_to raise_error end it "should accept true as a value" do expect { bucket(:path => true) }.not_to raise_error end it "should fail when given an array of values" do expect { bucket(:path => ['one', 'two']) }. to raise_error Puppet::Error, /only have one filebucket path/ end %w{one ../one one/two}.each do |path| it "should fail if given a relative path of #{path.inspect}" do expect { bucket(:path => path) }. to raise_error Puppet::Error, /Filebucket paths must be absolute/ end end it "should succeed if given an absolute path" do expect { bucket(:path => make_absolute('/tmp/bucket')) }.not_to raise_error end it "not be local if path is false" do expect(bucket(:path => false).bucket).not_to be_local end it "be local if both a path and a server are specified" do expect(bucket(:server => "puppet", :path => make_absolute("/my/path")).bucket).to be_local end end describe "when creating the filebucket" do before do @bucket = double('bucket', :name= => nil) end it "should use any provided path" do path = make_absolute("/foo/bar") bucket = Puppet::Type.type(:filebucket).new :name => "main", :path => path expect(Puppet::FileBucket::Dipper).to receive(:new).with({:Path => path}).and_return(@bucket) bucket.bucket end it "should use any provided server and port" do bucket = Puppet::Type.type(:filebucket).new :name => "main", :server => "myserv", :port => "myport", :path => false expect(Puppet::FileBucket::Dipper).to receive(:new).with({:Server => "myserv", :Port => "myport"}).and_return(@bucket) bucket.bucket end it "should not try to guess server or port if the path is unset and no server is provided" do Puppet.settings[:server] = "myserv" Puppet.settings[:server_list] = ['server_list_0', 'server_list_1'] expect(Puppet::FileBucket::Dipper).to receive(:new).with({:Server => nil, :Port => nil}).and_return(@bucket) bucket = Puppet::Type.type(:filebucket).new :name => "main", :path => false bucket.bucket end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/package_spec.rb
spec/unit/type/package_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package) do before do allow(Process).to receive(:euid).and_return(0) allow(Puppet::Util::Storage).to receive(:store) end it "should have a :reinstallable feature that requires the :reinstall method" do expect(Puppet::Type.type(:package).provider_feature(:reinstallable).methods).to eq([:reinstall]) end it "should have an :installable feature that requires the :install method" do expect(Puppet::Type.type(:package).provider_feature(:installable).methods).to eq([:install]) end it "should have an :uninstallable feature that requires the :uninstall method" do expect(Puppet::Type.type(:package).provider_feature(:uninstallable).methods).to eq([:uninstall]) end it "should have an :upgradeable feature that requires :update and :latest methods" do expect(Puppet::Type.type(:package).provider_feature(:upgradeable).methods).to eq([:update, :latest]) end it "should have a :purgeable feature that requires the :purge latest method" do expect(Puppet::Type.type(:package).provider_feature(:purgeable).methods).to eq([:purge]) end it "should have a :versionable feature" do expect(Puppet::Type.type(:package).provider_feature(:versionable)).not_to be_nil end it "should have a :supports_flavors feature" do expect(Puppet::Type.type(:package).provider_feature(:supports_flavors)).not_to be_nil end it "should have a :package_settings feature that requires :package_settings_insync?, :package_settings and :package_settings=" do expect(Puppet::Type.type(:package).provider_feature(:package_settings).methods).to eq([:package_settings_insync?, :package_settings, :package_settings=]) end it "should default to being installed" do pkg = Puppet::Type.type(:package).new(:name => "yay", :provider => :apt) expect(pkg.should(:ensure)).to eq(:present) end describe "when validating attributes" do [:name, :source, :instance, :status, :adminfile, :responsefile, :configfiles, :category, :platform, :root, :vendor, :description, :allowcdrom, :allow_virtual, :reinstall_on_refresh].each do |param| it "should have a #{param} parameter" do expect(Puppet::Type.type(:package).attrtype(param)).to eq(:param) end end it "should have an ensure property" do expect(Puppet::Type.type(:package).attrtype(:ensure)).to eq(:property) end it "should have a package_settings property" do expect(Puppet::Type.type(:package).attrtype(:package_settings)).to eq(:property) end it "should have a flavor property" do expect(Puppet::Type.type(:package).attrtype(:flavor)).to eq(:property) end end describe "when validating attribute values" do before :each do @provider = double( 'provider', :class => Puppet::Type.type(:package).defaultprovider, :clear => nil, :validate_source => nil ) allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(@provider) end after :each do Puppet::Type.type(:package).defaultprovider = nil end it "should support :present as a value to :ensure" do Puppet::Type.type(:package).new(:name => "yay", :ensure => :present) end it "should alias :installed to :present as a value to :ensure" do pkg = Puppet::Type.type(:package).new(:name => "yay", :ensure => :installed) expect(pkg.should(:ensure)).to eq(:present) end it "should support :absent as a value to :ensure" do Puppet::Type.type(:package).new(:name => "yay", :ensure => :absent) end it "should support :purged as a value to :ensure if the provider has the :purgeable feature" do expect(@provider).to receive(:satisfies?).with([:purgeable]).and_return(true) Puppet::Type.type(:package).new(:name => "yay", :ensure => :purged) end it "should not support :purged as a value to :ensure if the provider does not have the :purgeable feature" do expect(@provider).to receive(:satisfies?).with([:purgeable]).and_return(false) expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => :purged) }.to raise_error(Puppet::Error) end it "should support :latest as a value to :ensure if the provider has the :upgradeable feature" do expect(@provider).to receive(:satisfies?).with([:upgradeable]).and_return(true) Puppet::Type.type(:package).new(:name => "yay", :ensure => :latest) end it "should not support :latest as a value to :ensure if the provider does not have the :upgradeable feature" do expect(@provider).to receive(:satisfies?).with([:upgradeable]).and_return(false) expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => :latest) }.to raise_error(Puppet::Error) end it "should support version numbers as a value to :ensure if the provider has the :versionable feature" do expect(@provider).to receive(:satisfies?).with([:versionable]).and_return(true) Puppet::Type.type(:package).new(:name => "yay", :ensure => "1.0") end it "should not support version numbers as a value to :ensure if the provider does not have the :versionable feature" do expect(@provider).to receive(:satisfies?).with([:versionable]).and_return(false) expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => "1.0") }.to raise_error(Puppet::Error) end it "should accept any string as an argument to :source" do expect { Puppet::Type.type(:package).new(:name => "yay", :source => "stuff") }.to_not raise_error end it "should not accept a non-string name" do expect do Puppet::Type.type(:package).new(:name => ["error"]) end.to raise_error(Puppet::ResourceError, /Name must be a String/) end end module PackageEvaluationTesting def setprops(properties) allow(@provider).to receive(:properties).and_return(properties) end end describe Puppet::Type.type(:package) do before :each do @provider = double( 'provider', :class => Puppet::Type.type(:package).defaultprovider, :clear => nil, :satisfies? => true, :name => :mock, :validate_source => nil ) allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(@provider) allow(Puppet::Type.type(:package).defaultprovider).to receive(:instances).and_return([]) @package = Puppet::Type.type(:package).new(:name => "yay") @catalog = Puppet::Resource::Catalog.new @catalog.add_resource(@package) end describe Puppet::Type.type(:package), "when it should be purged" do include PackageEvaluationTesting before { @package[:ensure] = :purged } it "should do nothing if it is :purged" do expect(@provider).to receive(:properties).and_return(:ensure => :purged).at_least(:once) @catalog.apply end [:absent, :installed, :present, :latest].each do |state| it "should purge if it is #{state.to_s}" do allow(@provider).to receive(:properties).and_return(:ensure => state) expect(@provider).to receive(:purge) @catalog.apply end end end describe Puppet::Type.type(:package), "when it should be absent" do include PackageEvaluationTesting before { @package[:ensure] = :absent } [:purged, :absent].each do |state| it "should do nothing if it is #{state.to_s}" do expect(@provider).to receive(:properties).and_return(:ensure => state).at_least(:once) @catalog.apply end end [:installed, :present, :latest].each do |state| it "should uninstall if it is #{state.to_s}" do allow(@provider).to receive(:properties).and_return(:ensure => state) expect(@provider).to receive(:uninstall) @catalog.apply end end end describe Puppet::Type.type(:package), "when it should be present" do include PackageEvaluationTesting before { @package[:ensure] = :present } [:present, :latest, "1.0"].each do |state| it "should do nothing if it is #{state.to_s}" do expect(@provider).to receive(:properties).and_return(:ensure => state).at_least(:once) @catalog.apply end end [:purged, :absent].each do |state| it "should install if it is #{state.to_s}" do allow(@provider).to receive(:properties).and_return(:ensure => state) expect(@provider).to receive(:install) @catalog.apply end end end describe Puppet::Type.type(:package), "when it should be latest" do include PackageEvaluationTesting before { @package[:ensure] = :latest } [:purged, :absent].each do |state| it "should upgrade if it is #{state.to_s}" do allow(@provider).to receive(:properties).and_return(:ensure => state) expect(@provider).to receive(:update) @catalog.apply end end it "should upgrade if the current version is not equal to the latest version" do allow(@provider).to receive(:properties).and_return(:ensure => "1.0") allow(@provider).to receive(:latest).and_return("2.0") expect(@provider).to receive(:update) @catalog.apply end it "should do nothing if it is equal to the latest version" do allow(@provider).to receive(:properties).and_return(:ensure => "1.0") allow(@provider).to receive(:latest).and_return("1.0") expect(@provider).not_to receive(:update) @catalog.apply end it "should do nothing if the provider returns :present as the latest version" do allow(@provider).to receive(:properties).and_return(:ensure => :present) allow(@provider).to receive(:latest).and_return("1.0") expect(@provider).not_to receive(:update) @catalog.apply end end describe Puppet::Type.type(:package), "when it should be a specific version" do include PackageEvaluationTesting before { @package[:ensure] = "1.0" } [:purged, :absent].each do |state| it "should install if it is #{state.to_s}" do allow(@provider).to receive(:properties).and_return(:ensure => state) expect(@package.property(:ensure).insync?(state)).to be_falsey expect(@provider).to receive(:install) @catalog.apply end end it "should do nothing if the current version is equal to the desired version" do allow(@provider).to receive(:properties).and_return(:ensure => "1.0") expect(@package.property(:ensure).insync?('1.0')).to be_truthy expect(@provider).not_to receive(:install) @catalog.apply end it "should install if the current version is not equal to the specified version" do allow(@provider).to receive(:properties).and_return(:ensure => "2.0") expect(@package.property(:ensure).insync?('2.0')).to be_falsey expect(@provider).to receive(:install) @catalog.apply end describe "when current value is an array" do let(:installed_versions) { ["1.0", "2.0", "3.0"] } before (:each) do allow(@provider).to receive(:properties).and_return(:ensure => installed_versions) end it "should install if value not in the array" do @package[:ensure] = "1.5" expect(@package.property(:ensure).insync?(installed_versions)).to be_falsey expect(@provider).to receive(:install) @catalog.apply end it "should not install if value is in the array" do @package[:ensure] = "2.0" expect(@package.property(:ensure).insync?(installed_versions)).to be_truthy expect(@provider).not_to receive(:install) @catalog.apply end describe "when ensure is set to 'latest'" do it "should not install if the value is in the array" do expect(@provider).to receive(:latest).and_return("3.0") @package[:ensure] = "latest" expect(@package.property(:ensure).insync?(installed_versions)).to be_truthy expect(@provider).not_to receive(:install) @catalog.apply end end end end describe Puppet::Type.type(:package), "when responding to refresh" do include PackageEvaluationTesting it "should support :true as a value to :reinstall_on_refresh" do srv = Puppet::Type.type(:package).new(:name => "yay", :reinstall_on_refresh => :true) expect(srv[:reinstall_on_refresh]).to eq(:true) end it "should support :false as a value to :reinstall_on_refresh" do srv = Puppet::Type.type(:package).new(:name => "yay", :reinstall_on_refresh => :false) expect(srv[:reinstall_on_refresh]).to eq(:false) end it "should specify :false as the default value of :reinstall_on_refresh" do srv = Puppet::Type.type(:package).new(:name => "yay") expect(srv[:reinstall_on_refresh]).to eq(:false) end [:latest, :present, :installed].each do |state| it "should reinstall if it should be #{state.to_s} and reinstall_on_refresh is true" do @package[:ensure] = state @package[:reinstall_on_refresh] = :true allow(@provider).to receive(:reinstallable?).and_return(true) expect(@provider).to receive(:reinstall).once @package.refresh end it "should reinstall if it should be #{state.to_s} and reinstall_on_refresh is false" do @package[:ensure] = state @package[:reinstall_on_refresh] = :false allow(@provider).to receive(:reinstallable?).and_return(true) expect(@provider).not_to receive(:reinstall) @package.refresh end end [:purged, :absent].each do |state| it "should not reinstall if it should be #{state.to_s} and reinstall_on_refresh is true" do @package[:ensure] = state allow(@provider).to receive(:reinstallable?).and_return(true) expect(@provider).not_to receive(:reinstall) @package.refresh end it "should not reinstall if it should be #{state.to_s} and reinstall_on_refresh is false" do @package[:ensure] = state allow(@provider).to receive(:reinstallable?).and_return(true) expect(@provider).not_to receive(:reinstall) @package.refresh end end end end it "should select dnf over yum for dnf supported fedora versions" do dnf = Puppet::Type.type(:package).provider(:dnf) yum = Puppet::Type.type(:package).provider(:yum) allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:fedora) allow(Facter).to receive(:value).with('os.release.major').and_return("22") expect(dnf.specificity).to be > yum.specificity end describe "allow_virtual" do it "defaults to true on platforms that support virtual packages" do pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :yum) expect(pkg[:allow_virtual]).to eq true end it "defaults to false on dpkg provider" do pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :dpkg) expect(pkg[:allow_virtual]).to be_nil end it "defaults to false on platforms that do not support virtual packages" do pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :apple) expect(pkg[:allow_virtual]).to be_nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/schedule_spec.rb
spec/unit/type/schedule_spec.rb
require 'spec_helper' module ScheduleTesting def diff(unit, incr, method, count) diff = Time.now.to_i.send(method, incr * count) Time.at(diff) end def day(method, count) diff(:hour, 3600 * 24, method, count) end def hour(method, count) diff(:hour, 3600, method, count) end def min(method, count) diff(:min, 60, method, count) end end describe Puppet::Type.type(:schedule) do include ScheduleTesting before :each do Puppet[:ignoreschedules] = false @schedule = Puppet::Type.type(:schedule).new(:name => "testing") end describe Puppet::Type.type(:schedule) do it "should apply to device" do expect(@schedule).to be_appliable_to_device end it "should apply to host" do expect(@schedule).to be_appliable_to_host end it "should default to :distance for period-matching" do expect(@schedule[:periodmatch]).to eq(:distance) end it "should default to a :repeat of 1" do expect(@schedule[:repeat]).to eq(1) end it "should never match when the period is :never" do @schedule[:period] = :never expect(@schedule).to_not be_match end end describe Puppet::Type.type(:schedule), "when producing default schedules" do %w{hourly daily weekly monthly never}.each do |period| period = period.to_sym it "should produce a #{period} schedule with the period set appropriately" do schedules = Puppet::Type.type(:schedule).mkdefaultschedules expect(schedules.find { |s| s[:name] == period.to_s and s[:period] == period }).to be_instance_of(Puppet::Type.type(:schedule)) end end it "should not produce default schedules when default_schedules is false" do Puppet[:default_schedules] = false schedules = Puppet::Type.type(:schedule).mkdefaultschedules expect(schedules).to be_empty end it "should produce a schedule named puppet with a period of hourly and a repeat of 2" do schedules = Puppet::Type.type(:schedule).mkdefaultschedules expect(schedules.find { |s| s[:name] == "puppet" and s[:period] == :hourly and s[:repeat] == 2 }).to be_instance_of(Puppet::Type.type(:schedule)) end end describe Puppet::Type.type(:schedule), "when matching ranges" do before do allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0)) end it "should match when the start time is before the current time and the end time is after the current time" do @schedule[:range] = "10:59:50 - 11:00:10" expect(@schedule).to be_match end it "should not match when the start time is after the current time" do @schedule[:range] = "11:00:05 - 11:00:10" expect(@schedule).to_not be_match end it "should not match when the end time is previous to the current time" do @schedule[:range] = "10:59:50 - 10:59:55" expect(@schedule).to_not be_match end it "should not match the current time fails between an array of ranges" do @schedule[:range] = ["4-6", "20-23"] expect(@schedule).to_not be_match end it "should match the lower array of ranges" do @schedule[:range] = ["9-11", "14-16"] expect(@schedule).to be_match end it "should match the upper array of ranges" do @schedule[:range] = ["11:30 - 6", "11-12"] expect(@schedule).to be_match end end describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications" do before do allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 45, 59)) end it "should match when just an hour is specified" do @schedule[:range] = "11-12" expect(@schedule).to be_match end it "should not match when the ending hour is the current hour" do @schedule[:range] = "10-11" expect(@schedule).to_not be_match end it "should not match when the ending minute is the current minute" do @schedule[:range] = "10:00 - 11:45" expect(@schedule).to_not be_match end end describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 1" do before do allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 00, 00)) end it "should match when the current time is the start of the range using hours" do @schedule[:range] = "11 - 12" expect(@schedule).to be_match end it "should match when the current time is the end of the range using hours" do @schedule[:range] = "10 - 11" expect(@schedule).to be_match end it "should match when the current time is the start of the range using hours and minutes" do @schedule[:range] = "11:00 - 12:00" expect(@schedule).to be_match end it "should match when the current time is the end of the range using hours and minutes" do @schedule[:range] = "10:00 - 11:00" expect(@schedule).to be_match end end describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 2" do before do allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 00, 01)) end it "should match when the current time is just past the start of the range using hours" do @schedule[:range] = "11 - 12" expect(@schedule).to be_match end it "should not match when the current time is just past the end of the range using hours" do @schedule[:range] = "10 - 11" expect(@schedule).to_not be_match end it "should match when the current time is just past the start of the range using hours and minutes" do @schedule[:range] = "11:00 - 12:00" expect(@schedule).to be_match end it "should not match when the current time is just past the end of the range using hours and minutes" do @schedule[:range] = "10:00 - 11:00" expect(@schedule).to_not be_match end end describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 3" do before do allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 10, 59, 59)) end it "should not match when the current time is just before the start of the range using hours" do @schedule[:range] = "11 - 12" expect(@schedule).to_not be_match end it "should match when the current time is just before the end of the range using hours" do @schedule[:range] = "10 - 11" expect(@schedule).to be_match end it "should not match when the current time is just before the start of the range using hours and minutes" do @schedule[:range] = "11:00 - 12:00" expect(@schedule).to_not be_match end it "should match when the current time is just before the end of the range using hours and minutes" do @schedule[:range] = "10:00 - 11:00" expect(@schedule).to be_match end end describe Puppet::Type.type(:schedule), "when matching ranges spanning days, day 1" do before do # Test with the current time at a month's end boundary to ensure we are # advancing the day properly when we push the ending limit out a day. # For example, adding 1 to 31 would throw an error instead of advancing # the date. allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 22, 30, 0)) end it "should match when the start time is before current time and the end time is the following day" do @schedule[:range] = "22:00:00 - 02:00:00" expect(@schedule).to be_match end it "should not match when the current time is outside the range" do @schedule[:range] = "23:30:00 - 21:00:00" expect(@schedule).to_not be_match end end describe Puppet::Type.type(:schedule), "when matching ranges spanning days, day 2" do before do # Test with the current time at a month's end boundary to ensure we are # advancing the day properly when we push the ending limit out a day. # For example, adding 1 to 31 would throw an error instead of advancing # the date. allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 1, 30, 0)) end it "should match when the start time is the day before the current time and the end time is after the current time" do @schedule[:range] = "22:00:00 - 02:00:00" expect(@schedule).to be_match end it "should not match when the start time is after the current time" do @schedule[:range] = "02:00:00 - 00:30:00" expect(@schedule).to_not be_match end it "should not match when the end time is before the current time" do @schedule[:range] = "22:00:00 - 01:00:00" expect(@schedule).to_not be_match end end describe Puppet::Type.type(:schedule), "when matching hourly by distance" do before do @schedule[:period] = :hourly @schedule[:periodmatch] = :distance allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0)) end it "should match when the previous time was an hour ago" do expect(@schedule).to be_match(hour("-", 1)) end it "should not match when the previous time was now" do expect(@schedule).to_not be_match(Time.now) end it "should not match when the previous time was 59 minutes ago" do expect(@schedule).to_not be_match(min("-", 59)) end end describe Puppet::Type.type(:schedule), "when matching daily by distance" do before do @schedule[:period] = :daily @schedule[:periodmatch] = :distance allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0)) end it "should match when the previous time was one day ago" do expect(@schedule).to be_match(day("-", 1)) end it "should not match when the previous time is now" do expect(@schedule).to_not be_match(Time.now) end it "should not match when the previous time was 23 hours ago" do expect(@schedule).to_not be_match(hour("-", 23)) end end describe Puppet::Type.type(:schedule), "when matching weekly by distance" do before do @schedule[:period] = :weekly @schedule[:periodmatch] = :distance allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0)) end it "should match when the previous time was seven days ago" do expect(@schedule).to be_match(day("-", 7)) end it "should not match when the previous time was now" do expect(@schedule).to_not be_match(Time.now) end it "should not match when the previous time was six days ago" do expect(@schedule).to_not be_match(day("-", 6)) end end describe Puppet::Type.type(:schedule), "when matching monthly by distance" do before do @schedule[:period] = :monthly @schedule[:periodmatch] = :distance allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0)) end it "should match when the previous time was 32 days ago" do expect(@schedule).to be_match(day("-", 32)) end it "should not match when the previous time was now" do expect(@schedule).to_not be_match(Time.now) end it "should not match when the previous time was 27 days ago" do expect(@schedule).to_not be_match(day("-", 27)) end end describe Puppet::Type.type(:schedule), "when matching hourly by number" do before do @schedule[:period] = :hourly @schedule[:periodmatch] = :number end it "should match if the times are one minute apart and the current minute is 0" do current = Time.utc(2008, 1, 1, 0, 0, 0) previous = Time.utc(2007, 12, 31, 23, 59, 0) allow(Time).to receive(:now).and_return(current) expect(@schedule).to be_match(previous) end it "should not match if the times are 59 minutes apart and the current minute is 59" do current = Time.utc(2009, 2, 1, 12, 59, 0) previous = Time.utc(2009, 2, 1, 12, 0, 0) allow(Time).to receive(:now).and_return(current) expect(@schedule).to_not be_match(previous) end end describe Puppet::Type.type(:schedule), "when matching daily by number" do before do @schedule[:period] = :daily @schedule[:periodmatch] = :number end it "should match if the times are one minute apart and the current minute and hour are 0" do current = Time.utc(2010, "nov", 7, 0, 0, 0) # Now set the previous time to one minute before that previous = current - 60 allow(Time).to receive(:now).and_return(current) expect(@schedule).to be_match(previous) end it "should not match if the times are 23 hours and 58 minutes apart and the current hour is 23 and the current minute is 59" do # Reset the previous time to 00:00:00 previous = Time.utc(2010, "nov", 7, 0, 0, 0) # Set the current time to 23:59 now = previous + (23 * 3600) + (59 * 60) allow(Time).to receive(:now).and_return(now) expect(@schedule).to_not be_match(previous) end end describe Puppet::Type.type(:schedule), "when matching weekly by number" do before do @schedule[:period] = :weekly @schedule[:periodmatch] = :number end it "should match if the previous time is prior to the most recent Sunday" do now = Time.utc(2010, "nov", 11, 0, 0, 0) # Thursday allow(Time).to receive(:now).and_return(now) previous = Time.utc(2010, "nov", 6, 23, 59, 59) # Sat expect(@schedule).to be_match(previous) end it "should not match if the previous time is after the most recent Saturday" do now = Time.utc(2010, "nov", 11, 0, 0, 0) # Thursday allow(Time).to receive(:now).and_return(now) previous = Time.utc(2010, "nov", 7, 0, 0, 0) # Sunday expect(@schedule).to_not be_match(previous) end end describe Puppet::Type.type(:schedule), "when matching monthly by number" do before do @schedule[:period] = :monthly @schedule[:periodmatch] = :number end it "should match when the previous time is prior to the first day of this month" do now = Time.utc(2010, "nov", 8, 00, 59, 59) allow(Time).to receive(:now).and_return(now) previous = Time.utc(2010, "oct", 31, 23, 59, 59) expect(@schedule).to be_match(previous) end it "should not match when the previous time is after the last day of last month" do now = Time.utc(2010, "nov", 8, 00, 59, 59) allow(Time).to receive(:now).and_return(now) previous = Time.utc(2010, "nov", 1, 0, 0, 0) expect(@schedule).to_not be_match(previous) end end describe Puppet::Type.type(:schedule), "when matching with a repeat greater than one" do before do @schedule[:period] = :daily @schedule[:repeat] = 2 allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0)) end it "should fail if the periodmatch is 'number'" do @schedule[:periodmatch] = :number expect { @schedule[:repeat] = 2 }.to raise_error(Puppet::Error) end it "should match if the previous run was further away than the distance divided by the repeat" do previous = Time.now - (3600 * 13) expect(@schedule).to be_match(previous) end it "should not match if the previous run was closer than the distance divided by the repeat" do previous = Time.now - (3600 * 11) expect(@schedule).to_not be_match(previous) end end describe Puppet::Type.type(:schedule), "when matching days of the week" do before do # 2011-05-23 is a Monday allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0)) end it "should raise an error if the weekday is 'Someday'" do expect { @schedule[:weekday] = "Someday" }.to raise_error(Puppet::Error) end it "should raise an error if the weekday is '7'" do expect { @schedule[:weekday] = "7" }.to raise_error(Puppet::Error) end it "should accept all full weekday names as valid values" do expect { @schedule[:weekday] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] }.not_to raise_error end it "should accept all short weekday names as valid values" do expect { @schedule[:weekday] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] }.not_to raise_error end it "should accept all integers 0-6 as valid values" do expect {@schedule[:weekday] = [0, 1, 2, 3, 4, 5, 6] }.not_to raise_error end it "should match if the weekday is 'Monday'" do @schedule[:weekday] = "Monday" expect(@schedule.match?).to be_truthy end it "should match if the weekday is 'Mon'" do @schedule[:weekday] = "Mon" expect(@schedule.match?).to be_truthy end it "should match if the weekday is '1'" do @schedule[:weekday] = "1" expect(@schedule.match?).to be_truthy end it "should match if weekday is 1" do @schedule[:weekday] = 1 expect(@schedule).to be_match end it "should not match if the weekday is Tuesday" do @schedule[:weekday] = "Tuesday" expect(@schedule).not_to be_match end it "should match if weekday is ['Sun', 'Mon']" do @schedule[:weekday] = ["Sun", "Mon"] expect(@schedule.match?).to be_truthy end it "should not match if weekday is ['Sun', 'Tue']" do @schedule[:weekday] = ["Sun", "Tue"] expect(@schedule).not_to be_match end it "should match if the weekday is 'Monday'" do @schedule[:weekday] = "Monday" expect(@schedule.match?).to be_truthy end it "should match if the weekday is 'Mon'" do @schedule[:weekday] = "Mon" expect(@schedule.match?).to be_truthy end it "should match if the weekday is '1'" do @schedule[:weekday] = "1" expect(@schedule.match?).to be_truthy end it "should not match if the weekday is Tuesday" do @schedule[:weekday] = "Tuesday" expect(@schedule).not_to be_match end it "should match if weekday is ['Sun', 'Mon']" do @schedule[:weekday] = ["Sun", "Mon"] expect(@schedule.match?).to be_truthy end end it "should raise an error if the weekday is an int higher than 6" do expect { @schedule[:weekday] = 7 }.to raise_error(Puppet::ResourceError, /7 is not a valid day of the week/) end describe Puppet::Type.type(:schedule), "when matching days of week and ranges spanning days, day 1" do before do # Test with ranges and days-of-week both set. 2011-03-31 was a Thursday. allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 22, 30, 0)) end it "should match when the range and day of week matches" do @schedule[:range] = "22:00:00 - 02:00:00" @schedule[:weekday] = "Thursday" expect(@schedule).to be_match end it "should not match when the range doesn't match even if the day-of-week matches" do @schedule[:range] = "23:30:00 - 21:00:00" @schedule[:weekday] = "Thursday" expect(@schedule).to_not be_match end it "should not match when day-of-week doesn't match even if the range matches (1 day later)" do @schedule[:range] = "22:00:00 - 01:00:00" @schedule[:weekday] = "Friday" expect(@schedule).to_not be_match end it "should not match when day-of-week doesn't match even if the range matches (1 day earlier)" do @schedule[:range] = "22:00:00 - 01:00:00" @schedule[:weekday] = "Wednesday" expect(@schedule).to_not be_match end end describe Puppet::Type.type(:schedule), "when matching days of week and ranges spanning days, day 2" do before do # 2011-03-31 was a Thursday. As the end-time of a day spanning match, that means # we need to match on Wednesday. allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 1, 30, 0)) end it "should match when the range matches and the day of week should match" do @schedule[:range] = "22:00:00 - 02:00:00" @schedule[:weekday] = "Wednesday" expect(@schedule).to be_match end it "should not match when the range does not match and the day of week should match" do @schedule[:range] = "22:00:00 - 01:00:00" @schedule[:weekday] = "Thursday" expect(@schedule).to_not be_match end it "should not match when the range matches but the day-of-week does not (1 day later)" do @schedule[:range] = "22:00:00 - 02:00:00" @schedule[:weekday] = "Thursday" expect(@schedule).to_not be_match end it "should not match when the range matches but the day-of-week does not (1 day later)" do @schedule[:range] = "22:00:00 - 02:00:00" @schedule[:weekday] = "Tuesday" expect(@schedule).to_not be_match end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/service_spec.rb
spec/unit/type/service_spec.rb
require 'spec_helper' def safely_load_service_type before(:each) do # We have a :confine block that calls execute in our upstart provider, which fails # on jruby. Thus, we stub it out here since we don't care to do any assertions on it. # This is only an issue if you're running these unit tests on a platform where upstart # is a default provider, like Ubuntu trusty. allow(Puppet::Util::Execution).to receive(:execute) Puppet::Type.type(:service) end end test_title = 'Puppet::Type::Service' describe test_title do safely_load_service_type it "should have an :enableable feature that requires the :enable, :disable, and :enabled? methods" do expect(Puppet::Type.type(:service).provider_feature(:enableable).methods).to eq([:disable, :enable, :enabled?]) end it "should have a :refreshable feature that requires the :restart method" do expect(Puppet::Type.type(:service).provider_feature(:refreshable).methods).to eq([:restart]) end end describe test_title, "when validating attributes" do safely_load_service_type [:name, :binary, :hasstatus, :path, :pattern, :start, :restart, :stop, :status, :hasrestart, :control, :timeout].each do |param| it "should have a #{param} parameter" do expect(Puppet::Type.type(:service).attrtype(param)).to eq(:param) end end [:ensure, :enable].each do |param| it "should have an #{param} property" do expect(Puppet::Type.type(:service).attrtype(param)).to eq(:property) end end end describe test_title, "when validating attribute values" do safely_load_service_type before do @provider = double('provider', :class => Puppet::Type.type(:service).defaultprovider, :clear => nil, :controllable? => false) allow(Puppet::Type.type(:service).defaultprovider).to receive(:new).and_return(@provider) end it "should support :running as a value to :ensure" do Puppet::Type.type(:service).new(:name => "yay", :ensure => :running) end it "should support :stopped as a value to :ensure" do Puppet::Type.type(:service).new(:name => "yay", :ensure => :stopped) end it "should alias the value :true to :running in :ensure" do svc = Puppet::Type.type(:service).new(:name => "yay", :ensure => true) expect(svc.should(:ensure)).to eq(:running) end it "should alias the value :false to :stopped in :ensure" do svc = Puppet::Type.type(:service).new(:name => "yay", :ensure => false) expect(svc.should(:ensure)).to eq(:stopped) end describe "the enable property" do before :each do allow(@provider.class).to receive(:supports_parameter?).and_return(true) end describe "for value without required features" do before :each do allow(@provider).to receive(:satisfies?) end it "should not support :mask as a value" do expect { Puppet::Type.type(:service).new(:name => "yay", :enable => :mask) }.to raise_error( Puppet::ResourceError, /Provider .+ must have features 'maskable' to set 'enable' to 'mask'/ ) end it "should not support :manual as a value" do expect { Puppet::Type.type(:service).new(:name => "yay", :enable => :manual) }.to raise_error( Puppet::ResourceError, /Provider .+ must have features 'manual_startable' to set 'enable' to 'manual'/ ) end it "should not support :mask as a value" do expect { Puppet::Type.type(:service).new(:name => "yay", :enable => :delayed) }.to raise_error( Puppet::ResourceError, /Provider .+ must have features 'delayed_startable' to set 'enable' to 'delayed'/ ) end end describe "for value with required features" do before :each do allow(@provider).to receive(:satisfies?).and_return(:true) end it "should support :true as a value" do srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :true) expect(srv.should(:enable)).to eq(:true) end it "should support :false as a value" do srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :false) expect(srv.should(:enable)).to eq(:false) end it "should support :mask as a value" do srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :mask) expect(srv.should(:enable)).to eq(:mask) end it "should support :manual as a value on Windows" do allow(Puppet::Util::Platform).to receive(:windows?).and_return(true) srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :manual) expect(srv.should(:enable)).to eq(:manual) end it "should support :delayed as a value on Windows" do allow(Puppet::Util::Platform).to receive(:windows?).and_return(true) srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :delayed) expect(srv.should(:enable)).to eq(:delayed) end end end describe "the timeout parameter" do before do provider_class_with_timeout = Puppet::Type.type(:service).provide(:simple) do has_features :configurable_timeout end allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class_with_timeout) end it "should fail when timeout is not an integer" do expect { Puppet::Type.type(:service).new(:name => "yay", :timeout => 'foobar') }.to raise_error(Puppet::Error) end [-999, -1, 0].each do |int| it "should not support #{int} as a value to :timeout" do expect { Puppet::Type.type(:service).new(:name => "yay", :timeout => int) }.to raise_error(Puppet::Error) end end [1, 30, 999].each do |int| it "should support #{int} as a value to :timeout" do srv = Puppet::Type.type(:service).new(:name => "yay", :timeout => int) expect(srv[:timeout]).to eq(int) end end it "should default :timeout to 10 when provider has no default value" do srv = Puppet::Type.type(:service).new(:name => "yay") expect(srv[:timeout]).to eq(10) end it "should default :timeout to provider given default time when it has one" do provider_class_with_timeout = Puppet::Type.type(:service).provide(:simple) do has_features :configurable_timeout def default_timeout 30 end end allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class_with_timeout) srv = Puppet::Type.type(:service).new(:name => "yay") expect(srv[:timeout]).to eq(30) end it "should accept string as value" do srv = Puppet::Type.type(:service).new(:name => "yay", :timeout => "25") expect(srv[:timeout]).to eq(25) end it "should not support values that cannot be converted to Integer such as Array" do expect { Puppet::Type.type(:service).new(:name => "yay", :timeout => [25]) }.to raise_error(Puppet::Error) end end describe "the service logon credentials" do before do provider_class_with_logon_credentials = Puppet::Type.type(:service).provide(:simple) do has_features :manages_logon_credentials def logonpassword=(value) end def logonaccount_insync?(current) end end allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class_with_logon_credentials) end describe "the 'logonaccount' property" do let(:service) {Puppet::Type.type(:service).new(:name => "yay", :logonaccount => 'myUser')} it "should let superclass implementation resolve insyncness when provider does not respond to the 'logonaccount_insync?' method" do allow(service.provider).to receive(:respond_to?).with(:logonaccount_insync?).and_return(false) expect(service.property(:logonaccount).insync?('myUser')).to eq(true) end it "should let provider resolve insyncness when provider responds to the 'logonaccount_insync?' method" do allow(service.provider).to receive(:respond_to?).with(:logonaccount_insync?, any_args).and_return(true) allow(service.provider).to receive(:logonaccount_insync?).and_return(false) expect(service.property(:logonaccount).insync?('myUser')).to eq(false) end end describe "the logonpassword parameter" do it "should fail when logonaccount is not being managed as well" do expect { Puppet::Type.type(:service).new(:name => "yay", :logonpassword => 'myPass') }.to raise_error(Puppet::Error, /The 'logonaccount' parameter is mandatory when setting 'logonpassword'./) end it "should default to empty string when only logonaccount is being managed" do service = Puppet::Type.type(:service).new(:name => "yay", :logonaccount => 'myUser') expect { service }.not_to raise_error expect(service[:logonpassword]).to eq("") end it "should default to nil when not even logonaccount is being managed" do service = Puppet::Type.type(:service).new(:name => "yay") expect(service[:logonpassword]).to eq(nil) end it "should fail when logonpassword includes the ':' character" do expect { Puppet::Type.type(:service).new(:name => "yay", :logonaccount => 'myUser', :logonpassword => 'my:Pass') }.to raise_error(Puppet::Error, /Passwords cannot include ':'/) end end end it "should support :true as a value to :hasstatus" do srv = Puppet::Type.type(:service).new(:name => "yay", :hasstatus => :true) expect(srv[:hasstatus]).to eq(:true) end it "should support :false as a value to :hasstatus" do srv = Puppet::Type.type(:service).new(:name => "yay", :hasstatus => :false) expect(srv[:hasstatus]).to eq(:false) end it "should specify :true as the default value of hasstatus" do srv = Puppet::Type.type(:service).new(:name => "yay") expect(srv[:hasstatus]).to eq(:true) end it "should support :true as a value to :hasrestart" do srv = Puppet::Type.type(:service).new(:name => "yay", :hasrestart => :true) expect(srv[:hasrestart]).to eq(:true) end it "should support :false as a value to :hasrestart" do srv = Puppet::Type.type(:service).new(:name => "yay", :hasrestart => :false) expect(srv[:hasrestart]).to eq(:false) end it "should allow setting the :enable parameter if the provider has the :enableable feature" do allow(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).and_return(true) expect(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).with(Puppet::Type.type(:service).attrclass(:enable)).and_return(true) svc = Puppet::Type.type(:service).new(:name => "yay", :enable => true) expect(svc.should(:enable)).to eq(:true) end it "should not allow setting the :enable parameter if the provider is missing the :enableable feature" do allow(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).and_return(true) expect(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).with(Puppet::Type.type(:service).attrclass(:enable)).and_return(false) svc = Puppet::Type.type(:service).new(:name => "yay", :enable => true) expect(svc.should(:enable)).to be_nil end it "should split paths on '#{File::PATH_SEPARATOR}'" do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(FileTest).to receive(:directory?).and_return(true) svc = Puppet::Type.type(:service).new(:name => "yay", :path => "/one/two#{File::PATH_SEPARATOR}/three/four") expect(svc[:path]).to eq(%w{/one/two /three/four}) end it "should accept arrays of paths joined by '#{File::PATH_SEPARATOR}'" do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(FileTest).to receive(:directory?).and_return(true) svc = Puppet::Type.type(:service).new(:name => "yay", :path => ["/one#{File::PATH_SEPARATOR}/two", "/three#{File::PATH_SEPARATOR}/four"]) expect(svc[:path]).to eq(%w{/one /two /three /four}) end end describe test_title, "when setting default attribute values" do safely_load_service_type it "should default to the provider's default path if one is available" do allow(FileTest).to receive(:directory?).and_return(true) allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(Puppet::Type.type(:service).defaultprovider).to receive(:respond_to?).and_return(true) allow(Puppet::Type.type(:service).defaultprovider).to receive(:defpath).and_return("testing") svc = Puppet::Type.type(:service).new(:name => "other") expect(svc[:path]).to eq(["testing"]) end it "should default 'pattern' to the binary if one is provided" do svc = Puppet::Type.type(:service).new(:name => "other", :binary => "/some/binary") expect(svc[:pattern]).to eq("/some/binary") end it "should default 'pattern' to the name if no pattern is provided" do svc = Puppet::Type.type(:service).new(:name => "other") expect(svc[:pattern]).to eq("other") end it "should default 'control' to the upcased service name with periods replaced by underscores if the provider supports the 'controllable' feature" do provider = double('provider', :controllable? => true, :class => Puppet::Type.type(:service).defaultprovider, :clear => nil) allow(Puppet::Type.type(:service).defaultprovider).to receive(:new).and_return(provider) svc = Puppet::Type.type(:service).new(:name => "nfs.client") expect(svc[:control]).to eq("NFS_CLIENT_START") end end describe test_title, "when retrieving the host's current state" do safely_load_service_type before do @service = Puppet::Type.type(:service).new(:name => "yay") end it "should use the provider's status to determine whether the service is running" do expect(@service.provider).to receive(:status).and_return(:yepper) @service[:ensure] = :running expect(@service.property(:ensure).retrieve).to eq(:yepper) end it "should ask the provider whether it is enabled" do allow(@service.provider.class).to receive(:supports_parameter?).and_return(true) expect(@service.provider).to receive(:enabled?).and_return(:yepper) @service[:enable] = true expect(@service.property(:enable).retrieve).to eq(:yepper) end end describe test_title, "when changing the host" do safely_load_service_type before do @service = Puppet::Type.type(:service).new(:name => "yay") end it "should start the service if it is supposed to be running" do @service[:ensure] = :running expect(@service.provider).to receive(:start) @service.property(:ensure).sync end it "should stop the service if it is supposed to be stopped" do @service[:ensure] = :stopped expect(@service.provider).to receive(:stop) @service.property(:ensure).sync end it "should enable the service if it is supposed to be enabled" do allow(@service.provider.class).to receive(:supports_parameter?).and_return(true) @service[:enable] = true expect(@service.provider).to receive(:enable) @service.property(:enable).sync end it "should disable the service if it is supposed to be disabled" do allow(@service.provider.class).to receive(:supports_parameter?).and_return(true) @service[:enable] = false expect(@service.provider).to receive(:disable) @service.property(:enable).sync end it "should let superclass implementation resolve insyncness when provider does not respond to the 'enabled_insync?' method" do allow(@service.provider.class).to receive(:supports_parameter?).and_return(true) @service[:enable] = true allow(@service.provider).to receive(:respond_to?).with(:enabled_insync?).and_return(false) expect(@service.property(:enable).insync?(:true)).to eq(true) end it "insyncness should be resolved by provider instead of superclass implementation when provider responds to the 'enabled_insync?' method" do allow(@service.provider.class).to receive(:supports_parameter?).and_return(true) @service[:enable] = true allow(@service.provider).to receive(:respond_to?).with(:enabled_insync?, any_args).and_return(true) allow(@service.provider).to receive(:enabled_insync?).and_return(false) expect(@service.property(:enable).insync?(:true)).to eq(false) end it "should sync the service's enable state when changing the state of :ensure if :enable is being managed" do allow(@service.provider.class).to receive(:supports_parameter?).and_return(true) @service[:enable] = false @service[:ensure] = :stopped expect(@service.property(:enable)).to receive(:retrieve).and_return("whatever") expect(@service.property(:enable)).to receive(:insync?).and_return(false) expect(@service.property(:enable)).to receive(:sync) allow(@service.provider).to receive(:stop) @service.property(:ensure).sync end it "should sync the service's logonaccount state when changing the state of :ensure if :logonaccount is being managed" do allow(@service.provider.class).to receive(:supports_parameter?).and_return(true) allow(Puppet::Util::Platform).to receive(:windows?).and_return(false) @service[:ensure] = :stopped @service[:logonaccount] = 'LocalSystem' expect(@service.property(:logonaccount)).to receive(:retrieve).and_return("MyUser") expect(@service.property(:logonaccount)).to receive(:insync?).and_return(false) expect(@service.property(:logonaccount)).to receive(:sync) allow(@service.provider).to receive(:stop) @service.property(:ensure).sync end end describe test_title, "when refreshing the service" do safely_load_service_type before do @service = Puppet::Type.type(:service).new(:name => "yay") end it "should restart the service if it is running" do @service[:ensure] = :running expect(@service.provider).to receive(:status).and_return(:running) expect(@service.provider).to receive(:restart) @service.refresh end it "should restart the service if it is running, even if it is supposed to stopped" do @service[:ensure] = :stopped expect(@service.provider).to receive(:status).and_return(:running) expect(@service.provider).to receive(:restart) @service.refresh end it "should not restart the service if it is not running" do @service[:ensure] = :running expect(@service.provider).to receive(:status).and_return(:stopped) @service.refresh end it "should add :ensure as a property if it is not being managed" do expect(@service.provider).to receive(:status).and_return(:running) expect(@service.provider).to receive(:restart) @service.refresh end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/noop_metaparam_spec.rb
spec/unit/type/noop_metaparam_spec.rb
require 'spec_helper' require 'puppet/type' describe Puppet::Type.type(:file).attrclass(:noop) do include PuppetSpec::Files before do allow(Puppet.settings).to receive(:use) @file = Puppet::Type.newfile :path => make_absolute("/what/ever") end it "should accept true as a value" do expect { @file[:noop] = true }.not_to raise_error end it "should accept false as a value" do expect { @file[:noop] = false }.not_to raise_error end describe "when set on a resource" do it "should default to the :noop setting" do Puppet[:noop] = true expect(@file.noop).to eq(true) end it "should prefer true values from the attribute" do @file[:noop] = true expect(@file.noop).to be_truthy end it "should prefer false values from the attribute" do @file[:noop] = false expect(@file.noop).to be_falsey end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/resources_spec.rb
spec/unit/type/resources_spec.rb
require 'spec_helper' # A type and provider that can be purged Puppet::Type.newtype(:purgeable_test) do ensurable newparam(:name) {} end Puppet::Type.type(:purgeable_test).provide(:purgeable_test) do def self.instances [] end end resources = Puppet::Type.type(:resources) # There are still plenty of tests to port over from test/. describe resources do before :each do described_class.reset_system_users_max_uid! end context "when initializing" do it "should fail if the specified resource type does not exist" do allow(Puppet::Type).to receive(:type) do expect(x.to_s.downcase).to eq("resources") end.and_return(resources) expect(Puppet::Type).to receive(:type).with("nosuchtype").and_return(nil) expect { resources.new :name => "nosuchtype" }.to raise_error(Puppet::Error) end it "should not fail when the specified resource type exists" do expect { resources.new :name => "file" }.not_to raise_error end it "should set its :resource_type attribute" do expect(resources.new(:name => "file").resource_type).to eq(Puppet::Type.type(:file)) end end context "purge" do let (:instance) { described_class.new(:name => 'file') } it "defaults to false" do expect(instance[:purge]).to be_falsey end it "can be set to false" do instance[:purge] = 'false' end it "cannot be set to true for a resource type that does not accept ensure" do allow(instance.resource_type).to receive(:validproperty?).with(:ensure).and_return(false) expect { instance[:purge] = 'yes' }.to raise_error Puppet::Error, /Purging is only supported on types that accept 'ensure'/ end it "cannot be set to true for a resource type that does not have instances" do allow(instance.resource_type).to receive(:respond_to?).with(:instances).and_return(false) expect { instance[:purge] = 'yes' }.to raise_error Puppet::Error, /Purging resources of type file is not supported/ end it "can be set to true for a resource type that has instances and can accept ensure" do allow(instance.resource_type).to receive(:validproperty?).and_return(true) expect { instance[:purge] = 'yes' }.to_not raise_error end end context "#check_user purge behaviour" do context "with unless_system_user => true" do before do @res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true @res.catalog = Puppet::Resource::Catalog.new allow(Puppet::FileSystem).to receive(:exist?).with('/etc/login.defs').and_return(false) end it "should never purge hardcoded system users" do %w{root nobody bin noaccess daemon sys}.each do |sys_user| expect(@res.user_check(Puppet::Type.type(:user).new(:name => sys_user))).to be_falsey end end it "should not purge system users if unless_system_user => true" do user_hash = {:name => 'system_user', :uid => 125, :system => true} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end it "should purge non-system users if unless_system_user => true" do user_hash = {:name => 'system_user', :uid => described_class.system_users_max_uid + 1, :system => true} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_truthy end it "should not purge system users under 600 if unless_system_user => 600" do res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => 600 res.catalog = Puppet::Resource::Catalog.new user_hash = {:name => 'system_user', :uid => 500, :system => true} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(res.user_check(user)).to be_falsey end it "should not purge Windows system users" do res = Puppet::Type.type(:resources).new :name => :user, :purge => true res.catalog = Puppet::Resource::Catalog.new user_hash = {:name => 'Administrator', :uid => 'S-1-5-21-12345-500'} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(res.user_check(user)).to be_falsey end it "should not purge Windows system users" do res = Puppet::Type.type(:resources).new :name => :user, :purge => true res.catalog = Puppet::Resource::Catalog.new user_hash = {:name => 'other', :uid => 'S-1-5-21-12345-1001'} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(res.user_check(user)).to be_truthy end end %w(FreeBSD OpenBSD).each do |os| context "on #{os}" do before :each do allow(Facter).to receive(:value).with(:kernel).and_return(os) allow(Facter).to receive(:value).with('os.name').and_return(os) allow(Facter).to receive(:value).with('os.family').and_return(os) allow(Puppet::FileSystem).to receive(:exist?).with('/etc/login.defs').and_return(false) @res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true @res.catalog = Puppet::Resource::Catalog.new end it "should not purge system users under 1000" do user_hash = {:name => 'system_user', :uid => 999} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end it "should purge users over 999" do user_hash = {:name => 'system_user', :uid => 1000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_truthy end end end context 'with login.defs present' do before :each do expect(Puppet::FileSystem).to receive(:exist?).with('/etc/login.defs').and_return(true) expect(Puppet::FileSystem).to receive(:each_line).with('/etc/login.defs').and_yield(' UID_MIN 1234 # UID_MIN comment ') @res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true @res.catalog = Puppet::Resource::Catalog.new end it 'should not purge a system user' do user_hash = {:name => 'system_user', :uid => 1233} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end it 'should purge a non-system user' do user_hash = {:name => 'system_user', :uid => 1234} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_truthy end end context "with unless_uid" do context "with a uid array" do before do @res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => [15_000, 15_001, 15_002] @res.catalog = Puppet::Resource::Catalog.new end it "should purge uids that are not in a specified array" do user_hash = {:name => 'special_user', :uid => 25_000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_truthy end it "should not purge uids that are in a specified array" do user_hash = {:name => 'special_user', :uid => 15000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end end context "with a single integer uid" do before do @res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => 15_000 @res.catalog = Puppet::Resource::Catalog.new end it "should purge uids that are not specified" do user_hash = {:name => 'special_user', :uid => 25_000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_truthy end it "should not purge uids that are specified" do user_hash = {:name => 'special_user', :uid => 15_000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end end context "with a single string uid" do before do @res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => '15000' @res.catalog = Puppet::Resource::Catalog.new end it "should purge uids that are not specified" do user_hash = {:name => 'special_user', :uid => 25_000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_truthy end it "should not purge uids that are specified" do user_hash = {:name => 'special_user', :uid => 15_000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end end context "with a mixed uid array" do before do @res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => ['15000', 16_666] @res.catalog = Puppet::Resource::Catalog.new end it "should not purge ids in the range" do user_hash = {:name => 'special_user', :uid => 15_000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end it "should not purge specified ids" do user_hash = {:name => 'special_user', :uid => 16_666} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_falsey end it "should purge unspecified ids" do user_hash = {:name => 'special_user', :uid => 17_000} user = Puppet::Type.type(:user).new(user_hash) allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash)) expect(@res.user_check(user)).to be_truthy end end end end context "#generate" do before do @purgee = Puppet::Type.type(:purgeable_test).new(:name => 'localhost') @catalog = Puppet::Resource::Catalog.new end context "when the catalog contains a purging resource with an alias" do before do @resource = Puppet::Type.type(:resources).new(:name => "purgeable_test", :purge => true) @catalog.add_resource @resource @catalog.alias(@resource, "purgeable_test_alias") end it "should not copy the alias metaparameter" do allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgee]) generated = @resource.generate.first expect(generated[:alias]).to be_nil end end context "when dealing with non-purging resources" do before do @resources = Puppet::Type.type(:resources).new(:name => 'purgeable_test') end it "should not generate any resource" do expect(@resources.generate).to be_empty end end context "when the catalog contains a purging resource" do before do @resources = Puppet::Type.type(:resources).new(:name => 'purgeable_test', :purge => true) @purgeable_resource = Puppet::Type.type(:purgeable_test).new(:name => 'localhost') @catalog.add_resource @resources end it "should not generate a duplicate of that resource" do allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgee]) @catalog.add_resource @purgee expect(@resources.generate.collect { |r| r.ref }).not_to include(@purgee.ref) end it "should not include the skipped system users" do res = Puppet::Type.type(:resources).new :name => :user, :purge => true res.catalog = Puppet::Resource::Catalog.new root = Puppet::Type.type(:user).new(:name => "root") expect(Puppet::Type.type(:user)).to receive(:instances).and_return([root]) list = res.generate names = list.collect { |r| r[:name] } expect(names).not_to be_include("root") end context "when generating a purgeable resource" do it "should be included in the generated resources" do allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgeable_resource]) expect(@resources.generate.collect { |r| r.ref }).to include(@purgeable_resource.ref) end context "when the instance's do not have an ensure property" do it "should not be included in the generated resources" do @no_ensure_resource = Puppet::Type.type(:exec).new(:name => "#{File.expand_path('/usr/bin/env')} echo") allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@no_ensure_resource]) expect(@resources.generate.collect { |r| r.ref }).not_to include(@no_ensure_resource.ref) end end context "when the instance's ensure property does not accept absent" do it "should not be included in the generated resources" do # We have a :confine block that calls execute in our upstart provider, which fails # on jruby. Thus, we stub it out here since we don't care to do any assertions on it. # This is only an issue if you're running these unit tests on a platform where upstart # is a default provider, like Ubuntu trusty. allow(Puppet::Util::Execution).to receive(:execute) @no_absent_resource = Puppet::Type.type(:service).new(:name => 'foobar') allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@no_absent_resource]) expect(@resources.generate.collect { |r| r.ref }).not_to include(@no_absent_resource.ref) end end context "when checking the instance fails" do it "should not be included in the generated resources" do @purgeable_resource = Puppet::Type.type(:purgeable_test).new(:name => 'foobar') allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgeable_resource]) expect(@resources).to receive(:check).with(@purgeable_resource).and_return(false) expect(@resources.generate.collect { |r| r.ref }).not_to include(@purgeable_resource.ref) end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/stage_spec.rb
spec/unit/type/stage_spec.rb
require 'spec_helper' describe Puppet::Type.type(:stage) do it "should have a 'name' parameter'" do expect(Puppet::Type.type(:stage).new(:name => :foo)[:name]).to eq(:foo) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/user_spec.rb
spec/unit/type/user_spec.rb
# encoding: utf-8 require 'spec_helper' describe Puppet::Type.type(:user) do before :each do @provider_class = described_class.provide(:simple) do has_features :manages_expiry, :manages_password_age, :manages_passwords, :manages_solaris_rbac, :manages_roles, :manages_shell mk_resource_methods def create; end def delete; end def exists?; get(:ensure) != :absent; end def flush; end def self.instances; []; end end allow(described_class).to receive(:defaultprovider).and_return(@provider_class) end it "should be able to create an instance" do expect(described_class.new(:name => "foo")).not_to be_nil end it "should have an allows_duplicates feature" do expect(described_class.provider_feature(:allows_duplicates)).not_to be_nil end it "should have a manages_homedir feature" do expect(described_class.provider_feature(:manages_homedir)).not_to be_nil end it "should have a manages_passwords feature" do expect(described_class.provider_feature(:manages_passwords)).not_to be_nil end it "should have a manages_solaris_rbac feature" do expect(described_class.provider_feature(:manages_solaris_rbac)).not_to be_nil end it "should have a manages_roles feature" do expect(described_class.provider_feature(:manages_roles)).not_to be_nil end it "should have a manages_expiry feature" do expect(described_class.provider_feature(:manages_expiry)).not_to be_nil end it "should have a manages_password_age feature" do expect(described_class.provider_feature(:manages_password_age)).not_to be_nil end it "should have a system_users feature" do expect(described_class.provider_feature(:system_users)).not_to be_nil end it "should have a manages_shell feature" do expect(described_class.provider_feature(:manages_shell)).not_to be_nil end context "managehome" do let (:provider) { @provider_class.new(:name => 'foo', :ensure => :absent) } let (:instance) { described_class.new(:name => 'foo', :provider => provider) } it "defaults to false" do expect(instance[:managehome]).to be_falsey end it "can be set to false" do instance[:managehome] = 'false' end it "cannot be set to true for a provider that does not manage homedirs" do allow(provider.class).to receive(:manages_homedir?).and_return(false) expect { instance[:managehome] = 'yes' }.to raise_error(Puppet::Error, /can not manage home directories/) end it "can be set to true for a provider that does manage homedirs" do allow(provider.class).to receive(:manages_homedir?).and_return(true) instance[:managehome] = 'yes' end end describe "instances" do it "should delegate existence questions to its provider" do @provider = @provider_class.new(:name => 'foo', :ensure => :absent) instance = described_class.new(:name => "foo", :provider => @provider) expect(instance.exists?).to eq(false) @provider.set(:ensure => :present) expect(instance.exists?).to eq(true) end end properties = [:ensure, :uid, :gid, :home, :comment, :shell, :password, :password_min_age, :password_max_age, :password_warn_days, :groups, :roles, :auths, :profiles, :project, :keys, :expiry] properties.each do |property| it "should have a #{property} property" do expect(described_class.attrclass(property).ancestors).to be_include(Puppet::Property) end it "should have documentation for its #{property} property" do expect(described_class.attrclass(property).doc).to be_instance_of(String) end end list_properties = [:groups, :roles, :auths] list_properties.each do |property| it "should have a list '#{property}'" do expect(described_class.attrclass(property).ancestors).to be_include(Puppet::Property::List) end end it "should have an ordered list 'profiles'" do expect(described_class.attrclass(:profiles).ancestors).to be_include(Puppet::Property::OrderedList) end it "should have key values 'keys'" do expect(described_class.attrclass(:keys).ancestors).to be_include(Puppet::Property::KeyValue) end describe "when retrieving all current values" do before do @provider = @provider_class.new(:name => 'foo', :ensure => :present, :uid => 15, :gid => 15) @user = described_class.new(:name => "foo", :uid => 10, :provider => @provider) end it "should return a hash containing values for all set properties" do @user[:gid] = 10 values = @user.retrieve [@user.property(:uid), @user.property(:gid)].each { |property| expect(values).to be_include(property) } end it "should set all values to :absent if the user is absent" do expect(@user.property(:ensure)).to receive(:retrieve).and_return(:absent) expect(@user.property(:uid)).not_to receive(:retrieve) expect(@user.retrieve[@user.property(:uid)]).to eq(:absent) end it "should include the result of retrieving each property's current value if the user is present" do expect(@user.retrieve[@user.property(:uid)]).to eq(15) end end describe "when managing the ensure property" do it "should support a :present value" do expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error end it "should support an :absent value" do expect { described_class.new(:name => 'foo', :ensure => :absent) }.to_not raise_error end it "should call :create on the provider when asked to sync to the :present state" do @provider = @provider_class.new(:name => 'foo', :ensure => :absent) expect(@provider).to receive(:create) described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).sync end it "should call :delete on the provider when asked to sync to the :absent state" do @provider = @provider_class.new(:name => 'foo', :ensure => :present) expect(@provider).to receive(:delete) described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).sync end describe "and determining the current state" do it "should return :present when the provider indicates the user exists" do @provider = @provider_class.new(:name => 'foo', :ensure => :present) expect(described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).retrieve).to eq(:present) end it "should return :absent when the provider indicates the user does not exist" do @provider = @provider_class.new(:name => 'foo', :ensure => :absent) expect(described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).retrieve).to eq(:absent) end end end describe "when managing the uid property" do it "should convert number-looking strings into actual numbers" do expect(described_class.new(:name => 'foo', :uid => '50')[:uid]).to eq(50) end it "should support UIDs as numbers" do expect(described_class.new(:name => 'foo', :uid => 50)[:uid]).to eq(50) end it "should support :absent as a value" do expect(described_class.new(:name => 'foo', :uid => :absent)[:uid]).to eq(:absent) end end describe "when managing the gid" do it "should support :absent as a value" do expect(described_class.new(:name => 'foo', :gid => :absent)[:gid]).to eq(:absent) end it "should convert number-looking strings into actual numbers" do expect(described_class.new(:name => 'foo', :gid => '50')[:gid]).to eq(50) end it "should support GIDs specified as integers" do expect(described_class.new(:name => 'foo', :gid => 50)[:gid]).to eq(50) end it "should support groups specified by name" do expect(described_class.new(:name => 'foo', :gid => 'foo')[:gid]).to eq('foo') end describe "when testing whether in sync" do it "should return true if no 'should' values are set" do # this is currently not the case because gid has no default value, so we would never even # call insync? on that property if param = described_class.new(:name => 'foo').parameter(:gid) expect(param).to be_safe_insync(500) end end it "should return true if any of the specified groups are equal to the current integer" do expect(Puppet::Util).to receive(:gid).with("foo").and_return(300) expect(Puppet::Util).to receive(:gid).with("bar").and_return(500) expect(described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid)).to be_safe_insync(500) end it "should return false if none of the specified groups are equal to the current integer" do expect(Puppet::Util).to receive(:gid).with("foo").and_return(300) expect(Puppet::Util).to receive(:gid).with("bar").and_return(500) expect(described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid)).to_not be_safe_insync(700) end end describe "when syncing" do it "should use the first found, specified group as the desired value and send it to the provider" do expect(Puppet::Util).to receive(:gid).with("foo").and_return(nil) expect(Puppet::Util).to receive(:gid).with("bar").and_return(500) @provider = @provider_class.new(:name => 'foo') resource = described_class.new(:name => 'foo', :provider => @provider, :gid => [ 'foo', 'bar' ]) expect(@provider).to receive(:gid=).with(500) resource.parameter(:gid).sync end end end describe "when managing groups" do it "should support a singe group" do expect { described_class.new(:name => 'foo', :groups => 'bar') }.to_not raise_error end it "should support multiple groups as an array" do expect { described_class.new(:name => 'foo', :groups => [ 'bar' ]) }.to_not raise_error expect { described_class.new(:name => 'foo', :groups => [ 'bar', 'baz' ]) }.to_not raise_error end it "should not support a comma separated list" do expect { described_class.new(:name => 'foo', :groups => 'bar,baz') }.to raise_error(Puppet::Error, /Group names must be provided as an array/) end it "should not support an empty string" do expect { described_class.new(:name => 'foo', :groups => '') }.to raise_error(Puppet::Error, /Group names must not be empty/) end describe "when testing is in sync" do before :each do # the useradd provider uses a single string to represent groups and so does Puppet::Property::List when converting to should values @provider = @provider_class.new(:name => 'foo', :groups => 'a,b,e,f') end it "should not care about order" do @property = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ]).property(:groups) expect(@property).to be_safe_insync([ 'a', 'b', 'c' ]) expect(@property).to be_safe_insync([ 'a', 'c', 'b' ]) expect(@property).to be_safe_insync([ 'b', 'a', 'c' ]) expect(@property).to be_safe_insync([ 'b', 'c', 'a' ]) expect(@property).to be_safe_insync([ 'c', 'a', 'b' ]) expect(@property).to be_safe_insync([ 'c', 'b', 'a' ]) end it "should merge current value and desired value if membership minimal" do @instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider) @instance[:membership] = :minimum expect(@instance[:groups]).to eq('a,b,c,e,f') end it "should not treat a subset of groups insync if membership inclusive" do @instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider) @instance[:membership] = :inclusive expect(@instance[:groups]).to eq('a,b,c') end end end describe "when managing the purge_ssh_keys property" do context "with valid input" do ['true', :true, true].each do |input| it "should support #{input} as value" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => input) }.to_not raise_error end end ['false', :false, false].each do |input| it "should support #{input} as value" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => input) }.to_not raise_error end end it "should support a String value" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => File.expand_path('home/foo/.ssh/authorized_keys')) }.to_not raise_error end it "should support an Array value" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => [File.expand_path('home/foo/.ssh/authorized_keys'), File.expand_path('custom/authorized_keys')]) }.to_not raise_error end end context "with faulty input" do it "should raise error for relative path" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => 'home/foo/.ssh/authorized_keys') }.to raise_error(Puppet::ResourceError, /Paths to keyfiles must be absolute/ ) end it "should raise error for invalid type" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => :invalid) }.to raise_error(Puppet::ResourceError, /purge_ssh_keys must be true, false, or an array of file names/ ) end it "should raise error for array with relative path" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => ['home/foo/.ssh/authorized_keys', File.expand_path('custom/authorized_keys')]) }.to raise_error(Puppet::ResourceError, /Paths to keyfiles must be absolute/ ) end it "should raise error for array with invalid type" do expect { described_class.new(:name => 'foo', :purge_ssh_keys => [:invalid, File.expand_path('custom/authorized_keys')]) }.to raise_error(Puppet::ResourceError, /Each entry for purge_ssh_keys must be a string/ ) end end context "homedir retrieval" do it "should accept the home provided" do expect(Puppet).not_to receive(:debug).with("User 'foo' does not exist") described_class.new(:name => 'foo', :purge_ssh_keys => true, :home => '/my_home') end it "should accept the home provided" do expect(Dir).to receive(:home).with('foo').and_return('/my_home') expect(Puppet).not_to receive(:debug).with("User 'foo' does not exist") described_class.new(:name => 'foo', :purge_ssh_keys => true) end it "should output debug message when home directory cannot be retrieved" do allow(Dir).to receive(:home).with('foo').and_raise(ArgumentError) expect(Puppet).to receive(:debug).with("User 'foo' does not exist") described_class.new(:name => 'foo', :purge_ssh_keys => true) end end end describe "when managing expiry" do it "should fail if given an invalid date" do expect { described_class.new(:name => 'foo', :expiry => "200-20-20") }.to raise_error(Puppet::Error, /Expiry dates must be YYYY-MM-DD/) end end describe "when managing minimum password age" do it "should accept a negative minimum age" do expect { described_class.new(:name => 'foo', :password_min_age => '-1') }.to_not raise_error end it "should fail with an empty minimum age" do expect { described_class.new(:name => 'foo', :password_min_age => '') }.to raise_error(Puppet::Error, /minimum age must be provided as a number/) end end describe "when managing maximum password age" do it "should accept a negative maximum age" do expect { described_class.new(:name => 'foo', :password_max_age => '-1') }.to_not raise_error end it "should fail with an empty maximum age" do expect { described_class.new(:name => 'foo', :password_max_age => '') }.to raise_error(Puppet::Error, /maximum age must be provided as a number/) end end describe "when managing warning password days" do it "should accept a negative warning days" do expect { described_class.new(:name => 'foo', :password_warn_days => '-1') }.to_not raise_error end it "should fail with an empty warning days" do expect { described_class.new(:name => 'foo', :password_warn_days => '') }.to raise_error(Puppet::Error, /warning days must be provided as a number/) end end describe "when managing passwords" do let(:transaction) { Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil) } let(:harness) { Puppet::Transaction::ResourceHarness.new(transaction) } let(:provider) { @provider_class.new(:name => 'foo', :ensure => :present) } let(:resource) { described_class.new(:name => 'foo', :ensure => :present, :password => 'top secret', :provider => provider) } it "should not include the password in the change log when adding the password" do status = harness.evaluate(resource) sync_event = status.events[0] expect(sync_event.message).not_to include('top secret') expect(sync_event.message).to eql('changed [redacted] to [redacted]') end it "should not include the password in the change log when changing the password" do resource[:password] = 'super extra classified' status = harness.evaluate(resource) sync_event = status.events[0] expect(sync_event.message).not_to include('super extra classified') expect(sync_event.message).to eql('changed [redacted] to [redacted]') end it "should fail if a ':' is included in the password" do expect { described_class.new(:name => 'foo', :password => "some:thing") }.to raise_error(Puppet::Error, /Passwords cannot include ':'/) end it "should allow the value to be set to :absent" do expect { described_class.new(:name => 'foo', :password => :absent) }.to_not raise_error end end describe "when managing comment" do before :each do @value = 'abcd™' expect(@value.encoding).to eq(Encoding::UTF_8) @user = described_class.new(:name => 'foo', :comment => @value) end describe "#insync" do it "should delegate to the provider's #comments_insync? method if defined" do # useradd subclasses nameservice and thus inherits #comments_insync? user = described_class.new(:name => 'foo', :comment => @value, :provider => :useradd) comment_property = user.properties.find {|p| p.name == :comment} expect(user.provider).to receive(:comments_insync?) comment_property.insync?('bar') end describe "#change_to_s" do let(:is) { "\u2603" } let(:should) { "\u06FF" } let(:comment_property) { @user.properties.find { |p| p.name == :comment } } context "given is and should strings with incompatible encoding" do it "should return a formatted string" do is.force_encoding(Encoding::ASCII_8BIT) should.force_encoding(Encoding::UTF_8) expect(Encoding.compatible?(is, should)).to be_falsey expect(comment_property.change_to_s(is,should)).to match(/changed '\u{E2}\u{98}\u{83}' to '\u{DB}\u{BF}'/) end end context "given is and should strings with compatible encoding" do it "should return a formatted string" do is.force_encoding(Encoding::UTF_8) should.force_encoding(Encoding::UTF_8) expect(Encoding.compatible?(is, should)).to be_truthy expect(comment_property.change_to_s(is,should)).to match(/changed '\u{2603}' to '\u{6FF}'/u) end end end end end describe "when manages_solaris_rbac is enabled" do it "should support a :role value for ensure" do expect { described_class.new(:name => 'foo', :ensure => :role) }.to_not raise_error end end describe "when user has roles" do it "should autorequire roles on non-Windows", :unless => Puppet::Util::Platform.windows? do testuser = described_class.new(:name => "testuser", :roles => ['testrole'] ) testrole = described_class.new(:name => "testrole") Puppet::Resource::Catalog.new :testing do |conf| [testuser, testrole].each { |resource| conf.add_resource resource } end rel = testuser.autorequire[0] expect(rel.source.ref).to eq(testrole.ref) expect(rel.target.ref).to eq(testuser.ref) end it "should not autorequire roles on Windows", :if => Puppet::Util::Platform.windows? do testuser = described_class.new(:name => "testuser", :roles => ['testrole'] ) testrole = described_class.new(:name => "testrole") Puppet::Resource::Catalog.new :testing do |conf| [testuser, testrole].each { |resource| conf.add_resource resource } end expect(testuser.autorequire).to be_empty end it "should sync the user roles when changing the state of :ensure if :roles is being managed" do user = Puppet::Type.type(:user).new(:name => "myUser", :ensure => :present) user[:roles] = 'testRole' allow(user.provider.class).to receive(:supports_parameter?).and_return(true) expect(user.property(:roles)).to receive(:retrieve).and_return("other") expect(user.property(:roles)).to receive(:insync?).and_return(false) expect(user.property(:roles)).to receive(:sync) allow(user.provider).to receive(:create) user.property(:ensure).sync end end describe "when setting shell" do before :each do @shell_provider_class = described_class.provide(:shell_manager) do has_features :manages_shell mk_resource_methods def create; check_valid_shell;end def shell=(value); check_valid_shell; end def delete; end def exists?; get(:ensure) != :absent; end def flush; end def self.instances; []; end def check_valid_shell; end end allow(described_class).to receive(:defaultprovider).and_return(@shell_provider_class) end it "should call :check_valid_shell on the provider when changing shell value" do @provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :present) expect(@provider).to receive(:check_valid_shell) resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider) allow(Puppet::Util::Storage).to receive(:load) allow(Puppet::Util::Storage).to receive(:store) catalog = Puppet::Resource::Catalog.new catalog.add_resource resource catalog.apply end it "should call :check_valid_shell on the provider when changing ensure from present to absent" do @provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :absent) expect(@provider).to receive(:check_valid_shell) resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider) allow(Puppet::Util::Storage).to receive(:load) allow(Puppet::Util::Storage).to receive(:store) catalog = Puppet::Resource::Catalog.new catalog.add_resource resource catalog.apply end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/exec_spec.rb
spec/unit/type/exec_spec.rb
require 'spec_helper' RSpec.describe Puppet::Type.type(:exec) do include PuppetSpec::Files def exec_tester(command, exitstatus = 0, rest = {}) allow(Puppet.features).to receive(:root?).and_return(true) output = rest.delete(:output) || '' output = Puppet::Util::Execution::ProcessOutput.new(output, exitstatus) tries = rest[:tries] || 1 type_args = { :name => command, :path => @example_path, :logoutput => false, :loglevel => :err, :returns => 0 }.merge(rest) exec = Puppet::Type.type(:exec).new(type_args) expect(Puppet::Util::Execution).to receive(:execute) do |cmd, options| expect(cmd).to eq(command) expect(options[:override_locale]).to eq(false) expect(options).to have_key(:custom_environment) output end.exactly(tries).times return exec end def exec_stub(options = {}) command = options.delete(:command) || @command #unless_val = options.delete(:unless) || :true type_args = { :name => command, #:unless => unless_val, }.merge(options) # Chicken, meet egg: # Provider methods have to be stubbed before resource init or checks fail # We have to set 'unless' in resource init or it can not be marked sensitive correctly. # So: we create a dummy ahead of time and use 'any_instance' to stub out provider methods. dummy = Puppet::Type.type(:exec).new(:name => @command) allow_any_instance_of(dummy.provider.class).to receive(:validatecmd) allow_any_instance_of(dummy.provider.class).to receive(:checkexe).and_return(true) pass_status = double('status', :exitstatus => 0, :split => ["pass output"]) fail_status = double('status', :exitstatus => 1, :split => ["fail output"]) allow(Puppet::Util::Execution).to receive(:execute).with(:true, anything).and_return(pass_status) allow(Puppet::Util::Execution).to receive(:execute).with(:false, anything).and_return(fail_status) test = Puppet::Type.type(:exec).new(type_args) Puppet::Util::Log.level = :debug return test end before do @command = make_absolute('/bin/true whatever') @executable = make_absolute('/bin/true') @bogus_cmd = make_absolute('/bogus/cmd') end describe "when not stubbing the provider" do before do path = tmpdir('path') ext = Puppet::Util::Platform.windows? ? '.exe' : '' true_cmd = File.join(path, "true#{ext}") false_cmd = File.join(path, "false#{ext}") FileUtils.touch(true_cmd) FileUtils.touch(false_cmd) File.chmod(0755, true_cmd) File.chmod(0755, false_cmd) @example_path = [path] end it "should return :executed_command as its event" do resource = Puppet::Type.type(:exec).new :command => @command expect(resource.parameter(:returns).event.name).to eq(:executed_command) end describe "when execing" do it "should use the 'execute' method to exec" do expect(exec_tester("true").refresh).to eq(:executed_command) end it "should report a failure" do expect { exec_tester('false', 1).refresh }. to raise_error(Puppet::Error, /^'false' returned 1 instead of/) end it "should redact sensitive commands on failure" do expect { exec_tester('false', 1, :sensitive_parameters => [:command]).refresh }. to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/) end it "should not report a failure if the exit status is specified in a returns array" do expect { exec_tester("false", 1, :returns => [0, 1]).refresh }.to_not raise_error end it "should report a failure if the exit status is not specified in a returns array" do expect { exec_tester('false', 1, :returns => [0, 100]).refresh }. to raise_error(Puppet::Error, /^'false' returned 1 instead of/) end it "should report redact sensitive commands if the exit status is not specified in a returns array" do expect { exec_tester('false', 1, :returns => [0, 100], :sensitive_parameters => [:command]).refresh }. to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/) end it "should log the output on success" do output = "output1\noutput2\n" exec_tester('false', 0, :output => output, :logoutput => true).refresh output.split("\n").each do |line| log = @logs.shift expect(log.level).to eq(:err) expect(log.message).to eq(line) end end it "should log the output on failure" do output = "output1\noutput2\n" expect { exec_tester('false', 1, :output => output, :logoutput => true).refresh }. to raise_error(Puppet::Error) output.split("\n").each do |line| log = @logs.shift expect(log.level).to eq(:err) expect(log.message).to eq(line) end end end describe "when logoutput=>on_failure is set" do it "should log the output on failure" do output = "output1\noutput2\n" expect { exec_tester('false', 1, :output => output, :logoutput => :on_failure).refresh }. to raise_error(Puppet::Error, /^'false' returned 1 instead of/) output.split("\n").each do |line| log = @logs.shift expect(log.level).to eq(:err) expect(log.message).to eq(line) end end it "should redact the sensitive command on failure" do output = "output1\noutput2\n" expect { exec_tester('false', 1, :output => output, :logoutput => :on_failure, :sensitive_parameters => [:command]).refresh }. to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/) expect(@logs).to include(an_object_having_attributes(level: :err, message: '[output redacted]')) expect(@logs).to_not include(an_object_having_attributes(message: /output1|output2/)) end it "should log the output on failure when returns is specified as an array" do output = "output1\noutput2\n" expect { exec_tester('false', 1, :output => output, :returns => [0, 100], :logoutput => :on_failure).refresh }.to raise_error(Puppet::Error, /^'false' returned 1 instead of/) output.split("\n").each do |line| log = @logs.shift expect(log.level).to eq(:err) expect(log.message).to eq(line) end end it "should redact the sensitive command on failure when returns is specified as an array" do output = "output1\noutput2\n" expect { exec_tester('false', 1, :output => output, :returns => [0, 100], :logoutput => :on_failure, :sensitive_parameters => [:command]).refresh }.to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/) expect(@logs).to include(an_object_having_attributes(level: :err, message: '[output redacted]')) expect(@logs).to_not include(an_object_having_attributes(message: /output1|output2/)) end it "shouldn't log the output on success" do exec_tester('true', 0, :output => "a\nb\nc\n", :logoutput => :on_failure).refresh expect(@logs).to eq([]) end end it "shouldn't log the output on success when non-zero exit status is in a returns array" do exec_tester("true", 100, :output => "a\n", :logoutput => :on_failure, :returns => [1, 100]).refresh expect(@logs).to eq([]) end describe "when checks stop execution when debugging" do [[:unless, :true], [:onlyif, :false]].each do |check, result| it "should log a message with the command when #{check} is #{result}" do output = "'#{@command}' won't be executed because of failed check '#{check}'" test = exec_stub({:command => @command, check => result}) expect(test.check_all_attributes).to eq(false) expect(@logs).to include(an_object_having_attributes(level: :debug, message: output)) end it "should log a message with a redacted command and check if #{check} is sensitive" do output1 = "Executing check '[redacted]'" output2 = "'[command redacted]' won't be executed because of failed check '#{check}'" test = exec_stub({:command => @command, check => result, :sensitive_parameters => [check]}) expect(test.check_all_attributes).to eq(false) expect(@logs).to include(an_object_having_attributes(level: :debug, message: output1)) expect(@logs).to include(an_object_having_attributes(level: :debug, message: output2)) end end end describe " when multiple tries are set," do it "should repeat the command attempt 'tries' times on failure and produce an error" do tries = 5 resource = exec_tester("false", 1, :tries => tries, :try_sleep => 0) expect { resource.refresh }.to raise_error(Puppet::Error) end end end it "should be able to autorequire files mentioned in the command" do foo = make_absolute('/bin/foo') catalog = Puppet::Resource::Catalog.new tmp = Puppet::Type.type(:file).new(:name => foo) execer = Puppet::Type.type(:exec).new(:name => foo) catalog.add_resource tmp catalog.add_resource execer dependencies = execer.autorequire(catalog) expect(dependencies.collect(&:to_s)).to eq([Puppet::Relationship.new(tmp, execer).to_s]) end it "should be able to autorequire files mentioned in the array command" do foo = make_absolute('/bin/foo') catalog = Puppet::Resource::Catalog.new tmp = Puppet::Type.type(:file).new(:name => foo) execer = Puppet::Type.type(:exec).new(:name => 'test array', :command => [foo, 'bar']) catalog.add_resource tmp catalog.add_resource execer dependencies = execer.autorequire(catalog) expect(dependencies.collect(&:to_s)).to eq([Puppet::Relationship.new(tmp, execer).to_s]) end it "skips autorequire for deferred commands" do foo = make_absolute('/bin/foo') catalog = Puppet::Resource::Catalog.new tmp = Puppet::Type.type(:file).new(:name => foo) execer = Puppet::Type.type(:exec).new(:name => 'test array', :command => Puppet::Pops::Evaluator::DeferredValue.new(nil)) catalog.add_resource tmp catalog.add_resource execer dependencies = execer.autorequire(catalog) expect(dependencies.collect(&:to_s)).to eq([]) end describe "when handling the path parameter" do expect = %w{one two three four} { "an array" => expect, "a path-separator delimited list" => expect.join(File::PATH_SEPARATOR), "both array and path-separator delimited lists" => ["one", "two#{File::PATH_SEPARATOR}three", "four"], }.each do |test, input| it "should accept #{test}" do type = Puppet::Type.type(:exec).new(:name => @command, :path => input) expect(type[:path]).to eq(expect) end end describe "on platforms where path separator is not :" do before :each do stub_const('File::PATH_SEPARATOR', 'q') end it "should use the path separator of the current platform" do type = Puppet::Type.type(:exec).new(:name => @command, :path => "fooqbarqbaz") expect(type[:path]).to eq(%w[foo bar baz]) end end end describe "when setting user" do describe "on POSIX systems", :if => Puppet.features.posix? do it "should fail if we are not root" do allow(Puppet.features).to receive(:root?).and_return(false) expect { Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => 'input') }.to raise_error Puppet::Error, /Parameter user failed/ end it "accepts the current user" do allow(Puppet.features).to receive(:root?).and_return(false) allow(Etc).to receive(:getpwuid).and_return(Etc::Passwd.new('input')) type = Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => 'input') expect(type[:user]).to eq('input') end ['one', 2, 'root', 4294967295, 4294967296].each do |value| it "should accept '#{value}' as user if we are root" do allow(Puppet.features).to receive(:root?).and_return(true) type = Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => value) expect(type[:user]).to eq(value) end end end describe "on Windows systems", :if => Puppet::Util::Platform.windows? do before :each do allow(Puppet.features).to receive(:root?).and_return(true) end it "should reject user parameter" do expect { Puppet::Type.type(:exec).new(:name => 'c:\windows\notepad.exe', :user => 'input') }.to raise_error Puppet::Error, /Unable to execute commands as other users on Windows/ end end end describe "when setting group" do shared_examples_for "exec[:group]" do ['one', 2, 'wheel', 4294967295, 4294967296].each do |value| it "should accept '#{value}' without error or judgement" do type = Puppet::Type.type(:exec).new(:name => @command, :group => value) expect(type[:group]).to eq(value) end end end describe "when running as root" do before(:each) do allow(Puppet.features).to receive(:root?).and_return(true) end it_behaves_like "exec[:group]" end describe "when not running as root" do before(:each) do allow(Puppet.features).to receive(:root?).and_return(false) end it_behaves_like "exec[:group]" end end describe "when setting cwd" do it_should_behave_like "all path parameters", :cwd, :array => false do def instance(path) # Specify shell provider so we don't have to care about command validation Puppet::Type.type(:exec).new(:name => @executable, :cwd => path, :provider => :shell) end end end shared_examples_for "all exec command parameters" do |param| array_cmd = ["/bin/example", "*"] array_cmd = [["/bin/example", "*"]] if [:onlyif, :unless].include?(param) commands = { "relative" => "example", "absolute" => "/bin/example" } commands["array"] = array_cmd commands.sort.each do |name, command| describe "if command is #{name}" do before :each do @param = param end def test(command, valid) if @param == :name then instance = Puppet::Type.type(:exec).new() else instance = Puppet::Type.type(:exec).new(:name => @executable) end if valid then expect(instance.provider).to receive(:validatecmd).and_return(true) else expect(instance.provider).to receive(:validatecmd).and_raise(Puppet::Error, "from a stub") end instance[@param] = command end it "should work if the provider calls the command valid" do expect { test(command, true) }.to_not raise_error end it "should fail if the provider calls the command invalid" do expect { test(command, false) }. to raise_error Puppet::Error, /Parameter #{@param} failed on Exec\[.*\]: from a stub/ end end end end shared_examples_for "all exec command parameters that take arrays" do |param| [ %w{one two three}, [%w{one -a}, %w{two, -b}, 'three'] ].each do |input| context "when given #{input.inspect} as input" do let(:resource) { Puppet::Type.type(:exec).new(:name => @executable) } it "accepts the array when all commands return valid" do input = %w{one two three} allow(resource.provider).to receive(:validatecmd).exactly(input.length).times.and_return(true) resource[param] = input expect(resource[param]).to eq(input) end it "rejects the array when any commands return invalid" do input = %w{one two three} allow(resource.provider).to receive(:validatecmd).with(input[0]).and_return(true) allow(resource.provider).to receive(:validatecmd).with(input[1]).and_raise(Puppet::Error) expect { resource[param] = input }.to raise_error(Puppet::ResourceError, /Parameter #{param} failed/) end it "stops at the first invalid command" do input = %w{one two three} allow(resource.provider).to receive(:validatecmd).with(input[0]).and_raise(Puppet::Error) expect(resource.provider).not_to receive(:validatecmd).with(input[1]) expect(resource.provider).not_to receive(:validatecmd).with(input[2]) expect { resource[param] = input }.to raise_error(Puppet::ResourceError, /Parameter #{param} failed/) end end end end describe "when setting command" do subject { described_class.new(:name => @command) } it "fails when passed a Hash" do expect { subject[:command] = {} }.to raise_error Puppet::Error, /Command must be a String or Array<String>/ end end describe "when setting refresh" do it_should_behave_like "all exec command parameters", :refresh end describe "for simple parameters" do before :each do @exec = Puppet::Type.type(:exec).new(:name => @executable) end describe "when setting environment" do { "single values" => "foo=bar", "multiple values" => ["foo=bar", "baz=quux"], }.each do |name, data| it "should accept #{name}" do @exec[:environment] = data expect(@exec[:environment]).to eq(data) end end { "single values" => "foo", "only values" => ["foo", "bar"], "any values" => ["foo=bar", "baz"] }.each do |name, data| it "should reject #{name} without assignment" do expect { @exec[:environment] = data }. to raise_error Puppet::Error, /Invalid environment setting/ end end end describe "when setting timeout" do [0, 0.1, 1, 10, 4294967295].each do |valid| it "should accept '#{valid}' as valid" do @exec[:timeout] = valid expect(@exec[:timeout]).to eq(valid) end it "should accept '#{valid}' in an array as valid" do @exec[:timeout] = [valid] expect(@exec[:timeout]).to eq(valid) end end ['1/2', '', 'foo', '5foo'].each do |invalid| it "should reject '#{invalid}' as invalid" do expect { @exec[:timeout] = invalid }. to raise_error Puppet::Error, /The timeout must be a number/ end it "should reject '#{invalid}' in an array as invalid" do expect { @exec[:timeout] = [invalid] }. to raise_error Puppet::Error, /The timeout must be a number/ end end describe 'when timeout is exceeded' do subject do ruby_path = Puppet::Util::Execution.ruby_path() Puppet::Type.type(:exec).new(:name => "#{ruby_path} -e 'sleep 1'", :timeout => '0.1') end context 'on POSIX', :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do it 'sends a SIGTERM and raises a Puppet::Error' do expect(Process).to receive(:kill).at_least(:once) expect { subject.refresh }.to raise_error Puppet::Error, "Command exceeded timeout" end end context 'on Windows', :if => Puppet::Util::Platform.windows? do it 'raises a Puppet::Error' do expect { subject.refresh }.to raise_error Puppet::Error, "Command exceeded timeout" end end end it "should convert timeout to a float" do command = make_absolute('/bin/false') resource = Puppet::Type.type(:exec).new :command => command, :timeout => "12" expect(resource[:timeout]).to be_a(Float) expect(resource[:timeout]).to eq(12.0) end it "should munge negative timeouts to 0.0" do command = make_absolute('/bin/false') resource = Puppet::Type.type(:exec).new :command => command, :timeout => "-12.0" expect(resource.parameter(:timeout).value).to be_a(Float) expect(resource.parameter(:timeout).value).to eq(0.0) end end describe "when setting tries" do [1, 10, 4294967295].each do |valid| it "should accept '#{valid}' as valid" do @exec[:tries] = valid expect(@exec[:tries]).to eq(valid) end if "REVISIT: too much test log spam" == "a good thing" then it "should accept '#{valid}' in an array as valid" do pending "inconsistent, but this is not supporting arrays, unlike timeout" @exec[:tries] = [valid] expect(@exec[:tries]).to eq(valid) end end end [-3.5, -1, 0, 0.2, '1/2', '1_000_000', '+12', '', 'foo'].each do |invalid| it "should reject '#{invalid}' as invalid" do expect { @exec[:tries] = invalid }. to raise_error Puppet::Error, /Tries must be an integer/ end if "REVISIT: too much test log spam" == "a good thing" then it "should reject '#{invalid}' in an array as invalid" do pending "inconsistent, but this is not supporting arrays, unlike timeout" expect { @exec[:tries] = [invalid] }. to raise_error Puppet::Error, /Tries must be an integer/ end end end end describe "when setting try_sleep" do [0, 0.2, 1, 10, 4294967295].each do |valid| it "should accept '#{valid}' as valid" do @exec[:try_sleep] = valid expect(@exec[:try_sleep]).to eq(valid) end if "REVISIT: too much test log spam" == "a good thing" then it "should accept '#{valid}' in an array as valid" do pending "inconsistent, but this is not supporting arrays, unlike timeout" @exec[:try_sleep] = [valid] expect(@exec[:try_sleep]).to eq(valid) end end end { -3.5 => "cannot be a negative number", -1 => "cannot be a negative number", '1/2' => 'must be a number', '1_000_000' => 'must be a number', '+12' => 'must be a number', '' => 'must be a number', 'foo' => 'must be a number', }.each do |invalid, error| it "should reject '#{invalid}' as invalid" do expect { @exec[:try_sleep] = invalid }. to raise_error Puppet::Error, /try_sleep #{error}/ end if "REVISIT: too much test log spam" == "a good thing" then it "should reject '#{invalid}' in an array as invalid" do pending "inconsistent, but this is not supporting arrays, unlike timeout" expect { @exec[:try_sleep] = [invalid] }. to raise_error Puppet::Error, /try_sleep #{error}/ end end end end describe "when setting refreshonly" do [:true, :false].each do |value| it "should accept '#{value}'" do @exec[:refreshonly] = value expect(@exec[:refreshonly]).to eq(value) end end [1, 0, "1", "0", "yes", "y", "no", "n"].each do |value| it "should reject '#{value}'" do expect { @exec[:refreshonly] = value }. to raise_error(Puppet::Error, /Invalid value #{value.inspect}\. Valid values are true, false/ ) end end end end describe "when setting creates" do it_should_behave_like "all path parameters", :creates, :array => true do def instance(path) # Specify shell provider so we don't have to care about command validation Puppet::Type.type(:exec).new(:name => @executable, :creates => path, :provider => :shell) end end end describe "when setting unless" do it_should_behave_like "all exec command parameters", :unless it_should_behave_like "all exec command parameters that take arrays", :unless end describe "when setting onlyif" do it_should_behave_like "all exec command parameters", :onlyif it_should_behave_like "all exec command parameters that take arrays", :onlyif end describe "#check" do before :each do @test = Puppet::Type.type(:exec).new(:name => @executable) end describe ":refreshonly" do { :true => false, :false => true }.each do |input, result| it "should return '#{result}' when given '#{input}'" do @test[:refreshonly] = input expect(@test.check_all_attributes).to eq(result) end end end describe ":creates" do before :each do @exist = tmpfile('exist') FileUtils.touch(@exist) @unexist = tmpfile('unexist') end context "with a single item" do it "should run when the item does not exist" do @test[:creates] = @unexist expect(@test.check_all_attributes).to eq(true) end it "should not run when the item exists" do @test[:creates] = @exist expect(@test.check_all_attributes).to eq(false) end end context "with an array with one item" do it "should run when the item does not exist" do @test[:creates] = [@unexist] expect(@test.check_all_attributes).to eq(true) end it "should not run when the item exists" do @test[:creates] = [@exist] expect(@test.check_all_attributes).to eq(false) end end context "with an array with multiple items" do it "should run when all items do not exist" do @test[:creates] = [@unexist] * 3 expect(@test.check_all_attributes).to eq(true) end it "should not run when one item exists" do @test[:creates] = [@unexist, @exist, @unexist] expect(@test.check_all_attributes).to eq(false) end it "should not run when all items exist" do @test[:creates] = [@exist] * 3 end end context "when creates is being checked" do it "should be logged to debug when the path does exist" do Puppet::Util::Log.level = :debug @test[:creates] = @exist expect(@test.check_all_attributes).to eq(false) expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Checking that 'creates' path '#{@exist}' exists")) end it "should be logged to debug when the path does not exist" do Puppet::Util::Log.level = :debug @test[:creates] = @unexist expect(@test.check_all_attributes).to eq(true) expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Checking that 'creates' path '#{@unexist}' exists")) end end end { :onlyif => { :pass => false, :fail => true }, :unless => { :pass => true, :fail => false }, }.each do |param, sense| describe ":#{param}" do before :each do @pass = make_absolute("/magic/pass") @fail = make_absolute("/magic/fail") @pass_status = double('status', :exitstatus => sense[:pass] ? 0 : 1) @fail_status = double('status', :exitstatus => sense[:fail] ? 0 : 1) allow(@test.provider).to receive(:checkexe).and_return(true) [true, false].each do |check| allow(@test.provider).to receive(:run).with(@pass, check). and_return(['test output', @pass_status]) allow(@test.provider).to receive(:run).with(@fail, check). and_return(['test output', @fail_status]) end end context "with a single item" do it "should run if the command exits non-zero" do @test[param] = @fail expect(@test.check_all_attributes).to eq(true) end it "should not run if the command exits zero" do @test[param] = @pass expect(@test.check_all_attributes).to eq(false) end end context "with an array with a single item" do it "should run if the command exits non-zero" do @test[param] = [@fail] expect(@test.check_all_attributes).to eq(true) end it "should not run if the command exits zero" do @test[param] = [@pass] expect(@test.check_all_attributes).to eq(false) end end context "with an array with multiple items" do it "should run if all the commands exits non-zero" do @test[param] = [@fail] * 3 expect(@test.check_all_attributes).to eq(true) end it "should not run if one command exits zero" do @test[param] = [@pass, @fail, @pass] expect(@test.check_all_attributes).to eq(false) end it "should not run if all command exits zero" do @test[param] = [@pass] * 3 expect(@test.check_all_attributes).to eq(false) end end context 'with an array of arrays with multiple items' do before do [true, false].each do |check| allow(@test.provider).to receive(:run).with([@pass, '--flag'], check). and_return(['test output', @pass_status]) allow(@test.provider).to receive(:run).with([@fail, '--flag'], check). and_return(['test output', @fail_status]) allow(@test.provider).to receive(:run).with([@pass], check). and_return(['test output', @pass_status]) allow(@test.provider).to receive(:run).with([@fail], check). and_return(['test output', @fail_status]) end end it "runs if all the commands exits non-zero" do @test[param] = [[@fail, '--flag'], [@fail], [@fail, '--flag']] expect(@test.check_all_attributes).to eq(true) end it "does not run if one command exits zero" do @test[param] = [[@pass, '--flag'], [@pass], [@fail, '--flag']] expect(@test.check_all_attributes).to eq(false) end it "does not run if all command exits zero" do @test[param] = [[@pass, '--flag'], [@pass], [@pass, '--flag']] expect(@test.check_all_attributes).to eq(false) end end it "should emit output to debug" do Puppet::Util::Log.level = :debug @test[param] = @fail expect(@test.check_all_attributes).to eq(true) expect(@logs.shift.message).to eq("test output") end it "should not emit output to debug if sensitive is true" do Puppet::Util::Log.level = :debug @test[param] = @fail allow(@test.parameters[param]).to receive(:sensitive).and_return(true) expect(@test.check_all_attributes).to eq(true) expect(@logs).not_to include(an_object_having_attributes(level: :debug, message: "test output")) expect(@logs).to include(an_object_having_attributes(level: :debug, message: "[output redacted]")) end end end end describe "#retrieve" do before :each do @exec_resource = Puppet::Type.type(:exec).new(:name => @bogus_cmd) end it "should return :notrun when check_all_attributes returns true" do allow(@exec_resource).to receive(:check_all_attributes).and_return(true) expect(@exec_resource.retrieve[:returns]).to eq(:notrun) end it "should return default exit code 0 when check_all_attributes returns false" do allow(@exec_resource).to receive(:check_all_attributes).and_return(false) expect(@exec_resource.retrieve[:returns]).to eq(['0']) end it "should return the specified exit code when check_all_attributes returns false" do allow(@exec_resource).to receive(:check_all_attributes).and_return(false) @exec_resource[:returns] = 42 expect(@exec_resource.retrieve[:returns]).to eq(["42"]) end end describe "#output" do before :each do @exec_resource = Puppet::Type.type(:exec).new(:name => @bogus_cmd) end it "should return the provider's run output" do provider = double('provider') status = double('process_status') allow(status).to receive(:exitstatus).and_return("0") expect(provider).to receive(:run).and_return(["silly output", status]) allow(@exec_resource).to receive(:provider).and_return(provider) @exec_resource.refresh
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/whit_spec.rb
spec/unit/type/whit_spec.rb
require 'spec_helper' whit = Puppet::Type.type(:whit) describe whit do it "should stringify in a way that users will regognise" do expect(whit.new(:name => "Foo::Bar").to_s).to eq("Foo::Bar") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type/component_spec.rb
spec/unit/type/component_spec.rb
require 'spec_helper' component = Puppet::Type.type(:component) describe component do it "should have a :name attribute" do expect(component.attrclass(:name)).not_to be_nil end it "should use Class as its type when a normal string is provided as the title" do expect(component.new(:name => "bar").ref).to eq("Class[Bar]") end it "should always produce a resource reference string as its title" do expect(component.new(:name => "bar").title).to eq("Class[Bar]") end it "should have a reference string equivalent to its title" do comp = component.new(:name => "Foo[bar]") expect(comp.title).to eq(comp.ref) end it "should not fail when provided an invalid value" do comp = component.new(:name => "Foo[bar]") expect { comp[:yayness] = "ey" }.not_to raise_error end it "should return previously provided invalid values" do comp = component.new(:name => "Foo[bar]") comp[:yayness] = "eh" expect(comp[:yayness]).to eq("eh") end it "should correctly support metaparameters" do comp = component.new(:name => "Foo[bar]", :require => "Foo[bar]") expect(comp.parameter(:require)).to be_instance_of(component.attrclass(:require)) end describe "when building up the path" do it "should produce the class name if the component models a class" do expect(component.new(:name => "Class[foo]").pathbuilder).to eq(["Foo"]) end it "should produce the class name even for the class named main" do expect(component.new(:name => "Class[main]").pathbuilder).to eq(["Main"]) end it "should produce a resource reference if the component does not model a class" do expect(component.new(:name => "Foo[bar]").pathbuilder).to eq(["Foo[bar]"]) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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, /`down' for nil/) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false