repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load3.rb | spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load3.rb | module Puppet::Parser::Functions
newfunction(:bad_func_load3, :type => :rvalue, :doc => <<-EOS
A function using the 3x API
EOS
) do |arguments|
def bad_func_load3_illegal_method
"some return value from illegal method"
end
"some return value"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/func_with_syntax_error.rb | spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/func_with_syntax_error.rb | module Puppet::Parser::Functions
newfunction(:func_with_syntax_error, :type => :rvalue, :doc => <<-EOS
A function using the 3x API having a syntax error
EOS
) do |arguments|
# this syntax error is here on purpose!
1+ + + +
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/rb_func_a.rb | spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/rb_func_a.rb | Puppet::Functions.create_function(:rb_func_a) do
def rb_func_a()
"I am rb_func_a()"
end
end | ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/modulea/rb_func_a.rb | spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/modulea/rb_func_a.rb | Puppet::Functions.create_function(:'modulea::rb_func_a') do
def rb_func_a()
"I am modulea::rb_func_a()"
end
end | ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/wo_metadata_module/modules/moduleb/lib/puppet/functions/moduleb/rb_func_b.rb | spec/fixtures/unit/pops/loaders/loaders/wo_metadata_module/modules/moduleb/lib/puppet/functions/moduleb/rb_func_b.rb | Puppet::Functions.create_function(:'moduleb::rb_func_b') do
def rb_func_b()
# Should be able to call modulea::rb_func_a()
call_function('modulea::rb_func_a') + " + I am moduleb::rb_func_b()"
end
end | ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/data_providers/environments/production/modules/abc/lib/puppet/functions/abc/data.rb | spec/fixtures/unit/data_providers/environments/production/modules/abc/lib/puppet/functions/abc/data.rb | Puppet::Functions.create_function(:'abc::data') do
def data()
{ 'abc::def::test1' => 'module_test1',
'abc::def::test2' => 'module_test2',
'abc::def::test3' => 'module_test3',
'abc::def::ipl' => '%{lookup("abc::def::test2")}-ipl'
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/data_providers/environments/production/lib/puppet/functions/environment/data.rb | spec/fixtures/unit/data_providers/environments/production/lib/puppet/functions/environment/data.rb | Puppet::Functions.create_function(:'environment::data') do
def data()
{ 'abc::def::test1' => 'env_test1',
'abc::def::test2' => 'env_test2',
'xyz::def::test1' => 'env_test1',
'xyz::def::test2' => 'env_test2'
}
end
end | ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bad_data/lib/puppet/functions/bad_data/data.rb | spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bad_data/lib/puppet/functions/bad_data/data.rb | Puppet::Functions.create_function(:'bad_data::data') do
def data()
{ 'b' => 'module_b', # Intentionally bad key (no module prefix)
'bad_data::c' => 'module_c' # Good key. Should be OK
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/abc/lib/puppet/functions/abc/data.rb | spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/abc/lib/puppet/functions/abc/data.rb | Puppet::Functions.create_function(:'abc::data') do
def data()
{ 'abc::b' => 'module_b',
'abc::c' => 'module_c',
'abc::e' => { 'k1' => 'module_e1', 'k2' => 'module_e2' },
'abc::f' => { 'k1' => { 's1' => 'module_f11', 's3' => 'module_f13' }, 'k2' => { 's1' => 'module_f21', 's2' => 'module_f22' }},
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bca/lib/puppet/functions/bca/data.rb | spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bca/lib/puppet/functions/bca/data.rb | Puppet::Functions.create_function(:'bca::data') do
def data()
{ 'bca::b' => 'module_bca_b',
'bca::c' => 'module_bca_c',
'bca::e' => { 'k1' => 'module_bca_e1', 'k2' => 'module_bca_e2' },
'bca::f' => { 'k1' => { 's1' => 'module_bca_f11', 's3' => 'module_bca_f13' }, 'k2' => { 's1' => 'module_bca_f21', 's2' => 'module_bca_f22' }},
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/meta/lib/puppet/functions/meta/data.rb | spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/meta/lib/puppet/functions/meta/data.rb | Puppet::Functions.create_function(:'meta::data') do
def data()
{ 'meta::b' => 'module_b',
'meta::c' => 'module_c',
'meta::e' => { 'k1' => 'module_e1', 'k2' => 'module_e2' },
'meta::f' => { 'k1' => { 's1' => 'module_f11', 's3' => 'module_f13' }, 'k2' => { 's1' => 'module_f21', 's2' => 'module_f22' }},
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/lookup_fixture/environments/production/lib/puppet/functions/environment/data.rb | spec/fixtures/unit/functions/lookup_fixture/environments/production/lib/puppet/functions/environment/data.rb | Puppet::Functions.create_function(:'environment::data') do
def data()
{ 'abc::a' => 'env_a',
'abc::c' => 'env_c',
'abc::d' => { 'k1' => 'env_d1', 'k2' => 'env_d2', 'k3' => 'env_d3' },
'abc::e' => { 'k1' => 'env_e1', 'k3' => 'env_e3' },
'bca::e' => { 'k1' => 'env_bca_e1', 'k3' => 'env_bca_e3' },
'no_provider::e' => { 'k1' => 'env_no_provider_e1', 'k3' => 'env_no_provider_e3' },
'abc::f' => { 'k1' => { 's1' => 'env_f11', 's2' => 'env_f12' }, 'k2' => { 's1' => 'env_f21', 's3' => 'env_f23' }},
'abc::n' => nil
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/lookup/hiera/backend/other_backend.rb | spec/fixtures/unit/functions/lookup/hiera/backend/other_backend.rb | class Hiera::Backend::Other_backend
def lookup(key, scope, order_override, resolution_type, context)
value = Hiera::Config[:other][key.to_sym]
throw :no_such_key if value.nil?
value
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/lookup/hiera/backend/custom_backend.rb | spec/fixtures/unit/functions/lookup/hiera/backend/custom_backend.rb | class Hiera::Backend::Custom_backend
def lookup(key, scope, order_override, resolution_type, context)
case key
when 'hash_c'
{ 'hash_ca' => { 'cad' => 'value hash_c.hash_ca.cad (from global custom)' }}
when 'hash'
{ 'array' => [ 'x5,x6' ] }
when 'array'
[ 'x5,x6' ]
when 'datasources'
Hiera::Backend.datasources(scope, order_override) { |source| source }
when 'dotted.key'
'custom backend received request for dotted.key value'
else
throw :no_such_key
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/functions/hiera/hiera/backend/hieraspec_backend.rb | spec/fixtures/unit/functions/hiera/hiera/backend/hieraspec_backend.rb | class Hiera::Backend::Hieraspec_backend
def initialize(cache = nil)
Hiera.debug('Custom_backend starting')
end
def lookup(key, scope, order_override, resolution_type, context)
case key
when 'datasources'
Hiera::Backend.datasources(scope, order_override) { |source| source }
when 'resolution_type'
if resolution_type == :hash
{ key => resolution_type.to_s }
elsif resolution_type == :array
[ key, resolution_type.to_s ]
else
"resolution_type=#{resolution_type}"
end
else
throw :no_such_key
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/releases/jamtur01-apache/lib/puppet/type/a2mod.rb | spec/fixtures/releases/jamtur01-apache/lib/puppet/type/a2mod.rb | Puppet::Type.newtype(:a2mod) do
@doc = "Manage Apache 2 modules"
ensurable
newparam(:name) do
desc "The name of the module to be managed"
isnamevar
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/releases/jamtur01-apache/lib/puppet/provider/a2mod/debian.rb | spec/fixtures/releases/jamtur01-apache/lib/puppet/provider/a2mod/debian.rb | Puppet::Type.type(:a2mod).provide(:debian) do
desc "Manage Apache 2 modules on Debian-like OSes (e.g. Ubuntu)"
commands :encmd => "a2enmod"
commands :discmd => "a2dismod"
defaultfor 'os.name' => [:debian, :ubuntu]
def create
encmd resource[:name]
end
def destroy
discmd resource[:name]
end
def exists?
mod= "/etc/apache2/mods-enabled/" + resource[:name] + ".load"
Puppet::FileSystem.exist?(mod)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/shared_examples/rhel_package_provider.rb | spec/shared_examples/rhel_package_provider.rb | shared_examples "RHEL package provider" do |provider_class, provider_name|
describe provider_name do
let(:name) { 'mypackage' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => name,
:ensure => :installed,
:provider => provider_name
)
end
let(:provider) do
provider = provider_class.new
provider.resource = resource
provider
end
let(:arch) { 'x86_64' }
let(:arch_resource) do
Puppet::Type.type(:package).new(
:name => "#{name}.#{arch}",
:ensure => :installed,
:provider => provider_name
)
end
let(:arch_provider) do
provider = provider_class.new
provider.resource = arch_resource
provider
end
case provider_name
when 'yum'
let(:error_level) { '0' }
when 'dnf'
let(:error_level) { '1' }
when 'tdnf'
let(:error_level) { '1' }
end
case provider_name
when 'yum'
let(:upgrade_command) { 'update' }
when 'dnf'
let(:upgrade_command) { 'upgrade' }
when 'tdnf'
let(:upgrade_command) { 'upgrade' }
end
before do
allow(provider_class).to receive(:command).with(:cmd).and_return("/usr/bin/#{provider_name}")
allow(provider).to receive(:rpm).and_return('rpm')
allow(provider).to receive(:get).with(:version).and_return('1')
allow(provider).to receive(:get).with(:release).and_return('1')
allow(provider).to receive(:get).with(:arch).and_return('i386')
end
describe 'provider features' do
it { is_expected.to be_versionable }
it { is_expected.to be_install_options }
it { is_expected.to be_virtual_packages }
end
# provider should repond to the following methods
[:install, :latest, :update, :purge, :install_options].each do |method|
it "should have a(n) #{method}" do
expect(provider).to respond_to(method)
end
end
describe 'when installing' do
before(:each) do
allow(Puppet::Util).to receive(:which).with("rpm").and_return("/bin/rpm")
allow(provider).to receive(:which).with("rpm").and_return("/bin/rpm")
expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/rpm", "--version"], {:combine => true, :custom_environment => {}, :failonfail => true}).and_return(Puppet::Util::Execution::ProcessOutput.new("4.10.1\n", 0)).at_most(:once)
allow(Facter).to receive(:value).with('os.release.major').and_return('6')
end
it "should call #{provider_name} install for :installed" do
allow(resource).to receive(:should).with(:ensure).and_return(:installed)
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, 'mypackage'])
provider.install
end
if provider_name == 'yum'
context 'on el-5' do
before(:each) do
allow(Facter).to receive(:value).with('os.release.major').and_return('5')
end
it "should catch #{provider_name} install failures when status code is wrong" do
allow(resource).to receive(:should).with(:ensure).and_return(:installed)
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, name]).and_return(Puppet::Util::Execution::ProcessOutput.new("No package #{name} available.", 0))
expect {
provider.install
}.to raise_error(Puppet::Error, "Could not find package #{name}")
end
end
end
it 'should use :install to update' do
expect(provider).to receive(:install)
provider.update
end
it 'should be able to set version' do
version = '1.2'
resource[:ensure] = version
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, "#{name}-#{version}"])
allow(provider).to receive(:query).and_return(:ensure => version)
provider.install
end
it 'should handle partial versions specified' do
version = '1.3.4'
resource[:ensure] = version
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, 'mypackage-1.3.4'])
allow(provider).to receive(:query).and_return(:ensure => '1.3.4-1.el6')
provider.install
end
it 'should be able to downgrade' do
current_version = '1.2'
version = '1.0'
resource[:ensure] = '1.0'
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :downgrade, "#{name}-#{version}"])
allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version})
provider.install
end
it 'should be able to upgrade' do
current_version = '1.0'
version = '1.2'
resource[:ensure] = '1.2'
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', upgrade_command, "#{name}-#{version}"])
allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version})
provider.install
end
it 'should not run upgrade command if absent and ensure latest' do
current_version = ''
version = '1.2'
resource[:ensure] = :latest
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, name])
allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version})
provider.install
end
it 'should run upgrade command if present and ensure latest' do
current_version = '1.0'
version = '1.2'
resource[:ensure] = :latest
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', upgrade_command, name])
allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version})
provider.install
end
it 'should accept install options' do
resource[:ensure] = :installed
resource[:install_options] = ['-t', {'-x' => 'expackage'}]
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', ['-t', '-x=expackage'], :install, name])
provider.install
end
it 'allow virtual packages' do
resource[:ensure] = :installed
resource[:allow_virtual] = true
expect(Puppet::Util::Execution).not_to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :list, name])
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, name])
provider.install
end
it 'moves architecture to end of version' do
version = '1.2.3'
arch_resource[:ensure] = version
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, "#{name}-#{version}.#{arch}"])
allow(arch_provider).to receive(:query).and_return(:ensure => version)
arch_provider.install
end
it "does not move '-noarch' to the end of version" do
version = '1.2.3'
resource = Puppet::Type.type(:package).new(
:name => "#{name}-noarch",
:ensure => version,
:provider =>provider_name
)
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :install, "#{name}-noarch-#{version}"])
provider = provider_class.new
provider.resource = resource
allow(provider).to receive(:query).and_return(:ensure => version)
provider.install
end
end
describe 'when uninstalling' do
it 'should use remove to purge' do
expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :remove, name])
provider.purge
end
end
it 'should be versionable' do
expect(provider).to be_versionable
end
describe 'determining the latest version available for a package' do
it "passes the value of enablerepo install_options when querying" do
resource[:install_options] = [
{'--enablerepo' => 'contrib'},
{'--enablerepo' => 'centosplus'},
]
allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'})
expect(described_class).to receive(:latest_package_version).with(name, [], ['contrib', 'centosplus'], [])
provider.latest
end
it "passes the value of disablerepo install_options when querying" do
resource[:install_options] = [
{'--disablerepo' => 'updates'},
{'--disablerepo' => 'centosplus'},
]
allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'})
expect(described_class).to receive(:latest_package_version).with(name, ['updates', 'centosplus'], [], [])
provider.latest
end
it "passes the value of disableexcludes install_options when querying" do
resource[:install_options] = [
{'--disableexcludes' => 'main'},
{'--disableexcludes' => 'centosplus'},
]
allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'})
expect(described_class).to receive(:latest_package_version).with(name, [], [], ['main', 'centosplus'])
provider.latest
end
describe 'and a newer version is not available' do
before :each do
allow(described_class).to receive(:latest_package_version).with(name, [], [], []).and_return(nil)
end
it 'raises an error the package is not installed' do
allow(provider).to receive(:properties).and_return({:ensure => :absent})
expect {
provider.latest
}.to raise_error(Puppet::DevError, 'Tried to get latest on a missing package')
end
it 'returns version of the currently installed package' do
allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'})
expect(provider.latest).to eq('3.4.5')
end
end
describe 'and a newer version is available' do
let(:latest_version) do
{
:name => name,
:epoch => '1',
:version => '2.3.4',
:release => '5',
:arch => 'i686',
}
end
it 'includes the epoch in the version string' do
allow(described_class).to receive(:latest_package_version).with(name, [], [], []).and_return(latest_version)
expect(provider.latest).to eq('1:2.3.4-5')
end
end
end
describe "lazy loading of latest package versions" do
before { described_class.clear }
after { described_class.clear }
let(:mypackage_version) do
{
:name => name,
:epoch => '1',
:version => '2.3.4',
:release => '5',
:arch => 'i686',
}
end
let(:mypackage_newerversion) do
{
:name => name,
:epoch => '1',
:version => '4.5.6',
:release => '7',
:arch => 'i686',
}
end
let(:latest_versions) { {name => [mypackage_version]} }
let(:enabled_versions) { {name => [mypackage_newerversion]} }
it "returns the version hash if the package was found" do
expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions)
version = described_class.latest_package_version(name, [], [], [])
expect(version).to eq(mypackage_version)
end
it "is nil if the package was not found in the query" do
expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions)
version = described_class.latest_package_version('nopackage', [], [], [])
expect(version).to be_nil
end
it "caches the package list and reuses that for subsequent queries" do
expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions)
2.times {
version = described_class.latest_package_version(name, [], [], [])
expect(version).to eq mypackage_version
}
end
it "caches separate lists for each combination of 'disablerepo' and 'enablerepo' and 'disableexcludes'" do
expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions)
expect(described_class).to receive(:check_updates).with(['disabled'], ['enabled'], ['disableexcludes']).once.and_return(enabled_versions)
2.times {
version = described_class.latest_package_version(name, [], [], [])
expect(version).to eq mypackage_version
}
2.times {
version = described_class.latest_package_version(name, ['disabled'], ['enabled'], ['disableexcludes'])
expect(version).to eq(mypackage_newerversion)
}
end
end
describe "executing #{provider_name} check-update" do
it "passes repos to enable to '#{provider_name} check-update'" do
expect(Puppet::Util::Execution).to receive(:execute).with(
%W[/usr/bin/#{provider_name} -y check-update --enablerepo=updates --enablerepo=centosplus],
any_args
).and_return(double(:exitstatus => 0))
described_class.check_updates([], %W[updates centosplus], [])
end
it "passes repos to disable to '#{provider_name} check-update'" do
expect(Puppet::Util::Execution).to receive(:execute).with(
%W[/usr/bin/#{provider_name} -y check-update --disablerepo=updates --disablerepo=centosplus],
any_args
).and_return(double(:exitstatus => 0))
described_class.check_updates(%W[updates centosplus], [], [])
end
it "passes a combination of repos to enable and disable to '#{provider_name} check-update'" do
expect(Puppet::Util::Execution).to receive(:execute).with(
%W[/usr/bin/#{provider_name} -y check-update --disablerepo=updates --disablerepo=centosplus --enablerepo=os --enablerepo=contrib ],
any_args
).and_return(double(:exitstatus => 0))
described_class.check_updates(%W[updates centosplus], %W[os contrib], [])
end
it "passes disableexcludes to '#{provider_name} check-update'" do
expect(Puppet::Util::Execution).to receive(:execute).with(
%W[/usr/bin/#{provider_name} -y check-update --disableexcludes=main --disableexcludes=centosplus],
any_args
).and_return(double(:exitstatus => 0))
described_class.check_updates([], [], %W[main centosplus])
end
it "passes all options to '#{provider_name} check-update'" do
expect(Puppet::Util::Execution).to receive(:execute).with(
%W[/usr/bin/#{provider_name} -y check-update --disablerepo=a --disablerepo=b --enablerepo=c --enablerepo=d --disableexcludes=e --disableexcludes=f],
any_args
).and_return(double(:exitstatus => 0))
described_class.check_updates(%W[a b], %W[c d], %W[e f])
end
it "returns an empty hash if '#{provider_name} check-update' returned 0" do
expect(Puppet::Util::Execution).to receive(:execute).and_return(double(:exitstatus => 0))
expect(described_class.check_updates([], [], [])).to be_empty
end
it "returns a populated hash if '#{provider_name} check-update returned 100'" do
output = double(:exitstatus => 100)
expect(Puppet::Util::Execution).to receive(:execute).and_return(output)
expect(described_class).to receive(:parse_updates).with(output).and_return({:has => :updates})
expect(described_class.check_updates([], [], [])).to eq({:has => :updates})
end
it "returns an empty hash if '#{provider_name} check-update' returned an exit code that was not 0 or 100" do
expect(Puppet::Util::Execution).to receive(:execute).and_return(double(:exitstatus => 1))
expect(described_class).to receive(:warning).with("Could not check for updates, \'/usr/bin/#{provider_name} check-update\' exited with 1")
expect(described_class.check_updates([], [], [])).to eq({})
end
end
describe "parsing a line from #{provider_name} check-update" do
it "splits up the package name and architecture fields" do
checkupdate = %W[curl.i686 7.32.0-10.fc20]
parsed = described_class.update_to_hash(*checkupdate)
expect(parsed[:name]).to eq 'curl'
expect(parsed[:arch]).to eq 'i686'
end
it "splits up the epoch, version, and release fields" do
checkupdate = %W[dhclient.i686 12:4.1.1-38.P1.el6.centos]
parsed = described_class.update_to_hash(*checkupdate)
expect(parsed[:epoch]).to eq '12'
expect(parsed[:version]).to eq '4.1.1'
expect(parsed[:release]).to eq '38.P1.el6.centos'
end
it "sets the epoch to 0 when an epoch is not specified" do
checkupdate = %W[curl.i686 7.32.0-10.fc20]
parsed = described_class.update_to_hash(*checkupdate)
expect(parsed[:epoch]).to eq '0'
expect(parsed[:version]).to eq '7.32.0'
expect(parsed[:release]).to eq '10.fc20'
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/shared_contexts/provider.rb | spec/shared_contexts/provider.rb | require 'spec_helper'
RSpec.shared_context('provider specificity') do
around do |example|
old_defaults = described_class.instance_variable_get(:@defaults)
old_notdefaults = described_class.instance_variable_get(:@notdefaults)
begin
described_class.instance_variable_set(:@defaults, [])
described_class.instance_variable_set(:@notdefaults, [])
example.run
ensure
described_class.instance_variable_set(:@defaults, old_defaults)
described_class.instance_variable_set(:@notdefaults, old_notdefaults)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/shared_contexts/l10n.rb | spec/shared_contexts/l10n.rb | require 'spec_helper'
RSpec.shared_context('l10n') do |locale|
before :all do
@old_locale = Locale.current
Locale.current = locale
@old_gettext_disabled = Puppet::GettextConfig.instance_variable_get(:@gettext_disabled)
Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, false)
Puppet::GettextConfig.setup_locale
Puppet::GettextConfig.create_default_text_domain
# overwrite stubs with real implementation
::Object.send(:remove_method, :_)
::Object.send(:remove_method, :n_)
class ::Object
include FastGettext::Translation
end
end
after :all do
Locale.current = @old_locale
Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, @old_gettext_disabled)
# restore stubs
load File.expand_path(File.join(__dir__, '../../lib/puppet/gettext/stubs.rb'))
end
before :each do
Puppet[:disable_i18n] = false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/shared_contexts/checksum.rb | spec/shared_contexts/checksum.rb | # Shared contexts for testing against all supported checksum types.
#
# These helpers define nested rspec example groups to test code against all our
# supported checksum types. Example groups that need to be run against all
# types should use the `with_checksum_types` helper which will
# create a new example group for each types and will run the given block
# in each example group.
CHECKSUM_PLAINTEXT = "1\r\n"*4000
CHECKSUM_TYPES_TO_TRY = [
['md5', 'a7a169ac84bb863b30484d0aa03139c1'],
['md5lite', '22b4182363e81b326e98231fde616782'],
['sha256', '47fcae62967db2fb5cba2fc0d9cf3e6767035d763d825ecda535a7b1928b9746'],
['sha256lite', 'fd50217a2b0286ba25121bf2297bbe6c197933992de67e4e568f19861444ecf8'],
['sha224', '6894cd976b60b2caa825bc699b54f715853659f0243f67cda4dd7ac4'],
['sha384', 'afc3d952fe1a4d3aa083d438ea464f6e7456c048d34ff554340721b463b38547e5ee7c964513dfba0d65dd91ac97deb5'],
['sha512', 'a953dcd95824cfa2a555651585d3980b1091a740a785d52ee5e72a55c9038242433e55026758636b0a29d0e5f9e77f24bc888ea5d5e01ab36d2bbcb3d3163859']
]
CHECKSUM_STAT_TIME = Time.now
TIME_TYPES_TO_TRY = [
['ctime', "#{CHECKSUM_STAT_TIME}"],
['mtime', "#{CHECKSUM_STAT_TIME}"]
]
shared_context('with supported checksum types') do
def self.with_checksum_types(path, file, &block)
def checksum_valid(checksum_type, expected_checksum, actual_checksum_signature)
case checksum_type
when 'mtime', 'ctime'
expect(DateTime.parse(actual_checksum_signature)).to be >= DateTime.parse(expected_checksum)
else
expect(actual_checksum_signature).to eq("{#{checksum_type}}#{expected_checksum}")
end
end
def expect_correct_checksum(meta, checksum_type, checksum, type)
expect(meta).to_not be_nil
expect(meta).to be_instance_of(type)
expect(meta.checksum_type).to eq(checksum_type)
expect(checksum_valid(checksum_type, checksum, meta.checksum)).to be_truthy
end
(CHECKSUM_TYPES_TO_TRY + TIME_TYPES_TO_TRY).each do |checksum_type, checksum|
describe("when checksum_type is #{checksum_type}") do
let(:checksum_type) { checksum_type }
let(:plaintext) { CHECKSUM_PLAINTEXT }
let(:checksum) { checksum }
let(:env_path) { tmpfile(path) }
let(:checksum_file) { File.join(env_path, file) }
def digest(content)
Puppet::Util::Checksums.send(checksum_type, content)
end
before(:each) do
FileUtils.mkdir_p(File.dirname(checksum_file))
File.open(checksum_file, "wb") { |f| f.write plaintext }
end
instance_eval(&block)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/shared_contexts/digests.rb | spec/shared_contexts/digests.rb | # Shared contexts for testing against all supported digest algorithms.
#
# These helpers define nested rspec example groups to test code against all our
# supported digest algorithms. Example groups that need to be run against all
# algorithms should use the `with_digest_algorithms` helper which will
# create a new example group for each algorithm and will run the given block
# in each example group.
#
# For each algorithm a shared context is defined for the given algorithm that
# has precomputed checksum values and paths. These contexts are included
# automatically based on the rspec metadata selected with
# `with_digest_algorithms`.
DIGEST_ALGORITHMS_TO_TRY = ['md5', 'sha256', 'sha384', 'sha512', 'sha224']
shared_context('with supported digest algorithms', :uses_checksums => true) do
def self.with_digest_algorithms(&block)
DIGEST_ALGORITHMS_TO_TRY.each do |digest_algorithm|
describe("when digest_algorithm is #{digest_algorithm}", :digest_algorithm => digest_algorithm) do
instance_eval(&block)
end
end
end
end
shared_context("when digest_algorithm is set to sha256", :digest_algorithm => 'sha256') do
before { Puppet[:digest_algorithm] = 'sha256' }
after { Puppet[:digest_algorithm] = nil }
let(:digest_algorithm) { 'sha256' }
let(:plaintext) { "my\r\ncontents" }
let(:checksum) { '409a11465ed0938227128b1756c677a8480a8b84814f1963853775e15a74d4b4' }
let(:bucket_dir) { '4/0/9/a/1/1/4/6/409a11465ed0938227128b1756c677a8480a8b84814f1963853775e15a74d4b4' }
def digest(content)
Puppet::Util::Checksums.sha256(content)
end
end
shared_context("when digest_algorithm is set to md5", :digest_algorithm => 'md5') do
before { Puppet[:digest_algorithm] = 'md5' }
after { Puppet[:digest_algorithm] = nil }
let(:digest_algorithm) { 'md5' }
let(:plaintext) { "my\r\ncontents" }
let(:checksum) { 'f0d7d4e480ad698ed56aeec8b6bd6dea' }
let(:bucket_dir) { 'f/0/d/7/d/4/e/4/f0d7d4e480ad698ed56aeec8b6bd6dea' }
def digest(content)
Puppet::Util::Checksums.md5(content)
end
end
shared_context("when digest_algorithm is set to sha512", :digest_algorithm => 'sha512') do
before { Puppet[:digest_algorithm] = 'sha512' }
after { Puppet[:digest_algorithm] = nil }
let(:digest_algorithm) { 'sha512' }
let(:plaintext) { "my\r\ncontents" }
let(:checksum) { 'ed9b62ae313c8e4e3e6a96f937101e85f8f8af8d51dea7772177244087e5d6152778605ad6bdb42886ff1436abaec4fa44acbfe171fda755959b52b0e4e015d4' }
let(:bucket_dir) { 'e/d/9/b/6/2/a/e/ed9b62ae313c8e4e3e6a96f937101e85f8f8af8d51dea7772177244087e5d6152778605ad6bdb42886ff1436abaec4fa44acbfe171fda755959b52b0e4e015d4' }
def digest(content)
Puppet::Util::Checksums.sha512(content)
end
end
shared_context("when digest_algorithm is set to sha384", :digest_algorithm => 'sha384') do
before { Puppet[:digest_algorithm] = 'sha384' }
after { Puppet[:digest_algorithm] = nil }
let(:digest_algorithm) { 'sha384' }
let(:plaintext) { "my\r\ncontents" }
let(:checksum) { 'f40debfec135e4f2b9fb92110c53aadb8e9bda28bb05f09901480fd70126fe3b70f9f074ce6182ec8184eb1bcabe4440' }
let(:bucket_dir) { 'f/4/0/d/e/b/f/e/f40debfec135e4f2b9fb92110c53aadb8e9bda28bb05f09901480fd70126fe3b70f9f074ce6182ec8184eb1bcabe4440' }
def digest(content)
Puppet::Util::Checksums.sha384(content)
end
end
shared_context("when digest_algorithm is set to sha224", :digest_algorithm => 'sha224') do
before { Puppet[:digest_algorithm] = 'sha224' }
after { Puppet[:digest_algorithm] = nil }
let(:digest_algorithm) { 'sha224' }
let(:plaintext) { "my\r\ncontents" }
let(:checksum) { 'b8c05079b24c37a0e03f03e611167a3ea24455db3ad638a3a0c7e9cb' }
let(:bucket_dir) { 'b/8/c/0/5/0/7/9/b8c05079b24c37a0e03f03e611167a3ea24455db3ad638a3a0c7e9cb' }
def digest(content)
Puppet::Util::Checksums.sha224(content)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/shared_contexts/types_setup.rb | spec/shared_contexts/types_setup.rb | shared_context 'types_setup' do
# Do not include the special type Unit in this list
# Do not include the type Variant in this list as it needs to be parameterized to be meaningful
def self.all_types
[ Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PUndefType,
Puppet::Pops::Types::PNotUndefType,
Puppet::Pops::Types::PScalarType,
Puppet::Pops::Types::PScalarDataType,
Puppet::Pops::Types::PStringType,
Puppet::Pops::Types::PNumericType,
Puppet::Pops::Types::PIntegerType,
Puppet::Pops::Types::PFloatType,
Puppet::Pops::Types::PRegexpType,
Puppet::Pops::Types::PBooleanType,
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PArrayType,
Puppet::Pops::Types::PHashType,
Puppet::Pops::Types::PIterableType,
Puppet::Pops::Types::PIteratorType,
Puppet::Pops::Types::PRuntimeType,
Puppet::Pops::Types::PClassType,
Puppet::Pops::Types::PResourceType,
Puppet::Pops::Types::PPatternType,
Puppet::Pops::Types::PEnumType,
Puppet::Pops::Types::PStructType,
Puppet::Pops::Types::PTupleType,
Puppet::Pops::Types::PCallableType,
Puppet::Pops::Types::PTypeType,
Puppet::Pops::Types::POptionalType,
Puppet::Pops::Types::PDefaultType,
Puppet::Pops::Types::PTypeReferenceType,
Puppet::Pops::Types::PTypeAliasType,
Puppet::Pops::Types::PSemVerType,
Puppet::Pops::Types::PSemVerRangeType,
Puppet::Pops::Types::PTimespanType,
Puppet::Pops::Types::PTimestampType,
Puppet::Pops::Types::PSensitiveType,
Puppet::Pops::Types::PBinaryType,
Puppet::Pops::Types::PInitType,
Puppet::Pops::Types::PURIType,
]
end
def all_types
self.class.all_types
end
# Do not include the Variant type in this list - while it is abstract it is also special in that
# it must be parameterized to be meaningful.
#
def self.abstract_types
[ Puppet::Pops::Types::PAnyType,
Puppet::Pops::Types::PCallableType,
Puppet::Pops::Types::PEnumType,
Puppet::Pops::Types::PClassType,
Puppet::Pops::Types::PDefaultType,
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PInitType,
Puppet::Pops::Types::PIterableType,
Puppet::Pops::Types::PIteratorType,
Puppet::Pops::Types::PNotUndefType,
Puppet::Pops::Types::PResourceType,
Puppet::Pops::Types::PRuntimeType,
Puppet::Pops::Types::POptionalType,
Puppet::Pops::Types::PPatternType,
Puppet::Pops::Types::PScalarType,
Puppet::Pops::Types::PScalarDataType,
Puppet::Pops::Types::PUndefType,
Puppet::Pops::Types::PTypeReferenceType,
Puppet::Pops::Types::PTypeAliasType,
]
end
def abstract_types
self.class.abstract_types
end
# Internal types. Not meaningful in pp
def self.internal_types
[ Puppet::Pops::Types::PTypeReferenceType,
Puppet::Pops::Types::PTypeAliasType,
]
end
def internal_types
self.class.internal_types
end
def self.scalar_data_types
# PVariantType is also scalar data, if its types are all ScalarData
[
Puppet::Pops::Types::PScalarDataType,
Puppet::Pops::Types::PStringType,
Puppet::Pops::Types::PNumericType,
Puppet::Pops::Types::PIntegerType,
Puppet::Pops::Types::PFloatType,
Puppet::Pops::Types::PBooleanType,
Puppet::Pops::Types::PEnumType,
Puppet::Pops::Types::PPatternType,
]
end
def scalar_data_types
self.class.scalar_data_types
end
def self.scalar_types
# PVariantType is also scalar, if its types are all Scalar
[
Puppet::Pops::Types::PScalarType,
Puppet::Pops::Types::PScalarDataType,
Puppet::Pops::Types::PStringType,
Puppet::Pops::Types::PNumericType,
Puppet::Pops::Types::PIntegerType,
Puppet::Pops::Types::PFloatType,
Puppet::Pops::Types::PRegexpType,
Puppet::Pops::Types::PBooleanType,
Puppet::Pops::Types::PPatternType,
Puppet::Pops::Types::PEnumType,
Puppet::Pops::Types::PSemVerType,
Puppet::Pops::Types::PTimespanType,
Puppet::Pops::Types::PTimestampType,
]
end
def scalar_types
self.class.scalar_types
end
def self.numeric_types
# PVariantType is also numeric, if its types are all numeric
[
Puppet::Pops::Types::PNumericType,
Puppet::Pops::Types::PIntegerType,
Puppet::Pops::Types::PFloatType,
]
end
def numeric_types
self.class.numeric_types
end
def self.string_types
# PVariantType is also string type, if its types are all compatible
[
Puppet::Pops::Types::PStringType,
Puppet::Pops::Types::PPatternType,
Puppet::Pops::Types::PEnumType,
]
end
def string_types
self.class.string_types
end
def self.collection_types
# PVariantType is also string type, if its types are all compatible
[
Puppet::Pops::Types::PCollectionType,
Puppet::Pops::Types::PHashType,
Puppet::Pops::Types::PArrayType,
Puppet::Pops::Types::PStructType,
Puppet::Pops::Types::PTupleType,
]
end
def collection_types
self.class.collection_types
end
def self.data_compatible_types
tf = Puppet::Pops::Types::TypeFactory
result = scalar_data_types
result << Puppet::Pops::Types::PArrayType.new(tf.data)
result << Puppet::Pops::Types::PHashType.new(Puppet::Pops::Types::PStringType::DEFAULT, tf.data)
result << Puppet::Pops::Types::PUndefType
result << Puppet::Pops::Types::PTupleType.new([tf.data])
result
end
def data_compatible_types
self.class.data_compatible_types
end
def self.rich_data_compatible_types
tf = Puppet::Pops::Types::TypeFactory
result = scalar_types
result << Puppet::Pops::Types::PArrayType.new(tf.rich_data)
result << Puppet::Pops::Types::PHashType.new(tf.rich_data_key, tf.rich_data)
result << Puppet::Pops::Types::PUndefType
result << Puppet::Pops::Types::PDefaultType
result << Puppet::Pops::Types::PURIType
result << Puppet::Pops::Types::PTupleType.new([tf.rich_data])
result << Puppet::Pops::Types::PObjectType
result << Puppet::Pops::Types::PTypeType
result << Puppet::Pops::Types::PTypeSetType
result
end
def rich_data_compatible_types
self.class.rich_data_compatible_types
end
def self.type_from_class(c)
c.is_a?(Class) ? c::DEFAULT : c
end
def type_from_class(c)
self.class.type_from_class(c)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/shared_contexts/https.rb | spec/shared_contexts/https.rb | require 'spec_helper'
RSpec.shared_context('https client') do
before :all do
WebMock.disable!
end
after :all do
WebMock.enable!
end
before :each do
# make sure we don't take too long
Puppet[:http_connect_timeout] = '5s'
Puppet[:server] = '127.0.0.1'
Puppet[:certname] = '127.0.0.1'
Puppet[:localcacert] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'ca.pem')
Puppet[:hostcrl] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'crl.pem')
Puppet[:hostprivkey] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', '127.0.0.1-key.pem')
Puppet[:hostcert] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', '127.0.0.1.pem')
# set in memory facts since certname is changed above
facts = Puppet::Node::Facts.new(Puppet[:certname])
Puppet::Node::Facts.indirection.save(facts)
end
let(:https_server) { PuppetSpec::HTTPSServer.new }
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/matchers/match_tokens2.rb | spec/lib/matchers/match_tokens2.rb | # Matches tokens produced by lexer
# The given exepected is one or more entries where an entry is one of
# - a token symbol
# - an Array with a token symbol and the text value
# - an Array with a token symbol and a Hash specifying all attributes of the token
# - nil (ignore)
#
RSpec::Matchers.define :match_tokens2 do | *expected |
match do | actual |
expected.zip(actual).all? do |e, a|
compare(e, a)
end
end
def failure_message
msg = ["Expected (#{expected.size}):"]
expected.each {|e| msg << e.to_s }
zipped = expected.zip(actual)
msg << "\nGot (#{actual.size}):"
actual.each_with_index do |e, idx|
if zipped[idx]
zipped_expected = zipped[idx][0]
zipped_actual = zipped[idx][1]
prefix = compare(zipped_expected, zipped_actual) ? ' ' : '*'
msg2 = ["#{prefix}[:"]
msg2 << e[0].to_s
msg2 << ', '
if e[1] == false
msg2 << 'false'
else
msg2 << e[1][:value].to_s.dump
end
# If expectation has options, output them
if zipped_expected.is_a?(Array) && zipped_expected[2] && zipped_expected[2].is_a?(Hash)
msg2 << ", {"
msg3 = []
zipped_expected[2].each do |k,v|
prefix = e[1][k] != v ? "*" : ''
msg3 << "#{prefix}:#{k}=>#{e[1][k]}"
end
msg2 << msg3.join(", ")
msg2 << "}"
end
msg2 << ']'
msg << msg2.join('')
end
end
msg.join("\n")
end
def compare(e, a)
# if expected ends before actual
return true if !e
# If actual ends before expected
return false if !a
# Simple - only expect token to match
return true if a[0] == e
# Expect value and optional attributes to match
if e.is_a? Array
# tokens must match
return false unless a[0] == e[0]
if e[2].is_a?(Hash)
e[2].each {|k,v| return false unless a[1][k] == v }
end
return (a[1] == e[1] || (a[1][:value] == e[1]))
end
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/matchers/resource.rb | spec/lib/matchers/resource.rb | module Matchers; module Resource
extend RSpec::Matchers::DSL
matcher :have_resource do |expected_resource|
def resource_match(expected_resource, actual_resource)
matched = true
failures = []
if actual_resource.ref != expected_resource
matched = false
failures << "expected #{expected_resource} but was #{actual_resource.ref}"
end
@params ||= {}
@params.each do |name, value|
case value
when RSpec::Matchers::DSL::Matcher
if !value.matches?(actual_resource[name])
matched = false
failures << "expected #{name} to match '#{value.description}' but was '#{actual_resource[name]}'"
end
else
if actual_resource[name] != value
matched = false
failures << "expected #{name} to be '#{value}' but was '#{actual_resource[name]}'"
end
end
end
@mismatch = failures.join("\n")
matched
end
match do |actual_catalog|
@mismatch = ""
if resource = actual_catalog.resource(expected_resource)
resource_match(expected_resource, resource)
else
@mismatch = "expected #{@actual.to_dot} to include #{expected_resource}"
false
end
end
chain :with_parameter do |name, value|
@params ||= {}
@params[name] = value
end
def failure_message
@mismatch
end
end
matcher :be_resource do |expected_resource|
def resource_match(expected_resource, actual_resource)
if actual_resource.ref == expected_resource
true
else
@mismatch = "expected #{expected_resource} but was #{actual_resource.ref}"
false
end
end
match do |actual_resource|
resource_match(expected_resource, actual_resource)
end
def failure_message
@mismatch
end
end
end; end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/matchers/relationship_graph_matchers.rb | spec/lib/matchers/relationship_graph_matchers.rb | module RelationshipGraphMatchers
class EnforceOrderWithEdge
def initialize(before, after)
@before = before
@after = after
end
def matches?(actual_graph)
@actual_graph = actual_graph
@reverse_edge = actual_graph.edge?(
vertex_called(actual_graph, @after),
vertex_called(actual_graph, @before))
@forward_edge = actual_graph.edge?(
vertex_called(actual_graph, @before),
vertex_called(actual_graph, @after))
@forward_edge && !@reverse_edge
end
def failure_message
"expect #{@actual_graph.to_dot_graph} to only contain an edge from #{@before} to #{@after} but #{[forward_failure_message, reverse_failure_message].compact.join(' and ')}"
end
def forward_failure_message
if !@forward_edge
"did not contain an edge from #{@before} to #{@after}"
end
end
def reverse_failure_message
if @reverse_edge
"contained an edge from #{@after} to #{@before}"
end
end
private
def vertex_called(graph, name)
graph.vertices.find { |v| v.ref =~ /#{Regexp.escape(name)}/ }
end
end
def enforce_order_with_edge(before, after)
EnforceOrderWithEdge.new(before, after)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/matchers/json.rb | spec/lib/matchers/json.rb | module JSONMatchers
class SetJsonAttribute
def initialize(attributes)
@attributes = attributes
end
def format
@format ||= Puppet::Network::FormatHandler.format('json')
end
def json(instance)
Puppet::Util::Json.load(instance.to_json)
end
def attr_value(attrs, instance)
attrs = attrs.dup
hash = json(instance)
while attrs.length > 0
name = attrs.shift
hash = hash[name]
end
hash
end
def to(value)
@value = value
self
end
def matches?(instance)
@instance = instance
result = attr_value(@attributes, instance)
if @value
result == @value
else
! result.nil?
end
end
def failure_message
if @value
"expected #{@instance.inspect} to set #{@attributes.inspect} to #{@value.inspect}; got #{attr_value(@attributes, @instance).inspect}"
else
"expected #{@instance.inspect} to set #{@attributes.inspect} but was nil"
end
end
def failure_message_when_negated
if @value
"expected #{@instance.inspect} not to set #{@attributes.inspect} to #{@value.inspect}"
else
"expected #{@instance.inspect} not to set #{@attributes.inspect} to nil"
end
end
end
class ReadJsonAttribute
def initialize(attribute)
@attribute = attribute
end
def format
@format ||= Puppet::Network::FormatHandler.format('json')
end
def from(value)
@json = value
self
end
def as(as)
@value = as
self
end
def matches?(klass)
raise "Must specify json with 'from'" unless @json
@klass = klass
@instance = format.intern(klass, @json)
if @value
@instance.send(@attribute) == @value
else
! @instance.send(@attribute).nil?
end
end
def failure_message
if @value
"expected #{@klass} to read #{@attribute} from #{@json} as #{@value.inspect}; got #{@instance.send(@attribute).inspect}"
else
"expected #{@klass} to read #{@attribute} from #{@json} but was nil"
end
end
def failure_message_when_negated
if @value
"expected #{@klass} not to set #{@attribute} to #{@value}"
else
"expected #{@klass} not to set #{@attribute} to nil"
end
end
end
require 'puppet/util/json'
require 'json-schema'
class SchemaMatcher
JSON_META_SCHEMA = Puppet::Util::Json.load(File.read('api/schemas/json-meta-schema.json'))
def initialize(schema)
@schema = schema
end
def matches?(json)
JSON::Validator.validate!(JSON_META_SCHEMA, @schema)
JSON::Validator.validate!(@schema, json)
end
end
def validate_against(schema_file)
schema = Puppet::Util::Json.load(File.read(schema_file))
SchemaMatcher.new(schema)
end
def set_json_attribute(*attributes)
SetJsonAttribute.new(attributes)
end
def read_json_attribute(attribute)
ReadJsonAttribute.new(attribute)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/matchers/containment_matchers.rb | spec/lib/matchers/containment_matchers.rb | module ContainmentMatchers
class ContainClass
def initialize(containee)
@containee = containee
end
def in(container)
@container = container
self
end
def matches?(catalog)
@catalog = catalog
raise ArgumentError, "You must set the container using #in" unless @container
@container_resource = catalog.resource("Class", @container)
@containee_resource = catalog.resource("Class", @containee)
if @containee_resource && @container_resource
catalog.edge?(@container_resource, @containee_resource)
else
false
end
end
def failure_message
message = "Expected #{@catalog.to_dot} to contain Class #{@containee.inspect} inside of Class #{@container.inspect} but "
missing = []
if @container_resource.nil?
missing << @container
end
if @containee_resource.nil?
missing << @containee
end
if ! missing.empty?
message << "the catalog does not contain #{missing.map(&:inspect).join(' or ')}"
else
message << "no containment relationship exists"
end
message
end
end
# expect(catalog).to contain_class(containee).in(container)
def contain_class(containee)
ContainClass.new(containee)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/matchers/include_in_order_spec.rb | spec/lib/matchers/include_in_order_spec.rb | require 'spec_helper'
require 'matchers/include_in_order'
describe "Matching whether elements are included in order" do
context "an empty array" do
it "is included in an empty array" do
expect([]).to include_in_order()
end
it "is included in a non-empty array" do
expect([1]).to include_in_order()
end
end
it "[1,2,3] is included in [0,1,2,3,4]" do
expect([0,1,2,3,4]).to include_in_order(1,2,3)
end
it "[2,1] is not included in order in [1,2]" do
expect([1,2]).not_to include_in_order(2,1)
end
it "[2,4,6] is included in order in [1,2,3,4,5,6]" do
expect([1,2,3,4,5,6]).to include_in_order(2,4,6)
end
it "overlapping ordered array is not included" do
expect([1,2,3]).not_to include_in_order(2,3,4)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/matchers/include_in_order.rb | spec/lib/matchers/include_in_order.rb | RSpec::Matchers.define :include_in_order do |*expected|
match do |actual|
elements = expected.dup
actual.each do |elt|
if elt == elements.first
elements.shift
end
end
elements.empty?
end
def failure_message
"expected #{@actual.inspect} to include#{expected} in order"
end
def failure_message_when_negated
"expected #{@actual.inspect} not to include#{expected} in order"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/language.rb | spec/lib/puppet_spec/language.rb | require 'puppet_spec/compiler'
require 'matchers/resource'
module PuppetSpec::Language
extend RSpec::Matchers::DSL
def produces(expectations)
calledFrom = caller
expectations.each do |manifest, resources|
it "evaluates #{manifest} to produce #{resources}" do
begin
case resources
when String
node = Puppet::Node.new('specification')
Puppet[:code] = manifest
compiler = Puppet::Parser::Compiler.new(node)
evaluator = Puppet::Pops::Parser::EvaluatingParser.new()
# see lib/puppet/indirector/catalog/compiler.rb#filter
catalog = compiler.compile.filter { |r| r.virtual? }
compiler.send(:instance_variable_set, :@catalog, catalog)
Puppet.override(:loaders => compiler.loaders) do
expect(evaluator.evaluate_string(compiler.topscope, resources)).to eq(true)
end
when Array
catalog = PuppetSpec::Compiler.compile_to_catalog(manifest)
if resources.empty?
base_resources = ["Class[Settings]", "Class[main]", "Stage[main]"]
expect(catalog.resources.collect(&:ref) - base_resources).to eq([])
else
resources.each do |reference|
if reference.is_a?(Array)
matcher = Matchers::Resource.have_resource(reference[0])
reference[1].each do |name, value|
matcher = matcher.with_parameter(name, value)
end
else
matcher = Matchers::Resource.have_resource(reference)
end
expect(catalog).to matcher
end
end
else
raise "Unsupported creates specification: #{resources.inspect}"
end
rescue Puppet::Error, RSpec::Expectations::ExpectationNotMetError => e
# provide the backtrace from the caller, or it is close to impossible to find some originators
e.set_backtrace(calledFrom)
raise
end
end
end
end
def fails(expectations)
calledFrom = caller
expectations.each do |manifest, pattern|
it "fails to evaluate #{manifest} with message #{pattern}" do
begin
expect do
PuppetSpec::Compiler.compile_to_catalog(manifest)
end.to raise_error(Puppet::Error, pattern)
rescue RSpec::Expectations::ExpectationNotMetError => e
# provide the backgrace from the caller, or it is close to impossible to find some originators
e.set_backtrace(calledFrom)
raise
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/fixtures.rb | spec/lib/puppet_spec/fixtures.rb | module PuppetSpec::Fixtures
def fixtures(*rest)
File.join(PuppetSpec::FIXTURE_DIR, *rest)
end
def my_fixture_dir
callers = caller
while line = callers.shift do
next unless found = line.match(%r{/spec/(.*)_spec\.rb:})
return fixtures(found[1])
end
fail "sorry, I couldn't work out your path from the caller stack!"
end
def my_fixture(name)
file = File.join(my_fixture_dir, name)
unless File.readable? file then
fail Puppet::DevError, "fixture '#{name}' for #{my_fixture_dir} is not readable"
end
return file
end
def my_fixtures(glob = '*', flags = 0)
files = Dir.glob(File.join(my_fixture_dir, glob), flags)
unless files.length > 0 then
fail Puppet::DevError, "fixture '#{glob}' for #{my_fixture_dir} had no files!"
end
block_given? and files.each do |file| yield file end
files
end
def pem_content(name)
File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', name), encoding: 'UTF-8')
end
def cert_fixture(name)
OpenSSL::X509::Certificate.new(pem_content(name))
end
def crl_fixture(name)
OpenSSL::X509::CRL.new(pem_content(name))
end
def key_fixture(name)
OpenSSL::PKey::RSA.new(pem_content(name))
end
def ec_key_fixture(name)
OpenSSL::PKey::EC.new(pem_content(name))
end
def request_fixture(name)
OpenSSL::X509::Request.new(pem_content(name))
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/files.rb | spec/lib/puppet_spec/files.rb | require 'fileutils'
require 'tempfile'
require 'tmpdir'
require 'pathname'
# A support module for testing files.
module PuppetSpec::Files
def self.cleanup
$global_tempfiles ||= []
while path = $global_tempfiles.pop do
begin
FileUtils.rm_rf path, secure: true
rescue Errno::ENOENT
# nothing to do
end
end
end
module_function
def make_absolute(path)
path = File.expand_path(path)
path[0] = 'c' if Puppet::Util::Platform.windows?
path
end
def tmpfile(name, dir = nil)
dir ||= Dir.tmpdir
path = Puppet::FileSystem.expand_path(make_tmpname(name, nil).encode(Encoding::UTF_8), dir)
record_tmp(File.expand_path(path))
path
end
def file_containing(name, contents)
file = tmpfile(name)
File.open(file, 'wb') { |f| f.write(contents) }
file
end
def script_containing(name, contents)
file = tmpfile(name)
if Puppet::Util::Platform.windows?
file += '.bat'
text = contents[:windows]
else
text = contents[:posix]
end
File.open(file, 'wb') { |f| f.write(text) }
Puppet::FileSystem.chmod(0755, file)
file
end
def tmpdir(name)
dir = Puppet::FileSystem.expand_path(Dir.mktmpdir(name).encode!(Encoding::UTF_8))
record_tmp(dir)
dir
end
# Copied from ruby 2.4 source
def make_tmpname((prefix, suffix), n)
prefix = (String.try_convert(prefix) or
raise ArgumentError, "unexpected prefix: #{prefix.inspect}")
suffix &&= (String.try_convert(suffix) or
raise ArgumentError, "unexpected suffix: #{suffix.inspect}")
t = Time.now.strftime("%Y%m%d")
path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}".dup
path << "-#{n}" if n
path << suffix if suffix
path
end
def dir_containing(name, contents_hash)
dir_contained_in(tmpdir(name), contents_hash)
end
def dir_contained_in(dir, contents_hash)
contents_hash.each do |k,v|
if v.is_a?(Hash)
Dir.mkdir(tmp = File.join(dir,k))
dir_contained_in(tmp, v)
else
file = File.join(dir, k)
File.open(file, 'wb') {|f| f.write(v) }
end
end
dir
end
def record_tmp(tmp)
# ...record it for cleanup,
$global_tempfiles ||= []
$global_tempfiles << tmp
end
def expect_file_mode(file, mode)
actual_mode = "%o" % Puppet::FileSystem.stat(file).mode
target_mode = if Puppet::Util::Platform.windows?
mode
else
"10" + "%04i" % mode.to_i
end
expect(actual_mode).to eq(target_mode)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/matchers.rb | spec/lib/puppet_spec/matchers.rb | require 'stringio'
########################################################################
# Custom matchers...
RSpec::Matchers.define :have_matching_element do |expected|
match do |actual|
actual.any? { |item| item =~ expected }
end
end
RSpec::Matchers.define :have_matching_log do |expected|
match do |actual|
actual.map(&:to_s).any? { |item| item =~ expected }
end
end
RSpec::Matchers.define :have_matching_log_with_source do |expected, file, line, pos|
match do |actual|
actual.any? { |item| item.message =~ expected && item.file == file && item.line == line && item.pos == pos }
end
end
RSpec::Matchers.define :exit_with do |expected|
actual = nil
match do |block|
begin
block.call
rescue SystemExit => e
actual = e.status
end
actual and actual == expected
end
supports_block_expectations
failure_message do |block|
"expected exit with code #{expected} but " +
(actual.nil? ? " exit was not called" : "we exited with #{actual} instead")
end
failure_message_when_negated do |block|
"expected that exit would not be called with #{expected}"
end
description do
"expect exit with #{expected}"
end
end
RSpec::Matchers.define :equal_attributes_of do |expected|
match do |actual|
actual.instance_variables.all? do |attr|
actual.instance_variable_get(attr) == expected.instance_variable_get(attr)
end
end
end
RSpec::Matchers.define :equal_resource_attributes_of do |expected|
match do |actual|
actual.keys do |attr|
actual[attr] == expected[attr]
end
end
end
RSpec::Matchers.define :be_one_of do |*expected|
match do |actual|
expected.include? actual
end
failure_message do |actual|
"expected #{actual.inspect} to be one of #{expected.map(&:inspect).join(' or ')}"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/compiler.rb | spec/lib/puppet_spec/compiler.rb | module PuppetSpec::Compiler
module_function
def compile_to_catalog(string, node = Puppet::Node.new('test'))
Puppet[:code] = string
# see lib/puppet/indirector/catalog/compiler.rb#filter
Puppet::Parser::Compiler.compile(node).filter { |r| r.virtual? }
end
# Does not removed virtual resources in compiled catalog (i.e. keeps unrealized)
def compile_to_catalog_unfiltered(string, node = Puppet::Node.new('test'))
Puppet[:code] = string
# see lib/puppet/indirector/catalog/compiler.rb#filter
Puppet::Parser::Compiler.compile(node)
end
def compile_to_ral(manifest, node = Puppet::Node.new('test'))
catalog = compile_to_catalog(manifest, node)
ral = catalog.to_ral
ral.finalize
ral
end
def compile_to_relationship_graph(manifest, prioritizer = Puppet::Graph::SequentialPrioritizer.new)
ral = compile_to_ral(manifest)
graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
graph.populate_from(ral)
graph
end
def apply_compiled_manifest(manifest, prioritizer = Puppet::Graph::SequentialPrioritizer.new)
catalog = compile_to_ral(manifest)
if block_given?
catalog.resources.each { |res| yield res }
end
transaction = Puppet::Transaction.new(catalog,
Puppet::Transaction::Report.new,
prioritizer)
transaction.evaluate
transaction.report.finalize_report
transaction
end
def apply_with_error_check(manifest)
apply_compiled_manifest(manifest) do |res|
expect(res).not_to receive(:err)
end
end
def order_resources_traversed_in(relationships)
order_seen = []
relationships.traverse { |resource| order_seen << resource.ref }
order_seen
end
def collect_notices(code, node = Puppet::Node.new('foonode'))
Puppet[:code] = code
compiler = Puppet::Parser::Compiler.new(node)
node.environment.check_for_reparse
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
yield(compiler)
end
logs = logs.select { |log| log.level == :notice }.map { |log| log.message }
logs
end
def eval_and_collect_notices(code, node = Puppet::Node.new('foonode'), topscope_vars = {})
collect_notices(code, node) do |compiler|
unless topscope_vars.empty?
scope = compiler.topscope
topscope_vars.each {|k,v| scope.setvar(k, v) }
end
if block_given?
compiler.compile do |catalog|
yield(compiler.topscope, catalog)
catalog
end
else
compiler.compile
end
end
end
# Compiles a catalog, and if source is given evaluates it and returns its result.
# The catalog is returned if no source is given.
# Topscope variables are set before compilation
# Uses a created node 'testnode' if none is given.
# (Parameters given by name)
#
def evaluate(code: 'undef', source: nil, node: Puppet::Node.new('testnode'), variables: {})
source_location = caller[0]
Puppet[:code] = code
compiler = Puppet::Parser::Compiler.new(node)
unless variables.empty?
scope = compiler.topscope
variables.each {|k,v| scope.setvar(k, v) }
end
if source.nil?
compiler.compile
# see lib/puppet/indirector/catalog/compiler.rb#filter
return compiler.filter { |r| r.virtual? }
end
# evaluate given source is the context of the compiled state and return its result
compiler.compile do |catalog |
Puppet::Pops::Parser::EvaluatingParser.singleton.evaluate_string(compiler.topscope, source, source_location)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/network.rb | spec/lib/puppet_spec/network.rb | require 'spec_helper'
require 'puppet/network/http'
require 'puppet/network/http/api/indirected_routes'
require 'puppet/indirector_testing'
module PuppetSpec::Network
def not_found_error
Puppet::Network::HTTP::Error::HTTPNotFoundError
end
def not_acceptable_error
Puppet::Network::HTTP::Error::HTTPNotAcceptableError
end
def bad_request_error
Puppet::Network::HTTP::Error::HTTPBadRequestError
end
def not_authorized_error
Puppet::Network::HTTP::Error::HTTPNotAuthorizedError
end
def method_not_allowed_error
Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError
end
def unsupported_media_type_error
Puppet::Network::HTTP::Error::HTTPUnsupportedMediaTypeError
end
def params
{ :environment => "production" }
end
def acceptable_content_types
types = ['application/json']
types << 'application/x-msgpack' if Puppet.features.msgpack?
types << 'text/pson' if Puppet.features.pson?
types
end
def acceptable_content_types_string
acceptable_content_types.join(', ')
end
def acceptable_catalog_content_types
types = %w[application/vnd.puppet.rich+json application/json]
types.concat(%w[application/vnd.puppet.rich+msgpack application/x-msgpack]) if Puppet.features.msgpack?
types << 'text/pson' if Puppet.features.pson?
types
end
def master_url_prefix
"#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3"
end
def ca_url_prefix
"#{Puppet::Network::HTTP::CA_URL_PREFIX}/v1"
end
def a_request_that_heads(data, request = {}, params = params())
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "application/json"
},
:method => "HEAD",
:path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}",
:params => params,
})
end
def a_request_that_submits(data, request = {}, params = params())
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => request[:content_type_header] || "application/json"
},
:method => "PUT",
:path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}",
:params => params,
:body => request[:body].nil? ? data.render("json") : request[:body]
})
end
def a_request_that_destroys(data, request = {}, params = params())
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "application/json"
},
:method => "DELETE",
:path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}",
:params => params,
:body => ''
})
end
def a_request_that_finds(data, request = {}, params = params())
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "application/json"
},
:method => "GET",
:path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}",
:params => params,
:body => ''
})
end
def a_request_that_searches(data, request = {}, params = params())
Puppet::Network::HTTP::Request.from_hash({
:headers => {
'accept' => request[:accept_header],
'content-type' => "application/json"
},
:method => "GET",
:path => "#{master_url_prefix}/#{data.class.indirection.name}s/#{data.name}",
:params => params,
:body => ''
})
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/ssl.rb | spec/lib/puppet_spec/ssl.rb | require 'openssl'
module PuppetSpec
module SSL
PRIVATE_KEY_LENGTH = 2048
FIVE_YEARS = 5 * 365 * 24 * 60 * 60
CA_EXTENSIONS = [
["basicConstraints", "CA:TRUE", true],
["keyUsage", "keyCertSign, cRLSign", true],
["subjectKeyIdentifier", "hash", false],
["authorityKeyIdentifier", "keyid:always", false]
]
NODE_EXTENSIONS = [
["keyUsage", "digitalSignature", true],
["subjectKeyIdentifier", "hash", false]
]
DEFAULT_SIGNING_DIGEST = OpenSSL::Digest::SHA256.new
DEFAULT_REVOCATION_REASON = OpenSSL::OCSP::REVOKED_STATUS_KEYCOMPROMISE
ROOT_CA_NAME = "/CN=root-ca-\u{2070E}"
REVOKED_INT_CA_NAME = "/CN=revoked-int-ca-\u16A0"
INT_CA_NAME = "/CN=unrevoked-int-ca\u06FF\u16A0\u{2070E}"
LEAF_CA_NAME = "/CN=leaf-ca-\u06FF"
EXPLANATORY_TEXT = <<-EOT
# Root Issuer: #{ROOT_CA_NAME}
# Intermediate Issuer: #{INT_CA_NAME}
# Leaf Issuer: #{LEAF_CA_NAME}
EOT
def self.create_private_key(length = PRIVATE_KEY_LENGTH)
OpenSSL::PKey::RSA.new(length)
end
def self.self_signed_ca(key, name)
cert = OpenSSL::X509::Certificate.new
cert.public_key = key.public_key
cert.subject = OpenSSL::X509::Name.parse(name)
cert.issuer = cert.subject
cert.version = 2
cert.serial = rand(2**128)
not_before = just_now
cert.not_before = not_before
cert.not_after = not_before + FIVE_YEARS
ext_factory = extension_factory_for(cert, cert)
CA_EXTENSIONS.each do |ext|
extension = ext_factory.create_extension(*ext)
cert.add_extension(extension)
end
cert.sign(key, DEFAULT_SIGNING_DIGEST)
cert
end
def self.create_csr(key, name)
csr = OpenSSL::X509::Request.new
csr.public_key = key.public_key
csr.subject = OpenSSL::X509::Name.parse(name)
csr.version = 0
csr.sign(key, DEFAULT_SIGNING_DIGEST)
csr
end
def self.sign(ca_key, ca_cert, csr, extensions = NODE_EXTENSIONS)
cert = OpenSSL::X509::Certificate.new
cert.public_key = csr.public_key
cert.subject = csr.subject
cert.issuer = ca_cert.subject
cert.version = 2
cert.serial = rand(2**128)
not_before = just_now
cert.not_before = not_before
cert.not_after = not_before + FIVE_YEARS
ext_factory = extension_factory_for(ca_cert, cert)
extensions.each do |ext|
extension = ext_factory.create_extension(*ext)
cert.add_extension(extension)
end
cert.sign(ca_key, DEFAULT_SIGNING_DIGEST)
cert
end
def self.create_crl_for(ca_cert, ca_key)
crl = OpenSSL::X509::CRL.new
crl.version = 1
crl.issuer = ca_cert.subject
ef = extension_factory_for(ca_cert)
crl.add_extension(
ef.create_extension(["authorityKeyIdentifier", "keyid:always", false]))
crl.add_extension(
OpenSSL::X509::Extension.new("crlNumber", OpenSSL::ASN1::Integer(0)))
not_before = just_now
crl.last_update = not_before
crl.next_update = not_before + FIVE_YEARS
crl.sign(ca_key, DEFAULT_SIGNING_DIGEST)
crl
end
def self.revoke(serial, crl, ca_key)
revoked = OpenSSL::X509::Revoked.new
revoked.serial = serial
revoked.time = Time.now
revoked.add_extension(
OpenSSL::X509::Extension.new("CRLReason",
OpenSSL::ASN1::Enumerated(DEFAULT_REVOCATION_REASON)))
crl.add_revoked(revoked)
extensions = crl.extensions.group_by{|e| e.oid == 'crlNumber' }
crl_number = extensions[true].first
unchanged_exts = extensions[false]
next_crl_number = crl_number.value.to_i + 1
new_crl_number_ext = OpenSSL::X509::Extension.new("crlNumber",
OpenSSL::ASN1::Integer(next_crl_number))
crl.extensions = unchanged_exts + [new_crl_number_ext]
crl.sign(ca_key, DEFAULT_SIGNING_DIGEST)
crl
end
# Creates a self-signed root ca, then signs two node certs, revoking one of them.
# Creates an intermediate CA and one node cert off of it.
# Creates a second intermediate CA and one node cert off if it.
# Creates a leaf CA off of the intermediate CA, then signs two node certs revoking one of them.
# Revokes an intermediate CA.
# Returns the ca bundle, crl chain, and all the node certs
#
# -----
# / \
# / \
# | root +-------------------o------------------o
# \ CA / | |
# \ / | |
# --+-- | |
# | | |
# | | |
# | | |
# | --+-- --+--
# +---------+ | +---------+ / \ / \
# | revoked | | | | /revoked\ / \
# | node +--o---+ node | | int | | int |
# | | | | \ CA / \ CA /
# +---------+ +---------+ \ / \ /
# --+-- --+--
# | |
# | |
# | |
# --+-- |
# / \ +---+-----+
# / \ | |
# | leaf | | node |
# \ CA / | |
# \ / +---------+
# --+--
# |
# |
# +---------+ | +----------+
# | revoked | | | |
# | node +--o--+ node |
# | | | |
# +---------+ +----------+
def self.create_chained_pki
root_key = create_private_key
root_cert = self_signed_ca(root_key, ROOT_CA_NAME)
root_crl = create_crl_for(root_cert, root_key)
unrevoked_root_node_key = create_private_key
unrevoked_root_node_csr = create_csr(unrevoked_root_node_key, "/CN=unrevoked-root-node")
unrevoked_root_node_cert = sign(root_key, root_cert, unrevoked_root_node_csr)
revoked_root_node_key = create_private_key
revoked_root_node_csr = create_csr(revoked_root_node_key, "/CN=revoked-root-node")
revoked_root_node_cert = sign(root_key, root_cert, revoked_root_node_csr)
revoke(revoked_root_node_cert.serial, root_crl, root_key)
revoked_int_key = create_private_key
revoked_int_csr = create_csr(revoked_int_key, REVOKED_INT_CA_NAME)
revoked_int_cert = sign(root_key, root_cert, revoked_int_csr, CA_EXTENSIONS)
revoked_int_crl = create_crl_for(revoked_int_cert, revoked_int_key)
int_key = create_private_key
int_csr = create_csr(int_key, INT_CA_NAME)
int_cert = sign(root_key, root_cert, int_csr, CA_EXTENSIONS)
int_node_key = create_private_key
int_node_csr = create_csr(int_node_key, "/CN=unrevoked-int-node")
int_node_cert = sign(int_key, int_cert, int_node_csr)
unrevoked_int_node_key = create_private_key
unrevoked_int_node_csr = create_csr(unrevoked_int_node_key, "/CN=unrevoked-int-node")
unrevoked_int_node_cert = sign(revoked_int_key, revoked_int_cert, unrevoked_int_node_csr)
leaf_key = create_private_key
leaf_csr = create_csr(leaf_key, LEAF_CA_NAME)
leaf_cert = sign(revoked_int_key, revoked_int_cert, leaf_csr, CA_EXTENSIONS)
leaf_crl = create_crl_for(leaf_cert, leaf_key)
revoke(revoked_int_cert.serial, root_crl, root_key)
unrevoked_leaf_node_key = create_private_key
unrevoked_leaf_node_csr = create_csr(unrevoked_leaf_node_key, "/CN=unrevoked-leaf-node")
unrevoked_leaf_node_cert = sign(leaf_key, leaf_cert, unrevoked_leaf_node_csr)
revoked_leaf_node_key = create_private_key
revoked_leaf_node_csr = create_csr(revoked_leaf_node_key, "/CN=revoked-leaf-node")
revoked_leaf_node_cert = sign(leaf_key, leaf_cert, revoked_leaf_node_csr)
revoke(revoked_leaf_node_cert.serial, leaf_crl, leaf_key)
ca_bundle = bundle(root_cert, revoked_int_cert, leaf_cert)
crl_chain = bundle(root_crl, revoked_int_crl, leaf_crl)
{
:root_cert => root_cert,
:int_cert => int_cert,
:int_node_cert => int_node_cert,
:leaf_cert => leaf_cert,
:leaf_key => leaf_key,
:revoked_root_node_cert => revoked_root_node_cert,
:revoked_int_cert => revoked_int_cert,
:revoked_leaf_node_cert => revoked_leaf_node_cert,
:unrevoked_root_node_cert => unrevoked_root_node_cert,
:unrevoked_int_node_cert => unrevoked_int_node_cert,
:unrevoked_leaf_node_cert => unrevoked_leaf_node_cert,
:ca_bundle => ca_bundle,
:crl_chain => crl_chain,
}
end
private
def self.just_now
Time.now - 1
end
def self.extension_factory_for(ca, cert = nil)
ef = OpenSSL::X509::ExtensionFactory.new
ef.issuer_certificate = ca
ef.subject_certificate = cert if cert
ef
end
def self.bundle(*items)
items.map {|i| EXPLANATORY_TEXT + i.to_pem }.join("\n")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/verbose.rb | spec/lib/puppet_spec/verbose.rb | # Support code for running stuff with warnings disabled or enabled
module Kernel
def with_verbose_disabled
verbose, $VERBOSE = $VERBOSE, nil
begin
yield
ensure
$VERBOSE = verbose
end
end
def with_verbose_enabled
verbose, $VERBOSE = $VERBOSE, true
begin
yield
ensure
$VERBOSE = verbose
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/settings.rb | spec/lib/puppet_spec/settings.rb | module PuppetSpec::Settings
# It would probably be preferable to refactor defaults.rb such that the real definitions of
# these settings were available as a variable, which was then accessible for use during tests.
# However, I'm not doing that yet because I don't want to introduce any additional moving parts
# to this already very large changeset.
# Would be nice to clean this up later. --cprice 2012-03-20
TEST_APP_DEFAULT_DEFINITIONS = {
:name => { :default => "test", :desc => "name" },
:logdir => { :type => :directory, :default => "test", :desc => "logdir" },
:confdir => { :type => :directory, :default => "test", :desc => "confdir" },
:codedir => { :type => :directory, :default => "test", :desc => "codedir" },
:vardir => { :type => :directory, :default => "test", :desc => "vardir" },
:publicdir => { :type => :directory, :default => "test", :desc => "publicdir" },
:rundir => { :type => :directory, :default => "test", :desc => "rundir" },
}.freeze
TEST_APP_DEFAULT_VALUES = TEST_APP_DEFAULT_DEFINITIONS.inject({}) do |memo, (key, value)|
memo[key] = value[:default]
memo
end.freeze
def set_puppet_conf(confdir, settings)
FileUtils.mkdir_p(confdir)
write_file(File.join(confdir, "puppet.conf"), settings)
end
def set_environment_conf(environmentpath, environment, settings)
envdir = File.join(environmentpath, environment)
FileUtils.mkdir_p(envdir)
write_file(File.join(envdir, 'environment.conf'), settings)
end
def write_file(file, contents)
File.open(file, "w") do |f|
f.puts(contents)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/scope.rb | spec/lib/puppet_spec/scope.rb | module PuppetSpec::Scope
# Initialize a new scope suitable for testing.
#
def create_test_scope_for_node(node_name)
node = Puppet::Node.new(node_name)
compiler = Puppet::Parser::Compiler.new(node)
scope = Puppet::Parser::Scope.new(compiler)
scope.source = Puppet::Resource::Type.new(:node, node_name)
scope.parent = compiler.topscope
scope
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/handler.rb | spec/lib/puppet_spec/handler.rb | require 'puppet/network/http/handler'
class PuppetSpec::Handler
include Puppet::Network::HTTP::Handler
def initialize(* routes)
register(routes)
end
def set_content_type(response, format)
response[:content_type_header] = format
end
def set_response(response, body, status = 200)
response[:body] = body
response[:status] = status
end
def http_method(request)
request[:method]
end
def path(request)
request[:path]
end
def params(request)
request[:params]
end
def client_cert(request)
request[:client_cert]
end
def body(request)
request[:body]
end
def headers(request)
request[:headers] || {}
end
end
class PuppetSpec::HandlerProfiler
def start(metric, description)
end
def finish(context, metric, description)
end
def shutdown()
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/puppetserver.rb | spec/lib/puppet_spec/puppetserver.rb | require 'spec_helper'
require 'webrick'
require "webrick/ssl"
class PuppetSpec::Puppetserver
include PuppetSpec::Fixtures
include PuppetSpec::Files
attr_reader :ca_cert, :ca_crl, :server_cert, :server_key
class NodeServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
node = Puppet::Node.new(Puppet[:certname])
response.body = node.render(:json)
response['Content-Type'] = 'application/json'
end
end
class CatalogServlet < WEBrick::HTTPServlet::AbstractServlet
def do_POST request, response
response['Content-Type'] = 'application/json'
response['X-Puppet-Compiler-Name'] = 'test-compiler-hostname'
catalog = Puppet::Resource::Catalog.new(Puppet[:certname], 'production')
response.body = catalog.render(:json)
end
end
class FileMetadatasServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
response['Content-Type'] = 'application/json'
response.body = "[{\"path\":\"/etc/puppetlabs/code/environments/production/modules\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-03-06 20:14:25 UTC\"},\"type\":\"directory\",\"destination\":null}]"
end
end
class FileMetadataServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
response['Content-Type'] = 'application/json'
response.body = "{\"path\":\"/etc/puppetlabs/code/environments/production/modules\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-03-06 20:14:25 UTC\"},\"type\":\"directory\",\"destination\":null}"
end
end
class FileContentServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
response.status = 404
end
end
class ReportServlet < WEBrick::HTTPServlet::AbstractServlet
def do_PUT request, response
response['Content-Type'] = 'application/json'
response.body = "[]"
end
end
class StaticFileContentServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
response.status = 404
end
end
class FilebucketServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
end
def do_PUT request, response
upload = File.join(@config.config[:TempDir], 'filebucket')
File.open(upload, 'wb') { |f| f.write(request.body) }
response['Content-Type'] = 'application/octet-stream'
end
def do_HEAD request, response
response.status = 404
end
end
class CertificateServlet < WEBrick::HTTPServlet::AbstractServlet
def initialize(server, ca_cert)
super(server)
@ca_cert = ca_cert
end
def do_GET request, response
if request.path =~ %r{/puppet-ca/v1/certificate/ca$}
response['Content-Type'] = 'text/plain'
response.body = @ca_cert.to_pem
else
response.status = 404
end
end
end
class CertificateRevocationListServlet < WEBrick::HTTPServlet::AbstractServlet
def initialize(server, crl)
super(server)
@crl = crl
end
def do_GET request, response
response['Content-Type'] = 'text/plain'
response.body = @crl.to_pem
end
end
class CertificateRequestServlet < WEBrick::HTTPServlet::AbstractServlet
def do_PUT request, response
response.status = 404
end
end
def initialize
@ca_cert = cert_fixture('ca.pem')
@ca_crl = crl_fixture('crl.pem')
@server_key = key_fixture('127.0.0.1-key.pem')
@server_cert = cert_fixture('127.0.0.1.pem')
@path = tmpfile('webrick')
@https = WEBrick::HTTPServer.new(
BindAddress: "127.0.0.1",
Port: 0, # webrick will choose the first available port, and set it in the config
SSLEnable: true,
SSLStartImmediately: true,
SSLCACertificateFile: File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'ca.pem'),
SSLCertificate: @server_cert,
SSLPrivateKey: @server_key,
Logger: WEBrick::Log.new(@path),
AccessLog: [
[@path, WEBrick::AccessLog::COMBINED_LOG_FORMAT],
]
)
trap('INT') do
@https.shutdown
end
# Enable this line for more detailed webrick logging
# @https.logger.level = 5 # DEBUG
end
def start_server(mounts: {}, &block)
register_mounts(mounts: mounts)
Thread.new do
@https.start
end
begin
yield @https.config[:Port]
ensure
@https.shutdown
end
end
def register_mounts(mounts: {})
register_mount('/status/v1/simple/server', proc { |req, res| }, nil)
register_mount('/puppet/v3/node', mounts[:node], NodeServlet)
register_mount('/puppet/v3/catalog', mounts[:catalog], CatalogServlet)
register_mount('/puppet/v3/file_metadata', mounts[:file_metadata], FileMetadataServlet)
register_mount('/puppet/v3/file_metadatas', mounts[:file_metadatas], FileMetadatasServlet)
register_mount('/puppet/v3/file_content', mounts[:file_content], FileContentServlet)
register_mount('/puppet/v3/static_file_content', mounts[:static_file_content], StaticFileContentServlet)
register_mount('/puppet/v3/report', mounts[:report], ReportServlet)
register_mount('/puppet/v3/file_bucket_file', mounts[:filebucket], FilebucketServlet)
register_mount('/puppet-ca/v1/certificate', mounts[:certificate], CertificateServlet, @ca_cert)
register_mount('/puppet-ca/v1/certificate_revocation_list', mounts[:certificate_revocation_list], CertificateRevocationListServlet, @ca_crl)
register_mount('/puppet-ca/v1/certificate_request', mounts[:certificate_request], CertificateRequestServlet)
end
def register_mount(path, user_proc, default_servlet, *args)
handler = if user_proc
WEBrick::HTTPServlet::ProcHandler.new(user_proc)
else
default_servlet
end
@https.mount(path, handler, *args)
end
def upload_directory
@https.config[:TempDir]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/unindent.rb | spec/lib/puppet_spec/unindent.rb | class String
def unindent(left_padding = '')
gsub(/^#{scan(/^\s*/).min_by{ |l| l.length }}/, left_padding)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/https.rb | spec/lib/puppet_spec/https.rb | require 'spec_helper'
require 'webrick'
class PuppetSpec::HTTPSServer
include PuppetSpec::Fixtures
attr_reader :ca_cert, :ca_crl, :server_cert, :server_key
def initialize(ca_cert: nil, ca_crl: nil, server_key: nil, server_cert: nil)
@ca_cert = ca_cert || cert_fixture('ca.pem')
@ca_crl = ca_crl || crl_fixture('crl.pem')
@server_key = server_key || key_fixture('127.0.0.1-key.pem')
@server_cert = server_cert || cert_fixture('127.0.0.1.pem')
@config = WEBrick::Config::HTTP.dup
end
def handle_request(ctx, ssl, response_proc)
req = WEBrick::HTTPRequest.new(@config)
req.parse(ssl)
# always drain request body
req.body
res = WEBrick::HTTPResponse.new(@config)
res.status = 200
res.body = 'OK'
# The server explicitly closes the connection after handling it,
# so explicitly tell the client we're not going to keep it open.
# Without this, ruby will add `Connection: Keep-Alive`, which
# confuses the client when it tries to reuse the half-closed
# connection.
res['Connection'] = 'close'
response_proc.call(req, res) if response_proc
res.send_response(ssl)
end
def start_server(ctx_proc: nil, response_proc: nil, &block)
errors = []
IO.pipe {|stop_pipe_r, stop_pipe_w|
store = OpenSSL::X509::Store.new
Array(@ca_cert).each { |c| store.add_cert(c) }
store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert_store = store
ctx.cert = @server_cert
ctx.key = @server_key
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
ctx_proc.call(ctx) if ctx_proc
Socket.do_not_reverse_lookup = true
tcps = TCPServer.new("127.0.0.1", 0)
begin
port = tcps.connect_address.ip_port
begin
server_thread = Thread.new do
begin
ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
ssls.start_immediately = true
loop do
readable, = IO.select([ssls, stop_pipe_r])
break if readable.include?(stop_pipe_r)
ssl = ssls.accept
begin
handle_request(ctx, ssl, response_proc)
ensure
ssl.close
end
end
rescue => e
# uncomment this line if something goes wrong
# puts "SERVER #{e.message}"
errors << e
end
end
begin
yield port
ensure
stop_pipe_w.close
end
ensure
server_thread.join
end
ensure
tcps.close
end
}
errors
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/character_encoding.rb | spec/lib/puppet_spec/character_encoding.rb | # A support module for testing character encoding
module PuppetSpec::CharacterEncoding
def self.with_external_encoding(encoding, &blk)
original_encoding = Encoding.default_external
begin
Encoding.default_external = encoding
yield
ensure
Encoding.default_external = original_encoding
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/modules.rb | spec/lib/puppet_spec/modules.rb | module PuppetSpec::Modules
class << self
def create(name, dir, options = {})
module_dir = File.join(dir, name)
FileUtils.mkdir_p(module_dir)
environment = options[:environment]
metadata = options[:metadata]
if metadata
metadata[:source] ||= 'github'
metadata[:author] ||= 'puppetlabs'
metadata[:version] ||= '9.9.9'
metadata[:license] ||= 'to kill'
metadata[:dependencies] ||= []
metadata[:name] = "#{metadata[:author]}/#{name}"
File.open(File.join(module_dir, 'metadata.json'), 'w') do |f|
f.write(metadata.to_json)
end
end
tasks = options[:tasks]
if tasks
tasks_dir = File.join(module_dir, 'tasks')
FileUtils.mkdir_p(tasks_dir)
tasks.each do |task_files|
task_files.each do |task_file|
if task_file.is_a?(String)
# default content to acceptable metadata
task_file = { :name => task_file, :content => "{}" }
end
File.write(File.join(tasks_dir, task_file[:name]), task_file[:content])
end
end
end
if (plans = options[:plans])
plans_dir = File.join(module_dir, 'plans')
FileUtils.mkdir_p(plans_dir)
plans.each do |plan_file|
if plan_file.is_a?(String)
# default content to acceptable metadata
plan_file = { :name => plan_file, :content => "{}" }
end
File.write(File.join(plans_dir, plan_file[:name]), plan_file[:content])
end
end
if (scripts = options[:scripts])
scripts_dir = File.join(module_dir, 'scripts')
FileUtils.mkdir_p(scripts_dir)
scripts.each do |script_file|
if script_file.is_a?(String)
script_file = { :name => script_file, :content => "" }
end
File.write(File.join(scripts_dir, script_file[:name]), script_file[:content])
end
end
(options[:files] || {}).each do |fname, content|
path = File.join(module_dir, fname)
FileUtils.mkdir_p(File.dirname(path))
File.write(path, content)
end
Puppet::Module.new(name, module_dir, environment)
end
def generate_files(name, dir, options = {})
module_dir = File.join(dir, name)
FileUtils.mkdir_p(module_dir)
if (metadata = options[:metadata])
File.open(File.join(module_dir, 'metadata.json'), 'w') do |f|
f.write(metadata.to_json)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/pops.rb | spec/lib/puppet_spec/pops.rb | module PuppetSpec::Pops
extend RSpec::Matchers::DSL
# Checks if an Acceptor has a specific issue in its list of diagnostics
matcher :have_issue do |expected|
match do |actual|
actual.diagnostics.index { |i| i.issue == expected } != nil
end
failure_message do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to contain issue #{expected.issue_code}"
end
failure_message_when_negated do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to not contain issue #{expected.issue_code}"
end
end
# Checks if an Acceptor has any issues
matcher :have_any_issues do
match do |actual|
!actual.diagnostics.empty?
end
failure_message do |actual|
'expected Acceptor[] to contain at least one issue'
end
failure_message_when_negated do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to not contain any issues"
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/module_tool/stub_source.rb | spec/lib/puppet_spec/module_tool/stub_source.rb | module PuppetSpec
module ModuleTool
class StubSource < SemanticPuppet::Dependency::Source
def inspect; "Stub Source"; end
def host
"http://nowhe.re"
end
def fetch(name)
available_releases[name.tr('/', '-')].values
end
def available_releases
return @available_releases if defined? @available_releases
@available_releases = {
'puppetlabs-java' => {
'10.0.0' => { 'puppetlabs/stdlib' => '4.1.0' },
},
'puppetlabs-stdlib' => {
'4.1.0' => {},
},
'pmtacceptance-stdlib' => {
"4.1.0" => {},
"3.2.0" => {},
"3.1.0" => {},
"3.0.0" => {},
"2.6.0" => {},
"2.5.1" => {},
"2.5.0" => {},
"2.4.0" => {},
"2.3.2" => {},
"2.3.1" => {},
"2.3.0" => {},
"2.2.1" => {},
"2.2.0" => {},
"2.1.3" => {},
"2.0.0" => {},
"1.1.0" => {},
"1.0.0" => {},
},
'pmtacceptance-keystone' => {
'3.0.0-rc2' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'3.0.0-rc1' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.2.0' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.2.0-rc1' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.1.0' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.0.0' => { "pmtacceptance/mysql" => ">= 0.6.1" },
'1.2.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.1.1' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.1.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.0.1' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.0.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'0.2.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'0.1.0' => { "pmtacceptance/mysql" => ">= 0.3.0" },
},
'pmtacceptance-mysql' => {
"2.1.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc5" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc4" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc3" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc2" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"1.0.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.9.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.8.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.8.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.7.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.7.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.6.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.6.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.5.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.4.0" => {},
"0.3.0" => {},
"0.2.0" => {},
},
'pmtacceptance-apache' => {
"0.10.0" => { "pmtacceptance/stdlib" => ">= 2.4.0" },
"0.9.0" => { "pmtacceptance/stdlib" => ">= 2.4.0" },
"0.8.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.8.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.7.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.6.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.5.0-rc1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.4.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.3.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.2.2" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.2.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.2.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.1.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.0.4" => {},
"0.0.3" => {},
"0.0.2" => {},
"0.0.1" => {},
},
'pmtacceptance-bacula' => {
"0.0.3" => { "pmtacceptance/stdlib" => ">= 2.2.0", "pmtacceptance/mysql" => ">= 1.0.0" },
"0.0.2" => { "pmtacceptance/stdlib" => ">= 2.2.0", "pmtacceptance/mysql" => ">= 0.0.1" },
"0.0.1" => { "pmtacceptance/stdlib" => ">= 2.2.0" },
},
'puppetlabs-oneversion' => {
"0.0.1" => {}
}
}
@available_releases.each do |name, versions|
versions.each do |version, deps|
deps, metadata = deps.partition { |k,v| k.is_a? String }
dependencies = Hash[deps.map { |k, v| [ k.tr('/', '-'), v ] }]
versions[version] = create_release(name, version, dependencies).tap do |release|
release.meta_def(:prepare) { }
release.meta_def(:install) { |x| @install_dir = x.to_s }
release.meta_def(:install_dir) { @install_dir }
release.meta_def(:metadata) do
metadata = Hash[metadata].merge(
:name => name,
:version => version,
:source => '', # GRR, Puppet!
:author => '', # GRR, Puppet!
:license => '', # GRR, Puppet!
:dependencies => dependencies.map do |dep, range|
{ :name => dep, :version_requirement => range }
end
)
Hash[metadata.map { |k,v| [ k.to_s, v ] }]
end
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet_spec/module_tool/shared_functions.rb | spec/lib/puppet_spec/module_tool/shared_functions.rb | require 'puppet/util/json'
module PuppetSpec
module ModuleTool
module SharedFunctions
def remote_release(name, version)
remote_source.available_releases[name][version]
end
def preinstall(name, version, options = { :into => primary_dir })
release = remote_release(name, version)
raise "Could not preinstall #{name} v#{version}" if release.nil?
name = release.name[/-(.*)/, 1]
moddir = File.join(options[:into], name)
FileUtils.mkdir_p(moddir)
File.open(File.join(moddir, 'metadata.json'), 'w') do |file|
file.puts(Puppet::Util::Json.dump(release.metadata))
end
end
def mark_changed(path)
app = Puppet::ModuleTool::Applications::Checksummer
allow(app).to receive(:run).with(path).and_return(['README'])
end
def graph_should_include(name, options)
releases = flatten_graph(subject[:graph] || [])
release = releases.find { |x| x[:name] == name }
if options.nil?
expect(release).to be_nil
else
from = options.keys.find { |k| k.nil? || k.is_a?(SemanticPuppet::Version) }
to = options.delete(from)
if to or from
options[:previous_version] ||= from
options[:version] ||= to
end
expect(release).not_to be_nil
expect(release).to include options
end
end
def flatten_graph(graph)
graph + graph.map { |sub| flatten_graph(sub[:dependencies]) }.flatten
end
def v(str)
SemanticPuppet::Version.parse(str)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/certificate_factory.rb | spec/lib/puppet/certificate_factory.rb | require 'puppet/ssl'
# This class encapsulates the logic of creating and adding extensions to X509
# certificates.
#
# @api private
module Puppet::CertificateFactory
# Create a new X509 certificate and add any needed extensions to the cert.
#
# @param cert_type [Symbol] The certificate type to create, which specifies
# what extensions are added to the certificate.
# One of (:ca, :terminalsubca, :server, :ocsp, :client)
# @param csr [Puppet::SSL::CertificateRequest] The signing request associated with
# the certificate being created.
# @param issuer [OpenSSL::X509::Certificate, OpenSSL::X509::Request] An X509 CSR
# if this is a self signed certificate, or the X509 certificate of the CA if
# this is a CA signed certificate.
# @param serial [Integer] The serial number for the given certificate, which
# MUST be unique for the given CA.
# @param ttl [String] The duration of the validity for the given certificate.
#
# @api public
#
# @return [OpenSSL::X509::Certificate]
def self.build(cert_type, csr, issuer, serial, ttl = 3600)
# Work out if we can even build the requested type of certificate.
build_extensions = "build_#{cert_type}_extensions"
respond_to?(build_extensions) or
raise ArgumentError, _("%{cert_type} is an invalid certificate type!") % { cert_type: cert_type }
raise ArgumentError, _("Certificate TTL must be an integer") unless ttl.nil? || ttl.is_a?(Integer)
# set up the certificate, and start building the content.
cert = OpenSSL::X509::Certificate.new
cert.version = 2 # X509v3
cert.subject = csr.content.subject
cert.issuer = issuer.subject
cert.public_key = csr.content.public_key
cert.serial = serial
# Make the certificate valid as of yesterday, because so many people's
# clocks are out of sync. This gives one more day of validity than people
# might expect, but is better than making every person who has a messed up
# clock fail, and better than having every cert we generate expire a day
# before the user expected it to when they asked for "one year".
cert.not_before = Time.now - (60*60*24)
cert.not_after = Time.now + ttl
add_extensions_to(cert, csr, issuer, send(build_extensions))
return cert
end
# Add X509v3 extensions to the given certificate.
#
# @param cert [OpenSSL::X509::Certificate] The certificate to add the
# extensions to.
# @param csr [OpenSSL::X509::Request] The CSR associated with the given
# certificate, which may specify requested extensions for the given cert.
# See https://tools.ietf.org/html/rfc2985 Section 5.4.2 Extension request
# @param issuer [OpenSSL::X509::Certificate, OpenSSL::X509::Request] An X509 CSR
# if this is a self signed certificate, or the X509 certificate of the CA if
# this is a CA signed certificate.
# @param extensions [Hash<String, Array<String> | String>] The extensions to
# add to the certificate, based on the certificate type being created (CA,
# server, client, etc)
#
# @api private
#
# @return [void]
def self.add_extensions_to(cert, csr, issuer, extensions)
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = issuer.is_a?(OpenSSL::X509::Request) ? cert : issuer
# Extract the requested extensions from the CSR.
requested_exts = csr.request_extensions.inject({}) do |hash, re|
hash[re["oid"]] = [re["value"], re["critical"]]
hash
end
# Produce our final set of extensions. We deliberately order these to
# build the way we want:
# 1. "safe" default values, like the comment, that no one cares about.
# 2. request extensions, from the CSR
# 3. extensions based on the type we are generating
# 4. overrides, which we always want to have in their form
#
# This ordering *is* security-critical, but we want to allow the user
# enough rope to shoot themselves in the foot, if they want to ignore our
# advice and externally approve a CSR that sets the basicConstraints.
#
# Swapping the order of 2 and 3 would ensure that you couldn't slip a
# certificate through where the CA constraint was true, though, if
# something went wrong up there. --daniel 2011-10-11
defaults = { "nsComment" => "Puppet Ruby/OpenSSL Internal Certificate" }
# See https://www.openssl.org/docs/apps/x509v3_config.html
# for information about the special meanings of 'hash', 'keyid', 'issuer'
override = {
"subjectKeyIdentifier" => "hash",
"authorityKeyIdentifier" => "keyid,issuer"
}
exts = [defaults, requested_exts, extensions, override].
inject({}) {|ret, val| ret.merge(val) }
cert.extensions = exts.map do |oid, val|
generate_extension(ef, oid, *val)
end
end
private_class_method :add_extensions_to
# Woot! We're a CA.
def self.build_ca_extensions
{
# This was accidentally omitted in the previous version of this code: an
# effort was made to add it last, but that actually managed to avoid
# adding it to the certificate at all.
#
# We have some sort of bug, which means that when we add it we get a
# complaint that the issuer keyid can't be fetched, which breaks all
# sorts of things in our test suite and, e.g., bootstrapping the CA.
#
# https://tools.ietf.org/html/rfc5280#section-4.2.1.1 says that, to be a
# conforming CA we MAY omit the field if we are self-signed, which I
# think gives us a pass in the specific case.
#
# It also notes that we MAY derive the ID from the subject and serial
# number of the issuer, or from the key ID, and we definitely have the
# former data, should we want to restore this...
#
# Anyway, preserving this bug means we don't risk breaking anything in
# the field, even though it would be nice to have. --daniel 2011-10-11
#
# "authorityKeyIdentifier" => "keyid:always,issuer:always",
"keyUsage" => [%w{cRLSign keyCertSign}, true],
"basicConstraints" => ["CA:TRUE", true],
}
end
# We're a terminal CA, probably not self-signed.
def self.build_terminalsubca_extensions
{
"keyUsage" => [%w{cRLSign keyCertSign}, true],
"basicConstraints" => ["CA:TRUE,pathlen:0", true],
}
end
# We're a normal server.
def self.build_server_extensions
{
"keyUsage" => [%w{digitalSignature keyEncipherment}, true],
"extendedKeyUsage" => [%w{serverAuth clientAuth}, true],
"basicConstraints" => ["CA:FALSE", true],
}
end
# Um, no idea.
def self.build_ocsp_extensions
{
"keyUsage" => [%w{nonRepudiation digitalSignature}, true],
"extendedKeyUsage" => [%w{serverAuth OCSPSigning}, true],
"basicConstraints" => ["CA:FALSE", true],
}
end
# Normal client.
def self.build_client_extensions
{
"keyUsage" => [%w{nonRepudiation digitalSignature keyEncipherment}, true],
# We don't seem to use this, but that seems much more reasonable here...
"extendedKeyUsage" => [%w{clientAuth emailProtection}, true],
"basicConstraints" => ["CA:FALSE", true],
"nsCertType" => "client,email",
}
end
# Generate an extension with the given OID, value, and critical state
#
# @param oid [String] The numeric value or short name of a given OID. X509v3
# extensions must be passed by short name or long name, while custom
# extensions may be passed by short name, long name, oid numeric OID.
# @param ef [OpenSSL::X509::ExtensionFactory] The extension factory to use
# when generating the extension.
# @param val [String, Array<String>] The extension value.
# @param crit [true, false] Whether the given extension is critical, defaults
# to false.
#
# @return [OpenSSL::X509::Extension]
#
# @api private
def self.generate_extension(ef, oid, val, crit = false)
val = val.join(', ') unless val.is_a? String
# Enforce the X509v3 rules about subjectAltName being critical:
# specifically, it SHOULD NOT be critical if we have a subject, which we
# always do. --daniel 2011-10-18
crit = false if oid == "subjectAltName"
if Puppet::SSL::Oids.subtree_of?('id-ce', oid) or Puppet::SSL::Oids.subtree_of?('id-pkix', oid)
# Attempt to create a X509v3 certificate extension. Standard certificate
# extensions may need access to the associated subject certificate and
# issuing certificate, so must be created by the OpenSSL::X509::ExtensionFactory
# which provides that context.
ef.create_ext(oid, val, crit)
else
# This is not an X509v3 extension which means that the extension
# factory cannot generate it. We need to generate the extension
# manually.
OpenSSL::X509::Extension.new(oid, OpenSSL::ASN1::UTF8String.new(val).to_der, crit)
end
end
private_class_method :generate_extension
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/indirector_proxy.rb | spec/lib/puppet/indirector_proxy.rb | class Puppet::IndirectorProxy
class ProxyId
attr_accessor :name
def initialize(name)
self.name = name
end
end
# We should have some way to identify if we got a valid object back with the
# current values, no?
attr_accessor :value, :proxyname
alias_method :name, :value
alias_method :name=, :value=
def initialize(value, proxyname)
self.value = value
self.proxyname = proxyname
end
def self.indirection
ProxyId.new("file_metadata")
end
def self.from_binary(raw)
new(raw)
end
def self.from_data_hash(data)
new(data['value'])
end
def to_data_hash
{ 'value' => value }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/test_ca.rb | spec/lib/puppet/test_ca.rb | module Puppet
class TestCa
CERT_VALID_FROM = Time.at(0).freeze # 1969-12-31 16:00:00 -0800
CERT_VALID_UNTIL = (Time.now + (10 * 365 * 24 * 60 * 60)).freeze # 10 years from now
CA_EXTENSIONS = [
["basicConstraints", "CA:TRUE", true],
["keyUsage", "keyCertSign, cRLSign", true],
["subjectKeyIdentifier", "hash", false],
["nsComment", "Puppet Server Internal Certificate", false],
["authorityKeyIdentifier", "keyid:always", false]
].freeze
attr_reader :ca_cert, :ca_crl, :key
@serial = 0
def self.next_serial
id = @serial
@serial += 1
id
end
def initialize(name = 'Test CA')
@digest = OpenSSL::Digest::SHA256.new
info = create_cacert(name)
@key = info[:private_key]
@ca_cert = info[:cert]
@ca_crl = create_crl(@ca_cert, @key)
end
def create_request(name)
key = OpenSSL::PKey::RSA.new(2048)
csr = OpenSSL::X509::Request.new
csr.public_key = key.public_key
csr.subject = OpenSSL::X509::Name.new([["CN", name]])
csr.version = 0
csr.sign(key, @digest)
{ private_key: key, csr: csr }
end
def create_cert(name, issuer_cert, issuer_key, opts = {})
key, cert = build_cert(name, issuer_cert.subject, opts)
ef = extension_factory_for(issuer_cert, cert)
if opts[:subject_alt_names]
ext = ef.create_extension(["subjectAltName", opts[:subject_alt_names], false])
cert.add_extension(ext)
end
if exts = opts[:extensions]
exts.each do |e|
cert.add_extension(OpenSSL::X509::Extension.new(*e))
end
end
cert.sign(issuer_key, @digest)
{ private_key: key, cert: cert }
end
def create_intermediate_cert(name, issuer_cert, issuer_key)
key, cert = build_cert(name, issuer_cert.subject)
ef = extension_factory_for(issuer_cert, cert)
CA_EXTENSIONS.each do |ext|
cert.add_extension(ef.create_extension(*ext))
end
cert.sign(issuer_key, @digest)
{ private_key: key, cert: cert }
end
def create_cacert(name)
issuer = OpenSSL::X509::Name.new([["CN", name]])
key, cert = build_cert(name, issuer)
ef = extension_factory_for(cert, cert)
CA_EXTENSIONS.each do |ext|
cert.add_extension(ef.create_extension(*ext))
end
cert.sign(key, @digest)
{ private_key: key, cert: cert }
end
def create_crl(issuer_cert, issuer_key)
crl = OpenSSL::X509::CRL.new
crl.version = 1
crl.issuer = issuer_cert.subject
ef = extension_factory_for(issuer_cert)
crl.add_extension(
ef.create_extension(["authorityKeyIdentifier", "keyid:always", false]))
crl.add_extension(
OpenSSL::X509::Extension.new("crlNumber", OpenSSL::ASN1::Integer(0)))
crl.last_update = CERT_VALID_FROM
crl.next_update = CERT_VALID_UNTIL
crl.sign(issuer_key, @digest)
crl
end
def sign(csr, opts = {})
cert = OpenSSL::X509::Certificate.new
cert.public_key = csr.public_key
cert.subject = csr.subject
cert.issuer = @ca_cert.subject
cert.version = 2
cert.serial = self.class.next_serial
cert.not_before = CERT_VALID_FROM
cert.not_after = CERT_VALID_UNTIL
ef = extension_factory_for(@ca_cert, cert)
if opts[:subject_alt_names]
ext = ef.create_extension(["subjectAltName", opts[:subject_alt_names], false])
cert.add_extension(ext)
end
cert.sign(@key, @digest)
Puppet::SSL::Certificate.from_instance(cert)
end
def revoke(cert, crl = @crl, issuer_key = @key)
revoked = OpenSSL::X509::Revoked.new
revoked.serial = cert.serial
revoked.time = Time.now
enum = OpenSSL::ASN1::Enumerated(OpenSSL::OCSP::REVOKED_STATUS_KEYCOMPROMISE)
ext = OpenSSL::X509::Extension.new("CRLReason", enum)
revoked.add_extension(ext)
crl.add_revoked(revoked)
crl.sign(issuer_key, @digest)
end
def generate(name, opts)
info = create_request(name)
cert = sign(info[:csr], opts).content
info.merge(cert: cert)
end
private
def build_cert(name, issuer, opts = {})
key = if opts[:key_type] == :ec
key = OpenSSL::PKey::EC.generate('prime256v1')
elsif opts[:reuse_key]
key = opts[:reuse_key]
else
key = OpenSSL::PKey::RSA.new(2048)
end
cert = OpenSSL::X509::Certificate.new
cert.public_key = key
cert.subject = OpenSSL::X509::Name.new([["CN", name]])
cert.issuer = issuer
cert.version = 2
cert.serial = self.class.next_serial
cert.not_before = CERT_VALID_FROM
cert.not_after = CERT_VALID_UNTIL
[key, cert]
end
def extension_factory_for(ca, cert = nil)
ef = OpenSSL::X509::ExtensionFactory.new
ef.issuer_certificate = ca
ef.subject_certificate = cert if cert
ef
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/indirector_testing.rb | spec/lib/puppet/indirector_testing.rb | require 'puppet/indirector'
class Puppet::IndirectorTesting
extend Puppet::Indirector
indirects :indirector_testing
# We should have some way to identify if we got a valid object back with the
# current values, no?
attr_accessor :value
alias_method :name, :value
alias_method :name=, :value=
def initialize(value)
self.value = value
end
def self.from_binary(raw)
new(raw)
end
def self.from_data_hash(data)
new(data['value'])
end
def to_binary
value
end
def to_data_hash
{ 'value' => value }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/indirector/indirector_testing/memory.rb | spec/lib/puppet/indirector/indirector_testing/memory.rb | require 'puppet/indirector/memory'
class Puppet::IndirectorTesting::Memory < Puppet::Indirector::Memory
def supports_remote_requests?
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/indirector/indirector_testing/msgpack.rb | spec/lib/puppet/indirector/indirector_testing/msgpack.rb | require 'puppet/indirector_testing'
require 'puppet/indirector/msgpack'
class Puppet::IndirectorTesting::Msgpack < Puppet::Indirector::Msgpack
desc "Testing the MessagePack indirector"
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/indirector/indirector_testing/json.rb | spec/lib/puppet/indirector/indirector_testing/json.rb | require 'puppet/indirector_testing'
require 'puppet/indirector/json'
class Puppet::IndirectorTesting::JSON < Puppet::Indirector::JSON
desc "Testing the JSON indirector"
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/face/basetest.rb | spec/lib/puppet/face/basetest.rb | require 'puppet/face'
Puppet::Face.define(:basetest, '0.0.1') do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "This is just so tests don't fail"
option "--[no-]boolean"
option "--mandatory ARGUMENT"
action :foo do
option("--action")
when_invoked do |*args| args.length end
end
action :return_true do
summary "just returns true"
when_invoked do |options| true end
end
action :return_false do
summary "just returns false"
when_invoked do |options| false end
end
action :return_nil do
summary "just returns nil"
when_invoked do |options| nil end
end
action :raise do
summary "just raises an exception"
when_invoked do |options| raise ArgumentError, "your failure" end
end
action :with_s_rendering_hook do
summary "has a rendering hook for 's'"
when_invoked do |options| "this is not the hook you are looking for" end
when_rendering :s do |value| "you invoked the 's' rendering hook" end
end
action :count_args do
summary "return the count of arguments given"
when_invoked do |*args| args.length - 1 end
end
action :with_specific_exit_code do
summary "just call exit with the desired exit code"
when_invoked do |options| exit(5) end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/face/huzzah.rb | spec/lib/puppet/face/huzzah.rb | require 'puppet/face'
Puppet::Face.define(:huzzah, '2.0.1') do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "life is a thing for celebration"
action(:bar) { when_invoked { |options| "is where beer comes from" } }
action(:call_older) { when_invoked { |_| method_on_older } }
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/face/version_matching.rb | spec/lib/puppet/face/version_matching.rb | require 'puppet/face'
# The set of versions here are used explicitly in the interface_spec; if you
# change this you need to ensure that is still correct. --daniel 2011-04-21
['1.0.0', '1.0.1', '1.1.0', '1.1.1', '2.0.0'].each do |version|
Puppet::Face.define(:version_matching, version) do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "version matching face #{version}"
action(:version) { when_invoked { |options| version } }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/face/1.0.0/huzzah.rb | spec/lib/puppet/face/1.0.0/huzzah.rb | require 'puppet/face'
Puppet::Face.define(:huzzah, '1.0.0') do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "life is a thing for celebration"
action(:obsolete_in_core) { when_invoked { |_| "you are in obsolete core now!" } }
action(:call_newer) { when_invoked { |_| method_on_newer } }
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/lib/puppet/face/huzzah/obsolete.rb | spec/lib/puppet/face/huzzah/obsolete.rb | Puppet::Face.define(:huzzah, '1.0.0') do
action :obsolete do
summary "This is an action on version 1.0.0 of the face"
when_invoked do |options| options end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/environments_spec.rb | spec/unit/environments_spec.rb | require 'spec_helper'
require 'puppet/environments'
require 'puppet/file_system'
describe Puppet::Environments do
FS = Puppet::FileSystem
module FsRemove
def remove
@properties[:directory?] = false
@properties[:exist?] = false
@properties[:executable?] = false
end
end
before(:each) do
Puppet.settings.initialize_global_settings
Puppet[:environment_timeout] = "unlimited"
Puppet[:versioned_environment_dirs] = true
end
let(:directory_tree) do
FS::MemoryFile.a_directory(File.expand_path("top_level_dir"), [
FS::MemoryFile.a_directory("envdir", [
FS::MemoryFile.a_regular_file_containing("ignored_file", ''),
FS::MemoryFile.a_directory("an_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_directory("another_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
FS::MemoryFile.a_missing_file("doesnotexist"),
FS::MemoryFile.a_symlink("symlinked_environment", File.expand_path(File.join("top_level_dir", "versioned_env")))]),
FS::MemoryFile.a_directory("versioned_env", [
FS::MemoryFile.a_regular_file_containing("environment.conf", ''),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_missing_file("missing")
])
end
describe "directories loader" do
it "lists environments" do
global_path_1_location = File.expand_path("global_path_1")
global_path_2_location = File.expand_path("global_path_2")
global_path_1 = FS::MemoryFile.a_directory(global_path_1_location)
global_path_2 = FS::MemoryFile.a_directory(global_path_2_location)
loader_from(:filesystem => [directory_tree, global_path_1, global_path_2],
:directory => directory_tree.children.first,
:modulepath => [global_path_1_location, global_path_2_location]) do |loader|
expect(loader.list).to contain_exactly(
environment(:an_environment).
with_manifest("#{FS.path_string(directory_tree)}/envdir/an_environment/manifests").
with_modulepath(["#{FS.path_string(directory_tree)}/envdir/an_environment/modules",
global_path_1_location,
global_path_2_location]),
environment(:another_environment),
environment(:symlinked_environment).
with_manifest("#{FS.path_string(directory_tree)}/versioned_env/manifests").
with_modulepath(["#{FS.path_string(directory_tree)}/versioned_env/modules",
global_path_1_location,
global_path_2_location]))
end
end
it "has search_paths" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.search_paths).to eq(["file://#{directory_tree.children.first}"])
end
end
it "ignores directories that are not valid env names (alphanumeric and _)" do
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory(".foo"),
FS::MemoryFile.a_directory("bar-thing"),
FS::MemoryFile.a_directory("with spaces"),
FS::MemoryFile.a_directory("some.thing"),
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
FS::MemoryFile.a_directory("env2", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.list).to contain_exactly(environment(:env1), environment(:env2))
end
end
it "proceeds with non-existant env dir" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.last) do |loader|
expect(loader.list).to eq([])
end
end
it "gets a particular environment" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("an_environment")).to environment(:an_environment)
end
end
it "gets a symlinked environment" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("symlinked_environment")).to environment(:symlinked_environment)
end
end
it "sets the environment's configured and resolved paths set when symlinked" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
env = loader.get("symlinked_environment")
expect(env.resolved_path).to eq("#{FS.path_string(directory_tree)}/versioned_env")
expect(env.configured_path).to eq("#{FS.path_string(directory_tree)}/envdir/symlinked_environment")
end
end
it "ignores symlinked environments when `:versioned_environment_dirs` is false" do
Puppet[:versioned_environment_dirs] = false
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("symlinked_environment")).to be_nil
end
end
it "raises error when environment not found" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect do
loader.get!("doesnotexist")
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
it "returns nil if an environment can't be found" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("doesnotexist")).to be_nil
end
end
it "implements guard and unguard" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.guard('env1')).to be_nil
expect(loader.unguard('env1')).to be_nil
end
end
context "with an environment.conf" do
let(:envdir) do
FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
]),
])
end
let(:manifestdir) { FS::MemoryFile.a_directory(File.expand_path("/some/manifest/path")) }
let(:modulepath) do
[
FS::MemoryFile.a_directory(File.expand_path("/some/module/path")),
FS::MemoryFile.a_directory(File.expand_path("/some/other/path")),
]
end
let(:content) do
<<-EOF
manifest=#{manifestdir}
modulepath=#{modulepath.join(File::PATH_SEPARATOR)}
config_version=/some/script
static_catalogs=false
EOF
end
it "reads environment.conf settings" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path))
end
end
it "does not append global_module_path to environment.conf modulepath setting" do
global_path_location = File.expand_path("global_path")
global_path = FS::MemoryFile.a_directory(global_path_location)
loader_from(:filesystem => [envdir, manifestdir, modulepath, global_path].flatten,
:directory => envdir,
:modulepath => [global_path]) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path))
end
end
it "reads config_version setting" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
end
it "reads static_catalogs setting" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script')).
with_static_catalogs(false)
end
end
it "accepts an empty environment.conf without warning" do
content = nil
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
]),
])
manifestdir = FS::MemoryFile.a_directory(File.join(envdir, "env1", "manifests"))
modulesdir = FS::MemoryFile.a_directory(File.join(envdir, "env1", "modules"))
global_path_location = File.expand_path("global_path")
global_path = FS::MemoryFile.a_directory(global_path_location)
loader_from(:filesystem => [envdir, manifestdir, modulesdir, global_path].flatten,
:directory => envdir,
:modulepath => [global_path]) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest("#{FS.path_string(envdir)}/env1/manifests").
with_modulepath(["#{FS.path_string(envdir)}/env1/modules", global_path_location]).
with_config_version(nil).
with_static_catalogs(true)
end
expect(@logs).to be_empty
end
it "logs a warning, but processes the main settings if there are extraneous sections" do
content << "[foo]"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*may not have sections.*ignored: 'foo'/)
end
it "logs a warning, but processes the main settings if there are any extraneous settings" do
content << "dog=arf\n"
content << "cat=mew\n"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*unknown setting.*dog, cat/)
end
it "logs a warning, but processes the main settings if there are any ignored sections" do
content << "dog=arf\n"
content << "cat=mew\n"
content << "[ignored]\n"
content << "cow=moo\n"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*The following sections are being ignored: 'ignored'/)
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*unknown setting.*dog, cat/)
end
it "interpretes relative paths from the environment's directory" do
content = <<-EOF
manifest=relative/manifest
modulepath=relative/modules
config_version=relative/script
EOF
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_missing_file("modules"),
FS::MemoryFile.a_directory('relative', [
FS::MemoryFile.a_directory('modules'),
]),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(envdir, 'env1', 'relative', 'manifest')).
with_modulepath([File.join(envdir, 'env1', 'relative', 'modules')]).
with_config_version(File.join(envdir, 'env1', 'relative', 'script'))
end
end
it "interprets glob modulepaths from the environment's directory" do
allow(Dir).to receive(:glob).with(File.join(envdir, 'env1', 'other', '*', 'modules')).and_return([
File.join(envdir, 'env1', 'other', 'foo', 'modules'),
File.join(envdir, 'env1', 'other', 'bar', 'modules')
])
content = <<-EOF
manifest=relative/manifest
modulepath=relative/modules#{File::PATH_SEPARATOR}other/*/modules
config_version=relative/script
EOF
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_missing_file("modules"),
FS::MemoryFile.a_directory('relative', [
FS::MemoryFile.a_directory('modules'),
]),
FS::MemoryFile.a_directory('other', [
FS::MemoryFile.a_directory('foo', [
FS::MemoryFile.a_directory('modules'),
]),
FS::MemoryFile.a_directory('bar', [
FS::MemoryFile.a_directory('modules'),
]),
]),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(envdir, 'env1', 'relative', 'manifest')).
with_modulepath([File.join(envdir, 'env1', 'relative', 'modules'),
File.join(envdir, 'env1', 'other', 'foo', 'modules'),
File.join(envdir, 'env1', 'other', 'bar', 'modules')]).
with_config_version(File.join(envdir, 'env1', 'relative', 'script'))
end
end
it "interpolates other setting values correctly" do
modulepath = [
File.expand_path('/some/absolute'),
'$basemodulepath',
'modules'
].join(File::PATH_SEPARATOR)
content = <<-EOF
manifest=$confdir/whackymanifests
modulepath=#{modulepath}
config_version=$vardir/random/scripts
EOF
some_absolute_dir = FS::MemoryFile.a_directory(File.expand_path('/some/absolute'))
base_module_dirs = Puppet[:basemodulepath].split(File::PATH_SEPARATOR).map do |path|
FS::MemoryFile.a_directory(path)
end
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_directory("modules"),
]),
])
loader_from(:filesystem => [envdir, some_absolute_dir, base_module_dirs].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(Puppet[:confdir], 'whackymanifests')).
with_modulepath([some_absolute_dir.path,
base_module_dirs.map { |d| d.path },
File.join(envdir, 'env1', 'modules')].flatten).
with_config_version(File.join(Puppet[:vardir], 'random', 'scripts'))
end
end
it "uses environment.conf settings regardless of existence of modules and manifests subdirectories" do
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
])
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
end
it "should update environment settings if environment.conf has changed and timeout has expired" do
base_dir = File.expand_path("envdir")
original_envdir = FS::MemoryFile.a_directory(base_dir, [
FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", <<-EOF)
manifest=/manifest_orig
modulepath=/modules_orig
environment_timeout=0
EOF
]),
])
cached_loader_from(:filesystem => [original_envdir], :directory => original_envdir) do |loader|
original_env = loader.get("env3") # force the environment.conf to be read
changed_envdir = FS::MemoryFile.a_directory(base_dir, [
FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", <<-EOF)
manifest=/manifest_changed
modulepath=/modules_changed
environment_timeout=0
EOF
]),
])
FS.overlay(changed_envdir) do
changed_env = loader.get("env3")
expect(original_env).to environment(:env3).
with_manifest(File.expand_path("/manifest_orig")).
with_full_modulepath([File.expand_path("/modules_orig")])
expect(changed_env).to environment(:env3).
with_manifest(File.expand_path("/manifest_changed")).
with_full_modulepath([File.expand_path("/modules_changed")])
end
end
end
end
end
describe "static loaders" do
let(:static1) { Puppet::Node::Environment.create(:static1, []) }
let(:static2) { Puppet::Node::Environment.create(:static2, []) }
let(:loader) { Puppet::Environments::Static.new(static1, static2) }
it "lists environments" do
expect(loader.list).to eq([static1, static2])
end
it "has search_paths" do
expect(loader.search_paths).to eq(["data:text/plain,internal"])
end
it "gets an environment" do
expect(loader.get(:static2)).to eq(static2)
end
it "returns nil if env not found" do
expect(loader.get(:doesnotexist)).to be_nil
end
it "raises error if environment is not found" do
expect do
loader.get!(:doesnotexist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
it "gets a basic conf" do
conf = loader.get_conf(:static1)
expect(conf.modulepath).to eq('')
expect(conf.manifest).to eq(:no_manifest)
expect(conf.config_version).to be_nil
expect(conf.static_catalogs).to eq(true)
end
it "returns nil if you request a configuration from an env that doesn't exist" do
expect(loader.get_conf(:doesnotexist)).to be_nil
end
it "gets the conf environment_timeout if one is specified" do
Puppet[:environment_timeout] = 8675
conf = loader.get_conf(:static1)
expect(conf.environment_timeout).to eq(8675)
end
context "that are private" do
let(:private_env) { Puppet::Node::Environment.create(:private, []) }
let(:loader) { Puppet::Environments::StaticPrivate.new(private_env) }
it "lists nothing" do
expect(loader.list).to eq([])
end
end
end
describe "combined loaders" do
let(:static1) { Puppet::Node::Environment.create(:static1, []) }
let(:static2) { Puppet::Node::Environment.create(:static2, []) }
let(:static_loader) { Puppet::Environments::Static.new(static1, static2) }
let(:directory_tree) do
FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("an_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_missing_file("env_does_not_exist"),
FS::MemoryFile.a_missing_file("static2"),
])
end
it "lists environments" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
envs = Puppet::Environments::Combined.new(loader, static_loader).list
expect(envs[0]).to environment(:an_environment)
expect(envs[1]).to environment(:static1)
expect(envs[2]).to environment(:static2)
end
end
it "has search_paths" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).search_paths).to eq(["file://#{directory_tree}","data:text/plain,internal"])
end
end
it "gets an environment" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:an_environment)).to environment(:an_environment)
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:static2)).to environment(:static2)
end
end
it "returns nil if env not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:env_does_not_exist)).to be_nil
end
end
it "raises an error if environment is not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect do
Puppet::Environments::Combined.new(loader, static_loader).get!(:env_does_not_exist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
it "gets an environment.conf" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get_conf(:an_environment)).to match_environment_conf(:an_environment).
with_env_path(directory_tree).
with_global_module_path([])
end
end
end
describe "cached loaders" do
it "lists environments" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.list).to contain_exactly(
environment(:an_environment),
environment(:another_environment),
environment(:symlinked_environment))
end
end
it "returns the same cached environment object for list and get methods" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
env = loader.list.find { |e| e.name == :an_environment }
expect(env).to equal(loader.get(:an_environment)) # same object
end
end
it "returns the same cached environment object for multiple list calls" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.list.first).to equal(loader.list.first) # same object
end
end
it "expires environments and returns a new environment object with the same value" do
Puppet[:environment_timeout] = "0"
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
a = loader.list.first
b = loader.list.first
expect(a).to eq(b) # same value
expect(a).to_not equal(b) # not same object
end
end
it "has search_paths" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.search_paths).to eq(["file://#{directory_tree.children.first}"])
end
end
context "#get" do
it "gets an environment" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get(:an_environment)).to environment(:an_environment)
end
end
it "does not reload the environment if it isn't expired" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get).with(:cached).and_return(env).once
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get(:cached)
cached.get(:cached)
end
it "does not list deleted environments" do
env3 = FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", '')
])
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", '')
]),
FS::MemoryFile.a_directory("env2", [
FS::MemoryFile.a_regular_file_containing("environment.conf", '')
]),
env3
])
loader_from(:filesystem => [envdir], :directory => envdir) do |loader|
cached = Puppet::Environments::Cached.new(loader)
cached.get(:env1)
cached.get(:env2)
cached.get(:env3)
env3.extend(FsRemove).remove
expect(cached.list).to contain_exactly(environment(:env1),environment(:env2))
expect(cached.get(:env3)).to be_nil
end
end
it "normalizes environment name to symbol" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).not_to receive(:get).with('cached')
expect(mocked_loader).to receive(:get).with(:cached).and_return(env).once
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get('cached')
cached.get(:cached)
end
it "caches environment name as symbol and only once" do
mocked_loader = double('loader')
env = Puppet::Node::Environment.create(:cached, [])
allow(mocked_loader).to receive(:get).with(:cached).and_return(env)
allow(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20))
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get(:cached)
cached.get('cached')
expect(cached.instance_variable_get(:@cache).keys).to eq([:cached])
end
it "is able to cache multiple environments" do
mocked_loader = double('loader')
env1 = Puppet::Node::Environment.create(:env1, [])
allow(mocked_loader).to receive(:get).with(:env1).and_return(env1)
allow(mocked_loader).to receive(:get_conf).with(:env1).and_return(Puppet::Settings::EnvironmentConf.static_for(env1, 20))
env2 = Puppet::Node::Environment.create(:env2, [])
allow(mocked_loader).to receive(:get).with(:env2).and_return(env2)
allow(mocked_loader).to receive(:get_conf).with(:env2).and_return(Puppet::Settings::EnvironmentConf.static_for(env2, 20))
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get('env1')
cached.get('env2')
expect(cached.instance_variable_get(:@cache).keys).to eq([:env1, :env2])
end
it "returns nil if env not found" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get(:doesnotexist)).to be_nil
end
end
end
context "#get!" do
it "gets an environment" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get!(:an_environment)).to environment(:an_environment)
end
end
it "does not reload the environment if it isn't expired" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get).with(:cached).and_return(env).once
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get!(:cached)
cached.get!(:cached)
end
it "raises error if environment is not found" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect do
loader.get!(:doesnotexist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
end
context "#get_conf" do
it "loads environment.conf" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get_conf(:an_environment)).to match_environment_conf(:an_environment).
with_env_path(directory_tree.children.first).
with_global_module_path([])
end
end
it "always reloads environment.conf" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).twice
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get_conf(:cached)
cached.get_conf(:cached)
end
it "normalizes environment name to symbol" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).twice
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get_conf('cached')
cached.get_conf(:cached)
end
it "returns nil if environment is not found" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get_conf(:doesnotexist)).to be_nil
end
end
end
context "expiration policies" do
let(:service) { ReplayExpirationService.new }
it "notifies when the environment is first created" do
with_environment_loaded(service)
expect(service.created_envs).to eq([:an_environment])
end
it "does not evict an unexpired environment" do
Puppet[:environment_timeout] = 'unlimited'
with_environment_loaded(service) do |cached|
cached.get!(:an_environment)
end
expect(service.created_envs).to eq([:an_environment])
expect(service.evicted_envs).to eq([])
end
it "evicts an expired environment" do
expect(service).to receive(:expired?).and_return(true)
with_environment_loaded(service) do |cached|
cached.get!(:an_environment)
end
expect(service.created_envs).to eq([:an_environment, :an_environment])
expect(service.evicted_envs).to eq([:an_environment])
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/hiera_puppet_spec.rb | spec/unit/hiera_puppet_spec.rb | require 'spec_helper'
require 'hiera_puppet'
require 'puppet_spec/scope'
describe 'HieraPuppet', :if => Puppet.features.hiera? do
include PuppetSpec::Scope
after(:all) do
HieraPuppet.instance_variable_set(:@hiera, nil)
end
describe 'HieraPuppet#hiera_config' do
let(:hiera_config_data) do
{ :backend => 'yaml' }
end
context "when the hiera_config_file exists" do
before do
expect(Hiera::Config).to receive(:load).and_return(hiera_config_data)
expect(HieraPuppet).to receive(:hiera_config_file).and_return(true)
end
it "should return a configuration hash" do
expected_results = {
:backend => 'yaml',
:logger => 'puppet'
}
expect(HieraPuppet.send(:hiera_config)).to eq(expected_results)
end
end
context "when the hiera_config_file does not exist" do
before do
expect(Hiera::Config).not_to receive(:load)
expect(HieraPuppet).to receive(:hiera_config_file).and_return(nil)
end
it "should return a configuration hash" do
expect(HieraPuppet.send(:hiera_config)).to eq({ :logger => 'puppet' })
end
end
end
describe 'HieraPuppet#hiera_config_file' do
it "should return nil when we cannot derive the hiera config file from Puppet.settings" do
begin
Puppet.settings[:hiera_config] = nil
rescue ArgumentError => detail
raise unless detail.message =~ /unknown setting/
end
expect(HieraPuppet.send(:hiera_config_file)).to be_nil
end
it "should use Puppet.settings[:hiera_config] as the hiera config file" do
begin
Puppet.settings[:hiera_config] = "/dev/null/my_hiera.yaml"
rescue ArgumentError => detail
raise unless detail.message =~ /unknown setting/
pending("This example does not apply to Puppet #{Puppet.version} because it does not have this setting")
end
allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:hiera_config]).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(Puppet[:hiera_config])
end
context 'when hiera_config is not set' do
let(:code_hiera_config) { File.join(Puppet[:codedir], 'hiera.yaml') }
let(:conf_hiera_config) { File.join(Puppet[:confdir], 'hiera.yaml') }
before(:each) do
Puppet.settings.setting(:hiera_config).send(:remove_instance_variable, :@evaluated_default)
Puppet.settings[:hiera_config] = nil
Puppet.settings[:codedir] = '/dev/null/puppetlabs/code'
Puppet.settings[:confdir] = '/dev/null/puppetlabs/puppet'
end
it "should use Puppet.settings[:codedir]/hiera.yaml when '$codedir/hiera.yaml' exists and '$confdir/hiera.yaml' does not exist" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(false)
expect(HieraPuppet.send(:hiera_config_file)).to eq(code_hiera_config)
end
it "should use Puppet.settings[:confdir]/hiera.yaml when '$codedir/hiera.yaml' does not exist and '$confdir/hiera.yaml' exists" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(conf_hiera_config)
end
it "should use Puppet.settings[:codedir]/hiera.yaml when '$codedir/hiera.yaml' exists and '$confdir/hiera.yaml' exists" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(code_hiera_config)
end
it "should return nil when neither '$codedir/hiera.yaml' nor '$confdir/hiera.yaml' exists" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(false)
expect(HieraPuppet.send(:hiera_config_file)).to eq(nil)
end
it "should return explicitly set option even if both '$codedir/hiera.yaml' and '$confdir/hiera.yaml' exists" do
if Puppet::Util::Platform.windows?
explicit_hiera_config = 'C:/an/explicit/hiera.yaml'
else
explicit_hiera_config = '/an/explicit/hiera.yaml'
end
Puppet.settings[:hiera_config] = explicit_hiera_config
allow(Puppet::FileSystem).to receive(:exist?).with(explicit_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(explicit_hiera_config)
end
end
end
describe 'HieraPuppet#lookup' do
let :scope do create_test_scope_for_node('foo') end
before :each do
Puppet[:hiera_config] = PuppetSpec::Files.tmpfile('hiera_config')
end
it "should return the value from Hiera" do
allow_any_instance_of(Hiera).to receive(:lookup).and_return('8080')
expect(HieraPuppet.lookup('port', nil, scope, nil, :priority)).to eq('8080')
allow_any_instance_of(Hiera).to receive(:lookup).and_return(['foo', 'bar'])
expect(HieraPuppet.lookup('ntpservers', nil, scope, nil, :array)).to eq(['foo', 'bar'])
allow_any_instance_of(Hiera).to receive(:lookup).and_return({'uid' => '1000'})
expect(HieraPuppet.lookup('user', nil, scope, nil, :hash)).to eq({'uid' => '1000'})
end
it "should raise a useful error when the answer is nil" do
allow_any_instance_of(Hiera).to receive(:lookup).and_return(nil)
expect do
HieraPuppet.lookup('port', nil, scope, nil, :priority)
end.to raise_error(Puppet::ParseError,
/Could not find data item port in any Hiera data file and no default supplied/)
end
end
describe 'HieraPuppet#parse_args' do
it 'should return a 3 item array' do
args = ['foo', '8080', nil, nil]
expect(HieraPuppet.parse_args(args)).to eq(['foo', '8080', nil])
end
it 'should raise a useful error when no key is supplied' do
expect { HieraPuppet.parse_args([]) }.to raise_error(Puppet::ParseError,
/Please supply a parameter to perform a Hiera lookup/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/agent_spec.rb | spec/unit/agent_spec.rb | require 'spec_helper'
require 'puppet/agent'
require 'puppet/configurer'
class AgentTestClient
def initialize(transaction_uuid = nil, job_id = nil)
end
def run(client_args)
# no-op
end
def stop
# no-op
end
end
describe Puppet::Agent do
before do
@agent = Puppet::Agent.new(AgentTestClient, false)
# make Puppet::Application safe for stubbing
stub_const('Puppet::Application', Class.new(Puppet::Application))
allow(Puppet::Application).to receive(:clear?).and_return(true)
Puppet::Application.class_eval do
class << self
def controlled_run(&block)
block.call
end
end
end
ssl_context = Puppet::SSL::SSLContext.new
machine = instance_double("Puppet::SSL::StateMachine", ensure_client_certificate: ssl_context)
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(machine)
end
it "should set its client class at initialization" do
expect(Puppet::Agent.new("foo", false).client_class).to eq("foo")
end
it "should include the Locker module" do
expect(Puppet::Agent.ancestors).to be_include(Puppet::Agent::Locker)
end
it "should create an instance of its client class and run it when asked to run" do
client = double('client')
allow(AgentTestClient).to receive(:new).with(nil, nil).and_return(client)
allow(@agent).to receive(:disabled?).and_return(false)
expect(client).to receive(:run)
@agent.run
end
it "should initialize the client's transaction_uuid if passed as a client_option" do
client = double('client')
transaction_uuid = 'foo'
expect(AgentTestClient).to receive(:new).with(transaction_uuid, nil).and_return(client)
expect(client).to receive(:run)
allow(@agent).to receive(:disabled?).and_return(false)
@agent.run(:transaction_uuid => transaction_uuid)
end
it "should initialize the client's job_id if passed as a client_option" do
client = double('client')
job_id = '289'
expect(AgentTestClient).to receive(:new).with(anything, job_id).and_return(client)
expect(client).to receive(:run)
allow(@agent).to receive(:disabled?).and_return(false)
@agent.run(:job_id => job_id)
end
it "should be considered running if the lock file is locked" do
lockfile = double('lockfile')
expect(@agent).to receive(:lockfile).and_return(lockfile)
expect(lockfile).to receive(:locked?).and_return(true)
expect(@agent).to be_running
end
describe "when being run" do
before do
allow(@agent).to receive(:disabled?).and_return(false)
end
it "should splay" do
Puppet[:splay] = true
expect(@agent).to receive(:splay)
@agent.run
end
it "should do nothing if disabled" do
expect(@agent).to receive(:disabled?).and_return(true)
expect(AgentTestClient).not_to receive(:new)
@agent.run
end
it "(#11057) should notify the user about why a run is skipped" do
allow(Puppet::Application).to receive(:controlled_run).and_return(false)
allow(Puppet::Application).to receive(:run_status).and_return('MOCK_RUN_STATUS')
# This is the actual test that we inform the user why the run is skipped.
# We assume this information is contained in
# Puppet::Application.run_status
expect(Puppet).to receive(:notice).with(/MOCK_RUN_STATUS/)
@agent.run
end
it "should display an informative message if the agent is administratively disabled" do
expect(@agent).to receive(:disabled?).and_return(true)
expect(@agent).to receive(:disable_message).and_return("foo")
expect(Puppet).to receive(:notice).with(/Skipping run of .*; administratively disabled.*\(Reason: 'foo'\)/)
@agent.run
end
it "should use Puppet::Application.controlled_run to manage process state behavior" do
expect(Puppet::Application).to receive(:controlled_run).ordered.and_yield
expect(AgentTestClient).to receive(:new).ordered.once
@agent.run
end
it "should not fail if a client class instance cannot be created" do
expect(AgentTestClient).to receive(:new).and_raise("eh")
expect(Puppet).to receive(:log_exception)
@agent.run
end
it "should not fail if there is an exception while running its client" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise("eh")
expect(Puppet).to receive(:log_exception)
@agent.run
end
it "should use a filesystem lock to restrict multiple processes running the agent" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(@agent).to receive(:lock)
expect(client).not_to receive(:run) # if it doesn't run, then we know our yield is what triggers it
@agent.run
end
it "should make its client instance available while running" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run) { expect(@agent.client).to equal(client); nil }
@agent.run
end
it "should run the client instance with any arguments passed to it" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).with({:pluginsync => true, :other => :options})
@agent.run(:other => :options)
end
it "should return the agent result" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(@agent).to receive(:lock).and_return(:result)
expect(@agent.run).to eq(:result)
end
it "should check if it's disabled after splaying and log a message" do
Puppet[:splay] = true
Puppet[:splaylimit] = '5s'
Puppet[:onetime] = true
expect(@agent).to receive(:disabled?).and_return(false, true)
allow(Puppet).to receive(:notice).and_call_original
expect(Puppet).to receive(:notice).with(/Skipping run of .*; administratively disabled.*/)
@agent.run
end
it "should check if it's disabled after acquiring the lock and log a message" do
expect(@agent).to receive(:disabled?).and_return(false, true)
allow(Puppet).to receive(:notice).and_call_original
expect(Puppet).to receive(:notice).with(/Skipping run of .*; administratively disabled.*/)
@agent.run
end
describe "and a puppet agent is already running" do
before(:each) do
allow_any_instance_of(Object).to receive(:sleep)
lockfile = double('lockfile')
expect(@agent).to receive(:lockfile).and_return(lockfile).at_least(:once)
# so the lock method raises Puppet::LockError
allow(lockfile).to receive(:lock).and_return(false)
end
it "should notify that a run is already in progress" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(Puppet).to receive(:notice).with(/Run of .* already in progress; skipping .* exists/)
@agent.run
end
it "should inform that a run is already in progress and try to run every X seconds if waitforlock is used" do
# so the locked file exists
allow(File).to receive(:file?).and_return(true)
# so we don't have to wait again for the run to exit (default maxwaitforcert is 60)
# first 0 is to get the time, second 0 is to inform user, then 1000 so the time expires
allow(Time).to receive(:now).and_return(0, 0, 1000)
allow(Puppet).to receive(:info)
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
Puppet[:waitforlock] = 1
Puppet[:maxwaitforlock] = 2
expect(Puppet).to receive(:info).with(/Another puppet instance is already running; --waitforlock flag used, waiting for running instance to finish./)
expect(Puppet).to receive(:info).with(/Will try again in #{Puppet[:waitforlock]} seconds./)
@agent.run
end
it "should notify that the run is exiting if waitforlock is used and maxwaitforlock is exceeded" do
# so we don't have to wait again for the run to exit (default maxwaitforcert is 60)
# first 0 is to get the time, then 1000 so that the time expires
allow(Time).to receive(:now).and_return(0, 1000)
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
Puppet[:waitforlock] = 1
expect(Puppet).to receive(:notice).with(/Exiting now because the maxwaitforlock timeout has been exceeded./)
@agent.run
end
end
describe "when should_fork is true", :if => Puppet.features.posix? && RUBY_PLATFORM != 'java' do
before do
@agent = Puppet::Agent.new(AgentTestClient, true)
# So we don't actually try to hit the filesystem.
allow(@agent).to receive(:lock).and_yield
end
it "should run the agent in a forked process" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_return(0)
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(0)
end
it "should exit child process if child exit" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise(SystemExit.new(-1))
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(-1)
end
it 'should exit with 1 if an exception is raised' do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise(StandardError)
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(1)
end
it 'should exit with 254 if NoMemoryError exception is raised' do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise(NoMemoryError)
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(254)
end
it "should return the block exit code as the child exit code" do
expect(Kernel).to receive(:fork).and_yield
expect {
@agent.run_in_fork {
777
}
}.to exit_with(777)
end
it "should return `1` exit code if the block returns `nil`" do
expect(Kernel).to receive(:fork).and_yield
expect {
@agent.run_in_fork {
nil
}
}.to exit_with(1)
end
it "should return `1` exit code if the block returns `false`" do
expect(Kernel).to receive(:fork).and_yield
expect {
@agent.run_in_fork {
false
}
}.to exit_with(1)
end
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
it "should never fork" do
agent = Puppet::Agent.new(AgentTestClient, true)
expect(agent.should_fork).to be_falsey
end
end
describe 'when runtimeout is set' do
before(:each) do
Puppet[:runtimeout] = 1
end
it 'times out when a run exceeds the set limit' do
client = AgentTestClient.new
client.instance_eval do
# Stub methods used to set test expectations.
def processing; end
def handling; end
def run(client_options = {})
# Simulate a hanging agent operation that also traps errors.
begin
::Kernel.sleep(5)
processing()
rescue
handling()
end
end
end
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).not_to receive(:processing)
expect(client).not_to receive(:handling)
expect(Puppet).to receive(:log_exception).with(be_an_instance_of(Puppet::Agent::RunTimeoutError), anything)
expect(@agent.run).to eq(nil)
end
end
end
describe "when checking execution state" do
describe 'with regular run status' do
before :each do
allow(Puppet::Application).to receive(:restart_requested?).and_return(false)
allow(Puppet::Application).to receive(:stop_requested?).and_return(false)
allow(Puppet::Application).to receive(:interrupted?).and_return(false)
allow(Puppet::Application).to receive(:clear?).and_return(true)
end
it 'should be false for :stopping?' do
expect(@agent.stopping?).to be_falsey
end
it 'should be false for :needing_restart?' do
expect(@agent.needing_restart?).to be_falsey
end
end
describe 'with a stop requested' do
before :each do
allow(Puppet::Application).to receive(:clear?).and_return(false)
allow(Puppet::Application).to receive(:restart_requested?).and_return(false)
allow(Puppet::Application).to receive(:stop_requested?).and_return(true)
allow(Puppet::Application).to receive(:interrupted?).and_return(true)
end
it 'should be true for :stopping?' do
expect(@agent.stopping?).to be_truthy
end
it 'should be false for :needing_restart?' do
expect(@agent.needing_restart?).to be_falsey
end
end
describe 'with a restart requested' do
before :each do
allow(Puppet::Application).to receive(:clear?).and_return(false)
allow(Puppet::Application).to receive(:restart_requested?).and_return(true)
allow(Puppet::Application).to receive(:stop_requested?).and_return(false)
allow(Puppet::Application).to receive(:interrupted?).and_return(true)
end
it 'should be false for :stopping?' do
expect(@agent.stopping?).to be_falsey
end
it 'should be true for :needing_restart?' do
expect(@agent.needing_restart?).to be_truthy
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confine_collection_spec.rb | spec/unit/confine_collection_spec.rb | require 'spec_helper'
require 'puppet/confine_collection'
describe Puppet::ConfineCollection do
it "should be able to add confines" do
expect(Puppet::ConfineCollection.new("label")).to respond_to(:confine)
end
it "should require a label at initialization" do
expect { Puppet::ConfineCollection.new }.to raise_error(ArgumentError)
end
it "should make its label available" do
expect(Puppet::ConfineCollection.new("mylabel").label).to eq("mylabel")
end
describe "when creating confine instances" do
it "should create an instance of the named test with the provided values" do
test_class = double('test_class')
expect(test_class).to receive(:new).with(%w{my values}).and_return(double('confine', :label= => nil))
expect(Puppet::Confine).to receive(:test).with(:foo).and_return(test_class)
Puppet::ConfineCollection.new("label").confine :foo => %w{my values}
end
it "should copy its label to the confine instance" do
confine = double('confine')
test_class = double('test_class')
expect(test_class).to receive(:new).and_return(confine)
expect(Puppet::Confine).to receive(:test).and_return(test_class)
expect(confine).to receive(:label=).with("label")
Puppet::ConfineCollection.new("label").confine :foo => %w{my values}
end
describe "and the test cannot be found" do
it "should create a Facter test with the provided values and set the name to the test name" do
confine = Puppet::Confine.test(:variable).new(%w{my values})
expect(confine).to receive(:name=).with(:foo)
expect(confine.class).to receive(:new).with(%w{my values}).and_return(confine)
Puppet::ConfineCollection.new("label").confine(:foo => %w{my values})
end
end
describe "and the 'for_binary' option was provided" do
it "should mark the test as a binary confine" do
confine = Puppet::Confine.test(:exists).new(:bar)
expect(confine).to receive(:for_binary=).with(true)
expect(Puppet::Confine.test(:exists)).to receive(:new).with(:bar).and_return(confine)
Puppet::ConfineCollection.new("label").confine :exists => :bar, :for_binary => true
end
end
end
it "should be valid if no confines are present" do
expect(Puppet::ConfineCollection.new("label")).to be_valid
end
it "should be valid if all confines pass" do
c1 = double('c1', :valid? => true, :label= => nil)
c2 = double('c2', :valid? => true, :label= => nil)
expect(Puppet::Confine.test(:true)).to receive(:new).and_return(c1)
expect(Puppet::Confine.test(:false)).to receive(:new).and_return(c2)
confiner = Puppet::ConfineCollection.new("label")
confiner.confine :true => :bar, :false => :bee
expect(confiner).to be_valid
end
it "should not be valid if any confines fail" do
c1 = double('c1', :valid? => true, :label= => nil)
c2 = double('c2', :valid? => false, :label= => nil)
expect(Puppet::Confine.test(:true)).to receive(:new).and_return(c1)
expect(Puppet::Confine.test(:false)).to receive(:new).and_return(c2)
confiner = Puppet::ConfineCollection.new("label")
confiner.confine :true => :bar, :false => :bee
expect(confiner).not_to be_valid
end
describe "when providing a summary" do
before do
@confiner = Puppet::ConfineCollection.new("label")
end
it "should return a hash" do
expect(@confiner.summary).to be_instance_of(Hash)
end
it "should return an empty hash if the confiner is valid" do
expect(@confiner.summary).to eq({})
end
it "should add each test type's summary to the hash" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return(:tsumm)
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:true => :tsumm, :false => :fsumm})
end
it "should not include tests that return 0" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return(0)
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:false => :fsumm})
end
it "should not include tests that return empty arrays" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return([])
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:false => :fsumm})
end
it "should not include tests that return empty hashes" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return({})
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:false => :fsumm})
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/info_service_spec.rb | spec/unit/info_service_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/pops'
require 'puppet/info_service'
require 'puppet/pops/evaluator/literal_evaluator'
describe "Puppet::InfoService" do
include PuppetSpec::Files
context 'task information service' do
let(:mod_name) { 'test1' }
let(:metadata) {
{ "private" => true,
"description" => "a task that does a thing" } }
let(:task_name) { "#{mod_name}::thingtask" }
let(:modpath) { tmpdir('modpath') }
let(:env_name) { 'testing' }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [modpath]) }
let(:env_loader) { Puppet::Environments::Static.new(env) }
context 'tasks_per_environment method' do
it "returns task data for the tasks in an environment" do
Puppet.override(:environments => env_loader) do
PuppetSpec::Modules.create(mod_name, modpath, {:environment => env,
:tasks => [['thingtask',
{:name => 'thingtask.json',
:content => metadata.to_json}]]})
expect(Puppet::InfoService.tasks_per_environment(env_name)).to eq([{:name => task_name,
:module => {:name => mod_name},
:metadata => metadata} ])
end
end
it "returns task data for valid tasks in an environment even if invalid tasks exist" do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath, {:environment => env,
:tasks => [['atask',
{:name => 'atask.json',
:content => metadata.to_json}],
['btask',
{:name => 'btask.json',
:content => metadata.to_json}],
['ctask',
{:name => 'ctask.json',
:content => metadata.to_json}]]})
File.write("#{modpath}/#{mod_name}/tasks/atask.json", "NOT JSON")
expect(Puppet).to receive(:send_log).with(:err, /unexpected token|unexpected character|parse error/i)
@tasks = Puppet::InfoService.tasks_per_environment(env_name)
expect(@tasks.map{|t| t[:name]}).to contain_exactly('test1::btask', 'test1::ctask')
end
end
it "should throw EnvironmentNotFound if given a nonexistent environment" do
expect{ Puppet::InfoService.tasks_per_environment('utopia') }.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
context 'task_data method' do
context 'For a valid simple module' do
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask',
{:name => 'thingtask.json',
:content => '{}'}]]})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:files, :metadata])
end
it 'specifies the metadata_file correctly' do
expect(@result[:metadata]).to eq({})
end
it 'specifies the other files correctly' do
task = @mod.tasks[0]
expect(@result[:files]).to eq(task.files)
end
end
context 'For a module with multiple implemenations and files' do
let(:other_mod_name) { "shell_helpers" }
let(:metadata) {
{ "implementations" => [
{"name" => "thingtask.rb", "requirements" => ["puppet_agent"],
"files" => ["#{mod_name}/lib/puppet/providers/"]},
{"name" => "thingtask.sh", "requirements" => ["shell"] } ],
"files" => [
"#{mod_name}/files/my_data.json",
"#{other_mod_name}/files/scripts/helper.sh",
"#{mod_name}/files/data/files/data.rb"] } }
let(:expected_files) { [ {'name' => 'thingtask.rb',
'path' => "#{modpath}/#{mod_name}/tasks/thingtask.rb"},
{ 'name' => 'thingtask.sh',
'path' => "#{modpath}/#{mod_name}/tasks/thingtask.sh"},
{ 'name' => "#{mod_name}/lib/puppet/providers/prov.rb",
'path' => "#{modpath}/#{mod_name}/lib/puppet/providers/prov.rb"},
{ 'name' => "#{mod_name}/files/data/files/data.rb",
'path' => "#{modpath}/#{mod_name}/files/data/files/data.rb"},
{ 'name' => "#{mod_name}/files/my_data.json",
'path' => "#{modpath}/#{mod_name}/files/my_data.json"},
{ 'name' => "#{other_mod_name}/files/scripts/helper.sh",
'path' => "#{modpath}/#{other_mod_name}/files/scripts/helper.sh" }
].sort_by {|f| f['name']} }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.rb',
'thingtask.sh',
{:name => 'thingtask.json',
:content => metadata.to_json}]],
:files => {
"files/data/files/data.rb" => "a file of data",
"files/my_data.json" => "{}",
"lib/puppet/providers/prov.rb" => "provider_content"} })
@other_mod = PuppetSpec::Modules.create(other_mod_name, modpath, { :environment => env,
:files =>{
"files/scripts/helper.sh" => "helper content" } } )
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:files, :metadata])
end
it 'specifies the metadata_file correctly' do
expect(@result[:metadata]).to eq(metadata)
end
it 'specifies the other file names correctly' do
expect(@result[:files].sort_by{|f| f['name']}).to eq(expected_files)
end
end
context 'For a task with files that do not exist' do
let(:metadata) {
{ "files" => [
"#{mod_name}/files/random_data",
"shell_helpers/files/scripts/helper.sh"] } }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.rb',
{:name => 'thingtask.json',
:content => metadata.to_json}]]})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'errors when the file is not found' do
expect(@result[:error][:kind]).to eq('puppet.tasks/invalid-file')
end
end
context 'For a task with bad metadata' do
let(:metadata) {
{ "implementations" => [
{"name" => "thingtask.rb", "requirements" => ["puppet_agent"] },
{"name" => "thingtask.sh", "requirements" => ["shell"] } ] } }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.sh',
{:name => 'thingtask.json',
:content => metadata.to_json}]]})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:error, :files, :metadata])
end
it 'returns the expected error' do
expect(@result[:error][:kind]).to eq('puppet.tasks/missing-implementation')
end
end
context 'For a task with required directories with no trailing slash' do
let(:metadata) { { "files" => [ "#{mod_name}/files" ] } }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.sh',
{:name => 'thingtask.json',
:content => metadata.to_json}]],
:files => {
"files/helper.rb" => "help"}})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:error, :files, :metadata])
end
it 'returns the expected error' do
expect(@result[:error][:kind]).to eq('puppet.tasks/invalid-metadata')
end
end
it "should raise EnvironmentNotFound if given a nonexistent environment" do
expect{ Puppet::InfoService.task_data('utopia', mod_name, task_name) }.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
it "should raise MissingModule if the module does not exist" do
Puppet.override(:environments => env_loader) do
expect { Puppet::InfoService.task_data(env_name, 'notamodule', 'notamodule::thingtask') }
.to raise_error(Puppet::Module::MissingModule)
end
end
it "should raise TaskNotFound if the task does not exist" do
Puppet.override(:environments => env_loader) do
PuppetSpec::Modules.create(mod_name, modpath)
expect { Puppet::InfoService.task_data(env_name, mod_name, 'testing1::notatask') }
.to raise_error(Puppet::Module::Task::TaskNotFound)
end
end
end
end
context 'plan information service' do
let(:mod_name) { 'test1' }
let(:plan_name) { "#{mod_name}::thingplan" }
let(:modpath) { tmpdir('modpath') }
let(:env_name) { 'testing' }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [modpath]) }
let(:env_loader) { Puppet::Environments::Static.new(env) }
context 'plans_per_environment method' do
it "returns plan data for the plans in an environment" do
Puppet.override(:environments => env_loader) do
PuppetSpec::Modules.create(mod_name, modpath, {:environment => env, :plans => ['thingplan.pp']})
expect(Puppet::InfoService.plans_per_environment(env_name)).to eq([{:name => plan_name, :module => {:name => mod_name}}])
end
end
it "should throw EnvironmentNotFound if given a nonexistent environment" do
expect{ Puppet::InfoService.plans_per_environment('utopia') }.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
context 'plan_data method' do
context 'For a valid simple module' do
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:plans => ['thingplan.pp']})
@result = Puppet::InfoService.plan_data(env_name, mod_name, plan_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:files, :metadata])
end
it 'specifies the metadata_file correctly' do
expect(@result[:metadata]).to eq({})
end
it 'specifies the other files correctly' do
plan = @mod.plans[0]
expect(@result[:files]).to eq(plan.files)
end
end
end
end
context 'classes_per_environment service' do
let(:code_dir) do
dir_containing('manifests', {
'foo.pp' => <<-CODE,
class foo($foo_a, Integer $foo_b, String $foo_c = 'c default value') { }
class foo2($foo2_a, Integer $foo2_b, String $foo2_c = 'c default value') { }
CODE
'bar.pp' => <<-CODE,
class bar($bar_a, Integer $bar_b, String $bar_c = 'c default value') { }
class bar2($bar2_a, Integer $bar2_b, String $bar2_c = 'c default value') { }
CODE
'intp.pp' => <<-CODE,
class intp(String $intp_a = "default with interpolated $::os_family") { }
CODE
'fee.pp' => <<-CODE,
class fee(Integer $fee_a = 1+1) { }
CODE
'fum.pp' => <<-CODE,
class fum($fum_a) { }
CODE
'nothing.pp' => <<-CODE,
# not much to see here, move along
CODE
'borked.pp' => <<-CODE,
class Borked($Herp+$Derp) {}
CODE
'json_unsafe.pp' => <<-CODE,
class json_unsafe($arg1 = /.*/, $arg2 = default, $arg3 = {1 => 1}) {}
CODE
'non_literal.pp' => <<-CODE,
class oops(Integer[1-3] $bad_int) { }
CODE
'non_literal_2.pp' => <<-CODE,
class oops_2(Optional[[String]] $double_brackets) { }
CODE
})
end
it "errors if not given a hash" do
expect{ Puppet::InfoService.classes_per_environment("you wassup?")}.to raise_error(ArgumentError, 'Given argument must be a Hash')
end
it "returns empty hash if given nothing" do
expect(Puppet::InfoService.classes_per_environment({})).to eq({})
end
it "produces classes and parameters from a given file" do
files = ['foo.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/foo.pp"=> {:classes => [
{:name=>"foo",
:params=>[
{:name=>"foo_a"},
{:name=>"foo_b", :type=>"Integer"},
{:name=>"foo_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"foo2",
:params=>[
{:name=>"foo2_a"},
{:name=>"foo2_b", :type=>"Integer"},
{:name=>"foo2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]}} # end production env
})
end
it "produces classes and parameters from multiple files in same environment" do
files = ['foo.pp', 'bar.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/foo.pp"=>{:classes => [
{:name=>"foo",
:params=>[
{:name=>"foo_a"},
{:name=>"foo_b", :type=>"Integer"},
{:name=>"foo_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"foo2",
:params=>[
{:name=>"foo2_a"},
{:name=>"foo2_b", :type=>"Integer"},
{:name=>"foo2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
"#{code_dir}/bar.pp"=> {:classes =>[
{:name=>"bar",
:params=>[
{:name=>"bar_a"},
{:name=>"bar_b", :type=>"Integer"},
{:name=>"bar_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"bar2",
:params=>[
{:name=>"bar2_a"},
{:name=>"bar2_b", :type=>"Integer"},
{:name=>"bar2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
} # end production env
}
)
end
it "produces classes and parameters from multiple files in multiple environments" do
files_production = ['foo.pp', 'bar.pp'].map {|f| File.join(code_dir, f) }
files_test = ['fee.pp', 'fum.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({
'production' => files_production,
'test' => files_test
})
expect(result).to eq({
"production"=>{
"#{code_dir}/foo.pp"=>{:classes => [
{:name=>"foo",
:params=>[
{:name=>"foo_a"},
{:name=>"foo_b", :type=>"Integer"},
{:name=>"foo_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"foo2",
:params=>[
{:name=>"foo2_a"},
{:name=>"foo2_b", :type=>"Integer"},
{:name=>"foo2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
"#{code_dir}/bar.pp"=>{:classes => [
{:name=>"bar",
:params=>[
{:name=>"bar_a"},
{:name=>"bar_b", :type=>"Integer"},
{:name=>"bar_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"bar2",
:params=>[
{:name=>"bar2_a"},
{:name=>"bar2_b", :type=>"Integer"},
{:name=>"bar2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
}, # end production env
"test"=>{
"#{code_dir}/fee.pp"=>{:classes => [
{:name=>"fee",
:params=>[
{:name=>"fee_a", :type=>"Integer", :default_source=>"1+1"}
]},
]},
"#{code_dir}/fum.pp"=>{:classes => [
{:name=>"fum",
:params=>[
{:name=>"fum_a"}
]},
]},
} # end test env
}
)
end
it "avoids parsing file more than once when environments have same feature flag set" do
# in this version of puppet, all environments are equal in this respect
result = Puppet::Pops::Parser::EvaluatingParser.new.parse_file("#{code_dir}/fum.pp")
expect_any_instance_of(Puppet::Pops::Parser::EvaluatingParser).to receive(:parse_file).with("#{code_dir}/fum.pp").once.and_return(result)
files_production = ['fum.pp'].map {|f| File.join(code_dir, f) }
files_test = files_production
result = Puppet::InfoService.classes_per_environment({
'production' => files_production,
'test' => files_test
})
expect(result).to eq({
"production"=>{ "#{code_dir}/fum.pp"=>{:classes => [ {:name=>"fum", :params=>[ {:name=>"fum_a"}]}]}},
"test" =>{ "#{code_dir}/fum.pp"=>{:classes => [ {:name=>"fum", :params=>[ {:name=>"fum_a"}]}]}}
}
)
end
it "produces expression string if a default value is not literal" do
files = ['fee.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/fee.pp"=>{:classes => [
{:name=>"fee",
:params=>[
{:name=>"fee_a", :type=>"Integer", :default_source=>"1+1"}
]},
]}} # end production env
})
end
it "produces source string for literals that are not pure json" do
files = ['json_unsafe.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/json_unsafe.pp" => {:classes => [
{:name=>"json_unsafe",
:params => [
{:name => "arg1",
:default_source => "/.*/" },
{:name => "arg2",
:default_source => "default" },
{:name => "arg3",
:default_source => "{1 => 1}" }
]}
]}} # end production env
})
end
it "errors with a descriptive message if non-literal class parameter is given" do
files = ['non_literal.pp', 'non_literal_2.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(@logs).to have_matching_log_with_source(/The parameter '\$bad_int' must be a literal type, not a Puppet::Pops::Model::AccessExpression/, "#{code_dir}/non_literal.pp", 1, 37)
expect(@logs).to have_matching_log_with_source(/The parameter '\$double_brackets' must be a literal type, not a Puppet::Pops::Model::AccessExpression/, "#{code_dir}/non_literal_2.pp", 1, 44)
expect(result).to eq({
"production"=>{
"#{code_dir}/non_literal.pp" =>
{:error=> "The parameter '\$bad_int' is invalid: The expression <1-3> is not a valid type specification."},
"#{code_dir}/non_literal_2.pp" =>
{:error=> "The parameter '\$double_brackets' is invalid: The expression <Optional[[String]]> is not a valid type specification."}
} # end production env
})
end
it "produces no type entry if type is not given" do
files = ['fum.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/fum.pp"=>{:classes => [
{:name=>"fum",
:params=>[
{:name=>"fum_a" }
]},
]}} # end production env
})
end
it 'does not evaluate default expressions' do
files = ['intp.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
'production' =>{
"#{code_dir}/intp.pp"=>{:classes => [
{:name=> 'intp',
:params=>[
{:name=> 'intp_a',
:type=> 'String',
:default_source=>'"default with interpolated $::os_family"'}
]},
]}} # end production env
})
end
it "produces error entry if file is broken" do
files = ['borked.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/borked.pp"=>
{:error=>"Syntax error at '+' (file: #{code_dir}/borked.pp, line: 1, column: 30)",
},
} # end production env
})
end
it "produces empty {} if parsed result has no classes" do
files = ['nothing.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/nothing.pp"=> {:classes => [] }
},
})
end
it "produces error when given a file that does not exist" do
files = ['the_tooth_fairy_does_not_exist.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/the_tooth_fairy_does_not_exist.pp" => {:error => "The file #{code_dir}/the_tooth_fairy_does_not_exist.pp does not exist"}
},
})
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/version_spec.rb | spec/unit/version_spec.rb | require "spec_helper"
require "puppet/version"
require 'pathname'
describe "Puppet.version Public API" do
before :each do
@current_ver = Puppet.version
Puppet.instance_eval do
if @puppet_version
@puppet_version = nil
end
end
end
after :each do
Puppet.version = @current_ver
end
context "without a VERSION file" do
before :each do
allow(Puppet).to receive(:read_version_file).and_return(nil)
end
it "is Puppet::PUPPETVERSION" do
expect(Puppet.version).to eq(Puppet::PUPPETVERSION)
end
it "respects the version= setter" do
Puppet.version = '1.2.3'
expect(Puppet.version).to eq('1.2.3')
expect(Puppet.minor_version).to eq('1.2')
end
end
context "with a VERSION file" do
it "is the content of the file" do
expect(Puppet).to receive(:read_version_file) do |path|
pathname = Pathname.new(path)
pathname.basename.to_s == "VERSION"
end.and_return('3.0.1-260-g9ca4e54')
expect(Puppet.version).to eq('3.0.1-260-g9ca4e54')
expect(Puppet.minor_version).to eq('3.0')
end
it "respects the version= setter" do
Puppet.version = '1.2.3'
expect(Puppet.version).to eq('1.2.3')
expect(Puppet.minor_version).to eq('1.2')
end
end
context "Using version setter" do
it "does not read VERSION file if using set version" do
expect(Puppet).not_to receive(:read_version_file)
Puppet.version = '1.2.3'
expect(Puppet.version).to eq('1.2.3')
expect(Puppet.minor_version).to eq('1.2')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/certificate_factory_spec.rb | spec/unit/certificate_factory_spec.rb | require 'spec_helper'
require 'puppet/test_ca'
require 'puppet/certificate_factory'
describe Puppet::CertificateFactory, :unless => RUBY_PLATFORM == 'java' do
let :serial do OpenSSL::BN.new('12') end
let :name do "example.local" end
let :x509_name do OpenSSL::X509::Name.new([['CN', name]]) end
let :key do OpenSSL::PKey::RSA.new(Puppet[:keylength]) end
let :csr do
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key)
csr
end
let(:issuer) { Puppet::TestCa.new.ca_cert }
describe "when generating the certificate" do
it "should return a new X509 certificate" do
a = subject.build(:server, csr, issuer, serial)
b = subject.build(:server, csr, issuer, serial)
# The two instances are equal in every aspect except that they are
# different instances - they are `==`, but not hash `eql?`
expect(a).not_to eql(b)
end
it "should set the certificate's version to 2" do
expect(subject.build(:server, csr, issuer, serial).version).to eq(2)
end
it "should set the certificate's subject to the CSR's subject" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.subject).to eq x509_name
end
it "should set the certificate's issuer to the Issuer's subject" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.issuer).to eq issuer.subject
end
it "should set the certificate's public key to the CSR's public key" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.public_key).to be_public
expect(cert.public_key.to_s).to eq(csr.content.public_key.to_s)
end
it "should set the certificate's serial number to the provided serial number" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.serial).to eq(serial)
end
it "should have 24 hours grace on the start of the cert" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.not_before).to be_within(30).of(Time.now - 24*60*60)
end
it "should not allow a non-integer TTL" do
[ 'foo', 1.2, Time.now, true ].each do |ttl|
expect { subject.build(:server, csr, issuer, serial, ttl) }.to raise_error(ArgumentError)
end
end
it "should respect a custom TTL for the CA" do
now = Time.now.utc
expect(Time).to receive(:now).at_least(:once).and_return(now)
cert = subject.build(:server, csr, issuer, serial, 12)
expect(cert.not_after.to_i).to eq(now.to_i + 12)
end
it "should adds an extension for the nsComment" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.extensions.map {|x| x.to_h }.find {|x| x["oid"] == "nsComment" }).to eq(
{ "oid" => "nsComment",
# Note that this output is due to a bug in OpenSSL::X509::Extensions
# where the values of some extensions are not properly decoded
"value" => ".(Puppet Ruby/OpenSSL Internal Certificate",
"critical" => false }
)
end
it "should add an extension for the subjectKeyIdentifer" do
cert = subject.build(:server, csr, issuer, serial)
ef = OpenSSL::X509::ExtensionFactory.new(issuer, cert)
expect(cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "subjectKeyIdentifier" }).to eq(
ef.create_extension("subjectKeyIdentifier", "hash", false).to_h
)
end
it "should add an extension for the authorityKeyIdentifer" do
cert = subject.build(:server, csr, issuer, serial)
ef = OpenSSL::X509::ExtensionFactory.new(issuer, cert)
expect(cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "authorityKeyIdentifier" }).to eq(
ef.create_extension("authorityKeyIdentifier", "keyid:always", false).to_h
)
end
# See #2848 for why we are doing this: we need to make sure that
# subjectAltName is set if the CSR has it, but *not* if it is set when the
# certificate is built!
it "should not add subjectAltNames from dns_alt_names" do
Puppet[:dns_alt_names] = 'one, two'
# Verify the CSR still has no extReq, just in case...
expect(csr.request_extensions).to eq([])
cert = subject.build(:server, csr, issuer, serial)
expect(cert.extensions.find {|x| x.oid == 'subjectAltName' }).to be_nil
end
it "should add subjectAltName when the CSR requests them" do
Puppet[:dns_alt_names] = ''
expect = %w{one two} + [name]
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key, :dns_alt_names => expect.join(', '))
expect(csr.request_extensions).not_to be_nil
expect(csr.subject_alt_names).to match_array(expect.map{|x| "DNS:#{x}"})
cert = subject.build(:server, csr, issuer, serial)
san = cert.extensions.find {|x| x.oid == 'subjectAltName' }
expect(san).not_to be_nil
expect.each do |name|
expect(san.value).to match(/DNS:#{name}\b/i)
end
end
it "can add custom extension requests" do
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key)
allow(csr).to receive(:request_extensions).and_return([
{'oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'some-value'},
{'oid' => 'pp_uuid', 'value' => 'some-uuid'},
])
cert = subject.build(:client, csr, issuer, serial)
# The cert must be signed before being later DER-decoding
signer = Puppet::SSL::CertificateSigner.new
signer.sign(cert, key)
wrapped_cert = Puppet::SSL::Certificate.from_instance cert
priv_ext = wrapped_cert.custom_extensions.find {|ext| ext['oid'] == '1.3.6.1.4.1.34380.1.2.1'}
uuid_ext = wrapped_cert.custom_extensions.find {|ext| ext['oid'] == 'pp_uuid'}
# The expected results should be DER encoded, the Puppet cert wrapper will turn
# these into normal strings.
expect(priv_ext['value']).to eq 'some-value'
expect(uuid_ext['value']).to eq 'some-uuid'
end
# Can't check the CA here, since that requires way more infrastructure
# that I want to build up at this time. We can verify the critical
# values, though, which are non-CA certs. --daniel 2011-10-11
{ :ca => 'CA:TRUE',
:terminalsubca => ['CA:TRUE', 'pathlen:0'],
:server => 'CA:FALSE',
:ocsp => 'CA:FALSE',
:client => 'CA:FALSE',
}.each do |name, value|
it "should set basicConstraints for #{name} #{value.inspect}" do
cert = subject.build(name, csr, issuer, serial)
bc = cert.extensions.find {|x| x.oid == 'basicConstraints' }
expect(bc).to be
expect(bc.value.split(/\s*,\s*/)).to match_array(Array(value))
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/relationship_spec.rb | spec/unit/relationship_spec.rb | require 'spec_helper'
require 'puppet/relationship'
describe Puppet::Relationship do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should have a :source attribute" do
expect(@edge).to respond_to(:source)
end
it "should have a :target attribute" do
expect(@edge).to respond_to(:target)
end
it "should have a :callback attribute" do
@edge.callback = :foo
expect(@edge.callback).to eq(:foo)
end
it "should have an :event attribute" do
@edge.event = :NONE
expect(@edge.event).to eq(:NONE)
end
it "should require a callback if a non-NONE event is specified" do
expect { @edge.event = :something }.to raise_error(ArgumentError)
end
it "should have a :label attribute" do
expect(@edge).to respond_to(:label)
end
it "should provide a :ref method that describes the edge" do
@edge = Puppet::Relationship.new("a", "b")
expect(@edge.ref).to eq("a => b")
end
it "should be able to produce a label as a hash with its event and callback" do
@edge.callback = :foo
@edge.event = :bar
expect(@edge.label).to eq({:callback => :foo, :event => :bar})
end
it "should work if nil options are provided" do
expect { Puppet::Relationship.new("a", "b", nil) }.not_to raise_error
end
end
describe Puppet::Relationship, " when initializing" do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should use the first argument as the source" do
expect(@edge.source).to eq(:a)
end
it "should use the second argument as the target" do
expect(@edge.target).to eq(:b)
end
it "should set the rest of the arguments as the event and callback" do
@edge = Puppet::Relationship.new(:a, :b, :callback => :foo, :event => :bar)
expect(@edge.callback).to eq(:foo)
expect(@edge.event).to eq(:bar)
end
it "should accept events specified as strings" do
@edge = Puppet::Relationship.new(:a, :b, "event" => :NONE)
expect(@edge.event).to eq(:NONE)
end
it "should accept callbacks specified as strings" do
@edge = Puppet::Relationship.new(:a, :b, "callback" => :foo)
expect(@edge.callback).to eq(:foo)
end
end
describe Puppet::Relationship, " when matching edges with no specified event" do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should not match any other events" do
expect(@edge).not_to be_match(:whatever)
end
end
describe Puppet::Relationship, " when matching edges with :NONE as the event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :NONE)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should not match other events" do
expect(@edge).not_to be_match(:yayness)
end
end
describe Puppet::Relationship, " when matching edges with :ALL as the event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :ALL_EVENTS, :callback => :whatever)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should match :ALL_EVENTS" do
expect(@edge).to be_match(:ALL_EVENTS)
end
it "should match all other events" do
expect(@edge).to be_match(:foo)
end
end
describe Puppet::Relationship, " when matching edges with a non-standard event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :random, :callback => :whatever)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should match events with the same name" do
expect(@edge).to be_match(:random)
end
end
describe Puppet::Relationship, "when converting to json" do
before do
@edge = Puppet::Relationship.new('a', 'b', :event => :random, :callback => :whatever)
end
it "should store the stringified source as the source in the data" do
expect(JSON.parse(@edge.to_json)["source"]).to eq("a")
end
it "should store the stringified target as the target in the data" do
expect(JSON.parse(@edge.to_json)['target']).to eq("b")
end
it "should store the jsonified event as the event in the data" do
expect(JSON.parse(@edge.to_json)["event"]).to eq("random")
end
it "should not store an event when none is set" do
@edge.event = nil
expect(JSON.parse(@edge.to_json)).not_to include('event')
end
it "should store the jsonified callback as the callback in the data" do
@edge.callback = "whatever"
expect(JSON.parse(@edge.to_json)["callback"]).to eq("whatever")
end
it "should not store a callback when none is set in the edge" do
@edge.callback = nil
expect(JSON.parse(@edge.to_json)).not_to include('callback')
end
end
describe Puppet::Relationship, "when converting from json" do
it "should pass the source in as the first argument" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").source).to eq('mysource')
end
it "should pass the target in as the second argument" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").target).to eq('mytarget')
end
it "should pass the event as an argument if it's provided" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "event" => "myevent", "callback" => "eh").event).to eq(:myevent)
end
it "should pass the callback as an argument if it's provided" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "callback" => "mycallback").callback).to eq(:mycallback)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confiner_spec.rb | spec/unit/confiner_spec.rb | require 'spec_helper'
require 'puppet/confiner'
describe Puppet::Confiner do
let(:coll) { Puppet::ConfineCollection.new('') }
before do
@object = Object.new
@object.extend(Puppet::Confiner)
end
it "should have a method for defining confines" do
expect(@object).to respond_to(:confine)
end
it "should have a method for returning its confine collection" do
expect(@object).to respond_to(:confine_collection)
end
it "should have a method for testing suitability" do
expect(@object).to respond_to(:suitable?)
end
it "should delegate its confine method to its confine collection" do
allow(@object).to receive(:confine_collection).and_return(coll)
expect(coll).to receive(:confine).with({:foo => :bar, :bee => :baz})
@object.confine(:foo => :bar, :bee => :baz)
end
it "should create a new confine collection if one does not exist" do
expect(Puppet::ConfineCollection).to receive(:new).with("mylabel").and_return("mycoll")
expect(@object).to receive(:to_s).and_return("mylabel")
expect(@object.confine_collection).to eq("mycoll")
end
it "should reuse the confine collection" do
expect(@object.confine_collection).to equal(@object.confine_collection)
end
describe "when testing suitability" do
before do
allow(@object).to receive(:confine_collection).and_return(coll)
end
it "should return true if the confine collection is valid" do
expect(coll).to receive(:valid?).and_return(true)
expect(@object).to be_suitable
end
it "should return false if the confine collection is invalid" do
expect(coll).to receive(:valid?).and_return(false)
expect(@object).not_to be_suitable
end
it "should return the summary of the confine collection if a long result is asked for" do
expect(coll).to receive(:summary).and_return("myresult")
expect(@object.suitable?(false)).to eq("myresult")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/interface_spec.rb | spec/unit/interface_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/interface'
describe Puppet::Interface do
subject { Puppet::Interface }
before :each do
@faces = Puppet::Interface::FaceCollection.
instance_variable_get("@faces").dup
@dq = $".dup
$".delete_if do |path| path =~ %r{/face/.*\.rb$} end
Puppet::Interface::FaceCollection.instance_variable_get("@faces").clear
end
after :each do
Puppet::Interface::FaceCollection.instance_variable_set("@faces", @faces)
$".clear ; @dq.each do |item| $" << item end
end
describe "#[]" do
it "should fail when no version is requested" do
expect { subject[:huzzah] }.to raise_error ArgumentError
end
it "should raise an exception when the requested version is unavailable" do
expect { subject[:huzzah, '17.0.0'] }.to raise_error(Puppet::Error, /Could not find version/)
end
it "should raise an exception when the requested face doesn't exist" do
expect { subject[:burrble_toot, :current] }.to raise_error(Puppet::Error, /Could not find Puppet Face/)
end
describe "version matching" do
{ '1' => '1.1.1',
'1.0' => '1.0.1',
'1.0.1' => '1.0.1',
'1.1' => '1.1.1',
'1.1.1' => '1.1.1'
}.each do |input, expect|
it "should match #{input.inspect} to #{expect.inspect}" do
face = subject[:version_matching, input]
expect(face).to be
expect(face.version).to eq(expect)
end
end
%w{1.0.2 1.2}.each do |input|
it "should not match #{input.inspect} to any version" do
expect { subject[:version_matching, input] }.
to raise_error Puppet::Error, /Could not find version/
end
end
end
end
describe "#define" do
it "should register the face" do
face = subject.define(:face_test_register, '0.0.1')
expect(face).to eq(subject[:face_test_register, '0.0.1'])
end
it "should load actions" do
expect_any_instance_of(subject).to receive(:load_actions)
subject.define(:face_test_load_actions, '0.0.1')
end
it "should require a version number" do
expect { subject.define(:no_version) }.to raise_error ArgumentError
end
it "should support summary builder and accessor methods" do
expect(subject.new(:foo, '1.0.0')).to respond_to(:summary).with(0).arguments
expect(subject.new(:foo, '1.0.0')).to respond_to(:summary=).with(1).arguments
end
# Required documentation methods...
{ :summary => "summary",
:description => "This is the description of the stuff\n\nWhee",
:examples => "This is my example",
:short_description => "This is my custom short description",
:notes => "These are my notes...",
:author => "This is my authorship data",
}.each do |attr, value|
it "should support #{attr} in the builder" do
face = subject.new(:builder, '1.0.0') do
self.send(attr, value)
end
expect(face.send(attr)).to eq(value)
end
end
end
describe "#initialize" do
it "should require a version number" do
expect { subject.new(:no_version) }.to raise_error ArgumentError
end
it "should require a valid version number" do
expect { subject.new(:bad_version, 'Rasins') }.
to raise_error ArgumentError
end
it "should instance-eval any provided block" do
face = subject.new(:face_test_block, '0.0.1') do
action(:something) do
when_invoked {|_| "foo" }
end
end
expect(face.something).to eq("foo")
end
end
it "should have a name" do
expect(subject.new(:me, '0.0.1').name).to eq(:me)
end
it "should stringify with its own name" do
expect(subject.new(:me, '0.0.1').to_s).to match(/\bme\b/)
end
it "should try to require faces that are not known" do
expect(subject::FaceCollection).to receive(:load_face).with(:foo, :current)
expect(subject::FaceCollection).to receive(:load_face).with(:foo, '0.0.1')
expect { subject[:foo, '0.0.1'] }.to raise_error Puppet::Error
end
describe 'when raising NoMethodErrors' do
subject { described_class.new(:foo, '1.0.0') }
if RUBY_VERSION.to_f >= 3.3
it 'includes the face name in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /for an instance of Puppet::Interface/)
end
it 'includes the face version in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /for an instance of Puppet::Interface/)
end
else
it 'includes the face name in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /#{subject.name}/)
end
it 'includes the face version in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /#{subject.version}/)
end
end
end
it_should_behave_like "things that declare options" do
def add_options_to(&block)
subject.new(:with_options, '0.0.1', &block)
end
end
context "when deprecating a face" do
let(:face) { subject.new(:foo, '0.0.1') }
describe "#deprecate" do
it "should respond to #deprecate" do
expect(subject.new(:foo, '0.0.1')).to respond_to(:deprecate)
end
it "should set the deprecated value to true" do
expect(face.deprecated?).to be_falsey
face.deprecate
expect(face.deprecated?).to be_truthy
end
end
describe "#deprecated?" do
it "should return a nil (falsey) value by default" do
expect(face.deprecated?).to be_falsey
end
it "should return true if the face has been deprecated" do
expect(face.deprecated?).to be_falsey
face.deprecate
expect(face.deprecated?).to be_truthy
end
end
end
describe "with face-level display_global_options" do
it "should not return any action level display_global_options" do
face = subject.new(:with_display_global_options, '0.0.1') do
display_global_options "environment"
action :baz do
when_invoked {|_| true }
display_global_options "modulepath"
end
end
expect(face.display_global_options).to match(["environment"])
end
it "should not fail when a face d_g_o duplicates an action d_g_o" do
expect {
subject.new(:action_level_display_global_options, '0.0.1') do
action :bar do
when_invoked {|_| true }
display_global_options "environment"
end
display_global_options "environment"
end
}.to_not raise_error
end
it "should work when two actions have the same d_g_o" do
face = subject.new(:with_display_global_options, '0.0.1') do
action :foo do when_invoked {|_| true} ; display_global_options "environment" end
action :bar do when_invoked {|_| true} ; display_global_options "environment" end
end
expect(face.get_action(:foo).display_global_options).to match(["environment"])
expect(face.get_action(:bar).display_global_options).to match(["environment"])
end
end
describe "with inherited display_global_options" do
end
describe "with face-level options" do
it "should not return any action-level options" do
face = subject.new(:with_options, '0.0.1') do
option "--foo"
option "--bar"
action :baz do
when_invoked {|_| true }
option "--quux"
end
end
expect(face.options).to match_array([:foo, :bar])
end
it "should fail when a face option duplicates an action option" do
expect {
subject.new(:action_level_options, '0.0.1') do
action :bar do
when_invoked {|_| true }
option "--foo"
end
option "--foo"
end
}.to raise_error ArgumentError, /Option foo conflicts with existing option foo on/i
end
it "should work when two actions have the same option" do
face = subject.new(:with_options, '0.0.1') do
action :foo do when_invoked {|_| true } ; option "--quux" end
action :bar do when_invoked {|_| true } ; option "--quux" end
end
expect(face.get_action(:foo).options).to match_array([:quux])
expect(face.get_action(:bar).options).to match_array([:quux])
end
it "should only list options and not aliases" do
face = subject.new(:face_options, '0.0.1') do
option "--bar", "-b", "--foo-bar"
end
expect(face.options).to match_array([:bar])
end
end
describe "with inherited options" do
let :parent do
parent = Class.new(subject)
parent.option("--inherited")
parent.action(:parent_action) do when_invoked {|_| true } end
parent
end
let :face do
face = parent.new(:example, '0.2.1')
face.option("--local")
face.action(:face_action) do when_invoked {|_| true } end
face
end
describe "#options" do
it "should list inherited options" do
expect(face.options).to match_array([:inherited, :local])
end
it "should see all options on face actions" do
expect(face.get_action(:face_action).options).to match_array([:inherited, :local])
end
it "should see all options on inherited actions accessed on the subclass" do
expect(face.get_action(:parent_action).options).to match_array([:inherited, :local])
end
it "should not see subclass actions on the parent class" do
expect(parent.options).to match_array([:inherited])
end
it "should not see subclass actions on actions accessed on the parent class" do
expect(parent.get_action(:parent_action).options).to match_array([:inherited])
end
end
describe "#get_option" do
it "should return an inherited option object" do
expect(face.get_option(:inherited)).to be_an_instance_of subject::Option
end
end
end
it_should_behave_like "documentation on faces" do
subject do
Puppet::Interface.new(:face_documentation, '0.0.1')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider_spec.rb | spec/unit/provider_spec.rb | require 'spec_helper'
def existing_command
Puppet::Util::Platform.windows? ? "cmd" : "echo"
end
describe Puppet::Provider do
before :each do
Puppet::Type.newtype(:test) do
newparam(:name) { isnamevar }
end
end
after :each do
Puppet::Type.type(:test).provider_hash.clear
Puppet::Type.rmtype(:test)
end
let :type do Puppet::Type.type(:test) end
let :provider do type.provide(:default) {} end
subject { provider }
describe "has command" do
it "installs a method to run the command specified by the path" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
allow_creation_of(echo_command)
provider = provider_of do
has_command(:echo, "/bin/echo")
end
provider.echo("an argument")
end
it "installs a command that is run with a given environment" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
allow_creation_of(echo_command, {
:EV => "value",
:OTHER => "different"
})
provider = provider_of do
has_command(:echo, "/bin/echo") do
environment :EV => "value", :OTHER => "different"
end
end
provider.echo("an argument")
end
it "is required by default" do
provider = provider_of do
has_command(:does_not_exist, "/does/not/exist")
end
expect(provider).not_to be_suitable
end
it "is required by default" do
provider = provider_of do
has_command(:does_exist, File.expand_path("/exists/somewhere"))
end
file_exists_and_is_executable(File.expand_path("/exists/somewhere"))
expect(provider).to be_suitable
end
it "can be specified as optional" do
provider = provider_of do
has_command(:does_not_exist, "/does/not/exist") do
is_optional
end
end
expect(provider).to be_suitable
end
end
describe "has required commands" do
it "installs methods to run executables by path" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
ls_command = expect_command_executed(:ls, "/bin/ls")
allow_creation_of(echo_command)
allow_creation_of(ls_command)
provider = provider_of do
commands :echo => "/bin/echo", :ls => "/bin/ls"
end
provider.echo("an argument")
provider.ls
end
it "allows the provider to be suitable if the executable is present" do
provider = provider_of do
commands :always_exists => File.expand_path("/this/command/exists")
end
file_exists_and_is_executable(File.expand_path("/this/command/exists"))
expect(provider).to be_suitable
end
it "does not allow the provider to be suitable if the executable is not present" do
provider = provider_of do
commands :does_not_exist => "/this/command/does/not/exist"
end
expect(provider).not_to be_suitable
end
end
describe "has optional commands" do
it "installs methods to run executables" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
ls_command = expect_command_executed(:ls, "/bin/ls")
allow_creation_of(echo_command)
allow_creation_of(ls_command)
provider = provider_of do
optional_commands :echo => "/bin/echo", :ls => "/bin/ls"
end
provider.echo("an argument")
provider.ls
end
it "allows the provider to be suitable even if the executable is not present" do
provider = provider_of do
optional_commands :does_not_exist => "/this/command/does/not/exist"
end
expect(provider).to be_suitable
end
end
it "should have a specifity class method" do
expect(Puppet::Provider).to respond_to(:specificity)
end
it "should be Comparable" do
res = Puppet::Type.type(:notify).new(:name => "res")
# Normally I wouldn't like the stubs, but the only way to name a class
# otherwise is to assign it to a constant, and that hurts more here in
# testing world. --daniel 2012-01-29
a = Class.new(Puppet::Provider).new(res)
allow(a.class).to receive(:name).and_return("Puppet::Provider::Notify::A")
b = Class.new(Puppet::Provider).new(res)
allow(b.class).to receive(:name).and_return("Puppet::Provider::Notify::B")
c = Class.new(Puppet::Provider).new(res)
allow(c.class).to receive(:name).and_return("Puppet::Provider::Notify::C")
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].each do |this|
expect(this.sort).to eq([a, b, c])
end
expect(a).to be < b
expect(a).to be < c
expect(b).to be > a
expect(b).to be < c
expect(c).to be > a
expect(c).to be > b
[a, b, c].each {|x| expect(a).to be <= x }
[a, b, c].each {|x| expect(c).to be >= x }
expect(b).to be_between(a, c)
end
context "when creating instances" do
context "with a resource" do
let :resource do type.new(:name => "fred") end
subject { provider.new(resource) }
it "should set the resource correctly" do
expect(subject.resource).to equal resource
end
it "should set the name from the resource" do
expect(subject.name).to eq(resource.name)
end
end
context "with a hash" do
subject { provider.new(:name => "fred") }
it "should set the name" do
expect(subject.name).to eq("fred")
end
it "should not have a resource" do expect(subject.resource).to be_nil end
end
context "with no arguments" do
subject { provider.new }
it "should raise an internal error if asked for the name" do
expect { subject.name }.to raise_error Puppet::DevError
end
it "should not have a resource" do expect(subject.resource).to be_nil end
end
end
context "when confining" do
it "should be suitable by default" do
expect(subject).to be_suitable
end
it "should not be default by default" do
expect(subject).not_to be_default
end
{ { :true => true } => true,
{ :true => false } => false,
{ :false => false } => true,
{ :false => true } => false,
{ 'os.name' => Puppet.runtime[:facter].value('os.name') } => true,
{ 'os.name' => :yayness } => false,
{ :nothing => :yayness } => false,
{ :exists => Puppet::Util.which(existing_command) } => true,
{ :exists => "/this/file/does/not/exist" } => false,
{ :true => true, :exists => Puppet::Util.which(existing_command) } => true,
{ :true => true, :exists => "/this/file/does/not/exist" } => false,
{ 'os.name' => Puppet.runtime[:facter].value('os.name'),
:exists => Puppet::Util.which(existing_command) } => true,
{ 'os.name' => :yayness,
:exists => Puppet::Util.which(existing_command) } => false,
{ 'os.name' => Puppet.runtime[:facter].value('os.name'),
:exists => "/this/file/does/not/exist" } => false,
{ 'os.name' => :yayness,
:exists => "/this/file/does/not/exist" } => false,
}.each do |confines, result|
it "should confine #{confines.inspect} to #{result}" do
confines.each {|test, value| subject.confine test => value }
if result
expect(subject).to be_suitable
else
expect(subject).to_not be_suitable
end
end
end
it "should not override a confine even if a second has the same type" do
subject.confine :true => false
expect(subject).not_to be_suitable
subject.confine :true => true
expect(subject).not_to be_suitable
end
it "should not be suitable if any confine fails" do
subject.confine :true => false
expect(subject).not_to be_suitable
10.times do
subject.confine :true => true
expect(subject).not_to be_suitable
end
end
end
context "default providers" do
let :os do Puppet.runtime[:facter].value('os.name') end
it { is_expected.to respond_to :specificity }
it "should find the default provider" do
type.provide(:nondefault) {}
subject.defaultfor 'os.name' => os
expect(subject.name).to eq(type.defaultprovider.name)
end
describe "regex matches" do
it "should match a singular regex" do
expect(Facter).to receive(:value).with('os.family').at_least(:once).and_return("solaris")
one = type.provide(:one) do
defaultfor 'os.family' => /solaris/
end
expect(one).to be_default
end
it "should not match a non-matching regex " do
expect(Facter).to receive(:value).with('os.family').at_least(:once).and_return("redhat")
one = type.provide(:one) do
defaultfor 'os.family' => /solaris/
end
expect(one).to_not be_default
end
it "should allow a mix of regex and string" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return("fedora")
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("24")
one = type.provide(:one) do
defaultfor 'os.name' => "fedora", 'os.release.major' => /^2[2-9]$/
end
two = type.provide(:two) do
defaultfor 'os.name' => /fedora/, 'os.release.major' => '24'
end
expect(one).to be_default
expect(two).to be_default
end
end
describe "when there are multiple defaultfor's of equal specificity" do
before :each do
subject.defaultfor 'os.name' => :os1
subject.defaultfor 'os.name' => :os2
end
let(:alternate) { type.provide(:alternate) {} }
it "should be default for the first defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os1)
expect(provider).to be_default
expect(alternate).not_to be_default
end
it "should be default for the last defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os2)
expect(provider).to be_default
expect(alternate).not_to be_default
end
end
describe "when there are multiple defaultfor's with different specificity" do
before :each do
subject.defaultfor 'os.name' => :os1
subject.defaultfor 'os.name' => :os2, 'os.release.major' => "42"
subject.defaultfor 'os.name' => :os3, 'os.release.major' => /^4[2-9]$/
end
let(:alternate) { type.provide(:alternate) {} }
it "should be default for a more specific, but matching, defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os2)
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("42")
expect(provider).to be_default
expect(alternate).not_to be_default
end
it "should be default for a more specific, but matching, defaultfor with regex" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os3)
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("42")
expect(provider).to be_default
expect(alternate).not_to be_default
end
it "should be default for a less specific, but matching, defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os1)
expect(provider).to be_default
expect(alternate).not_to be_default
end
end
it "should consider any true value enough to be default" do
alternate = type.provide(:alternate) {}
subject.defaultfor 'os.name' => [:one, :two, :three, os]
expect(subject.name).to eq(type.defaultprovider.name)
expect(subject).to be_default
expect(alternate).not_to be_default
end
it "should not be default if the defaultfor doesn't match" do
expect(subject).not_to be_default
subject.defaultfor 'os.name' => :one
expect(subject).not_to be_default
end
it "should not be default if the notdefaultfor does match" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return("fedora")
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("24")
one = type.provide(:one) do
defaultfor 'os.name' => "fedora"
notdefaultfor 'os.name' => "fedora", 'os.release.major' => 24
end
expect(one).not_to be_default
end
it "should be default if the notdefaultfor doesn't match" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return("fedora")
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("24")
one = type.provide(:one) do
defaultfor 'os.name' => "fedora"
notdefaultfor 'os.name' => "fedora", 'os.release.major' => 42
end
expect(one).to be_default
end
# Key: spec has 4 required and 1 optional part:
# one-defaultfor, one-notdefaultfor, two-defaultfor, two-notdefaultfor
# d = defaultfor, n = notdefaultfor,
# d2 - two clauses in defaultfor constraint,
# ! = constraint exists but doesn't match
# none = no constraint
# d+/!d+/none+ - provider class has deeper inheritence
context "defaultfor/notdefaultfor configurable tests" do
[
# Two default? group - ties go to first to register
%w{d none d none pickone},
# Two default? group - second is selected for specificity
%w{d !n d2 !n },
%w{d !n d2 none },
# Two default? group - second is selected for inheritence
%w{d !n d+ !n },
%w{d !n d+ none },
# One default? group - second (only default?) always is selected
%w{!d !n d none },
%w{!d !n d !n },
%w{!d n d none },
%w{!d n d !n },
%w{d n d none },
%w{d n d !n },
# No default? group:
%w{d !n d !n pickone},
%w{d !n d none pickone},
%w{!d !n !d !n pickone},
%w{!d !n !d none pickone},
%w{!d none !d none pickone},
%w{none !n none !n pickone},
%w{none none none none pickone},
# No default? but deeper class inheritence group:
%w{!d !n !d+ !n },
%w{!d !n !d+ none },
%w{!d none !d+ none },
%w{none !n none+ !n },
%w{none none none+ none },
].each do |thisspec|
defaultforspec = {
:one => {},
:two => {},
:expect_one => false #Default expectation is to expect provider two for these tests
}
fail "Inheritence not supported on first provider" if thisspec[0].end_with?('+')
case thisspec[0] # First provider defaultfor spec
when 'd'
defaultforspec[:one][:defaultfor] = true
when '!d'
defaultforspec[:one][:defaultfor] = false
when 'none'
# Do not include a defaultfor constraint
else
fail "Did not understand first spec: %{spec}" % { spec: thisspec[0] }
end
case thisspec[1] # First provider notdefaultfor spec
when 'n'
defaultforspec[:one][:notdefaultfor] = true
when '!n'
defaultforspec[:one][:notdefaultfor] = false
when 'none'
# Do not include a notdefaultfor constraint
else
fail "Did not understand second spec: %{spec}" % { spec: thisspec[1] }
end
if thisspec[2].end_with?('+') then # d+ !d+ none+
defaultforspec[:two][:derived] = true
thisspec[2] = thisspec[2][0 .. -2]
end
case thisspec[2]
when 'd'
defaultforspec[:two][:defaultfor] = true
when 'd2'
defaultforspec[:two][:extradefaultfor] = true
when '!d'
defaultforspec[:two][:defaultfor] = false
when 'none'
# Do not include a defaultfor constraint
else
fail "Did not understand third spec: %{spec}" % { spec: thisspec[2] }
end
case thisspec[3] # Second provider notdefaultfor spec
when 'n'
defaultforspec[:two][:notdefaultfor] = true
when '!n'
defaultforspec[:two][:notdefaultfor] = false
when 'none'
# Do not include a notdefaultfor constraint
else
fail "Did not understand fourth spec: %{spec}" % { spec: thisspec[3] }
end
if thisspec.length == 5 && thisspec[4] == "pickone" then
defaultforspec[:expect_one] = true
end
it "with the specification: %{spec}" % { spec: thisspec.join(', ') } do
allow(Facter).to receive(:value).with('os.family').and_return("redhat")
allow(Facter).to receive(:value).with('os.name').and_return("centos")
allow(Facter).to receive(:value).with('os.release.full').and_return("27")
one = type.provide(:one) do
if defaultforspec[:one].key?(:defaultfor)
defaultfor 'os.family' => "redhat" if defaultforspec[:one][:defaultfor]
defaultfor 'os.family' => "ubuntu" if !defaultforspec[:one][:defaultfor]
end
if defaultforspec[:one].key?(:notdefaultfor)
notdefaultfor 'os.name' => "centos" if defaultforspec[:one][:notdefaultfor]
notdefaultfor 'os.name' => "ubuntu" if !defaultforspec[:one][:notdefaultfor]
end
end
provider_options = {}
provider_options[:parent] = one if defaultforspec[:two][:derived] # :two inherits from one, if spec'd
two = type.provide(:two, provider_options) do
if defaultforspec[:two].key?(:defaultfor) || defaultforspec[:two].key?(:extradefaultfor)
defaultfor 'os.family' => "redhat" if defaultforspec[:two][:defaultfor]
defaultfor 'os.family' => "redhat",# defaultforspec[:two][:extradefaultfor] has two parts
'os.name' => "centos" if defaultforspec[:two][:extradefaultfor]
defaultfor 'os.family' => "ubuntu" if !defaultforspec[:two][:defaultfor]
end
if defaultforspec[:two].key?(:notdefaultfor)
notdefaultfor 'os.release.full' => "27" if defaultforspec[:two][:notdefaultfor]
notdefaultfor 'os.release.full' => "99" if !defaultforspec[:two][:notdefaultfor]
end
end
if defaultforspec[:expect_one] then
expect(Puppet).to receive(:warning).with(/Found multiple default providers/)
expect(type.defaultprovider).to eq(one)
else
expect(type.defaultprovider).to eq(two)
end
end
end
end
describe "using a :feature key" do
before :each do
Puppet.features.add(:yay) do true end
Puppet.features.add(:boo) do false end
end
it "is default for an available feature" do
one = type.provide(:one) do
defaultfor :feature => :yay
end
expect(one).to be_default
end
it "is not default for a missing feature" do
two = type.provide(:two) do
defaultfor :feature => :boo
end
expect(two).not_to be_default
end
end
end
context "provider commands" do
it "should raise for unknown commands" do
expect { subject.command(:something) }.to raise_error(Puppet::DevError)
end
it "should handle command inheritance" do
parent = type.provide("parent")
child = type.provide("child", :parent => parent.name)
command = Puppet::Util.which('sh') || Puppet::Util.which('cmd.exe')
parent.commands :sh => command
expect(Puppet::FileSystem.exist?(parent.command(:sh))).to be_truthy
expect(parent.command(:sh)).to match(/#{Regexp.escape(command)}$/)
expect(Puppet::FileSystem.exist?(child.command(:sh))).to be_truthy
expect(child.command(:sh)).to match(/#{Regexp.escape(command)}$/)
end
it "#1197: should find commands added in the same run" do
subject.commands :testing => "puppet-bug-1197"
expect(subject.command(:testing)).to be_nil
allow(subject).to receive(:which).with("puppet-bug-1197").and_return("/puppet-bug-1197")
expect(subject.command(:testing)).to eq("/puppet-bug-1197")
# Ideally, we would also test that `suitable?` returned the right thing
# here, but it is impossible to get access to the methods that do that
# without digging way down into the implementation. --daniel 2012-03-20
end
context "with optional commands" do
before :each do
subject.optional_commands :cmd => "/no/such/binary/exists"
end
it { is_expected.to be_suitable }
it "should not be suitable if a mandatory command is also missing" do
subject.commands :foo => "/no/such/binary/either"
expect(subject).not_to be_suitable
end
it "should define a wrapper for the command" do
expect(subject).to respond_to(:cmd)
end
it "should return nil if the command is requested" do
expect(subject.command(:cmd)).to be_nil
end
it "should raise if the command is invoked" do
expect { subject.cmd }.to raise_error(Puppet::Error, /Command cmd is missing/)
end
end
end
context "execution" do
before :each do
expect(Puppet).not_to receive(:deprecation_warning)
end
it "delegates instance execute to Puppet::Util::Execution" do
expect(Puppet::Util::Execution).to receive(:execute).with("a_command", { :option => "value" })
provider.new.execute("a_command", { :option => "value" })
end
it "delegates class execute to Puppet::Util::Execution" do
expect(Puppet::Util::Execution).to receive(:execute).with("a_command", { :option => "value" })
provider.execute("a_command", { :option => "value" })
end
it "delegates instance execpipe to Puppet::Util::Execution" do
allow(Puppet::Util::Execution).to receive(:execpipe).with("a_command", true).and_yield('some output')
expect { |b| provider.new.execpipe("a_command", true, &b) }.to yield_with_args('some output')
end
it "delegates class execpipe to Puppet::Util::Execution" do
allow(Puppet::Util::Execution).to receive(:execpipe).with("a_command", true).and_yield('some output')
expect { |b| provider.execpipe("a_command", true, &b) }.to yield_with_args('some output')
end
end
context "mk_resource_methods" do
before :each do
type.newproperty(:prop)
type.newparam(:param)
provider.mk_resource_methods
end
let(:instance) { provider.new(nil) }
it "defaults to :absent" do
expect(instance.prop).to eq(:absent)
expect(instance.param).to eq(:absent)
end
it "should update when set" do
instance.prop = 'hello'
instance.param = 'goodbye'
expect(instance.prop).to eq('hello')
expect(instance.param).to eq('goodbye')
end
it "treats nil the same as absent" do
instance.prop = "value"
instance.param = "value"
instance.prop = nil
instance.param = nil
expect(instance.prop).to eq(:absent)
expect(instance.param).to eq(:absent)
end
it "preserves false as false" do
instance.prop = false
instance.param = false
expect(instance.prop).to eq(false)
expect(instance.param).to eq(false)
end
end
context "source" do
it "should default to the provider name" do
expect(subject.source).to eq(:default)
end
it "should default to the provider name for a child provider" do
expect(type.provide(:sub, :parent => subject.name).source).to eq(:sub)
end
it "should override if requested" do
provider = type.provide(:sub, :parent => subject.name, :source => subject.source)
expect(provider.source).to eq(subject.source)
end
it "should override to anything you want" do
expect { subject.source = :banana }.to change { subject.source }.
from(:default).to(:banana)
end
end
context "features" do
before :each do
type.feature :numeric, '', :methods => [:one, :two]
type.feature :alpha, '', :methods => [:a, :b]
type.feature :nomethods, ''
end
{ :no => { :alpha => false, :numeric => false, :methods => [] },
:numeric => { :alpha => false, :numeric => true, :methods => [:one, :two] },
:alpha => { :alpha => true, :numeric => false, :methods => [:a, :b] },
:all => {
:alpha => true, :numeric => true,
:methods => [:a, :b, :one, :two]
},
:alpha_and_partial => {
:alpha => true, :numeric => false,
:methods => [:a, :b, :one]
},
:numeric_and_partial => {
:alpha => false, :numeric => true,
:methods => [:a, :one, :two]
},
:all_partial => { :alpha => false, :numeric => false, :methods => [:a, :one] },
:other_and_none => { :alpha => false, :numeric => false, :methods => [:foo, :bar] },
:other_and_alpha => {
:alpha => true, :numeric => false,
:methods => [:foo, :bar, :a, :b]
},
}.each do |name, setup|
context "with #{name.to_s.gsub('_', ' ')} features" do
let :provider do
provider = type.provide(name)
setup[:methods].map do |method|
provider.send(:define_method, method) do true end
end
type.provider(name)
end
context "provider class" do
subject { provider }
it { is_expected.to respond_to(:has_features) }
it { is_expected.to respond_to(:has_feature) }
it { is_expected.to respond_to(:nomethods?) }
it { is_expected.not_to be_nomethods }
it { is_expected.to respond_to(:numeric?) }
if setup[:numeric]
it { is_expected.to be_numeric }
it { is_expected.to be_satisfies(:numeric) }
else
it { is_expected.not_to be_numeric }
it { is_expected.not_to be_satisfies(:numeric) }
end
it { is_expected.to respond_to(:alpha?) }
if setup[:alpha]
it { is_expected.to be_alpha }
it { is_expected.to be_satisfies(:alpha) }
else
it { is_expected.not_to be_alpha }
it { is_expected.not_to be_satisfies(:alpha) }
end
end
context "provider instance" do
subject { provider.new }
it { is_expected.to respond_to(:numeric?) }
if setup[:numeric]
it { is_expected.to be_numeric }
it { is_expected.to be_satisfies(:numeric) }
else
it { is_expected.not_to be_numeric }
it { is_expected.not_to be_satisfies(:numeric) }
end
it { is_expected.to respond_to(:alpha?) }
if setup[:alpha]
it { is_expected.to be_alpha }
it { is_expected.to be_satisfies(:alpha) }
else
it { is_expected.not_to be_alpha }
it { is_expected.not_to be_satisfies(:alpha) }
end
end
end
end
context "feature with no methods" do
before :each do
type.feature :undemanding, ''
end
it { is_expected.to respond_to(:undemanding?) }
context "when the feature is not declared" do
it { is_expected.not_to be_undemanding }
it { is_expected.not_to be_satisfies(:undemanding) }
end
context "when the feature is declared" do
before :each do
subject.has_feature :undemanding
end
it { is_expected.to be_undemanding }
it { is_expected.to be_satisfies(:undemanding) }
end
end
context "supports_parameter?" do
before :each do
type.newparam(:no_feature)
type.newparam(:one_feature, :required_features => :alpha)
type.newparam(:two_features, :required_features => [:alpha, :numeric])
end
let :providers do
{
:zero => type.provide(:zero),
:one => type.provide(:one) do has_features :alpha end,
:two => type.provide(:two) do has_features :alpha, :numeric end
}
end
{ :zero => { :yes => [:no_feature], :no => [:one_feature, :two_features] },
:one => { :yes => [:no_feature, :one_feature], :no => [:two_features] },
:two => { :yes => [:no_feature, :one_feature, :two_features], :no => [] }
}.each do |name, data|
data[:yes].each do |param|
it "should support #{param} with provider #{name}" do
expect(providers[name]).to be_supports_parameter(param)
end
end
data[:no].each do |param|
it "should not support #{param} with provider #{name}" do
expect(providers[name]).not_to be_supports_parameter(param)
end
end
end
end
end
def provider_of(options = {}, &block)
type = Puppet::Type.newtype(:dummy) do
provide(:dummy, options, &block)
end
type.provider(:dummy)
end
def expect_command_executed(name, path, *args)
command = Puppet::Provider::Command.new(name, path, Puppet::Util, Puppet::Util::Execution)
args = [no_args] if args.empty?
expect(command).to receive(:execute).with(*args)
command
end
def allow_creation_of(command, environment = {})
allow(Puppet::Provider::Command).to receive(:new).with(command.name, command.executable, Puppet::Util, Puppet::Util::Execution, { :failonfail => true, :combine => true, :custom_environment => environment }).and_return(command)
end
def file_exists_and_is_executable(path)
expect(FileTest).to receive(:file?).with(path).and_return(true)
expect(FileTest).to receive(:executable?).with(path).and_return(true)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/face_spec.rb | spec/unit/face_spec.rb | # You should look at interface_spec.rb
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/confine_spec.rb | spec/unit/confine_spec.rb | require 'spec_helper'
require 'puppet/confine'
class Puppet::TestConfine < Puppet::Confine
def pass?(value)
false
end
end
describe Puppet::Confine do
it "should require a value" do
expect { Puppet::Confine.new }.to raise_error(ArgumentError)
end
it "should always convert values to an array" do
expect(Puppet::Confine.new("/some/file").values).to be_instance_of(Array)
end
it "should have a 'true' test" do
expect(Puppet::Confine.test(:true)).to be_instance_of(Class)
end
it "should have a 'false' test" do
expect(Puppet::Confine.test(:false)).to be_instance_of(Class)
end
it "should have a 'feature' test" do
expect(Puppet::Confine.test(:feature)).to be_instance_of(Class)
end
it "should have an 'exists' test" do
expect(Puppet::Confine.test(:exists)).to be_instance_of(Class)
end
it "should have a 'variable' test" do
expect(Puppet::Confine.test(:variable)).to be_instance_of(Class)
end
describe "when testing all values" do
before do
@confine = Puppet::TestConfine.new(%w{a b c})
@confine.label = "foo"
end
it "should be invalid if any values fail" do
allow(@confine).to receive(:pass?).and_return(true)
expect(@confine).to receive(:pass?).with("b").and_return(false)
expect(@confine).not_to be_valid
end
it "should be valid if all values pass" do
allow(@confine).to receive(:pass?).and_return(true)
expect(@confine).to be_valid
end
it "should short-cut at the first failing value" do
expect(@confine).to receive(:pass?).once.and_return(false)
@confine.valid?
end
it "should log failing confines with the label and message" do
Puppet[:log_level] = 'debug'
allow(@confine).to receive(:pass?).and_return(false)
expect(@confine).to receive(:message).and_return("My message")
expect(@confine).to receive(:label).and_return("Mylabel")
expect(Puppet).to receive(:debug) { |&b| expect(b.call).to eq("Mylabel: My message") }
@confine.valid?
end
end
describe "when testing the result of the values" do
before { @confine = Puppet::TestConfine.new(%w{a b c d}) }
it "should return an array with the result of the test for each value" do
allow(@confine).to receive(:pass?).and_return(true)
expect(@confine).to receive(:pass?).with("b").and_return(false)
expect(@confine).to receive(:pass?).with("d").and_return(false)
expect(@confine.result).to eq([true, false, true, false])
end
end
describe "when requiring" do
it "does not cache failed requires when always_retry_plugins is true" do
Puppet[:always_retry_plugins] = true
expect(Puppet::Confine).to receive(:require).with('puppet/confine/os.family').twice.and_raise(LoadError)
Puppet::Confine.test('os.family')
Puppet::Confine.test('os.family')
end
it "caches failed requires when always_retry_plugins is false" do
Puppet[:always_retry_plugins] = false
expect(Puppet::Confine).to receive(:require).with('puppet/confine/os.family').once.and_raise(LoadError)
Puppet::Confine.test('os.family')
Puppet::Confine.test('os.family')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/context_spec.rb | spec/unit/context_spec.rb | require 'spec_helper'
describe Puppet::Context do
let(:context) { Puppet::Context.new({ :testing => "value" }) }
describe "with additional context" do
before :each do
context.push("a" => 1)
end
it "allows rebinding values in a nested context" do
inner = nil
context.override("a" => 2) do
inner = context.lookup("a")
end
expect(inner).to eq(2)
end
it "outer bindings are available in an overridden context" do
inner_a = nil
inner_b = nil
context.override("b" => 2) do
inner_a = context.lookup("a")
inner_b = context.lookup("b")
end
expect(inner_a).to eq(1)
expect(inner_b).to eq(2)
end
it "overridden bindings do not exist outside of the override" do
context.override("a" => 2) do
end
expect(context.lookup("a")).to eq(1)
end
it "overridden bindings do not exist outside of the override even when leaving via an error" do
begin
context.override("a" => 2) do
raise "this should still cause the bindings to leave"
end
rescue
end
expect(context.lookup("a")).to eq(1)
end
end
context "a rollback" do
it "returns to the mark" do
context.push("a" => 1)
context.mark("start")
context.push("a" => 2)
context.push("a" => 3)
context.pop
context.rollback("start")
expect(context.lookup("a")).to eq(1)
end
it "rolls back to the mark across a scoped override" do
context.push("a" => 1)
context.mark("start")
context.override("a" => 3) do
context.rollback("start")
expect(context.lookup("a")).to eq(1)
end
expect(context.lookup("a")).to eq(1)
end
it "fails to rollback to an unknown mark" do
expect do
context.rollback("unknown")
end.to raise_error(Puppet::Context::UnknownRollbackMarkError)
end
it "does not allow the same mark to be set twice" do
context.mark("duplicate")
expect do
context.mark("duplicate")
end.to raise_error(Puppet::Context::DuplicateRollbackMarkError)
end
end
context "with multiple threads" do
it "a value pushed in another thread is not seen in the original thread" do
context.push(a: 1)
t = Thread.new do
context.push(a: 2, b: 5)
end
t.join
expect(context.lookup(:a)).to eq(1)
expect{ context.lookup(:b) }.to raise_error(Puppet::Context::UndefinedBindingError)
end
it "pops on a different thread do not interfere" do
context.push(a: 1)
t = Thread.new do
context.pop
end
t.join
# Raises exception if the binding we pushed has already been popped
context.pop
end
it "a mark in one thread is not seen in another thread" do
t = Thread.new do
context.push(b: 2)
context.mark('point b')
end
t.join
expect { context.rollback('point b') }.to raise_error(Puppet::Context::UnknownRollbackMarkError)
end
end
end
describe Puppet::Context::EmptyStack do
let(:empty_stack) { Puppet::Context::EmptyStack.new }
it "raises undefined binding on lookup" do
expect { empty_stack.lookup("a") }.to raise_error(Puppet::Context::UndefinedBindingError)
end
it "calls a provided block for a default value when none is found" do
expect(empty_stack.lookup("a") { "default" }).to eq("default")
end
it "raises an error when trying to pop" do
expect { empty_stack.pop }.to raise_error(Puppet::Context::StackUnderflow)
end
it "returns a stack when something is pushed" do
stack = empty_stack.push(a: 1)
expect(stack).to be_a(Puppet::Context::Stack)
end
it "returns a new stack with no bindings when pushed nil" do
stack = empty_stack.push(nil)
expect(stack).not_to be(empty_stack)
expect(stack.pop).to be(empty_stack)
end
end
describe Puppet::Context::Stack do
let(:empty_stack) { Puppet::Context::EmptyStack.new }
context "a stack with depth of 1" do
let(:stack) { empty_stack.push(a: 1) }
it "returns the empty stack when popped" do
expect(stack.pop).to be(empty_stack)
end
it "calls a provided block for a default value when none is found" do
expect(stack.lookup("a") { "default" }).to eq("default")
end
it "returns a new but equivalent stack when pushed nil" do
stackier = stack.push(nil)
expect(stackier).not_to be(stack)
expect(stackier.pop).to be(stack)
expect(stackier.bindings).to eq(stack.bindings)
end
end
context "a stack with more than 1 element" do
let(:level_one) { empty_stack.push(a: 1, c: 4) }
let(:level_two) { level_one.push(b: 2, c: 3) }
it "falls back to lower levels on lookup" do
expect(level_two.lookup(:c)).to eq(3)
expect(level_two.lookup(:a)).to eq(1)
expect{ level_two.lookup(:d) }.to raise_error(Puppet::Context::UndefinedBindingError)
end
it "the parent is immutable" do
expect(level_one.lookup(:c)).to eq(4)
expect{ level_one.lookup(:b) }.to raise_error(Puppet::Context::UndefinedBindingError)
end
end
context 'supports lazy entries' do
it 'by evaluating a bound proc' do
stack = empty_stack.push(a: lambda { || 'yay' })
expect(stack.lookup(:a)).to eq('yay')
end
it 'by memoizing the bound value' do
original = 'yay'
stack = empty_stack.push(:a => lambda {|| tmp = original; original = 'no'; tmp})
expect(stack.lookup(:a)).to eq('yay')
expect(original).to eq('no')
expect(stack.lookup(:a)).to eq('yay')
end
it 'the bound value is memoized only at the top level of the stack' do
# I'm just characterizing the current behavior here
original = 'yay'
stack = empty_stack.push(:a => lambda {|| tmp = original; original = 'no'; tmp})
stack_two = stack.push({})
expect(stack.lookup(:a)).to eq('yay')
expect(original).to eq('no')
expect(stack.lookup(:a)).to eq('yay')
expect(stack_two.lookup(:a)).to eq('no')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/plan_spec.rb | spec/unit/plan_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/module/plan'
describe Puppet::Module::Plan do
include PuppetSpec::Files
let(:modpath) { tmpdir('plan_modpath') }
let(:mymodpath) { File.join(modpath, 'mymod') }
let(:othermodpath) { File.join(modpath, 'othermod') }
let(:mymod) { Puppet::Module.new('mymod', mymodpath, nil) }
let(:othermod) { Puppet::Module.new('othermod', othermodpath, nil) }
let(:plans_path) { File.join(mymodpath, 'plans') }
let(:other_plans_path) { File.join(othermodpath, 'plans') }
let(:plans_glob) { File.join(mymodpath, 'plans', '*') }
describe :naming do
word = (Puppet::Module::Plan::RESERVED_WORDS - Puppet::Module::Plan::RESERVED_DATA_TYPES).sample
datatype = (Puppet::Module::Plan::RESERVED_DATA_TYPES - Puppet::Module::Plan::RESERVED_WORDS).sample
test_cases = { 'iLegal.pp' => 'Plan names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores',
'name.md' => 'Plan name cannot have extension .md, must be .pp or .yaml',
"#{word}.pp" => "Plan name cannot be a reserved word, but was '#{word}'",
"#{datatype}.pp" => "Plan name cannot be a Puppet data type, but was '#{datatype}'",
'test_1.pp' => nil,
'test_2.yaml' => nil }
test_cases.each do |filename, error|
it "constructs plans when needed with #{filename}" do
name = File.basename(filename, '.*')
if error
expect { Puppet::Module::Plan.new(mymod, name, [File.join(plans_path, filename)]) }
.to raise_error(Puppet::Module::Plan::InvalidName,
error)
else
expect { Puppet::Module::Plan.new(mymod, name, [filename]) }
.not_to raise_error
end
end
end
end
it "finds all plans in module" do
og_files = %w{plan1.pp plan2.yaml not-a-plan.ok}.map { |bn| "#{plans_path}/#{bn}" }
expect(Dir).to receive(:glob).with(plans_glob).and_return(og_files)
plans = Puppet::Module::Plan.plans_in_module(mymod)
expect(plans.count).to eq(2)
end
it "selects .pp file before .yaml" do
og_files = %w{plan1.pp plan1.yaml}.map { |bn| "#{plans_path}/#{bn}" }
expect(Dir).to receive(:glob).with(plans_glob).and_return(og_files)
plans = Puppet::Module::Plan.plans_in_module(mymod)
expect(plans.count).to eq(1)
expect(plans.first.files.count).to eq(1)
expect(plans.first.files.first['name']).to eq('plan1.pp')
end
it "gives the 'init' plan a name that is just the module's name" do
expect(Puppet::Module::Plan.new(mymod, 'init', ["#{plans_path}/init.pp"]).name).to eq('mymod')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type_spec.rb | spec/unit/type_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet/property/boolean'
Puppet::Type.newtype(:type_test) do
ensurable
newparam(:name, isnamevar: true)
newproperty(:device)
newproperty(:blockdevice)
newproperty(:fstype)
newproperty(:options)
newproperty(:pass)
newproperty(:atboot, parent: Puppet::Property::Boolean) do
def munge(value)
munged = super
if munged
:yes
else
:no
end
end
end
newparam(:remounts) do
newvalues(:true, :false)
defaultto do
true
end
end
end
Puppet::Type.type(:type_test).provide(:type_test) do
mk_resource_methods
end
describe Puppet::Type, :unless => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
include PuppetSpec::Compiler
let(:resource_type) { :type_test }
let(:klass) { Puppet::Type.type(resource_type) }
let(:ref_type) { klass.name.to_s.capitalize }
it "should be Comparable" do
a = Puppet::Type.type(:notify).new(:name => "a")
b = Puppet::Type.type(:notify).new(:name => "b")
c = Puppet::Type.type(:notify).new(:name => "c")
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].each do |this|
expect(this.sort).to eq([a, b, c])
end
expect(a).to be < b
expect(a).to be < c
expect(b).to be > a
expect(b).to be < c
expect(c).to be > a
expect(c).to be > b
[a, b, c].each {|x| expect(a).to be <= x }
[a, b, c].each {|x| expect(c).to be >= x }
expect(b).to be_between(a, c)
end
it "should consider a parameter to be valid if it is a valid parameter" do
expect(klass).to be_valid_parameter(:name)
end
it "should consider a parameter to be valid if it is a valid property" do
expect(klass).to be_valid_parameter(:fstype)
end
it "should consider a parameter to be valid if it is a valid metaparam" do
expect(klass).to be_valid_parameter(:noop)
end
it "should be able to retrieve a property by name" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
expect(resource.property(:fstype)).to be_instance_of(klass.attrclass(:fstype))
end
it "should be able to retrieve a parameter by name" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
expect(resource.parameter(:name)).to be_instance_of(klass.attrclass(:name))
end
it "should be able to retrieve a property by name using the :parameter method" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
expect(resource.parameter(:fstype)).to be_instance_of(klass.attrclass(:fstype))
end
it "should be able to retrieve all set properties" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
props = resource.properties
expect(props).not_to be_include(nil)
[:fstype, :ensure, :pass].each do |name|
expect(props).to be_include(resource.parameter(name))
end
end
it "can retrieve all set parameters" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present, :tag => 'foo')
params = resource.parameters_with_value
[:name, :provider, :ensure, :fstype, :pass, :loglevel, :tag].each do |name|
expect(params).to be_include(resource.parameter(name))
end
end
it "can not return any `nil` values when retrieving all set parameters" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present, :tag => 'foo')
params = resource.parameters_with_value
expect(params).not_to be_include(nil)
end
it "can return an iterator for all set parameters" do
resource = Puppet::Type.type(:notify).new(:name=>'foo',:message=>'bar',:tag=>'baz',:require=> "File['foo']")
params = [:name, :message, :withpath, :loglevel, :tag, :require]
resource.eachparameter { |param|
expect(params).to be_include(param.to_s.to_sym)
}
end
it "should have a method for setting default values for resources" do
expect(klass.new(:name => "foo")).to respond_to(:set_default)
end
it "should do nothing for attributes that have no defaults and no specified value" do
expect(klass.new(:name => "foo").parameter(:noop)).to be_nil
end
it "should have a method for adding tags" do
expect(klass.new(:name => "foo")).to respond_to(:tags)
end
it "should use the tagging module" do
expect(klass.ancestors).to be_include(Puppet::Util::Tagging)
end
it "should delegate to the tagging module when tags are added" do
resource = klass.new(:name => "foo")
allow(resource).to receive(:tag).with(resource_type)
expect(resource).to receive(:tag).with(:tag1, :tag2)
resource.tags = [:tag1,:tag2]
end
it "should add the current type as tag" do
resource = klass.new(:name => "foo")
allow(resource).to receive(:tag)
expect(resource).to receive(:tag).with(resource_type)
resource.tags = [:tag1,:tag2]
end
it "should have a method to know if the resource is exported" do
expect(klass.new(:name => "foo")).to respond_to(:exported?)
end
it "should have a method to know if the resource is virtual" do
expect(klass.new(:name => "foo")).to respond_to(:virtual?)
end
it "should consider its version to be zero if it has no catalog" do
expect(klass.new(:name => "foo").version).to eq(0)
end
it "reports the correct path even after path is used during setup of the type" do
Puppet::Type.newtype(:testing) do
newparam(:name) do
isnamevar
validate do |value|
path # forces the computation of the path
end
end
end
ral = compile_to_ral(<<-MANIFEST)
class something {
testing { something: }
}
include something
MANIFEST
expect(ral.resource("Testing[something]").path).to eq("/Stage[main]/Something/Testing[something]")
end
context "alias metaparam" do
it "creates a new name that can be used for resource references" do
ral = compile_to_ral(<<-MANIFEST)
notify { a: alias => c }
MANIFEST
expect(ral.resource("Notify[a]")).to eq(ral.resource("Notify[c]"))
end
end
context 'aliased resource' do
it 'fails if a resource is defined and then redefined using name that results in the same alias' do
drive = Puppet::Util::Platform.windows? ? 'C:' : ''
code = <<~PUPPET
$dir='#{drive}/tmp/test'
$same_dir='#{drive}/tmp/test/'
file {$dir:
ensure => directory
}
file { $same_dir:
ensure => directory
}
PUPPET
expect { compile_to_ral(code) }.to raise_error(/resource \["File", "#{drive}\/tmp\/test"\] already declared/)
end
end
context "resource attributes" do
let(:resource) {
resource = klass.new(:name => "foo")
catalog = Puppet::Resource::Catalog.new
catalog.version = 50
catalog.add_resource resource
resource
}
it "should consider its version to be its catalog version" do
expect(resource.version).to eq(50)
end
it "should have tags" do
expect(resource).to be_tagged(resource_type.to_s)
expect(resource).to be_tagged("foo")
end
it "should have a path" do
expect(resource.path).to eq("/#{ref_type}[foo]")
end
end
it "should consider its type to be the name of its class" do
expect(klass.new(:name => "foo").type).to eq(resource_type)
end
it "should use any provided noop value" do
expect(klass.new(:name => "foo", :noop => true)).to be_noop
end
it "should use the global noop value if none is provided" do
Puppet[:noop] = true
expect(klass.new(:name => "foo")).to be_noop
end
it "should not be noop if in a non-host_config catalog" do
resource = klass.new(:name => "foo")
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
expect(resource).not_to be_noop
end
describe "when creating an event" do
before do
@resource = klass.new :name => "foo"
end
it "should have the resource's reference as the resource" do
expect(@resource.event.resource).to eq("#{ref_type}[foo]")
end
it "should have the resource's log level as the default log level" do
@resource[:loglevel] = :warning
expect(@resource.event.default_log_level).to eq(:warning)
end
{:file => "/my/file", :line => 50}.each do |attr, value|
it "should set the #{attr}" do
allow(@resource).to receive(attr).and_return(value)
expect(@resource.event.send(attr)).to eq(value)
end
end
it "should set the tags" do
@resource.tag("abc", "def")
expect(@resource.event).to be_tagged("abc")
expect(@resource.event).to be_tagged("def")
end
it "should allow specification of event attributes" do
expect(@resource.event(:status => "noop").status).to eq("noop")
end
end
describe "when creating a provider" do
before :each do
@type = Puppet::Type.newtype(:provider_test_type) do
newparam(:name) { isnamevar }
newparam(:foo)
newproperty(:bar)
end
end
after :each do
@type.provider_hash.clear
end
describe "when determining if instances of the type are managed" do
it "should not consider audit only resources to be managed" do
expect(@type.new(:name => "foo", :audit => 'all').managed?).to be_falsey
end
it "should not consider resources with only parameters to be managed" do
expect(@type.new(:name => "foo", :foo => 'did someone say food?').managed?).to be_falsey
end
it "should consider resources with any properties set to be managed" do
expect(@type.new(:name => "foo", :bar => 'Let us all go there').managed?).to be_truthy
end
end
it "should have documentation for the 'provider' parameter if there are providers" do
@type.provide(:test_provider)
expect(@type.paramdoc(:provider)).to match(/`provider_test_type`[\s]+resource/)
end
it "should not have documentation for the 'provider' parameter if there are no providers" do
expect { @type.paramdoc(:provider) }.to raise_error(NoMethodError)
end
it "should create a subclass of Puppet::Provider for the provider" do
provider = @type.provide(:test_provider)
expect(provider.ancestors).to include(Puppet::Provider)
end
it "should use a parent class if specified" do
parent_provider = @type.provide(:parent_provider)
child_provider = @type.provide(:child_provider, :parent => parent_provider)
expect(child_provider.ancestors).to include(parent_provider)
end
it "should use a parent class if specified by name" do
parent_provider = @type.provide(:parent_provider)
child_provider = @type.provide(:child_provider, :parent => :parent_provider)
expect(child_provider.ancestors).to include(parent_provider)
end
it "should raise an error when the parent class can't be found" do
expect {
@type.provide(:child_provider, :parent => :parent_provider)
}.to raise_error(Puppet::DevError, /Could not find parent provider.+parent_provider/)
end
it "should ensure its type has a 'provider' parameter" do
@type.provide(:test_provider)
expect(@type.parameters).to include(:provider)
end
it "should remove a previously registered provider with the same name" do
old_provider = @type.provide(:test_provider)
new_provider = @type.provide(:test_provider)
expect(old_provider).not_to equal(new_provider)
end
it "should register itself as a provider for the type" do
provider = @type.provide(:test_provider)
expect(provider).to eq(@type.provider(:test_provider))
end
it "should create a provider when a provider with the same name previously failed" do
@type.provide(:test_provider) do
raise "failed to create this provider"
end rescue nil
provider = @type.provide(:test_provider)
expect(provider.ancestors).to include(Puppet::Provider)
expect(provider).to eq(@type.provider(:test_provider))
end
describe "with a parent class from another type" do
before :each do
@parent_type = Puppet::Type.newtype(:provider_parent_type) do
newparam(:name) { isnamevar }
end
@parent_provider = @parent_type.provide(:parent_provider)
end
it "should be created successfully" do
child_provider = @type.provide(:child_provider, :parent => @parent_provider)
expect(child_provider.ancestors).to include(@parent_provider)
end
it "should be registered as a provider of the child type" do
@type.provide(:child_provider, :parent => @parent_provider)
expect(@type.providers).to include(:child_provider)
expect(@parent_type.providers).not_to include(:child_provider)
end
end
end
describe "when choosing a default provider" do
it "should choose the provider with the highest specificity" do
# Make a fake type
type = Puppet::Type.newtype(:defaultprovidertest) do
newparam(:name) do end
end
basic = type.provide(:basic) {}
greater = type.provide(:greater) {}
allow(basic).to receive(:specificity).and_return(1)
allow(greater).to receive(:specificity).and_return(2)
expect(type.defaultprovider).to equal(greater)
end
end
context "autorelations" do
before :each do
Puppet::Type.newtype(:autorelation_one) do
newparam(:name) { isnamevar }
end
end
describe "when building autorelations" do
it "should be able to autorequire puppet resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autorequire(:autorelation_one) { Puppet::Type.type(:notify).new(name: 'test') }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'Notify[test]': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Notify[test]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autorequire resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autorequire(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it 'should not fail autorequire contains undef entries' do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autorequire(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autosubscribe resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autosubscribe(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
it 'should not fail if autosubscribe contains undef entries' do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autosubscribe(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
it "should be able to autobefore resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autobefore(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should not fail when autobefore contains undef entries" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autobefore(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autonotify resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autonotify(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
it 'should not fail if autonotify contains undef entries' do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autonotify(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
end
end
describe "when initializing" do
describe "and passed a Puppet::Resource instance" do
it "should set its title to the title of the resource if the resource type is equal to the current type" do
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:name => "/other"})
expect(klass.new(resource).title).to eq("/foo")
end
it "should set its title to the resource reference if the resource type is not equal to the current type" do
resource = Puppet::Resource.new(:user, "foo")
expect(klass.new(resource).title).to eq("User[foo]")
end
[:line, :file, :catalog, :exported, :virtual].each do |param|
it "should copy '#{param}' from the resource if present" do
resource = Puppet::Resource.new(resource_type, "/foo")
resource.send(param.to_s + "=", "foo")
resource.send(param.to_s + "=", "foo")
expect(klass.new(resource).send(param)).to eq("foo")
end
end
it "should copy any tags from the resource" do
resource = Puppet::Resource.new(resource_type, "/foo")
resource.tag "one", "two"
tags = klass.new(resource).tags
expect(tags).to be_include("one")
expect(tags).to be_include("two")
end
it "should copy the resource's parameters as its own" do
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:atboot => :yes, :fstype => "boo"})
params = klass.new(resource).to_hash
expect(params[:fstype]).to eq("boo")
expect(params[:atboot]).to eq(:yes)
end
it "copies sensitive parameters to the appropriate properties" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo"},
:sensitive_parameters => [:fstype])
type = klass.new(resource)
expect(type.property(:fstype).sensitive).to eq true
end
it "logs a warning when a parameter is marked as sensitive" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo", :remounts => true},
:sensitive_parameters => [:remounts])
expect_any_instance_of(klass).to receive(:warning).with(/Unable to mark 'remounts' as sensitive: remounts is a parameter and not a property/)
klass.new(resource)
end
it "logs a warning when a property is not set but is marked as sensitive" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo"},
:sensitive_parameters => [:device])
expect_any_instance_of(klass).to receive(:warning).with("Unable to mark 'device' as sensitive: the property itself was not assigned a value.")
klass.new(resource)
end
it "logs an error when a property is not defined on the type but is marked as sensitive" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo"},
:sensitive_parameters => [:content])
expect_any_instance_of(klass).to receive(:err).with("Unable to mark 'content' as sensitive: the property itself is not defined on #{resource_type}.")
klass.new(resource)
end
end
describe "and passed a Hash" do
it "should extract the title from the hash" do
expect(klass.new(:title => "/yay").title).to eq("/yay")
end
it "should work when hash keys are provided as strings" do
expect(klass.new("title" => "/yay").title).to eq("/yay")
end
it "should work when hash keys are provided as symbols" do
expect(klass.new(:title => "/yay").title).to eq("/yay")
end
it "should use the name from the hash as the title if no explicit title is provided" do
expect(klass.new(:name => "/yay").title).to eq("/yay")
end
it "should use the Resource Type's namevar to determine how to find the name in the hash" do
yay = make_absolute('/yay')
expect(Puppet::Type.type(:file).new(:path => yay).title).to eq(yay)
end
[:catalog].each do |param|
it "should extract '#{param}' from the hash if present" do
expect(klass.new(:name => "/yay", param => "foo").send(param)).to eq("foo")
end
end
it "should use any remaining hash keys as its parameters" do
resource = klass.new(:title => "/foo", :catalog => "foo", :atboot => :yes, :fstype => "boo")
expect(resource[:fstype]).to eq("boo")
expect(resource[:atboot]).to eq(:yes)
end
end
it "should fail if any invalid attributes have been provided" do
expect { klass.new(:title => "/foo", :nosuchattr => "whatever") }.to raise_error(Puppet::Error, /no parameter named 'nosuchattr'/)
end
context "when an attribute fails validation" do
it "should fail with Puppet::ResourceError when PuppetError raised" do
expect { Puppet::Type.type(:file).new(:title => "/foo", :source => "unknown:///") }.to raise_error(Puppet::ResourceError, /Parameter source failed on File\[.*foo\]/)
end
it "should fail with Puppet::ResourceError when ArgumentError raised" do
expect { Puppet::Type.type(:file).new(:title => "/foo", :mode => "abcdef") }.to raise_error(Puppet::ResourceError, /Parameter mode failed on File\[.*foo\]/)
end
it "should include the file/line in the error" do
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return("example.pp")
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(42)
expect { Puppet::Type.type(:file).new(:title => "/foo", :source => "unknown:///") }.to raise_error(Puppet::ResourceError, /\(file: example\.pp, line: 42\)/)
end
end
it "should set its name to the resource's title if the resource does not have a :name or namevar parameter set" do
resource = Puppet::Resource.new(resource_type, "/foo")
expect(klass.new(resource).name).to eq("/foo")
end
it "should fail if no title, name, or namevar are provided" do
expect { klass.new(:atboot => :yes) }.to raise_error(Puppet::Error)
end
it "should set the attributes in the order returned by the class's :allattrs method" do
allow(klass).to receive(:allattrs).and_return([:name, :atboot, :noop])
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:name => "myname", :atboot => :yes, :noop => "whatever"})
set = []
allow_any_instance_of(klass).to receive(:newattr) do |_, param, hash|
set << param
double("a property", :value= => nil, :default => nil, :name => nil)
end
klass.new(resource)
expect(set[-1]).to eq(:noop)
expect(set[-2]).to eq(:atboot)
end
it "should always set the name and then default provider before anything else" do
allow(klass).to receive(:allattrs).and_return([:provider, :name, :atboot])
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:name => "myname", :atboot => :yes})
set = []
allow_any_instance_of(klass).to receive(:newattr) do |_, param, hash|
set << param
double("a property", :value= => nil, :default => nil, :name => nil)
end
klass.new(resource)
expect(set[0]).to eq(:name)
expect(set[1]).to eq(:provider)
end
# This one is really hard to test :/
it "should set each default immediately if no value is provided" 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)
defaults = []
allow_any_instance_of(Puppet::Type.type(:service)).to receive(:set_default) { |_, value| defaults << value }
Puppet::Type.type(:service).new :name => "whatever"
expect(defaults[0]).to eq(:provider)
end
it "should retain a copy of the originally provided parameters" do
expect(klass.new(:name => "foo", :atboot => :yes, :noop => false).original_parameters).to eq({:atboot => :yes, :noop => false})
end
it "should delete the name via the namevar from the originally provided parameters" do
expect(Puppet::Type.type(:file).new(:name => make_absolute('/foo')).original_parameters[:path]).to be_nil
end
context "when validating the resource" do
it "should call the type's validate method if present" do
expect_any_instance_of(Puppet::Type.type(:file)).to receive(:validate)
Puppet::Type.type(:file).new(:name => make_absolute('/foo'))
end
it "should raise Puppet::ResourceError with resource name when Puppet::Error raised" do
expect do
Puppet::Type.type(:file).new(
:name => make_absolute('/foo'),
:source => "puppet:///",
:content => "foo"
)
end.to raise_error(Puppet::ResourceError, /Validation of File\[.*foo.*\]/)
end
it "should raise Puppet::ResourceError with manifest file and line on failure" do
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return("example.pp")
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(42)
expect do
Puppet::Type.type(:file).new(
:name => make_absolute('/foo'),
:source => "puppet:///",
:content => "foo"
)
end.to raise_error(Puppet::ResourceError, /Validation.*\(file: example\.pp, line: 42\)/)
end
end
end
describe "#set_sensitive_parameters" do
let(:sensitive_type) do
Puppet::Type.newtype(:sensitive_test) do
newparam(:name) { isnamevar }
newproperty(:secret) do
newvalues(/.*/)
sensitive true
end
newproperty(:transparency) do
newvalues(/.*/)
sensitive false
end
newproperty(:things) { newvalues(/.*/) }
end
end
it "should mark properties as sensitive" do
resource = sensitive_type.new(:name => 'foo', :secret => 'uber classified')
expect(resource.parameters[:secret].sensitive).to be true
end
it "should not have a sensitive flag when not set" do
resource = sensitive_type.new(:name => 'foo', :things => '1337')
expect(resource.parameters[:things].sensitive).to be_nil
end
it "should define things as not sensitive" do
resource = sensitive_type.new(:name => 'foo', :transparency => 'public knowledge')
expect(resource.parameters[:transparency].sensitive).to be false
end
it "should honor when sensitivity is set in a manifest" do
resource = sensitive_type.new(:name => 'foo',
:transparency => Puppet::Pops::Types::PSensitiveType::Sensitive.new('top secret'),
:sensitive_parameters => [:transparency]
)
expect(resource.parameters[:transparency].sensitive).to be true
end
end
describe "when #finish is called on a type" do
let(:post_hook_type) do
Puppet::Type.newtype(:finish_test) do
newparam(:name) { isnamevar }
newparam(:post) do
def post_compile
raise "post_compile hook ran"
end
end
end
end
let(:post_hook_resource) do
post_hook_type.new(:name => 'foo',:post => 'fake_value')
end
it "should call #post_compile on parameters that implement it" do
expect { post_hook_resource.finish }.to raise_error(RuntimeError, "post_compile hook ran")
end
end
it "should have a class method for converting a hash into a Puppet::Resource instance" do
expect(klass).to respond_to(:hash2resource)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_system_spec.rb | spec/unit/file_system_spec.rb | require 'spec_helper'
require 'puppet/file_system'
require 'puppet/util/platform'
describe "Puppet::FileSystem" do
include PuppetSpec::Files
# 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ۿᚠ𠜎
def with_file_content(content)
path = tmpfile('file-system')
file = File.new(path, 'wb')
file.sync = true
file.print content
yield path
ensure
file.close
end
SYSTEM_SID_BYTES = [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0]
def is_current_user_system?
SYSTEM_SID_BYTES == Puppet::Util::Windows::ADSI::User.current_user_sid.sid_bytes
end
def expects_public_file(path)
if Puppet::Util::Platform.windows?
current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
expect(sd.dacl).to contain_exactly(
an_object_having_attributes(sid: Puppet::Util::Windows::SID::LocalSystem, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinAdministrators, mask: 0x1f01ff),
an_object_having_attributes(sid: current_sid, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinUsers, mask: 0x120089)
)
else
expect(File.stat(path).mode & 07777).to eq(0644)
end
end
def expects_private_file(path)
if Puppet::Util::Platform.windows?
current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
expect(sd.dacl).to contain_exactly(
an_object_having_attributes(sid: Puppet::Util::Windows::SID::LocalSystem, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinAdministrators, mask: 0x1f01ff),
an_object_having_attributes(sid: current_sid, mask: 0x1f01ff)
)
else
expect(File.stat(path).mode & 07777).to eq(0640)
end
end
context "#open" do
it "uses the same default mode as File.open, when specifying a nil mode (umask used on non-Windows)" do
file = tmpfile('file_to_update')
expect(Puppet::FileSystem.exist?(file)).to be_falsey
Puppet::FileSystem.open(file, nil, 'a') { |fh| fh.write('') }
expected_perms = Puppet::Util::Platform.windows? ?
# default Windows mode based on temp file storage for SYSTEM user or regular user
# for Jenkins or other services running as SYSTEM writing to c:\windows\temp
# the permissions will typically be SYSTEM(F) / Administrators(F) which is 770
# but sometimes there are extra users like IIS_IUSRS granted rights which adds the "extra ace" 2
# for local Administrators writing to their own temp folders under c:\users\USER
# they will have (F) for themselves, and Users will not have a permission, hence 700
(is_current_user_system? ? ['770', '2000770'] : '2000700') :
# or for *nix determine expected mode via bitwise AND complement of umask
(0100000 | 0666 & ~File.umask).to_s(8)
expect([expected_perms].flatten).to include(Puppet::FileSystem.stat(file).mode.to_s(8))
default_file = tmpfile('file_to_update2')
expect(Puppet::FileSystem.exist?(default_file)).to be_falsey
File.open(default_file, 'a') { |fh| fh.write('') }
# which matches the behavior of File.open
expect(Puppet::FileSystem.stat(file).mode).to eq(Puppet::FileSystem.stat(default_file).mode)
end
it "can accept an octal mode integer" do
file = tmpfile('file_to_update')
# NOTE: 777 here returns 755, but due to Ruby?
Puppet::FileSystem.open(file, 0444, 'a') { |fh| fh.write('') }
# Behavior may change in the future on Windows, to *actually* change perms
# but for now, setting a mode doesn't touch them
expected_perms = Puppet::Util::Platform.windows? ?
(is_current_user_system? ? ['770', '2000770'] : '2000700') :
'100444'
expect([expected_perms].flatten).to include(Puppet::FileSystem.stat(file).mode.to_s(8))
expected_ruby_mode = Puppet::Util::Platform.windows? ?
# The Windows behavior has been changed to ignore the mode specified by open
# given it's unlikely a caller expects Windows file attributes to be set
# therefore mode is explicitly not managed (until PUP-6959 is fixed)
#
# In default Ruby on Windows a mode controls file attribute setting
# (like archive, read-only, etc)
# The GetFileInformationByHandle API returns an attributes value that is
# a bitmask of Windows File Attribute Constants at
# https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx
'100644' :
# On other platforms, the mode should be what was set by octal 0444
'100444'
expect(File.stat(file).mode.to_s(8)).to eq(expected_ruby_mode)
end
it "cannot accept a mode string" do
file = tmpfile('file_to_update')
expect {
Puppet::FileSystem.open(file, "444", 'a') { |fh| fh.write('') }
}.to raise_error(TypeError)
end
it "opens, creates ands allows updating of a new file, using by default, the external system encoding" do
begin
original_encoding = Encoding.default_external
# this must be set through Ruby API and cannot be mocked - it sets internal state used by File.open
# pick a bizarre encoding unlikely to be used in any real tests
Encoding.default_external = Encoding::CP737
file = tmpfile('file_to_update')
# test writing a UTF-8 string when Default external encoding is something different
Puppet::FileSystem.open(file, 0660, 'w') do |fh|
# note Ruby behavior which has no external_encoding, but implicitly uses Encoding.default_external
expect(fh.external_encoding).to be_nil
# write a UTF-8 string to this file
fh.write(mixed_utf8)
end
# prove that Ruby implicitly converts read strings back to Encoding.default_external
# and that it did that in the previous write
written = Puppet::FileSystem.read(file)
expect(written.encoding).to eq(Encoding.default_external)
expect(written).to eq(mixed_utf8.force_encoding(Encoding.default_external))
ensure
# carefully roll back to the previous
Encoding.default_external = original_encoding
end
end
end
context "#exclusive_open" do
it "opens ands allows updating of an existing file" do
file = file_containing("file_to_update", "the contents")
Puppet::FileSystem.exclusive_open(file, 0660, 'r+') do |fh|
old = fh.read
fh.truncate(0)
fh.rewind
fh.write("updated #{old}")
end
expect(Puppet::FileSystem.read(file)).to eq("updated the contents")
end
it "opens, creates ands allows updating of a new file, using by default, the external system encoding" do
begin
original_encoding = Encoding.default_external
# this must be set through Ruby API and cannot be mocked - it sets internal state used by File.open
# pick a bizarre encoding unlikely to be used in any real tests
Encoding.default_external = Encoding::CP737
file = tmpfile('file_to_update')
# test writing a UTF-8 string when Default external encoding is something different
Puppet::FileSystem.exclusive_open(file, 0660, 'w') do |fh|
# note Ruby behavior which has no external_encoding, but implicitly uses Encoding.default_external
expect(fh.external_encoding).to be_nil
# write a UTF-8 string to this file
fh.write(mixed_utf8)
end
# prove that Ruby implicitly converts read strings back to Encoding.default_external
# and that it did that in the previous write
written = Puppet::FileSystem.read(file)
expect(written.encoding).to eq(Encoding.default_external)
expect(written).to eq(mixed_utf8.force_encoding(Encoding.default_external))
ensure
# carefully roll back to the previous
Encoding.default_external = original_encoding
end
end
it "excludes other processes from updating at the same time",
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
file = file_containing("file_to_update", "0")
increment_counter_in_multiple_processes(file, 5, 'r+')
expect(Puppet::FileSystem.read(file)).to eq("5")
end
it "excludes other processes from updating at the same time even when creating the file",
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
file = tmpfile("file_to_update")
increment_counter_in_multiple_processes(file, 5, 'a+')
expect(Puppet::FileSystem.read(file)).to eq("5")
end
it "times out if the lock cannot be acquired in a specified amount of time",
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
file = tmpfile("file_to_update")
child = spawn_process_that_locks(file)
expect do
Puppet::FileSystem.exclusive_open(file, 0666, 'a', 0.1) do |f|
end
end.to raise_error(Timeout::Error, /Timeout waiting for exclusive lock on #{file}/)
Process.kill(9, child)
end
def spawn_process_that_locks(file)
read, write = IO.pipe
child = Kernel.fork do
read.close
Puppet::FileSystem.exclusive_open(file, 0666, 'a') do |fh|
write.write(true)
write.close
sleep 10
end
end
write.close
read.read
read.close
child
end
def increment_counter_in_multiple_processes(file, num_procs, options)
children = []
num_procs.times do
children << Kernel.fork do
Puppet::FileSystem.exclusive_open(file, 0660, options) do |fh|
fh.rewind
contents = (fh.read || 0).to_i
fh.truncate(0)
fh.rewind
fh.write((contents + 1).to_s)
end
exit(0)
end
end
children.each { |pid| Process.wait(pid) }
end
end
context "read_preserve_line_endings" do
it "should read a file with line feed" do
with_file_content("file content \n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \n")
end
end
it "should read a file with carriage return line feed" do
with_file_content("file content \r\n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \r\n")
end
end
it "should read a mixed file using only the first line newline when lf" do
with_file_content("file content \nsecond line \r\n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \nsecond line \r\n")
end
end
it "should read a mixed file using only the first line newline when crlf" do
with_file_content("file content \r\nsecond line \n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \r\nsecond line \n")
end
end
it "should ignore leading BOM" do
with_file_content("\uFEFFfile content \n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \n")
end
end
it "should not warn about misusage of BOM with non-UTF encoding" do
allow(Encoding).to receive(:default_external).and_return(Encoding::US_ASCII)
with_file_content("file content \n") do |file|
expect{ Puppet::FileSystem.read_preserve_line_endings(file) }.not_to output(/BOM with non-UTF encoding US-ASCII is nonsense/).to_stderr
end
end
end
context "read without an encoding specified" do
it "returns strings as Encoding.default_external" do
temp_file = file_containing('test.txt', 'hello world')
contents = Puppet::FileSystem.read(temp_file)
expect(contents.encoding).to eq(Encoding.default_external)
expect(contents).to eq('hello world')
end
end
context "read should allow an encoding to be specified" do
# First line of Rune version of Rune poem at http://www.columbia.edu/~fdc/utf8/
# characters chosen since they will not parse on Windows with codepage 437 or 1252
# Section 3.2.1.3 of Ruby spec guarantees that \u strings are encoded as UTF-8
let (:rune_utf8) { "\u16A0\u16C7\u16BB" } # 'ᚠᛇᚻ'
it "and should read a UTF8 file properly" do
temp_file = file_containing('utf8.txt', rune_utf8)
contents = Puppet::FileSystem.read(temp_file, :encoding => 'utf-8')
expect(contents.encoding).to eq(Encoding::UTF_8)
expect(contents).to eq(rune_utf8)
end
it "does not strip the UTF8 BOM (Byte Order Mark) if present in a file" do
bom = "\uFEFF"
temp_file = file_containing('utf8bom.txt', "#{bom}#{rune_utf8}")
contents = Puppet::FileSystem.read(temp_file, :encoding => 'utf-8')
expect(contents.encoding).to eq(Encoding::UTF_8)
expect(contents).to eq("#{bom}#{rune_utf8}")
end
end
describe "symlink",
:if => ! Puppet.features.manages_symlinks? &&
Puppet::Util::Platform.windows? do
let(:file) { tmpfile("somefile") }
let(:missing_file) { tmpfile("missingfile") }
let(:expected_msg) { "This version of Windows does not support symlinks. Windows Vista / 2008 or higher is required." }
before :each do
FileUtils.touch(file)
end
it "should raise an error when trying to create a symlink" do
expect { Puppet::FileSystem.symlink(file, 'foo') }.to raise_error(Puppet::Util::Windows::Error)
end
it "should return false when trying to check if a path is a symlink" do
expect(Puppet::FileSystem.symlink?(file)).to be_falsey
end
it "should raise an error when trying to read a symlink" do
expect { Puppet::FileSystem.readlink(file) }.to raise_error(Puppet::Util::Windows::Error)
end
it "should return a File::Stat instance when calling stat on an existing file" do
expect(Puppet::FileSystem.stat(file)).to be_instance_of(File::Stat)
end
it "should raise Errno::ENOENT when calling stat on a missing file" do
expect { Puppet::FileSystem.stat(missing_file) }.to raise_error(Errno::ENOENT)
end
it "should fall back to stat when trying to lstat a file" do
expect(Puppet::Util::Windows::File).to receive(:stat).with(Puppet::FileSystem.assert_path(file))
Puppet::FileSystem.lstat(file)
end
end
describe "symlink", :if => Puppet.features.manages_symlinks? do
let(:file) { tmpfile("somefile") }
let(:missing_file) { tmpfile("missingfile") }
let(:dir) { tmpdir("somedir") }
before :each do
FileUtils.touch(file)
end
it "should return true for exist? on a present file" do
expect(Puppet::FileSystem.exist?(file)).to be_truthy
end
it "should return true for file? on a present file" do
expect(Puppet::FileSystem.file?(file)).to be_truthy
end
it "should return false for exist? on a non-existent file" do
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
end
it "should return true for exist? on a present directory" do
expect(Puppet::FileSystem.exist?(dir)).to be_truthy
end
it "should return false for exist? on a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
it "should return true for exist? on valid symlinks" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target).to_s}_link")
Puppet::FileSystem.symlink(target, symlink)
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_truthy
end
end
it "should return false for exist? when resolving a cyclic symlink chain" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
# point symlink3 -> symlink2
symlink3 = tmpfile("somefile_link3")
Puppet::FileSystem.symlink(symlink2, symlink3)
# yank file, temporarily dangle
::File.delete(file)
# and trash it so that we can recreate it OK on windows
Puppet::FileSystem.unlink(symlink)
# point symlink -> symlink3 to create a cycle
Puppet::FileSystem.symlink(symlink3, symlink)
expect(Puppet::FileSystem.exist?(symlink3)).to be_falsey
end
it "should return true for exist? when resolving a symlink chain pointing to a file" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
# point symlink3 -> symlink2
symlink3 = tmpfile("somefile_link3")
Puppet::FileSystem.symlink(symlink2, symlink3)
expect(Puppet::FileSystem.exist?(symlink3)).to be_truthy
end
it "should return false for exist? when resolving a symlink chain that dangles" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
# point symlink3 -> symlink2
symlink3 = tmpfile("somefile_link3")
Puppet::FileSystem.symlink(symlink2, symlink3)
# yank file, and make symlink dangle
::File.delete(file)
# symlink3 is now indirectly dangled
expect(Puppet::FileSystem.exist?(symlink3)).to be_falsey
end
it "should not create a symlink when the :noop option is specified" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink, { :noop => true })
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
it "should raise Errno::EEXIST if trying to create a file / directory symlink when the symlink path already exists as a file" do
existing_file = tmpfile("#{Puppet::FileSystem.basename(file)}_link")
FileUtils.touch(existing_file)
[file, dir].each do |target|
expect { Puppet::FileSystem.symlink(target, existing_file) }.to raise_error(Errno::EEXIST)
expect(Puppet::FileSystem.exist?(existing_file)).to be_truthy
expect(Puppet::FileSystem.symlink?(existing_file)).to be_falsey
end
end
it "should silently fail if trying to create a file / directory symlink when the symlink path already exists as a directory" do
existing_dir = tmpdir("#{Puppet::FileSystem.basename(file)}_dir")
[file, dir].each do |target|
expect(Puppet::FileSystem.symlink(target, existing_dir)).to eq(0)
expect(Puppet::FileSystem.exist?(existing_dir)).to be_truthy
expect(File.directory?(existing_dir)).to be_truthy
expect(Puppet::FileSystem.symlink?(existing_dir)).to be_falsey
end
end
it "should silently fail to modify an existing directory symlink to reference a new file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_dir")
symlink = tmpfile("#{Puppet::FileSystem.basename(existing_dir)}_link")
Puppet::FileSystem.symlink(existing_dir, symlink)
expect(Puppet::FileSystem.readlink(symlink)).to eq(Puppet::FileSystem.path_string(existing_dir))
# now try to point it at the new target, no error raised, but file system unchanged
expect(Puppet::FileSystem.symlink(target, symlink)).to eq(0)
expect(Puppet::FileSystem.readlink(symlink)).to eq(existing_dir.to_s)
end
end
it "should raise Errno::EEXIST if trying to modify a file symlink to reference a new file or directory" do
symlink = tmpfile("#{Puppet::FileSystem.basename(file)}_link")
file_2 = tmpfile("#{Puppet::FileSystem.basename(file)}_2")
FileUtils.touch(file_2)
# symlink -> file_2
Puppet::FileSystem.symlink(file_2, symlink)
[file, dir].each do |target|
expect { Puppet::FileSystem.symlink(target, symlink) }.to raise_error(Errno::EEXIST)
expect(Puppet::FileSystem.readlink(symlink)).to eq(file_2.to_s)
end
end
it "should delete the existing file when creating a file / directory symlink with :force when the symlink path exists as a file" do
[file, dir].each do |target|
existing_file = tmpfile("#{Puppet::FileSystem.basename(target)}_existing")
FileUtils.touch(existing_file)
expect(Puppet::FileSystem.symlink?(existing_file)).to be_falsey
Puppet::FileSystem.symlink(target, existing_file, { :force => true })
expect(Puppet::FileSystem.symlink?(existing_file)).to be_truthy
expect(Puppet::FileSystem.readlink(existing_file)).to eq(target.to_s)
end
end
it "should modify an existing file symlink when using :force to reference a new file or directory" do
[file, dir].each do |target|
existing_file = tmpfile("#{Puppet::FileSystem.basename(target)}_existing")
FileUtils.touch(existing_file)
existing_symlink = tmpfile("#{Puppet::FileSystem.basename(existing_file)}_link")
Puppet::FileSystem.symlink(existing_file, existing_symlink)
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_file.to_s)
Puppet::FileSystem.symlink(target, existing_symlink, { :force => true })
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(target.to_s)
end
end
it "should silently fail if trying to overwrite an existing directory with a new symlink when using :force to reference a file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_existing")
expect(Puppet::FileSystem.symlink(target, existing_dir, { :force => true })).to eq(0)
expect(Puppet::FileSystem.symlink?(existing_dir)).to be_falsey
end
end
it "should silently fail if trying to modify an existing directory symlink when using :force to reference a new file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_existing")
existing_symlink = tmpfile("#{Puppet::FileSystem.basename(existing_dir)}_link")
Puppet::FileSystem.symlink(existing_dir, existing_symlink)
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_dir.to_s)
expect(Puppet::FileSystem.symlink(target, existing_symlink, { :force => true })).to eq(0)
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_dir.to_s)
end
end
it "should accept a string, Pathname or object with to_str (Puppet::Util::WatchedFile) for exist?" do
[ tmpfile('bogus1'),
Pathname.new(tmpfile('bogus2')),
Puppet::Util::WatchedFile.new(tmpfile('bogus3'))
].each { |f| expect(Puppet::FileSystem.exist?(f)).to be_falsey }
end
it "should return a File::Stat instance when calling stat on an existing file" do
expect(Puppet::FileSystem.stat(file)).to be_instance_of(File::Stat)
end
it "should raise Errno::ENOENT when calling stat on a missing file" do
expect { Puppet::FileSystem.stat(missing_file) }.to raise_error(Errno::ENOENT)
end
it "should be able to create a symlink, and verify it with symlink?" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
expect(Puppet::FileSystem.symlink?(symlink)).to be_truthy
end
it "should report symlink? as false on file, directory and missing files" do
[file, dir, missing_file].each do |f|
expect(Puppet::FileSystem.symlink?(f)).to be_falsey
end
end
it "should return a File::Stat with ftype 'link' when calling lstat on a symlink pointing to existing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
stat = Puppet::FileSystem.lstat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('link')
end
it "should return a File::Stat of ftype 'link' when calling lstat on a symlink pointing to missing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
stat = Puppet::FileSystem.lstat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('link')
end
it "should return a File::Stat of ftype 'file' when calling stat on a symlink pointing to existing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
stat = Puppet::FileSystem.stat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('file')
end
it "should return a File::Stat of ftype 'directory' when calling stat on a symlink pointing to existing directory" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(dir, symlink)
stat = Puppet::FileSystem.stat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('directory')
# on Windows, this won't get cleaned up if still linked
Puppet::FileSystem.unlink(symlink)
end
it "should return a File::Stat of ftype 'file' when calling stat on a symlink pointing to another symlink" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
expect(Puppet::FileSystem.stat(symlink2).ftype).to eq('file')
end
it "should raise Errno::ENOENT when calling stat on a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
expect { Puppet::FileSystem.stat(symlink) }.to raise_error(Errno::ENOENT)
end
it "should be able to readlink to resolve the physical path to a symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink)).to eq(file.to_s)
end
it "should not resolve entire symlink chain with readlink on a symlink'd symlink" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink2)).to eq(symlink.to_s)
end
it "should be able to readlink to resolve the physical path to a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
expect(Puppet::FileSystem.readlink(symlink)).to eq(missing_file.to_s)
end
it "should be able to unlink a dangling symlink pointed at a file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
::File.delete(file)
Puppet::FileSystem.unlink(symlink)
expect(Puppet::FileSystem).to_not be_exist(file)
expect(Puppet::FileSystem).to_not be_exist(symlink)
end
it "should be able to unlink a dangling symlink pointed at a directory" do
symlink = tmpfile("somedir_link")
Puppet::FileSystem.symlink(dir, symlink)
Dir.rmdir(dir)
Puppet::FileSystem.unlink(symlink)
expect(Puppet::FileSystem).to_not be_exist(dir)
expect(Puppet::FileSystem).to_not be_exist(symlink)
end
it "should delete only the symlink and not the target when calling unlink instance method" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink)
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink)).to eq(target.to_s)
expect(Puppet::FileSystem.unlink(symlink)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
it "should delete only the symlink and not the target when calling unlink class method" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink)
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink)).to eq(target.to_s)
expect(Puppet::FileSystem.unlink(symlink)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
describe "unlink" do
it "should delete files with unlink" do
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.unlink(file)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "should delete files with unlink class method" do
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.unlink(file)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "should delete multiple files with unlink class method" do
paths = (1..3).collect do |i|
f = tmpfile("somefile_#{i}")
FileUtils.touch(f)
expect(Puppet::FileSystem.exist?(f)).to be_truthy
f.to_s
end
expect(Puppet::FileSystem.unlink(*paths)).to eq(3) # count of files
paths.each { |p| expect(Puppet::FileSystem.exist?(p)).to be_falsey }
end
it "should raise Errno::EPERM or Errno::EISDIR when trying to delete a directory with the unlink class method" do
expect(Puppet::FileSystem.exist?(dir)).to be_truthy
ex = nil
begin
Puppet::FileSystem.unlink(dir)
rescue Exception => e
ex = e
end
expect([
Errno::EPERM, # Windows and OSX
Errno::EISDIR # Linux
]).to include(ex.class)
expect(Puppet::FileSystem.exist?(dir)).to be_truthy
end
it "should raise Errno::EACCESS when trying to delete a file whose parent directory does not allow execute/traverse", unless: Puppet::Util::Platform.windows? do
dir = tmpdir('file_system_unlink')
path = File.join(dir, 'deleteme')
mode = Puppet::FileSystem.stat(dir).mode
Puppet::FileSystem.chmod(0, dir)
begin
# JRuby 9.2.21.0 drops the path from the message..
message = Puppet::Util::Platform.jruby? ? /^Permission denied/ : /^Permission denied .* #{path}/
expect {
Puppet::FileSystem.unlink(path)
}.to raise_error(Errno::EACCES, message)
ensure
Puppet::FileSystem.chmod(mode, dir)
end
end
end
describe "exclusive_create" do
it "should create a file that doesn't exist" do
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
Puppet::FileSystem.exclusive_create(missing_file, nil) {}
expect(Puppet::FileSystem.exist?(missing_file)).to be_truthy
end
it "should raise Errno::EEXIST creating a file that does exist" do
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/puppet_spec.rb | spec/unit/puppet_spec.rb | require 'spec_helper'
require 'puppet'
require 'puppet_spec/files'
describe Puppet do
include PuppetSpec::Files
context "#version" do
it "should be valid semver" do
expect(SemanticPuppet::Version).to be_valid Puppet.version
end
end
Puppet::Util::Log.eachlevel do |level|
it "should have a method for sending '#{level}' logs" do
expect(Puppet).to respond_to(level)
end
end
it "should be able to change the path" do
newpath = ENV["PATH"] + File::PATH_SEPARATOR + "/something/else"
Puppet[:path] = newpath
expect(ENV["PATH"]).to eq(newpath)
end
it 'should propagate --modulepath to base environment' do
expect(Puppet::Node::Environment).to receive(:create).with(
be_a(Symbol), ['/my/modules'], Puppet::Node::Environment::NO_MANIFEST)
Puppet.base_context({
:environmentpath => '/envs',
:basemodulepath => '/base/modules',
:modulepath => '/my/modules'
})
end
it 'empty modulepath does not override basemodulepath' do
expect(Puppet::Node::Environment).to receive(:create).with(
be_a(Symbol), ['/base/modules'], Puppet::Node::Environment::NO_MANIFEST)
Puppet.base_context({
:environmentpath => '/envs',
:basemodulepath => '/base/modules',
:modulepath => ''
})
end
it 'nil modulepath does not override basemodulepath' do
expect(Puppet::Node::Environment).to receive(:create).with(
be_a(Symbol), ['/base/modules'], Puppet::Node::Environment::NO_MANIFEST)
Puppet.base_context({
:environmentpath => '/envs',
:basemodulepath => '/base/modules',
:modulepath => nil
})
end
context "Puppet::OLDEST_RECOMMENDED_RUBY_VERSION" do
it "should have an oldest recommended ruby version constant" do
expect(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION).not_to be_nil
end
it "should be a string" do
expect(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION).to be_a_kind_of(String)
end
it "should match a semver version" do
expect(SemanticPuppet::Version).to be_valid(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION)
end
end
context "Settings" do
before(:each) do
@old_settings = Puppet.settings
end
after(:each) do
Puppet.replace_settings_object(@old_settings)
end
it "should allow for settings to be redefined with a custom object" do
new_settings = double()
Puppet.replace_settings_object(new_settings)
expect(Puppet.settings).to eq(new_settings)
end
end
context 'when registering implementations' do
it 'does not register an implementation by default' do
Puppet.initialize_settings
expect(Puppet.runtime[:http]).to be_an_instance_of(Puppet::HTTP::Client)
end
it 'allows a http implementation to be registered' do
http_impl = double('http')
Puppet.initialize_settings([], true, true, http: http_impl)
expect(Puppet.runtime[:http]).to eq(http_impl)
end
it 'allows a facter implementation to be registered' do
facter_impl = double('facter')
Puppet.initialize_settings([], true, true, facter: facter_impl)
expect(Puppet.runtime[:facter]).to eq(facter_impl)
end
end
context "initializing $LOAD_PATH" do
it "should add libdir and module paths to the load path" do
libdir = tmpdir('libdir_test')
vendor_dir = tmpdir('vendor_modules')
module_libdir = File.join(vendor_dir, 'amodule_core', 'lib')
FileUtils.mkdir_p(module_libdir)
Puppet[:libdir] = libdir
Puppet[:vendormoduledir] = vendor_dir
Puppet.initialize_settings
expect($LOAD_PATH).to include(libdir)
expect($LOAD_PATH).to include(module_libdir)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/facter_impl_spec.rb | spec/unit/facter_impl_spec.rb | require 'spec_helper'
describe 'Puppet::FacterImpl' do
subject(:facter_impl) { Puppet::FacterImpl.new }
it { is_expected.to respond_to(:value) }
it { is_expected.to respond_to(:add) }
describe '.value' do
let(:method_name) { :value }
before { allow(Facter).to receive(method_name) }
it 'delegates to Facter API' do
facter_impl.value('test_fact')
expect(Facter).to have_received(method_name).with('test_fact')
end
end
describe '.add' do
let(:block) { Proc.new { setcode 'test' } }
let(:method_name) { :add }
before { allow(Facter).to receive(method_name) }
it 'delegates to Facter API' do
facter_impl.add('test_fact', &block)
expect(Facter).to have_received(method_name).with('test_fact', &block)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/configurer_spec.rb | spec/unit/configurer_spec.rb | require 'spec_helper'
require 'puppet/configurer'
describe Puppet::Configurer do
include PuppetSpec::Files
before do
Puppet[:server] = "puppetmaster"
Puppet[:report] = true
catalog.add_resource(resource)
Puppet[:lastrunfile] = file_containing('last_run_summary.yaml', <<~SUMMARY)
---
version:
config: 1624882680
puppet: #{Puppet.version}
application:
initial_environment: #{Puppet[:environment]}
converged_environment: #{Puppet[:environment]}
run_mode: agent
SUMMARY
end
let(:node_name) { Puppet[:node_name_value] }
let(:configurer) { Puppet::Configurer.new }
let(:report) { Puppet::Transaction::Report.new }
let(:catalog) { Puppet::Resource::Catalog.new(node_name, Puppet::Node::Environment.remote(Puppet[:environment].to_sym)) }
let(:resource) { Puppet::Resource.new(:notice, 'a') }
let(:facts) { Puppet::Node::Facts.new(node_name) }
describe "when executing a pre-run hook" do
it "should do nothing if the hook is set to an empty string" do
Puppet.settings[:prerun_command] = ""
expect(Puppet::Util::Execution).not_to receive(:execute)
configurer.execute_prerun_command
end
it "should execute any pre-run command provided via the 'prerun_command' setting" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
configurer.execute_prerun_command
end
it "should fail if the command fails" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer.execute_prerun_command).to be_falsey
end
end
describe "when executing a post-run hook" do
it "should do nothing if the hook is set to an empty string" do
Puppet.settings[:postrun_command] = ""
expect(Puppet::Util::Execution).not_to receive(:execute)
configurer.execute_postrun_command
end
it "should execute any post-run command provided via the 'postrun_command' setting" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
configurer.execute_postrun_command
end
it "should fail if the command fails" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer.execute_postrun_command).to be_falsey
end
end
describe "when executing a catalog run without stubbing valid_server_environment?" do
before do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
allow(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(catalog)
end
it 'skips initial plugin sync if environment is not found and no strict_environment_mode' do
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/plugins?}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
configurer.run(:pluginsync => true)
expect(@logs).to include(an_object_having_attributes(level: :notice, message: %r{Environment 'production' not found on server, skipping initial pluginsync.}))
expect(@logs).to include(an_object_having_attributes(level: :notice, message: /Applied catalog in .* seconds/))
end
it 'if strict_environment_mode is set and environment is not found, aborts the puppet run' do
Puppet[:strict_environment_mode] = true
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/plugins?}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
configurer.run(:pluginsync => true)
expect(@logs).to include(an_object_having_attributes(level: :err, message: %r{Failed to apply catalog: Environment 'production' not found on server, aborting run.}))
end
end
describe "when executing a catalog run" do
before do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
allow(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(catalog)
allow_any_instance_of(described_class).to(
receive(:valid_server_environment?).and_return(true)
)
end
it "downloads plugins when told" do
expect(configurer).to receive(:download_plugins)
configurer.run(:pluginsync => true)
end
it "does not download plugins when told" do
expect(configurer).not_to receive(:download_plugins)
configurer.run(:pluginsync => false)
end
it "does not download plugins when specified environment is not vaild on server" do
expect(configurer).to receive(:valid_server_environment?).and_return(false)
expect(configurer).not_to receive(:download_plugins)
configurer.run(:pluginsync => true)
end
it "fails the run if pluginsync fails when usecacheonfailure is false" do
Puppet[:ignore_plugin_errors] = false
# --test implies these, set them so we don't fall back to a cached catalog
Puppet[:use_cached_catalog] = false
Puppet[:usecacheonfailure] = false
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
stub_request(:get, %r{/puppet/v3/file_metadata/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
configurer.run(pluginsync: true)
expect(@logs).to include(an_object_having_attributes(level: :err, message: %r{Failed to apply catalog: Failed to retrieve pluginfacts: Could not retrieve information from environment production source\(s\) puppet:///pluginfacts}))
end
it "applies a cached catalog if pluginsync fails when usecacheonfailure is true" do
Puppet[:ignore_plugin_errors] = false
Puppet[:use_cached_catalog] = false
Puppet[:usecacheonfailure] = true
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
stub_request(:get, %r{/puppet/v3/file_metadata/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
expect(configurer.run(pluginsync: true, :report => report)).to eq(0)
expect(report.cached_catalog_status).to eq('on_failure')
end
it "applies a cached catalog when it can't connect to the master" do
error = Errno::ECONNREFUSED.new('Connection refused - connect(2)')
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(:ignore_cache => true)).and_raise(error)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(:ignore_terminus => true)).and_return(catalog)
expect(configurer.run).to eq(0)
end
it "should initialize a transaction report if one is not provided" do
# host and settings catalogs each create a report...
expect(Puppet::Transaction::Report).to receive(:new).and_return(report).twice
configurer.run
end
it "should respect node_name_fact when setting the host on a report" do
Puppet[:node_name_value] = nil
Puppet[:node_name_fact] = 'my_name_fact'
facts.values = {'my_name_fact' => 'node_name_from_fact'}
Puppet::Node::Facts.indirection.save(facts)
configurer.run(:report => report)
expect(report.host).to eq('node_name_from_fact')
end
it "should warn the user when the fact value length limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 1
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = { 'processors' => {
'isa' => "i386" }
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/Fact processors.isa with value i386 with the value length: 4 exceeds the value length limit: 1/)
configurer.run
end
it "should warn the user when the payload limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 1
facts.values = { 'processors' => {
'cores' => 1,
'count' => 2,
'isa' => "i386",
'models' => [
"CPU1 @ 2.80GHz"
],
'physicalcount' => 4 }
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/Payload with the current size of: \d* exceeds the payload size limit: \d*/)
configurer.run
end
it "should warn the user when the total number of facts limit is exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 1
Puppet[:payload_soft_limit] = 0
facts.values = {
'processors' => {
'cores' => 1,
'count' => 2,
'isa' => "i386",
'models' => [
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
{
'processors' => {
'cores' => [1,2]
}
}
],
'physicalcount' => 4
}
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/The current total number of fact values: [1-9]* exceeds the fact values limit: [1-9]*/)
configurer.run
end
it "should warn the user when the top level facts size limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 1
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = {'my_new_fact_name' => 'my_new_fact_value',
'my_new_fact_name2' => 'my_new_fact_value2'}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/The current number of top level facts: [1-9]* exceeds the top facts limit: [1-9]*/)
configurer.run
end
it "should warn the user when the fact name length limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 1
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = { 'processors' => {
'isa' => "i386" }
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/Fact processors.isa with length: 25 exceeds the fact name length limit: 1/)
configurer.run
end
it "shouldn't warn the user when the fact limit settings are set to 0" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = {'my_new_fact_name' => 'my_new_fact_value'}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).not_to receive(:warning)
configurer.run
end
it "creates a new report when applying the catalog" do
options = {}
configurer.run(options)
expect(options[:report].metrics['time']['catalog_application']).to be_an_instance_of(Float)
end
it "uses the provided report when applying the catalog" do
configurer.run(:report => report)
expect(report.metrics['time']['catalog_application']).to be_an_instance_of(Float)
end
it "should log a failure and do nothing if no catalog can be retrieved" do
expect(configurer).to receive(:retrieve_catalog).and_return(nil)
expect(Puppet).to receive(:err).with("Could not retrieve catalog; skipping run")
configurer.run
end
it "passes arbitrary options when applying the catalog" do
expect(catalog).to receive(:apply).with(hash_including(one: true))
configurer.run(catalog: catalog, one: true)
end
it "should benchmark how long it takes to apply the catalog" do
configurer.run(report: report)
expect(report.logs).to include(an_object_having_attributes(level: :notice, message: /Applied catalog in .* seconds/))
end
it "should create report with passed transaction_uuid and job_id" do
configurer = Puppet::Configurer.new("test_tuuid", "test_jid")
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).with(anything, anything, 'test_tuuid', 'test_jid', anything).and_return(report)
expect(configurer).to receive(:send_report).with(report)
configurer.run
end
it "should send the report" do
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect(configurer).to receive(:send_report).with(report)
expect(report.environment).to eq("test")
expect(report.transaction_uuid).to eq("aaaa")
configurer.run
end
it "should send the transaction report even if the catalog could not be retrieved" do
expect(configurer).to receive(:retrieve_catalog).and_return(nil)
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect(configurer).to receive(:send_report).with(report)
expect(report.environment).to eq("test")
expect(report.transaction_uuid).to eq("aaaa")
configurer.run
end
it "should send the transaction report even if there is a failure" do
expect(configurer).to receive(:retrieve_catalog).and_raise("whatever")
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect(configurer).to receive(:send_report).with(report)
expect(report.environment).to eq("test")
expect(report.transaction_uuid).to eq("aaaa")
expect(configurer.run).to be_nil
end
it "should remove the report as a log destination when the run is finished" do
configurer.run(report: report)
expect(Puppet::Util::Log.destinations).not_to include(report)
end
it "should return an exit status of 2 due to the notify resource 'changing'" do
cat = Puppet::Resource::Catalog.new("tester", Puppet::Node::Environment.remote(Puppet[:environment].to_sym))
cat.add_resource(Puppet::Type.type(:notify).new(:name => 'something changed'))
expect(configurer.run(catalog: cat, report: report)).to eq(2)
end
it "should return nil if catalog application fails" do
expect(catalog).to receive(:apply).and_raise(Puppet::Error, 'One or more resource dependency cycles detected in graph')
expect(configurer.run(catalog: catalog, report: report)).to be_nil
end
it "should send the transaction report even if the pre-run command fails" do
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer).to receive(:send_report).with(report)
expect(configurer.run).to be_nil
end
it "should include the pre-run command failure in the report" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer.run(report: report)).to be_nil
expect(report.logs.find { |x| x.message =~ /Could not run command from prerun_command/ }).to be
end
it "should send the transaction report even if the post-run command fails" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer).to receive(:send_report).with(report)
expect(configurer.run(report: report)).to be_nil
end
it "should include the post-run command failure in the report" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(report).to receive(:<<) { |log, _| expect(log.message).to match(/Could not run command from postrun_command/) }.at_least(:once)
expect(configurer.run(report: report)).to be_nil
end
it "should execute post-run command even if the pre-run command fails" do
Puppet.settings[:prerun_command] = "/my/precommand"
Puppet.settings[:postrun_command] = "/my/postcommand"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/precommand"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/postcommand"])
expect(configurer.run).to be_nil
end
it "should finalize the report" do
expect(report).to receive(:finalize_report)
configurer.run(report: report)
end
it "should not apply the catalog if the pre-run command fails" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect_any_instance_of(Puppet::Resource::Catalog).not_to receive(:apply)
expect(configurer).to receive(:send_report)
expect(configurer.run(report: report)).to be_nil
end
it "should apply the catalog, send the report, and return nil if the post-run command fails" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect_any_instance_of(Puppet::Resource::Catalog).to receive(:apply)
expect(configurer).to receive(:send_report)
expect(configurer.run(report: report)).to be_nil
end
it 'includes total time metrics in the report after successfully applying the catalog' do
configurer.run(report: report)
expect(report.metrics['time']).to be
expect(report.metrics['time']['total']).to be_a_kind_of(Numeric)
end
it 'includes total time metrics in the report even if prerun fails' do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
configurer.run(report: report)
expect(report.metrics['time']).to be
expect(report.metrics['time']['total']).to be_a_kind_of(Numeric)
end
it 'includes total time metrics in the report even if catalog retrieval fails' do
allow(configurer).to receive(:prepare_and_retrieve_catalog_from_cache).and_raise
configurer.run(:report => report)
expect(report.metrics['time']).to be
expect(report.metrics['time']['total']).to be_a_kind_of(Numeric)
end
it "should refetch the catalog if the server specifies a new environment in the catalog" do
catalog = Puppet::Resource::Catalog.new(node_name, Puppet::Node::Environment.remote('second_env'))
expect(configurer).to receive(:retrieve_catalog).and_return(catalog).twice
configurer.run
end
it "changes the configurer's environment if the server specifies a new environment in the catalog" do
allow_any_instance_of(Puppet::Resource::Catalog).to receive(:environment).and_return("second_env")
configurer.run
expect(configurer.environment).to eq("second_env")
end
it "changes the report's environment if the server specifies a new environment in the catalog" do
allow_any_instance_of(Puppet::Resource::Catalog).to receive(:environment).and_return("second_env")
configurer.run(report: report)
expect(report.environment).to eq("second_env")
end
it "sends the transaction uuid in a catalog request" do
configurer = Puppet::Configurer.new('aaa')
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(transaction_uuid: 'aaa'))
configurer.run
end
it "sends the transaction uuid in a catalog request" do
configurer = Puppet::Configurer.new('b', 'aaa')
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(job_id: 'aaa'))
configurer.run
end
it "sets the static_catalog query param to true in a catalog request" do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(static_catalog: true))
configurer.run
end
it "sets the checksum_type query param to the default supported_checksum_types in a catalog request" do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything,
hash_including(checksum_type: 'sha256.sha384.sha512.sha224.md5'))
configurer.run
end
it "sets the checksum_type query param to the supported_checksum_types setting in a catalog request" do
Puppet[:supported_checksum_types] = ['sha256']
# Regenerate the agent to pick up the new setting
configurer = Puppet::Configurer.new
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(checksum_type: 'sha256'))
configurer.run
end
describe "when not using a REST terminus for catalogs" do
it "should not pass any facts when retrieving the catalog" do
# This is weird, we collect facts when constructing the node,
# but we don't send them in the indirector request. Then the compiler
# looks up the node, and collects its facts, which we could have sent
# in the first place. This seems like a bug.
Puppet::Resource::Catalog.indirection.terminus_class = :compiler
expect(Puppet::Resource::Catalog.indirection).to receive(:find) do |name, options|
expect(options[:facts]).to be_nil
end.and_return(catalog)
configurer.run
end
end
describe "when using a REST terminus for catalogs" do
it "should pass the url encoded facts and facts format as arguments when retrieving the catalog" do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
facts.values = { 'foo' => 'bar' }
Puppet::Node::Facts.indirection.save(facts)
expect(
Puppet::Resource::Catalog.indirection
).to receive(:find) do |_, options|
expect(options[:facts_format]).to eq("application/json")
unescaped = JSON.parse(CGI.unescape(options[:facts]))
expect(unescaped).to include("values" => {"foo" => "bar"})
end.and_return(catalog)
configurer.run
end
end
end
describe "when sending a report" do
include PuppetSpec::Files
before do
Puppet[:lastrunfile] = tmpfile('last_run_file')
Puppet[:reports] = "none"
end
it "should print a report summary if configured to do so" do
Puppet.settings[:summarize] = true
expect(report).to receive(:summary).and_return("stuff")
expect(configurer).to receive(:puts).with("stuff")
configurer.send_report(report)
end
it "should not print a report summary if not configured to do so" do
Puppet.settings[:summarize] = false
expect(configurer).not_to receive(:puts)
configurer.send_report(report)
end
it "should save the report if reporting is enabled" do
Puppet.settings[:report] = true
expect(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, instance_of(Hash)).twice
configurer.send_report(report)
end
it "should not save the report if reporting is disabled" do
Puppet.settings[:report] = false
expect(Puppet::Transaction::Report.indirection).not_to receive(:save).with(report, nil, instance_of(Hash))
configurer.send_report(report)
end
it "should save the last run summary if reporting is enabled" do
Puppet.settings[:report] = true
expect(configurer).to receive(:save_last_run_summary).with(report)
configurer.send_report(report)
end
it "should save the last run summary if reporting is disabled" do
Puppet.settings[:report] = false
expect(configurer).to receive(:save_last_run_summary).with(report)
configurer.send_report(report)
end
it "should log but not fail if saving the report fails" do
Puppet.settings[:report] = true
expect(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_cache: true)).and_raise("whatever")
expect(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_terminus: true))
configurer.send_report(report)
expect(@logs).to include(an_object_having_attributes(level: :err, message: 'Could not send report: whatever'))
end
it "should save the cached report if fails to send the report" do
allow(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_terminus: true)).and_call_original
allow(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_cache: true)).and_raise("whatever")
expect(File).to_not be_exist(Puppet[:lastrunfile])
configurer.send_report(report)
expect(File.read(Puppet[:lastrunfile])).to match(/puppet: #{Puppet::PUPPETVERSION}/)
end
end
describe "when saving the summary report file" do
include PuppetSpec::Files
before do
Puppet[:lastrunfile] = tmpfile('last_run_file')
end
it "should write the last run file" do
configurer.save_last_run_summary(report)
expect(Puppet::FileSystem.exist?(Puppet[:lastrunfile])).to be_truthy
end
it "should write the raw summary as yaml" do
expect(report).to receive(:raw_summary).and_return("summary")
configurer.save_last_run_summary(report)
expect(File.read(Puppet[:lastrunfile])).to eq(YAML.dump("summary"))
end
it "should log but not fail if saving the last run summary fails" do
# The mock will raise an exception on any method used. This should
# simulate a nice hard failure from the underlying OS for us.
fh = Class.new(Object) do
def method_missing(*args)
raise "failed to do #{args[0]}"
end
end.new
expect(Puppet::Util).to receive(:replace_file).and_yield(fh)
configurer.save_last_run_summary(report)
expect(@logs).to include(an_object_having_attributes(level: :err, message: 'Could not save last run local report: failed to do print'))
end
it "should create the last run file with the correct mode" do
expect(Puppet.settings.setting(:lastrunfile)).to receive(:mode).and_return('664')
configurer.save_last_run_summary(report)
if Puppet::Util::Platform.windows?
require 'puppet/util/windows/security'
mode = Puppet::Util::Windows::Security.get_mode(Puppet[:lastrunfile])
else
mode = Puppet::FileSystem.stat(Puppet[:lastrunfile]).mode
end
expect(mode & 0777).to eq(0664)
end
it "should report invalid last run file permissions" do
expect(Puppet.settings.setting(:lastrunfile)).to receive(:mode).and_return('892')
configurer.save_last_run_summary(report)
expect(@logs).to include(an_object_having_attributes(level: :err, message: /Could not save last run local report.*892 is invalid/))
end
end
def expects_pluginsync
metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":420,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]"
stub_request(:get, %r{/puppet/v3/file_metadatas/(plugins|locales)}).to_return(status: 200, body: metadata, headers: {'Content-Type' => 'application/json'})
# response retains owner/group/mode due to source_permissions => use
facts_metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":500,\"group\":500,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]"
stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(status: 200, body: facts_metadata, headers: {'Content-Type' => 'application/json'})
end
def expects_new_catalog_only(catalog)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true, check_environment: true)).and_return(catalog)
expect(Puppet::Resource::Catalog.indirection).not_to receive(:find).with(anything, hash_including(ignore_terminus: true))
end
def expects_cached_catalog_only(catalog)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(catalog)
expect(Puppet::Resource::Catalog.indirection).not_to receive(:find).with(anything, hash_including(ignore_cache: true))
end
def expects_fallback_to_cached_catalog(catalog)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true)).and_return(nil)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(catalog)
end
def expects_fallback_to_new_catalog(catalog)
expects_pluginsync
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(nil)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true, check_environment: true)).and_return(catalog)
end
def expects_neither_new_or_cached_catalog
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true)).and_return(nil)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(nil)
end
describe "when retrieving a catalog" do
before do
allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class).and_return(:rest)
end
describe "and configured to only retrieve a catalog from the cache" do
before do
Puppet.settings[:use_cached_catalog] = true
end
it "should first look in the cache for a catalog" do
expects_cached_catalog_only(catalog)
configurer.run
end
it "should not pluginsync when a cached catalog is successfully retrieved" do
expects_cached_catalog_only(catalog)
expect(configurer).not_to receive(:download_plugins)
configurer.run
end
it "should set its cached_catalog_status to 'explicitly_requested'" do
expects_cached_catalog_only(catalog)
options = {}
configurer.run(options)
expect(options[:report].cached_catalog_status).to eq('explicitly_requested')
end
it "should set its cached_catalog_status to 'explicitly requested' if the cached catalog is from a different environment" do
cached_catalog = Puppet::Resource::Catalog.new(node_name, Puppet::Node::Environment.remote('second_env'))
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_spec.rb | spec/unit/module_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/module_tool/checksums'
describe Puppet::Module do
include PuppetSpec::Files
let(:env) { double("environment") }
let(:path) { "/path" }
let(:name) { "mymod" }
let(:mod) { Puppet::Module.new(name, path, env) }
before do
# This is necessary because of the extra checks we have for the deprecated
# 'plugins' directory
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
end
it "should have a class method that returns a named module from a given environment" do
env = Puppet::Node::Environment.create(:myenv, [])
expect(env).to receive(:module).with(name).and_return("yep")
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
expect(Puppet::Module.find(name, "myenv")).to eq("yep")
end
end
it "should return nil if asked for a named module that doesn't exist" do
env = Puppet::Node::Environment.create(:myenv, [])
expect(env).to receive(:module).with(name).and_return(nil)
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
expect(Puppet::Module.find(name, "myenv")).to be_nil
end
end
describe "is_module_directory?" do
let(:first_modulepath) { tmpdir('firstmodules') }
let(:not_a_module) { tmpfile('thereisnomodule', first_modulepath) }
it "should return false for a non-directory" do
expect(Puppet::Module.is_module_directory?('thereisnomodule', first_modulepath)).to be_falsey
end
it "should return true for a well named directories" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo2', first_modulepath)
PuppetSpec::Modules.generate_files('foo_bar', first_modulepath)
expect(Puppet::Module.is_module_directory?('foo', first_modulepath)).to be_truthy
expect(Puppet::Module.is_module_directory?('foo2', first_modulepath)).to be_truthy
expect(Puppet::Module.is_module_directory?('foo_bar', first_modulepath)).to be_truthy
end
it "should return false for badly named directories" do
PuppetSpec::Modules.generate_files('foo=bar', first_modulepath)
PuppetSpec::Modules.generate_files('.foo', first_modulepath)
expect(Puppet::Module.is_module_directory?('foo=bar', first_modulepath)).to be_falsey
expect(Puppet::Module.is_module_directory?('.foo', first_modulepath)).to be_falsey
end
end
describe "is_module_directory_name?" do
it "should return true for a valid directory module name" do
expect(Puppet::Module.is_module_directory_name?('foo')).to be_truthy
expect(Puppet::Module.is_module_directory_name?('foo2')).to be_truthy
expect(Puppet::Module.is_module_directory_name?('foo_bar')).to be_truthy
end
it "should return false for badly formed directory module names" do
expect(Puppet::Module.is_module_directory_name?('foo-bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo=bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo.bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('-foo')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo-')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo--bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('.foo')).to be_falsey
end
end
describe "is_module_namespaced_name?" do
it "should return true for a valid namespaced module name" do
expect(Puppet::Module.is_module_namespaced_name?('foo-bar')).to be_truthy
end
it "should return false for badly formed namespaced module names" do
expect(Puppet::Module.is_module_namespaced_name?('foo')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('.foo-bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo2')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo_bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo=bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo.bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('-foo')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo-')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo--bar')).to be_falsey
end
end
describe "attributes" do
it "should support a 'version' attribute" do
mod.version = 1.09
expect(mod.version).to eq(1.09)
end
it "should support a 'source' attribute" do
mod.source = "http://foo/bar"
expect(mod.source).to eq("http://foo/bar")
end
it "should support a 'project_page' attribute" do
mod.project_page = "http://foo/bar"
expect(mod.project_page).to eq("http://foo/bar")
end
it "should support an 'author' attribute" do
mod.author = "Luke Kanies <luke@madstop.com>"
expect(mod.author).to eq("Luke Kanies <luke@madstop.com>")
end
it "should support a 'license' attribute" do
mod.license = "GPL2"
expect(mod.license).to eq("GPL2")
end
it "should support a 'summary' attribute" do
mod.summary = "GPL2"
expect(mod.summary).to eq("GPL2")
end
it "should support a 'description' attribute" do
mod.description = "GPL2"
expect(mod.description).to eq("GPL2")
end
end
describe "when finding unmet dependencies" do
before do
allow(Puppet::FileSystem).to receive(:exist?).and_call_original
@modpath = tmpdir('modpath')
Puppet.settings[:modulepath] = @modpath
end
it "should resolve module dependencies using forge names" do
parent = PuppetSpec::Modules.create(
'parent',
@modpath,
:metadata => {
:author => 'foo',
:dependencies => [{
"name" => "foo/child"
}]
},
:environment => env
)
child = PuppetSpec::Modules.create(
'child',
@modpath,
:metadata => {
:author => 'foo',
:dependencies => []
},
:environment => env
)
expect(env).to receive(:module_by_forge_name).with('foo/child').and_return(child)
expect(parent.unmet_dependencies).to eq([])
end
it "should list modules that are missing" do
mod = PuppetSpec::Modules.create(
'needy',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
expect(env).to receive(:module_by_forge_name).with('baz/foobar').and_return(nil)
expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:name => "baz/foobar",
:version_constraint => ">= 2.2.0",
:parent => { :name => 'puppetlabs/needy', :version => 'v9.9.9' },
:mod_details => { :installed_version => nil }
}])
end
it "should list modules that are missing and have invalid names" do
mod = PuppetSpec::Modules.create(
'needy',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar=bar"
}]
},
:environment => env
)
expect(env).to receive(:module_by_forge_name).with('baz/foobar=bar').and_return(nil)
expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:name => "baz/foobar=bar",
:version_constraint => ">= 2.2.0",
:parent => { :name => 'puppetlabs/needy', :version => 'v9.9.9' },
:mod_details => { :installed_version => nil }
}])
end
it "should list modules with unmet version requirement" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
['test_gte_req', 'test_specific_req', 'foobar'].each do |mod_name|
mod_dir = "#{@modpath}/#{mod_name}"
metadata_file = "#{mod_dir}/metadata.json"
allow(Puppet::FileSystem).to receive(:exist?).with(metadata_file).and_return(true)
end
mod = PuppetSpec::Modules.create(
'test_gte_req',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
mod2 = PuppetSpec::Modules.create(
'test_specific_req',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => "1.0.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => { :version => '2.0.0', :author => 'baz' },
:environment => env
)
expect(mod.unmet_dependencies).to eq([{
:reason => :version_mismatch,
:name => "baz/foobar",
:version_constraint => ">= 2.2.0",
:parent => { :version => "v9.9.9", :name => "puppetlabs/test_gte_req" },
:mod_details => { :installed_version => "2.0.0" }
}])
expect(mod2.unmet_dependencies).to eq([{
:reason => :version_mismatch,
:name => "baz/foobar",
:version_constraint => "v1.0.0",
:parent => { :version => "v9.9.9", :name => "puppetlabs/test_specific_req" },
:mod_details => { :installed_version => "2.0.0" }
}])
end
it "should consider a dependency without a version requirement to be satisfied" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => [{
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:version => '2.0.0',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to be_empty
end
it "should consider a dependency without a semantic version to be unmet" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => [{
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:version => '5.1',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to eq([{
:reason => :non_semantic_version,
:parent => { :version => "v9.9.9", :name => "puppetlabs/foobar" },
:mod_details => { :installed_version => "5.1" },
:name => "baz/foobar",
:version_constraint => ">= 0.0.0"
}])
end
it "should have valid dependencies when no dependencies have been specified" do
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => []
}
)
expect(mod.unmet_dependencies).to eq([])
end
it "should throw an error if invalid dependencies are specified" do
expect {
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => ""
}
)
}.to raise_error(
Puppet::Module::MissingMetadata,
/dependencies in the file metadata.json of the module foobar must be an array, not: ''/)
end
it "should only list unmet dependencies" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
name,
@modpath,
:metadata => {
:dependencies => [
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/satisfied"
},
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/notsatisfied"
}
]
},
:environment => env
)
PuppetSpec::Modules.create(
'satisfied',
@modpath,
:metadata => {
:version => '3.3.0',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:mod_details => { :installed_version => nil },
:parent => { :version => "v9.9.9", :name => "puppetlabs/#{name}" },
:name => "baz/notsatisfied",
:version_constraint => ">= 2.2.0"
}])
end
it "should be empty when all dependencies are met" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'mymod2',
@modpath,
:metadata => {
:dependencies => [
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/satisfied"
},
{
"version_requirement" => "< 2.2.0",
"name" => "baz/alsosatisfied"
}
]
},
:environment => env
)
PuppetSpec::Modules.create(
'satisfied',
@modpath,
:metadata => {
:version => '3.3.0',
:author => 'baz'
},
:environment => env
)
PuppetSpec::Modules.create(
'alsosatisfied',
@modpath,
:metadata => {
:version => '2.1.0',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to be_empty
end
end
describe "when managing supported platforms" do
it "should support specifying a supported platform" do
mod.supports "solaris"
end
it "should support specifying a supported platform and version" do
mod.supports "solaris", 1.0
end
end
it "should return nil if asked for a module whose name is 'nil'" do
expect(Puppet::Module.find(nil, "myenv")).to be_nil
end
it "should provide support for logging" do
expect(Puppet::Module.ancestors).to be_include(Puppet::Util::Logging)
end
it "should be able to be converted to a string" do
expect(mod.to_s).to eq("Module #{name}(#{path})")
end
it "should fail if its name is not alphanumeric" do
expect { Puppet::Module.new(".something", "/path", env) }.to raise_error(Puppet::Module::InvalidName)
end
it "should require a name at initialization" do
expect { Puppet::Module.new }.to raise_error(ArgumentError)
end
it "should accept an environment at initialization" do
expect(Puppet::Module.new("foo", "/path", env).environment).to eq(env)
end
describe '#modulepath' do
it "should return the directory the module is installed in, if a path exists" do
mod = Puppet::Module.new("foo", "/a/foo", env)
expect(mod.modulepath).to eq('/a')
end
end
[:plugins, :pluginfacts, :templates, :files, :manifests, :scripts].each do |filetype|
case filetype
when :plugins
dirname = "lib"
when :pluginfacts
dirname = "facts.d"
else
dirname = filetype.to_s
end
it "should be able to return individual #{filetype}" do
module_file = File.join(path, dirname, "my/file")
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(true)
expect(mod.send(filetype.to_s.sub(/s$/, ''), "my/file")).to eq(module_file)
end
it "should consider #{filetype} to be present if their base directory exists" do
module_file = File.join(path, dirname)
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(true)
expect(mod.send(filetype.to_s + "?")).to be_truthy
end
it "should consider #{filetype} to be absent if their base directory does not exist" do
module_file = File.join(path, dirname)
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(false)
expect(mod.send(filetype.to_s + "?")).to be_falsey
end
it "should return nil if asked to return individual #{filetype} that don't exist" do
module_file = File.join(path, dirname, "my/file")
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(false)
expect(mod.send(filetype.to_s.sub(/s$/, ''), "my/file")).to be_nil
end
it "should return the base directory if asked for a nil path" do
base = File.join(path, dirname)
expect(Puppet::FileSystem).to receive(:exist?).with(base).and_return(true)
expect(mod.send(filetype.to_s.sub(/s$/, ''), nil)).to eq(base)
end
end
it "should return the path to the plugin directory" do
expect(mod.plugin_directory).to eq(File.join(path, "lib"))
end
it "should return the path to the tasks directory" do
expect(mod.tasks_directory).to eq(File.join(path, "tasks"))
end
it "should return the path to the plans directory" do
expect(mod.plans_directory).to eq(File.join(path, "plans"))
end
describe "when finding tasks" do
before do
allow(Puppet::FileSystem).to receive(:exist?).and_call_original
@modpath = tmpdir('modpath')
Puppet.settings[:modulepath] = @modpath
end
it "should have an empty array for the tasks when the tasks directory does not exist" do
mod = PuppetSpec::Modules.create('tasks_test_nodir', @modpath, :environment => env)
expect(mod.tasks).to eq([])
end
it "should have an empty array for the tasks when the tasks directory does exist and is empty" do
mod = PuppetSpec::Modules.create('tasks_test_empty', @modpath, {:environment => env,
:tasks => []})
expect(mod.tasks).to eq([])
end
it "should list the expected tasks when the required files exist" do
fake_tasks = [['task1'], ['task2.sh', 'task2.json']]
mod = PuppetSpec::Modules.create('tasks_smoke', @modpath, {:environment => env,
:tasks => fake_tasks})
expect(mod.tasks.count).to eq(2)
expect(mod.tasks.map{|t| t.name}.sort).to eq(['tasks_smoke::task1', 'tasks_smoke::task2'])
expect(mod.tasks.map{|t| t.class}).to eq([Puppet::Module::Task] * 2)
end
it "should be able to find individual task files when they exist" do
task_exe = 'stateskatetask.stk'
mod = PuppetSpec::Modules.create('task_file_smoke', @modpath, {:environment => env,
:tasks => [[task_exe]]})
expect(mod.task_file(task_exe)).to eq("#{mod.path}/tasks/#{task_exe}")
end
it "should list files from the scripts directory if required by the task" do
mod = 'loads_scripts'
task_dep = 'myscript.sh'
script_ref = "#{mod}/scripts/#{task_dep}"
task_json = JSON.generate({'files' => [script_ref]})
task = [['task', { name: 'task.json', content: task_json }]]
mod = PuppetSpec::Modules.create(mod, @modpath, {:environment => env,
:scripts => [task_dep],
:tasks => task})
expect(mod.tasks.first.files).to include({'name' => script_ref,
'path' => /#{script_ref}/})
end
it "should return nil when asked for an individual task file if it does not exist" do
mod = PuppetSpec::Modules.create('task_file_neg', @modpath, {:environment => env,
:tasks => []})
expect(mod.task_file('nosuchtask')).to be_nil
end
describe "does the task finding" do
let(:mod_name) { 'tasks_test_lazy' }
let(:mod_tasks_dir) { File.join(@modpath, mod_name, 'tasks') }
it "after the module is initialized" do
expect(Puppet::FileSystem).not_to receive(:exist?).with(mod_tasks_dir)
expect(Puppet::Module::Task).not_to receive(:tasks_in_module)
Puppet::Module.new(mod_name, @modpath, env)
end
it "when the tasks method is called" do
expect(Puppet::Module::Task).to receive(:tasks_in_module)
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:tasks => [['itascanstaccatotask']]})
mod.tasks
end
it "only once for the lifetime of the module object" do
expect(Dir).to receive(:glob).with("#{mod_tasks_dir}/*").once.and_return(['allalaskataskattacktactics'])
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:tasks => []})
mod.tasks
mod.tasks
end
end
end
describe "when finding plans" do
before do
allow(Puppet::FileSystem).to receive(:exist?).and_call_original
@modpath = tmpdir('modpath')
Puppet.settings[:modulepath] = @modpath
end
it "should have an empty array for the plans when the plans directory does not exist" do
mod = PuppetSpec::Modules.create('plans_test_nodir', @modpath, :environment => env)
expect(mod.plans).to eq([])
end
it "should have an empty array for the plans when the plans directory does exist and is empty" do
mod = PuppetSpec::Modules.create('plans_test_empty', @modpath, {:environment => env,
:plans => []})
expect(mod.plans).to eq([])
end
it "should list the expected plans when the required files exist" do
fake_plans = ['plan1.pp', 'plan2.yaml']
mod = PuppetSpec::Modules.create('plans_smoke', @modpath, {:environment => env,
:plans => fake_plans})
expect(mod.plans.count).to eq(2)
expect(mod.plans.map{|t| t.name}.sort).to eq(['plans_smoke::plan1', 'plans_smoke::plan2'])
expect(mod.plans.map{|t| t.class}).to eq([Puppet::Module::Plan] * 2)
end
it "should be able to find individual plan files when they exist" do
plan_exe = 'stateskateplan.pp'
mod = PuppetSpec::Modules.create('plan_file_smoke', @modpath, {:environment => env,
:plans => [plan_exe]})
expect(mod.plan_file(plan_exe)).to eq("#{mod.path}/plans/#{plan_exe}")
end
it "should return nil when asked for an individual plan file if it does not exist" do
mod = PuppetSpec::Modules.create('plan_file_neg', @modpath, {:environment => env,
:plans => []})
expect(mod.plan_file('nosuchplan')).to be_nil
end
describe "does the plan finding" do
let(:mod_name) { 'plans_test_lazy' }
let(:mod_plans_dir) { File.join(@modpath, mod_name, 'plans') }
it "after the module is initialized" do
expect(Puppet::FileSystem).not_to receive(:exist?).with(mod_plans_dir)
expect(Puppet::Module::Plan).not_to receive(:plans_in_module)
Puppet::Module.new(mod_name, @modpath, env)
end
it "when the plans method is called" do
expect(Puppet::Module::Plan).to receive(:plans_in_module)
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:plans => ['itascanstaccatoplan.yaml']})
mod.plans
end
it "only once for the lifetime of the module object" do
expect(Dir).to receive(:glob).with("#{mod_plans_dir}/*").once.and_return(['allalaskaplanattacktactics'])
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:plans => []})
mod.plans
mod.plans
end
end
end
end
describe Puppet::Module, "when finding matching manifests" do
before do
@mod = Puppet::Module.new("mymod", "/a", double("environment"))
@pq_glob_with_extension = "yay/*.xx"
@fq_glob_with_extension = "/a/manifests/#{@pq_glob_with_extension}"
end
it "should return all manifests matching the glob pattern" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return(%w{foo bar})
allow(FileTest).to receive(:directory?).and_return(false)
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{foo bar})
end
it "should not return directories" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return(%w{foo bar})
expect(FileTest).to receive(:directory?).with("foo").and_return(false)
expect(FileTest).to receive(:directory?).with("bar").and_return(true)
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{foo})
end
it "should default to the 'init' file if no glob pattern is specified" do
expect(Puppet::FileSystem).to receive(:exist?).with("/a/manifests/init.pp").and_return(true)
expect(@mod.match_manifests(nil)).to eq(%w{/a/manifests/init.pp})
end
it "should return all manifests matching the glob pattern in all existing paths" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return(%w{a b})
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{a b})
end
it "should match the glob pattern plus '.pp' if no extension is specified" do
expect(Dir).to receive(:glob).with("/a/manifests/yay/foo.pp").and_return(%w{yay})
expect(@mod.match_manifests("yay/foo")).to eq(%w{yay})
end
it "should return an empty array if no manifests matched" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return([])
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq([])
end
it "should raise an error if the pattern tries to leave the manifest directory" do
expect do
@mod.match_manifests("something/../../*")
end.to raise_error(Puppet::Module::InvalidFilePattern, 'The pattern "something/../../*" to find manifests in the module "mymod" is invalid and potentially unsafe.')
end
end
describe Puppet::Module do
include PuppetSpec::Files
let!(:modpath) do
path = tmpdir('modpath')
PuppetSpec::Modules.create('mymod', path)
path
end
let!(:mymodpath) { File.join(modpath, 'mymod') }
let!(:mymod_metadata) { File.join(mymodpath, 'metadata.json') }
let(:mymod) { Puppet::Module.new('mymod', mymodpath, nil) }
it "should use 'License' in its current path as its metadata file" do
expect(mymod.license_file).to eq("#{modpath}/mymod/License")
end
it "should cache the license file" do
expect(mymod).to receive(:path).once.and_return(nil)
mymod.license_file
mymod.license_file
end
it "should use 'metadata.json' in its current path as its metadata file" do
expect(mymod_metadata).to eq("#{modpath}/mymod/metadata.json")
end
it "should not have metadata if it has a metadata file and its data is valid but empty json hash" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return("{}")
expect(mymod).not_to be_has_metadata
end
it "should not have metadata if it has a metadata file and its data is empty" do
Puppet[:strict] = :warning
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return("")
expect(mymod).not_to be_has_metadata
end
it "should not have metadata if has a metadata file and its data is invalid" do
Puppet[:strict] = :warning
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return("This is some invalid json.\n")
expect(mymod).not_to be_has_metadata
end
it "should know if it is missing a metadata file" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
expect(mymod).not_to be_has_metadata
end
it "should be able to parse its metadata file" do
expect(mymod).to respond_to(:load_metadata)
end
it "should parse its metadata file on initialization if it is present" do
expect_any_instance_of(Puppet::Module).to receive(:load_metadata)
Puppet::Module.new("yay", "/path", double("env"))
end
describe 'when --strict is warning' do
before :each do
Puppet[:strict] = :warning
end
it "should warn about a failure to parse" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect(mymod.has_metadata?).to be_falsey
expect(@logs).to have_matching_log(/mymod has an invalid and unparsable metadata\.json file/)
end
end
describe 'when --strict is off' do
before :each do
Puppet[:strict] = :off
end
it "should not warn about a failure to parse" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect(mymod.has_metadata?).to be_falsey
expect(@logs).to_not have_matching_log(/mymod has an invalid and unparsable metadata\.json file.*/)
end
it "should log debug output about a failure to parse when --debug is on" do
Puppet[:log_level] = :debug
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect(mymod.has_metadata?).to be_falsey
expect(@logs).to have_matching_log(/mymod has an invalid and unparsable metadata\.json file.*/)
end
end
describe 'when --strict is error' do
before :each do
Puppet[:strict] = :error
end
it "should fail on a failure to parse" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect do
expect(mymod.has_metadata?).to be_falsey
end.to raise_error(/mymod has an invalid and unparsable metadata\.json file/)
end
end
def a_module_with_metadata(data)
allow(File).to receive(:read).with("/path/metadata.json", {:encoding => 'utf-8'}).and_return(data.to_json)
Puppet::Module.new("foo", "/path", double("env"))
end
describe "when loading the metadata file" do
let(:data) do
{
:license => "GPL2",
:author => "luke",
:version => "1.0",
:source => "http://foo/",
:dependencies => []
}
end
%w{source author version license}.each do |attr|
it "should set #{attr} if present in the metadata file" do
mod = a_module_with_metadata(data)
expect(mod.send(attr)).to eq(data[attr.to_sym])
end
it "should fail if #{attr} is not present in the metadata file" do
data.delete(attr.to_sym)
expect { a_module_with_metadata(data) }.to raise_error(
Puppet::Module::MissingMetadata,
"No #{attr} module metadata provided for foo"
)
end
end
end
describe "when loading the metadata file from disk" do
it "should properly parse utf-8 contents" do
rune_utf8 = "\u16A0\u16C7\u16BB" # ᚠᛇᚻ
metadata_json = tmpfile('metadata.json')
File.open(metadata_json, 'w:UTF-8') do |file|
file.puts <<-EOF
{
"license" : "GPL2",
"author" : "#{rune_utf8}",
"version" : "1.0",
"source" : "http://foo/",
"dependencies" : []
}
EOF
end
allow_any_instance_of(Puppet::Module).to receive(:metadata_file).and_return(metadata_json)
mod = Puppet::Module.new('foo', '/path', double('env'))
mod.load_metadata
expect(mod.author).to eq(rune_utf8)
end
end
it "should be able to tell if there are local changes" do
modpath = tmpdir('modpath')
foo_checksum = 'acbd18db4cc2f85cedef654fccc4a4d8'
checksummed_module = PuppetSpec::Modules.create(
'changed',
modpath,
:metadata => {
:checksums => {
"foo" => foo_checksum,
}
}
)
foo_path = Pathname.new(File.join(checksummed_module.path, 'foo'))
IO.binwrite(foo_path, 'notfoo')
expect(Puppet::ModuleTool::Checksums.new(foo_path).checksum(foo_path)).not_to eq(foo_checksum)
IO.binwrite(foo_path, 'foo')
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/forge_spec.rb | spec/unit/forge_spec.rb | require 'spec_helper'
require 'spec_helper'
require 'net/http'
require 'puppet/forge'
require 'puppet/module_tool'
describe Puppet::Forge do
let(:http_response) do
File.read(my_fixture('bacula.json'))
end
let(:search_results) do
JSON.parse(http_response)['results'].map do |hash|
hash.merge(
"author" => "puppetlabs",
"name" => "bacula",
"tag_list" => ["backup", "bacula"],
"full_name" => "puppetlabs/bacula",
"version" => "0.0.2",
"project_url" => "https://github.com/puppetlabs/puppetlabs-bacula",
"desc" => "bacula"
)
end
end
let(:release_response) do
releases = JSON.parse(http_response)
releases['results'] = []
JSON.dump(releases)
end
let(:forge) { Puppet::Forge.new }
it "returns a list of matches from the forge when there are matches for the search term" do
stub_request(:get, "https://forgeapi.puppet.com/v3/modules?query=bacula").to_return(status: 200, body: http_response)
expect(forge.search('bacula')).to eq(search_results)
end
context "when module_groups are defined" do
before :each do
Puppet[:module_groups] = "foo"
end
it "passes module_groups with search" do
stub_request(:get, "https://forgeapi.puppet.com/v3/modules")
.with(query: hash_including("module_groups" => "foo"))
.to_return(status: 200, body: release_response)
forge.search('bacula')
end
it "passes module_groups with fetch" do
stub_request(:get, "https://forgeapi.puppet.com/v3/releases")
.with(query: hash_including("module_groups" => "foo"))
.to_return(status: 200, body: release_response)
forge.fetch('puppetlabs-bacula')
end
end
# See PUP-8008
context "when multiple module_groups are defined" do
context "with space seperator" do
before :each do
Puppet[:module_groups] = "foo bar"
end
it "passes module_groups with search" do
stub_request(:get, %r{forgeapi.puppet.com/v3/modules}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.search('bacula')
end
it "passes module_groups with fetch" do
stub_request(:get, %r{forgeapi.puppet.com/v3/releases}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.fetch('puppetlabs-bacula')
end
end
context "with plus seperator" do
before :each do
Puppet[:module_groups] = "foo+bar"
end
it "passes module_groups with search" do
stub_request(:get, %r{forgeapi.puppet.com/v3/modules}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.search('bacula')
end
it "passes module_groups with fetch" do
stub_request(:get, %r{forgeapi.puppet.com/v3/releases}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.fetch('puppetlabs-bacula')
end
end
# See PUP-8008
context "when there are multiple pages of results" do
before(:each) do
stub_request(:get, %r{forgeapi.puppet.com}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: first_page)
.to_return(status: 200, body: last_page)
end
context "with space seperator" do
before(:each) do
Puppet[:module_groups] = "foo bar"
end
let(:first_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['next'] = "/v3/modules?limit=1&offset=1&module_groups=foo%20bar"
JSON.dump(resp)
end
let(:last_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['current'] = "/v3/modules?limit=1&offset=1&module_groups=foo%20bar"
JSON.dump(resp)
end
it "traverses pages during search" do
forge.search('bacula')
end
it "traverses pages during fetch" do
forge.fetch('puppetlabs-bacula')
end
end
context "with plus seperator" do
before(:each) do
Puppet[:module_groups] = "foo+bar"
end
let(:first_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['next'] = "/v3/modules?limit=1&offset=1&module_groups=foo+bar"
JSON.dump(resp)
end
let(:last_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['current'] = "/v3/modules?limit=1&offset=1&module_groups=foo+bar"
JSON.dump(resp)
end
it "traverses pages during search" do
forge.search('bacula')
end
it "traverses pages during fetch" do
forge.fetch('puppetlabs-bacula')
end
end
end
end
context "when the connection to the forge fails" do
before :each do
stub_request(:get, /forgeapi.puppet.com/).to_return(status: [404, 'not found'])
end
it "raises an error for search" do
expect { forge.search('bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 404 not found."
end
it "raises an error for fetch" do
expect { forge.fetch('puppetlabs/bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 404 not found."
end
end
context "when the API responds with an error" do
it "raises an error for fetch" do
stub_request(:get, /forgeapi.puppet.com/).to_return(status: [410, 'Gone'], body: '{"error":"invalid module"}')
expect { forge.fetch('puppetlabs/bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 410 Gone."
end
end
context "when the forge returns a module with unparseable dependencies" do
it "ignores modules with unparseable dependencies" do
response = JSON.parse(http_response)
release = response['results'][0]['current_release']
release['metadata']['dependencies'] = [{'name' => 'broken-garbage >= 1.0.0', 'version_requirement' => 'banana'}]
response['results'] = [release]
stub_request(:get, /forgeapi.puppet.com/).to_return(status: 200, body: JSON.dump(response))
expect(forge.fetch('puppetlabs/bacula')).to be_empty
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/indirector_spec.rb | spec/unit/indirector_spec.rb | require 'spec_helper'
require 'puppet/defaults'
require 'puppet/indirector'
describe Puppet::Indirector, "when configuring routes" do
before :each do
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
end
after :each do
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
end
it "should configure routes as requested" do
routes = {
"node" => {
"terminus" => "exec",
"cache" => "plain"
}
}
Puppet::Indirector.configure_routes(routes)
expect(Puppet::Node.indirection.terminus_class).to eq("exec")
expect(Puppet::Node.indirection.cache_class).to eq("plain")
end
it "should fail when given an invalid indirection" do
routes = {
"fake_indirection" => {
"terminus" => "exec",
"cache" => "plain"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/fake_indirection does not exist/)
end
it "should fail when given an invalid terminus" do
routes = {
"node" => {
"terminus" => "fake_terminus",
"cache" => "plain"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/Could not find terminus fake_terminus/)
end
it "should fail when given an invalid cache" do
routes = {
"node" => {
"terminus" => "exec",
"cache" => "fake_cache"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/Could not find terminus fake_cache/)
end
end
describe Puppet::Indirector, " when available to a model" do
before do
@thingie = Class.new do
extend Puppet::Indirector
end
end
it "should provide a way for the model to register an indirection under a name" do
expect(@thingie).to respond_to(:indirects)
end
end
describe Puppet::Indirector, "when registering an indirection" do
before do
@thingie = Class.new do
extend Puppet::Indirector
# override Class#name, since we're not naming this ephemeral class
def self.name
'Thingie'
end
attr_reader :name
def initialize(name)
@name = name
end
end
end
it "should require a name when registering a model" do
expect {@thingie.send(:indirects) }.to raise_error(ArgumentError)
end
it "should create an indirection instance to manage each indirecting model" do
@indirection = @thingie.indirects(:test)
expect(@indirection).to be_instance_of(Puppet::Indirector::Indirection)
end
it "should not allow a model to register under multiple names" do
# Keep track of the indirection instance so we can delete it on cleanup
@indirection = @thingie.indirects :first
expect { @thingie.indirects :second }.to raise_error(ArgumentError)
end
it "should make the indirection available via an accessor" do
@indirection = @thingie.indirects :first
expect(@thingie.indirection).to equal(@indirection)
end
it "should pass any provided options to the indirection during initialization" do
expect(Puppet::Indirector::Indirection).to receive(:new).with(@thingie, :first, {:doc => 'some docs', :indirected_class => 'Thingie'})
@indirection = @thingie.indirects :first, :doc => 'some docs'
end
it "should extend the class to handle serialization" do
@indirection = @thingie.indirects :first
expect(@thingie).to respond_to(:convert_from)
end
after do
@indirection.delete if @indirection
end
end
describe Puppet::Indirector, "when redirecting a model" do
before do
@thingie = Class.new do
extend Puppet::Indirector
attr_reader :name
def initialize(name)
@name = name
end
end
@indirection = @thingie.send(:indirects, :test)
end
it "should include the Envelope module in the model" do
expect(@thingie.ancestors).to be_include(Puppet::Indirector::Envelope)
end
after do
@indirection.delete
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/puppet_pal_catalog_spec.rb | spec/unit/puppet_pal_catalog_spec.rb | #! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_pal'
describe 'Puppet Pal' do
include PuppetSpec::Files
let(:testing_env) do
{
'pal_env' => {
'functions' => functions,
'lib' => { 'puppet' => lib_puppet },
'manifests' => manifests,
'modules' => modules,
'plans' => plans,
'tasks' => tasks,
'types' => types,
},
'other_env1' => { 'modules' => {} },
'other_env2' => { 'modules' => {} },
}
end
let(:functions) { {} }
let(:manifests) { {} }
let(:modules) { {} }
let(:plans) { {} }
let(:lib_puppet) { {} }
let(:tasks) { {} }
let(:types) { {} }
let(:environments_dir) { Puppet[:environmentpath] }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'pal_env')
PuppetSpec::Files.record_tmp(env_dir)
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env1'))
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env2'))
env_dir
end
let(:modules_dir) { File.join(testing_env_dir, 'modules') }
# Without any facts - this speeds up the tests that do not require $facts to have any values
let(:node_facts) { Hash.new }
# TODO: to be used in examples for running in an existing env
# let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) }
context 'in general - without code in modules or env' do
let(:modulepath) { [] }
context "with a catalog compiler" do
it 'errors if given both configured_by_env and manifest_file' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler(configured_by_env: true, manifest_file: 'undef.pp') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
it 'errors if given both configured_by_env and code_string' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler(configured_by_env: true, code_string: 'undef') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
it 'shadows target variables that collide with plan variables' do
facts = { 'var' => 'fact' }
target_vars = { 'var' => 'target' }
expect(Puppet).to receive(:warning).with(/Target variable \$var will be overridden by fact of the same name/)
result = Puppet::Pal.in_tmp_environment('pal_env', facts: {}) do |ctx|
ctx.with_catalog_compiler(facts: facts, target_variables: target_vars ) do |c|
c.evaluate_string('$var')
end
end
expect(result).to eq('fact')
end
it 'shadows target variables that collide with facts' do
plan_vars = { 'var' => 'plan' }
target_vars = { 'var' => 'target' }
expect(Puppet).to receive(:warning).with(/Target variable \$var will be overridden by plan variable of the same name/)
result = Puppet::Pal.in_tmp_environment('pal_env', facts: {}) do |ctx|
ctx.with_catalog_compiler(variables: plan_vars, target_variables: target_vars ) do |c|
c.evaluate_string('$var')
end
end
expect(result).to eq('plan')
end
it 'shadows plan variables that collide with facts' do
facts = { 'var' => 'fact' }
plan_vars = { 'var' => 'plan' }
expect(Puppet).to receive(:warning).with(/Plan variable \$var will be overridden by fact of the same name/)
result = Puppet::Pal.in_tmp_environment('pal_env', facts: {}) do |ctx|
ctx.with_catalog_compiler(facts: facts, variables: plan_vars ) do |c|
c.evaluate_string('$var')
end
end
expect(result).to eq('fact')
end
context "evaluate_string method" do
it 'evaluates code string in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string('1+2+3') }
end
expect(result).to eq(6)
end
it 'can be evaluated more than once in a given tmp environment - each in fresh compiler' do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
expect( ctx.with_catalog_compiler {|c| c.evaluate_string('$a = 1+2+3')}).to eq(6)
expect { ctx.with_catalog_compiler {|c| c.evaluate_string('$a') }}.to raise_error(/Unknown variable: 'a'/)
end
end
it 'instantiates a function definition in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler do |compiler|
compiler.evaluate_string(<<-CODE)
function run_me() { "worked1" }
run_me()
CODE
end
end
expect(result).to eq('worked1')
end
it 'instantiates a user defined resource definition in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler do |compiler|
compiler.evaluate_string(<<-CODE)
define run_me() { }
run_me { test: }
CODE
end
end
resource = result[0]
expect(resource).to be_a(Puppet::Pops::Types::PResourceType)
expect(resource.type_name).to eq("Run_me")
expect(resource.title).to eq('test')
end
context 'catalog_data_hash' do
it 'produces a data_hash encoding of a catalog' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.catalog_data_hash
}
end
expect(result['resources']).to include(include('type' => 'Notify'))
end
end
context 'the with_json_encoding()' do
it 'produces json for a catalog' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding() {|encoder| encoder.encode }
}
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
it 'produces pretty json by default' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding() {|encoder| encoder.encode }
}
end
expect(result.count("\n")).to be > 10
end
it 'produces compact (non pretty) json when pretty is false' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding(pretty: false) {|encoder| encoder.encode }
}
end
expect(result.count("\n")).to be < 10
end
it 'produces json for an individual resource by giving type and title to encode_resource()' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => 'yay'}")
c.with_json_encoding() {|encoder| encoder.encode_resource('notify', 'test') }
}
end
expect(result).to match(/"message":"yay"/)
end
it 'encodes values as rich data when needed' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding(pretty: true) {|encoder| encoder.encode_resource('notify', 'test') }
}
end
expect(result).to match(/"__ptype":"Regexp"/)
end
end
end
context "evaluate_file method" do
it 'evaluates a manifest file in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('testing.pp', "1+2+3+4")
ctx.with_catalog_compiler {|c| c.evaluate_file(manifest) }
end
expect(result).to eq(10)
end
it 'instantiates definitions in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler do |compiler|
manifest = file_containing('testing.pp', (<<-CODE))
function run_me() { "worked1" }
run_me()
CODE
pal.with_catalog_compiler {|c| c.evaluate_file(manifest) }
end
end
expect(result).to eq('worked1')
end
end
context "variables are supported such that" do
it 'they can be set in any scope' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(40)
end
it 'an error is raised if a variable name is illegal' do
vars = {'_a::b'=> 10}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
manifest = file_containing('testing.pp', "ok")
ctx.with_catalog_compiler {|c| c.evaluate_file(manifest) }
end
end.to raise_error(/has illegal name/)
end
it 'an error is raised if variable value is not RichData compliant' do
vars = {'a'=> ArgumentError.new("not rich data")}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_catalog_compiler {|c| }
end
end.to raise_error(/has illegal type - got: ArgumentError/)
end
it 'variable given to script_compiler overrides those given for environment' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_catalog_compiler(variables: {'x::y' => 40}) {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(60)
end
end
context "functions are supported such that" do
it '"call_function" calls a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc($a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) {|c| c.call_function('myfunc', 6) }
end
expect(result).to eq(12)
end
it '"call_function" accepts a call with a ruby block' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.call_function('with', 6) {|x| x * 2} }
end
expect(result).to eq(12)
end
it '"function_signature" returns a signature of a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc')
end
end
expect(result.class).to eq(Puppet::Pal::FunctionSignature)
end
it '"FunctionSignature#callable_with?" returns boolean if function is callable with given argument values' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
[ signature.callable_with?([10]),
signature.callable_with?(['nope'])
]
end
end
expect(result).to eq([true, false])
end
it '"FunctionSignature#callable_with?" calls a given lambda if there is an error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'not yay'
signature.callable_with?(['nope']) {|error| local_result = error }
local_result
end
end
expect(result).to match(/'myfunc' parameter 'a' expects an Integer value, got String/)
end
it '"FunctionSignature#callable_with?" does not call a given lambda when there is no error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'yay'
signature.callable_with?([10]) {|error| local_result = 'not yay' }
local_result
end
end
expect(result).to eq('yay')
end
it '"function_signature" gets the signatures from a ruby function with multiple dispatch' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.function_signature('lookup') }
end
# check two different signatures of the lookup function
expect(result.callable_with?(['key'])).to eq(true)
expect(result.callable_with?(['key'], lambda() {|k| })).to eq(true)
end
it '"function_signature" returns nil if function is not found' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.function_signature('no_where_to_be_found') }
end
expect(result).to eq(nil)
end
it '"FunctionSignature#callables" returns an array of callables' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc').callables
end
end
expect(result.class).to eq(Array)
expect(result.all? {|c| c.is_a?(Puppet::Pops::Types::PCallableType)}).to eq(true)
end
it '"list_functions" returns an array with all function names that can be loaded' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.list_functions() }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are certainly more than 30 functions in puppet - (56 when writing this, but some refactoring
# may take place, so don't want an exact number here - jsut make sure it found "all of them"
expect(result.count).to be > 30
end
it '"list_functions" filters on name based on a given regexp' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.list_functions(/epp/) }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are two functions currently that have 'epp' in their name
expect(result.count).to eq(2)
end
end
context 'supports puppet data types such that' do
it '"type" parses and returns a Type from a string specification' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "type MyType = Float")
ctx.with_catalog_compiler(manifest_file: manifest) {|c| c.type('Variant[Integer, Boolean, MyType]') }
end
expect(result.is_a?(Puppet::Pops::Types::PVariantType)).to eq(true)
expect(result.types.size).to eq(3)
expect(result.instance?(3.14)).to eq(true)
end
it '"create" creates a new object from a puppet data type and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.create(Puppet::Pops::Types::PIntegerType::DEFAULT, '0x10') }
end
expect(result).to eq(16)
end
it '"create" creates a new object from puppet data type in string form and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.create('Integer', '010') }
end
expect(result).to eq(8)
end
end
end
context 'supports parsing such that' do
it '"parse_string" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.parse_string('$a = 10') }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
{ nil => Puppet::Error,
'0xWAT' => Puppet::ParseErrorWithIssue,
'$0 = 1' => Puppet::ParseErrorWithIssue,
'else 32' => Puppet::ParseErrorWithIssue,
}.each_pair do |input, error_class|
it "'parse_string' raises an error for invalid input: '#{input}'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.parse_string(input) }
end
}.to raise_error(error_class)
end
end
it '"parse_file" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "$a = 10")
ctx.with_catalog_compiler { |c| c.parse_file(manifest) }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
it "'parse_file' raises an error for invalid input: 'else 32'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "else 32")
ctx.with_catalog_compiler { |c| c.parse_file(manifest) }
end
}.to raise_error(Puppet::ParseErrorWithIssue)
end
it "'parse_file' raises an error for invalid input, file is not a string" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.parse_file(42) }
end
}.to raise_error(Puppet::Error)
end
it 'the "evaluate" method evaluates the parsed AST' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate(c.parse_string('10 + 20')) }
end
expect(result).to eq(30)
end
it 'the "evaluate" method instantiates definitions when given a Program' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate(c.parse_string('function foo() { "yay"}; foo()')) }
end
expect(result).to eq('yay')
end
it 'the "evaluate" method does not instantiates definitions when given ast other than Program' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
program= c.parse_string('function foo() { "yay"}; foo()')
c.evaluate(program.body)
end
end
end.to raise_error(/Unknown function: 'foo'/)
end
it 'the "evaluate_literal" method evaluates AST being a representation of a literal value' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate_literal(c.parse_string('{10 => "hello"}')) }
end
expect(result).to eq({10 => 'hello'})
end
it 'the "evaluate_literal" method errors if ast is not representing a literal value' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate_literal(c.parse_string('{10+1 => "hello"}')) }
end
end.to raise_error(/does not represent a literal value/)
end
it 'the "evaluate_literal" method errors if ast contains definitions' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate_literal(c.parse_string('function foo() { }; 42')) }
end
end.to raise_error(/does not represent a literal value/)
end
it 'the "evaluate" method evaluates but does not evaluate lazy constructs' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: }'))
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to_not include(include('type' => 'Notify'))
end
it 'an "evaluate" followed by "compile_additions" evaluates lazy constructs' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: }'))
c.compile_additions
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
it 'an "evaluate" followed by "compile_additions" validates the result' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: before =>"Bar[nope]"}'))
c.compile_additions
end
end
end.to raise_error(Puppet::Error, /Could not find resource 'Bar\[nope\]'/)
end
it 'an "evaluate" followed by "evaluate_additions" does not validate the result' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: before =>"Bar[nope]"}'))
c.evaluate_additions
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
it 'an "evaluate" followed by "evaluate_additions" and "validate" validates the result' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: before =>"Bar[nope]"}'))
c.compile_additions
c.validate
end
end
end.to raise_error(Puppet::Error, /Could not find resource 'Bar\[nope\]'/)
end
it 'an "evaluate" followed by "evaluate_ast_node" will correctly parse a node definition' do
Puppet[:node_name_value] = 'testing_node'
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string("node 'testing_node' { notify {'PASSED': } }"))
c.evaluate_ast_node
c.compile_additions
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
end
end
context 'with code in modules and env' do
let(:modulepath) { [modules_dir] }
let(:metadata_json_a) {
{
'name' => 'example/a',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-a.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_b) {
{
'name' => 'example/b',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-b.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_c) {
{
'name' => 'example/c',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-c.git',
'dependencies' => [],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
# TODO: there is something amiss with the metadata wrt dependencies - when metadata is present there is an error
# that dependencies could not be resolved. Metadata is therefore commented out.
# Dependency based visibility is probably something that we should remove...
let(:modules) {
{
'a' => {
'functions' => a_functions,
'lib' => { 'puppet' => a_lib_puppet },
'types' => a_types,
},
'b' => {
'functions' => b_functions,
'lib' => b_lib,
'types' => b_types,
},
'c' => {
'types' => c_types,
},
}
}
let(:a_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type A::Atype = Integer
PUPPET
}
}
let(:a_functions) {
{
'afunc.pp' => 'function a::afunc() { "a::afunc value" }',
}
}
let(:a_lib_puppet) {
{
'functions' => {
'a' => {
'arubyfunc.rb' => <<-RUBY.unindent,
require 'stuff/something'
Puppet::Functions.create_function(:'a::arubyfunc') do
def arubyfunc
Stuff::SOMETHING
end
end
RUBY
'mycatalogcompilerfunc.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:'a::mycatalogcompilerfunc', Puppet::Functions::InternalFunction) do
dispatch :mycatalogcompilerfunc do
compiler_param
param 'String',:name
end
def mycatalogcompilerfunc(the_compiler, name)
the_compiler.is_a?(Puppet::Pal::CatalogCompiler) ? name : 'no go'
end
end
RUBY
}
},
'datatypes' => {
'mytype.rb' => <<-RUBY.unindent,
Puppet::DataTypes.create_type('Mytype') do
interface <<-PUPPET
attributes => {
name => { type => String },
year_of_birth => { type => Integer },
age => { type => Integer, kind => derived },
}
PUPPET
implementation do
def age
DateTime.now.year - @year_of_birth
end
end
end
RUBY
}
}
}
let(:b_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type B::Atype = Integer
PUPPET
}
}
let(:b_functions) {
{
'afunc.pp' => 'function b::afunc() {}',
}
}
let(:b_lib) {
{
'puppet' => b_lib_puppet,
'stuff' => {
'something.rb' => "module Stuff; SOMETHING = 'something'; end"
}
}
}
let(:b_lib_puppet) {
{
'functions' => {
'b' => {
'arubyfunc.rb' => "Puppet::Functions.create_function(:'b::arubyfunc') { def arubyfunc; 'arubyfunc_value'; end }",
}
}
}
}
let(:c_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type C::Atype = Integer
PUPPET
}
}
context 'configured as temporary environment such that' do
it 'modules are available' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string('a::afunc()') }
end
expect(result).to eq("a::afunc value")
end
it 'libs in a given "modulepath" are added to the Ruby $LOAD_PATH' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string('a::arubyfunc()') }
end
expect(result).to eql('something')
end
it 'errors if a block is not given to in_tmp_environment' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts)
end.to raise_error(/A block must be given to 'in_tmp_environment/)
end
it 'errors if an env_name is given and is not a String[1]' do
expect do
Puppet::Pal.in_tmp_environment('', modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
expect do
Puppet::Pal.in_tmp_environment(32, modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
end
{ 'a hash' => {'a' => 'hm'},
'an integer' => 32,
'separated strings' => 'dir1;dir2',
'empty string in array' => ['']
}.each_pair do |what, value|
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util_spec.rb | spec/unit/util_spec.rb | require 'spec_helper'
describe Puppet::Util do
include PuppetSpec::Files
if Puppet::Util::Platform.windows?
def set_mode(mode, file)
Puppet::Util::Windows::Security.set_mode(mode, file)
end
def get_mode(file)
Puppet::Util::Windows::Security.get_mode(file) & 07777
end
else
def set_mode(mode, file)
File.chmod(mode, file)
end
def get_mode(file)
Puppet::FileSystem.lstat(file).mode & 07777
end
end
describe "#withenv" do
let(:mode) { Puppet::Util::Platform.windows? ? :windows : :posix }
before :each do
@original_path = ENV["PATH"]
@new_env = {:PATH => "/some/bogus/path"}
end
it "should change environment variables within the block then reset environment variables to their original values" do
Puppet::Util.withenv @new_env, mode do
expect(ENV["PATH"]).to eq("/some/bogus/path")
end
expect(ENV["PATH"]).to eq(@original_path)
end
it "should reset environment variables to their original values even if the block fails" do
begin
Puppet::Util.withenv @new_env, mode do
expect(ENV["PATH"]).to eq("/some/bogus/path")
raise "This is a failure"
end
rescue
end
expect(ENV["PATH"]).to eq(@original_path)
end
it "should reset environment variables even when they are set twice" do
# Setting Path & Environment parameters in Exec type can cause weirdness
@new_env["PATH"] = "/someother/bogus/path"
Puppet::Util.withenv @new_env, mode do
# When assigning duplicate keys, can't guarantee order of evaluation
expect(ENV["PATH"]).to match(/\/some.*\/bogus\/path/)
end
expect(ENV["PATH"]).to eq(@original_path)
end
it "should remove any new environment variables after the block ends" do
@new_env[:FOO] = "bar"
ENV["FOO"] = nil
Puppet::Util.withenv @new_env, mode do
expect(ENV["FOO"]).to eq("bar")
end
expect(ENV["FOO"]).to eq(nil)
end
it "accepts symbolic keys" do
Puppet::Util.withenv(:FOO => "bar") do
expect(ENV["FOO"]).to eq("bar")
end
end
it "coerces invalid keys to strings" do
Puppet::Util.withenv(12345678 => "bar") do
expect(ENV["12345678"]).to eq("bar")
end
end
it "rejects keys with leading equals" do
expect {
Puppet::Util.withenv("=foo" => "bar") {}
}.to raise_error(Errno::EINVAL, /Invalid argument/)
end
it "includes keys with unicode replacement characters" do
Puppet::Util.withenv("foo\uFFFD" => "bar") do
expect(ENV).to be_include("foo\uFFFD")
end
end
it "accepts a unicode key" do
key = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7"
Puppet::Util.withenv(key => "bar") do
expect(ENV[key]).to eq("bar")
end
end
it "accepts a unicode value" do
value = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7"
Puppet::Util.withenv("runes" => value) do
expect(ENV["runes"]).to eq(value)
end
end
it "rejects a non-string value" do
expect {
Puppet::Util.withenv("reject" => 123) {}
}.to raise_error(TypeError, /no implicit conversion of Integer into String/)
end
it "accepts a nil value" do
Puppet::Util.withenv("foo" => nil) do
expect(ENV["foo"]).to eq(nil)
end
end
end
describe "#withenv on POSIX", :unless => Puppet::Util::Platform.windows? do
it "compares keys case sensitively" do
# start with lower case key,
env_key = SecureRandom.uuid.downcase
begin
original_value = 'hello'
ENV[env_key] = original_value
new_value = 'goodbye'
Puppet::Util.withenv(env_key.upcase => new_value) do
expect(ENV[env_key]).to eq(original_value)
expect(ENV[env_key.upcase]).to eq(new_value)
end
expect(ENV[env_key]).to eq(original_value)
expect(ENV[env_key.upcase]).to be_nil
ensure
ENV.delete(env_key)
end
end
end
describe "#withenv on Windows", :if => Puppet::Util::Platform.windows? do
let(:process) { Puppet::Util::Windows::Process }
it "compares keys case-insensitively" do
# start with lower case key, ensuring string is not entirely numeric
env_key = SecureRandom.uuid.downcase + 'a'
begin
original_value = 'hello'
ENV[env_key] = original_value
new_value = 'goodbye'
Puppet::Util.withenv(env_key.upcase => new_value) do
expect(ENV[env_key]).to eq(new_value)
expect(ENV[env_key.upcase]).to eq(new_value)
end
expect(ENV[env_key]).to eq(original_value)
expect(ENV[env_key.upcase]).to eq(original_value)
ensure
ENV.delete(env_key)
end
end
def withenv_utf8(&block)
env_var_name = SecureRandom.uuid
utf_8_bytes = [225, 154, 160] # rune ᚠ
utf_8_key = env_var_name + utf_8_bytes.pack('c*').force_encoding(Encoding::UTF_8)
utf_8_value = utf_8_key + 'value'
codepage_key = utf_8_key.dup.force_encoding(Encoding.default_external)
Puppet::Util.withenv(utf_8_key => utf_8_value) do
# the true Windows environment APIs see the variables correctly
expect(process.get_environment_strings[utf_8_key]).to eq(utf_8_value)
# the string contain the same bytes, but have different Ruby metadata
expect(utf_8_key.bytes.to_a).to eq(codepage_key.bytes.to_a)
yield utf_8_key, utf_8_value, codepage_key
end
# real environment shouldn't have env var anymore
expect(process.get_environment_strings[utf_8_key]).to eq(nil)
end
it "should preseve existing environment and should not corrupt UTF-8 environment variables" do
env_var_name = SecureRandom.uuid
utf_8_bytes = [225, 154, 160] # rune ᚠ
utf_8_str = env_var_name + utf_8_bytes.pack('c*').force_encoding(Encoding::UTF_8)
env_var_name_utf_8 = utf_8_str
begin
# UTF-8 name and value
process.set_environment_variable(env_var_name_utf_8, utf_8_str)
# ASCII name / UTF-8 value
process.set_environment_variable(env_var_name, utf_8_str)
original_keys = process.get_environment_strings.keys.to_a
Puppet::Util.withenv({}) { }
env = process.get_environment_strings
expect(env[env_var_name]).to eq(utf_8_str)
expect(env[env_var_name_utf_8]).to eq(utf_8_str)
expect(env.keys.to_a).to eq(original_keys)
ensure
process.set_environment_variable(env_var_name_utf_8, nil)
process.set_environment_variable(env_var_name, nil)
end
end
end
describe "#absolute_path?" do
describe "on posix systems", :if => Puppet.features.posix? do
it "should default to the platform of the local system" do
expect(Puppet::Util).to be_absolute_path('/foo')
expect(Puppet::Util).not_to be_absolute_path('C:/foo')
end
end
describe "on windows", :if => Puppet::Util::Platform.windows? do
it "should default to the platform of the local system" do
expect(Puppet::Util).to be_absolute_path('C:/foo')
expect(Puppet::Util).not_to be_absolute_path('/foo')
end
end
describe "when using platform :posix" do
%w[/ /foo /foo/../bar //foo //Server/Foo/Bar //?/C:/foo/bar /\Server/Foo /foo//bar/baz].each do |path|
it "should return true for #{path}" do
expect(Puppet::Util).to be_absolute_path(path, :posix)
end
end
%w[. ./foo \foo C:/foo \\Server\Foo\Bar \\?\C:\foo\bar \/?/foo\bar \/Server/foo foo//bar/baz].each do |path|
it "should return false for #{path}" do
expect(Puppet::Util).not_to be_absolute_path(path, :posix)
end
end
end
describe "when using platform :windows" do
%w[C:/foo C:\foo \\\\Server\Foo\Bar \\\\?\C:\foo\bar //Server/Foo/Bar //?/C:/foo/bar /\?\C:/foo\bar \/Server\Foo/Bar c:/foo//bar//baz].each do |path|
it "should return true for #{path}" do
expect(Puppet::Util).to be_absolute_path(path, :windows)
end
end
%w[/ . ./foo \foo /foo /foo/../bar //foo C:foo/bar foo//bar/baz].each do |path|
it "should return false for #{path}" do
expect(Puppet::Util).not_to be_absolute_path(path, :windows)
end
end
end
end
describe "#path_to_uri" do
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte - 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ۿᚠ
let (:mixed_utf8_urlencoded) { "A%DB%BF%E1%9A%A0%F0%A0%9C%8E" }
%w[. .. foo foo/bar foo/../bar].each do |path|
it "should reject relative path: #{path}" do
expect { Puppet::Util.path_to_uri(path) }.to raise_error(Puppet::Error)
end
end
it "should perform URI escaping" do
expect(Puppet::Util.path_to_uri("/foo bar").path).to eq("/foo%20bar")
end
it "should properly URI encode + and space in path" do
expect(Puppet::Util.path_to_uri("/foo+foo bar").path).to eq("/foo+foo%20bar")
end
# reserved characters are different for each part
# https://web.archive.org/web/20151229061347/http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding#Thereservedcharactersaredifferentforeachpart
# "?" is allowed unescaped anywhere within a query part,
# "/" is allowed unescaped anywhere within a query part,
# "=" is allowed unescaped anywhere within a path parameter or query parameter value, and within a path segment,
# ":@-._~!$&'()*+,;=" are allowed unescaped anywhere within a path segment part,
# "/?:@-._~!$&'()*+,;=" are allowed unescaped anywhere within a fragment part.
it "should properly URI encode + and space in path and query" do
path = "/foo+foo bar?foo+foo bar"
uri = Puppet::Util.path_to_uri(path)
expected_encoding = Encoding::UTF_8
expect(uri.to_s.encoding).to eq(expected_encoding)
expect(uri.path).to eq("/foo+foo%20bar")
# either + or %20 is correct for an encoded space in query
# + is usually used for backward compatibility, but %20 is preferred for compat with Puppet::Util.uri_unescape
expect(uri.query).to eq("foo%2Bfoo%20bar")
# complete roundtrip
expect(Puppet::Util.uri_unescape(uri.to_s).sub(%r{^file:(//)?}, '')).to eq(path)
expect(Puppet::Util.uri_unescape(uri.to_s).encoding).to eq(expected_encoding)
end
it "should perform UTF-8 URI escaping" do
uri = Puppet::Util.path_to_uri("/#{mixed_utf8}")
expect(uri.path.encoding).to eq(Encoding::UTF_8)
expect(uri.path).to eq("/#{mixed_utf8_urlencoded}")
end
describe "when using platform :posix" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
%w[/ /foo /foo/../bar].each do |path|
it "should convert #{path} to URI" do
expect(Puppet::Util.path_to_uri(path).path).to eq(path)
end
end
end
describe "when using platform :windows" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
it "should normalize backslashes" do
expect(Puppet::Util.path_to_uri('c:\\foo\\bar\\baz').path).to eq('/' + 'c:/foo/bar/baz')
end
%w[C:/ C:/foo/bar].each do |path|
it "should convert #{path} to absolute URI" do
expect(Puppet::Util.path_to_uri(path).path).to eq('/' + path)
end
end
%w[share C$].each do |path|
it "should convert UNC #{path} to absolute URI" do
uri = Puppet::Util.path_to_uri("\\\\server\\#{path}")
expect(uri.host).to eq('server')
expect(uri.path).to eq('/' + Puppet::Util.uri_encode(path))
end
end
end
end
describe "#uri_query_encode" do
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ𠜎
let (:mixed_utf8_urlencoded) { "A%DB%BF%E1%9A%A0%F0%A0%9C%8E" }
it "should perform basic URI escaping that includes space and +" do
expect(Puppet::Util.uri_query_encode("foo bar+foo")).to eq("foo%20bar%2Bfoo")
end
it "should URI encode any special characters: = + <space> & * and #" do
expect(Puppet::Util.uri_query_encode("foo=bar+foo baz&bar=baz qux&special= *&qux=not fragment#")).to eq("foo%3Dbar%2Bfoo%20baz%26bar%3Dbaz%20qux%26special%3D%20%2A%26qux%3Dnot%20fragment%23")
end
[
"A\u06FF\u16A0\u{2070E}",
"A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::BINARY)
].each do |uri_string|
it "should perform UTF-8 URI escaping, even when input strings are not UTF-8" do
uri = Puppet::Util.uri_query_encode(mixed_utf8)
expect(uri.encoding).to eq(Encoding::UTF_8)
expect(uri).to eq(mixed_utf8_urlencoded)
end
end
it "should be usable by URI::parse" do
uri = URI::parse("puppet://server/path?" + Puppet::Util.uri_query_encode(mixed_utf8))
expect(uri.scheme).to eq('puppet')
expect(uri.host).to eq('server')
expect(uri.path).to eq('/path')
expect(uri.query).to eq(mixed_utf8_urlencoded)
end
it "should be usable by URI::Generic.build" do
params = {
:scheme => 'file',
:host => 'foobar',
:path => '/path/to',
:query => Puppet::Util.uri_query_encode(mixed_utf8)
}
uri = URI::Generic.build(params)
expect(uri.scheme).to eq('file')
expect(uri.host).to eq('foobar')
expect(uri.path).to eq("/path/to")
expect(uri.query).to eq(mixed_utf8_urlencoded)
end
end
describe "#uri_encode" do
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ
let (:mixed_utf8_urlencoded) { "A%DB%BF%E1%9A%A0%F0%A0%9C%8E" }
it "should perform URI escaping" do
expect(Puppet::Util.uri_encode("/foo bar")).to eq("/foo%20bar")
end
[
"A\u06FF\u16A0\u{2070E}",
"A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::BINARY)
].each do |uri_string|
it "should perform UTF-8 URI escaping, even when input strings are not UTF-8" do
uri = Puppet::Util.uri_encode(mixed_utf8)
expect(uri.encoding).to eq(Encoding::UTF_8)
expect(uri).to eq(mixed_utf8_urlencoded)
end
end
it "should treat & and = as delimiters in a query string, but URI encode other special characters: + <space> * and #" do
input = "http://foo.bar.com/path?foo=bar+foo baz&bar=baz qux&special= *&qux=not fragment#"
expected_output = "http://foo.bar.com/path?foo=bar%2Bfoo%20baz&bar=baz%20qux&special=%20%2A&qux=not%20fragment%23"
expect(Puppet::Util.uri_encode(input)).to eq(expected_output)
end
it "should be usable by URI::parse" do
uri = URI::parse(Puppet::Util.uri_encode("puppet://server/path/to/#{mixed_utf8}"))
expect(uri.scheme).to eq('puppet')
expect(uri.host).to eq('server')
expect(uri.path).to eq("/path/to/#{mixed_utf8_urlencoded}")
end
it "should be usable by URI::Generic.build" do
params = {
:scheme => 'file',
:host => 'foobar',
:path => Puppet::Util.uri_encode("/path/to/#{mixed_utf8}")
}
uri = URI::Generic.build(params)
expect(uri.scheme).to eq('file')
expect(uri.host).to eq('foobar')
expect(uri.path).to eq("/path/to/#{mixed_utf8_urlencoded}")
end
describe "when using platform :posix" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
%w[/ /foo /foo/../bar].each do |path|
it "should not replace / in #{path} with %2F" do
expect(Puppet::Util.uri_encode(path)).to eq(path)
end
end
end
describe "with fragment support" do
context "disabled by default" do
it "should encode # as %23 in path" do
encoded = Puppet::Util.uri_encode("/foo bar#fragment")
expect(encoded).to eq("/foo%20bar%23fragment")
end
it "should encode # as %23 in query" do
encoded = Puppet::Util.uri_encode("/foo bar?baz+qux#fragment")
expect(encoded).to eq("/foo%20bar?baz%2Bqux%23fragment")
end
end
context "optionally enabled" do
it "should leave fragment delimiter # after encoded paths" do
encoded = Puppet::Util.uri_encode("/foo bar#fragment", { :allow_fragment => true })
expect(encoded).to eq("/foo%20bar#fragment")
end
it "should leave fragment delimiter # after encoded query" do
encoded = Puppet::Util.uri_encode("/foo bar?baz+qux#fragment", { :allow_fragment => true })
expect(encoded).to eq("/foo%20bar?baz%2Bqux#fragment")
end
end
end
describe "when using platform :windows" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
it "should url encode \\ as %5C, but not replace : as %3F" do
expect(Puppet::Util.uri_encode('c:\\foo\\bar\\baz')).to eq('c:%5Cfoo%5Cbar%5Cbaz')
end
%w[C:/ C:/foo/bar].each do |path|
it "should not replace / in #{path} with %2F" do
expect(Puppet::Util.uri_encode(path)).to eq(path)
end
end
end
end
describe ".uri_to_path" do
require 'uri'
# 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 "should strip host component" do
expect(Puppet::Util.uri_to_path(URI.parse('http://foo/bar'))).to eq('/bar')
end
it "should accept puppet URLs" do
expect(Puppet::Util.uri_to_path(URI.parse('puppet:///modules/foo'))).to eq('/modules/foo')
end
it "should return unencoded path" do
expect(Puppet::Util.uri_to_path(URI.parse('http://foo/bar%20baz'))).to eq('/bar baz')
end
[
"http://foo/A%DB%BF%E1%9A%A0%F0%A0%9C%8E",
"http://foo/A%DB%BF%E1%9A%A0%F0%A0%9C%8E".force_encoding(Encoding::ASCII)
].each do |uri_string|
it "should return paths as UTF-8" do
path = Puppet::Util.uri_to_path(URI.parse(uri_string))
expect(path).to eq("/#{mixed_utf8}")
expect(path.encoding).to eq(Encoding::UTF_8)
end
end
it "should be nil-safe" do
expect(Puppet::Util.uri_to_path(nil)).to be_nil
end
describe "when using platform :posix",:if => Puppet.features.posix? do
it "should accept root" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/'))).to eq('/')
end
it "should accept single slash" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/foo/bar'))).to eq('/foo/bar')
end
it "should accept triple slashes" do
expect(Puppet::Util.uri_to_path(URI.parse('file:///foo/bar'))).to eq('/foo/bar')
end
end
describe "when using platform :windows", :if => Puppet::Util::Platform.windows? do
it "should accept root" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/C:/'))).to eq('C:/')
end
it "should accept single slash" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/C:/foo/bar'))).to eq('C:/foo/bar')
end
it "should accept triple slashes" do
expect(Puppet::Util.uri_to_path(URI.parse('file:///C:/foo/bar'))).to eq('C:/foo/bar')
end
it "should accept file scheme with double slashes as a UNC path" do
expect(Puppet::Util.uri_to_path(URI.parse('file://host/share/file'))).to eq('//host/share/file')
end
end
end
describe "safe_posix_fork on Windows and JRuby", if: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
it "raises not implemented error" do
expect {
Puppet::Util.safe_posix_fork
}.to raise_error(NotImplementedError, /fork/)
end
end
describe "safe_posix_fork", unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:pid) { 5501 }
before :each do
# Most of the things this method does are bad to do during specs. :/
allow(Kernel).to receive(:fork).and_return(pid).and_yield
allow($stdin).to receive(:reopen)
allow($stdout).to receive(:reopen)
allow($stderr).to receive(:reopen)
# ensure that we don't really close anything!
allow(IO).to receive(:new)
end
it "should close all open file descriptors except stdin/stdout/stderr when /proc/self/fd exists" do
# This is ugly, but I can't really think of a better way to do it without
# letting it actually close fds, which seems risky
fds = [".", "..","0","1","2","3","5","100","1000"]
fds.each do |fd|
if fd == '.' || fd == '..'
next
elsif ['0', '1', '2', '5'].include? fd
expect(IO).not_to receive(:new).with(fd.to_i)
else
expect(IO).to receive(:new).with(fd.to_i).and_return(double('io', close: nil))
end
end
dir = double(Dir, fileno: '5')
dir_expectation = receive(:each_child)
fds.each do |fd|
dir_expectation = dir_expectation.and_yield(fd)
end
allow(dir).to dir_expectation
allow(Dir).to receive(:new).with('/proc/self/fd').and_return(dir)
Puppet::Util.safe_posix_fork
end
it "should close all open file descriptors except stdin/stdout/stderr when /proc/self/fd doesn't exist" do
# This is ugly, but I can't really think of a better way to do it without
# letting it actually close fds, which seems risky
(0..2).each {|n| expect(IO).not_to receive(:new).with(n)}
(3..256).each {|n| expect(IO).to receive(:new).with(n).and_return(double('io', close: nil)) }
allow(Dir).to receive(:new).with('/proc/self/fd').and_raise(Errno::ENOENT)
Puppet::Util.safe_posix_fork
end
it "should close all open file descriptors except stdin/stdout/stderr when /proc/self is not a directory" do
# This is ugly, but I can't really think of a better way to do it without
# letting it actually close fds, which seems risky
(0..2).each {|n| expect(IO).not_to receive(:new).with(n)}
(3..256).each {|n| expect(IO).to receive(:new).with(n).and_return(double('io', close: nil)) }
allow(Dir).to receive(:new).with('/proc/self/fd').and_raise(Errno::ENOTDIR)
Puppet::Util.safe_posix_fork
end
it "should fork a child process to execute the block" do
expect(Kernel).to receive(:fork).and_return(pid).and_yield
Puppet::Util.safe_posix_fork do
"Fork this!"
end
end
it "should return the pid of the child process" do
expect(Puppet::Util.safe_posix_fork).to eq(pid)
end
end
describe "#which" do
let(:base) { File.expand_path('/bin') }
let(:path) { File.join(base, 'foo') }
before :each do
allow(FileTest).to receive(:file?).and_return(false)
allow(FileTest).to receive(:file?).with(path).and_return(true)
allow(FileTest).to receive(:executable?).and_return(false)
allow(FileTest).to receive(:executable?).with(path).and_return(true)
end
it "should accept absolute paths" do
expect(Puppet::Util.which(path)).to eq(path)
end
it "should return nil if no executable found" do
expect(Puppet::Util.which('doesnotexist')).to be_nil
end
it "should reject directories" do
expect(Puppet::Util.which(base)).to be_nil
end
it "should ignore ~user directories if the user doesn't exist" do
# Windows treats *any* user as a "user that doesn't exist", which means
# that this will work correctly across all our platforms, and should
# behave consistently. If they ever implement it correctly (eg: to do
# the lookup for real) it should just work transparently.
baduser = 'if_this_user_exists_I_will_eat_my_hat'
Puppet::Util.withenv("PATH" => "~#{baduser}#{File::PATH_SEPARATOR}#{base}") do
expect(Puppet::Util.which('foo')).to eq(path)
end
end
describe "on POSIX systems" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
it "should walk the search PATH returning the first executable" do
allow(ENV).to receive(:fetch).with('PATH').and_return(File.expand_path('/bin'))
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(nil)
expect(Puppet::Util.which('foo')).to eq(path)
end
end
describe "on Windows systems" do
let(:path) { File.expand_path(File.join(base, 'foo.CMD')) }
before :each do
allow(Puppet.features).to receive(:posix?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
describe "when a file extension is specified" do
it "should walk each directory in PATH ignoring PATHEXT" do
allow(ENV).to receive(:fetch).with('PATH').and_return(%w[/bar /bin].map{|dir| File.expand_path(dir)}.join(File::PATH_SEPARATOR))
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return('.FOOBAR')
expect(FileTest).to receive(:file?).with(File.join(File.expand_path('/bar'), 'foo.CMD')).and_return(false)
expect(Puppet::Util.which('foo.CMD')).to eq(path)
end
end
describe "when a file extension is not specified" do
it "should walk each extension in PATHEXT until an executable is found" do
bar = File.expand_path('/bar')
allow(ENV).to receive(:fetch).with('PATH').and_return("#{bar}#{File::PATH_SEPARATOR}#{base}")
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(".EXE#{File::PATH_SEPARATOR}.CMD")
expect(FileTest).to receive(:file?).ordered().with(File.join(bar, 'foo.EXE')).and_return(false)
expect(FileTest).to receive(:file?).ordered().with(File.join(bar, 'foo.CMD')).and_return(false)
expect(FileTest).to receive(:file?).ordered().with(File.join(base, 'foo.EXE')).and_return(false)
expect(FileTest).to receive(:file?).ordered().with(path).and_return(true)
expect(Puppet::Util.which('foo')).to eq(path)
end
it "should walk the default extension path if the environment variable is not defined" do
allow(ENV).to receive(:fetch).with('PATH').and_return(base)
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(nil)
%w[.COM .EXE .BAT].each do |ext|
expect(FileTest).to receive(:file?).ordered().with(File.join(base, "foo#{ext}")).and_return(false)
end
expect(FileTest).to receive(:file?).ordered().with(path).and_return(true)
expect(Puppet::Util.which('foo')).to eq(path)
end
it "should fall back if no extension matches" do
allow(ENV).to receive(:fetch).with('PATH').and_return(base)
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(".EXE")
allow(FileTest).to receive(:file?).with(File.join(base, 'foo.EXE')).and_return(false)
allow(FileTest).to receive(:file?).with(File.join(base, 'foo')).and_return(true)
allow(FileTest).to receive(:executable?).with(File.join(base, 'foo')).and_return(true)
expect(Puppet::Util.which('foo')).to eq(File.join(base, 'foo'))
end
end
end
end
describe "hash symbolizing functions" do
let (:myhash) { { "foo" => "bar", :baz => "bam" } }
let (:resulthash) { { :foo => "bar", :baz => "bam" } }
describe "#symbolizehash" do
it "should return a symbolized hash" do
newhash = Puppet::Util.symbolizehash(myhash)
expect(newhash).to eq(resulthash)
end
end
end
context "#replace_file" do
subject { Puppet::Util }
it { is_expected.to respond_to :replace_file }
let :target do
target = Tempfile.new("puppet-util-replace-file")
target.puts("hello, world")
target.flush # make sure content is on disk.
target.fsync rescue nil
target.close
target
end
it "should fail if no block is given" do
expect { subject.replace_file(target.path, 0600) }.to raise_error(/block/)
end
it "should replace a file when invoked" do
# Check that our file has the expected content.
expect(File.read(target.path)).to eq("hello, world\n")
# Replace the file.
subject.replace_file(target.path, 0600) do |fh|
fh.puts "I am the passenger..."
end
# ...and check the replacement was complete.
expect(File.read(target.path)).to eq("I am the passenger...\n")
end
# When running with the same user and group sid, which is the default,
# Windows collapses the owner and group modes into a single ACE, resulting
# in set(0600) => get(0660) and so forth. --daniel 2012-03-30
modes = [0555, 0660, 0770]
modes += [0600, 0700] unless Puppet::Util::Platform.windows?
modes.each do |mode|
it "should copy 0#{mode.to_s(8)} permissions from the target file by default" do
set_mode(mode, target.path)
expect(get_mode(target.path)).to eq(mode)
subject.replace_file(target.path, 0000) {|fh| fh.puts "bazam" }
expect(get_mode(target.path)).to eq(mode)
expect(File.read(target.path)).to eq("bazam\n")
end
end
it "should copy the permissions of the source file after yielding on Unix", :if => !Puppet::Util::Platform.windows? do
set_mode(0555, target.path)
inode = Puppet::FileSystem.stat(target.path).ino
yielded = false
subject.replace_file(target.path, 0660) do |fh|
expect(get_mode(fh.path)).to eq(0600)
yielded = true
end
expect(yielded).to be_truthy
expect(Puppet::FileSystem.stat(target.path).ino).not_to eq(inode)
expect(get_mode(target.path)).to eq(0555)
end
it "should be able to create a new file with read-only permissions when it doesn't already exist" do
temp_file = Tempfile.new('puppet-util-replace-file')
temp_path = temp_file.path
temp_file.close
temp_file.unlink
subject.replace_file(temp_path, 0440) do |fh|
fh.puts('some text in there')
end
expect(File.read(temp_path)).to eq("some text in there\n")
expect(get_mode(temp_path)).to eq(0440)
end
it "should use the default permissions if the source file doesn't exist" do
new_target = target.path + '.foo'
expect(Puppet::FileSystem.exist?(new_target)).to be_falsey
begin
subject.replace_file(new_target, 0555) {|fh| fh.puts "foo" }
expect(get_mode(new_target)).to eq(0555)
ensure
Puppet::FileSystem.unlink(new_target) if Puppet::FileSystem.exist?(new_target)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/daemon_spec.rb | spec/unit/daemon_spec.rb | require 'spec_helper'
require 'puppet/daemon'
require 'puppet/agent'
require 'puppet/configurer'
describe Puppet::Daemon, :unless => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
class RecordingScheduler
attr_reader :jobs
def run_loop(jobs)
@jobs = jobs
end
end
let(:agent) { Puppet::Agent.new(Puppet::Configurer, false) }
let(:server) { double("Server", :start => nil, :wait_for_shutdown => nil) }
let(:pidfile) { double("PidFile", :lock => true, :unlock => true, :file_path => 'fake.pid') }
let(:scheduler) { RecordingScheduler.new }
let(:daemon) { Puppet::Daemon.new(agent, pidfile, scheduler) }
before(:each) do
allow(Signal).to receive(:trap)
allow(daemon).to receive(:close_streams).and_return(nil)
end
it "should fail when no agent is provided" do
expect { Puppet::Daemon.new(nil, pidfile, scheduler) }.to raise_error(Puppet::DevError)
end
it "should reopen the Log logs when told to reopen logs" do
expect(Puppet::Util::Log).to receive(:reopen)
daemon.reopen_logs
end
describe "when setting signal traps" do
[:INT, :TERM].each do |signal|
it "logs a notice and exits when sent #{signal}" do
allow(Signal).to receive(:trap).with(signal).and_yield
expect(Puppet).to receive(:notice).with("Caught #{signal}; exiting")
expect(daemon).to receive(:stop)
daemon.set_signal_traps
end
end
{:HUP => :restart, :USR1 => :reload, :USR2 => :reopen_logs}.each do |signal, method|
it "logs a notice and remembers to call #{method} when it receives #{signal}" do
allow(Signal).to receive(:trap).with(signal).and_yield
expect(Puppet).to receive(:notice).with("Caught #{signal}; storing #{method}")
daemon.set_signal_traps
expect(daemon.signals).to eq([method])
end
end
end
describe "when starting" do
let(:reparse_run) { scheduler.jobs[0] }
let(:agent_run) { scheduler.jobs[1] }
before do
allow(daemon).to receive(:set_signal_traps)
end
it "should create its pidfile" do
expect(pidfile).to receive(:lock).and_return(true)
daemon.start
end
it "should fail if it cannot lock" do
expect(pidfile).to receive(:lock).and_return(false)
expect { daemon.start }.to raise_error(RuntimeError, "Could not create PID file: #{pidfile.file_path}")
end
it "disables the reparse of configs if the filetimeout is 0" do
Puppet[:filetimeout] = 0
daemon.start
expect(reparse_run).not_to be_enabled
end
it "does not splay the agent run by default" do
daemon.start
expect(agent_run.splay).to eq(0)
end
describe "and calculating splay" do
before do
# Set file timeout so the daemon reparses
Puppet[:filetimeout] = 1
Puppet[:splay] = true
end
it "recalculates when splaylimit changes" do
daemon.start
Puppet[:splaylimit] = 60
init_splay = agent_run.splay
next_splay = init_splay + 1
allow(agent_run).to receive(:rand).and_return(next_splay)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(next_splay)
end
it "does not change splay if splaylimit is unmodified" do
daemon.start
init_splay = agent_run.splay
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(init_splay)
end
it "recalculates when splay is enabled later" do
Puppet[:splay] = false
daemon.start
Puppet[:splay] = true
allow(agent_run).to receive(:rand).and_return(999)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(999)
end
it "sets splay to 0 when splay is disabled" do
daemon.start
Puppet[:splay] = false
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(0)
end
it "recalculates splay when runinterval is decreased" do
Puppet[:runinterval] = 60
daemon.start
Puppet[:runinterval] = Puppet[:runinterval] - 30
new_splay = agent_run.splay + 1
allow(agent_run).to receive(:rand).and_return(new_splay)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(new_splay)
end
it "recalculates splay when runinterval is increased" do
Puppet[:runinterval] = 60
daemon.start
Puppet[:runinterval] = Puppet[:runinterval] + 30
new_splay = agent_run.splay - 1
allow(agent_run).to receive(:rand).and_return(new_splay)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(new_splay)
end
end
end
describe "when stopping" do
before do
allow(Puppet::Util::Log).to receive(:close_all)
# to make the global safe to mock, set it to a subclass of itself
stub_const('Puppet::Application', Class.new(Puppet::Application))
end
it 'should request a stop from Puppet::Application' do
expect(Puppet::Application).to receive(:stop!)
expect { daemon.stop }.to exit_with 0
end
it "should remove its pidfile" do
expect(pidfile).to receive(:unlock)
expect { daemon.stop }.to exit_with 0
end
it "should close all logs" do
expect(Puppet::Util::Log).to receive(:close_all)
expect { daemon.stop }.to exit_with 0
end
it "should exit unless called with ':exit => false'" do
expect { daemon.stop }.to exit_with 0
end
it "should not exit if called with ':exit => false'" do
daemon.stop :exit => false
end
end
describe "when reloading" do
it "should do nothing if the agent is running" do
expect(agent).to receive(:run).with({:splay => false}).and_raise(Puppet::LockError, 'Failed to aquire lock')
expect(Puppet).to receive(:notice).with('Not triggering already-running agent')
daemon.reload
end
it "should run the agent if one is available and it is not running" do
expect(agent).to receive(:run).with({:splay => false})
expect(Puppet).not_to receive(:notice).with('Not triggering already-running agent')
daemon.reload
end
end
describe "when restarting" do
before do
stub_const('Puppet::Application', Class.new(Puppet::Application))
end
it 'should set Puppet::Application.restart!' do
expect(Puppet::Application).to receive(:restart!)
allow(daemon).to receive(:reexec)
daemon.restart
end
it "should reexec itself if no agent is available" do
expect(daemon).to receive(:reexec)
daemon.restart
end
it "should reexec itself if the agent is not running" do
expect(daemon).to receive(:reexec)
daemon.restart
end
end
describe "when reexecing it self" do
before do
allow(daemon).to receive(:exec)
allow(daemon).to receive(:stop)
end
it "should fail if no argv values are available" do
expect(daemon).to receive(:argv).and_return(nil)
expect { daemon.reexec }.to raise_error(Puppet::DevError)
end
it "should shut down without exiting" do
daemon.argv = %w{foo}
expect(daemon).to receive(:stop).with({:exit => false})
daemon.reexec
end
it "should call 'exec' with the original executable and arguments" do
daemon.argv = %w{foo}
expect(daemon).to receive(:exec).with($0 + " foo")
daemon.reexec
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/property_spec.rb | spec/unit/property_spec.rb | require 'spec_helper'
require 'puppet/property'
Puppet::Type.newtype(:property_test) do
newparam(:name, isnamevar: true)
end
Puppet::Type.type(:property_test).provide(:property_test) do
attr_accessor :foo
end
describe Puppet::Property do
let :resource do
Puppet::Type.type(:property_test).new(:name => "foo")
end
let :subclass do
# We need a completely fresh subclass every time, because we modify both
# class and instance level things inside the tests.
subclass = Class.new(Puppet::Property) do
class << self
attr_accessor :name
end
@name = :foo
end
subclass.initvars
subclass
end
let :property do subclass.new :resource => resource end
it "should be able to look up the modified name for a given value" do
subclass.newvalue(:foo)
expect(subclass.value_name("foo")).to eq(:foo)
end
it "should be able to look up the modified name for a given value matching a regex" do
subclass.newvalue(%r{.})
expect(subclass.value_name("foo")).to eq(%r{.})
end
it "should be able to look up a given value option" do
subclass.newvalue(:foo, :event => :whatever)
expect(subclass.value_option(:foo, :event)).to eq(:whatever)
end
it "should be able to specify required features" do
expect(subclass).to respond_to(:required_features=)
end
{"one" => [:one],:one => [:one],%w{a} => [:a],[:b] => [:b],%w{one two} => [:one,:two],[:a,:b] => [:a,:b]}.each { |in_value,out_value|
it "should always convert required features into an array of symbols (e.g. #{in_value.inspect} --> #{out_value.inspect})" do
subclass.required_features = in_value
expect(subclass.required_features).to eq(out_value)
end
}
it "should return its name as a string when converted to a string" do
expect(property.to_s).to eq(property.name.to_s)
end
describe "when returning the default event name" do
it "should use the current 'should' value to pick the event name" do
expect(property).to receive(:should).and_return("myvalue")
expect(subclass).to receive(:value_option).with('myvalue', :event).and_return(:event_name)
property.event_name
end
it "should return any event defined with the specified value" do
expect(property).to receive(:should).and_return(:myval)
expect(subclass).to receive(:value_option).with(:myval, :event).and_return(:event_name)
expect(property.event_name).to eq(:event_name)
end
describe "and the property is 'ensure'" do
before :each do
allow(property).to receive(:name).and_return(:ensure)
expect(resource).to receive(:type).and_return(:mytype)
end
it "should use <type>_created if the 'should' value is 'present'" do
expect(property).to receive(:should).and_return(:present)
expect(property.event_name).to eq(:mytype_created)
end
it "should use <type>_removed if the 'should' value is 'absent'" do
expect(property).to receive(:should).and_return(:absent)
expect(property.event_name).to eq(:mytype_removed)
end
it "should use <type>_changed if the 'should' value is not 'absent' or 'present'" do
expect(property).to receive(:should).and_return(:foo)
expect(property.event_name).to eq(:mytype_changed)
end
it "should use <type>_changed if the 'should value is nil" do
expect(property).to receive(:should).and_return(nil)
expect(property.event_name).to eq(:mytype_changed)
end
end
it "should use <property>_changed if the property is not 'ensure'" do
allow(property).to receive(:name).and_return(:myparam)
expect(property).to receive(:should).and_return(:foo)
expect(property.event_name).to eq(:myparam_changed)
end
it "should use <property>_changed if no 'should' value is set" do
allow(property).to receive(:name).and_return(:myparam)
expect(property).to receive(:should).and_return(nil)
expect(property.event_name).to eq(:myparam_changed)
end
end
describe "when creating an event" do
before :each do
allow(property).to receive(:should).and_return("myval")
end
it "should use an event from the resource as the base event" do
event = Puppet::Transaction::Event.new
expect(resource).to receive(:event).and_return(event)
expect(property.event).to equal(event)
end
it "should have the default event name" do
expect(property).to receive(:event_name).and_return(:my_event)
expect(property.event.name).to eq(:my_event)
end
it "should have the property's name" do
expect(property.event.property).to eq(property.name.to_s)
end
it "should have the 'should' value set" do
allow(property).to receive(:should).and_return("foo")
expect(property.event.desired_value).to eq("foo")
end
it "should provide its path as the source description" do
allow(property).to receive(:path).and_return("/my/param")
expect(property.event.source_description).to eq("/my/param")
end
it "should have the 'invalidate_refreshes' value set if set on a value" do
allow(property).to receive(:event_name).and_return(:my_event)
allow(property).to receive(:should).and_return("foo")
foo = double()
expect(foo).to receive(:invalidate_refreshes).and_return(true)
collection = double()
expect(collection).to receive(:match?).with("foo").and_return(foo)
allow(property.class).to receive(:value_collection).and_return(collection)
expect(property.event.invalidate_refreshes).to be_truthy
end
it "sets the redacted field on the event when the property is sensitive" do
property.sensitive = true
expect(property.event.redacted).to eq true
end
end
describe "when defining new values" do
it "should define a method for each value created with a block that's not a regex" do
subclass.newvalue(:foo) { }
expect(property).to respond_to(:set_foo)
end
end
describe "when assigning the value" do
it "should just set the 'should' value" do
property.value = "foo"
expect(property.should).to eq("foo")
end
it "should validate each value separately" do
expect(property).to receive(:validate).with("one")
expect(property).to receive(:validate).with("two")
property.value = %w{one two}
end
it "should munge each value separately and use any result as the actual value" do
expect(property).to receive(:munge).with("one").and_return(:one)
expect(property).to receive(:munge).with("two").and_return(:two)
# Do this so we get the whole array back.
subclass.array_matching = :all
property.value = %w{one two}
expect(property.should).to eq([:one, :two])
end
it "should return any set value" do
expect(property.value = :one).to eq(:one)
end
end
describe "when returning the value" do
it "should return nil if no value is set" do
expect(property.should).to be_nil
end
it "should return the first set 'should' value if :array_matching is set to :first" do
subclass.array_matching = :first
property.should = %w{one two}
expect(property.should).to eq("one")
end
it "should return all set 'should' values as an array if :array_matching is set to :all" do
subclass.array_matching = :all
property.should = %w{one two}
expect(property.should).to eq(%w{one two})
end
it "should default to :first array_matching" do
expect(subclass.array_matching).to eq(:first)
end
it "should unmunge the returned value if :array_matching is set to :first" do
property.class.unmunge do |v| v.to_sym end
subclass.array_matching = :first
property.should = %w{one two}
expect(property.should).to eq(:one)
end
it "should unmunge all the returned values if :array_matching is set to :all" do
property.class.unmunge do |v| v.to_sym end
subclass.array_matching = :all
property.should = %w{one two}
expect(property.should).to eq([:one, :two])
end
end
describe "when validating values" do
it "should do nothing if no values or regexes have been defined" do
expect { property.should = "foo" }.not_to raise_error
end
it "should fail if the value is not a defined value or alias and does not match a regex" do
subclass.newvalue(:foo)
expect { property.should = "bar" }.to raise_error(Puppet::Error, /Invalid value "bar"./)
end
it "should succeeed if the value is one of the defined values" do
subclass.newvalue(:foo)
expect { property.should = :foo }.not_to raise_error
end
it "should succeeed if the value is one of the defined values even if the definition uses a symbol and the validation uses a string" do
subclass.newvalue(:foo)
expect { property.should = "foo" }.not_to raise_error
end
it "should succeeed if the value is one of the defined values even if the definition uses a string and the validation uses a symbol" do
subclass.newvalue("foo")
expect { property.should = :foo }.not_to raise_error
end
it "should succeed if the value is one of the defined aliases" do
subclass.newvalue("foo")
subclass.aliasvalue("bar", "foo")
expect { property.should = :bar }.not_to raise_error
end
it "should succeed if the value matches one of the regexes" do
subclass.newvalue(/./)
expect { property.should = "bar" }.not_to raise_error
end
it "should validate that all required features are present" do
subclass.newvalue(:foo, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(true)
property.should = :foo
end
it "should fail if required features are missing" do
subclass.newvalue(:foo, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(false)
expect { property.should = :foo }.to raise_error(Puppet::Error)
end
it "should internally raise an ArgumentError if required features are missing" do
subclass.newvalue(:foo, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(false)
expect { property.validate_features_per_value :foo }.to raise_error(ArgumentError)
end
it "should validate that all required features are present for regexes" do
subclass.newvalue(/./, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(true)
property.should = "foo"
end
it "should support specifying an individual required feature" do
subclass.newvalue(/./, :required_features => :a)
expect(resource.provider).to receive(:satisfies?).and_return(true)
property.should = "foo"
end
end
describe "when munging values" do
it "should do nothing if no values or regexes have been defined" do
expect(property.munge("foo")).to eq("foo")
end
it "should return return any matching defined values" do
subclass.newvalue(:foo)
expect(property.munge("foo")).to eq(:foo)
end
it "should return any matching aliases" do
subclass.newvalue(:foo)
subclass.aliasvalue(:bar, :foo)
expect(property.munge("bar")).to eq(:foo)
end
it "should return the value if it matches a regex" do
subclass.newvalue(/./)
expect(property.munge("bar")).to eq("bar")
end
it "should return the value if no other option is matched" do
subclass.newvalue(:foo)
expect(property.munge("bar")).to eq("bar")
end
end
describe "when syncing the 'should' value" do
it "should set the value" do
subclass.newvalue(:foo)
property.should = :foo
expect(property).to receive(:set).with(:foo)
property.sync
end
end
describe "when setting a value" do
it "should catch exceptions and raise Puppet::Error" do
subclass.newvalue(:foo) { raise "eh" }
expect { property.set(:foo) }.to raise_error(Puppet::Error)
end
it "fails when the provider does not handle the attribute" do
subclass.name = "unknown"
expect { property.set(:a_value) }.to raise_error(Puppet::Error)
end
it "propogates the errors about missing methods from the provider" do
provider = resource.provider
def provider.bad_method=(value)
value.this_method_does_not_exist
end
subclass.name = :bad_method
expect { property.set(:a_value) }.to raise_error(NoMethodError, /this_method_does_not_exist/)
end
describe "that was defined without a block" do
it "should call the settor on the provider" do
subclass.newvalue(:bar)
expect(resource.provider).to receive(:foo=).with(:bar)
property.set(:bar)
end
it "should generate setter named from :method argument and propagate call to the provider" do
subclass.newvalue(:bar, :method => 'set_vv')
expect(resource.provider).to receive(:foo=).with(:bar)
property.set_vv(:bar)
end
end
describe "that was defined with a block" do
it "should call the method created for the value if the value is not a regex" do
subclass.newvalue(:bar) {}
expect(property).to receive(:set_bar)
property.set(:bar)
end
it "should call the provided block if the value is a regex" do
thing = double
subclass.newvalue(/./) { thing.test }
expect(thing).to receive(:test)
property.set("foo")
end
end
end
describe "when producing a change log" do
it "should say 'defined' when the current value is 'absent'" do
expect(property.change_to_s(:absent, "foo")).to match(/^defined/)
end
it "should say 'undefined' when the new value is 'absent'" do
expect(property.change_to_s("foo", :absent)).to match(/^undefined/)
end
it "should say 'changed' when neither value is 'absent'" do
expect(property.change_to_s("foo", "bar")).to match(/changed/)
end
end
shared_examples_for "#insync?" do
# We share a lot of behaviour between the all and first matching, so we
# use a shared behaviour set to emulate that. The outside world makes
# sure the class, etc, point to the right content.
[[], [12], [12, 13]].each do |input|
it "should return true if should is empty with is => #{input.inspect}" do
property.should = []
expect(property).to be_insync(input)
expect(property.insync_values?([], input)).to be true
end
end
end
describe "#insync?" do
context "array_matching :all" do
# `@should` is an array of scalar values, and `is` is an array of scalar values.
before :each do
property.class.array_matching = :all
end
it_should_behave_like "#insync?"
context "if the should value is an array" do
let(:input) { [1,2] }
before :each do property.should = input end
it "should match if is exactly matches" do
val = [1, 2]
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
it "should match if it matches, but all stringified" do
val = ["1", "2"]
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
it "should not match if some-but-not-all values are stringified" do
val = ["1", 2]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
val = [1, "2"]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if order is different but content the same" do
val = [2, 1]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if there are more items in should than is" do
val = [1]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if there are less items in should than is" do
val = [1, 2, 3]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if `is` is empty but `should` isn't" do
val = []
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
end
end
context "array_matching :first" do
# `@should` is an array of scalar values, and `is` is a scalar value.
before :each do
property.class.array_matching = :first
end
it_should_behave_like "#insync?"
[[1], # only the value
[1, 2], # matching value first
[2, 1], # matching value last
[0, 1, 2], # matching value in the middle
].each do |input|
it "should by true if one unmodified should value of #{input.inspect} matches what is" do
val = 1
property.should = input
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
it "should be true if one stringified should value of #{input.inspect} matches what is" do
val = "1"
property.should = input
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
end
it "should not match if we expect a string but get the non-stringified value" do
property.should = ["1"]
expect(property).to_not be_insync 1
expect(property.insync_values?(["1"], 1)).to_not be true
end
[[0], [0, 2]].each do |input|
it "should not match if no should values match what is" do
property.should = input
expect(property).to_not be_insync 1
expect(property.insync_values?(input, 1)).to_not be true
expect(property).to_not be_insync "1" # shouldn't match either.
expect(property.insync_values?(input, "1")).to_not be true
end
end
end
end
describe "#property_matches?" do
[1, "1", [1], :one].each do |input|
it "should treat two equal objects as equal (#{input.inspect})" do
expect(property.property_matches?(input, input)).to be_truthy
end
end
it "should treat two objects as equal if the first argument is the stringified version of the second" do
expect(property.property_matches?("1", 1)).to be_truthy
end
it "should NOT treat two objects as equal if the first argument is not a string, and the second argument is a string, even if it stringifies to the first" do
expect(property.property_matches?(1, "1")).to be_falsey
end
end
describe "#insync_values?" do
it "should log an exception when insync? throws one" do
expect(property).to receive(:insync?).and_raise(ArgumentError)
expect(property.insync_values?("foo","bar")).to be nil
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/settings_spec.rb | spec/unit/settings_spec.rb | require 'spec_helper'
require 'ostruct'
require 'puppet/settings/errors'
require 'puppet_spec/files'
require 'matchers/resource'
describe Puppet::Settings do
include PuppetSpec::Files
include Matchers::Resource
let(:main_config_file_default_location) do
File.join(Puppet::Util::RunMode[:server].conf_dir, "puppet.conf")
end
let(:user_config_file_default_location) do
File.join(Puppet::Util::RunMode[:user].conf_dir, "puppet.conf")
end
# Return a given object's file metadata.
def metadata(setting)
if setting.is_a?(Puppet::Settings::FileSetting)
{
:owner => setting.owner,
:group => setting.group,
:mode => setting.mode
}.delete_if { |key, value| value.nil? }
else
nil
end
end
def stub_config_with(content)
allow(Puppet.features).to receive(:root?).and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).
with(user_config_file_default_location).
and_return(true).ordered
expect(@settings).to receive(:read_file).
with(user_config_file_default_location).
and_return(content).ordered
@settings.send(:parse_config_files)
end
describe "when specifying defaults" do
before do
@settings = Puppet::Settings.new
end
it "should start with no defined sections or parameters" do
# Note this relies on undocumented side effect that eachsection returns the Settings internal
# configuration on which keys returns all parameters.
expect(@settings.eachsection.keys.length).to eq(0)
end
it "should not allow specification of default values associated with a section as an array" do
expect {
@settings.define_settings(:section, :myvalue => ["defaultval", "my description"])
}.to raise_error(ArgumentError, /setting definition for 'myvalue' is not a hash!/)
end
it "should not allow duplicate parameter specifications" do
@settings.define_settings(:section, :myvalue => { :default => "a", :desc => "b" })
expect { @settings.define_settings(:section, :myvalue => { :default => "c", :desc => "d" }) }.to raise_error(ArgumentError)
end
it "should allow specification of default values associated with a section as a hash" do
@settings.define_settings(:section, :myvalue => {:default => "defaultval", :desc => "my description"})
end
it "should consider defined parameters to be valid" do
@settings.define_settings(:section, :myvalue => { :default => "defaultval", :desc => "my description" })
expect(@settings.valid?(:myvalue)).to be_truthy
end
it "should require a description when defaults are specified with a hash" do
expect { @settings.define_settings(:section, :myvalue => {:default => "a value"}) }.to raise_error(ArgumentError)
end
it "should support specifying owner, group, and mode when specifying files" do
@settings.define_settings(:section, :myvalue => {:type => :file, :default => "/some/file", :owner => "service", :mode => "boo", :group => "service", :desc => "whatever"})
end
it "should support specifying a short name" do
@settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
end
it "should support specifying the setting type" do
@settings.define_settings(:section, :myvalue => {:default => "/w", :desc => "b", :type => :string})
expect(@settings.setting(:myvalue)).to be_instance_of(Puppet::Settings::StringSetting)
end
it "should fail if an invalid setting type is specified" do
expect { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :type => :foo}) }.to raise_error(ArgumentError)
end
it "should fail when short names conflict" do
@settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
expect { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"}) }.to raise_error(ArgumentError)
end
end
describe "when initializing application defaults do" do
before do
@settings = Puppet::Settings.new
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
end
it "should fail if the app defaults hash is missing any required values" do
expect {
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.reject { |key, _| key == :confdir })
}.to raise_error(Puppet::Settings::SettingsError)
end
# ultimately I'd like to stop treating "run_mode" as a normal setting, because it has so many special
# case behaviors / uses. However, until that time... we need to make sure that our private run_mode=
# setter method gets properly called during app initialization.
it "sets the preferred run mode when initializing the app defaults" do
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :server))
expect(@settings.preferred_run_mode).to eq(:server)
end
it "creates ancestor directories for all required app settings" do
# initialize_app_defaults is called in spec_helper, before we even
# get here, but call it here to make it explicit what we're trying
# to do.
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
Puppet::Settings::REQUIRED_APP_SETTINGS.each do |key|
expect(File).to exist(File.dirname(Puppet[key]))
end
end
end
describe "#call_hooks_deferred_to_application_initialization" do
let(:good_default) { "yay" }
let(:bad_default) { "$doesntexist" }
before(:each) do
@settings = Puppet::Settings.new
end
describe "when ignoring dependency interpolation errors" do
let(:options) { {:ignore_interpolation_dependency_errors => true} }
describe "if interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(:section, :badhook => {:default => bad_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
describe "if no interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(:section, :goodhook => {:default => good_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
end
describe "when not ignoring dependency interpolation errors" do
[ {}, {:ignore_interpolation_dependency_errors => false}].each do |options|
describe "if interpolation error" do
it "should raise an error" do
hook_values = []
@settings.define_settings(
:section,
:badhook => {
:default => bad_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to raise_error(Puppet::Settings::InterpolationError)
end
it "should contain the setting name in error message" do
hook_values = []
@settings.define_settings(
:section,
:badhook => {
:default => bad_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to raise_error(Puppet::Settings::InterpolationError, /badhook/)
end
end
describe "if no interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(
:section,
:goodhook => {
:default => good_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
end
end
end
describe "when setting values" do
before do
@settings = Puppet::Settings.new
@settings.define_settings :main, :myval => { :default => "val", :desc => "desc" }
@settings.define_settings :main, :bool => { :type => :boolean, :default => true, :desc => "desc" }
end
it "should provide a method for setting values from other objects" do
@settings[:myval] = "something else"
expect(@settings[:myval]).to eq("something else")
end
it "should support a getopt-specific mechanism for setting values" do
@settings.handlearg("--myval", "newval")
expect(@settings[:myval]).to eq("newval")
end
it "should support a getopt-specific mechanism for turning booleans off" do
@settings.override_default(:bool, true)
@settings.handlearg("--no-bool", "")
expect(@settings[:bool]).to eq(false)
end
it "should support a getopt-specific mechanism for turning booleans on" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool", "")
expect(@settings[:bool]).to eq(true)
end
it "should consider a cli setting with no argument to be a boolean" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool")
expect(@settings[:bool]).to eq(true)
end
it "should consider a cli setting with an empty string as an argument to be an empty argument, if the setting itself is not a boolean" do
@settings.override_default(:myval, "bob")
@settings.handlearg("--myval", "")
expect(@settings[:myval]).to eq("")
end
it "should consider a cli setting with a boolean as an argument to be a boolean" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool", "true")
expect(@settings[:bool]).to eq(true)
end
it "should not consider a cli setting of a non boolean with a boolean as an argument to be a boolean" do
@settings.override_default(:myval, "bob")
@settings.handlearg("--no-myval", "")
expect(@settings[:myval]).to eq("")
end
it "should retrieve numeric settings from the CLI" do
@settings.handlearg("--myval", "12")
expect(@settings.set_by_cli(:myval)).to eq("12")
expect(@settings.set_by_cli?(:myval)).to be true
end
it "should retrieve string settings from the CLI" do
@settings.handlearg("--myval", "something")
expect(@settings.set_by_cli(:myval)).to eq("something")
expect(@settings.set_by_cli?(:myval)).to be true
end
it "should retrieve bool settings from the CLI" do
@settings.handlearg("--bool")
expect(@settings.set_by_cli(:bool)).to be true
expect(@settings.set_by_cli?(:bool)).to be true
end
it "should not retrieve settings set in memory as from CLI" do
@settings[:myval] = "12"
expect(@settings.set_by_cli?(:myval)).to be false
end
it "should find no configured settings by default" do
expect(@settings.set_by_config?(:myval)).to be false
end
it "should identify configured settings in memory" do
expect(@settings.instance_variable_get(:@value_sets)[:memory]).to receive(:lookup).with(:myval).and_return('foo')
expect(@settings.set_by_config?(:myval)).to be_truthy
end
it "should identify configured settings from CLI" do
expect(@settings.instance_variable_get(:@value_sets)[:cli]).to receive(:lookup).with(:myval).and_return('foo')
expect(@settings.set_by_config?(:myval)).to be_truthy
end
it "should not identify configured settings from environment by default" do
expect(Puppet.lookup(:environments)).not_to receive(:get_conf).with(Puppet[:environment].to_sym)
expect(@settings.set_by_config?(:manifest)).to be_falsey
end
it "should identify configured settings from environment by when an environment is specified" do
foo = double('environment', :manifest => 'foo')
expect(Puppet.lookup(:environments)).to receive(:get_conf).with(Puppet[:environment].to_sym).and_return(foo)
expect(@settings.set_by_config?(:manifest, Puppet[:environment])).to be_truthy
end
context "when handling puppet.conf" do
describe "#set_by_config?" do
it "should identify configured settings from the preferred run mode" do
stub_config_with(<<~CONFIG)
[#{@settings.preferred_run_mode}]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval)).to be_truthy
end
it "should identify configured settings from the specified run mode" do
stub_config_with(<<~CONFIG)
[server]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval, nil, :server)).to be_truthy
end
it "should not identify configured settings from an unspecified run mode" do
stub_config_with(<<~CONFIG)
[zaz]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval)).to be_falsey
end
it "should identify configured settings from the main section" do
stub_config_with(<<~CONFIG)
[main]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval)).to be_truthy
end
end
describe "#set_in_section" do
it "should retrieve configured settings from the specified section" do
stub_config_with(<<~CONFIG)
[agent]
myval = foo
CONFIG
expect(@settings.set_in_section(:myval, :agent)).to eq("foo")
expect(@settings.set_in_section?(:myval, :agent)).to be true
end
it "should not retrieve configured settings from a different section" do
stub_config_with(<<~CONFIG)
[main]
myval = foo
CONFIG
expect(@settings.set_in_section(:myval, :agent)).to be nil
expect(@settings.set_in_section?(:myval, :agent)).to be false
end
end
end
it "should clear the cache when setting getopt-specific values" do
@settings.define_settings :mysection,
:one => { :default => "whah", :desc => "yay" },
:two => { :default => "$one yay", :desc => "bah" }
expect(@settings).to receive(:unsafe_flush_cache)
expect(@settings[:two]).to eq("whah yay")
@settings.handlearg("--one", "else")
expect(@settings[:two]).to eq("else yay")
end
it "should clear the cache when the preferred_run_mode is changed" do
expect(@settings).to receive(:flush_cache)
@settings.preferred_run_mode = :server
end
it "should not clear other values when setting getopt-specific values" do
@settings[:myval] = "yay"
@settings.handlearg("--no-bool", "")
expect(@settings[:myval]).to eq("yay")
end
it "should clear the list of used sections" do
expect(@settings).to receive(:clearused)
@settings[:myval] = "yay"
end
describe "call_hook" do
let(:config_file) { tmpfile('config') }
before :each do
# We can't specify the config file to read from using `Puppet[:config] =`
# or pass it as an arg to Puppet.initialize_global_settings, because
# both of those will set the value on the `Puppet.settings` instance
# which is different from the `@settings` instance created in the test.
# Instead, we define a `:config` setting and set its default value to
# the `config_file` temp file, and then access the `config_file` within
# each test.
@settings.define_settings(:main, :config => { :type => :file, :desc => "config file", :default => config_file })
end
Puppet::Settings::StringSetting.available_call_hook_values.each do |val|
describe "when :#{val}" do
describe "and definition invalid" do
it "should raise error if no hook defined" do
expect do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => val})
end.to raise_error(ArgumentError, /no :hook/)
end
it "should include the setting name in the error message" do
expect do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => val})
end.to raise_error(ArgumentError, /for :setting/)
end
end
describe "and definition valid" do
before(:each) do
hook_values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => val, :hook => lambda { |v| hook_values << v }})
end
it "should call the hook when value written" do
expect(@settings.setting(:setting)).to receive(:handle).with("something").once
@settings[:setting] = "something"
end
end
end
end
it "should have a default value of :on_write_only" do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
expect(@settings.setting(:setting).call_hook).to eq(:on_write_only)
end
describe "when nil" do
it "should generate a warning" do
expect(Puppet).to receive(:warning)
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v }})
end
it "should use default" do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v }})
expect(@settings.setting(:setting).call_hook).to eq(:on_write_only)
end
end
describe "when invalid" do
it "should raise an error" do
expect do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => :foo, :hook => lambda { |v| hook_values << v }})
end.to raise_error(ArgumentError, /invalid.*call_hook/i)
end
end
describe "when :on_write_only" do
it "returns its hook type" do
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |_| }})
expect(@settings.setting(:setting).call_hook).to eq(:on_write_only)
end
it "should not call the hook at definition" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
expect(hook_values).to eq(%w[])
end
it "calls the hook when initializing global defaults with the value from the `main` section" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
END
@settings.initialize_global_settings
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[in_main])
end
it "doesn't call the hook when initializing app defaults" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[])
end
it "doesn't call the hook with value from a section that matches the run_mode" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :agent))
expect(@settings[:setting]).to eq('in_agent')
expect(hook_values).to eq(%w[])
end
end
describe "when :on_define_and_write" do
it "returns its hook type" do
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |_| }})
expect(@settings.setting(:setting).call_hook).to eq(:on_define_and_write)
end
it "should call the hook at definition with the default value" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
expect(hook_values).to eq(%w[yay])
end
it "calls the hook when initializing global defaults with the value from the `main` section" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
END
@settings.initialize_global_settings
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[yay in_main])
end
it "doesn't call the hook when initializing app defaults" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq([])
end
it "doesn't call the hook with value from a section that matches the run_mode" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :agent))
# The correct value is returned
expect(@settings[:setting]).to eq('in_agent')
# but the hook is never called, seems like a bug!
expect(hook_values).to eq([])
end
end
describe "when :on_initialize_and_write" do
it "returns its hook type" do
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |_| }})
expect(@settings.setting(:setting).call_hook).to eq(:on_initialize_and_write)
end
it "should not call the hook at definition" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect(hook_values).to eq([])
end
it "calls the hook when initializing global defaults with the value from the `main` section" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
END
@settings.initialize_global_settings
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[in_main])
end
it "calls the hook when initializing app defaults" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[in_main])
end
it "calls the hook with the overridden value from a section that matches the run_mode" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :agent))
expect(@settings[:setting]).to eq('in_agent')
expect(hook_values).to eq(%w[in_agent])
end
end
end
it "should call passed blocks when values are set" do
values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
expect(values).to eq([])
@settings[:setting] = "something"
expect(values).to eq(%w{something})
end
it "should call passed blocks when values are set via the command line" do
values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
expect(values).to eq([])
@settings.handlearg("--setting", "yay")
expect(values).to eq(%w{yay})
end
it "should provide an option to call passed blocks during definition" do
values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
expect(values).to eq(%w{yay})
end
it "should pass the fully interpolated value to the hook when called on definition" do
values = []
@settings.define_settings(:section, :one => { :default => "test", :desc => "a" })
@settings.define_settings(:section, :setting => {:default => "$one/yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
expect(values).to eq(%w{test/yay})
end
it "should munge values using the setting-specific methods" do
@settings[:bool] = "false"
expect(@settings[:bool]).to eq(false)
end
it "should prefer values set in ruby to values set on the cli" do
@settings[:myval] = "memarg"
@settings.handlearg("--myval", "cliarg")
expect(@settings[:myval]).to eq("memarg")
end
it "should raise an error if we try to set a setting that hasn't been defined'" do
expect{
@settings[:why_so_serious] = "foo"
}.to raise_error(ArgumentError, /unknown setting/)
end
it "allows overriding cli args based on the cli-set value" do
@settings.handlearg("--myval", "cliarg")
@settings.patch_value(:myval, "modified #{@settings[:myval]}", :cli)
expect(@settings[:myval]).to eq("modified cliarg")
end
end
describe "when returning values" do
before do
@settings = Puppet::Settings.new
@settings.define_settings :section,
:config => { :type => :file, :default => "/my/file", :desc => "eh" },
:one => { :default => "ONE", :desc => "a" },
:two => { :default => "$one TWO", :desc => "b"},
:three => { :default => "$one $two THREE", :desc => "c"},
:four => { :default => "$two $three FOUR", :desc => "d"},
:five => { :default => nil, :desc => "e" },
:code => { :default => "", :desc => "my code"}
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
end
it "should provide a mechanism for returning set values" do
@settings[:one] = "other"
expect(@settings[:one]).to eq("other")
end
it "setting a value to nil causes it to return to its default" do
@settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:one => "skipped value"))
@settings[:one] = "value will disappear"
@settings[:one] = nil
expect(@settings[:one]).to eq("ONE")
end
it "should interpolate default values for other parameters into returned parameter values" do
expect(@settings[:one]).to eq("ONE")
expect(@settings[:two]).to eq("ONE TWO")
expect(@settings[:three]).to eq("ONE ONE TWO THREE")
end
it "should interpolate default values that themselves need to be interpolated" do
expect(@settings[:four]).to eq("ONE TWO ONE ONE TWO THREE FOUR")
end
it "should provide a method for returning uninterpolated values" do
@settings[:two] = "$one tw0"
expect(@settings.value(:two, nil, true)).to eq("$one tw0")
expect(@settings.value(:four, nil, true)).to eq("$two $three FOUR")
end
it "should interpolate set values for other parameters into returned parameter values" do
@settings[:one] = "on3"
@settings[:two] = "$one tw0"
@settings[:three] = "$one $two thr33"
@settings[:four] = "$one $two $three f0ur"
expect(@settings[:one]).to eq("on3")
expect(@settings[:two]).to eq("on3 tw0")
expect(@settings[:three]).to eq("on3 on3 tw0 thr33")
expect(@settings[:four]).to eq("on3 on3 tw0 on3 on3 tw0 thr33 f0ur")
end
it "should not cache interpolated values such that stale information is returned" do
expect(@settings[:two]).to eq("ONE TWO")
@settings[:one] = "one"
expect(@settings[:two]).to eq("one TWO")
end
it "should not interpolate the value of the :code setting" do
@code = @settings.setting(:code)
expect(@code).not_to receive(:munge)
expect(@settings[:code]).to eq("")
end
it "should have a run_mode that defaults to user" do
expect(@settings.preferred_run_mode).to eq(:user)
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions4_spec.rb | spec/unit/functions4_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
module FunctionAPISpecModule
class TestDuck
end
class TestFunctionLoader < Puppet::Pops::Loader::StaticLoader
def initialize
@constants = {}
end
def add_function(name, function)
set_entry(Puppet::Pops::Loader::TypedName.new(:function, name), function, __FILE__)
end
def add_type(name, type)
set_entry(Puppet::Pops::Loader::TypedName.new(:type, name), type, __FILE__)
end
def set_entry(typed_name, value, origin = nil)
@constants[typed_name] = Puppet::Pops::Loader::Loader::NamedEntry.new(typed_name, value, origin)
end
# override StaticLoader
def load_constant(typed_name)
@constants[typed_name]
end
end
end
describe 'the 4x function api' do
include FunctionAPISpecModule
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:loader) { FunctionAPISpecModule::TestFunctionLoader.new }
def parse_eval(code, here)
if here.respond_to?(:source_location)
eval(code, here, here.source_location[0], here.source_location[1])
else
# this can be removed when ruby < 2.6 is dropped
eval(code, here)
end
end
it 'allows a simple function to be created without dispatch declaration' do
f = Puppet::Functions.create_function('min') do
def min(x,y)
x <= y ? x : y
end
end
# the produced result is a Class inheriting from Function
expect(f.class).to be(Class)
expect(f.superclass).to be(Puppet::Functions::Function)
# and this class had the given name (not a real Ruby class name)
expect(f.name).to eql('min')
end
it 'refuses to create functions that are not based on the Function class' do
expect do
Puppet::Functions.create_function('testing', Object) {}
end.to raise_error(ArgumentError, /function 'testing'.*Functions must be based on Puppet::Pops::Functions::Function. Got Object/)
end
it 'refuses to create functions with parameters that are not named with a symbol' do
expect do
Puppet::Functions.create_function('testing') do
dispatch :test do
param 'Integer', 'not_symbol'
end
def test(x)
end
end
end.to raise_error(ArgumentError, /Parameter name argument must be a Symbol/)
end
it 'a function without arguments can be defined and called without dispatch declaration' do
f = create_noargs_function_class()
func = f.new(:closure_scope, :loader)
expect(func.call({})).to eql(10)
end
it 'an error is raised when calling a no arguments function with arguments' do
f = create_noargs_function_class()
func = f.new(:closure_scope, :loader)
expect{func.call({}, 'surprise')}.to raise_error(ArgumentError, "'test' expects no arguments, got 1")
end
it 'a simple function can be called' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect(func.call({}, 10,20)).to eql(10)
end
it 'an error is raised if called with too few arguments' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10)
end.to raise_error(ArgumentError, "'min' expects 2 arguments, got 1")
end
it 'an error is raised if called with too many arguments' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, 10, 10)
end.to raise_error(ArgumentError, "'min' expects 2 arguments, got 3")
end
it 'correct dispatch is chosen when zero parameter dispatch exists' do
f = create_function_with_no_parameter_dispatch
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect(func.call({}, 1)).to eql(1)
end
it 'an error is raised if simple function-name and method are not matched' do
expect do
create_badly_named_method_function_class()
end.to raise_error(ArgumentError, /Function Creation Error, cannot create a default dispatcher for function 'mix', no method with this name found/)
end
it 'the implementation separates dispatchers for different functions' do
# this tests that meta programming / construction puts class attributes in the correct class
f1 = create_min_function_class()
f2 = create_max_function_class()
d1 = f1.dispatcher
d2 = f2.dispatcher
expect(d1).to_not eql(d2)
expect(d1.dispatchers[0]).to_not eql(d2.dispatchers[0])
end
context 'when using regular dispatch' do
it 'a function can be created using dispatch and called' do
f = create_min_function_class_using_dispatch()
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3,4)).to eql(3)
end
it 'an error is raised with reference to given parameter names when called with mis-matched arguments' do
f = create_min_function_class_using_dispatch()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, 'ten')
end.to raise_error(ArgumentError, "'min' parameter 'b' expects a Numeric value, got String")
end
it 'an error includes optional indicators for last element' do
f = create_function_with_optionals_and_repeated_via_multiple_dispatch()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 3, 10, 3, "4")
end.to raise_error(ArgumentError, "The function 'min' was called with arguments it does not accept. It expects one of:
(Numeric x, Numeric y, Numeric a?, Numeric b?, Numeric c*)
rejected: parameter 'b' expects a Numeric value, got String
(String x, String y, String a+)
rejected: parameter 'x' expects a String value, got Integer")
end
it 'can create optional repeated parameter' do
f = create_function_with_repeated
func = f.new(:closure_scope, :loader)
expect(func.call({})).to eql(0)
expect(func.call({}, 1)).to eql(1)
expect(func.call({}, 1, 2)).to eql(2)
f = create_function_with_optional_repeated
func = f.new(:closure_scope, :loader)
expect(func.call({})).to eql(0)
expect(func.call({}, 1)).to eql(1)
expect(func.call({}, 1, 2)).to eql(2)
end
it 'can create required repeated parameter' do
f = create_function_with_required_repeated
func = f.new(:closure_scope, :loader)
expect(func.call({}, 1)).to eql(1)
expect(func.call({}, 1, 2)).to eql(2)
expect { func.call({}) }.to raise_error(ArgumentError, "'count_args' expects at least 1 argument, got none")
end
it 'can create scope_param followed by repeated parameter' do
f = create_function_with_scope_param_required_repeat
func = f.new(:closure_scope, :loader)
expect(func.call({}, 'yay', 1,2,3)).to eql([{}, 'yay',1,2,3])
end
it 'a function can use inexact argument mapping' do
f = create_function_with_inexact_dispatch
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3.0,4.0,5.0)).to eql([Float, Float, Float])
expect(func.call({}, 'Apple', 'Banana')).to eql([String, String])
end
it 'a function can be created using dispatch and called' do
f = create_min_function_class_disptaching_to_two_methods()
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3,4)).to eql(3)
expect(func.call({}, 'Apple', 'Banana')).to eql('Apple')
end
it 'a function can not be created with parameters declared after a repeated parameter' do
expect { create_function_with_param_after_repeated }.to raise_error(ArgumentError,
/function 't1'.*Parameters cannot be added after a repeated parameter/)
end
it 'a function can not be created with required parameters declared after optional ones' do
expect { create_function_with_rq_after_opt }.to raise_error(ArgumentError,
/function 't1'.*A required parameter cannot be added after an optional parameter/)
end
it 'a function can not be created with required repeated parameters declared after optional ones' do
expect { create_function_with_rq_repeated_after_opt }.to raise_error(ArgumentError,
/function 't1'.*A required repeated parameter cannot be added after an optional parameter/)
end
it 'an error is raised with reference to multiple methods when called with mis-matched arguments' do
f = create_min_function_class_disptaching_to_two_methods()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, '20')
end.to raise_error(ArgumentError, "The function 'min' was called with arguments it does not accept. It expects one of:
(Numeric a, Numeric b)
rejected: parameter 'b' expects a Numeric value, got String
(String s1, String s2)
rejected: parameter 's1' expects a String value, got Integer")
end
context 'an argument_mismatch handler' do
let(:func) { create_function_with_mismatch_handler.new(:closure_scope, :loader) }
it 'is called on matching arguments' do
expect { func.call({}, '1') }.to raise_error(ArgumentError, "'test' It's not OK to pass a string")
end
it 'is not called unless arguments are matching' do
expect { func.call({}, '1', 3) }.to raise_error(ArgumentError, "'test' expects 1 argument, got 2")
end
it 'is not included in a signature mismatch description' do
expect { func.call({}, 2.3) }.to raise_error { |e| expect(e.message).not_to match(/String/) }
end
end
context 'when requesting a type' do
it 'responds with a Callable for a single signature' do
tf = Puppet::Pops::Types::TypeFactory
fc = create_min_function_class_using_dispatch()
t = fc.dispatcher.to_type
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t.param_types.types).to eql([tf.numeric(), tf.numeric()])
expect(t.block_type).to be_nil
end
it 'responds with a Variant[Callable...] for multiple signatures' do
tf = Puppet::Pops::Types::TypeFactory
fc = create_min_function_class_disptaching_to_two_methods()
t = fc.dispatcher.to_type
expect(t.class).to be(Puppet::Pops::Types::PVariantType)
expect(t.types.size).to eql(2)
t1 = t.types[0]
expect(t1.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t1.param_types.types).to eql([tf.numeric(), tf.numeric()])
expect(t1.block_type).to be_nil
t2 = t.types[1]
expect(t2.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t2.param_types.types).to eql([tf.string(), tf.string()])
expect(t2.block_type).to be_nil
end
end
context 'supports lambdas' do
it 'such that, a required block can be defined and given as an argument' do
the_function = create_function_with_required_block_all_defaults().new(:closure_scope, :loader)
result = the_function.call({}, 7) { |a,b| a < b ? a : b }
expect(result).to eq(7)
end
it 'such that, a missing required block when called raises an error' do
the_function = create_function_with_required_block_all_defaults().new(:closure_scope, :loader)
expect do
the_function.call({}, 10)
end.to raise_error(ArgumentError, "'test' expects a block")
end
it 'such that, an optional block can be defined and given as an argument' do
the_function = create_function_with_optional_block_all_defaults().new(:closure_scope, :loader)
result = the_function.call({}, 4) { |a,b| a < b ? a : b }
expect(result).to eql(4)
end
it 'such that, an optional block can be omitted when called and gets the value nil' do
the_function = create_function_with_optional_block_all_defaults().new(:closure_scope, :loader)
expect(the_function.call({}, 2)).to be_nil
end
it 'such that, a scope can be injected and a block can be used' do
the_function = create_function_with_scope_required_block_all_defaults().new(:closure_scope, :loader)
expect(the_function.call({}, 1) { |a,b| a < b ? a : b }).to eql(1)
end
end
context 'provides signature information' do
it 'about capture rest (varargs)' do
fc = create_function_with_optionals_and_repeated
signatures = fc.signatures
expect(signatures.size).to eql(1)
signature = signatures[0]
expect(signature.last_captures_rest?).to be_truthy
end
it 'about optional and required parameters' do
fc = create_function_with_optionals_and_repeated
signature = fc.signatures[0]
expect(signature.args_range).to eql( [2, Float::INFINITY ] )
expect(signature.infinity?(signature.args_range[1])).to be_truthy
end
it 'about block not being allowed' do
fc = create_function_with_optionals_and_repeated
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 0, 0 ] )
expect(signature.block_type).to be_nil
end
it 'about required block' do
fc = create_function_with_required_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 1, 1 ] )
expect(signature.block_type).to_not be_nil
end
it 'about optional block' do
fc = create_function_with_optional_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 0, 1 ] )
expect(signature.block_type).to_not be_nil
end
it 'about the type' do
fc = create_function_with_optional_block_all_defaults
signature = fc.signatures[0]
expect(signature.type.class).to be(Puppet::Pops::Types::PCallableType)
end
it 'about parameter names obtained from ruby introspection' do
fc = create_min_function_class
signature = fc.signatures[0]
expect(signature.parameter_names).to eql(['x', 'y'])
end
it 'about parameter names specified with dispatch' do
fc = create_min_function_class_using_dispatch
signature = fc.signatures[0]
expect(signature.parameter_names).to eql([:a, :b])
end
it 'about block_name when it is *not* given in the definition' do
# neither type, nor name
fc = create_function_with_required_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_name).to eql(:block)
# no name given, only type
fc = create_function_with_required_block_given_type
signature = fc.signatures[0]
expect(signature.block_name).to eql(:block)
end
it 'about block_name when it *is* given in the definition' do
# neither type, nor name
fc = create_function_with_required_block_default_type
signature = fc.signatures[0]
expect(signature.block_name).to eql(:the_block)
# no name given, only type
fc = create_function_with_required_block_fully_specified
signature = fc.signatures[0]
expect(signature.block_name).to eql(:the_block)
end
end
context 'supports calling other functions' do
before(:each) do
Puppet.push_context( {:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))})
end
after(:each) do
Puppet.pop_context()
end
it 'such that, other functions are callable by name' do
fc = Puppet::Functions.create_function('test') do
def test()
# Call a function available in the puppet system
call_function('assert_type', 'Integer', 10)
end
end
# initiate the function the same way the loader initiates it
f = fc.new(:closure_scope, Puppet.lookup(:loaders).puppet_system_loader)
expect(f.call({})).to eql(10)
end
it 'such that, calling a non existing function raises an error' do
fc = Puppet::Functions.create_function('test') do
def test()
# Call a function not available in the puppet system
call_function('no_such_function', 'Integer', 'hello')
end
end
# initiate the function the same way the loader initiates it
f = fc.new(:closure_scope, Puppet.lookup(:loaders).puppet_system_loader)
expect{f.call({})}.to raise_error(ArgumentError, "Function test(): Unknown function: 'no_such_function'")
end
end
context 'functions in a context with a compiler' do
before(:each) do
Puppet.push_context( {:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))})
end
after(:each) do
Puppet.pop_context()
end
before(:each) do
Puppet[:strict_variables] = true
end
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
let(:node) { 'node.example.com' }
let(:scope) { s = create_test_scope_for_node(node); s }
let(:loader) { Puppet::Pops::Loaders.find_loader(nil) }
context 'supports calling ruby functions with lambda from puppet' do
it 'function with required block can be called' do
# construct ruby function to call
fc = Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'Integer', :x
# block called 'the_block', and using "all_callables"
required_block_param #(all_callables(), 'the_block')
end
def test(x)
# call the block with x
yield(x)
end
end
# add the function to the loader (as if it had been loaded from somewhere)
the_loader = loader
f = fc.new({}, the_loader)
loader.set_entry(Puppet::Pops::Loader::TypedName.new(:function, 'testing::test'), f)
# evaluate a puppet call
source = "testing::test(10) |$x| { $x+1 }"
program = parser.parse_string(source, __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).at_least(:once).and_return(the_loader)
expect(parser.evaluate(scope, program)).to eql(11)
end
end
it 'supports injection of a cache' do
the_function = create_function_with_cache_param.new(:closure_scope, :loader)
expect(the_function.call(scope, 'key', 10)).to eql(nil)
expect(the_function.call(scope, 'key', 20)).to eql(10)
expect(the_function.call(scope, 'key', 30)).to eql(20)
end
end
context 'reports meaningful errors' do
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
it 'syntax error in local type is reported with puppet source, puppet location, and ruby file containing function' do
the_loader = loader()
here = get_binding(the_loader)
expect do
parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'MyType += Array[Integer]'
end
dispatch :test do
param 'MyType', :x
end
def test(x)
x
end
end
CODE
end.to raise_error(/MyType \+\= Array.*<Syntax error at '\+\=' \(line: 1, column: [0-9]+\)>.*functions4_spec\.rb.*/m)
# Note that raised error reports this spec file as the function source since the function is defined here
end
it 'syntax error in param type is reported with puppet source, puppet location, and ruby file containing function' do
the_loader = loader()
here = get_binding(the_loader)
expect do
parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'Array[1+=1]', :x
end
def test(x)
x
end
end
CODE
end.to raise_error(/Parsing of type string '"Array\[1\+=1\]"' failed with message: <Syntax error at '\]' \(line: 1, column: [0-9]+\)>/m)
end
end
context 'can use a loader when parsing types in function dispatch, and' do
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
it 'uses return_type to validate returned value' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'Integer', :x
return_type 'String'
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test(10)', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect { parser.evaluate({}, program) }.to raise_error(Puppet::Error,
/value returned from function 'test' has wrong type, expects a String value, got Integer/)
end
it 'resolve a referenced Type alias' do
the_loader = loader()
the_loader.add_type('myalias', type_alias_t('MyAlias', 'Integer'))
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'MyAlias', :x
return_type 'MyAlias'
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test(10)', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eql(10)
end
it 'reports a reference to an unresolved type' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'MyAlias', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test(10)', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect { parser.evaluate({}, program) }.to raise_error(Puppet::Error, /parameter 'x' references an unresolved type 'MyAlias'/)
end
it 'create local Type aliases' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'MyType = Array[Integer]'
end
dispatch :test do
param 'MyType', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test([10,20])', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eq([10,20])
end
it 'create nested local Type aliases' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'InnerType = Array[Integer]'
type 'OuterType = Hash[String,InnerType]'
end
dispatch :test do
param 'OuterType', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string("testing::test({'x' => [10,20]})", __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eq({'x' => [10,20]})
end
it 'create self referencing local Type aliases' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'Tree = Hash[String,Variant[String,Tree]]'
end
dispatch :test do
param 'Tree', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string("testing::test({'x' => {'y' => 'n'}})", __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eq({'x' => {'y' => 'n'}})
end
end
end
def create_noargs_function_class
Puppet::Functions.create_function('test') do
def test()
10
end
end
end
def create_min_function_class
Puppet::Functions.create_function('min') do
def min(x,y)
x <= y ? x : y
end
end
end
def create_max_function_class
Puppet::Functions.create_function('max') do
def max(x,y)
x >= y ? x : y
end
end
end
def create_badly_named_method_function_class
Puppet::Functions.create_function('mix') do
def mix_up(x,y)
x <= y ? x : y
end
end
end
def create_min_function_class_using_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :a
param 'Numeric', :b
end
def min(x,y)
x <= y ? x : y
end
end
end
def create_min_function_class_disptaching_to_two_methods
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :a
param 'Numeric', :b
end
dispatch :min_s do
param 'String', :s1
param 'String', :s2
end
def min(x,y)
x <= y ? x : y
end
def min_s(x,y)
cmp = (x.downcase <=> y.downcase)
cmp <= 0 ? x : y
end
end
end
def create_function_with_optionals_and_repeated
Puppet::Functions.create_function('min') do
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_optionals_and_repeated_via_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :x
param 'Numeric', :y
optional_param 'Numeric', :a
optional_param 'Numeric', :b
repeated_param 'Numeric', :c
end
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_optionals_and_repeated_via_multiple_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :x
param 'Numeric', :y
optional_param 'Numeric', :a
optional_param 'Numeric', :b
repeated_param 'Numeric', :c
end
dispatch :min do
param 'String', :x
param 'String', :y
required_repeated_param 'String', :a
end
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_required_repeated_via_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :x
param 'Numeric', :y
required_repeated_param 'Numeric', :z
end
def min(x,y, *z)
x <= y ? x : y
end
end
end
def create_function_with_repeated
Puppet::Functions.create_function('count_args') do
dispatch :count_args do
repeated_param 'Any', :c
end
def count_args(*c)
c.size
end
end
end
def create_function_with_optional_repeated
Puppet::Functions.create_function('count_args') do
dispatch :count_args do
optional_repeated_param 'Any', :c
end
def count_args(*c)
c.size
end
end
end
def create_function_with_required_repeated
Puppet::Functions.create_function('count_args') do
dispatch :count_args do
required_repeated_param 'Any', :c
end
def count_args(*c)
c.size
end
end
end
def create_function_with_inexact_dispatch
Puppet::Functions.create_function('t1') do
dispatch :t1 do
param 'Numeric', :x
param 'Numeric', :y
repeated_param 'Numeric', :z
end
dispatch :t1 do
param 'String', :x
param 'String', :y
repeated_param 'String', :z
end
def t1(first, *x)
[first.class, *x.map {|e|e.class}]
end
end
end
def create_function_with_rq_after_opt
Puppet::Functions.create_function('t1') do
dispatch :t1 do
optional_param 'Numeric', :x
param 'Numeric', :y
end
def t1(*x)
x
end
end
end
def create_function_with_rq_repeated_after_opt
Puppet::Functions.create_function('t1') do
dispatch :t1 do
optional_param 'Numeric', :x
required_repeated_param 'Numeric', :y
end
def t1(x, *y)
x
end
end
end
def create_function_with_param_after_repeated
Puppet::Functions.create_function('t1') do
dispatch :t1 do
repeated_param 'Numeric', :x
param 'Numeric', :y
end
def t1(*x)
x
end
end
end
# DEAD TODO REMOVE
# def create_function_with_param_injection_regular
# Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
# attr_injected Puppet::Pops::Types::TypeFactory.type_of(FunctionAPISpecModule::TestDuck), :test_attr
# attr_injected Puppet::Pops::Types::TypeFactory.string(), :test_attr2, "a_string"
# attr_injected_producer Puppet::Pops::Types::TypeFactory.integer(), :serial, "an_int"
#
# dispatch :test do
# injected_param Puppet::Pops::Types::TypeFactory.string, :x, 'a_string'
# injected_producer_param Puppet::Pops::Types::TypeFactory.integer, :y, 'an_int'
# param 'Scalar', :a
# param 'Scalar', :b
# end
#
# def test(x,y,a,b)
# y_produced = y.produce(nil)
# "#{x}! #{a}, and #{b} < #{y_produced} = #{ !!(a < y_produced && b < y_produced)}"
# end
# end
# end
def create_function_with_required_block_all_defaults
Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
block_param
end
def test(x)
yield(8,x)
end
end
end
def create_function_with_scope_required_block_all_defaults
Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
dispatch :test do
scope_param
param 'Integer', :x
# use defaults, any callable, name is 'block'
required_block_param
end
def test(scope, x)
yield(3,x)
end
end
end
def create_function_with_required_block_default_type
Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
required_block_param :the_block
end
def test(x)
yield
end
end
end
def create_function_with_scope_param_required_repeat
Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/reports_spec.rb | spec/unit/reports_spec.rb | require 'spec_helper'
require 'puppet/reports'
describe Puppet::Reports do
it "should instance-load report types" do
expect(Puppet::Reports.instance_loader(:report)).to be_instance_of(Puppet::Util::Autoload)
end
it "should have a method for registering report types" do
expect(Puppet::Reports).to respond_to(:register_report)
end
it "should have a method for retrieving report types by name" do
expect(Puppet::Reports).to respond_to(:report)
end
it "should provide a method for returning documentation for all reports" do
expect(Puppet::Reports).to receive(:loaded_instances).with(:report).and_return([:one, :two])
one = double('one', :doc => "onedoc")
two = double('two', :doc => "twodoc")
expect(Puppet::Reports).to receive(:report).with(:one).and_return(one)
expect(Puppet::Reports).to receive(:report).with(:two).and_return(two)
doc = Puppet::Reports.reportdocs
expect(doc.include?("onedoc")).to be_truthy
expect(doc.include?("twodoc")).to be_truthy
end
end
describe Puppet::Reports, " when loading report types" do
it "should use the instance loader to retrieve report types" do
expect(Puppet::Reports).to receive(:loaded_instance).with(:report, :myreporttype)
Puppet::Reports.report(:myreporttype)
end
end
describe Puppet::Reports, " when registering report types" do
it "should evaluate the supplied block as code for a module" do
expect(Puppet::Reports).to receive(:genmodule).and_return(Module.new)
Puppet::Reports.register_report(:testing) { }
end
it "should allow a successful report to be reloaded" do
Puppet::Reports.register_report(:testing) { }
Puppet::Reports.register_report(:testing) { }
end
it "should allow a failed report to be reloaded and show the correct exception both times" do
expect { Puppet::Reports.register_report(:testing) { raise TypeError, 'failed report' } }.to raise_error(TypeError)
expect { Puppet::Reports.register_report(:testing) { raise TypeError, 'failed report' } }.to raise_error(TypeError)
end
it "should extend the report type with the Puppet::Util::Docs module" do
mod = double('module', :define_method => true)
expect(Puppet::Reports).to receive(:genmodule).with(anything, hash_including(extend: Puppet::Util::Docs)).and_return(mod)
Puppet::Reports.register_report(:testing) { }
end
it "should define a :report_name method in the module that returns the name of the report" do
mod = double('module')
expect(mod).to receive(:define_method).with(:report_name)
expect(Puppet::Reports).to receive(:genmodule).and_return(mod)
Puppet::Reports.register_report(:testing) { }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/data_binding_spec.rb | spec/unit/data_binding_spec.rb | require 'spec_helper'
require 'puppet/data_binding'
describe Puppet::DataBinding do
describe "when indirecting" do
it "should default to the 'hiera' data_binding terminus" do
Puppet::DataBinding.indirection.reset_terminus_class
expect(Puppet::DataBinding.indirection.terminus_class).to eq(:hiera)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/etc_spec.rb | spec/unit/etc_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/character_encoding'
# The Ruby::Etc module is largely non-functional on Windows - many methods
# simply return nil regardless of input, the Etc::Group struct is not defined,
# and Etc::Passwd is missing fields
# We want to test that:
# - We correctly set external encoding values IF they're valid UTF-8 bytes
# - We do not modify non-UTF-8 values if they're NOT valid UTF-8 bytes
describe Puppet::Etc, :if => !Puppet::Util::Platform.windows? do
# http://www.fileformat.info/info/unicode/char/5e0c/index.htm
# 希 Han Character 'rare; hope, expect, strive for'
# In EUC_KR: \xfd \xf1 - 253 241
# In UTF-8: \u5e0c - \xe5 \xb8 \x8c - 229 184 140
let(:euc_kr) { [253, 241].pack('C*').force_encoding(Encoding::EUC_KR) } # valid_encoding? == true
let(:euc_kr_as_binary) { [253, 241].pack('C*') } # valid_encoding? == true
let(:euc_kr_as_utf_8) { [253, 241].pack('C*').force_encoding(Encoding::UTF_8) } # valid_encoding? == false
# characters representing 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_utf_8) { "A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::UTF_8) } # Aۿᚠ𠜎
let(:mixed_utf_8_as_binary) { "A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::BINARY) }
let(:mixed_utf_8_as_euc_kr) { "A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::EUC_KR) }
# An uninteresting value that ruby might return in an Etc struct.
let(:root) { 'root' }
# Set up example Etc Group structs with values representative of what we would
# get back in these encodings
let(:utf_8_group_struct) do
group = Etc::Group.new
# In a UTF-8 environment, these values will come back as UTF-8, even if
# they're not valid UTF-8. We do not modify anything about either the
# valid or invalid UTF-8 strings.
# Group member contains a mix of valid and invalid UTF-8-labeled strings
group.mem = [mixed_utf_8, root.dup.force_encoding(Encoding::UTF_8), euc_kr_as_utf_8]
# group name contains same EUC_KR bytes labeled as UTF-8
group.name = euc_kr_as_utf_8
# group passwd field is valid UTF-8
group.passwd = mixed_utf_8
group.gid = 12345
group
end
let(:euc_kr_group_struct) do
# In an EUC_KR environment, values will come back as EUC_KR, even if they're
# not valid in that encoding. For values that are valid in UTF-8 we expect
# their external encoding to be set to UTF-8 by Puppet::Etc. For values that
# are invalid in UTF-8, we expect the string to be kept intact, unmodified,
# as we can't transcode it.
group = Etc::Group.new
group.mem = [euc_kr, root.dup.force_encoding(Encoding::EUC_KR), mixed_utf_8_as_euc_kr]
group.name = euc_kr
group.passwd = mixed_utf_8_as_euc_kr
group.gid = 12345
group
end
let(:ascii_group_struct) do
# In a POSIX environment, any strings containing only values under
# code-point 128 will be returned as ASCII, whereas anything above that
# point will be returned as BINARY. In either case we override the encoding
# to UTF-8 if that would be valid.
group = Etc::Group.new
group.mem = [euc_kr_as_binary, root.dup.force_encoding(Encoding::ASCII), mixed_utf_8_as_binary]
group.name = euc_kr_as_binary
group.passwd = mixed_utf_8_as_binary
group.gid = 12345
group
end
let(:utf_8_user_struct) do
user = Etc::Passwd.new
# user name contains same EUC_KR bytes labeled as UTF-8
user.name = euc_kr_as_utf_8
# group passwd field is valid UTF-8
user.passwd = mixed_utf_8
user.uid = 12345
user
end
let(:euc_kr_user_struct) do
user = Etc::Passwd.new
user.name = euc_kr
user.passwd = mixed_utf_8_as_euc_kr
user.uid = 12345
user
end
let(:ascii_user_struct) do
user = Etc::Passwd.new
user.name = euc_kr_as_binary
user.passwd = mixed_utf_8_as_binary
user.uid = 12345
user
end
shared_examples "methods that return an overridden group struct from Etc" do |param|
it "should return a new Struct object with corresponding canonical_ members" do
group = Etc::Group.new
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(group)
puppet_group = Puppet::Etc.send(subject, *param)
expect(puppet_group.members).to include(*group.members)
expect(puppet_group.members).to include(*group.members.map { |mem| "canonical_#{mem}".to_sym })
# Confirm we haven't just added the new members to the original struct object, ie this is really a new struct
expect(group.members.any? { |elem| elem.match(/^canonical_/) }).to be_falsey
end
context "when Encoding.default_external is UTF-8" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(utf_8_group_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::UTF_8) do
Puppet::Etc.send(subject, *param)
end
}
it "should leave the valid UTF-8 values in arrays unmodified" do
expect(overridden.mem[0]).to eq(mixed_utf_8)
expect(overridden.mem[1]).to eq(root)
end
it "should replace invalid characters with replacement characters in invalid UTF-8 values in arrays" do
expect(overridden.mem[2]).to eq("\uFFFD\uFFFD")
end
it "should keep an unmodified version of the invalid UTF-8 values in arrays in the corresponding canonical_ member" do
expect(overridden.canonical_mem[2]).to eq(euc_kr_as_utf_8)
end
it "should leave the valid UTF-8 values unmodified" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should replace invalid characters with '?' characters in invalid UTF-8 values" do
expect(overridden.name).to eq("\uFFFD\uFFFD")
end
it "should keep an unmodified version of the invalid UTF-8 values in the corresponding canonical_ member" do
expect(overridden.canonical_name).to eq(euc_kr_as_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
utf_8_group_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is EUC_KR (i.e., neither UTF-8 nor POSIX)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(euc_kr_group_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::EUC_KR) do
Puppet::Etc.send(subject, *param)
end
}
it "should override EUC_KR-labeled values in arrays to UTF-8 if that would result in valid UTF-8" do
expect(overridden.mem[2]).to eq(mixed_utf_8)
expect(overridden.mem[1]).to eq(root)
end
it "should leave valid EUC_KR-labeled values that would not be valid UTF-8 in arrays unmodified" do
expect(overridden.mem[0]).to eq(euc_kr)
end
it "should override EUC_KR-labeled values to UTF-8 if that would result in valid UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should leave valid EUC_KR-labeled values that would not be valid UTF-8 unmodified" do
expect(overridden.name).to eq(euc_kr)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
euc_kr_group_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is POSIX (ASCII-7bit)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(ascii_group_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ASCII) do
Puppet::Etc.send(subject, *param)
end
}
it "should not modify binary values in arrays that would be invalid UTF-8" do
expect(overridden.mem[0]).to eq(euc_kr_as_binary)
end
it "should set the encoding to UTF-8 on binary values in arrays that would be valid UTF-8" do
expect(overridden.mem[1]).to eq(root.dup.force_encoding(Encoding::UTF_8))
expect(overridden.mem[2]).to eq(mixed_utf_8)
end
it "should not modify binary values that would be invalid UTF-8" do
expect(overridden.name).to eq(euc_kr_as_binary)
end
it "should set the encoding to UTF-8 on binary values that would be valid UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
ascii_group_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
end
shared_examples "methods that return an overridden user struct from Etc" do |param|
it "should return a new Struct object with corresponding canonical_ members" do
user = Etc::Passwd.new
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(user)
puppet_user = Puppet::Etc.send(subject, *param)
expect(puppet_user.members).to include(*user.members)
expect(puppet_user.members).to include(*user.members.map { |mem| "canonical_#{mem}".to_sym })
# Confirm we haven't just added the new members to the original struct object, ie this is really a new struct
expect(user.members.any? { |elem| elem.match(/^canonical_/)}).to be_falsey
end
context "when Encoding.default_external is UTF-8" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(utf_8_user_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::UTF_8) do
Puppet::Etc.send(subject, *param)
end
}
it "should leave the valid UTF-8 values unmodified" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should replace invalid characters with unicode replacement characters in invalid UTF-8 values" do
expect(overridden.name).to eq("\uFFFD\uFFFD")
end
it "should keep an unmodified version of the invalid UTF-8 values in the corresponding canonical_ member" do
expect(overridden.canonical_name).to eq(euc_kr_as_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
utf_8_user_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is EUC_KR (i.e., neither UTF-8 nor POSIX)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(euc_kr_user_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::EUC_KR) do
Puppet::Etc.send(subject, *param)
end
}
it "should override valid UTF-8 EUC_KR-labeled values to UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should leave invalid EUC_KR-labeled values unmodified" do
expect(overridden.name).to eq(euc_kr)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
euc_kr_user_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is POSIX (ASCII-7bit)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(ascii_user_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ASCII) do
Puppet::Etc.send(subject, *param)
end
}
it "should not modify binary values that would be invalid UTF-8" do
expect(overridden.name).to eq(euc_kr_as_binary)
end
it "should set the encoding to UTF-8 on binary values that would be valid UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
ascii_user_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
end
describe :getgrent do
it_should_behave_like "methods that return an overridden group struct from Etc"
end
describe :getgrnam do
it_should_behave_like "methods that return an overridden group struct from Etc", 'foo'
it "should call Etc.getgrnam with the supplied group name" do
expect(Etc).to receive(:getgrnam).with('foo')
Puppet::Etc.getgrnam('foo')
end
end
describe :getgrgid do
it_should_behave_like "methods that return an overridden group struct from Etc", 0
it "should call Etc.getgrgid with supplied group id" do
expect(Etc).to receive(:getgrgid).with(0)
Puppet::Etc.getgrgid(0)
end
end
describe :getpwent do
it_should_behave_like "methods that return an overridden user struct from Etc"
end
describe :getpwnam do
it_should_behave_like "methods that return an overridden user struct from Etc", 'foo'
it "should call Etc.getpwnam with that username" do
expect(Etc).to receive(:getpwnam).with('foo')
Puppet::Etc.getpwnam('foo')
end
end
describe :getpwuid do
it_should_behave_like "methods that return an overridden user struct from Etc", 2
it "should call Etc.getpwuid with the id" do
expect(Etc).to receive(:getpwuid).with(2)
Puppet::Etc.getpwuid(2)
end
end
describe :group do
it 'should return the next group struct if a block is not provided' do
expect(Puppet::Etc).to receive(:getgrent).and_return(ascii_group_struct)
expect(Puppet::Etc.group).to eql(ascii_group_struct)
end
it 'should iterate over the available groups if a block is provided' do
expected_groups = [
utf_8_group_struct,
euc_kr_group_struct,
ascii_group_struct
]
allow(Puppet::Etc).to receive(:getgrent).and_return(*(expected_groups + [nil]))
expect(Puppet::Etc).to receive(:setgrent)
expect(Puppet::Etc).to receive(:endgrent)
actual_groups = []
Puppet::Etc.group { |group| actual_groups << group }
expect(actual_groups).to eql(expected_groups)
end
end
describe "endgrent" do
it "should call Etc.getgrent" do
expect(Etc).to receive(:getgrent)
Puppet::Etc.getgrent
end
end
describe "setgrent" do
it "should call Etc.setgrent" do
expect(Etc).to receive(:setgrent)
Puppet::Etc.setgrent
end
end
describe "endpwent" do
it "should call Etc.endpwent" do
expect(Etc).to receive(:endpwent)
Puppet::Etc.endpwent
end
end
describe "setpwent" do
it "should call Etc.setpwent" do
expect(Etc).to receive(:setpwent)
Puppet::Etc.setpwent
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/task_spec.rb | spec/unit/task_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/module/task'
describe Puppet::Module::Task do
include PuppetSpec::Files
let(:modpath) { tmpdir('task_modpath') }
let(:mymodpath) { File.join(modpath, 'mymod') }
let(:othermodpath) { File.join(modpath, 'othermod') }
let(:mymod) { Puppet::Module.new('mymod', mymodpath, nil) }
let(:othermod) { Puppet::Module.new('othermod', othermodpath, nil) }
let(:tasks_path) { File.join(mymodpath, 'tasks') }
let(:other_tasks_path) { File.join(othermodpath, 'tasks') }
let(:tasks_glob) { File.join(mymodpath, 'tasks', '*') }
it "cannot construct tasks with illegal names" do
expect { Puppet::Module::Task.new(mymod, "iLegal", []) }
.to raise_error(Puppet::Module::Task::InvalidName,
"Task names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")
end
it "constructs tasks as expected when every task has a metadata file with the same name (besides extension)" do
task_files = %w{task1.json task1 task2.json task2.exe task3.json task3.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
expect(tasks.count).to eq(3)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1 mymod::task2 mymod::task3})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json",
"#{tasks_path}/task2.json",
"#{tasks_path}/task3.json"])
expect(tasks.map{|t| t.files.map { |f| f["path"] } }).to eq([["#{tasks_path}/task1"],
["#{tasks_path}/task2.exe"],
["#{tasks_path}/task3.sh"]])
expect(tasks.map{|t| t.files.map { |f| f["name"] } }).to eq([["task1"],
["task2.exe"],
["task3.sh"]])
tasks.map{|t| t.metadata_file}.each do |metadata_file|
expect(metadata_file).to eq(File.absolute_path(metadata_file))
end
tasks.map{|t| t.files}.each do |file_data|
path = file_data[0]['path']
expect(path).to eq(File.absolute_path(path))
end
end
it "constructs tasks as expected when some tasks don't have a metadata file" do
task_files = %w{task1 task2.exe task3.json task3.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(3)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1 mymod::task2 mymod::task3})
expect(tasks.map{|t| t.metadata_file}).to eq([nil, nil, "#{tasks_path}/task3.json"])
expect(tasks.map{|t| t.files.map { |f| f["path"] } }).to eq([["#{tasks_path}/task1"],
["#{tasks_path}/task2.exe"],
["#{tasks_path}/task3.sh"]])
end
it "constructs a task as expected when a task has implementations" do
task_files = %w{task1.elf task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [{"name" => "task1.sh"}]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh"]])
end
it "constructs a task as expected when task metadata declares additional files" do
task_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(Puppet::Module::Task).to receive(:find_extra_files).and_return([{'name' => 'mymod/lib/file0.elf', 'path' => "/path/to/file0.elf"}])
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'files' => ["mymod/lib/file0.elf"]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh", "/path/to/file0.elf"]])
end
it "constructs a task as expected when a task implementation declares additional files" do
task_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(Puppet::Module::Task).to receive(:find_extra_files).and_return([{'name' => 'mymod/lib/file0.elf', 'path' => "/path/to/file0.elf"}])
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [{"name" => "task1.sh", "files" => ["mymod/lib/file0.elf"]}]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh", "/path/to/file0.elf"]])
end
it "constructs a task as expected when task metadata and a task implementation both declare additional files" do
task_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(Puppet::Module::Task).to receive(:find_extra_files).and_return([
{'name' => 'mymod/lib/file0.elf', 'path' => "/path/to/file0.elf"},
{'name' => 'yourmod/files/file1.txt', 'path' => "/other/path/to/file1.txt"}
])
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [{"name" => "task1.sh", "files" => ["mymod/lib/file0.elf"]}]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([[
"#{tasks_path}/task1.sh",
"/path/to/file0.elf",
"/other/path/to/file1.txt"
]])
end
it "constructs a task as expected when a task has files" do
og_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(File).to receive(:exist?).with(any_args).and_return(true).at_least(:once)
expect(Puppet::Module).to receive(:find).with(othermod.name, "production").and_return(othermod).at_least(:once)
short_files = %w{other_task.sh other_task.json task_2.sh}.map { |bn| "#{othermod.name}/tasks/#{bn}" }
long_files = %w{other_task.sh other_task.json task_2.sh}.map { |bn| "#{other_tasks_path}/#{bn}" }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'files' => short_files})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh"] + long_files])
end
it "fails to load a task if its metadata specifies a non-existent file" do
og_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
allow(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(File).to receive(:exist?).with(any_args).and_return(true)
expect(Puppet::Module).to receive(:find).with(othermod.name, "production").and_return(nil).at_least(:once)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'files' => ["#{othermod.name}/files/test"]})
expect { tasks.first.files }.to raise_error(Puppet::Module::Task::InvalidMetadata, /Could not find module #{othermod.name} containing task file test/)
end
it "finds files whose names (besides extensions) are valid task names" do
og_files = %w{task task_1 xx_t_a_s_k_2_xx}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(3)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task mymod::task_1 mymod::xx_t_a_s_k_2_xx})
end
it "ignores files that have names (besides extensions) that are not valid task names" do
og_files = %w{.nottask.exe .wat !runme _task 2task2furious def_a_task_PSYCH Fake_task not-a-task realtask}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::realtask})
end
it "ignores files that have names ending in .conf and .md" do
og_files = %w{ginuwine_task task.conf readme.md other_task.md}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::ginuwine_task})
end
it "ignores files which are not regular files" do
og_files = %w{foo}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(false) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(0)
end
it "gives the 'init' task a name that is just the module's name" do
expect(Puppet::Module::Task.new(mymod, 'init', ["#{tasks_path}/init.sh"]).name).to eq('mymod')
end
describe :metadata do
it "loads metadata for a task" do
metadata = {'desciption': 'some info'}
og_files = %w{task1.exe task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(Puppet::Module::Task).to receive(:read_metadata).and_return(metadata)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].metadata).to eq(metadata)
end
it 'returns nil for metadata if no file is present' do
og_files = %w{task1.exe}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].metadata).to be_nil
end
it 'raises InvalidMetadata if the json metadata is invalid' do
FileUtils.mkdir_p(tasks_path)
File.open(File.join(tasks_path, 'task.json'), 'w') { |f| f.write '{ "whoops"' }
FileUtils.touch(File.join(tasks_path, 'task'))
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect {
tasks[0].metadata
}.to raise_error(Puppet::Module::Task::InvalidMetadata)
end
it 'returns empty hash for metadata when json metadata file is empty' do
FileUtils.mkdir_p(tasks_path)
FileUtils.touch(File.join(tasks_path, 'task.json'))
FileUtils.touch(File.join(tasks_path, 'task'))
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].metadata).to eq({})
end
end
describe :validate do
it "validates when there is no metadata" do
og_files = %w{task1.exe}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].validate).to eq(true)
end
it "validates when an implementation isn't used" do
metadata = {'desciption' => 'some info',
'implementations' => [ {"name" => "task1.exe"}, ] }
og_files = %w{task1.exe task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(Puppet::Module::Task).to receive(:read_metadata).and_return(metadata)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].validate).to be(true)
end
it "validates when an implementation is another task" do
metadata = {'desciption' => 'some info',
'implementations' => [ {"name" => "task2.sh"}, ] }
og_files = %w{task1.exe task2.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(Puppet::Module::Task).to receive(:read_metadata).and_return(metadata)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(2)
expect(tasks.map(&:validate)).to eq([true, true])
end
it "fails validation when there is no metadata and multiple task files" do
og_files = %w{task1.elf task1.exe task1.json task2.ps1 task2.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
tasks.each do |task|
expect {task.validate}.to raise_error(Puppet::Module::Task::InvalidTask)
end
end
it "fails validation when an implementation references a non-existant file" do
og_files = %w{task1.elf task1.exe task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [ { 'name' => 'task1.sh' } ] })
tasks.each do |task|
expect {task.validate}.to raise_error(Puppet::Module::Task::InvalidTask)
end
end
it 'fails validation when there is metadata but no executable' do
og_files = %w{task1.json task2.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
expect { tasks.find { |t| t.name == 'mymod::task1' }.validate }.to raise_error(Puppet::Module::Task::InvalidTask)
end
it 'fails validation when the implementations are not an array' do
og_files = %w{task1.json task2.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({"implemenations" => {}})
expect { tasks.find { |t| t.name == 'mymod::task1' }.validate }.to raise_error(Puppet::Module::Task::InvalidTask)
end
it 'fails validation when the implementation is json' do
og_files = %w{task1.json task1.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [ { 'name' => 'task1.json' } ] })
expect { tasks.find { |t| t.name == 'mymod::task1' }.validate }.to raise_error(Puppet::Module::Task::InvalidTask)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/puppet_pal_2pec.rb | spec/unit/puppet_pal_2pec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_pal'
describe 'Puppet Pal' do
include PuppetSpec::Files
let(:testing_env) do
{
'pal_env' => {
'functions' => functions,
'lib' => { 'puppet' => lib_puppet },
'manifests' => manifests,
'modules' => modules,
'plans' => plans,
'tasks' => tasks,
'types' => types,
},
'other_env1' => { 'modules' => {} },
'other_env2' => { 'modules' => {} },
}
end
let(:functions) { {} }
let(:manifests) { {} }
let(:modules) { {} }
let(:plans) { {} }
let(:lib_puppet) { {} }
let(:tasks) { {} }
let(:types) { {} }
let(:environments_dir) { Puppet[:environmentpath] }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'pal_env')
PuppetSpec::Files.record_tmp(env_dir)
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env1'))
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env2'))
env_dir
end
let(:modules_dir) { File.join(testing_env_dir, 'modules') }
# Without any facts - this speeds up the tests that do not require $facts to have any values
let(:node_facts) { Hash.new }
# TODO: to be used in examples for running in an existing env
# let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) }
context 'in general - without code in modules or env' do
let(:modulepath) { [] }
context 'deprecated PAL API methods work and' do
it '"evaluate_script_string" evaluates a code string in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.evaluate_script_string('1+2+3')
end
expect(result).to eq(6)
end
it '"evaluate_script_manifest" evaluates a manifest file in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('testing.pp', "1+2+3+4")
ctx.evaluate_script_manifest(manifest)
end
expect(result).to eq(10)
end
end
context "with a script compiler" do
it 'errors if given both configured_by_env and manifest_file' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler(configured_by_env: true, manifest_file: 'undef.pp') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
it 'errors if given both configured_by_env and code_string' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler(configured_by_env: true, code_string: 'undef') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
context "evaluate_string method" do
it 'evaluates code string in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string('1+2+3') }
end
expect(result).to eq(6)
end
it 'can be evaluated more than once in a given tmp environment - each in fresh compiler' do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
expect( ctx.with_script_compiler {|c| c.evaluate_string('$a = 1+2+3')}).to eq(6)
expect { ctx.with_script_compiler {|c| c.evaluate_string('$a') }}.to raise_error(/Unknown variable: 'a'/)
end
end
it 'instantiates definitions in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_script_compiler do |compiler|
compiler.evaluate_string(<<-CODE)
function run_me() { "worked1" }
run_me()
CODE
end
end
expect(result).to eq('worked1')
end
end
context "evaluate_file method" do
it 'evaluates a manifest file in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('testing.pp', "1+2+3+4")
ctx.with_script_compiler {|c| c.evaluate_file(manifest) }
end
expect(result).to eq(10)
end
it 'instantiates definitions in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_script_compiler do |compiler|
manifest = file_containing('testing.pp', (<<-CODE))
function run_me() { "worked1" }
run_me()
CODE
pal.with_script_compiler {|c| c.evaluate_file(manifest) }
end
end
expect(result).to eq('worked1')
end
end
context "variables are supported such that" do
it 'they can be set in any scope' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(40)
end
it 'an error is raised if a variable name is illegal' do
vars = {'_a::b'=> 10}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
manifest = file_containing('testing.pp', "ok")
ctx.with_script_compiler {|c| c.evaluate_file(manifest) }
end
end.to raise_error(/has illegal name/)
end
it 'an error is raised if variable value is not RichData compliant' do
vars = {'a'=> ArgumentError.new("not rich data")}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_script_compiler {|c| }
end
end.to raise_error(/has illegal type - got: ArgumentError/)
end
it 'variable given to script_compiler overrides those given for environment' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_script_compiler(variables: {'x::y' => 40}) {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(60)
end
end
context "functions are supported such that" do
it '"call_function" calls a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc($a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) {|c| c.call_function('myfunc', 6) }
end
expect(result).to eq(12)
end
it '"call_function" accepts a call with a ruby block' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.call_function('with', 6) {|x| x * 2} }
end
expect(result).to eq(12)
end
it '"function_signature" returns a signature of a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc')
end
end
expect(result.class).to eq(Puppet::Pal::FunctionSignature)
end
it '"FunctionSignature#callable_with?" returns boolean if function is callable with given argument values' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
[ signature.callable_with?([10]),
signature.callable_with?(['nope'])
]
end
end
expect(result).to eq([true, false])
end
it '"FunctionSignature#callable_with?" calls a given lambda if there is an error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'not yay'
signature.callable_with?(['nope']) {|error| local_result = error }
local_result
end
end
expect(result).to match(/'myfunc' parameter 'a' expects an Integer value, got String/)
end
it '"FunctionSignature#callable_with?" does not call a given lambda when there is no error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'yay'
signature.callable_with?([10]) {|error| local_result = 'not yay' }
local_result
end
end
expect(result).to eq('yay')
end
it '"function_signature" gets the signatures from a ruby function with multiple dispatch' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.function_signature('lookup') }
end
# check two different signatures of the lookup function
expect(result.callable_with?(['key'])).to eq(true)
expect(result.callable_with?(['key'], lambda() {|k| })).to eq(true)
end
it '"function_signature" returns nil if function is not found' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.function_signature('no_where_to_be_found') }
end
expect(result).to eq(nil)
end
it '"FunctionSignature#callables" returns an array of callables' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc').callables
end
end
expect(result.class).to eq(Array)
expect(result.all? {|c| c.is_a?(Puppet::Pops::Types::PCallableType)}).to eq(true)
end
it '"list_functions" returns an array with all function names that can be loaded' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.list_functions() }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are certainly more than 30 functions in puppet - (56 when writing this, but some refactoring
# may take place, so don't want an exact number here - jsut make sure it found "all of them"
expect(result.count).to be > 30
end
it '"list_functions" filters on name based on a given regexp' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.list_functions(/epp/) }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are two functions currently that have 'epp' in their name
expect(result.count).to eq(2)
end
end
context 'supports plans such that' do
it '"plan_signature" returns the signatures of a plan' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.plan_signature('myplan')
[ signature.callable_with?({'a' => 10}),
signature.callable_with?({'a' => 'nope'})
]
end
end
expect(result).to eq([true, false])
end
it 'a PlanSignature.callable_with? calls a given lambda with any errors as a formatted string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a, Integer $b) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.plan_signature('myplan')
local_result = nil
signature.callable_with?({'a' => 'nope'}) {|errors| local_result = errors }
local_result
end
end
# Note that errors are indented one space and on separate lines
#
expect(result).to eq(" parameter 'a' expects an Integer value, got String\n expects a value for parameter 'b'")
end
it 'a PlanSignature.callable_with? does not call a given lambda if there are no errors' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.plan_signature('myplan')
local_result = 'yay'
signature.callable_with?({'a' => 1}) {|errors| local_result = 'not yay' }
local_result
end
end
expect(result).to eq('yay')
end
it '"plan_signature" returns nil if plan is not found' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.plan_signature('no_where_to_be_found') }
end
expect(result).to be(nil)
end
it '"PlanSignature#params_type" returns a map of all parameters and their types' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a, String $b) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
c.plan_signature('myplan').params_type
end
end
expect(result.class).to eq(Puppet::Pops::Types::PStructType)
expect(result.to_s).to eq("Struct[{'a' => Integer, 'b' => String}]")
end
end
context 'supports puppet data types such that' do
it '"type" parses and returns a Type from a string specification' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "type MyType = Float")
ctx.with_script_compiler(manifest_file: manifest) {|c| c.type('Variant[Integer, Boolean, MyType]') }
end
expect(result.is_a?(Puppet::Pops::Types::PVariantType)).to eq(true)
expect(result.types.size).to eq(3)
expect(result.instance?(3.14)).to eq(true)
end
it '"create" creates a new object from a puppet data type and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.create(Puppet::Pops::Types::PIntegerType::DEFAULT, '0x10') }
end
expect(result).to eq(16)
end
it '"create" creates a new object from puppet data type in string form and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.create('Integer', '010') }
end
expect(result).to eq(8)
end
end
end
context 'supports parsing such that' do
it '"parse_string" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.parse_string('$a = 10') }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
{ nil => Puppet::Error,
'0xWAT' => Puppet::ParseErrorWithIssue,
'$0 = 1' => Puppet::ParseErrorWithIssue,
'else 32' => Puppet::ParseErrorWithIssue,
}.each_pair do |input, error_class|
it "'parse_string' raises an error for invalid input: '#{input}'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.parse_string(input) }
end
}.to raise_error(error_class)
end
end
it '"parse_file" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "$a = 10")
ctx.with_script_compiler { |c| c.parse_file(manifest) }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
it "'parse_file' raises an error for invalid input: 'else 32'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "else 32")
ctx.with_script_compiler { |c| c.parse_file(manifest) }
end
}.to raise_error(Puppet::ParseErrorWithIssue)
end
it "'parse_file' raises an error for invalid input, file is not a string" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.parse_file(42) }
end
}.to raise_error(Puppet::Error)
end
it 'the "evaluate" method evaluates the parsed AST' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate(c.parse_string('10 + 20')) }
end
expect(result).to eq(30)
end
it 'the "evaluate" method instantiates definitions when given a Program' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate(c.parse_string('function foo() { "yay"}; foo()')) }
end
expect(result).to eq('yay')
end
it 'the "evaluate" method does not instantiates definitions when given ast other than Program' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler do |c|
program= c.parse_string('function foo() { "yay"}; foo()')
c.evaluate(program.body)
end
end
end.to raise_error(/Unknown function: 'foo'/)
end
it 'the "evaluate_literal" method evaluates AST being a representation of a literal value' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate_literal(c.parse_string('{10 => "hello"}')) }
end
expect(result).to eq({10 => 'hello'})
end
it 'the "evaluate_literal" method errors if ast is not representing a literal value' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate_literal(c.parse_string('{10+1 => "hello"}')) }
end
end.to raise_error(/does not represent a literal value/)
end
it 'the "evaluate_literal" method errors if ast contains definitions' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate_literal(c.parse_string('function foo() { }; 42')) }
end
end.to raise_error(/does not represent a literal value/)
end
end
end
context 'with code in modules and env' do
let(:modulepath) { [modules_dir] }
let(:metadata_json_a) {
{
'name' => 'example/a',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-a.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_b) {
{
'name' => 'example/b',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-b.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_c) {
{
'name' => 'example/c',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-c.git',
'dependencies' => [],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
# TODO: there is something amiss with the metadata wrt dependencies - when metadata is present there is an error
# that dependencies could not be resolved. Metadata is therefore commented out.
# Dependency based visibility is probably something that we should remove...
let(:modules) {
{
'a' => {
'functions' => a_functions,
'lib' => { 'puppet' => a_lib_puppet },
'plans' => a_plans,
'tasks' => a_tasks,
'types' => a_types,
# 'metadata.json' => metadata_json_a.to_json
},
'b' => {
'functions' => b_functions,
'lib' => b_lib,
'plans' => b_plans,
'tasks' => b_tasks,
'types' => b_types,
# 'metadata.json' => metadata_json_b.to_json
},
'c' => {
'types' => c_types,
# 'metadata.json' => metadata_json_c.to_json
},
}
}
let(:a_plans) {
{
'aplan.pp' => <<-PUPPET.unindent,
plan a::aplan() { 'a::aplan value' }
PUPPET
}
}
let(:a_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type A::Atype = Integer
PUPPET
}
}
let(:a_tasks) {
{
'atask' => '',
}
}
let(:a_functions) {
{
'afunc.pp' => 'function a::afunc() { "a::afunc value" }',
}
}
let(:a_lib_puppet) {
{
'functions' => {
'a' => {
'arubyfunc.rb' => <<-RUBY.unindent,
require 'stuff/something'
Puppet::Functions.create_function(:'a::arubyfunc') do
def arubyfunc
Stuff::SOMETHING
end
end
RUBY
'myscriptcompilerfunc.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:'a::myscriptcompilerfunc', Puppet::Functions::InternalFunction) do
dispatch :myscriptcompilerfunc do
script_compiler_param
param 'String',:name
end
def myscriptcompilerfunc(script_compiler, name)
script_compiler.is_a?(Puppet::Pal::ScriptCompiler) ? name : 'no go'
end
end
RUBY
}
}
}
}
let(:b_plans) {
{
'aplan.pp' => <<-PUPPET.unindent,
plan b::aplan() {}
PUPPET
}
}
let(:b_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type B::Atype = Integer
PUPPET
}
}
let(:b_tasks) {
{
'atask' => "# doing exactly nothing\n",
'atask.json' => <<-JSONTEXT.unindent
{
"description": "test task b::atask",
"input_method": "stdin",
"parameters": {
"string_param": {
"description": "A string parameter",
"type": "String[1]"
},
"int_param": {
"description": "An integer parameter",
"type": "Integer"
}
}
}
JSONTEXT
}
}
let(:b_functions) {
{
'afunc.pp' => 'function b::afunc() {}',
}
}
let(:b_lib) {
{
'puppet' => b_lib_puppet,
'stuff' => {
'something.rb' => "module Stuff; SOMETHING = 'something'; end"
}
}
}
let(:b_lib_puppet) {
{
'functions' => {
'b' => {
'arubyfunc.rb' => "Puppet::Functions.create_function(:'b::arubyfunc') { def arubyfunc; 'arubyfunc_value'; end }",
}
}
}
}
let(:c_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type C::Atype = Integer
PUPPET
}
}
context 'configured as temporary environment such that' do
it 'modules are available' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string('a::afunc()') }
end
expect(result).to eq("a::afunc value")
end
it 'libs in a given "modulepath" are added to the Ruby $LOAD_PATH' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string('a::arubyfunc()') }
end
expect(result).to eql('something')
end
it 'errors if a block is not given to in_tmp_environment' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts)
end.to raise_error(/A block must be given to 'in_tmp_environment/)
end
it 'errors if an env_name is given and is not a String[1]' do
expect do
Puppet::Pal.in_tmp_environment('', modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
expect do
Puppet::Pal.in_tmp_environment(32, modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
end
{ 'a hash' => {'a' => 'hm'},
'an integer' => 32,
'separated strings' => 'dir1;dir2',
'empty string in array' => ['']
}.each_pair do |what, value|
it "errors if modulepath is #{what}" do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: value, facts: node_facts) { |ctx| }
end.to raise_error(/modulepath has wrong type/)
end
end
context 'facts are supported such that' do
it 'they are obtained if they are not given' do
facts = Puppet::Node::Facts.new(Puppet[:certname], 'puppetversion' => Puppet.version)
Puppet::Node::Facts.indirection.save(facts)
testing_env_dir # creates the structure
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath ) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string("$facts =~ Hash and $facts[puppetversion] == '#{Puppet.version}'") }
end
expect(result).to eq(true)
end
it 'can be given as a hash when creating the environment' do
testing_env_dir # creates the structure
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: { 'myfact' => 42 }) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string("$facts =~ Hash and $facts[myfact] == 42") }
end
expect(result).to eq(true)
end
it 'can be overridden with a hash when creating a script compiler' do
testing_env_dir # creates the structure
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: { 'myfact' => 42 }) do |ctx|
ctx.with_script_compiler(facts: { 'myfact' => 43 }) {|c| c.evaluate_string("$facts =~ Hash and $facts[myfact] == 43") }
end
expect(result).to eq(true)
end
it 'can be disabled with the :set_local_facts option' do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: { 'myfact' => 42}) do |ctx|
ctx.with_script_compiler(facts: { 'myfact' => 42 }, set_local_facts: false) do |compiler|
expect { compiler.evaluate_string('$facts') }.to raise_error(
Puppet::PreformattedError,
/Unknown variable: 'facts'/
)
end
end
end
end
context 'supports tasks such that' do
it '"task_signature" returns the signatures of a generic task' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler do |c|
signature = c.task_signature('a::atask')
[ signature.runnable_with?('whatever' => 10),
signature.runnable_with?('anything_goes' => 'foo')
]
end
end
expect(result).to eq([true, true])
end
it '"TaskSignature#runnable_with?" calls a given lambda if there is an error in a generic task' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler do |c|
signature = c.task_signature('a::atask')
local_result = 'not yay'
signature.runnable_with?('string_param' => /not data/) {|error| local_result = error }
local_result
end
end
expect(result).to match(/Task a::atask:\s+entry 'string_param' expects a Data value, got Regexp/m)
end
it '"task_signature" returns the signatures of a task defined with metadata' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler do |c|
signature = c.task_signature('b::atask')
[ signature.runnable_with?('string_param' => 'foo', 'int_param' => 10),
signature.runnable_with?('anything_goes' => 'foo'),
signature.task_hash['name'],
signature.task_hash['metadata']['parameters']['string_param']['description'],
signature.task_hash['metadata']['description'],
signature.task_hash['metadata']['parameters']['int_param']['type'],
]
end
end
expect(result).to eq([true, false, 'b::atask', 'A string parameter', 'test task b::atask', 'Integer'])
end
it '"TaskSignature#runnable_with?" calls a given lambda if there is an error' do
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/module_tool_spec.rb | spec/unit/module_tool_spec.rb | # encoding: UTF-8
require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool do
describe '.is_module_root?' do
it 'should return true if directory has a metadata.json file' do
expect(FileTest).to receive(:file?).with(have_attributes(to_s: '/a/b/c/metadata.json')).and_return(true)
expect(subject.is_module_root?(Pathname.new('/a/b/c'))).to be_truthy
end
it 'should return false if directory does not have a metadata.json file' do
expect(FileTest).to receive(:file?).with(have_attributes(to_s: '/a/b/c/metadata.json')).and_return(false)
expect(subject.is_module_root?(Pathname.new('/a/b/c'))).to be_falsey
end
end
describe '.find_module_root' do
let(:sample_path) { Pathname.new('/a/b/c').expand_path }
it 'should return the first path as a pathname when it contains a module file' do
expect(Puppet::ModuleTool).to receive(:is_module_root?).with(sample_path).
and_return(true)
expect(subject.find_module_root(sample_path)).to eq(sample_path)
end
it 'should return a parent path as a pathname when it contains a module file' do
expect(Puppet::ModuleTool).to receive(:is_module_root?).with(have_attributes(to_s: File.expand_path('/a/b/c'))).and_return(false)
expect(Puppet::ModuleTool).to receive(:is_module_root?).with(have_attributes(to_s: File.expand_path('/a/b'))).and_return(true)
expect(subject.find_module_root(sample_path)).to eq(Pathname.new('/a/b').expand_path)
end
it 'should return nil when no module root can be found' do
expect(Puppet::ModuleTool).to receive(:is_module_root?).at_least(:once).and_return(false)
expect(subject.find_module_root(sample_path)).to be_nil
end
end
describe '.format_tree' do
it 'should return an empty tree when given an empty list' do
expect(subject.format_tree([])).to eq('')
end
it 'should return a shallow when given a list without dependencies' do
list = [ { :text => 'first' }, { :text => 'second' }, { :text => 'third' } ]
expect(subject.format_tree(list)).to eq <<-TREE
├── first
├── second
└── third
TREE
end
it 'should return a deeply nested tree when given a list with deep dependencies' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
}
]
},
]
expect(subject.format_tree(list)).to eq <<-TREE
└─┬ first
└─┬ second
└── third
TREE
end
it 'should show connectors when deep dependencies are not on the last node of the top level' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
}
]
},
{ :text => 'fourth' }
]
expect(subject.format_tree(list)).to eq <<-TREE
├─┬ first
│ └─┬ second
│ └── third
└── fourth
TREE
end
it 'should show connectors when deep dependencies are not on the last node of any level' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
},
{ :text => 'fourth' }
]
}
]
expect(subject.format_tree(list)).to eq <<-TREE
└─┬ first
├─┬ second
│ └── third
└── fourth
TREE
end
it 'should show connectors in every case when deep dependencies are not on the last node' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
},
{ :text => 'fourth' }
]
},
{ :text => 'fifth' }
]
expect(subject.format_tree(list)).to eq <<-TREE
├─┬ first
│ ├─┬ second
│ │ └── third
│ └── fourth
└── fifth
TREE
end
end
describe '.set_option_defaults' do
let(:options) { {} }
let(:modulepath) { ['/env/module/path', '/global/module/path'] }
let(:environment_name) { :current_environment }
let(:environment) { Puppet::Node::Environment.create(environment_name, modulepath) }
subject do
described_class.set_option_defaults(options)
options
end
around do |example|
envs = Puppet::Environments::Static.new(environment)
Puppet.override(:environments => envs) do
example.run
end
end
describe ':environment' do
context 'as String' do
let(:options) { { :environment => "#{environment_name}" } }
it 'assigns the environment with the given name to :environment_instance' do
expect(subject).to include :environment_instance => environment
end
end
context 'as Symbol' do
let(:options) { { :environment => :"#{environment_name}" } }
it 'assigns the environment with the given name to :environment_instance' do
expect(subject).to include :environment_instance => environment
end
end
context 'as Puppet::Node::Environment' do
let(:env) { Puppet::Node::Environment.create('anonymous', []) }
let(:options) { { :environment => env } }
it 'assigns the given environment to :environment_instance' do
expect(subject).to include :environment_instance => env
end
end
end
describe ':modulepath' do
let(:options) do
{ :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR) }
end
let(:paths) { options[:modulepath].split(File::PATH_SEPARATOR).map { |dir| File.expand_path(dir) } }
it 'is expanded to an absolute path' do
expect(subject[:environment_instance].full_modulepath).to eql paths
end
it 'is used to compute :target_dir' do
expect(subject).to include :target_dir => paths.first
end
context 'conflicts with :environment' do
let(:options) do
{ :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR), :environment => environment_name }
end
it 'replaces the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath).to eql paths
end
it 'is used to compute :target_dir' do
expect(subject).to include :target_dir => paths.first
end
end
end
describe ':target_dir' do
let(:options) do
{ :target_dir => 'foo' }
end
let(:target) { File.expand_path(options[:target_dir]) }
it 'is expanded to an absolute path' do
expect(subject).to include :target_dir => target
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
context 'conflicts with :modulepath' do
let(:options) do
{ :target_dir => 'foo', :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR) }
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
it 'shares the provided :modulepath via the :environment_instance' do
paths = %w[foo] + options[:modulepath].split(File::PATH_SEPARATOR)
paths.map! { |dir| File.expand_path(dir) }
expect(subject[:environment_instance].full_modulepath).to eql paths
end
end
context 'conflicts with :environment' do
let(:options) do
{ :target_dir => 'foo', :environment => environment_name }
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
it 'shares the provided :modulepath via the :environment_instance' do
paths = %w[foo] + environment.full_modulepath
paths.map! { |dir| File.expand_path(dir) }
expect(subject[:environment_instance].full_modulepath).to eql paths
end
end
context 'when not passed' do
it 'is populated with the first component of the modulepath' do
expect(subject).to include :target_dir => subject[:environment_instance].full_modulepath.first
end
end
end
end
describe '.parse_module_dependency' do
it 'parses a dependency without a version range expression' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar')
expect(name).to eql('foo-bar')
expect(range).to eql(SemanticPuppet::VersionRange.parse('>= 0.0.0'))
expect(expr).to eql('>= 0.0.0')
end
it 'parses a dependency with a version range expression' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar', 'version_requirement' => '1.2.x')
expect(name).to eql('foo-bar')
expect(range).to eql(SemanticPuppet::VersionRange.parse('1.2.x'))
expect(expr).to eql('1.2.x')
end
it 'does not raise an error on invalid version range expressions' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar', 'version_requirement' => 'nope')
expect(name).to eql('foo-bar')
expect(range).to eql(SemanticPuppet::VersionRange::EMPTY_RANGE)
expect(expr).to eql('nope')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application_spec.rb | spec/unit/application_spec.rb | require 'spec_helper'
require 'puppet/application'
require 'puppet'
require 'getoptlong'
require 'timeout'
describe Puppet::Application do
before(:each) do
@appclass = Class.new(Puppet::Application) do
def handle_unknown(opt, arg); end
end
@app = @appclass.new
allow(@app).to receive(:name).and_return("test_app")
end
describe "application commandline" do
it "should not pick up changes to the array of arguments" do
args = %w{subcommand --arg}
command_line = Puppet::Util::CommandLine.new('puppet', args)
app = Puppet::Application.new(command_line)
args[0] = 'different_subcommand'
args[1] = '--other-arg'
expect(app.command_line.subcommand_name).to eq('subcommand')
expect(app.command_line.args).to eq(['--arg'])
end
end
describe "application defaults" do
it "should fail if required app default values are missing" do
allow(@app).to receive(:app_defaults).and_return({ :foo => 'bar' })
expect(Puppet).to receive(:send_log).with(:err, /missing required app default setting/)
expect {
@app.run
}.to exit_with(1)
end
end
describe "finding" do
before do
@klass = Puppet::Application
allow(@klass).to receive(:puts)
end
it "should find classes in the namespace" do
expect(@klass.find("Agent")).to eq(@klass::Agent)
end
it "should not find classes outside the namespace" do
expect { @klass.find("String") }.to raise_error(LoadError)
end
it "should error if it can't find a class" do
expect(Puppet).to receive(:send_log) do |_level, message|
expect(message).to match(/Unable to find application 'ThisShallNeverEverEverExist'/)
expect(message).to match(/puppet\/application\/thisshallneverevereverexist/)
expect(message).to match(/no such file to load|cannot load such file/)
end
expect {
@klass.find("ThisShallNeverEverEverExist")
}.to raise_error(LoadError)
end
end
describe "#available_application_names" do
it 'should be able to find available application names' do
apps = %w{describe filebucket kick queue resource agent cert apply doc master}
expect(Puppet::Util::Autoload).to receive(:files_to_load).and_return(apps)
expect(Puppet::Application.available_application_names).to match_array(apps)
end
it 'should find applications from multiple paths' do
expect(Puppet::Util::Autoload).to receive(:files_to_load).with(
'puppet/application',
be_a(Puppet::Node::Environment)
).and_return(%w{ /a/foo.rb /b/bar.rb })
expect(Puppet::Application.available_application_names).to match_array(%w{ foo bar })
end
it 'should return unique application names' do
expect(Puppet::Util::Autoload).to receive(:files_to_load).with(
'puppet/application',
be_a(Puppet::Node::Environment)
).and_return(%w{ /a/foo.rb /b/foo.rb })
expect(Puppet::Application.available_application_names).to eq(%w{ foo })
end
it 'finds the application using the configured environment' do
Puppet[:environment] = 'production'
expect(Puppet::Util::Autoload).to receive(:files_to_load) do |_, env|
expect(env.name).to eq(:production)
end.and_return(%w{ /a/foo.rb })
expect(Puppet::Application.available_application_names).to eq(%w{ foo })
end
it "falls back to the current environment if the configured environment doesn't exist" do
Puppet[:environment] = 'doesnotexist'
expect(Puppet::Util::Autoload).to receive(:files_to_load) do |_, env|
expect(env.name).to eq(:'*root*')
end.and_return(%w[a/foo.rb])
expect(Puppet::Application.available_application_names).to eq(%w[foo])
end
end
describe ".run_mode" do
it "should default to user" do
expect(@appclass.run_mode.name).to eq(:user)
end
it "should set and get a value" do
@appclass.run_mode :agent
expect(@appclass.run_mode.name).to eq(:agent)
end
it "considers :server to be master" do
@appclass.run_mode :server
expect(@appclass.run_mode).to be_master
end
end
describe ".environment_mode" do
it "should default to :local" do
expect(@appclass.get_environment_mode).to eq(:local)
end
it "should set and get a value" do
@appclass.environment_mode :remote
expect(@appclass.get_environment_mode).to eq(:remote)
end
it "should error if given a random symbol" do
expect{@appclass.environment_mode :foo}.to raise_error(/Invalid environment mode/)
end
it "should error if given a string" do
expect{@appclass.environment_mode 'local'}.to raise_error(/Invalid environment mode/)
end
end
# These tests may look a little weird and repetative in its current state;
# it used to illustrate several ways that the run_mode could be changed
# at run time; there are fewer ways now, but it would still be nice to
# get to a point where it was entirely impossible.
describe "when dealing with run_mode" do
class TestApp < Puppet::Application
run_mode :server
def run_command
# no-op
end
end
it "should sadly and frighteningly allow run_mode to change at runtime via #initialize_app_defaults" do
allow(Puppet.features).to receive(:syslog?).and_return(true)
app = TestApp.new
app.initialize_app_defaults
expect(Puppet.run_mode).to be_server
end
it "should sadly and frighteningly allow run_mode to change at runtime via #run" do
app = TestApp.new
app.run
expect(app.class.run_mode.name).to eq(:server)
expect(Puppet.run_mode).to be_server
end
end
it "should explode when an invalid run mode is set at runtime, for great victory" do
expect {
class InvalidRunModeTestApp < Puppet::Application
run_mode :abracadabra
def run_command
# no-op
end
end
}.to raise_error(Puppet::Settings::ValidationError, /Invalid run mode/)
end
it "should have a run entry-point" do
expect(@app).to respond_to(:run)
end
it "should have a read accessor to options" do
expect(@app).to respond_to(:options)
end
it "should include a default setup method" do
expect(@app).to respond_to(:setup)
end
it "should include a default preinit method" do
expect(@app).to respond_to(:preinit)
end
it "should include a default run_command method" do
expect(@app).to respond_to(:run_command)
end
it "should invoke main as the default" do
expect(@app).to receive(:main)
@app.run_command
end
describe 'when invoking clear!' do
before :each do
Puppet::Application.run_status = :stop_requested
Puppet::Application.clear!
end
it 'should have nil run_status' do
expect(Puppet::Application.run_status).to be_nil
end
it 'should return false for restart_requested?' do
expect(Puppet::Application.restart_requested?).to be_falsey
end
it 'should return false for stop_requested?' do
expect(Puppet::Application.stop_requested?).to be_falsey
end
it 'should return false for interrupted?' do
expect(Puppet::Application.interrupted?).to be_falsey
end
it 'should return true for clear?' do
expect(Puppet::Application.clear?).to be_truthy
end
end
describe 'after invoking stop!' do
before :each do
Puppet::Application.run_status = nil
Puppet::Application.stop!
end
after :each do
Puppet::Application.run_status = nil
end
it 'should have run_status of :stop_requested' do
expect(Puppet::Application.run_status).to eq(:stop_requested)
end
it 'should return true for stop_requested?' do
expect(Puppet::Application.stop_requested?).to be_truthy
end
it 'should return false for restart_requested?' do
expect(Puppet::Application.restart_requested?).to be_falsey
end
it 'should return true for interrupted?' do
expect(Puppet::Application.interrupted?).to be_truthy
end
it 'should return false for clear?' do
expect(Puppet::Application.clear?).to be_falsey
end
end
describe 'when invoking restart!' do
before :each do
Puppet::Application.run_status = nil
Puppet::Application.restart!
end
after :each do
Puppet::Application.run_status = nil
end
it 'should have run_status of :restart_requested' do
expect(Puppet::Application.run_status).to eq(:restart_requested)
end
it 'should return true for restart_requested?' do
expect(Puppet::Application.restart_requested?).to be_truthy
end
it 'should return false for stop_requested?' do
expect(Puppet::Application.stop_requested?).to be_falsey
end
it 'should return true for interrupted?' do
expect(Puppet::Application.interrupted?).to be_truthy
end
it 'should return false for clear?' do
expect(Puppet::Application.clear?).to be_falsey
end
end
describe 'when performing a controlled_run' do
it 'should not execute block if not :clear?' do
Puppet::Application.run_status = :stop_requested
target = double('target')
expect(target).not_to receive(:some_method)
Puppet::Application.controlled_run do
target.some_method
end
end
it 'should execute block if :clear?' do
Puppet::Application.run_status = nil
target = double('target')
expect(target).to receive(:some_method).once
Puppet::Application.controlled_run do
target.some_method
end
end
describe 'on POSIX systems', :if => (Puppet.features.posix? && RUBY_PLATFORM != 'java') do
it 'should signal process with HUP after block if restart requested during block execution' do
Timeout::timeout(3) do # if the signal doesn't fire, this causes failure.
has_run = false
old_handler = trap('HUP') { has_run = true }
begin
Puppet::Application.controlled_run do
Puppet::Application.run_status = :restart_requested
end
# Ruby 1.9 uses a separate OS level thread to run the signal
# handler, so we have to poll - ideally, in a way that will kick
# the OS into running other threads - for a while.
#
# You can't just use the Ruby Thread yield thing either, because
# that is just an OS hint, and Linux ... doesn't take that
# seriously. --daniel 2012-03-22
sleep 0.001 while not has_run
ensure
trap('HUP', old_handler)
end
end
end
end
after :each do
Puppet::Application.run_status = nil
end
end
describe "when parsing command-line options" do
before :each do
allow(@app.command_line).to receive(:args).and_return([])
allow(Puppet.settings).to receive(:optparse_addargs).and_return([])
end
it "should pass the banner to the option parser" do
option_parser = double("option parser")
allow(option_parser).to receive(:on)
allow(option_parser).to receive(:parse!)
@app.class.instance_eval do
banner "banner"
end
expect(OptionParser).to receive(:new).with("banner").and_return(option_parser)
@app.parse_options
end
it "should ask OptionParser to parse the command-line argument" do
allow(@app.command_line).to receive(:args).and_return(%w{ fake args })
expect_any_instance_of(OptionParser).to receive(:parse!).with(%w{ fake args })
@app.parse_options
end
describe "when using --help" do
it "should call exit" do
allow(@app).to receive(:puts)
expect { @app.handle_help(nil) }.to exit_with 0
end
end
describe "when using --version" do
it "should declare a version option" do
expect(@app).to respond_to(:handle_version)
end
it "should exit after printing the version" do
allow(@app).to receive(:puts)
expect { @app.handle_version(nil) }.to exit_with 0
end
end
describe "when dealing with an argument not declared directly by the application" do
it "should pass it to handle_unknown if this method exists" do
allow(Puppet.settings).to receive(:optparse_addargs).and_return([["--not-handled", :REQUIRED]])
expect(@app).to receive(:handle_unknown).with("--not-handled", "value").and_return(true)
allow(@app.command_line).to receive(:args).and_return(["--not-handled", "value"])
@app.parse_options
end
it "should transform boolean option to normal form for Puppet.settings" do
expect(@app).to receive(:handle_unknown).with("--option", true)
@app.send(:handlearg, "--[no-]option", true)
end
it "should transform boolean option to no- form for Puppet.settings" do
expect(@app).to receive(:handle_unknown).with("--no-option", false)
@app.send(:handlearg, "--[no-]option", false)
end
end
end
describe "when calling default setup" do
before :each do
allow(@app.options).to receive(:[])
end
[ :debug, :verbose ].each do |level|
it "should honor option #{level}" do
allow(@app.options).to receive(:[]).with(level).and_return(true)
allow(Puppet::Util::Log).to receive(:newdestination)
@app.setup
expect(Puppet::Util::Log.level).to eq(level == :verbose ? :info : :debug)
end
end
it "should honor setdest option" do
allow(@app.options).to receive(:[]).with(:setdest).and_return(false)
expect(Puppet::Util::Log).to receive(:setup_default)
@app.setup
end
it "sets the log destination if provided via settings" do
allow(@app.options).to receive(:[]).and_call_original
Puppet[:logdest] = "set_via_config"
expect(Puppet::Util::Log).to receive(:newdestination).with("set_via_config")
@app.setup
end
it "does not downgrade the loglevel when --verbose is specified" do
Puppet[:log_level] = :debug
allow(@app.options).to receive(:[]).with(:verbose).and_return(true)
@app.setup_logs
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "allows the loglevel to be specified as an argument" do
@app.set_log_level(:debug => true)
expect(Puppet::Util::Log.level).to eq(:debug)
end
end
describe "when configuring routes" do
include PuppetSpec::Files
before :each do
Puppet::Node.indirection.reset_terminus_class
end
after :each do
Puppet::Node.indirection.reset_terminus_class
end
it "should use the routes specified for only the active application" do
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
test_app:
node:
terminus: exec
other_app:
node:
terminus: plain
catalog:
terminus: invalid
ROUTES
end
@app.configure_indirector_routes
expect(Puppet::Node.indirection.terminus_class).to eq('exec')
end
it "should not fail if the route file doesn't exist" do
Puppet[:route_file] = "/dev/null/non-existent"
expect { @app.configure_indirector_routes }.to_not raise_error
end
it "should raise an error if the routes file is invalid" do
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
invalid : : yaml
ROUTES
end
expect { @app.configure_indirector_routes }.to raise_error(Puppet::Error, /mapping values are not allowed/)
end
it "should treat master routes on server application" do
allow(@app).to receive(:name).and_return("server")
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
master:
node:
terminus: exec
ROUTES
end
@app.configure_indirector_routes
expect(Puppet::Node.indirection.terminus_class).to eq('exec')
end
it "should treat server routes on master application" do
allow(@app).to receive(:name).and_return("master")
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
server:
node:
terminus: exec
ROUTES
end
@app.configure_indirector_routes
expect(Puppet::Node.indirection.terminus_class).to eq('exec')
end
end
describe "when running" do
before :each do
allow(@app).to receive(:preinit)
allow(@app).to receive(:setup)
allow(@app).to receive(:parse_options)
end
it "should call preinit" do
allow(@app).to receive(:run_command)
expect(@app).to receive(:preinit)
@app.run
end
it "should call parse_options" do
allow(@app).to receive(:run_command)
expect(@app).to receive(:parse_options)
@app.run
end
it "should call run_command" do
expect(@app).to receive(:run_command)
@app.run
end
it "should call run_command" do
expect(@app).to receive(:run_command)
@app.run
end
it "should call main as the default command" do
expect(@app).to receive(:main)
@app.run
end
it "should warn and exit if no command can be called" do
expect(Puppet).to receive(:send_log).with(:err, "Could not run: No valid command or main")
expect { @app.run }.to exit_with 1
end
it "should raise an error if dispatch returns no command" do
expect(Puppet).to receive(:send_log).with(:err, "Could not run: No valid command or main")
expect { @app.run }.to exit_with 1
end
end
describe "when metaprogramming" do
describe "when calling option" do
it "should create a new method named after the option" do
@app.class.option("--test1","-t") do
end
expect(@app).to respond_to(:handle_test1)
end
it "should transpose in option name any '-' into '_'" do
@app.class.option("--test-dashes-again","-t") do
end
expect(@app).to respond_to(:handle_test_dashes_again)
end
it "should create a new method called handle_test2 with option(\"--[no-]test2\")" do
@app.class.option("--[no-]test2","-t") do
end
expect(@app).to respond_to(:handle_test2)
end
describe "when a block is passed" do
it "should create a new method with it" do
@app.class.option("--[no-]test2","-t") do
raise "I can't believe it, it works!"
end
expect { @app.handle_test2 }.to raise_error(RuntimeError, /I can't believe it, it works!/)
end
it "should declare the option to OptionParser" do
allow_any_instance_of(OptionParser).to receive(:on)
expect_any_instance_of(OptionParser).to receive(:on).with("--[no-]test3", anything)
@app.class.option("--[no-]test3","-t") do
end
@app.parse_options
end
it "should pass a block that calls our defined method" do
allow_any_instance_of(OptionParser).to receive(:on)
allow_any_instance_of(OptionParser).to receive(:on).with('--test4', '-t').and_yield(nil)
expect(@app).to receive(:send).with(:handle_test4, nil)
@app.class.option("--test4","-t") do
end
@app.parse_options
end
end
describe "when no block is given" do
it "should declare the option to OptionParser" do
allow_any_instance_of(OptionParser).to receive(:on)
expect_any_instance_of(OptionParser).to receive(:on).with("--test4", "-t")
@app.class.option("--test4","-t")
@app.parse_options
end
it "should give to OptionParser a block that adds the value to the options array" do
allow_any_instance_of(OptionParser).to receive(:on)
allow_any_instance_of(OptionParser).to receive(:on).with("--test4", "-t").and_yield(nil)
expect(@app.options).to receive(:[]=).with(:test4, nil)
@app.class.option("--test4","-t")
@app.parse_options
end
end
end
end
describe "#handle_logdest_arg" do
let(:test_arg) { "arg_test_logdest" }
it "should log an exception that is raised" do
our_exception = Puppet::DevError.new("test exception")
expect(Puppet::Util::Log).to receive(:newdestination).with(test_arg).and_raise(our_exception)
expect(Puppet).to receive(:log_and_raise).with(our_exception, anything)
@app.handle_logdest_arg(test_arg)
end
it "should exit when an exception is raised" do
our_exception = Puppet::DevError.new("test exception")
expect(Puppet::Util::Log).to receive(:newdestination).with(test_arg).and_raise(our_exception)
expect(Puppet).to receive(:log_and_raise).with(our_exception, anything).and_raise(our_exception)
expect { @app.handle_logdest_arg(test_arg) }.to raise_error(Puppet::DevError)
end
it "should set the new log destination" do
expect(Puppet::Util::Log).to receive(:newdestination).with(test_arg)
@app.handle_logdest_arg(test_arg)
end
it "should set the flag that a destination is set in the options hash" do
allow(Puppet::Util::Log).to receive(:newdestination).with(test_arg)
@app.handle_logdest_arg(test_arg)
expect(@app.options[:setdest]).to be_truthy
end
it "does not set the log destination if arg is nil" do
expect(Puppet::Util::Log).not_to receive(:newdestination)
@app.handle_logdest_arg(nil)
end
it "accepts multiple destinations as a comma sepparated list" do
dest1 = '/tmp/path1'
dest2 = 'console'
dest3 = '/tmp/path2'
dest_args = [dest1, dest2, dest3].join(' , ')
[dest1, dest2, dest3].each do |dest|
expect(Puppet::Util::Log).to receive(:newdestination).with(dest)
end
@app.handle_logdest_arg(dest_args)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/transaction_spec.rb | spec/unit/transaction_spec.rb | require 'spec_helper'
require 'matchers/include_in_order'
require 'puppet_spec/compiler'
require 'puppet/transaction'
require 'fileutils'
describe Puppet::Transaction do
include PuppetSpec::Files
include PuppetSpec::Compiler
def catalog_with_resource(resource)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(resource)
catalog
end
def transaction_with_resource(resource)
transaction = Puppet::Transaction.new(catalog_with_resource(resource), nil, Puppet::Graph::SequentialPrioritizer.new)
transaction
end
before(:all) do
Puppet::Type.newtype(:transaction_generator) do
newparam(:name) { isnamevar }
def generate
end
end
end
after(:all) do
Puppet::Type.rmtype(:transaction_generator)
end
before do
@basepath = make_absolute("/what/ever")
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, Puppet::Graph::SequentialPrioritizer.new)
end
it "should be able to look resource status up by resource reference" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(transaction.resource_status(resource.to_s)).to be_changed
end
# This will basically only ever be used during testing.
it "should automatically create resource statuses if asked for a non-existent status" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
expect(transaction.resource_status(resource)).to be_instance_of(Puppet::Resource::Status)
end
it "should add provided resource statuses to its report" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
status = transaction.resource_status(resource)
expect(transaction.report.resource_statuses[resource.to_s]).to equal(status)
end
it "should not consider there to be failed or failed_to_restart resources if no statuses are marked failed" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(transaction).not_to be_any_failed
end
it "should use the provided report object" do
report = Puppet::Transaction::Report.new
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, report, nil)
expect(transaction.report).to eq(report)
end
it "should create a report if none is provided" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
expect(transaction.report).to be_kind_of Puppet::Transaction::Report
end
describe "when initializing" do
it "should create an event manager" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
expect(transaction.event_manager).to be_instance_of(Puppet::Transaction::EventManager)
expect(transaction.event_manager.transaction).to equal(transaction)
end
it "should create a resource harness" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
expect(transaction.resource_harness).to be_instance_of(Puppet::Transaction::ResourceHarness)
expect(transaction.resource_harness.transaction).to equal(transaction)
end
it "should set retrieval time on the report" do
catalog = Puppet::Resource::Catalog.new
report = Puppet::Transaction::Report.new
catalog.retrieval_duration = 5
expect(report).to receive(:add_times).with(:config_retrieval, 5)
Puppet::Transaction.new(catalog, report, nil)
end
end
describe "when evaluating a resource" do
let(:resource) { Puppet::Type.type(:file).new :path => @basepath }
it "should process events" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(false)
expect(transaction.event_manager).to receive(:process_events).with(resource)
transaction.evaluate
end
describe "and the resource should be skipped" do
it "should mark the resource's status as skipped" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
transaction.evaluate
expect(transaction.resource_status(resource)).to be_skipped
end
it "does not process any scheduled events" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
expect(transaction.event_manager).not_to receive(:process_events).with(resource)
transaction.evaluate
end
it "dequeues all events scheduled on that resource" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
expect(transaction.event_manager).to receive(:dequeue_all_events_for_resource).with(resource)
transaction.evaluate
end
end
end
describe "when evaluating a skipped resource for corrective change it" do
before :each do
# Enable persistence during tests
allow_any_instance_of(Puppet::Transaction::Persistence).to receive(:enabled?).and_return(true)
end
it "should persist in the transactionstore" do
Puppet[:transactionstorefile] = tmpfile('persistence_test')
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(transaction.resource_status(resource)).to be_changed
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
expect(transaction.event_manager).not_to receive(:process_events).with(resource)
transaction.evaluate
expect(transaction.resource_status(resource)).to be_skipped
persistence = Puppet::Transaction::Persistence.new
persistence.load
expect(persistence.get_system_value(resource.ref, "message")).to eq(["foobar"])
end
end
describe "when applying a resource" do
before do
@catalog = Puppet::Resource::Catalog.new
@resource = Puppet::Type.type(:file).new :path => @basepath
@catalog.add_resource(@resource)
@status = Puppet::Resource::Status.new(@resource)
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
allow(@transaction.event_manager).to receive(:queue_events)
end
it "should use its resource harness to apply the resource" do
expect(@transaction.resource_harness).to receive(:evaluate).with(@resource)
@transaction.evaluate
end
it "should add the resulting resource status to its status list" do
allow(@transaction.resource_harness).to receive(:evaluate).and_return(@status)
@transaction.evaluate
expect(@transaction.resource_status(@resource)).to be_instance_of(Puppet::Resource::Status)
end
it "should queue any events added to the resource status" do
allow(@transaction.resource_harness).to receive(:evaluate).and_return(@status)
expect(@status).to receive(:events).and_return(%w{a b})
expect(@transaction.event_manager).to receive(:queue_events).with(@resource, ["a", "b"])
@transaction.evaluate
end
it "should log and skip any resources that cannot be applied" do
expect(@resource).to receive(:properties).and_raise(ArgumentError)
@transaction.evaluate
expect(@transaction.report.resource_statuses[@resource.to_s]).to be_failed
end
it "should report any_failed if any resources failed" do
expect(@resource).to receive(:properties).and_raise(ArgumentError)
@transaction.evaluate
expect(@transaction).to be_any_failed
end
it "should report any_failed if any resources failed to restart" do
@transaction.evaluate
@transaction.report.resource_statuses[@resource.to_s].failed_to_restart = true
expect(@transaction).to be_any_failed
end
end
describe "#unblock" do
let(:graph) { @transaction.relationship_graph }
let(:resource) { Puppet::Type.type(:notify).new(:name => 'foo') }
it "should calculate the number of blockers if it's not known" do
graph.add_vertex(resource)
3.times do |i|
other = Puppet::Type.type(:notify).new(:name => i.to_s)
graph.add_vertex(other)
graph.add_edge(other, resource)
end
graph.unblock(resource)
expect(graph.blockers[resource]).to eq(2)
end
it "should decrement the number of blockers if there are any" do
graph.blockers[resource] = 40
graph.unblock(resource)
expect(graph.blockers[resource]).to eq(39)
end
it "should warn if there are no blockers" do
vertex = double('vertex')
expect(vertex).to receive(:warning).with("appears to have a negative number of dependencies")
graph.blockers[vertex] = 0
graph.unblock(vertex)
end
it "should return true if the resource is now unblocked" do
graph.blockers[resource] = 1
expect(graph.unblock(resource)).to eq(true)
end
it "should return false if the resource is still blocked" do
graph.blockers[resource] = 2
expect(graph.unblock(resource)).to eq(false)
end
end
describe "when traversing" do
let(:path) { tmpdir('eval_generate') }
let(:resource) { Puppet::Type.type(:file).new(:path => path, :recurse => true) }
before :each do
@transaction.catalog.add_resource(resource)
end
it "should yield the resource even if eval_generate is called" do
expect_any_instance_of(Puppet::Transaction::AdditionalResourceGenerator).to receive(:eval_generate).with(resource).and_return(true)
yielded = false
@transaction.evaluate do |res|
yielded = true if res == resource
end
expect(yielded).to eq(true)
end
it "should prefetch the provider if necessary" do
expect(@transaction).to receive(:prefetch_if_necessary).with(resource)
@transaction.evaluate {}
end
it "traverses independent resources before dependent resources" do
dependent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(dependent)
seen = []
@transaction.evaluate do |res|
seen << res
end
expect(seen).to include_in_order(resource, dependent)
end
it "traverses completely independent resources in the order they appear in the catalog" do
independent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(independent)
seen = []
@transaction.evaluate do |res|
seen << res
end
expect(seen).to include_in_order(resource, independent)
end
it "should fail unsuitable resources and go on if it gets blocked" do
dependent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(dependent)
allow(resource).to receive(:suitable?).and_return(false)
evaluated = []
@transaction.evaluate do |res|
evaluated << res
end
# We should have gone on to evaluate the children
expect(evaluated).to eq([dependent])
expect(@transaction.resource_status(resource)).to be_failed
end
end
describe "when generating resources before traversal" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) { Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) }
let(:generator) { Puppet::Type.type(:transaction_generator).new :title => "generator" }
let(:generated) do
%w[a b c].map { |name| Puppet::Type.type(:transaction_generator).new(:name => name) }
end
before :each do
catalog.add_resource generator
allow(generator).to receive(:generate).and_return(generated)
# avoid crude failures because of nil resources that result
# from implicit containment and lacking containers
allow(catalog).to receive(:container_of).and_return(generator)
end
it "should call 'generate' on all created resources" do
generated.each { |res| expect(res).to receive(:generate) }
transaction.evaluate
end
it "should finish all resources" do
generated.each { |res| expect(res).to receive(:finish) }
transaction.evaluate
end
it "should copy all tags to the newly generated resources" do
generator.tag('one', 'two')
transaction.evaluate
generated.each do |res|
expect(res).to be_tagged(*generator.tags)
end
end
end
describe "after resource traversal" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
let(:report) { Puppet::Transaction::Report.new }
let(:transaction) { Puppet::Transaction.new(catalog, report, prioritizer) }
let(:generator) { Puppet::Transaction::AdditionalResourceGenerator.new(catalog, nil, prioritizer) }
before :each do
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, nil, prioritizer)
allow(Puppet::Transaction::AdditionalResourceGenerator).to receive(:new).and_return(generator)
end
it "should should query the generator for whether resources failed to generate" do
relationship_graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
allow(catalog).to receive(:relationship_graph).and_return(relationship_graph)
expect(relationship_graph).to receive(:traverse).ordered
expect(generator).to receive(:resources_failed_to_generate).ordered
transaction.evaluate
end
it "should report that resources failed to generate" do
expect(generator).to receive(:resources_failed_to_generate).and_return(true)
expect(report).to receive(:resources_failed_to_generate=).with(true)
transaction.evaluate
end
it "should not report that resources failed to generate if none did" do
expect(generator).to receive(:resources_failed_to_generate).and_return(false)
expect(report).not_to receive(:resources_failed_to_generate=)
transaction.evaluate
end
end
describe "when performing pre-run checks" do
let(:resource) { Puppet::Type.type(:notify).new(:title => "spec") }
let(:transaction) { transaction_with_resource(resource) }
let(:spec_exception) { 'spec-exception' }
it "should invoke each resource's hook and apply the catalog after no failures" do
expect(resource).to receive(:pre_run_check)
transaction.evaluate
end
it "should abort the transaction on failure" do
expect(resource).to receive(:pre_run_check).and_raise(Puppet::Error, spec_exception)
expect { transaction.evaluate }.to raise_error(Puppet::Error, /Some pre-run checks failed/)
end
it "should log the resource-specific exception" do
expect(resource).to receive(:pre_run_check).and_raise(Puppet::Error, spec_exception)
expect(resource).to receive(:log_exception).with(have_attributes(message: match(/#{spec_exception}/)))
expect { transaction.evaluate }.to raise_error(Puppet::Error)
end
end
describe "when skipping a resource" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
@transaction = Puppet::Transaction.new(@catalog, nil, nil)
end
it "should skip resource with missing tags" do
allow(@transaction).to receive(:missing_tags?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip resources tagged with the skip tags" do
allow(@transaction).to receive(:skip_tags?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip unscheduled resources" do
allow(@transaction).to receive(:scheduled?).and_return(false)
expect(@transaction).to be_skip(@resource)
end
it "should skip resources with failed dependencies" do
allow(@transaction).to receive(:failed_dependencies?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip virtual resource" do
allow(@resource).to receive(:virtual?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip device only resouce on normal host" do
allow(@resource).to receive(:appliable_to_host?).and_return(false)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = false
expect(@transaction).to be_skip(@resource)
end
it "should not skip device only resouce on remote device" do
allow(@resource).to receive(:appliable_to_host?).and_return(false)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = true
expect(@transaction).not_to be_skip(@resource)
end
it "should skip host resouce on device" do
allow(@resource).to receive(:appliable_to_host?).and_return(true)
allow(@resource).to receive(:appliable_to_device?).and_return(false)
@transaction.for_network_device = true
expect(@transaction).to be_skip(@resource)
end
it "should not skip resouce available on both device and host when on device" do
allow(@resource).to receive(:appliable_to_host?).and_return(true)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = true
expect(@transaction).not_to be_skip(@resource)
end
it "should not skip resouce available on both device and host when on host" do
allow(@resource).to receive(:appliable_to_host?).and_return(true)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = false
expect(@transaction).not_to be_skip(@resource)
end
end
describe "when determining if tags are missing" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
@transaction = Puppet::Transaction.new(@catalog, nil, nil)
allow(@transaction).to receive(:ignore_tags?).and_return(false)
end
it "should not be missing tags if tags are being ignored" do
expect(@transaction).to receive(:ignore_tags?).and_return(true)
expect(@resource).not_to receive(:tagged?)
expect(@transaction).not_to be_missing_tags(@resource)
end
it "should not be missing tags if the transaction tags are empty" do
@transaction.tags = []
expect(@resource).not_to receive(:tagged?)
expect(@transaction).not_to be_missing_tags(@resource)
end
it "should otherwise let the resource determine if it is missing tags" do
tags = ['one', 'two']
@transaction.tags = tags
expect(@transaction).to be_missing_tags(@resource)
end
end
describe "when determining if a resource should be scheduled" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@resource)
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
end
it "should always schedule resources if 'ignoreschedules' is set" do
@transaction.ignoreschedules = true
expect(@transaction.resource_harness).not_to receive(:scheduled?)
@transaction.evaluate
expect(@transaction.resource_status(@resource)).to be_changed
end
it "should let the resource harness determine whether the resource should be scheduled" do
expect(@transaction.resource_harness).to receive(:scheduled?).with(@resource).and_return("feh")
@transaction.evaluate
end
end
describe "when prefetching" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) { Puppet::Transaction.new(catalog, nil, nil) }
let(:resource) { Puppet::Type.type(:package).new :title => "foo", :name => "bar", :provider => :pkgng }
let(:resource2) { Puppet::Type.type(:package).new :title => "blah", :provider => :apt }
before :each do
allow(resource).to receive(:suitable?).and_return(true)
catalog.add_resource resource
catalog.add_resource resource2
end
it "should match resources by name, not title" do
expect(resource.provider.class).to receive(:prefetch).with({"bar" => resource})
transaction.prefetch_if_necessary(resource)
end
it "should not prefetch a provider which has already been prefetched" do
transaction.prefetched_providers[:package][:pkgng] = true
expect(resource.provider.class).not_to receive(:prefetch)
transaction.prefetch_if_necessary(resource)
end
it "should mark the provider prefetched" do
allow(resource.provider.class).to receive(:prefetch)
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetched_providers[:package][:pkgng]).to be_truthy
end
it "should prefetch resources without a provider if prefetching the default provider" do
other = Puppet::Type.type(:package).new :name => "other"
other.instance_variable_set(:@provider, nil)
catalog.add_resource other
allow(resource.class).to receive(:defaultprovider).and_return(resource.provider.class)
expect(resource.provider.class).to receive(:prefetch).with({'bar' => resource, 'other' => other})
transaction.prefetch_if_necessary(resource)
end
it "should not prefetch a provider which has failed" do
transaction.prefetch_failed_providers[:package][:pkgng] = true
expect(resource.provider.class).not_to receive(:prefetch)
transaction.prefetch_if_necessary(resource)
end
it "should not rescue SystemExit" do
expect(resource.provider.class).to receive(:prefetch).and_raise(SystemExit, "SystemMessage")
expect { transaction.prefetch_if_necessary(resource) }.to raise_error(SystemExit, "SystemMessage")
end
it "should mark resources as failed when prefetching raises LoadError" do
expect(resource.provider.class).to receive(:prefetch).and_raise(LoadError, "LoadMessage")
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetched_providers[:package][:pkgng]).to be_truthy
end
describe "and prefetching raises Puppet::Error" do
before :each do
expect(resource.provider.class).to receive(:prefetch).and_raise(Puppet::Error, "message")
end
it "should rescue prefetch executions" do
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetched_providers[:package][:pkgng]).to be_truthy
end
it "should mark resources as failed", :unless => RUBY_PLATFORM == 'java' do
transaction.evaluate
expect(transaction.resource_status(resource).failed?).to be_truthy
end
it "should mark a provider that has failed prefetch" do
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetch_failed_providers[:package][:pkgng]).to be_truthy
end
describe "and new resources are generated" do
let(:generator) { Puppet::Type.type(:transaction_generator).new :title => "generator" }
let(:generated) do
%w[a b c].map { |name| Puppet::Type.type(:package).new :title => "foo", :name => name, :provider => :apt }
end
before :each do
catalog.add_resource generator
allow(generator).to receive(:generate).and_return(generated)
allow(catalog).to receive(:container_of).and_return(generator)
end
it "should not evaluate resources with a failed provider, even if the prefetch is rescued" do
#Only the generator resource should be applied, all the other resources are failed, and skipped.
catalog.remove_resource resource2
expect(transaction).to receive(:apply).once
transaction.evaluate
end
it "should not fail other resources added after the failing resource", :unless => RUBY_PLATFORM == 'java' do
new_resource = Puppet::Type.type(:notify).new :name => "baz"
catalog.add_resource(new_resource)
transaction.evaluate
expect(transaction.resource_status(new_resource).failed?).to be_falsey
end
it "should fail other resources that require the failing resource" do
new_resource = Puppet::Type.type(:notify).new(:name => "baz", :require => resource)
catalog.add_resource(new_resource)
catalog.remove_resource resource2
expect(transaction).to receive(:apply).once
transaction.evaluate
expect(transaction.resource_status(resource).failed?).to be_truthy
expect(transaction.resource_status(new_resource).dependency_failed?).to be_truthy
expect(transaction.skip?(new_resource)).to be_truthy
end
end
end
end
describe "during teardown" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) do
Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
end
let(:teardown_type) do
Puppet::Type.newtype(:teardown_test) do
newparam(:name) {}
end
end
before :each do
teardown_type.provide(:teardown_provider) do
class << self
attr_reader :result
def post_resource_eval
@result = 'passed'
end
end
end
end
it "should call ::post_resource_eval on provider classes that support it" do
resource = teardown_type.new(:title => "foo", :provider => :teardown_provider)
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(resource.provider.class.result).to eq('passed')
end
it "should call ::post_resource_eval even if other providers' ::post_resource_eval fails" do
teardown_type.provide(:always_fails) do
class << self
attr_reader :result
def post_resource_eval
@result = 'failed'
raise Puppet::Error, "This provider always fails"
end
end
end
good_resource = teardown_type.new(:title => "bloo", :provider => :teardown_provider)
bad_resource = teardown_type.new(:title => "blob", :provider => :always_fails)
catalog.add_resource(bad_resource)
catalog.add_resource(good_resource)
transaction.evaluate
expect(good_resource.provider.class.result).to eq('passed')
expect(bad_resource.provider.class.result).to eq('failed')
end
it "should call ::post_resource_eval even if one of the resources fails" do
resource = teardown_type.new(:title => "foo", :provider => :teardown_provider)
allow(resource).to receive(:retrieve_resource).and_raise
catalog.add_resource resource
expect(resource.provider.class).to receive(:post_resource_eval)
transaction.evaluate
end
it "should call Selinux.selabel_close in case Selinux is enabled", :if => Puppet.features.posix? do
handle = double('selinux_handle')
selinux = class_double('selinux', is_selinux_enabled: 1, selabel_close: nil, selabel_open: handle, selabel_lookup: -1)
stub_const('Selinux', selinux)
stub_const('Selinux::SELABEL_CTX_FILE', 0)
resource = Puppet::Type.type(:file).new(:path => make_absolute("/tmp/foo"))
transaction = transaction_with_resource(resource)
expect(Selinux).to receive(:selabel_close).with(handle)
transaction.evaluate
end
end
describe 'when checking application run state' do
before do
@catalog = Puppet::Resource::Catalog.new
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
end
context "when stop is requested" do
before :each do
allow(Puppet::Application).to receive(:stop_requested?).and_return(true)
end
it 'should return true for :stop_processing?' do
expect(@transaction).to be_stop_processing
end
it 'always evaluates non-host_config catalogs' do
@catalog.host_config = false
expect(@transaction).not_to be_stop_processing
end
end
it 'should return false for :stop_processing? if Puppet::Application.stop_requested? is false' do
allow(Puppet::Application).to receive(:stop_requested?).and_return(false)
expect(@transaction.stop_processing?).to be_falsey
end
describe 'within an evaluate call' do
before do
@resource = Puppet::Type.type(:notify).new :title => "foobar"
@catalog.add_resource @resource
end
it 'should stop processing if :stop_processing? is true' do
allow(@transaction).to receive(:stop_processing?).and_return(true)
expect(@transaction).not_to receive(:eval_resource)
@transaction.evaluate
end
it 'should continue processing if :stop_processing? is false' do
allow(@transaction).to receive(:stop_processing?).and_return(false)
expect(@transaction).to receive(:eval_resource).and_return(nil)
@transaction.evaluate
end
end
end
it "errors with a dependency cycle for a resource that requires itself" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: require => Notify[cycle] }
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
it "errors with a dependency cycle for a self-requiring resource also required by another resource" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: require => Notify[cycle] }
notify { other: require => Notify[cycle] }
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
it "errors with a dependency cycle for a resource that requires itself and another resource" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle:
require => [Notify[other], Notify[cycle]]
}
notify { other: }
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
it "errors with a dependency cycle for a resource that is later modified to require itself" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: }
Notify <| title == 'cycle' |> {
require => Notify[cycle]
}
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
context "when generating a report for a transaction with a dependency cycle" do
let(:catalog) do
compile_to_ral(<<-MANIFEST)
notify { foo: require => Notify[bar] }
notify { bar: require => Notify[foo] }
MANIFEST
end
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
let(:transaction) { Puppet::Transaction.new(catalog,
Puppet::Transaction::Report.new("apply"),
prioritizer) }
before(:each) do
expect { transaction.evaluate }.to raise_error(Puppet::Error)
transaction.report.finalize_report
end
it "should report resources involved in a dependency cycle as failed" do
expect(transaction.report.resource_statuses['Notify[foo]']).to be_failed
expect(transaction.report.resource_statuses['Notify[bar]']).to be_failed
end
it "should generate a failure event for a resource in a dependency cycle" do
status = transaction.report.resource_statuses['Notify[foo]']
expect(status.events.first.status).to eq('failure')
expect(status.events.first.message).to eq('resource is part of a dependency cycle')
end
it "should report that the transaction is failed" do
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/defaults_spec.rb | spec/unit/defaults_spec.rb | require 'spec_helper'
require 'puppet/settings'
describe "Defaults" do
describe ".default_diffargs" do
it "should be '-u'" do
expect(Puppet.default_diffargs).to eq("-u")
end
end
describe 'strict' do
it 'should accept the valid value :off' do
expect {Puppet.settings[:strict] = 'off'}.to_not raise_exception
end
it 'should accept the valid value :warning' do
expect {Puppet.settings[:strict] = 'warning'}.to_not raise_exception
end
it 'should accept the valid value :error' do
expect {Puppet.settings[:strict] = 'error'}.to_not raise_exception
end
it 'should fail if given an invalid value' do
expect {Puppet.settings[:strict] = 'ignore'}.to raise_exception(/Invalid value 'ignore' for parameter strict\./)
end
end
describe '.default_digest_algorithm' do
it 'defaults to sha256 when FIPS is not enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false)
expect(Puppet.default_digest_algorithm).to eq('sha256')
end
it 'defaults to sha256 when FIPS is enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect(Puppet.default_digest_algorithm).to eq('sha256')
end
end
describe '.supported_checksum_types' do
it 'defaults to sha256, sha384, sha512, sha224, md5 when FIPS is not enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false)
expect(Puppet.default_file_checksum_types).to eq(%w[sha256 sha384 sha512 sha224 md5])
end
it 'defaults to sha256, sha384, sha512, sha224 when FIPS is enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect(Puppet.default_file_checksum_types).to eq(%w[sha256 sha384 sha512 sha224])
end
end
describe 'Puppet[:supported_checksum_types]' do
it 'defaults to sha256, sha512, sha384, sha224, md5' do
expect(Puppet.settings[:supported_checksum_types]).to eq(%w[sha256 sha384 sha512 sha224 md5])
end
it 'should raise an error on an unsupported checksum type' do
expect {
Puppet.settings[:supported_checksum_types] = %w[md5 foo]
}.to raise_exception ArgumentError,
/Invalid value 'foo' for parameter supported_checksum_types. Allowed values are/
end
it 'should not raise an error on setting a valid list of checksum types' do
Puppet.settings[:supported_checksum_types] = %w[sha256 md5lite mtime]
expect(Puppet.settings[:supported_checksum_types]).to eq(%w[sha256 md5lite mtime])
end
it 'raises when setting md5 in FIPS mode' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect {
Puppet.settings[:supported_checksum_types] = %w[md5]
}.to raise_error(ArgumentError,
/Invalid value 'md5' for parameter supported_checksum_types. Allowed values are 'sha256'/)
end
end
describe 'manage_internal_file_permissions' do
describe 'on windows', :if => Puppet::Util::Platform.windows? do
it 'should default to false' do
expect(Puppet.settings[:manage_internal_file_permissions]).to be false
end
end
describe 'on non-windows', :if => ! Puppet::Util::Platform.windows? do
it 'should default to true' do
expect(Puppet.settings[:manage_internal_file_permissions]).to be true
end
end
end
describe 'basemodulepath' do
it 'includes the user and system modules', :unless => Puppet::Util::Platform.windows? do
expect(
Puppet[:basemodulepath]
).to match(%r{.*/code/modules:/opt/puppetlabs/puppet/modules$})
end
describe 'on windows', :if => Puppet::Util::Platform.windows? do
let(:installdir) { 'C:\Program Files\Puppet Labs\Puppet' }
it 'includes user and system modules' do
allow(ENV).to receive(:fetch).with("FACTER_env_windows_installdir", anything).and_return(installdir)
expect(
Puppet.default_basemodulepath
).to eq('$codedir/modules;C:\Program Files\Puppet Labs\Puppet/puppet/modules')
end
it 'includes user modules if installdir fact is missing' do
allow(ENV).to receive(:[]).with("FACTER_env_windows_installdir").and_return(nil)
expect(
Puppet.default_basemodulepath
).to eq('$codedir/modules')
end
end
end
describe 'vendormoduledir' do
it 'includes the default vendormoduledir', :unless => Puppet::Util::Platform.windows? do
expect(
Puppet[:vendormoduledir]
).to eq('/opt/puppetlabs/puppet/vendor_modules')
end
describe 'on windows', :if => Puppet::Util::Platform.windows? do
let(:installdir) { 'C:\Program Files\Puppet Labs\Puppet' }
it 'includes the default vendormoduledir' do
allow(ENV).to receive(:fetch).with("FACTER_env_windows_installdir", anything).and_return(installdir)
expect(
Puppet.default_vendormoduledir
).to eq('C:\Program Files\Puppet Labs\Puppet\puppet\vendor_modules')
end
it 'is nil if installdir fact is missing' do
allow(ENV).to receive(:[]).with("FACTER_env_windows_installdir").and_return(nil)
expect(Puppet.default_vendormoduledir).to be_nil
end
end
end
describe "deprecated settings" do
it 'does not issue a deprecation warning by default' do
expect(Puppet).to receive(:deprecation_warning).never
Puppet.initialize_settings
end
end
describe "the default cadir", :unless => Puppet::Util::Platform.windows? do
it 'defaults to the puppetserver confdir when no cadir is found' do
Puppet.initialize_settings
expect(Puppet[:cadir]).to eq('/etc/puppetlabs/puppetserver/ca')
end
it 'returns an empty string for Windows platforms', :if => Puppet::Util::Platform.windows? do
Puppet.initialize_settings
expect(Puppet[:cadir]).to eq("")
end
end
describe '#default_cadir', :unless => Puppet::Util::Platform.windows? do
it 'warns when a CA dir exists in the current ssldir' do
cadir = File.join(Puppet[:ssldir], 'ca')
FileUtils.mkdir_p(cadir)
expect(Puppet.default_cadir).to eq(cadir)
end
end
describe "#preferred_serialization_format" do
it 'raises if PSON is not available', unless: Puppet.features.pson? do
expect {
Puppet.settings[:preferred_serialization_format] = "pson"
}.to raise_error(Puppet::Settings::ValidationError, "The 'puppet-pson' gem must be installed to use the PSON serialization format.")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.