repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/aptrpm_spec.rb | spec/unit/provider/package/aptrpm_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:aptrpm) do
let :type do Puppet::Type.type(:package) end
let :pkg do
type.new(:name => 'faff', :provider => :aptrpm, :source => '/tmp/faff.rpm')
end
it { is_expected.to be_versionable }
context "when retrieving ensure" do
before(:each) do
allow(Puppet::Util).to receive(:which).with("rpm").and_return("/bin/rpm")
allow(pkg.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)
end
def rpm_args
['-q', 'faff', '--nosignature', '--nodigest', '--qf', "%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n"]
end
it "should report purged packages" do
expect(pkg.provider).to receive(:rpm).and_raise(Puppet::ExecutionFailure, "couldn't find rpm")
expect(pkg.property(:ensure).retrieve).to eq(:purged)
end
it "should report present packages correctly" do
expect(pkg.provider).to receive(:rpm).and_return("faff-1.2.3-1 0 1.2.3-1 5 i686\n")
expect(pkg.property(:ensure).retrieve).to eq("1.2.3-1-5")
end
end
it "should try and install when asked" do
expect(pkg.provider).to receive(:aptget).with('-q', '-y', 'install', 'faff').and_return(0)
pkg.provider.install
end
it "should try and purge when asked" do
expect(pkg.provider).to receive(:aptget).with('-y', '-q', 'remove', '--purge', 'faff').and_return(0)
pkg.provider.purge
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/package/opkg_spec.rb | spec/unit/provider/package/opkg_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:opkg) do
let(:resource) do
Puppet::Type.type(:package).new(:name => 'package')
end
let(:provider) { described_class.new(resource) }
before do
allow(Puppet::Util).to receive(:which).with("opkg").and_return("/bin/opkg")
allow(provider).to receive(:package_lists).and_return(['.', '..', 'packages'])
end
describe "when installing" do
before do
allow(provider).to receive(:query).and_return({ :ensure => '1.0' })
end
context "when the package list is absent" do
before do
allow(provider).to receive(:package_lists).and_return(['.', '..']) #empty, no package list
end
it "fetches the package list when installing" do
expect(provider).to receive(:opkg).with('update')
expect(provider).to receive(:opkg).with("--force-overwrite", "install", resource[:name])
provider.install
end
end
context "when the package list is present" do
before do
allow(provider).to receive(:package_lists).and_return(['.', '..', 'lists']) # With a pre-downloaded package list
end
it "fetches the package list when installing" do
expect(provider).not_to receive(:opkg).with('update')
expect(provider).to receive(:opkg).with("--force-overwrite", "install", resource[:name])
provider.install
end
end
it "should call opkg install" do
expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/opkg", "--force-overwrite", "install", resource[:name]], {:failonfail => true, :combine => true, :custom_environment => {}})
provider.install
end
context "when :source is specified" do
context "works on valid urls" do
%w{
/some/package/file
http://some.package.in/the/air
ftp://some.package.in/the/air
}.each do |source|
it "should install #{source} directly" do
resource[:source] = source
expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/opkg", "--force-overwrite", "install", resource[:source]], {:failonfail => true, :combine => true, :custom_environment => {}})
provider.install
end
end
end
context "as a file:// URL" do
before do
@package_file = "file:///some/package/file"
@actual_file_path = "/some/package/file"
resource[:source] = @package_file
end
it "should install from the path segment of the URL" do
expect(Puppet::Util::Execution).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new("", 0))
provider.install
end
end
context "with invalid URL for opkg" do
before do
# Emulate the `opkg` command returning a non-zero exit value
allow(Puppet::Util::Execution).to receive(:execute).and_raise(Puppet::ExecutionFailure, 'oops')
end
context "puppet://server/whatever" do
before do
resource[:source] = "puppet://server/whatever"
end
it "should fail" do
expect { provider.install }.to raise_error Puppet::ExecutionFailure
end
end
context "as a malformed URL" do
before do
resource[:source] = "blah://"
end
it "should fail" do
expect { provider.install }.to raise_error Puppet::ExecutionFailure
end
end
end
end # end when source is specified
end # end when installing
describe "when updating" do
it "should call install" do
expect(provider).to receive(:install).and_return("install return value")
expect(provider.update).to eq("install return value")
end
end
describe "when uninstalling" do
it "should run opkg remove bla" do
expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/opkg", "remove", resource[:name]], {:failonfail => true, :combine => true, :custom_environment => {}})
provider.uninstall
end
end
describe "when querying" do
describe "self.instances" do
let (:packages) do
<<-OPKG_OUTPUT
dropbear - 2011.54-2
kernel - 3.3.8-1-ba5cdb2523b4fc7722698b4a7ece6702
uhttpd - 2012-10-30-e57bf6d8bfa465a50eea2c30269acdfe751a46fd
OPKG_OUTPUT
end
it "returns an array of packages" do
allow(Puppet::Util).to receive(:which).with("opkg").and_return("/bin/opkg")
allow(described_class).to receive(:which).with("opkg").and_return("/bin/opkg")
expect(described_class).to receive(:execpipe).with("/bin/opkg list-installed").and_yield(packages)
installed_packages = described_class.instances
expect(installed_packages.length).to eq(3)
expect(installed_packages[0].properties).to eq(
{
:provider => :opkg,
:name => "dropbear",
:ensure => "2011.54-2"
}
)
expect(installed_packages[1].properties).to eq(
{
:provider => :opkg,
:name => "kernel",
:ensure => "3.3.8-1-ba5cdb2523b4fc7722698b4a7ece6702"
}
)
expect(installed_packages[2].properties).to eq(
{
:provider => :opkg,
:name => "uhttpd",
:ensure => "2012-10-30-e57bf6d8bfa465a50eea2c30269acdfe751a46fd"
}
)
end
end
it "should return a nil if the package isn't found" do
expect(Puppet::Util::Execution).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new("", 0))
expect(provider.query).to be_nil
end
it "should return a hash indicating that the package is missing on error" do
expect(Puppet::Util::Execution).to receive(:execute).and_raise(Puppet::ExecutionFailure.new("ERROR!"))
expect(provider.query).to eq({
:ensure => :purged,
:status => 'missing',
:name => resource[:name],
:error => 'ok',
})
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/package/macports_spec.rb | spec/unit/provider/package/macports_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:macports) do
let :resource_name do
"foo"
end
let :resource do
Puppet::Type.type(:package).new(:name => resource_name, :provider => :macports)
end
let :provider do
prov = resource.provider
expect(prov).not_to receive(:execute)
prov
end
let :current_hash do
{:name => resource_name, :ensure => "1.2.3", :revision => "1", :provider => :macports}
end
context "provider features" do
subject { provider }
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_upgradeable }
it { is_expected.to be_versionable }
end
context "when listing all instances" do
it "should call port -q installed" do
expect(described_class).to receive(:port).with("-q", :installed).and_return("")
described_class.instances
end
it "should create instances from active ports" do
expect(described_class).to receive(:port).and_return("foo @1.234.5_2 (active)")
expect(described_class.instances.size).to eq(1)
end
it "should ignore ports that aren't activated" do
expect(described_class).to receive(:port).and_return("foo @1.234.5_2")
expect(described_class.instances.size).to eq(0)
end
it "should ignore variants" do
expect(described_class.parse_installed_query_line("bar @1.0beta2_38_1+x11+java (active)")).
to eq({:provider=>:macports, :revision=>"1", :name=>"bar", :ensure=>"1.0beta2_38"})
end
end
context "when installing" do
it "should not specify a version when ensure is set to latest" do
resource[:ensure] = :latest
# version would be the 4th argument, if provided.
expect(provider).to receive(:port).with(anything, anything, anything)
provider.install
end
it "should not specify a version when ensure is set to present" do
resource[:ensure] = :present
# version would be the 4th argument, if provided.
expect(provider).to receive(:port).with(anything, anything, anything)
provider.install
end
it "should specify a version when ensure is set to a version" do
resource[:ensure] = "1.2.3"
expect(provider).to receive(:port).with(anything, anything, anything, '@1.2.3')
provider.install
end
end
context "when querying for the latest version" do
# Redefine provider to avoid the "expect(prov).not_to receive(:execute)"
# that was set in the original definition.
let(:provider) { resource.provider }
let(:new_info_line) do
"1.2.3 2"
end
let(:infoargs) do
["/opt/local/bin/port", "-q", :info, "--line", "--version", "--revision", resource_name]
end
let(:arguments) do
{:failonfail => false, :combine => false}
end
before :each do
allow(provider).to receive(:command).with(:port).and_return("/opt/local/bin/port")
end
it "should return nil when the package cannot be found" do
resource[:name] = resource_name
expect(provider).to receive(:execute).with(infoargs, arguments).and_return("")
expect(provider.latest).to eq(nil)
end
it "should return the current version if the installed port has the same revision" do
current_hash[:revision] = "2"
expect(provider).to receive(:execute).with(infoargs, arguments).and_return(new_info_line)
expect(provider).to receive(:query).and_return(current_hash)
expect(provider.latest).to eq(current_hash[:ensure])
end
it "should return the new version_revision if the installed port has a lower revision" do
current_hash[:revision] = "1"
expect(provider).to receive(:execute).with(infoargs, arguments).and_return(new_info_line)
expect(provider).to receive(:query).and_return(current_hash)
expect(provider.latest).to eq("1.2.3_2")
end
it "should return the newest version if the port is not installed" do
resource[:name] = resource_name
expect(provider).to receive(:execute).with(infoargs, arguments).and_return(new_info_line)
expect(provider).to receive(:execute).with(["/opt/local/bin/port", "-q", :installed, resource[:name]], arguments).and_return("")
expect(provider.latest).to eq("1.2.3_2")
end
end
context "when updating a port" do
it "should execute port install if the port is installed" do
resource[:name] = resource_name
resource[:ensure] = :present
allow(provider).to receive(:query).and_return(current_hash)
expect(provider).to receive(:port).with("-q", :install, resource_name)
provider.update
end
it "should execute port install if the port is not installed" do
resource[:name] = resource_name
resource[:ensure] = :present
allow(provider).to receive(:query).and_return("")
expect(provider).to receive(:port).with("-q", :install, resource_name)
provider.update
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/package/hpux_spec.rb | spec/unit/provider/package/hpux_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:hpux) do
before(:each) do
# Create a mock resource
@resource = double('resource')
# A catch all; no parameters set
allow(@resource).to receive(:[]).and_return(nil)
# But set name and source
allow(@resource).to receive(:[]).with(:name).and_return("mypackage")
allow(@resource).to receive(:[]).with(:source).and_return("mysource")
allow(@resource).to receive(:[]).with(:ensure).and_return(:installed)
@provider = subject()
allow(@provider).to receive(:resource).and_return(@resource)
end
it "should have an install method" do
@provider = subject()
expect(@provider).to respond_to(:install)
end
it "should have an uninstall method" do
@provider = subject()
expect(@provider).to respond_to(:uninstall)
end
it "should have a swlist method" do
@provider = subject()
expect(@provider).to respond_to(:swlist)
end
context "when installing" do
it "should use a command-line like 'swinstall -x mount_all_filesystems=false -s SOURCE PACKAGE-NAME'" do
expect(@provider).to receive(:swinstall).with('-x', 'mount_all_filesystems=false', '-s', 'mysource', 'mypackage')
@provider.install
end
end
context "when uninstalling" do
it "should use a command-line like 'swremove -x mount_all_filesystems=false PACKAGE-NAME'" do
expect(@provider).to receive(:swremove).with('-x', 'mount_all_filesystems=false', 'mypackage')
@provider.uninstall
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/package/up2date_spec.rb | spec/unit/provider/package/up2date_spec.rb | require 'spec_helper'
describe 'up2date package provider' do
# This sets the class itself as the subject rather than
# an instance of the class.
subject do
Puppet::Type.type(:package).provider(:up2date)
end
osfamilies = [ 'redhat' ]
releases = [ '2.1', '3', '4' ]
osfamilies.each do |osfamily|
releases.each do |release|
it "should be the default provider on #{osfamily} #{release}" do
allow(Facter).to receive(:value).with('os.family').and_return(osfamily)
allow(Facter).to receive(:value).with('os.distro.release.full').and_return(release)
expect(subject.default?).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/provider/package/sun_spec.rb | spec/unit/provider/package/sun_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:sun) do
let(:resource) { Puppet::Type.type(:package).new(:name => 'dummy', :ensure => :installed, :provider => :sun) }
let(:provider) { resource.provider }
describe 'provider features' do
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_upgradeable }
it { is_expected.not_to be_versionable }
end
[:install, :uninstall, :latest, :query, :update].each do |method|
it "should have a #{method} method" do
expect(provider).to respond_to(method)
end
end
context '#install' do
it "should install a package" do
resource[:ensure] = :installed
resource[:source] = '/cdrom'
expect(provider).to receive(:pkgadd).with(['-d', '/cdrom', '-n', 'dummy'])
provider.install
end
it "should install a package if it is not present on update" do
expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_return(File.read(my_fixture('dummy.server')))
expect(provider).to receive(:pkgrm).with(['-n', 'dummy'])
expect(provider).to receive(:install)
provider.update
end
it "should install a package on global zone if -G specified" do
resource[:ensure] = :installed
resource[:source] = '/cdrom'
resource[:install_options] = '-G'
expect(provider).to receive(:pkgadd).with(['-d', '/cdrom', '-G', '-n', 'dummy'])
provider.install
end
end
context '#uninstall' do
it "should uninstall a package" do
expect(provider).to receive(:pkgrm).with(['-n','dummy'])
provider.uninstall
end
end
context '#update' do
it "should call uninstall if not :absent on info2hash" do
allow(provider).to receive(:info2hash).and_return({:name => 'SUNWdummy', :ensure => "11.11.0,REV=2010.10.12.04.23"})
expect(provider).to receive(:uninstall)
expect(provider).to receive(:install)
provider.update
end
it "should not call uninstall if :absent on info2hash" do
allow(provider).to receive(:info2hash).and_return({:name => 'SUNWdummy', :ensure => :absent})
expect(provider).to receive(:install)
provider.update
end
end
context '#query' do
it "should find the package on query" do
expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_return(File.read(my_fixture('dummy.server')))
expect(provider.query).to eq({
:name => 'SUNWdummy',
:category=>"system",
:platform=>"i386",
:ensure => "11.11.0,REV=2010.10.12.04.23",
:root=>"/",
:description=>"Dummy server (9.6.1-P3)",
:vendor => "Oracle Corporation",
})
end
it "shouldn't find the package on query if it is not present" do
expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_raise(Puppet::ExecutionFailure, "Execution of 'pkginfo -l dummy' returned 3: ERROR: information for \"dummy\" not found.")
expect(provider.query).to eq({:ensure => :absent})
end
it "unknown message should raise error." do
expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_return('RANDOM')
expect { provider.query }.to raise_error Puppet::Error
end
end
context '#instance' do
it "should list instances when there are packages in the system" do
expect(described_class).to receive(:pkginfo).with('-l').and_return(File.read(my_fixture('simple')))
instances = provider.class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} }
expect(instances.size).to eq(2)
expect(instances[0]).to eq({
:name => 'SUNWdummy',
:ensure => "11.11.0,REV=2010.10.12.04.23",
})
expect(instances[1]).to eq({
:name => 'SUNWdummyc',
:ensure => "11.11.0,REV=2010.10.12.04.24",
})
end
it "should return empty if there were no packages" do
expect(described_class).to receive(:pkginfo).with('-l').and_return('')
instances = provider.class.instances
expect(instances.size).to eq(0)
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/package/dnf_spec.rb | spec/unit/provider/package/dnf_spec.rb | require 'spec_helper'
# Note that much of the functionality of the dnf provider is already tested with yum provider tests,
# as yum is the parent provider.
describe Puppet::Type.type(:package).provider(:dnf) do
context 'default' do
(19..21).each do |ver|
it "should not be the default provider on fedora#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:fedora)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(described_class).to_not be_default
end
end
(22..26).each do |ver|
it "should be the default provider on fedora#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:fedora)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(described_class).to be_default
end
end
it "should not be the default provider on rhel7" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:redhat)
allow(Facter).to receive(:value).with('os.release.major').and_return("7")
expect(described_class).to_not be_default
end
it "should be the default provider on some random future fedora" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:fedora)
allow(Facter).to receive(:value).with('os.release.major').and_return("8675")
expect(described_class).to be_default
end
it "should be the default provider on rhel8" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:redhat)
allow(Facter).to receive(:value).with('os.release.major').and_return("8")
expect(described_class).to be_default
end
it "should be the default provider on Amazon Linux 2023" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:amazon)
allow(Facter).to receive(:value).with('os.release.major').and_return("2023")
expect(described_class).to be_default
end
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 }
it { is_expected.to be_install_only }
end
it_behaves_like 'RHEL package provider', described_class, 'dnf'
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/package/pkgng_spec.rb | spec/unit/provider/package/pkgng_spec.rb | require 'spec_helper'
require 'puppet/provider/package/pkgng'
describe Puppet::Type.type(:package).provider(:pkgng) do
let(:name) { 'bash' }
let(:installed_name) { 'zsh' }
let(:pkgng) { 'pkgng' }
let(:resource) do
# When bash is not present
Puppet::Type.type(:package).new(:name => name, :provider => pkgng)
end
let(:installed_resource) do
# When zsh is present
Puppet::Type.type(:package).new(:name => installed_name, :provider => pkgng)
end
let(:latest_resource) do
# When curl is installed but not the latest
Puppet::Type.type(:package).new(:name => 'ftp/curl', :provider => pkgng, :ensure => latest)
end
let (:provider) { resource.provider }
let (:installed_provider) { installed_resource.provider }
def run_in_catalog(*resources)
catalog = Puppet::Resource::Catalog.new
catalog.host_config = false
resources.each do |resource|
catalog.add_resource(resource)
end
catalog.apply
end
before do
allow(described_class).to receive(:command).with(:pkg).and_return('/usr/local/sbin/pkg')
info = File.read(my_fixture('pkg.query'))
allow(described_class).to receive(:get_query).and_return(info)
version_list = File.read(my_fixture('pkg.version'))
allow(described_class).to receive(:get_version_list).and_return(version_list)
end
context "#instances" do
it "should return the empty set if no packages are listed" do
allow(described_class).to receive(:get_query).and_return('')
allow(described_class).to receive(:get_version_list).and_return('')
expect(described_class.instances).to be_empty
end
it "should return all packages when invoked" do
expect(described_class.instances.map(&:name).sort).to eq(
%w{ca_root_nss curl nmap pkg gnupg zsh tac_plus}.sort)
end
it "should set latest to current version when no upgrade available" do
nmap = described_class.instances.find {|i| i.properties[:origin] == 'security/nmap' }
expect(nmap.properties[:version]).to eq(nmap.properties[:latest])
end
it "should return an empty array when pkg calls raise an exception" do
allow(described_class).to receive(:get_query).and_raise(Puppet::ExecutionFailure, 'An error occurred.')
expect(described_class.instances).to eq([])
end
describe "version" do
it "should retrieve the correct version of the current package" do
zsh = described_class.instances.find {|i| i.properties[:origin] == 'shells/zsh' }
expect(zsh.properties[:version]).to eq('5.0.2_1')
end
end
end
context "#install" do
it "should call pkg with the specified package version given an origin for package name" do
resource = Puppet::Type.type(:package).new(
:name => 'ftp/curl',
:provider => :pkgng,
:ensure => '7.33.1'
)
expect(resource.provider).to receive(:pkg) do |arg|
expect(arg).to include('curl-7.33.1')
end
resource.provider.install
end
it "should call pkg with the specified package version" do
resource = Puppet::Type.type(:package).new(
:name => 'curl',
:provider => :pkgng,
:ensure => '7.33.1'
)
expect(resource.provider).to receive(:pkg) do |arg|
expect(arg).to include('curl-7.33.1')
end
resource.provider.install
end
it "should call pkg with the specified package repo" do
resource = Puppet::Type.type(:package).new(
:name => 'curl',
:provider => :pkgng,
:source => 'urn:freebsd:repo:FreeBSD'
)
expect(resource.provider).to receive(:pkg) do |arg|
expect(arg).to include('FreeBSD')
end
resource.provider.install
end
it "should call pkg with the specified install options string" do
resource = Puppet::Type.type(:package).new(
:name => 'curl',
:provider => :pkgng,
:install_options => ['--foo', '--bar']
)
expect(resource.provider).to receive(:pkg) do |arg|
expect(arg).to include('--foo', '--bar')
end
resource.provider.install
end
it "should call pkg with the specified install options hash" do
resource = Puppet::Type.type(:package).new(
:name => 'curl',
:provider => :pkgng,
:install_options => ['--foo', { '--bar' => 'baz', '--baz' => 'foo' }]
)
expect(resource.provider).to receive(:pkg) do |arg|
expect(arg).to include('--foo', '--bar=baz', '--baz=foo')
end
resource.provider.install
end
end
context "#prefetch" do
it "should fail gracefully when " do
allow(described_class).to receive(:instances).and_return([])
expect{ described_class.prefetch({}) }.to_not raise_error
end
end
context "#query" do
it "should return the installed version if present" do
pkg_query_zsh = File.read(my_fixture('pkg.query.zsh'))
allow(described_class).to receive(:get_resource_info).with('zsh').and_return(pkg_query_zsh)
described_class.prefetch({installed_name => installed_resource})
expect(installed_provider.query).to be >= {:version=>'5.0.2_1'}
end
it "should return nil if not present" do
allow(described_class).to receive(:get_resource_info).with('bash').and_raise(Puppet::ExecutionFailure, 'An error occurred')
expect(provider.query).to equal(nil)
end
end
describe "latest" do
it "should retrieve the correct version of the latest package" do
described_class.prefetch( { installed_name => installed_resource })
expect(installed_provider.latest).not_to be_nil
end
it "should set latest to newer package version when available" do
instances = described_class.instances
curl = instances.find {|i| i.properties[:origin] == 'ftp/curl' }
expect(curl.properties[:latest]).to eq('7.33.0_2')
end
it "should call update to upgrade the version" do
allow(described_class).to receive(:get_resource_info).with('ftp/curl').and_return('curl 7.61.1 ftp/curl')
resource = Puppet::Type.type(:package).new(
:name => 'ftp/curl',
:provider => pkgng,
:ensure => :latest
)
expect(resource.provider).to receive(:update)
resource.property(:ensure).sync
end
end
describe "get_latest_version" do
it "should rereturn nil when the current package is the latest" do
version_list = File.read(my_fixture('pkg.version'))
allow(described_class).to receive(:get_version_list).and_return(version_list)
nmap_latest_version = described_class.get_latest_version('security/nmap')
expect(nmap_latest_version).to be_nil
end
it "should match the package name exactly" do
version_list = File.read(my_fixture('pkg.version'))
allow(described_class).to receive(:get_version_list).and_return(version_list)
bash_comp_latest_version = described_class.get_latest_version('shells/bash-completion')
expect(bash_comp_latest_version).to eq('2.1_3')
end
it "should return nil when the package is orphaned" do
version_list = File.read(my_fixture('pkg.version'))
allow(described_class).to receive(:get_version_list).and_return(version_list)
orphan_latest_version = described_class.get_latest_version('sysutils/orphan')
expect(orphan_latest_version).to be_nil
end
it "should return nil when the package is broken" do
version_list = File.read(my_fixture('pkg.version'))
allow(described_class).to receive(:get_version_list).and_return(version_list)
broken_latest_version = described_class.get_latest_version('sysutils/broken')
expect(broken_latest_version).to be_nil
end
end
describe "confine" do
context "on FreeBSD" do
it "should be the default provider" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:freebsd)
expect(described_class).to be_default
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/provider/package/pkgin_spec.rb | spec/unit/provider/package/pkgin_spec.rb | require "spec_helper"
describe Puppet::Type.type(:package).provider(:pkgin) do
let(:resource) { Puppet::Type.type(:package).new(:name => "vim", :provider => :pkgin) }
subject { resource.provider }
describe "Puppet provider interface" do
it "can return the list of all packages" do
expect(described_class).to respond_to(:instances)
end
end
describe "#install" do
describe "a package not installed" do
before { resource[:ensure] = :absent }
it "uses pkgin install to install" do
expect(subject).to receive(:pkgin).with("-y", :install, "vim").once()
subject.install
end
end
describe "a package with a fixed version" do
before { resource[:ensure] = '7.2.446' }
it "uses pkgin install to install a fixed version" do
expect(subject).to receive(:pkgin).with("-y", :install, "vim-7.2.446").once()
subject.install
end
end
end
describe "#uninstall" do
it "uses pkgin remove to uninstall" do
expect(subject).to receive(:pkgin).with("-y", :remove, "vim").once()
subject.uninstall
end
end
describe "#instances" do
let(:pkgin_ls_output) do
"zlib-1.2.3;General purpose data compression library\nzziplib-0.13.59;Library for ZIP archive handling\n"
end
before do
allow(described_class).to receive(:pkgin).with(:list).and_return(pkgin_ls_output)
end
it "returns an array of providers for each package" do
instances = described_class.instances
expect(instances.count).to eq 2
instances.each do |instance|
expect(instance).to be_a(described_class)
end
end
it "populates each provider with an installed package" do
zlib_provider, zziplib_provider = described_class.instances
expect(zlib_provider.get(:name)).to eq("zlib")
expect(zlib_provider.get(:ensure)).to eq("1.2.3")
expect(zziplib_provider.get(:name)).to eq("zziplib")
expect(zziplib_provider.get(:ensure)).to eq("0.13.59")
end
end
describe "#latest" do
before do
allow(described_class).to receive(:pkgin).with(:search, "vim").and_return(pkgin_search_output)
end
context "when the package is installed" do
let(:pkgin_search_output) do
"vim-7.2.446;=;Vim editor (vi clone) without GUI\nvim-share-7.2.446;=;Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n"
end
it "returns installed version" do
expect(subject).to receive(:properties).and_return({ :ensure => "7.2.446" })
expect(subject.latest).to eq("7.2.446")
end
end
context "when the package is out of date" do
let(:pkgin_search_output) do
"vim-7.2.447;<;Vim editor (vi clone) without GUI\nvim-share-7.2.447;<;Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n"
end
it "returns the version to be installed" do
expect(subject.latest).to eq("7.2.447")
end
end
context "when the package is ahead of date" do
let(:pkgin_search_output) do
"vim-7.2.446;>;Vim editor (vi clone) without GUI\nvim-share-7.2.446;>;Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n"
end
it "returns current version" do
expect(subject).to receive(:properties).and_return({ :ensure => "7.2.446" })
expect(subject.latest).to eq("7.2.446")
end
end
context "when multiple candidates do exists" do
let(:pkgin_search_output) do
<<-SEARCH
vim-7.1;>;Vim editor (vi clone) without GUI
vim-share-7.1;>;Data files for the vim editor (vi clone)
vim-7.2.446;=;Vim editor (vi clone) without GUI
vim-share-7.2.446;=;Data files for the vim editor (vi clone)
vim-7.3;<;Vim editor (vi clone) without GUI
vim-share-7.3;<;Data files for the vim editor (vi clone)
=: package is installed and up-to-date
<: package is installed but newer version is available
>: installed package has a greater version than available package
SEARCH
end
it "returns the newest available version" do
allow(described_class).to receive(:pkgin).with(:search, "vim").and_return(pkgin_search_output)
expect(subject.latest).to eq("7.3")
end
end
context "when the package cannot be found" do
let(:pkgin_search_output) do
"No results found for is-puppet"
end
it "returns nil" do
expect { subject.latest }.to raise_error(Puppet::Error, "No candidate to be installed")
end
end
end
describe "#parse_pkgin_line" do
context "with an installed package" do
let(:package) { "vim-7.2.446;=;Vim editor (vi clone) without GUI" }
it "extracts the name and status" do
expect(described_class.parse_pkgin_line(package)).to eq({ :name => "vim" ,
:status => "=" ,
:ensure => "7.2.446" })
end
end
context "with an installed package with a hyphen in the name" do
let(:package) { "ruby18-puppet-0.25.5nb1;>;Configuration management framework written in Ruby" }
it "extracts the name and status" do
expect(described_class.parse_pkgin_line(package)).to eq({ :name => "ruby18-puppet",
:status => ">" ,
:ensure => "0.25.5nb1" })
end
end
context "with an installed package with a hyphen in the name and package description" do
let(:package) { "ruby200-facter-2.4.3nb1;=;Cross-platform Ruby library for retrieving facts from OS" }
it "extracts the name and status" do
expect(described_class.parse_pkgin_line(package)).to eq({ :name => "ruby200-facter",
:status => "=" ,
:ensure => "2.4.3nb1" })
end
end
context "with a package not yet installed" do
let(:package) { "vim-7.2.446;Vim editor (vi clone) without GUI" }
it "extracts the name and status" do
expect(described_class.parse_pkgin_line(package)).to eq({ :name => "vim" ,
:status => nil ,
:ensure => "7.2.446" })
end
end
context "with an invalid package" do
let(:package) { "" }
it "returns nil" do
expect(described_class.parse_pkgin_line(package)).to be_nil
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/dpkg_spec.rb | spec/unit/provider/package/dpkg_spec.rb | require 'spec_helper'
require 'stringio'
describe Puppet::Type.type(:package).provider(:dpkg), unless: Puppet::Util::Platform.jruby? do
let(:bash_version) { '4.2-5ubuntu3' }
let(:bash_installed_output) { "install ok installed bash #{bash_version}\n" }
let(:bash_installed_io) { StringIO.new(bash_installed_output) }
let(:vim_installed_output) { "install ok installed vim 2:7.3.547-6ubuntu5\n" }
let(:all_installed_io) { StringIO.new([bash_installed_output, vim_installed_output].join) }
let(:args) { ['-W', '--showformat', %Q{'${Status} ${Package} ${Version}\\n'}] }
let(:args_with_provides) { ['/bin/dpkg-query','-W', '--showformat', %Q{'${Status} ${Package} ${Version} [${Provides}]\\n'}]}
let(:execute_options) do
{:failonfail => true, :combine => true, :custom_environment => {}}
end
let(:resource_name) { 'python' }
let(:resource) { double('resource', :[] => resource_name) }
let(:dpkg_query_result) { 'install ok installed python 2.7.13' }
let(:provider) { described_class.new(resource) }
it "has documentation" do
expect(described_class.doc).to be_instance_of(String)
end
context "when listing all instances" do
let(:execpipe_args) { args.unshift('myquery') }
before do
allow(described_class).to receive(:command).with(:dpkgquery).and_return('myquery')
end
it "creates and return an instance for a single dpkg-query entry" do
expect(Puppet::Util::Execution).to receive(:execpipe).with(execpipe_args).and_yield(bash_installed_io)
installed = double('bash')
expect(described_class).to receive(:new).with({:ensure => "4.2-5ubuntu3", :error => "ok", :desired => "install", :name => "bash", :mark => :none, :status => "installed", :provider => :dpkg}).and_return(installed)
expect(described_class.instances).to eq([installed])
end
it "parses multiple dpkg-query multi-line entries in the output" do
expect(Puppet::Util::Execution).to receive(:execpipe).with(execpipe_args).and_yield(all_installed_io)
bash = double('bash')
expect(described_class).to receive(:new).with({:ensure => "4.2-5ubuntu3", :error => "ok", :desired => "install", :name => "bash", :mark => :none, :status => "installed", :provider => :dpkg}).and_return(bash)
vim = double('vim')
expect(described_class).to receive(:new).with({:ensure => "2:7.3.547-6ubuntu5", :error => "ok", :desired => "install", :name => "vim", :mark => :none, :status => "installed", :provider => :dpkg}).and_return(vim)
expect(described_class.instances).to eq([bash, vim])
end
it "continues without failing if it encounters bad lines between good entries" do
expect(Puppet::Util::Execution).to receive(:execpipe).with(execpipe_args).and_yield(StringIO.new([bash_installed_output, "foobar\n", vim_installed_output].join))
bash = double('bash')
vim = double('vim')
expect(described_class).to receive(:new).twice.and_return(bash, vim)
expect(described_class.instances).to eq([bash, vim])
end
end
context "when querying the current state" do
let(:dpkgquery_path) { '/bin/dpkg-query' }
let(:query_args) do
args.unshift(dpkgquery_path)
args.push(resource_name)
end
def dpkg_query_execution_returns(output)
expect(Puppet::Util::Execution).to receive(:execute).with(query_args, execute_options).and_return(Puppet::Util::Execution::ProcessOutput.new(output, 0))
end
def dpkg_query_execution_with_multiple_args_returns(output, *args)
args.each do |arg|
allow(Puppet::Util::Execution).to receive(:execute).with(arg, execute_options).and_return(Puppet::Util::Execution::ProcessOutput.new(output, 0))
end
end
before do
allow(Puppet::Util).to receive(:which).with('/usr/bin/dpkg-query').and_return(dpkgquery_path)
end
it "considers the package purged if dpkg-query fails" do
allow(resource).to receive(:allow_virtual?).and_return(false)
allow(Puppet::Util::Execution).to receive(:execute).with(query_args, execute_options).and_raise(Puppet::ExecutionFailure.new("eh"))
expect(provider.query[:ensure]).to eq(:purged)
end
context "allow_virtual true" do
before do
allow(resource).to receive(:allow_virtual?).and_return(true)
end
context "virtual_packages" do
let(:query_output) { 'install ok installed python 2.7.13 [python-ctypes, python-email, python-importlib, python-profiler, python-wsgiref, python-gold]' }
let(:virtual_packages_query_args) do
result = args_with_provides.dup
result.push(resource_name)
end
it "considers the package purged if dpkg-query fails" do
allow(Puppet::Util::Execution).to receive(:execute).with(args_with_provides, execute_options).and_raise(Puppet::ExecutionFailure.new("eh"))
expect(provider.query[:ensure]).to eq(:purged)
end
it "returns a hash of the found package status for an installed package" do
dpkg_query_execution_with_multiple_args_returns(query_output, args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result, args, query_args)
expect(provider.query).to eq(:ensure => "2.7.13", :error => "ok", :desired => "install", :name => "python", :mark => :none, :status => "installed", :provider => :dpkg)
end
it "considers the package absent if the dpkg-query result cannot be interpreted" do
dpkg_query_execution_with_multiple_args_returns('some-bad-data',args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns('some-bad-data', args, query_args)
expect(provider.query[:ensure]).to eq(:absent)
end
it "fails if an error is discovered" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("ok","error"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("ok","error"), args, query_args)
expect { provider.query }.to raise_error(Puppet::Error, /Package python, version 2.7.13 is in error state: error/)
end
it "considers the package purged if it is marked 'not-installed" do
not_installed_query = query_output.gsub("installed", "not-installed").delete!('2.7.13')
dpkg_query_execution_with_multiple_args_returns(not_installed_query, args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed", "not-installed").delete!('2.7.13'), args, query_args)
expect(provider.query[:ensure]).to eq(:purged)
end
it "considers the package absent if it is marked 'config-files'" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","config-files"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","config-files"), args, query_args)
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package absent if it is marked 'half-installed'" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","half-installed"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","half-installed"), args, query_args)
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package absent if it is marked 'unpacked'" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","unpacked"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","unpacked"), args, query_args)
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package absent if it is marked 'half-configured'" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","half-configured"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","half-configured"), args, query_args)
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package held if its state is 'hold'" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("install","hold"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("install","hold"), args, query_args)
expect(provider.query[:ensure]).to eq("2.7.13")
expect(provider.query[:mark]).to eq(:hold)
end
it "considers the package held if its state is 'hold'" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("install","hold"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("install","hold"), args, query_args)
expect(provider.query[:ensure]).to eq("2.7.13")
expect(provider.query[:mark]).to eq(:hold)
end
it "considers mark status to be none if package is not held" do
dpkg_query_execution_with_multiple_args_returns(query_output.gsub("install","ok"),args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("install","ok"), args, query_args)
expect(provider.query[:ensure]).to eq("2.7.13")
expect(provider.query[:mark]).to eq(:none)
end
context "regex check for query search" do
let(:resource_name) { 'python-email' }
let(:resource) { instance_double('Puppet::Type::Package') }
before do
allow(resource).to receive(:[]).with(:name).and_return(resource_name)
allow(resource).to receive(:[]=)
end
it "checks if virtual package regex for query is correct and physical package is installed" do
dpkg_query_execution_with_multiple_args_returns(query_output,args_with_provides,virtual_packages_query_args)
dpkg_query_execution_with_multiple_args_returns(dpkg_query_result, args, query_args)
expect(provider.query).to match({:desired => "install", :ensure => "2.7.13", :error => "ok", :name => "python", :mark => :none, :provider => :dpkg, :status => "installed"})
end
context "regex check with no partial matching" do
let(:resource_name) { 'python-em' }
it "checks if virtual package regex for query is correct and regext dosen't make partial matching" do
expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version} [${Provides}]\\n'}).and_return(query_output)
expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version}\\n'}, resource_name).and_return("#{dpkg_query_result} #{resource_name}")
provider.query
end
context "regex check with special characters" do
let(:resource_name) { 'g++' }
it "checks if virtual package regex for query is correct and regext dosen't make partial matching" do
expect(Puppet).to_not receive(:info).with(/is virtual/)
expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version} [${Provides}]\\n'}).and_return(query_output)
expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version}\\n'}, resource_name).and_return("#{dpkg_query_result} #{resource_name}")
provider.query
end
end
end
end
end
end
context "allow_virtual false" do
before do
allow(resource).to receive(:allow_virtual?).and_return(false)
end
it "returns a hash of the found package status for an installed package" do
dpkg_query_execution_returns(bash_installed_output)
expect(provider.query).to eq({:ensure => "4.2-5ubuntu3", :error => "ok", :desired => "install", :name => "bash", :mark => :none, :status => "installed", :provider => :dpkg})
end
it "considers the package absent if the dpkg-query result cannot be interpreted" do
allow(resource).to receive(:allow_virtual?).and_return(false)
dpkg_query_execution_returns('some-bad-data')
expect(provider.query[:ensure]).to eq(:absent)
end
it "fails if an error is discovered" do
dpkg_query_execution_returns(bash_installed_output.gsub("ok","error"))
expect { provider.query }.to raise_error(Puppet::Error)
end
it "considers the package purged if it is marked 'not-installed'" do
not_installed_bash = bash_installed_output.gsub("installed", "not-installed")
not_installed_bash.gsub!(bash_version, "")
dpkg_query_execution_returns(not_installed_bash)
expect(provider.query[:ensure]).to eq(:purged)
end
it "considers the package held if its state is 'hold'" do
dpkg_query_execution_returns(bash_installed_output.gsub("install","hold"))
query=provider.query
expect(query[:ensure]).to eq("4.2-5ubuntu3")
expect(query[:mark]).to eq(:hold)
end
it "considers the package absent if it is marked 'config-files'" do
dpkg_query_execution_returns(bash_installed_output.gsub("installed","config-files"))
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package absent if it is marked 'half-installed'" do
dpkg_query_execution_returns(bash_installed_output.gsub("installed","half-installed"))
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package absent if it is marked 'unpacked'" do
dpkg_query_execution_returns(bash_installed_output.gsub("installed","unpacked"))
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package absent if it is marked 'half-configured'" do
dpkg_query_execution_returns(bash_installed_output.gsub("installed","half-configured"))
expect(provider.query[:ensure]).to eq(:absent)
end
it "considers the package held if its state is 'hold'" do
dpkg_query_execution_returns(bash_installed_output.gsub("install","hold"))
query=provider.query
expect(query[:ensure]).to eq("4.2-5ubuntu3")
expect(query[:mark]).to eq(:hold)
end
context "parsing tests" do
let(:resource_name) { 'name' }
let(:package_hash) do
{
:desired => 'desired',
:error => 'ok',
:status => 'status',
:name => resource_name,
:mark => :none,
:ensure => 'ensure',
:provider => :dpkg,
}
end
let(:package_not_found_hash) do
{:ensure => :purged, :status => 'missing', :name => resource_name, :error => 'ok'}
end
let(:output) {'an unexpected dpkg msg with an exit code of 0'}
def parser_test(dpkg_output_string, gold_hash, number_of_debug_logs = 0)
dpkg_query_execution_returns(dpkg_output_string)
expect(Puppet).not_to receive(:warning)
expect(Puppet).to receive(:debug).exactly(number_of_debug_logs).times
expect(provider.query).to eq(gold_hash)
end
it "parses properly even if optional ensure field is missing" do
no_ensure = 'desired ok status name '
parser_test(no_ensure, package_hash.merge(:ensure => ''))
end
it "provides debug logging of unparsable lines with allow_virtual enabled" do
allow(resource).to receive(:allow_virtual?).and_return(true)
dpkg_query_execution_with_multiple_args_returns(output, args_with_provides, query_args)
expect(Puppet).not_to receive(:warning)
expect(Puppet).to receive(:debug).exactly(1).times
expect(provider.query).to eq(package_not_found_hash.merge(:ensure => :absent))
end
it "provides debug logging of unparsable lines" do
parser_test('an unexpected dpkg msg with an exit code of 0', package_not_found_hash.merge(:ensure => :absent), 1)
end
it "does not log if execution returns with non-zero exit code with allow_virtual enabled" do
allow(resource).to receive(:allow_virtual?).and_return(true)
expect(Puppet::Util::Execution).to receive(:execute).with(args_with_provides, execute_options).and_raise(Puppet::ExecutionFailure.new("failed"))
expect(Puppet).not_to receive(:debug)
expect(provider.query).to eq(package_not_found_hash)
end
it "does not log if execution returns with non-zero exit code" do
expect(Puppet::Util::Execution).to receive(:execute).with(query_args, execute_options).and_raise(Puppet::ExecutionFailure.new("failed"))
expect(Puppet).not_to receive(:debug)
expect(provider.query).to eq(package_not_found_hash)
end
end
end
end
context "when installing" do
before do
allow(resource).to receive(:[]).with(:source).and_return("mypkg")
end
it "fails to install if no source is specified in the resource" do
expect(resource).to receive(:[]).with(:source).and_return(nil)
expect { provider.install }.to raise_error(ArgumentError)
end
it "uses 'dpkg -i' to install the package" do
expect(resource).to receive(:[]).with(:source).and_return("mypackagefile")
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:unhold)
expect(provider).to receive(:dpkg).with(any_args, "-i", "mypackagefile")
provider.install
end
it "keeps old config files if told to do so" do
expect(resource).to receive(:[]).with(:configfiles).and_return(:keep)
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:unhold)
expect(provider).to receive(:dpkg).with("--force-confold", any_args)
provider.install
end
it "replaces old config files if told to do so" do
expect(resource).to receive(:[]).with(:configfiles).and_return(:replace)
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:unhold)
expect(provider).to receive(:dpkg).with("--force-confnew", any_args)
provider.install
end
it "ensures any hold is removed" do
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:unhold).once
expect(provider).to receive(:dpkg)
provider.install
end
end
context "when holding or unholding" do
let(:tempfile) { double('tempfile', :print => nil, :close => nil, :flush => nil, :path => "/other/file") }
before do
allow(tempfile).to receive(:write)
allow(Tempfile).to receive(:open).and_yield(tempfile)
end
it "executes dpkg --set-selections when holding" do
allow(provider).to receive(:install)
expect(provider).to receive(:execute).with([:dpkg, '--set-selections'], {:failonfail => false, :combine => false, :stdinfile => tempfile.path}).once
provider.hold
end
it "executes dpkg --set-selections when unholding" do
allow(provider).to receive(:install)
expect(provider).to receive(:execute).with([:dpkg, '--set-selections'], {:failonfail => false, :combine => false, :stdinfile => tempfile.path}).once
provider.hold
end
end
it "uses :install to update" do
expect(provider).to receive(:install)
provider.update
end
context "when determining latest available version" do
it "returns the version found by dpkg-deb" do
expect(resource).to receive(:[]).with(:source).and_return("python")
expect(provider).to receive(:dpkg_deb).with('--show', "python").and_return("package\t1.0")
expect(provider.latest).to eq("1.0")
end
it "warns if the package file contains a different package" do
expect(provider).to receive(:dpkg_deb).and_return("foo\tversion")
expect(provider).to receive(:warning)
provider.latest
end
it "copes with names containing ++" do
resource = double('resource', :[] => "package++")
provider = described_class.new(resource)
expect(provider).to receive(:dpkg_deb).and_return("package++\t1.0")
expect(provider.latest).to eq("1.0")
end
end
it "uses 'dpkg -r' to uninstall" do
expect(provider).to receive(:dpkg).with("-r", resource_name)
provider.uninstall
end
it "uses 'dpkg --purge' to purge" do
expect(provider).to receive(:dpkg).with("--purge", resource_name)
provider.purge
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/package/appdmg_spec.rb | spec/unit/provider/package/appdmg_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:appdmg) do
let(:resource) { Puppet::Type.type(:package).new(:name => 'foo', :provider => :appdmg) }
let(:provider) { described_class.new(resource) }
describe "when installing an appdmg" do
let(:fake_mountpoint) { "/tmp/dmg.foo" }
let(:fake_hdiutil_plist) { {"system-entities" => [{"mount-point" => fake_mountpoint}]} }
before do
fh = double('filehandle', path: '/tmp/foo')
resource[:source] = "foo.dmg"
allow(File).to receive(:open).and_yield(fh)
allow(Dir).to receive(:mktmpdir).and_return("/tmp/testtmp123")
allow(FileUtils).to receive(:remove_entry_secure)
end
describe "from a remote source" do
let(:tmpdir) { "/tmp/good123" }
before :each do
resource[:source] = "http://fake.puppetlabs.com/foo.dmg"
end
it "should call tmpdir and use the returned directory" do
expect(Dir).to receive(:mktmpdir).and_return(tmpdir)
allow(Dir).to receive(:entries).and_return(["foo.app"])
expect(described_class).to receive(:curl) do |*args|
expect(args[0]).to eq("-o")
expect(args[1]).to include(tmpdir)
expect(args).not_to include("-k")
end
allow(described_class).to receive(:hdiutil).and_return('a plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist)
expect(described_class).to receive(:installapp)
provider.install
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/provider/package/openbsd_spec.rb | spec/unit/provider/package/openbsd_spec.rb | require 'spec_helper'
require 'stringio'
describe Puppet::Type.type(:package).provider(:openbsd) do
let(:package) { Puppet::Type.type(:package).new(:name => 'bash', :provider => 'openbsd') }
let(:provider) { described_class.new(package) }
def expect_read_from_pkgconf(lines)
pkgconf = double(:readlines => lines)
expect(Puppet::FileSystem).to receive(:exist?).with('/etc/pkg.conf').and_return(true)
expect(File).to receive(:open).with('/etc/pkg.conf', 'rb').and_return(pkgconf)
end
def expect_pkgadd_with_source(source)
expect(provider).to receive(:pkgadd).with([source]) do
expect(ENV).not_to have_key('PKG_PATH')
end
end
def expect_pkgadd_with_env_and_name(source, &block)
expect(ENV).not_to have_key('PKG_PATH')
expect(provider).to receive(:pkgadd).with([provider.resource[:name]]) do
expect(ENV).to have_key('PKG_PATH')
expect(ENV['PKG_PATH']).to eq(source)
end
expect(provider).to receive(:execpipe).with(['/bin/pkg_info', '-I', provider.resource[:name]]).and_yield('')
yield
expect(ENV).not_to be_key('PKG_PATH')
end
context 'provider features' do
it { is_expected.to be_installable }
it { is_expected.to be_install_options }
it { is_expected.to be_uninstallable }
it { is_expected.to be_uninstall_options }
it { is_expected.to be_upgradeable }
it { is_expected.to be_versionable }
end
before :each do
# Stub some provider methods to avoid needing the actual software
# installed, so we can test on whatever platform we want.
allow(described_class).to receive(:command).with(:pkginfo).and_return('/bin/pkg_info')
allow(described_class).to receive(:command).with(:pkgadd).and_return('/bin/pkg_add')
allow(described_class).to receive(:command).with(:pkgdelete).and_return('/bin/pkg_delete')
allow(Puppet::FileSystem).to receive(:exist?)
end
context "#instances" do
it "should return nil if execution failed" do
expect(described_class).to receive(:execpipe).and_raise(Puppet::ExecutionFailure, 'wawawa')
expect(described_class.instances).to be_nil
end
it "should return the empty set if no packages are listed" do
expect(described_class).to receive(:execpipe).with(%w{/bin/pkg_info -a}).and_yield(StringIO.new(''))
expect(described_class.instances).to be_empty
end
it "should return all packages when invoked" do
fixture = File.read(my_fixture('pkginfo.list'))
expect(described_class).to receive(:execpipe).with(%w{/bin/pkg_info -a}).and_yield(fixture)
expect(described_class.instances.map(&:name).sort).to eq(
%w{bash bzip2 expat gettext libiconv lzo openvpn python vim wget}.sort
)
end
it "should return all flavors if set" do
fixture = File.read(my_fixture('pkginfo_flavors.list'))
expect(described_class).to receive(:execpipe).with(%w{/bin/pkg_info -a}).and_yield(fixture)
instances = described_class.instances.map {|p| {:name => p.get(:name),
:ensure => p.get(:ensure), :flavor => p.get(:flavor)}}
expect(instances.size).to eq(2)
expect(instances[0]).to eq({:name => 'bash', :ensure => '3.1.17', :flavor => 'static'})
expect(instances[1]).to eq({:name => 'vim', :ensure => '7.0.42', :flavor => 'no_x11'})
end
end
context "#install" do
it "should fail if the resource doesn't have a source" do
expect(Puppet::FileSystem).to receive(:exist?).with('/etc/pkg.conf').and_return(false)
expect {
provider.install
}.to raise_error(Puppet::Error, /must specify a package source/)
end
it "should fail if /etc/pkg.conf exists, but is not readable" do
expect(Puppet::FileSystem).to receive(:exist?).with('/etc/pkg.conf').and_return(true)
expect(File).to receive(:open).with('/etc/pkg.conf', 'rb').and_raise(Errno::EACCES)
expect {
provider.install
}.to raise_error(Errno::EACCES, /Permission denied/)
end
it "should fail if /etc/pkg.conf exists, but there is no installpath" do
expect_read_from_pkgconf([])
expect {
provider.install
}.to raise_error(Puppet::Error, /No valid installpath found in \/etc\/pkg\.conf and no source was set/)
end
it "should install correctly when given a directory-unlike source" do
source = '/whatever.tgz'
provider.resource[:source] = source
expect_pkgadd_with_source(source)
provider.install
end
it "should install correctly when given a directory-like source" do
source = '/whatever/'
provider.resource[:source] = source
expect_pkgadd_with_env_and_name(source) do
provider.install
end
end
it "should install correctly when given a CDROM installpath" do
dir = '/mnt/cdrom/5.2/packages/amd64/'
expect_read_from_pkgconf(["installpath = #{dir}"])
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should install correctly when given a ftp mirror" do
url = 'ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/'
expect_read_from_pkgconf(["installpath = #{url}"])
expect_pkgadd_with_env_and_name(url) do
provider.install
end
end
it "should set the resource's source parameter" do
url = 'ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/'
expect_read_from_pkgconf(["installpath = #{url}"])
expect_pkgadd_with_env_and_name(url) do
provider.install
end
expect(provider.resource[:source]).to eq(url)
end
it "should strip leading whitespace in installpath" do
dir = '/one/'
lines = ["# Notice the extra spaces after the ='s\n",
"installpath = #{dir}\n",
"# And notice how each line ends with a newline\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should not require spaces around the equals" do
dir = '/one/'
lines = ["installpath=#{dir}"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should be case-insensitive" do
dir = '/one/'
lines = ["INSTALLPATH = #{dir}"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should ignore unknown keywords" do
dir = '/one/'
lines = ["foo = bar\n",
"installpath = #{dir}\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(dir) do
provider.install
end
end
it "should preserve trailing spaces" do
dir = '/one/ '
lines = ["installpath = #{dir}"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_source(dir)
provider.install
end
it "should append installpath" do
urls = ["ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/",
"http://another.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/"]
lines = ["installpath = #{urls[0]}\n",
"installpath += #{urls[1]}\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(urls.join(":")) do
provider.install
end
end
it "should handle append on first installpath" do
url = "ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/"
lines = ["installpath += #{url}\n"]
expect_read_from_pkgconf(lines)
expect_pkgadd_with_env_and_name(url) do
provider.install
end
end
%w{ installpath installpath= installpath+=}.each do |line|
it "should reject '#{line}'" do
expect_read_from_pkgconf([line])
expect {
provider.install
}.to raise_error(Puppet::Error, /No valid installpath found in \/etc\/pkg\.conf and no source was set/)
end
end
it 'should use install_options as Array' do
provider.resource[:source] = '/tma1/'
provider.resource[:install_options] = ['-r', '-z']
expect(provider).to receive(:pkgadd).with(['-r', '-z', 'bash'])
provider.install
end
end
context "#latest" do
before do
provider.resource[:source] = '/tmp/tcsh.tgz'
provider.resource[:name] = 'tcsh'
allow(provider).to receive(:pkginfo).with('tcsh')
end
it "should return the ensure value if the package is already installed" do
allow(provider).to receive(:properties).and_return({:ensure => '4.2.45'})
allow(provider).to receive(:pkginfo).with('-Q', 'tcsh')
expect(provider.latest).to eq('4.2.45')
end
it "should recognize a new version" do
pkginfo_query = 'tcsh-6.18.01p1'
allow(provider).to receive(:pkginfo).with('-Q', 'tcsh').and_return(pkginfo_query)
expect(provider.latest).to eq('6.18.01p1')
end
it "should recognize a newer version" do
allow(provider).to receive(:properties).and_return({:ensure => '1.6.8'})
pkginfo_query = 'tcsh-1.6.10'
allow(provider).to receive(:pkginfo).with('-Q', 'tcsh').and_return(pkginfo_query)
expect(provider.latest).to eq('1.6.10')
end
it "should recognize a package that is already the newest" do
pkginfo_query = 'tcsh-6.18.01p0 (installed)'
allow(provider).to receive(:pkginfo).with('-Q', 'tcsh').and_return(pkginfo_query)
expect(provider.latest).to eq('6.18.01p0')
end
end
context "#get_full_name" do
it "should return the full unversioned package name when updating with a flavor" do
provider.resource[:ensure] = 'latest'
provider.resource[:flavor] = 'static'
expect(provider.get_full_name).to eq('bash--static')
end
it "should return the full unversioned package name when updating without a flavor" do
provider.resource[:name] = 'puppet'
provider.resource[:ensure] = 'latest'
expect(provider.get_full_name).to eq('puppet')
end
it "should use the ensure parameter if it is numeric" do
provider.resource[:name] = 'zsh'
provider.resource[:ensure] = '1.0'
expect(provider.get_full_name).to eq('zsh-1.0')
end
it "should lookup the correct version" do
output = 'bash-3.1.17 GNU Bourne Again Shell'
expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I bash}).and_yield(output)
expect(provider.get_full_name).to eq('bash-3.1.17')
end
it "should lookup the correction version with flavors" do
provider.resource[:name] = 'fossil'
provider.resource[:flavor] = 'static'
output = 'fossil-1.29v0-static simple distributed software configuration management'
expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I fossil}).and_yield(output)
expect(provider.get_full_name).to eq('fossil-1.29v0-static')
end
end
context "#get_version" do
it "should return nil if execution fails" do
expect(provider).to receive(:execpipe).and_raise(Puppet::ExecutionFailure, 'wawawa')
expect(provider.get_version).to be_nil
end
it "should return the package version if in the output" do
output = 'bash-3.1.17 GNU Bourne Again Shell'
expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I bash}).and_yield(output)
expect(provider.get_version).to eq('3.1.17')
end
it "should return the empty string if the package is not present" do
provider.resource[:name] = 'zsh'
expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I zsh}).and_yield(StringIO.new(''))
expect(provider.get_version).to eq('')
end
end
context "#query" do
it "should return the installed version if present" do
fixture = File.read(my_fixture('pkginfo.detail'))
expect(provider).to receive(:pkginfo).with('bash').and_return(fixture)
expect(provider.query).to eq({ :ensure => '3.1.17' })
end
it "should return nothing if not present" do
provider.resource[:name] = 'zsh'
expect(provider).to receive(:pkginfo).with('zsh').and_return('')
expect(provider.query).to be_nil
end
end
context "#install_options" do
it "should return nill by default" do
expect(provider.install_options).to be_nil
end
it "should return install_options when set" do
provider.resource[:install_options] = ['-n']
expect(provider.resource[:install_options]).to eq(['-n'])
end
it "should return multiple install_options when set" do
provider.resource[:install_options] = ['-L', '/opt/puppet']
expect(provider.resource[:install_options]).to eq(['-L', '/opt/puppet'])
end
it 'should return install_options when set as hash' do
provider.resource[:install_options] = { '-Darch' => 'vax' }
expect(provider.install_options).to eq(['-Darch=vax'])
end
end
context "#uninstall_options" do
it "should return nill by default" do
expect(provider.uninstall_options).to be_nil
end
it "should return uninstall_options when set" do
provider.resource[:uninstall_options] = ['-n']
expect(provider.resource[:uninstall_options]).to eq(['-n'])
end
it "should return multiple uninstall_options when set" do
provider.resource[:uninstall_options] = ['-q', '-c']
expect(provider.resource[:uninstall_options]).to eq(['-q', '-c'])
end
it 'should return uninstall_options when set as hash' do
provider.resource[:uninstall_options] = { '-Dbaddepend' => '1' }
expect(provider.uninstall_options).to eq(['-Dbaddepend=1'])
end
end
context "#uninstall" do
describe 'when uninstalling' do
it 'should use erase to purge' do
expect(provider).to receive(:pkgdelete).with('-c', '-q', 'bash')
provider.purge
end
end
describe 'with uninstall_options' do
it 'should use uninstall_options as Array' do
provider.resource[:uninstall_options] = ['-q', '-c']
expect(provider).to receive(:pkgdelete).with(['-q', '-c'], 'bash')
provider.uninstall
end
end
end
context "#flavor" do
before do
provider.instance_variable_get('@property_hash')[:flavor] = 'no_x11-python'
end
it 'should return the existing flavor' do
expect(provider.flavor).to eq('no_x11-python')
end
it 'should remove and install the new flavor if different' do
provider.resource[:flavor] = 'no_x11-ruby'
expect(provider).to receive(:uninstall).ordered
expect(provider).to receive(:install).ordered
provider.flavor = provider.resource[:flavor]
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/package/aix_spec.rb | spec/unit/provider/package/aix_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:aix) do
before(:each) do
# Create a mock resource
@resource = Puppet::Type.type(:package).new(:name => 'mypackage', :ensure => :installed, :source => 'mysource', :provider => :aix)
@provider = @resource.provider
end
[:install, :uninstall, :latest, :query, :update].each do |method|
it "should have a #{method} method" do
expect(@provider).to respond_to(method)
end
end
it "should uninstall a package" do
expect(@provider).to receive(:installp).with('-gu', 'mypackage')
expect(@provider.class).to receive(:pkglist).with({:pkgname => 'mypackage'}).and_return(nil)
@provider.uninstall
end
context "when installing" do
it "should install a package" do
allow(@provider).to receive(:query).and_return({:name => 'mypackage', :ensure => 'present', :status => :committed})
expect(@provider).to receive(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage')
@provider.install
end
it "should install a specific package version" do
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.4")
allow(@provider).to receive(:query).and_return({:name => 'mypackage', :ensure => '1.2.3.4', :status => :committed})
expect(@provider).to receive(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage 1.2.3.4')
@provider.install
end
[:broken, :inconsistent].each do |state|
it "should fail if the installation resulted in a '#{state}' state" do
allow(@provider).to receive(:query).and_return({:name => 'mypackage', :ensure => 'present', :status => state})
expect(@provider).to receive(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage')
expect { @provider.install }.to raise_error(Puppet::Error, "Package 'mypackage' is in a #{state} state and requires manual intervention")
end
end
it "should fail if the specified version is superseded" do
@resource[:ensure] = '1.2.3.3'
allow(@provider).to receive(:installp).and_return(<<-OUTPUT)
+-----------------------------------------------------------------------------+
Pre-installation Verification...
+-----------------------------------------------------------------------------+
Verifying selections...done
Verifying requisites...done
Results...
WARNINGS
--------
Problems described in this section are not likely to be the source of any
immediate or serious failures, but further actions may be necessary or
desired.
Already Installed
-----------------
The number of selected filesets that are either already installed
or effectively installed through superseding filesets is 1. See
the summaries at the end of this installation for details.
NOTE: Base level filesets may be reinstalled using the "Force"
option (-F flag), or they may be removed, using the deinstall or
"Remove Software Products" facility (-u flag), and then reinstalled.
<< End of Warning Section >>
+-----------------------------------------------------------------------------+
BUILDDATE Verification ...
+-----------------------------------------------------------------------------+
Verifying build dates...done
FILESET STATISTICS
------------------
1 Selected to be installed, of which:
1 Already installed (directly or via superseding filesets)
----
0 Total to be installed
Pre-installation Failure/Warning Summary
----------------------------------------
Name Level Pre-installation Failure/Warning
-------------------------------------------------------------------------------
mypackage 1.2.3.3 Already superseded by 1.2.3.4
OUTPUT
expect { @provider.install }.to raise_error(Puppet::Error, "aix package provider is unable to downgrade packages")
end
end
context "when finding the latest version" do
it "should return the current version when no later version is present" do
allow(@provider).to receive(:latest_info).and_return(nil)
allow(@provider).to receive(:properties).and_return({ :ensure => "1.2.3.4" })
expect(@provider.latest).to eq("1.2.3.4")
end
it "should return the latest version of a package" do
allow(@provider).to receive(:latest_info).and_return({ :version => "1.2.3.5" })
expect(@provider.latest).to eq("1.2.3.5")
end
it "should prefetch the right values" do
allow(Process).to receive(:euid).and_return(0)
resource = Puppet::Type.type(:package).
new(:name => 'sudo.rte', :ensure => :latest,
:source => 'mysource', :provider => :aix)
allow(resource).to receive(:should).with(:ensure).and_return(:latest)
resource.should(:ensure)
allow(resource.provider.class).to receive(:execute).and_return(<<-END.chomp)
sudo:sudo.rte:1.7.10.4::I:C:::::N:Configurable super-user privileges runtime::::0::
sudo:sudo.rte:1.8.6.4::I:T:::::N:Configurable super-user privileges runtime::::0::
END
resource.provider.class.prefetch('sudo.rte' => resource)
expect(resource.provider.latest).to eq('1.8.6.4')
end
end
it "update should install a package" do
expect(@provider).to receive(:install).with(false)
@provider.update
end
it "should prefetch when some packages lack sources" do
latest = Puppet::Type.type(:package).new(:name => 'mypackage', :ensure => :latest, :source => 'mysource', :provider => :aix)
absent = Puppet::Type.type(:package).new(:name => 'otherpackage', :ensure => :absent, :provider => :aix)
allow(Process).to receive(:euid).and_return(0)
expect(described_class).to receive(:execute).and_return('mypackage:mypackage.rte:1.8.6.4::I:T:::::N:A Super Cool Package::::0::\n')
described_class.prefetch({ 'mypackage' => latest, 'otherpackage' => absent })
end
context "when querying instances" do
before(:each) do
allow(described_class).to receive(:execute).and_return(<<-END.chomp)
sysmgt.cim.providers:sysmgt.cim.providers.metrics:2.12.1.1: : :B: :Metrics Providers for AIX OS: : : : : : :1:0:/:
sysmgt.cim.providers:sysmgt.cim.providers.osbase:2.12.1.1: : :C: :Base Providers for AIX OS: : : : : : :1:0:/:
openssl.base:openssl.base:1.0.2.1800: : :?: :Open Secure Socket Layer: : : : : : :0:0:/:
END
end
it "should treat installed packages in broken and inconsistent state as absent" do
installed_packages = described_class.instances.map { |package| package.properties }
expected_packages = [{:name => 'sysmgt.cim.providers.metrics', :ensure => :absent, :status => :broken, :provider => :aix},
{:name => 'sysmgt.cim.providers.osbase', :ensure => '2.12.1.1', :status => :committed, :provider => :aix},
{:name => 'openssl.base', :ensure => :absent, :status => :inconsistent, :provider => :aix}]
expect(installed_packages).to eql(expected_packages)
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/package/freebsd_spec.rb | spec/unit/provider/package/freebsd_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:freebsd) do
before :each do
# Create a mock resource
@resource = double('resource')
# A catch all; no parameters set
allow(@resource).to receive(:[]).and_return(nil)
# But set name and source
allow(@resource).to receive(:[]).with(:name).and_return("mypackage")
allow(@resource).to receive(:[]).with(:ensure).and_return(:installed)
@provider = subject()
@provider.resource = @resource
end
it "should have an install method" do
@provider = subject()
expect(@provider).to respond_to(:install)
end
context "when installing" do
before :each do
allow(@resource).to receive(:should).with(:ensure).and_return(:installed)
end
it "should install a package from a path to a directory" do
# For better or worse, trailing '/' is needed. --daniel 2011-01-26
path = '/path/to/directory/'
allow(@resource).to receive(:[]).with(:source).and_return(path)
expect(Puppet::Util).to receive(:withenv).once.with({:PKG_PATH => path}).and_yield
expect(@provider).to receive(:pkgadd).once.with("mypackage")
expect { @provider.install }.to_not raise_error
end
%w{http https ftp}.each do |protocol|
it "should install a package via #{protocol}" do
# For better or worse, trailing '/' is needed. --daniel 2011-01-26
path = "#{protocol}://localhost/"
allow(@resource).to receive(:[]).with(:source).and_return(path)
expect(Puppet::Util).to receive(:withenv).once.with({:PACKAGESITE => path}).and_yield
expect(@provider).to receive(:pkgadd).once.with('-r', "mypackage")
expect { @provider.install }.to_not raise_error
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/rpm_spec.rb | spec/unit/provider/package/rpm_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:rpm) do
let (:packages) do
<<-RPM_OUTPUT
'cracklib-dicts 0 2.8.9 3.3 x86_64
basesystem 0 8.0 5.1.1.el5.centos noarch
chkconfig 0 1.3.30.2 2.el5 x86_64
myresource 0 1.2.3.4 5.el4 noarch
mysummaryless 0 1.2.3.4 5.el4 noarch
tomcat 1 1.2.3.4 5.el4 x86_64
kernel 1 1.2.3.4 5.el4 x86_64
kernel 1 1.2.3.6 5.el4 x86_64
'
RPM_OUTPUT
end
let(:resource_name) { 'myresource' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :installed,
:provider => 'rpm'
)
end
let(:provider) do
provider = subject()
provider.resource = resource
provider
end
let(:nevra_format) { %Q{%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n} }
let(:execute_options) do
{:failonfail => true, :combine => true, :custom_environment => {}}
end
let(:rpm_version) { "RPM version 5.0.0\n" }
before(:each) do
allow(Puppet::Util).to receive(:which).with("rpm").and_return("/bin/rpm")
allow(described_class).to receive(:which).with("rpm").and_return("/bin/rpm")
described_class.instance_variable_set("@current_version", nil)
expect(Puppet::Type::Package::ProviderRpm).to receive(:execute)
.with(["/bin/rpm", "--version"])
.and_return(rpm_version).at_most(:once)
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "--version"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new(rpm_version, 0)).at_most(:once)
end
describe 'provider features' do
it { is_expected.to be_versionable }
it { is_expected.to be_install_options }
it { is_expected.to be_uninstall_options }
it { is_expected.to be_virtual_packages }
end
describe "self.instances" do
describe "with a modern version of RPM" do
it "includes all the modern flags" do
expect(Puppet::Util::Execution).to receive(:execpipe)
.with("/bin/rpm -qa --nosignature --nodigest --qf '#{nevra_format}' | sort")
.and_yield(packages)
described_class.instances
end
end
describe "with a version of RPM < 4.1" do
let(:rpm_version) { "RPM version 4.0.2\n" }
it "excludes the --nosignature flag" do
expect(Puppet::Util::Execution).to receive(:execpipe)
.with("/bin/rpm -qa --nodigest --qf '#{nevra_format}' | sort")
.and_yield(packages)
described_class.instances
end
end
describe "with a version of RPM < 4.0.2" do
let(:rpm_version) { "RPM version 3.0.5\n" }
it "excludes the --nodigest flag" do
expect(Puppet::Util::Execution).to receive(:execpipe)
.with("/bin/rpm -qa --qf '#{nevra_format}' | sort")
.and_yield(packages)
described_class.instances
end
end
it "returns an array of packages" do
expect(Puppet::Util::Execution).to receive(:execpipe)
.with("/bin/rpm -qa --nosignature --nodigest --qf '#{nevra_format}' | sort")
.and_yield(packages)
installed_packages = described_class.instances
expect(installed_packages[0].properties).to eq(
{
:provider => :rpm,
:name => "cracklib-dicts",
:epoch => "0",
:version => "2.8.9",
:release => "3.3",
:arch => "x86_64",
:ensure => "2.8.9-3.3",
}
)
expect(installed_packages[1].properties).to eq(
{
:provider => :rpm,
:name => "basesystem",
:epoch => "0",
:version => "8.0",
:release => "5.1.1.el5.centos",
:arch => "noarch",
:ensure => "8.0-5.1.1.el5.centos",
}
)
expect(installed_packages[2].properties).to eq(
{
:provider => :rpm,
:name => "chkconfig",
:epoch => "0",
:version => "1.3.30.2",
:release => "2.el5",
:arch => "x86_64",
:ensure => "1.3.30.2-2.el5",
}
)
expect(installed_packages[3].properties).to eq(
{
:provider => :rpm,
:name => "myresource",
:epoch => "0",
:version => "1.2.3.4",
:release => "5.el4",
:arch => "noarch",
:ensure => "1.2.3.4-5.el4",
}
)
expect(installed_packages[4].properties).to eq(
{
:provider => :rpm,
:name => "mysummaryless",
:epoch => "0",
:version => "1.2.3.4",
:release => "5.el4",
:arch => "noarch",
:ensure => "1.2.3.4-5.el4",
}
)
expect(installed_packages[5].properties).to eq(
{
:provider => :rpm,
:name => "tomcat",
:epoch => "1",
:version => "1.2.3.4",
:release => "5.el4",
:arch => "x86_64",
:ensure => "1:1.2.3.4-5.el4",
}
)
expect(installed_packages[6].properties).to eq(
{
:provider => :rpm,
:name => "kernel",
:epoch => "1",
:version => "1.2.3.4",
:release => "5.el4",
:arch => "x86_64",
:ensure => "1:1.2.3.4-5.el4; 1:1.2.3.6-5.el4",
}
)
end
end
describe "#install" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => 'myresource',
:ensure => :installed,
:source => '/path/to/package'
)
end
describe "when not already installed" do
it "only includes the '-i' flag" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-i"], '/path/to/package'], execute_options)
provider.install
end
end
describe "when installed with options" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :installed,
:provider => 'rpm',
:source => '/path/to/package',
:install_options => ['-D', {'--test' => 'value'}, '-Q']
)
end
it "includes the options" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-i", "-D", "--test=value", "-Q"], '/path/to/package'], execute_options)
provider.install
end
end
describe "when an older version is installed" do
before(:each) do
# Force the provider to think a version of the package is already installed
# This is real hacky. I'm sorry. --jeffweiss 25 Jan 2013
provider.instance_variable_get('@property_hash')[:ensure] = '1.2.3.3'
end
it "includes the '-U --oldpackage' flags" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-U", "--oldpackage"], '/path/to/package'], execute_options)
provider.install
end
end
end
describe "#latest" do
it "retrieves version string after querying rpm for version from source file" do
expect(resource).to receive(:[]).with(:source).and_return('source-string')
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", "--qf", "#{nevra_format}", "-p", "source-string"])
.and_return(Puppet::Util::Execution::ProcessOutput.new("myresource 0 1.2.3.4 5.el4 noarch\n", 0))
expect(provider.latest).to eq("1.2.3.4-5.el4")
end
it "raises an error if the rpm command fails" do
expect(resource).to receive(:[]).with(:source).and_return('source-string')
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", "--qf", "#{nevra_format}", "-p", "source-string"])
.and_raise(Puppet::ExecutionFailure, 'rpm command failed')
expect {
provider.latest
}.to raise_error(Puppet::Error, 'rpm command failed')
end
end
describe "#uninstall" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :installed
)
end
describe "on an ancient RPM" do
let(:rpm_version) { "RPM version 3.0.6\n" }
before(:each) do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", resource_name, '', '', '--qf', "#{nevra_format}"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0))
end
it "excludes the architecture from the package name" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-e"], resource_name], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once)
provider.uninstall
end
end
describe "on a modern RPM" do
let(:rpm_version) { "RPM version 4.10.0\n" }
before(:each) do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", resource_name, '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0))
end
it "excludes the architecture from the package name" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-e"], resource_name], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once)
provider.uninstall
end
end
describe "on a modern RPM when architecture is specified" do
let(:rpm_version) { "RPM version 4.10.0\n" }
let(:resource) do
Puppet::Type.type(:package).new(
:name => "#{resource_name}.noarch",
:ensure => :absent,
)
end
before(:each) do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", "#{resource_name}.noarch", '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0))
end
it "includes the architecture in the package name" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-e"], "#{resource_name}.noarch"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once)
provider.uninstall
end
end
describe "when version and release are specified" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => "#{resource_name}-1.2.3.4-5.el4",
:ensure => :absent,
)
end
before(:each) do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", "#{resource_name}-1.2.3.4-5.el4", '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0))
end
it "includes the version and release in the package name" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-e"], "#{resource_name}-1.2.3.4-5.el4"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once)
provider.uninstall
end
end
describe "when only version is specified" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => "#{resource_name}-1.2.3.4",
:ensure => :absent,
)
end
before(:each) do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", "#{resource_name}-1.2.3.4", '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0))
end
it "includes the version in the package name" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-e"], "#{resource_name}-1.2.3.4"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once)
provider.uninstall
end
end
describe "when uninstalled with options" do
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :absent,
:provider => 'rpm',
:uninstall_options => ['--nodeps']
)
end
before(:each) do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", resource_name, '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0))
end
it "includes the options" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", ["-e", "--nodeps"], resource_name], execute_options)
provider.uninstall
end
end
end
describe "parsing" do
def parser_test(rpm_output_string, gold_hash, number_of_debug_logs = 0)
expect(Puppet).to receive(:debug).exactly(number_of_debug_logs).times()
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", "#{nevra_format}"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new(rpm_output_string, 0))
expect(provider.query).to eq(gold_hash)
end
let(:resource_name) { 'name' }
let('delimiter') { ':DESC:' }
let(:package_hash) do
{
:name => 'name',
:epoch => 'epoch',
:version => 'version',
:release => 'release',
:arch => 'arch',
:provider => :rpm,
:ensure => 'epoch:version-release',
}
end
let(:line) { 'name epoch version release arch' }
['name', 'epoch', 'version', 'release', 'arch'].each do |field|
it "still parses if #{field} is replaced by delimiter" do
parser_test(
line.gsub(field, delimiter),
package_hash.merge(
field.to_sym => delimiter,
:ensure => 'epoch:version-release'.gsub(field, delimiter)
)
)
end
end
it "does not fail if line is unparseable, but issues a debug log" do
parser_test('bad data', {}, 1)
end
describe "when the package is not found" do
before do
expect(Puppet).not_to receive(:debug)
expected_args = ["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", "#{nevra_format}"]
expect(Puppet::Util::Execution).to receive(:execute)
.with(expected_args, execute_options)
.and_raise(Puppet::ExecutionFailure.new("package #{resource_name} is not installed"))
end
it "does not log or fail if allow_virtual is false" do
resource[:allow_virtual] = false
expect(provider.query).to be_nil
end
it "does not log or fail if allow_virtual is true" do
resource[:allow_virtual] = true
expected_args = ['/bin/rpm', '-q', resource_name, '--nosignature', '--nodigest', '--qf', "#{nevra_format}", '--whatprovides']
expect(Puppet::Util::Execution).to receive(:execute)
.with(expected_args, execute_options)
.and_raise(Puppet::ExecutionFailure.new("package #{resource_name} is not provided"))
expect(provider.query).to be_nil
end
end
it "parses virtual package" do
provider.resource[:allow_virtual] = true
expected_args = ["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", "#{nevra_format}"]
expect(Puppet::Util::Execution).to receive(:execute)
.with(expected_args, execute_options)
.and_raise(Puppet::ExecutionFailure.new("package #{resource_name} is not installed"))
expect(Puppet::Util::Execution).to receive(:execute)
.with(expected_args + ["--whatprovides"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new("myresource 0 1.2.3.4 5.el4 noarch\n", 0))
expect(provider.query).to eq({
:name => "myresource",
:epoch => "0",
:version => "1.2.3.4",
:release => "5.el4",
:arch => "noarch",
:provider => :rpm,
:ensure => "1.2.3.4-5.el4"
})
end
end
describe "#install_options" do
it "returns nil by default" do
expect(provider.install_options).to eq(nil)
end
it "returns install_options when set" do
provider.resource[:install_options] = ['-n']
expect(provider.install_options).to eq(['-n'])
end
it "returns multiple install_options when set" do
provider.resource[:install_options] = ['-L', '/opt/puppet']
expect(provider.install_options).to eq(['-L', '/opt/puppet'])
end
it 'returns install_options when set as hash' do
provider.resource[:install_options] = [{ '-Darch' => 'vax' }]
expect(provider.install_options).to eq(['-Darch=vax'])
end
it 'returns install_options when an array with hashes' do
provider.resource[:install_options] = [ '-L', { '-Darch' => 'vax' }]
expect(provider.install_options).to eq(['-L', '-Darch=vax'])
end
end
describe "#uninstall_options" do
it "returns nil by default" do
expect(provider.uninstall_options).to eq(nil)
end
it "returns uninstall_options when set" do
provider.resource[:uninstall_options] = ['-n']
expect(provider.uninstall_options).to eq(['-n'])
end
it "returns multiple uninstall_options when set" do
provider.resource[:uninstall_options] = ['-L', '/opt/puppet']
expect(provider.uninstall_options).to eq(['-L', '/opt/puppet'])
end
it 'returns uninstall_options when set as hash' do
provider.resource[:uninstall_options] = [{ '-Darch' => 'vax' }]
expect(provider.uninstall_options).to eq(['-Darch=vax'])
end
it 'returns uninstall_options when an array with hashes' do
provider.resource[:uninstall_options] = [ '-L', { '-Darch' => 'vax' }]
expect(provider.uninstall_options).to eq(['-L', '-Darch=vax'])
end
end
describe ".nodigest" do
{ '4.0' => nil,
'4.0.1' => nil,
'4.0.2' => '--nodigest',
'4.0.3' => '--nodigest',
'4.1' => '--nodigest',
'5' => '--nodigest',
}.each do |version, expected|
describe "when current version is #{version}" do
it "returns #{expected.inspect}" do
allow(described_class).to receive(:current_version).and_return(version)
expect(described_class.nodigest).to eq(expected)
end
end
end
end
describe ".nosignature" do
{ '4.0.3' => nil,
'4.1' => '--nosignature',
'4.1.1' => '--nosignature',
'4.2' => '--nosignature',
'5' => '--nosignature',
}.each do |version, expected|
describe "when current version is #{version}" do
it "returns #{expected.inspect}" do
allow(described_class).to receive(:current_version).and_return(version)
expect(described_class.nosignature).to eq(expected)
end
end
end
end
describe 'insync?' do
context 'for multiple versions' do
let(:is) { '1:1.2.3.4-5.el4; 1:5.6.7.8-5.el4' }
it 'returns true if there is match and feature is enabled' do
resource[:install_only] = true
resource[:ensure] = '1:1.2.3.4-5.el4'
expect(provider).to be_insync(is)
end
it 'returns false if there is match and feature is not enabled' do
resource[:ensure] = '1:1.2.3.4-5.el4'
expect(provider).to_not be_insync(is)
end
it 'returns false if no match and feature is enabled' do
resource[:install_only] = true
resource[:ensure] = '1:1.2.3.6-5.el4'
expect(provider).to_not be_insync(is)
end
it 'returns false if no match and feature is not enabled' do
resource[:ensure] = '1:1.2.3.6-5.el4'
expect(provider).to_not be_insync(is)
end
end
context 'for simple versions' do
let(:is) { '1:1.2.3.4-5.el4' }
it 'returns true if there is match and feature is enabled' do
resource[:install_only] = true
resource[:ensure] = '1:1.2.3.4-5.el4'
expect(provider).to be_insync(is)
end
it 'returns true if there is match and feature is not enabled' do
resource[:ensure] = '1:1.2.3.4-5.el4'
expect(provider).to be_insync(is)
end
it 'returns false if no match and feature is enabled' do
resource[:install_only] = true
resource[:ensure] = '1:1.2.3.6-5.el4'
expect(provider).to_not be_insync(is)
end
it 'returns false if no match and feature is not enabled' do
resource[:ensure] = '1:1.2.3.6-5.el4'
expect(provider).to_not be_insync(is)
end
end
end
describe 'rpm multiversion to hash' do
it 'should return empty hash for empty imput' do
package_hash = described_class.nevra_to_multiversion_hash('')
expect(package_hash).to eq({})
end
it 'should return package hash for one package input' do
package_list = <<-RPM_OUTPUT
kernel-devel 1 1.2.3.4 5.el4 x86_64
RPM_OUTPUT
package_hash = described_class.nevra_to_multiversion_hash(package_list)
expect(package_hash).to eq(
{
:arch => "x86_64",
:ensure => "1:1.2.3.4-5.el4",
:epoch => "1",
:name => "kernel-devel",
:provider => :rpm,
:release => "5.el4",
:version => "1.2.3.4",
}
)
end
it 'should return package hash with versions concatenated in ensure for two package input' do
package_list = <<-RPM_OUTPUT
kernel-devel 1 1.2.3.4 5.el4 x86_64
kernel-devel 1 5.6.7.8 5.el4 x86_64
RPM_OUTPUT
package_hash = described_class.nevra_to_multiversion_hash(package_list)
expect(package_hash).to eq(
{
:arch => "x86_64",
:ensure => "1:1.2.3.4-5.el4; 1:5.6.7.8-5.el4",
:epoch => "1",
:name => "kernel-devel",
:provider => :rpm,
:release => "5.el4",
:version => "1.2.3.4",
}
)
end
it 'should return list of packages for one multiversion and one package input' do
package_list = <<-RPM_OUTPUT
kernel-devel 1 1.2.3.4 5.el4 x86_64
kernel-devel 1 5.6.7.8 5.el4 x86_64
basesystem 0 8.0 5.1.1.el5.centos noarch
RPM_OUTPUT
package_hash = described_class.nevra_to_multiversion_hash(package_list)
expect(package_hash).to eq(
[
{
:arch => "x86_64",
:ensure => "1:1.2.3.4-5.el4; 1:5.6.7.8-5.el4",
:epoch => "1",
:name => "kernel-devel",
:provider => :rpm,
:release => "5.el4",
:version => "1.2.3.4",
},
{
:provider => :rpm,
:name => "basesystem",
:epoch => "0",
:version => "8.0",
:release => "5.1.1.el5.centos",
:arch => "noarch",
:ensure => "8.0-5.1.1.el5.centos",
}
]
)
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/package/pip3_spec.rb | spec/unit/provider/package/pip3_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:pip3) do
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_upgradeable }
it { is_expected.to be_versionable }
it { is_expected.to be_install_options }
it { is_expected.to be_targetable }
it "should inherit most things from pip provider" do
expect(described_class < Puppet::Type.type(:package).provider(:pip))
end
it "should use pip3 command" do
expect(described_class.cmd).to eq(["pip3"])
end
context 'calculated specificity' do
include_context 'provider specificity'
context 'when is not defaultfor' do
subject { described_class.specificity }
it { is_expected.to eql 1 }
end
context 'when is defaultfor' do
let(:os) { Puppet.runtime[:facter].value('os.name') }
subject do
described_class.defaultfor('os.name': os)
described_class.specificity
end
it { is_expected.to be > 100 }
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/package/pip2_spec.rb | spec/unit/provider/package/pip2_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:pip2) do
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_upgradeable }
it { is_expected.to be_versionable }
it { is_expected.to be_install_options }
it { is_expected.to be_targetable }
it "should inherit most things from pip provider" do
expect(described_class < Puppet::Type.type(:package).provider(:pip))
end
it "should use pip2 command" do
expect(described_class.cmd).to eq(["pip2"])
end
context 'calculated specificity' do
include_context 'provider specificity'
context 'when is not defaultfor' do
subject { described_class.specificity }
it { is_expected.to eql 1 }
end
context 'when is defaultfor' do
let(:os) { Puppet.runtime[:facter].value('os.name') }
subject do
described_class.defaultfor('os.name': os)
described_class.specificity
end
it { is_expected.to be > 100 }
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/package/yum_spec.rb | spec/unit/provider/package/yum_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:yum) do
include PuppetSpec::Fixtures
let(:resource_name) { 'myresource' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => resource_name,
:ensure => :installed,
:provider => 'yum'
)
end
let(:provider) { Puppet::Type.type(:package).provider(:yum).new(resource) }
it_behaves_like 'RHEL package provider', described_class, 'yum'
it "should have lower specificity" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:fedora)
allow(Facter).to receive(:value).with('os.release.major').and_return("22")
expect(described_class.specificity).to be < 200
end
describe "should have logical defaults" do
[2, 2018].each do |ver|
it "should be the default provider on Amazon Linux #{ver}" do
allow(Facter).to receive(:value).with('os.name').and_return('amazon')
allow(Facter).to receive(:value).with('os.family').and_return('redhat')
allow(Facter).to receive(:value).with('os.release.major').and_return(ver)
expect(described_class).to be_default
end
end
Array(4..7).each do |ver|
it "should be default for redhat #{ver}" do
allow(Facter).to receive(:value).with('os.name').and_return('redhat')
allow(Facter).to receive(:value).with('os.family').and_return('redhat')
allow(Facter).to receive(:value).with('os.release.major').and_return(ver.to_s)
expect(described_class).to be_default
end
end
it "should not be default for redhat 8" do
allow(Facter).to receive(:value).with('os.name').and_return('redhat')
allow(Facter).to receive(:value).with('os.family').and_return('redhat')
allow(Facter).to receive(:value).with('os.release.major').and_return('8')
expect(described_class).not_to be_default
end
it "should not be default for Ubuntu 16.04" do
allow(Facter).to receive(:value).with('os.name').and_return('ubuntu')
allow(Facter).to receive(:value).with('os.family').and_return('ubuntu')
allow(Facter).to receive(:value).with('os.release.major').and_return('16.04')
expect(described_class).not_to be_default
end
end
describe "when supplied the source param" do
let(:name) { 'baz' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => name,
:provider => 'yum',
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
before { allow(described_class).to receive(:command).with(:cmd).and_return("/usr/bin/yum") }
describe 'provider features' do
it { is_expected.to be_versionable }
it { is_expected.to be_install_options }
it { is_expected.to be_virtual_packages }
it { is_expected.to be_install_only }
end
context "when installing" do
it "should use the supplied source as the explicit path to a package to install" do
resource[:ensure] = :present
resource[:source] = "/foo/bar/baz-1.1.0.rpm"
expect(provider).to receive(:execute) do |arr|
expect(arr[-2..-1]).to eq([:install, "/foo/bar/baz-1.1.0.rpm"])
end
provider.install
end
end
context "when ensuring a specific version" do
it "should use the suppplied source as the explicit path to the package to update" do
# The first query response informs yum provider that package 1.1.0 is
# already installed, and the second that it's been upgraded
expect(provider).to receive(:query).twice.and_return({:ensure => "1.1.0"}, {:ensure => "1.2.0"})
resource[:ensure] = "1.2.0"
resource[:source] = "http://foo.repo.com/baz-1.2.0.rpm"
expect(provider).to receive(:execute) do |arr|
expect(arr[-2..-1]).to eq(['update', "http://foo.repo.com/baz-1.2.0.rpm"])
end
provider.install
end
end
describe 'with install_options' do
it 'can parse disable-repo with array of strings' do
resource[:install_options] = ['--disable-repo=dev*', '--disable-repo=prod*']
expect(provider).to receive(:execute) do | arr|
expect(arr[-3]).to eq(["--disable-repo=dev*", "--disable-repo=prod*"])
end
provider.install
end
it 'can parse disable-repo with array of hashes' do
resource[:install_options] = [{'--disable-repo' => 'dev*'}, {'--disable-repo' => 'prod*'}]
expect(provider).to receive(:execute) do | arr|
expect(arr[-3]).to eq(["--disable-repo=dev*", "--disable-repo=prod*"])
end
provider.install
end
it 'can parse enable-repo with array of strings' do
resource[:install_options] = ['--enable-repo=dev*', '--enable-repo=prod*']
expect(provider).to receive(:execute) do | arr|
expect(arr[-3]).to eq(["--enable-repo=dev*", "--enable-repo=prod*"])
end
provider.install
end
it 'can parse enable-repo with array of hashes' do
resource[:install_options] = [{'--enable-repo' => 'dev*'}, {'--disable-repo' => 'prod*'}]
expect(provider).to receive(:execute) do | arr|
expect(arr[-3]).to eq(["--enable-repo=dev*", "--disable-repo=prod*"])
end
provider.install
end
it 'can parse enable-repo with single hash' do
resource[:install_options] = [{'--enable-repo' => 'dev*','--disable-repo' => 'prod*'}]
expect(provider).to receive(:execute) do | arr|
expect(arr[-3]).to eq(["--disable-repo=prod*", "--enable-repo=dev*"])
end
provider.install
end
it 'can parse enable-repo with empty array' do
resource[:install_options] = []
expect(provider).to receive(:execute) do | arr|
expect(arr[-3]).to eq([])
end
provider.install
end
end
end
context "latest" do
let(:name) { 'baz' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => name,
:provider => 'yum',
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
before {
allow(described_class).to receive(:command).with(:cmd).and_return("/usr/bin/yum")
Puppet[:log_level] = 'debug'
}
it "should print a debug message with the current version if newer package is not available" do
expect(provider).to receive(:query).and_return({:ensure => "1.2.3"})
expect(described_class).to receive(:latest_package_version).and_return(nil)
resource[:ensure] = :present
provider.latest
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Yum didn't find updates, current version (1.2.3) is the latest"))
end
end
context "parsing the output of check-update" do
context "with no multiline entries" do
let(:check_update) { File.read(my_fixture("yum-check-update-simple.txt")) }
let(:output) { described_class.parse_updates(check_update) }
it 'creates an entry for each package keyed on the package name' do
expect(output['curl']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}, {:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}])
expect(output['gawk']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}])
expect(output['dhclient']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}])
expect(output['selinux-policy']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}])
end
it 'creates an entry for each package keyed on the package name and package architecture' do
expect(output['curl.i686']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}])
expect(output['curl.x86_64']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}])
expect(output['gawk.i686']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}])
expect(output['dhclient.i686']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}])
expect(output['selinux-policy.noarch']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}])
expect(output['java-1.8.0-openjdk.x86_64']).to eq([{:name => 'java-1.8.0-openjdk', :epoch => '1', :version => '1.8.0.131', :release => '2.b11.el7_3', :arch => 'x86_64'}])
end
end
context "with multiline entries" do
let(:check_update) { File.read(my_fixture("yum-check-update-multiline.txt")) }
let(:output) { described_class.parse_updates(check_update) }
it "parses multi-line values as a single package tuple" do
expect(output['libpcap']).to eq([{:name => 'libpcap', :epoch => '14', :version => '1.4.0', :release => '1.20130826git2dbcaa1.el6', :arch => 'x86_64'}])
end
end
context "with obsoleted packages" do
let(:check_update) { File.read(my_fixture("yum-check-update-obsoletes.txt")) }
let(:output) { described_class.parse_updates(check_update) }
it "ignores all entries including and after 'Obsoleting Packages'" do
expect(output).not_to include("Obsoleting")
expect(output).not_to include("NetworkManager-bluetooth.x86_64")
expect(output).not_to include("1:1.0.0-14.git20150121.b4ea599c.el7")
end
end
context "with security notifications" do
let(:check_update) { File.read(my_fixture("yum-check-update-security.txt")) }
let(:output) { described_class.parse_updates(check_update) }
it "ignores all entries including and after 'Security'" do
expect(output).not_to include("Security")
end
it "includes updates before 'Security'" do
expect(output).to include("yum-plugin-fastestmirror.noarch")
end
end
context "with broken update notices" do
let(:check_update) { File.read(my_fixture("yum-check-update-broken-notices.txt")) }
let(:output) { described_class.parse_updates(check_update) }
it "ignores all entries including and after 'Update'" do
expect(output).not_to include("Update")
end
it "includes updates before 'Update'" do
expect(output).to include("yum-plugin-fastestmirror.noarch")
end
end
context "with improper package names in output" do
it "raises an exception parsing package name" do
expect {
described_class.update_to_hash('badpackagename', '1')
}.to raise_exception(Exception, /Failed to parse/)
end
end
context "with trailing plugin output" do
let(:check_update) { File.read(my_fixture("yum-check-update-plugin-output.txt")) }
let(:output) { described_class.parse_updates(check_update) }
it "parses correctly formatted entries" do
expect(output['bash']).to eq([{:name => 'bash', :epoch => '0', :version => '4.2.46', :release => '12.el7', :arch => 'x86_64'}])
end
it "ignores all mentions of plugin output" do
expect(output).not_to include("Random plugin")
end
end
context "with subscription manager enabled " do
let(:check_update) { File.read(my_fixture("yum-check-update-subscription-manager.txt")) }
let(:output) { described_class.parse_updates(check_update) }
it "parses correctly formatted entries" do
expect(output['curl.x86_64']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}])
end
end
end
describe 'insync?' do
context 'when version is not a valid RPM version' do
let(:is) { '>===a:123' }
before do
resource[:ensure] = is
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Cannot parse #{is} as a RPM version range")
provider.insync?(is)
end
end
context 'with valid semantic versions' do
let(:is) { '1:1.2.3.4-5.el4' }
it 'returns true if the current version matches the given semantic version' do
resource[:ensure] = is
expect(provider).to be_insync(is)
end
it 'returns false if the current version does not match the given semantic version' do
resource[:ensure] = '999r'
expect(provider).not_to be_insync(is)
end
it 'no debug logs if the current version matches the given semantic version' do
resource[:ensure] = is
expect(Puppet).not_to receive(:debug)
provider.insync?(is)
end
it 'returns true if current version matches the greater or equal semantic version in ensure' do
resource[:ensure] = '<=1:1.2.3.4-5.el4'
expect(provider).to be_insync(is)
end
it 'returns true if current version matches the lesser semantic version in ensure' do
resource[:ensure] = '>1:1.0.0'
expect(provider).to be_insync(is)
end
it 'returns true if current version matches two semantic conditions' do
resource[:ensure] = '>1:1.1.3.4-5.el4 <1:1.3.3.6-5.el4'
expect(provider).to be_insync(is)
end
it 'returns false if current version does not match matches two semantic conditions' do
resource[:ensure] = '<1:1.1.3.4-5.el4 <1:1.3.3.6-5.el4'
expect(provider).not_to be_insync(is)
end
end
end
describe 'install' do
before do
resource[:ensure] = ensure_value
allow(Facter).to receive(:value).with('os.release.major').and_return('7')
allow(described_class).to receive(:command).with(:cmd).and_return('/usr/bin/yum')
allow(provider).to receive(:query).twice.and_return(nil, ensure: '18.3.2')
allow(provider).to receive(:insync?).with('18.3.2').and_return(true)
end
context 'with version range' do
before do
allow(provider).to receive(:available_versions).and_return(available_versions)
end
context 'without epoch' do
let(:ensure_value) { '>18.1 <19' }
let(:available_versions) { ['17.5.2', '18.0', 'a:23', '18.3', '18.3.2', '19.0', '3:18.4'] }
it 'selects best_version' do
expect(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, 'myresource-18.3.2']
)
provider.install
end
context 'when comparing with available packages that do not have epoch' do
let(:ensure_value) { '>18' }
let(:available_versions) { ['18.3.3', '3:18.3.2'] }
it 'treats no epoch as zero' do
expect(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, 'myresource-18.3.2']
)
provider.install
end
end
end
context 'with epoch' do
let(:ensure_value) { '>18.1 <3:19' }
let(:available_versions) { ['3:17.5.2', '3:18.0', 'a:23', '18.3.3', '3:18.3.2', '3:19.0', '19.1'] }
it 'selects best_version and removes epoch' do
expect(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, 'myresource-18.3.2']
)
provider.install
end
end
context 'when no suitable version in range' do
let(:ensure_value) { '>18.1 <19' }
let(:available_versions) { ['3:17.5.2', '3:18.0', 'a:23' '18.3', '3:18.3.2', '3:19.0', '19.1'] }
it 'uses requested version' do
expect(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, "myresource->18.1 <19"]
)
provider.install
end
it 'logs a debug message' do
allow(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, "myresource->18.1 <19"]
)
expect(Puppet).to receive(:debug).with(
"No available version for package myresource is included in range >18.1 <19"
)
provider.install
end
end
end
context 'with fix version' do
let(:ensure_value) { '1:18.12' }
it 'passes the version to yum command' do
expect(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, "myresource-1:18.12"]
)
provider.install
end
end
context 'when upgrading' do
let(:ensure_value) { '>18.1 <19' }
let(:available_versions) { ['17.5.2', '18.0', 'a:23' '18.3', '18.3.2', '19.0', '3:18.4'] }
before do
allow(provider).to receive(:available_versions).and_return(available_versions)
allow(provider).to receive(:query).twice
.and_return({ ensure: '17.0' }, { ensure: '18.3.2' })
end
it 'adds update flag to install command' do
expect(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', 'update', 'myresource-18.3.2']
)
provider.install
end
end
context 'when dowgrading' do
let(:ensure_value) { '>18.1 <19' }
let(:available_versions) { ['17.5.2', '18.0', 'a:23' '18.3', '18.3.2', '19.0', '3:18.4'] }
before do
allow(provider).to receive(:available_versions).and_return(available_versions)
allow(provider).to receive(:query).twice
.and_return({ ensure: '19.0' }, { ensure: '18.3.2' })
end
it 'adds downgrade flag to install command' do
expect(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :downgrade, 'myresource-18.3.2']
)
provider.install
end
end
context 'on failure' do
let(:ensure_value) { '20' }
context 'when execute command fails' do
before do
allow(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, "myresource-20"]
).and_return('No package myresource-20 available.')
end
it 'raises Puppet::Error' do
expect { provider.install }.to \
raise_error(Puppet::Error, 'Could not find package myresource-20')
end
end
context 'when package is not found' do
before do
allow(provider).to receive(:query)
allow(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, "myresource-20"]
)
end
it 'raises Puppet::Error' do
expect { provider.install }.to \
raise_error(Puppet::Error, 'Could not find package myresource')
end
end
context 'when package is not installed' do
before do
allow(provider).to receive(:execute).with(
['/usr/bin/yum', '-y', :install, "myresource-20"]
)
allow(provider).to receive(:insync?).and_return(false)
end
it 'raises Puppet::Error' do
expect { provider.install }.to \
raise_error(Puppet::Error, 'Failed to update to version 20, got version 18.3.2 instead')
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/windows_spec.rb | spec/unit/provider/package/windows_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:windows), :if => Puppet.features.microsoft_windows? do
let(:name) { 'mysql-5.1.58-win-x64' }
let(:source) { 'E:\Rando\Directory\mysql-5.1.58-win-x64.msi' }
let(:resource) { Puppet::Type.type(:package).new(:name => name, :provider => :windows, :source => source) }
let(:provider) { resource.provider }
let(:execute_options) do {:failonfail => false, :combine => true, :suppress_window => true} end
before(:each) do
# make sure we never try to execute anything
@times_execute_called = 0
allow(provider).to receive(:execute) { @times_execute_called += 1}
end
after(:each) do
expect(@times_execute_called).to eq(0)
end
def expect_execute(command, status)
expect(provider).to receive(:execute).with(command, execute_options).and_return(Puppet::Util::Execution::ProcessOutput.new('',status))
end
describe 'provider features' do
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_install_options }
it { is_expected.to be_uninstall_options }
it { is_expected.to be_versionable }
end
describe 'on Windows', :if => Puppet::Util::Platform.windows? do
it 'should be the default provider' do
expect(Puppet::Type.type(:package).defaultprovider).to eq(subject.class)
end
end
context '::instances' do
it 'should return an array of provider instances' do
pkg1 = double('pkg1')
pkg2 = double('pkg2')
prov1 = double('prov1', :name => 'pkg1', :version => '1.0.0', :package => pkg1)
prov2 = double('prov2', :name => 'pkg2', :version => nil, :package => pkg2)
expect(Puppet::Provider::Package::Windows::Package).to receive(:map).and_yield(prov1).and_yield(prov2).and_return([prov1, prov2])
providers = provider.class.instances
expect(providers.count).to eq(2)
expect(providers[0].name).to eq('pkg1')
expect(providers[0].version).to eq('1.0.0')
expect(providers[0].package).to eq(pkg1)
expect(providers[1].name).to eq('pkg2')
expect(providers[1].version).to be_nil
expect(providers[1].package).to eq(pkg2)
end
it 'should return an empty array if none found' do
expect(Puppet::Provider::Package::Windows::Package).to receive(:map).and_return([])
expect(provider.class.instances).to eq([])
end
end
context '#query' do
it 'should return the hash of the matched packaged' do
pkg = double(:name => 'pkg1', :version => nil)
expect(pkg).to receive(:match?).and_return(true)
expect(Puppet::Provider::Package::Windows::Package).to receive(:find).and_yield(pkg)
expect(provider.query).to eq({ :name => 'pkg1', :ensure => :installed, :provider => :windows })
end
it 'should include the version string when present' do
pkg = double(:name => 'pkg1', :version => '1.0.0')
expect(pkg).to receive(:match?).and_return(true)
expect(Puppet::Provider::Package::Windows::Package).to receive(:find).and_yield(pkg)
expect(provider.query).to eq({ :name => 'pkg1', :ensure => '1.0.0', :provider => :windows })
end
it 'should return nil if no package was found' do
expect(Puppet::Provider::Package::Windows::Package).to receive(:find)
expect(provider.query).to be_nil
end
end
context '#install' do
let(:command) { 'blarg.exe /S' }
let(:klass) { double('installer', :install_command => ['blarg.exe', '/S'] ) }
let(:execute_options) do {:failonfail => false, :combine => true, :cwd => nil, :suppress_window => true} end
before :each do
expect(Puppet::Provider::Package::Windows::Package).to receive(:installer_class).and_return(klass)
end
it 'should join the install command and options' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql-5.1' }
expect_execute("#{command} INSTALLDIR=C:\\mysql-5.1", 0)
provider.install
end
it 'should compact nil install options' do
expect_execute(command, 0)
provider.install
end
it 'should not warn if the package install succeeds' do
expect_execute(command, 0)
expect(provider).not_to receive(:warning)
provider.install
end
it 'should warn if reboot initiated' do
expect_execute(command, 1641)
expect(provider).to receive(:warning).with('The package installed successfully and the system is rebooting now.')
provider.install
end
it 'should warn if reboot required' do
expect_execute(command, 3010)
expect(provider).to receive(:warning).with('The package installed successfully, but the system must be rebooted.')
provider.install
end
it 'should fail otherwise', :if => Puppet::Util::Platform.windows? do
expect_execute(command, 5)
expect do
provider.install
end.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(5) # ERROR_ACCESS_DENIED
end
end
context 'With a real working dir' do
let(:execute_options) do {:failonfail => false, :combine => true, :cwd => 'E:\Rando\Directory', :suppress_window => true} end
it 'should not try to set the working directory' do
expect(Puppet::FileSystem).to receive(:exist?).with('E:\Rando\Directory').and_return(true)
expect_execute(command, 0)
provider.install
end
end
end
context '#uninstall' do
let(:command) { 'unblarg.exe /Q' }
let(:package) { double('package', :uninstall_command => ['unblarg.exe', '/Q'] ) }
before :each do
resource[:ensure] = :absent
provider.package = package
end
it 'should join the uninstall command and options' do
resource[:uninstall_options] = { 'INSTALLDIR' => 'C:\mysql-5.1' }
expect_execute("#{command} INSTALLDIR=C:\\mysql-5.1", 0)
provider.uninstall
end
it 'should compact nil install options' do
expect_execute(command, 0)
provider.uninstall
end
it 'should not warn if the package install succeeds' do
expect_execute(command, 0)
expect(provider).not_to receive(:warning)
provider.uninstall
end
it 'should warn if reboot initiated' do
expect_execute(command, 1641)
expect(provider).to receive(:warning).with('The package uninstalled successfully and the system is rebooting now.')
provider.uninstall
end
it 'should warn if reboot required' do
expect_execute(command, 3010)
expect(provider).to receive(:warning).with('The package uninstalled successfully, but the system must be rebooted.')
provider.uninstall
end
it 'should fail otherwise', :if => Puppet::Util::Platform.windows? do
expect_execute(command, 5)
expect do
provider.uninstall
end.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(5) # ERROR_ACCESS_DENIED
end
end
end
context '#validate_source' do
it 'should fail if the source parameter is empty' do
expect do
resource[:source] = ''
end.to raise_error(Puppet::Error, /The source parameter cannot be empty when using the Windows provider/)
end
it 'should accept a source' do
resource[:source] = source
end
end
context '#install_options' do
it 'should return nil by default' do
expect(provider.install_options).to be_nil
end
it 'should return the options' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql-here' }
expect(provider.install_options).to eq(['INSTALLDIR=C:\mysql-here'])
end
it 'should only quote if needed' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql here' }
expect(provider.install_options).to eq(['INSTALLDIR="C:\mysql here"'])
end
it 'should escape embedded quotes in install_options values with spaces' do
resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql "here"' }
expect(provider.install_options).to eq(['INSTALLDIR="C:\mysql \"here\""'])
end
end
context '#uninstall_options' do
it 'should return nil by default' do
expect(provider.uninstall_options).to be_nil
end
it 'should return the options' do
resource[:uninstall_options] = { 'INSTALLDIR' => 'C:\mysql-here' }
expect(provider.uninstall_options).to eq(['INSTALLDIR=C:\mysql-here'])
end
end
context '#join_options' do
it 'should return nil if there are no options' do
expect(provider.join_options(nil)).to be_nil
end
it 'should sort hash keys' do
expect(provider.join_options([{'b' => '2', 'a' => '1', 'c' => '3'}])).to eq(['a=1', 'b=2', 'c=3'])
end
it 'should return strings and hashes' do
expect(provider.join_options([{'a' => '1'}, 'b'])).to eq(['a=1', 'b'])
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/package/tdnf_spec.rb | spec/unit/provider/package/tdnf_spec.rb | require 'spec_helper'
# Note that much of the functionality of the tdnf provider is already tested with yum provider tests,
# as yum is the parent provider, via dnf
describe Puppet::Type.type(:package).provider(:tdnf) do
it_behaves_like 'RHEL package provider', described_class, 'tdnf'
context 'default' do
it 'should be the default provider on PhotonOS' do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return("PhotonOS")
expect(described_class).to be_default
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/package/dnfmodule_spec.rb | spec/unit/provider/package/dnfmodule_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:dnfmodule) do
include PuppetSpec::Fixtures
let(:dnf_version) do
<<-DNF_OUTPUT
4.0.9
Installed: dnf-0:4.0.9.2-5.el8.noarch at Wed 29 May 2019 07:05:05 AM GMT
Built : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> at Thu 14 Feb 2019 12:04:07 PM GMT
Installed: rpm-0:4.14.2-9.el8.x86_64 at Wed 29 May 2019 07:04:33 AM GMT
Built : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> at Thu 20 Dec 2018 01:30:03 PM GMT
DNF_OUTPUT
end
let(:execute_options) do
{:failonfail => true, :combine => true, :custom_environment => {}}
end
let(:packages) { File.read(my_fixture("dnf-module-list.txt")) }
let(:dnf_path) { '/usr/bin/dnf' }
before(:each) { allow(Puppet::Util).to receive(:which).with('/usr/bin/dnf').and_return(dnf_path) }
it "should have lower specificity" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:redhat)
allow(Facter).to receive(:value).with('os.release.major').and_return('8')
expect(described_class.specificity).to be < 200
end
describe "should be an opt-in provider" do
Array(4..8).each do |ver|
it "should not be default for redhat #{ver}" do
allow(Facter).to receive(:value).with('os.name').and_return('redhat')
allow(Facter).to receive(:value).with('os.family').and_return('redhat')
allow(Facter).to receive(:value).with('os.release.major').and_return(ver.to_s)
expect(described_class).not_to be_default
end
end
end
describe "handling dnf versions" do
before(:each) do
expect(Puppet::Type::Package::ProviderDnfmodule).to receive(:execute)
.with(["/usr/bin/dnf", "--version"])
.and_return(Puppet::Util::Execution::ProcessOutput.new(dnf_version, 0)).at_most(:once)
expect(Puppet::Util::Execution).to receive(:execute)
.with(["/usr/bin/dnf", "--version"], execute_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new(dnf_version, 0))
end
before(:each) { described_class.instance_variable_set("@current_version", nil) }
describe "with a supported dnf version" do
it "correctly parses the version" do
expect(described_class.current_version).to eq('4.0.9')
end
end
describe "with an unsupported dnf version" do
let(:dnf_version) do
<<-DNF_OUTPUT
2.7.5
Installed: dnf-0:2.7.5-12.fc28.noarch at Mon 13 Aug 2018 11:05:27 PM GMT
Built : Fedora Project at Wed 18 Apr 2018 02:29:51 PM GMT
Installed: rpm-0:4.14.1-7.fc28.x86_64 at Mon 13 Aug 2018 11:05:25 PM GMT
Built : Fedora Project at Mon 19 Feb 2018 09:29:01 AM GMT
DNF_OUTPUT
end
it "correctly parses the version" do
expect(described_class.current_version).to eq('2.7.5')
end
it "raises an error when attempting prefetch" do
expect { described_class.prefetch('anything') }.to raise_error(Puppet::Error, "Modules are not supported on DNF versions lower than 3.0.1")
end
end
end
describe "when ensuring a module" do
let(:name) { 'baz' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => name,
:provider => 'dnfmodule',
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
describe 'provider features' do
it { is_expected.to be_versionable }
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
end
context "when installing a new module" do
before do
provider.instance_variable_get('@property_hash')[:ensure] = :absent
end
it "should not reset the module stream when package is absent" do
resource[:ensure] = :present
expect(provider).not_to receive(:uninstall)
expect(provider).to receive(:execute)
provider.install
end
it "should not reset the module stream when package is purged" do
provider.instance_variable_get('@property_hash')[:ensure] = :purged
resource[:ensure] = :present
expect(provider).not_to receive(:uninstall)
expect(provider).to receive(:execute)
provider.install
end
it "should just enable the module if it has no default profile (missing groups or modules)" do
dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nmissing groups or modules: #{resource[:name]}")
allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception)
resource[:ensure] = :present
expect(provider).to receive(:execute).with(array_including('install')).ordered
expect(provider).to receive(:execute).with(array_including('enable')).ordered
provider.install
end
it "should just enable the module with the right stream if it has no default profile (missing groups or modules)" do
stream = '12.3'
dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nmissing groups or modules: #{resource[:name]}:#{stream}")
allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception)
resource[:ensure] = stream
expect(provider).to receive(:execute).with(array_including('install')).ordered
expect(provider).to receive(:execute).with(array_including('enable')).ordered
provider.install
end
it "should just enable the module if it has no default profile (broken groups or modules)" do
dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nbroken groups or modules: #{resource[:name]}")
allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception)
resource[:ensure] = :present
expect(provider).to receive(:execute).with(array_including('install')).ordered
expect(provider).to receive(:execute).with(array_including('enable')).ordered
provider.install
end
it "should just enable the module with the right stream if it has no default profile (broken groups or modules)" do
stream = '12.3'
dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nbroken groups or modules: #{resource[:name]}:#{stream}")
allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception)
resource[:ensure] = stream
expect(provider).to receive(:execute).with(array_including('install')).ordered
expect(provider).to receive(:execute).with(array_including('enable')).ordered
provider.install
end
it "should just enable the module if enable_only = true" do
resource[:ensure] = :present
resource[:enable_only] = true
expect(provider).to receive(:execute).with(array_including('enable'))
expect(provider).not_to receive(:execute).with(array_including('install'))
provider.install
end
it "should install the default stream and flavor" do
resource[:ensure] = :present
expect(provider).to receive(:execute).with(array_including('baz'))
provider.install
end
it "should install a specific stream" do
resource[:ensure] = '9.6'
expect(provider).to receive(:execute).with(array_including('baz:9.6'))
provider.install
end
it "should install a specific flavor" do
resource[:ensure] = :present
resource[:flavor] = 'minimal'
expect(provider).to receive(:execute).with(array_including('baz/minimal'))
provider.install
end
it "should install a specific flavor and stream" do
resource[:ensure] = '9.6'
resource[:flavor] = 'minimal'
expect(provider).to receive(:execute).with(array_including('baz:9.6/minimal'))
provider.install
end
end
context "when ensuring a specific version on top of another stream" do
before do
provider.instance_variable_get('@property_hash')[:ensure] = '9.6'
end
it "should remove existing packages and reset the module stream before installing" do
resource[:ensure] = '10'
expect(provider).to receive(:execute).thrice.with(array_including(/remove|reset|install/))
provider.install
end
end
context "with an installed flavor" do
before do
provider.instance_variable_get('@property_hash')[:flavor] = 'minimal'
end
it "should remove existing packages and reset the module stream before installing another flavor" do
resource[:flavor] = 'common'
expect(provider).to receive(:execute).thrice.with(array_including(/remove|reset|install/))
provider.flavor = resource[:flavor]
end
it "should not do anything if the flavor doesn't change" do
resource[:flavor] = 'minimal'
expect(provider).not_to receive(:execute)
provider.flavor = resource[:flavor]
end
it "should return the existing flavor" do
expect(provider.flavor).to eq('minimal')
end
end
context "when disabling a module" do
it "executed the disable command" do
resource[:ensure] = :disabled
expect(provider).to receive(:execute).with(array_including('disable'))
provider.disable
end
it "does not try to disable if package is already disabled" do
allow(described_class).to receive(:command).with(:dnf).and_return(dnf_path)
allow(Puppet::Util::Execution).to receive(:execute)
.with("/usr/bin/dnf module list -y")
.and_return("baz 1.2 [d][x] common [d], complete Package Description")
resource[:ensure] = :disabled
expect(provider).to be_insync(:disabled)
end
end
end
context "parsing the output of module list" do
before { allow(described_class).to receive(:command).with(:dnf).and_return(dnf_path) }
it "returns an array of enabled modules" do
allow(Puppet::Util::Execution).to receive(:execute)
.with("/usr/bin/dnf module list -y")
.and_return(packages)
enabled_packages = described_class.instances.map { |package| package.properties }
expected_packages = [{name: "389-ds", ensure: "1.4", flavor: :absent, provider: :dnfmodule},
{name: "gimp", ensure: "2.8", flavor: "devel", provider: :dnfmodule},
{name: "mariadb", ensure: "10.3", flavor: "client", provider: :dnfmodule},
{name: "nodejs", ensure: "10", flavor: "minimal", provider: :dnfmodule},
{name: "perl", ensure: "5.26", flavor: "minimal", provider: :dnfmodule},
{name: "postgresql", ensure: "10", flavor: "server", provider: :dnfmodule},
{name: "ruby", ensure: "2.5", flavor: :absent, provider: :dnfmodule},
{name: "rust-toolset", ensure: "rhel8", flavor: "common", provider: :dnfmodule},
{name: "subversion", ensure: "1.10", flavor: "server", provider: :dnfmodule},
{name: "swig", ensure: :disabled, flavor: :absent, provider: :dnfmodule},
{name: "virt", ensure: :disabled, flavor: :absent, provider: :dnfmodule}]
expect(enabled_packages).to eql(expected_packages)
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/package/urpmi_spec.rb | spec/unit/provider/package/urpmi_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:urpmi) do
before do
%w[rpm urpmi urpme urpmq].each do |executable|
allow(Puppet::Util).to receive(:which).with(executable).and_return(executable)
end
allow(Puppet::Util::Execution).to receive(:execute)
.with(['rpm', '--version'], anything)
.and_return(Puppet::Util::Execution::ProcessOutput.new('RPM version 4.9.1.3', 0))
end
let(:resource) do
Puppet::Type.type(:package).new(:name => 'foopkg', :provider => :urpmi)
end
before do
subject.resource = resource
allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(described_class)
end
describe '#install' do
before do
allow(subject).to receive(:rpm).with('-q', 'foopkg', any_args).and_return("foopkg 0 1.2.3.4 5 noarch :DESC:\n")
end
describe 'without a version' do
it 'installs the unversioned package' do
resource[:ensure] = :present
expect(Puppet::Util::Execution).to receive(:execute).with(['urpmi', '--auto', 'foopkg'], anything)
subject.install
end
end
describe 'with a version' do
it 'installs the versioned package' do
resource[:ensure] = '4.5.6'
expect(Puppet::Util::Execution).to receive(:execute).with(['urpmi', '--auto', 'foopkg-4.5.6'], anything)
subject.install
end
end
describe "and the package install fails" do
it "raises an error" do
allow(Puppet::Util::Execution).to receive(:execute).with(['urpmi', '--auto', 'foopkg'], anything)
allow(subject).to receive(:query)
expect { subject.install }.to raise_error Puppet::Error, /Package \S+ was not present after trying to install it/
end
end
end
describe '#latest' do
let(:urpmq_output) { 'foopkg : Lorem ipsum dolor sit amet, consectetur adipisicing elit ( 7.8.9-1.mga2 )' }
it "uses urpmq to determine the latest package" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['urpmq', '-S', 'foopkg'], anything)
.and_return(Puppet::Util::Execution::ProcessOutput.new(urpmq_output, 0))
expect(subject.latest).to eq('7.8.9-1.mga2')
end
it "falls back to the current version" do
resource[:ensure] = '5.4.3'
expect(Puppet::Util::Execution).to receive(:execute)
.with(['urpmq', '-S', 'foopkg'], anything)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(subject.latest).to eq('5.4.3')
end
end
describe '#update' do
it 'delegates to #install' do
expect(subject).to receive(:install)
subject.update
end
end
describe '#purge' do
it 'uses urpme to purge packages' do
expect(Puppet::Util::Execution).to receive(:execute).with(['urpme', '--auto', 'foopkg'], anything)
subject.purge
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/package/puppet_gem_spec.rb | spec/unit/provider/package/puppet_gem_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:puppet_gem) do
let(:resource) do
Puppet::Type.type(:package).new(
:name => 'myresource',
:ensure => :installed
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
if Puppet::Util::Platform.windows?
let(:provider_gem_cmd) { 'C:\Program Files\Puppet Labs\Puppet\puppet\bin\gem.bat' }
else
let(:provider_gem_cmd) { '/opt/puppetlabs/puppet/bin/gem' }
end
let(:execute_options) do
{
failonfail: true,
combine: true,
custom_environment: {
'HOME'=>ENV['HOME'],
'PKG_CONFIG_PATH' => '/opt/puppetlabs/puppet/lib/pkgconfig'
}
}
end
before :each do
resource.provider = provider
if Puppet::Util::Platform.windows?
# provider is loaded before we can stub, so stub the class we're testing
allow(provider.class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd)
else
allow(provider.class).to receive(:which).with(provider_gem_cmd).and_return(provider_gem_cmd)
end
allow(File).to receive(:file?).with(provider_gem_cmd).and_return(true)
end
context "when installing" do
before :each do
allow(provider).to receive(:rubygem_version).and_return('1.9.9')
end
it "should use the path to the gem command" do
expect(described_class).to receive(:execute).with([provider_gem_cmd, be_an(Array)], be_a(Hash)).and_return('')
provider.install
end
it "should not append install_options by default" do
expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{install --no-rdoc --no-ri myresource}], anything).and_return('')
provider.install
end
it "should allow setting an install_options parameter" do
resource[:install_options] = [ '--force', {'--bindir' => '/usr/bin' } ]
expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{install --force --bindir=/usr/bin --no-rdoc --no-ri myresource}], anything).and_return('')
provider.install
end
end
context "when uninstalling" do
it "should use the path to the gem command" do
expect(described_class).to receive(:execute).with([provider_gem_cmd, be_an(Array)], be_a(Hash)).and_return('')
provider.uninstall
end
it "should not append uninstall_options by default" do
expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{uninstall --executables --all myresource}], anything).and_return('')
provider.uninstall
end
it "should allow setting an uninstall_options parameter" do
resource[:uninstall_options] = [ '--force', {'--bindir' => '/usr/bin' } ]
expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{uninstall --executables --all myresource --force --bindir=/usr/bin}], anything).and_return('')
provider.uninstall
end
it 'should invalidate the rubygems cache' do
gem_source = double('gem_source')
allow(Puppet::Util::Autoload).to receive(:gem_source).and_return(gem_source)
expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{uninstall --executables --all myresource}], anything).and_return('')
expect(gem_source).to receive(:clear_paths)
provider.uninstall
end
end
context 'calculated specificity' do
include_context 'provider specificity'
context 'when is not defaultfor' do
subject { described_class.specificity }
it { is_expected.to eql 1 }
end
context 'when is defaultfor' do
let(:os) { Puppet.runtime[:facter].value('os.name') }
subject do
described_class.defaultfor('os.name': os)
described_class.specificity
end
it { is_expected.to be > 100 }
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/package/base_spec.rb | spec/unit/provider/package/base_spec.rb | require 'spec_helper'
require 'puppet/provider/package'
Puppet::Type.type(:package).provide(:test_base_provider, parent: Puppet::Provider::Package) do
def query; end
end
describe Puppet::Provider::Package do
let(:provider) { Puppet::Type.type(:package).provider(:test_base_provider).new }
it 'returns absent for uninstalled packages when not purgeable' do
expect(provider.properties[:ensure]).to eq(:absent)
end
it 'returns purged for uninstalled packages when purgeable' do
expect(provider.class).to receive(:feature?).with(:purgeable).and_return(true)
expect(provider.properties[:ensure]).to eq(:purged)
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/package/pkg_spec.rb | spec/unit/provider/package/pkg_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:pkg), unless: Puppet::Util::Platform.jruby? do
let (:resource) { Puppet::Resource.new(:package, 'dummy', :parameters => {:name => 'dummy', :ensure => :latest}) }
let (:provider) { described_class.new(resource) }
before :each do
allow(described_class).to receive(:command).with(:pkg).and_return('/bin/pkg')
end
def self.it_should_respond_to(*actions)
actions.each do |action|
it "should respond to :#{action}" do
expect(provider).to respond_to(action)
end
end
end
it_should_respond_to :install, :uninstall, :update, :query, :latest
context 'default' do
[ 10 ].each do |ver|
it "should not be the default provider on Solaris #{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:Solaris)
allow(Facter).to receive(:value).with(:kernelrelease).and_return("5.#{ver}")
allow(Facter).to receive(:value).with('os.name').and_return(:Solaris)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(described_class).to_not be_default
end
end
[ 11, 12 ].each do |ver|
it "should be the default provider on Solaris #{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:Solaris)
allow(Facter).to receive(:value).with(:kernelrelease).and_return("5.#{ver}")
allow(Facter).to receive(:value).with('os.name').and_return(:Solaris)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(described_class).to be_default
end
end
end
it "should be versionable" do
expect(described_class).to be_versionable
end
describe "#methods" do
context ":pkg_state" do
it "should raise error on unknown values" do
expect {
expect(described_class.pkg_state('extra')).to
}.to raise_error(ArgumentError, /Unknown format/)
end
['known', 'installed'].each do |k|
it "should return known values" do
expect(described_class.pkg_state(k)).to eq({:status => k})
end
end
end
context ":ifo_flag" do
it "should raise error on unknown values" do
expect {
expect(described_class.ifo_flag('x--')).to
}.to raise_error(ArgumentError, /Unknown format/)
end
{'i--' => 'installed', '---'=> 'known'}.each do |k, v|
it "should return known values" do
expect(described_class.ifo_flag(k)).to eq({:status => v})
end
end
end
context ":parse_line" do
it "should raise error on unknown values" do
expect {
expect(described_class.parse_line('pkg (mypkg) 1.2.3.4 i-- zzz')).to
}.to raise_error(ArgumentError, /Unknown line format/)
end
{
'pkg://omnios/SUNWcs@0.5.11,5.11-0.151006:20130506T161045Z i--' => {:name => 'SUNWcs', :ensure => '0.5.11,5.11-0.151006:20130506T161045Z', :status => 'installed', :provider => :pkg, :publisher => 'omnios'},
'pkg://omnios/incorporation/jeos/illumos-gate@11,5.11-0.151006:20130506T183443Z if-' => {:name => 'incorporation/jeos/illumos-gate', :ensure => "11,5.11-0.151006:20130506T183443Z", :mark => :hold, :status => 'installed', :provider => :pkg, :publisher => 'omnios'},
'pkg://solaris/SUNWcs@0.5.11,5.11-0.151.0.1:20101105T001108Z installed -----' => {:name => 'SUNWcs', :ensure => '0.5.11,5.11-0.151.0.1:20101105T001108Z', :status => 'installed', :provider => :pkg, :publisher => 'solaris'},
}.each do |k, v|
it "[#{k}] should correctly parse" do
expect(described_class.parse_line(k)).to eq(v)
end
end
end
context ":latest" do
before do
expect(described_class).to receive(:pkg).with(:refresh)
end
it "should work correctly for ensure latest on solaris 11 (UFOXI) when there are no further packages to install" do
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.installed')))
expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "should work correctly for ensure latest on solaris 11 in the presence of a certificate expiration warning" do
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.certificate_warning')))
expect(provider.latest).to eq("1.0.6-0.175.0.0.0.2.537")
end
it "should work correctly for ensure latest on solaris 11(known UFOXI)" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', '-n', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.known')))
expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "should work correctly for ensure latest on solaris 11 (IFO)" do
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.ifo.installed')))
expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "should work correctly for ensure latest on solaris 11(known IFO)" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', '-n', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.ifo.known')))
expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z')
end
it "issues a warning when the certificate has expired" do
warning = "Certificate '/var/pkg/ssl/871b4ed0ade09926e6adf95f86bf17535f987684' for publisher 'solarisstudio', needed to access 'https://pkg.oracle.com/solarisstudio/release/', will expire in '29' days."
expect(Puppet).to receive(:warning).with("pkg warning: #{warning}")
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.certificate_warning')))
provider.latest
end
it "doesn't issue a warning when the certificate hasn't expired" do
expect(Puppet).not_to receive(:warning).with(/pkg warning/)
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.installed')))
provider.latest
end
it "applies install options if available" do
resource[:install_options] = ['--foo', {'--bar' => 'baz'}]
expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.known')))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', '-n', '--foo', '--bar=baz', 'dummy'], {failonfail: false, combine: true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.latest
end
end
context ":instances" do
it "should correctly parse lines on solaris 11" do
expect(described_class).to receive(:pkg).with(:list, '-Hv').and_return(File.read(my_fixture('solaris11')))
expect(described_class).not_to receive(:warning)
instances = described_class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure) }}
expect(instances.size).to eq(2)
expect(instances[0]).to eq({:name => 'dummy/dummy', :ensure => '3.0,5.11-0.175.0.0.0.2.537:20131230T130000Z'})
expect(instances[1]).to eq({:name => 'dummy/dummy2', :ensure => '1.8.1.2-0.175.0.0.0.2.537:20131230T130000Z'})
end
it "should fail on incorrect lines" do
fake_output = File.read(my_fixture('incomplete'))
expect(described_class).to receive(:pkg).with(:list,'-Hv').and_return(fake_output)
expect {
described_class.instances
}.to raise_error(ArgumentError, /Unknown line format pkg/)
end
it "should fail on unknown package status" do
expect(described_class).to receive(:pkg).with(:list,'-Hv').and_return(File.read(my_fixture('unknown_status')))
expect {
described_class.instances
}.to raise_error(ArgumentError, /Unknown format pkg/)
end
end
context ":query" do
context "on solaris 10" do
it "should find the package" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_solaris10')), 0))
expect(provider.query).to eq({
:name => 'dummy',
:ensure => '2.5.5,5.10-0.111:20131230T130000Z',
:publisher => 'solaris',
:status => 'installed',
:provider => :pkg,
})
end
it "should return :absent when the package is not found" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 1))
expect(provider.query).to eq({:ensure => :absent, :name => "dummy"})
end
end
context "on solaris 11" do
it "should find the package" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_solaris11.installed')), 0))
expect(provider.query).to eq({
:name => 'dummy',
:status => 'installed',
:ensure => '1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z',
:publisher => 'solaris',
:provider => :pkg,
})
end
it "should return :absent when the package is not found" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 1))
expect(provider.query).to eq({:ensure => :absent, :name => "dummy"})
end
end
it "should return fail when the packageline cannot be parsed" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('incomplete')), 0))
expect {
provider.query
}.to raise_error(ArgumentError, /Unknown line format/)
end
end
context ":install" do
[
{ :osrel => '11.0', :flags => ['--accept'] },
{ :osrel => '11.2', :flags => ['--accept', '--sync-actuators-timeout', '900'] },
].each do |hash|
context "with 'os.release.full' #{hash[:osrel]}" do
before :each do
allow(Facter).to receive(:value).with('os.release.full').and_return(hash[:osrel])
end
it "should support install options" do
resource[:install_options] = ['--foo', {'--bar' => 'baz'}]
expect(provider).to receive(:query).and_return({:ensure => :absent})
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:unhold)
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', *hash[:flags], '--foo', '--bar=baz', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.install
end
it "should accept all licenses" do
expect(provider).to receive(:query).with(no_args).and_return({:ensure => :absent})
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', *hash[:flags], 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.install
end
it "should install specific version(1)" do
# Should install also check if the version installed is the same version we are asked to install? or should we rely on puppet for that?
resource[:ensure] = '0.0.7,5.11-0.151006:20131230T130000Z'
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('pkg://foo/dummy@0.0.6,5.11-0.151006:20131230T130000Z installed -----', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', *hash[:flags], 'dummy@0.0.7,5.11-0.151006:20131230T130000Z'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.install
end
it "should install specific version(2)" do
resource[:ensure] = '0.0.8'
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('pkg://foo/dummy@0.0.7,5.11-0.151006:20131230T130000Z installed -----', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', *hash[:flags], 'dummy@0.0.8'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.install
end
it "should downgrade to specific version" do
resource[:ensure] = '0.0.7'
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:query).with(no_args).and_return({:ensure => '0.0.8,5.11-0.151106:20131230T130000Z'})
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', *hash[:flags], 'dummy@0.0.7'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.install
end
it "should install any if version is not specified" do
resource[:ensure] = :present
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:query).with(no_args).and_return({:ensure => :absent})
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', *hash[:flags], 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.install
end
it "should install if no version was previously installed, and a specific version was requested" do
resource[:ensure] = '0.0.7'
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:query).with(no_args).and_return({:ensure => :absent})
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', *hash[:flags], 'dummy@0.0.7'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.install
end
it "installs the latest matching version when given implicit version, and none are installed" do
resource[:ensure] = '1.0-0.151006'
is = :absent
expect(provider).to receive(:query).with(no_args).and_return({:ensure => is})
expect(provider).to receive(:properties).and_return({:mark => :hold}).exactly(3).times
expect(described_class).to receive(:pkg)
.with(:freeze, 'dummy')
expect(described_class).to receive(:pkg)
.with(:list, '-Hvfa', 'dummy@1.0-0.151006')
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(provider).to receive(:unhold).with(no_args).twice
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', *hash[:flags], 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.insync?(is)
provider.install
end
it "updates to the latest matching version when given implicit version" do
resource[:ensure] = '1.0-0.151006'
is = '1.0,5.11-0.151006:20140219T191204Z'
expect(provider).to receive(:query).with(no_args).and_return({:ensure => is})
expect(provider).to receive(:properties).and_return({:mark => :hold}).exactly(3).times
expect(described_class).to receive(:pkg)
.with(:freeze, 'dummy')
expect(described_class).to receive(:pkg)
.with(:list, '-Hvfa', 'dummy@1.0-0.151006')
.and_return(File.read(my_fixture('dummy_implicit_version')))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(provider).to receive(:unhold).with(no_args).twice
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', *hash[:flags], 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.insync?(is)
provider.install
end
it "issues a warning when an implicit version number is used, and in sync" do
resource[:ensure] = '1.0-0.151006'
is = '1.0,5.11-0.151006:20140220T084443Z'
expect(provider).to receive(:warning).with("Implicit version 1.0-0.151006 has 3 possible matches")
expect(described_class).to receive(:pkg)
.with(:list, '-Hvfa', 'dummy@1.0-0.151006')
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'update', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 4))
provider.insync?(is)
end
it "issues a warning when choosing a version number for an implicit match" do
resource[:ensure] = '1.0-0.151006'
is = :absent
expect(provider).to receive(:warning).with("Implicit version 1.0-0.151006 has 3 possible matches")
expect(provider).to receive(:warning).with("Selecting version '1.0,5.11-0.151006:20140220T084443Z' for implicit '1.0-0.151006'")
expect(described_class).to receive(:pkg)
.with(:list, '-Hvfa', 'dummy@1.0-0.151006')
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0))
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.insync?(is)
end
it "should try 5 times to install and fail when all tries failed" do
allow_any_instance_of(Kernel).to receive(:sleep)
expect(provider).to receive(:query).and_return({:ensure => :absent})
expect(provider).to receive(:properties).and_return({:mark => :hold})
expect(provider).to receive(:unhold)
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/bin/pkg', 'install', *hash[:flags], 'dummy'], {:failonfail => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 7))
.exactly(5).times
expect {
provider.update
}.to raise_error(Puppet::Error, /Pkg could not install dummy after 5 tries. Aborting run/)
end
end
end
end
context ":update" do
it "should not raise error if not necessary" do
expect(provider).to receive(:install).with(true).and_return({:exit => 0})
provider.update
end
it "should not raise error if not necessary (2)" do
expect(provider).to receive(:install).with(true).and_return({:exit => 4})
provider.update
end
it "should raise error if necessary" do
expect(provider).to receive(:install).with(true).and_return({:exit => 1})
expect {
provider.update
}.to raise_error(Puppet::Error, /Unable to update/)
end
end
context ":uninstall" do
it "should support current pkg version" do
expect(described_class).to receive(:pkg).with(:version).and_return('630e1ffc7a19')
expect(described_class).to receive(:pkg).with([:uninstall, resource[:name]])
expect(provider).to receive(:properties).and_return({:hold => false})
provider.uninstall
end
it "should support original pkg commands" do
expect(described_class).to receive(:pkg).with(:version).and_return('052adf36c3f4')
expect(described_class).to receive(:pkg).with([:uninstall, '-r', resource[:name]])
expect(provider).to receive(:properties).and_return({:hold => false})
provider.uninstall
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/provider/package/pacman_spec.rb | spec/unit/provider/package/pacman_spec.rb | require 'spec_helper'
require 'stringio'
describe Puppet::Type.type(:package).provider(:pacman) do
let(:no_extra_options) { { :failonfail => true, :combine => true, :custom_environment => {} } }
let(:executor) { Puppet::Util::Execution }
let(:resolver) { Puppet::Util }
let(:resource) { Puppet::Type.type(:package).new(:name => 'package', :provider => 'pacman') }
let(:provider) { described_class.new(resource) }
before do
allow(resolver).to receive(:which).with('/usr/bin/pacman').and_return('/usr/bin/pacman')
allow(described_class).to receive(:which).with('/usr/bin/pacman').and_return('/usr/bin/pacman')
allow(resolver).to receive(:which).with('/usr/bin/yaourt').and_return('/usr/bin/yaourt')
allow(described_class).to receive(:which).with('/usr/bin/yaourt').and_return('/usr/bin/yaourt')
allow(described_class).to receive(:group?).and_return(false)
allow(described_class).to receive(:yaourt?).and_return(false)
end
describe "when installing" do
before do
allow(provider).to receive(:query).and_return({
:ensure => '1.0'
})
end
it "should call pacman to install the right package quietly when yaourt is not installed" do
args = ['--noconfirm', '--needed', '--noprogressbar', '--sync', resource[:name]]
expect(provider).to receive(:pacman).at_least(:once).with(*args).and_return('')
provider.install
end
it "should call yaourt to install the right package quietly when yaourt is installed" do
without_partial_double_verification do
allow(described_class).to receive(:yaourt?).and_return(true)
args = ['--noconfirm', '--needed', '--noprogressbar', '--sync', resource[:name]]
expect(provider).to receive(:yaourt).at_least(:once).with(*args).and_return('')
provider.install
end
end
it "should raise an Puppet::Error if the installation failed" do
allow(executor).to receive(:execute).and_return("")
expect(provider).to receive(:query).and_return(nil)
expect {
provider.install
}.to raise_exception(Puppet::Error, /Could not find package/)
end
it "should raise an Puppet::Error when trying to install a group and allow_virtual is false" do
allow(described_class).to receive(:group?).and_return(true)
resource[:allow_virtual] = false
expect {
provider.install
}.to raise_error(Puppet::Error, /Refusing to install package group/)
end
it "should not raise an Puppet::Error when trying to install a group and allow_virtual is true" do
allow(described_class).to receive(:group?).and_return(true)
resource[:allow_virtual] = true
allow(executor).to receive(:execute).and_return("")
provider.install
end
describe "and install_options are given" do
before do
resource[:install_options] = ['-x', {'--arg' => 'value'}]
end
it "should call pacman to install the right package quietly when yaourt is not installed" do
args = ['--noconfirm', '--needed', '--noprogressbar', '-x', '--arg=value', '--sync', resource[:name]]
expect(provider).to receive(:pacman).at_least(:once).with(*args).and_return('')
provider.install
end
it "should call yaourt to install the right package quietly when yaourt is installed" do
without_partial_double_verification do
expect(described_class).to receive(:yaourt?).and_return(true)
args = ['--noconfirm', '--needed', '--noprogressbar', '-x', '--arg=value', '--sync', resource[:name]]
expect(provider).to receive(:yaourt).at_least(:once).with(*args).and_return('')
provider.install
end
end
end
context "when :source is specified" do
let(:install_seq) { sequence("install") }
context "recognizable by pacman" do
%w{
/some/package/file
http://some.package.in/the/air
ftp://some.package.in/the/air
}.each do |source|
it "should install #{source} directly" do
resource[:source] = source
expect(executor).to receive(:execute).
with(include("--update") & include(source), no_extra_options).
ordered.
and_return("")
provider.install
end
end
end
context "as a file:// URL" do
let(:actual_file_path) { "/some/package/file" }
before do
resource[:source] = "file:///some/package/file"
end
it "should install from the path segment of the URL" do
expect(executor).to receive(:execute).
with(include("--update") & include(actual_file_path), no_extra_options).
ordered.
and_return("")
provider.install
end
end
context "as a puppet URL" do
before do
resource[:source] = "puppet://server/whatever"
end
it "should fail" do
expect {
provider.install
}.to raise_error(Puppet::Error, /puppet:\/\/ URL is not supported/)
end
end
context "as an unsupported URL scheme" do
before do
resource[:source] = "blah://foo.com"
end
it "should fail" do
expect {
provider.install
}.to raise_error(Puppet::Error, /Source blah:\/\/foo\.com is not supported/)
end
end
end
end
describe "when updating" do
it "should call install" do
expect(provider).to receive(:install).and_return("install return value")
expect(provider.update).to eq("install return value")
end
end
describe "when purging" do
it "should call pacman to remove the right package and configs quietly" do
args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "--remove", "--nosave", resource[:name]]
expect(executor).to receive(:execute).with(args, no_extra_options).and_return("")
provider.purge
end
end
describe "when uninstalling" do
it "should call pacman to remove the right package quietly" do
args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "--remove", resource[:name]]
expect(executor).to receive(:execute).with(args, no_extra_options).and_return("")
provider.uninstall
end
it "should call yaourt to remove the right package quietly" do
without_partial_double_verification do
allow(described_class).to receive(:yaourt?).and_return(true)
args = ["--noconfirm", "--noprogressbar", "--remove", resource[:name]]
expect(provider).to receive(:yaourt).with(*args)
provider.uninstall
end
end
it "adds any uninstall_options" do
resource[:uninstall_options] = ['-x', {'--arg' => 'value'}]
args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "-x", "--arg=value", "--remove", resource[:name]]
expect(executor).to receive(:execute).with(args, no_extra_options).and_return("")
provider.uninstall
end
it "should recursively remove packages when given a package group" do
allow(described_class).to receive(:group?).and_return(true)
args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "--remove", "--recursive", resource[:name]]
expect(executor).to receive(:execute).with(args, no_extra_options).and_return("")
provider.uninstall
end
end
describe "when querying" do
it "should query pacman" do
expect(executor).to receive(:execpipe).with(["/usr/bin/pacman", '--query'])
expect(executor).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg', 'package'])
provider.query
end
it "should return the version" do
expect(executor).to receive(:execpipe).
with(["/usr/bin/pacman", "--query"]).and_yield(<<EOF)
otherpackage 1.2.3.4
package 1.01.3-2
yetanotherpackage 1.2.3.4
EOF
expect(executor).to receive(:execpipe).with(['/usr/bin/pacman', '--sync', '-gg', 'package']).and_yield('')
expect(provider.query).to eq({ :name => 'package', :ensure => '1.01.3-2', :provider => :pacman, })
end
it "should return a hash indicating that the package is missing" do
expect(executor).to receive(:execpipe).twice.and_yield("")
expect(provider.query).to be_nil
end
it "should raise an error if execpipe fails" do
expect(executor).to receive(:execpipe).and_raise(Puppet::ExecutionFailure.new("ERROR!"))
expect { provider.query }.to raise_error(RuntimeError)
end
describe 'when querying a group' do
before :each do
expect(executor).to receive(:execpipe).with(['/usr/bin/pacman', '--query']).and_yield('foo 1.2.3')
expect(executor).to receive(:execpipe).with(['/usr/bin/pacman', '--sync', '-gg', 'package']).and_yield('package foo')
end
it 'should warn when allow_virtual is false' do
resource[:allow_virtual] = false
expect(provider).to receive(:warning)
provider.query
end
it 'should not warn allow_virtual is true' do
resource[:allow_virtual] = true
expect(described_class).not_to receive(:warning)
provider.query
end
end
end
describe "when determining instances" do
it "should retrieve installed packages and groups" do
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query'])
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg'])
described_class.instances
end
it "should return installed packages" do
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query']).and_yield(StringIO.new("package1 1.23-4\npackage2 2.00\n"))
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg']).and_yield("")
instances = described_class.instances
expect(instances.length).to eq(2)
expect(instances[0].properties).to eq({
:provider => :pacman,
:ensure => '1.23-4',
:name => 'package1'
})
expect(instances[1].properties).to eq({
:provider => :pacman,
:ensure => '2.00',
:name => 'package2'
})
end
it "should return completely installed groups with a virtual version together with packages" do
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query']).and_yield(<<EOF)
package1 1.00
package2 1.00
EOF
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg']).and_yield(<<EOF)
group1 package1
group1 package2
EOF
instances = described_class.instances
expect(instances.length).to eq(3)
expect(instances[0].properties).to eq({
:provider => :pacman,
:ensure => '1.00',
:name => 'package1'
})
expect(instances[1].properties).to eq({
:provider => :pacman,
:ensure => '1.00',
:name => 'package2'
})
expect(instances[2].properties).to eq({
:provider => :pacman,
:ensure => 'package1 1.00, package2 1.00',
:name => 'group1'
})
end
it "should not return partially installed packages" do
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query']).and_yield(<<EOF)
package1 1.00
EOF
expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg']).and_yield(<<EOF)
group1 package1
group1 package2
EOF
instances = described_class.instances
expect(instances.length).to eq(1)
expect(instances[0].properties).to eq({
:provider => :pacman,
:ensure => '1.00',
:name => 'package1'
})
end
it 'should sort package names for installed groups' do
expect(described_class).to receive(:execpipe).with(['/usr/bin/pacman', '--sync', '-gg', 'group1']).and_yield(<<EOF)
group1 aa
group1 b
group1 a
EOF
package_versions= {
'a' => '1',
'aa' => '1',
'b' => '1',
}
virtual_group_version = described_class.get_installed_groups(package_versions, 'group1')
expect(virtual_group_version).to eq({ 'group1' => 'a 1, aa 1, b 1' })
end
it "should return nil on error" do
expect(described_class).to receive(:execpipe).and_raise(Puppet::ExecutionFailure.new("ERROR!"))
expect { described_class.instances }.to raise_error(RuntimeError)
end
it "should warn on invalid input" do
expect(described_class).to receive(:execpipe).twice.and_yield(StringIO.new("blah"))
expect(described_class).to receive(:warning).with("Failed to match line 'blah'")
expect(described_class.instances).to eq([])
end
end
describe "when determining the latest version" do
it "should get query pacman for the latest version" do
expect(executor).to receive(:execute).
ordered.
with(['/usr/bin/pacman', '--sync', '--print', '--print-format', '%v', resource[:name]], no_extra_options).
and_return("")
provider.latest
end
it "should return the version number from pacman" do
expect(executor).to receive(:execute).at_least(:once).and_return("1.00.2-3\n")
expect(provider.latest).to eq("1.00.2-3")
end
it "should return a virtual group version when resource is a package group" do
allow(described_class).to receive(:group?).and_return(true)
expect(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--print', '--print-format', '%n %v', resource[:name]], no_extra_options).ordered.
and_return(<<EOF)
package2 1.0.1
package1 1.0.0
EOF
expect(provider.latest).to eq('package1 1.0.0, package2 1.0.1')
end
end
describe 'when determining if a resource is a group' do
before do
allow(described_class).to receive(:group?).and_call_original
end
it 'should return false on non-zero pacman exit' do
allow(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--groups', 'git'], {:failonfail => true, :combine => true, :custom_environment => {}}).and_raise(Puppet::ExecutionFailure, 'error')
expect(described_class.group?('git')).to eq(false)
end
it 'should return false on empty pacman output' do
allow(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--groups', 'git'], {:failonfail => true, :combine => true, :custom_environment => {}}).and_return('')
expect(described_class.group?('git')).to eq(false)
end
it 'should return true on non-empty pacman output' do
allow(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--groups', 'vim-plugins'], {:failonfail => true, :combine => true, :custom_environment => {}}).and_return('vim-plugins vim-a')
expect(described_class.group?('vim-plugins')).to eq(true)
end
end
describe 'when querying installed groups' do
let(:installed_packages) { {'package1' => '1.0', 'package2' => '2.0', 'package3' => '3.0'} }
let(:groups) { [['foo package1'], ['foo package2'], ['bar package3'], ['bar package4'], ['baz package5']] }
it 'should raise an error on non-zero pacman exit without a filter' do
expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg 2>&1').and_return('error!')
expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(1)
expect { described_class.get_installed_groups(installed_packages) }.to raise_error(Puppet::ExecutionFailure, 'error!')
end
it 'should return empty groups on non-zero pacman exit with a filter' do
expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg git 2>&1').and_return('')
expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(1)
expect(described_class.get_installed_groups(installed_packages, 'git')).to eq({})
end
it 'should return empty groups on empty pacman output' do
pipe = double()
expect(pipe).to receive(:each_line)
expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg 2>&1').and_yield(pipe).and_return('')
expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(0)
expect(described_class.get_installed_groups(installed_packages)).to eq({})
end
it 'should return groups on non-empty pacman output' do
pipe = double()
pipe_expectation = receive(:each_line)
groups.each { |group| pipe_expectation = pipe_expectation.and_yield(*group) }
expect(pipe).to pipe_expectation
expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg 2>&1').and_yield(pipe).and_return('')
expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(0)
expect(described_class.get_installed_groups(installed_packages)).to eq({'foo' => 'package1 1.0, package2 2.0'})
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/package/nim_spec.rb | spec/unit/provider/package/nim_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:nim) do
before(:each) do
@resource = double('resource')
# A catch all; no parameters set
allow(@resource).to receive(:[]).and_return(nil)
# But set name and source
allow(@resource).to receive(:[]).with(:name).and_return("mypackage.foo")
allow(@resource).to receive(:[]).with(:source).and_return("mysource")
allow(@resource).to receive(:[]).with(:ensure).and_return(:installed)
@provider = subject()
@provider.resource = @resource
end
it "should have an install method" do
@provider = subject()
expect(@provider).to respond_to(:install)
end
let(:bff_showres_output) {
Puppet::Util::Execution::ProcessOutput.new(<<END, 0)
mypackage.foo ALL @@I:mypackage.foo _all_filesets
@ 1.2.3.1 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.1
+ 1.2.3.4 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.4
+ 1.2.3.8 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.8
END
}
let(:rpm_showres_output) {
Puppet::Util::Execution::ProcessOutput.new(<<END, 0)
mypackage.foo ALL @@R:mypackage.foo _all_filesets
@@R:mypackage.foo-1.2.3-1 1.2.3-1
@@R:mypackage.foo-1.2.3-4 1.2.3-4
@@R:mypackage.foo-1.2.3-8 1.2.3-8
END
}
context "when installing" do
it "should install a package" do
allow(@resource).to receive(:should).with(:ensure).and_return(:installed)
expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo'").and_return(bff_showres_output)
expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.8")
@provider.install
end
context "when installing versioned packages" do
it "should fail if the package is not available on the lpp source" do
nimclient_showres_output = ""
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.4")
expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.4'").and_return(nimclient_showres_output)
expect {
@provider.install
}.to raise_error(Puppet::Error, "Unable to find package 'mypackage.foo' with version '1.2.3.4' on lpp_source 'mysource'")
end
it "should succeed if a BFF/installp package is available on the lpp source" do
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.4")
expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.4'").and_return(bff_showres_output).ordered
expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.4").ordered
@provider.install
end
it "should fail if the specified version of a BFF package is superseded" do
install_output = <<OUTPUT
+-----------------------------------------------------------------------------+
Pre-installation Verification...
+-----------------------------------------------------------------------------+
Verifying selections...done
Verifying requisites...done
Results...
WARNINGS
--------
Problems described in this section are not likely to be the source of any
immediate or serious failures, but further actions may be necessary or
desired.
Already Installed
-----------------
The number of selected filesets that are either already installed
or effectively installed through superseding filesets is 1. See
the summaries at the end of this installation for details.
NOTE: Base level filesets may be reinstalled using the "Force"
option (-F flag), or they may be removed, using the deinstall or
"Remove Software Products" facility (-u flag), and then reinstalled.
<< End of Warning Section >>
+-----------------------------------------------------------------------------+
BUILDDATE Verification ...
+-----------------------------------------------------------------------------+
Verifying build dates...done
FILESET STATISTICS
------------------
1 Selected to be installed, of which:
1 Already installed (directly or via superseding filesets)
----
0 Total to be installed
Pre-installation Failure/Warning Summary
----------------------------------------
Name Level Pre-installation Failure/Warning
-------------------------------------------------------------------------------
mypackage.foo 1.2.3.1 Already superseded by 1.2.3.4
OUTPUT
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.1")
expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.1'").and_return(bff_showres_output).ordered
expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.1").and_return(install_output).ordered
expect { @provider.install }.to raise_error(Puppet::Error, "NIM package provider is unable to downgrade packages")
end
it "should succeed if an RPM package is available on the lpp source" do
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4")
expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\-4'").and_return(rpm_showres_output).ordered
expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo-1.2.3-4").ordered
@provider.install
end
end
it "should fail if the specified version of a RPM package is superseded" do
install_output = <<OUTPUT
Validating RPM package selections ...
Please wait...
+-----------------------------------------------------------------------------+
RPM Error Summary:
+-----------------------------------------------------------------------------+
The following RPM packages were requested for installation
but they are already installed or superseded by a package installed
at a higher level:
mypackage.foo-1.2.3-1 is superseded by mypackage.foo-1.2.3-4
OUTPUT
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-1")
expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\-1'").and_return(rpm_showres_output)
expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo-1.2.3-1").and_return(install_output)
expect { @provider.install }.to raise_error(Puppet::Error, "NIM package provider is unable to downgrade packages")
end
end
context "when uninstalling" do
it "should call installp to uninstall a bff package" do
expect(@provider).to receive(:lslpp).with("-qLc", "mypackage.foo").and_return("#bos.atm:bos.atm.atmle:7.1.2.0: : :C: :ATM LAN Emulation Client Support : : : : : : :0:0:/:1241")
expect(@provider).to receive(:installp).with("-gu", "mypackage.foo")
expect(@provider.class).to receive(:pkglist).with({:pkgname => 'mypackage.foo'}).and_return(nil)
@provider.uninstall
end
it "should call rpm to uninstall an rpm package" do
expect(@provider).to receive(:lslpp).with("-qLc", "mypackage.foo").and_return("cdrecord:cdrecord-1.9-6:1.9-6: : :C:R:A command line CD/DVD recording program.: :/bin/rpm -e cdrecord: : : : :0: :/opt/freeware:Wed Jun 29 09:41:32 PDT 2005")
expect(@provider).to receive(:rpm).with("-e", "mypackage.foo")
expect(@provider.class).to receive(:pkglist).with({:pkgname => 'mypackage.foo'}).and_return(nil)
@provider.uninstall
end
end
context "when parsing nimclient showres output" do
describe "#parse_showres_output" do
it "should be able to parse installp/BFF package listings" do
packages = subject.send(:parse_showres_output, bff_showres_output)
expect(Set.new(packages.keys)).to eq(Set.new(['mypackage.foo']))
versions = packages['mypackage.foo']
['1.2.3.1', '1.2.3.4', '1.2.3.8'].each do |version|
expect(versions.has_key?(version)).to eq(true)
expect(versions[version]).to eq(:installp)
end
end
it "should be able to parse RPM package listings" do
packages = subject.send(:parse_showres_output, rpm_showres_output)
expect(Set.new(packages.keys)).to eq(Set.new(['mypackage.foo']))
versions = packages['mypackage.foo']
['1.2.3-1', '1.2.3-4', '1.2.3-8'].each do |version|
expect(versions.has_key?(version)).to eq(true)
expect(versions[version]).to eq(:rpm)
end
end
it "should be able to parse RPM package listings with letters in version" do
showres_output = <<END
cairo ALL @@R:cairo _all_filesets
@@R:cairo-1.14.6-2waixX11 1.14.6-2waixX11
END
packages = subject.send(:parse_showres_output, showres_output)
expect(Set.new(packages.keys)).to eq(Set.new(['cairo']))
versions = packages['cairo']
expect(versions.has_key?('1.14.6-2waixX11')).to eq(true)
expect(versions['1.14.6-2waixX11']).to eq(:rpm)
end
it "should raise error when parsing invalid RPM package listings" do
showres_output = <<END
cairo ALL @@R:cairo _all_filesets
@@R:cairo-invalid_version invalid_version
END
expect{ subject.send(:parse_showres_output, showres_output) }.to raise_error(Puppet::Error,
/Unable to parse output from nimclient showres: package string does not match expected rpm package string format/)
end
end
context "#determine_latest_version" do
context "when there are multiple versions" do
it "should return the latest version" do
expect(subject.send(:determine_latest_version, rpm_showres_output, 'mypackage.foo')).to eq([:rpm, '1.2.3-8'])
end
end
context "when there is only one version" do
it "should return the type specifier and `nil` for the version number" do
nimclient_showres_output = <<END
mypackage.foo ALL @@R:mypackage.foo _all_filesets
@@R:mypackage.foo-1.2.3-4 1.2.3-4
END
expect(subject.send(:determine_latest_version, nimclient_showres_output, 'mypackage.foo')).to eq([:rpm, nil])
end
end
end
context "#determine_package_type" do
it "should return :rpm for rpm packages" do
expect(subject.send(:determine_package_type, rpm_showres_output, 'mypackage.foo', '1.2.3-4')).to eq(:rpm)
end
it "should return :installp for installp/bff packages" do
expect(subject.send(:determine_package_type, bff_showres_output, 'mypackage.foo', '1.2.3.4')).to eq(:installp)
end
it "should return :installp for security updates" do
nimclient_showres_output = <<END
bos.net ALL @@S:bos.net _all_filesets
+ 7.2.0.1 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.1
+ 7.2.0.2 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.2
END
expect(subject.send(:determine_package_type, nimclient_showres_output, 'bos.net.tcp.ntp', '7.2.0.2')).to eq(:installp)
end
it "should raise error when invalid header format is given" do
nimclient_showres_output = <<END
bos.net ALL @@INVALID_TYPE:bos.net _all_filesets
+ 7.2.0.1 TCP/IP ntp Applications @@INVALID_TYPE:bos.net.tcp.ntp 7.2.0.1
+ 7.2.0.2 TCP/IP ntp Applications @@INVALID_TYPE:bos.net.tcp.ntp 7.2.0.2
END
expect{ subject.send(:determine_package_type, nimclient_showres_output, 'bos.net.tcp.ntp', '7.2.0.2') }.to raise_error(
Puppet::Error, /Unable to parse output from nimclient showres: line does not match expected package header format/)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/xbps_spec.rb | spec/unit/provider/package/xbps_spec.rb | require "spec_helper"
require "stringio"
describe Puppet::Type.type(:package).provider(:xbps) do
before do
@resource = Puppet::Type.type(:package).new(name: "gcc", provider: "xbps")
@provider = described_class.new(@resource)
@resolver = Puppet::Util
allow(described_class).to receive(:which).with("/usr/bin/xbps-install").and_return("/usr/bin/xbps-install")
allow(described_class).to receive(:which).with("/usr/bin/xbps-remove").and_return("/usr/bin/xbps-remove")
allow(described_class).to receive(:which).with("/usr/bin/xbps-query").and_return("/usr/bin/xbps-query")
end
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_install_options }
it { is_expected.to be_uninstall_options }
it { is_expected.to be_upgradeable }
it { is_expected.to be_holdable }
it { is_expected.to be_virtual_packages }
it "should be the default provider on 'os.name' => Void" do
expect(Facter).to receive(:value).with('os.name').and_return("Void")
expect(described_class.default?).to be_truthy
end
describe "when determining instances" do
it "should return installed packages" do
sample_installed_packages = %{
ii gcc-12.2.0_1 GNU Compiler Collection
ii ruby-devel-3.1.3_1 Ruby programming language - development files
}
expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"])
.and_yield(StringIO.new(sample_installed_packages))
instances = described_class.instances
expect(instances.length).to eq(2)
expect(instances[0].properties).to eq({
:name => "gcc",
:ensure => "12.2.0_1",
:provider => :xbps,
})
expect(instances[1].properties).to eq({
:name => "ruby-devel",
:ensure => "3.1.3_1",
:provider => :xbps,
})
end
it "should warn on invalid input" do
expect(described_class).to receive(:execpipe).and_yield(StringIO.new("blah"))
expect(described_class).to receive(:warning).with('Failed to match line \'blah\'')
expect(described_class.instances).to eq([])
end
end
describe "when installing" do
it "and install_options are given it should call xbps to install the package quietly with the passed options" do
@resource[:install_options] = ["-x", { "--arg" => "value" }]
args = ["-S", "-y", "-x", "--arg=value", @resource[:name]]
expect(@provider).to receive(:xbps_install).with(*args).and_return("")
expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"])
@provider.install
end
it "and source is given it should call xbps to install the package from the source as repository" do
@resource[:source] = "/path/to/xbps/containing/directory"
args = ["-S", "-y", "--repository=#{@resource[:source]}", @resource[:name]]
expect(@provider).to receive(:xbps_install).at_least(:once).with(*args).and_return("")
expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"])
@provider.install
end
end
describe "when updating" do
it "should call install" do
expect(@provider).to receive(:install).and_return("ran install")
expect(@provider.update).to eq("ran install")
end
end
describe "when uninstalling" do
it "should call xbps to remove the right package quietly" do
args = ["-R", "-y", @resource[:name]]
expect(@provider).to receive(:xbps_remove).with(*args).and_return("")
@provider.uninstall
end
it "adds any uninstall_options" do
@resource[:uninstall_options] = ["-x", { "--arg" => "value" }]
args = ["-R", "-y", "-x", "--arg=value", @resource[:name]]
expect(@provider).to receive(:xbps_remove).with(*args).and_return("")
@provider.uninstall
end
end
describe "when determining the latest version" do
it "should return the latest version number of the package" do
@resource[:name] = "ruby-devel"
expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"]).and_yield(StringIO.new(%{
ii ruby-devel-3.1.3_1 Ruby programming language - development files
}))
expect(@provider.latest).to eq("3.1.3_1")
end
end
describe "when querying" do
it "should call self.instances and return nil if the package is missing" do
expect(described_class).to receive(:instances)
.and_return([])
expect(@provider.query).to be_nil
end
it "should get real-package in case allow_virtual is true" do
@resource[:name] = "nodejs-runtime"
@resource[:allow_virtual] = true
expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"])
.and_yield(StringIO.new(""))
args = ["-Rs", @resource[:name]]
expect(@provider).to receive(:xbps_query).with(*args).and_return(%{
[*] nodejs-16.19.0_1 Evented I/O for V8 javascript
[-] nodejs-lts-12.22.10_2 Evented I/O for V8 javascript'
})
expect(@provider.query).to eq({
:name => "nodejs",
:ensure => "16.19.0_1",
:provider => :xbps,
})
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/package/portage_spec.rb | spec/unit/provider/package/portage_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:portage) do
before do
packagename = "sl"
@resource = double('resource', :should => true)
allow(@resource).to receive(:[]).with(:name).and_return(packagename)
allow(@resource).to receive(:[]).with(:install_options).and_return(['--foo', '--bar'])
allow(@resource).to receive(:[]).with(:uninstall_options).and_return(['--foo', { '--bar' => 'baz', '--baz' => 'foo' }])
unslotted_packagename = "dev-lang/ruby"
@unslotted_resource = double('resource', :should => true)
allow(@unslotted_resource).to receive(:should).with(:ensure).and_return(:latest)
allow(@unslotted_resource).to receive(:[]).with(:name).and_return(unslotted_packagename)
allow(@unslotted_resource).to receive(:[]).with(:install_options).and_return([])
slotted_packagename = "dev-lang/ruby:2.1"
@slotted_resource = double('resource', :should => true)
allow(@slotted_resource).to receive(:[]).with(:name).and_return(slotted_packagename)
allow(@slotted_resource).to receive(:[]).with(:install_options).and_return(['--foo', { '--bar' => 'baz', '--baz' => 'foo' }])
versioned_packagename = "=dev-lang/ruby-1.9.3"
@versioned_resource = double('resource', :should => true)
allow(@versioned_resource).to receive(:[]).with(:name).and_return(versioned_packagename)
allow(@versioned_resource).to receive(:[]).with(:install_options).and_return([])
allow(@versioned_resource).to receive(:[]).with(:uninstall_options).and_return([])
versioned_slotted_packagename = "=dev-lang/ruby-1.9.3:1.9"
@versioned_slotted_resource = double('resource', :should => true)
allow(@versioned_slotted_resource).to receive(:[]).with(:name).and_return(versioned_slotted_packagename)
allow(@versioned_slotted_resource).to receive(:[]).with(:install_options).and_return([])
allow(@versioned_slotted_resource).to receive(:[]).with(:uninstall_options).and_return([])
set_packagename = "@system"
@set_resource = double('resource', :should => true)
allow(@set_resource).to receive(:[]).with(:name).and_return(set_packagename)
allow(@set_resource).to receive(:[]).with(:install_options).and_return([])
package_sets = "system\nworld\n"
@provider = described_class.new(@resource)
allow(@provider).to receive(:qatom).and_return({:category=>nil, :pn=>"sl", :pv=>nil, :pr=>nil, :slot=>nil, :pfx=>nil, :sfx=>nil})
allow(@provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets)
@unslotted_provider = described_class.new(@unslotted_resource)
allow(@unslotted_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>nil, :pr=>nil, :slot=>nil, :pfx=>nil, :sfx=>nil})
allow(@unslotted_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets)
@slotted_provider = described_class.new(@slotted_resource)
allow(@slotted_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>nil, :pr=>nil, :slot=>"2.1", :pfx=>nil, :sfx=>nil})
allow(@slotted_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets)
@versioned_provider = described_class.new(@versioned_resource)
allow(@versioned_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>"1.9.3", :pr=>nil, :slot=>nil, :pfx=>"=", :sfx=>nil})
allow(@versioned_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets)
@versioned_slotted_provider = described_class.new(@versioned_slotted_resource)
allow(@versioned_slotted_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>"1.9.3", :pr=>nil, :slot=>"1.9", :pfx=>"=", :sfx=>nil})
allow(@versioned_slotted_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets)
@set_provider = described_class.new(@set_resource)
allow(@set_provider).to receive(:qatom).and_return({:category=>nil, :pn=>"@system", :pv=>nil, :pr=>nil, :slot=>nil, :pfx=>nil, :sfx=>nil})
allow(@set_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets)
portage = double(:executable => "foo",:execute => true)
allow(Puppet::Provider::CommandDefiner).to receive(:define).and_return(portage)
@nomatch_result = ""
@match_result = "app-misc sl [] [5.02] [] [] [5.02] [5.02:0] http://www.tkl.iis.u-tokyo.ac.jp/~toyoda/index_e.html https://github.com/mtoyoda/sl/ sophisticated graphical program which corrects your miss typing\n"
@slot_match_result = "dev-lang ruby [2.1.8] [2.1.9] [2.1.8:2.1] [2.1.8] [2.1.9,,,,,,,] [2.1.9:2.1] http://www.ruby-lang.org/ An object-oriented scripting language\n"
end
it "is versionable" do
expect(described_class).to be_versionable
end
it "is reinstallable" do
expect(described_class).to be_reinstallable
end
it "should be the default provider on 'os.family' => Gentoo" do
expect(Facter).to receive(:value).with('os.family').and_return("Gentoo")
expect(described_class.default?).to be_truthy
end
it 'should support string install options' do
expect(@provider).to receive(:emerge).with('--foo', '--bar', @resource[:name])
@provider.install
end
it 'should support updating' do
expect(@unslotted_provider).to receive(:emerge).with('--update', @unslotted_resource[:name])
@unslotted_provider.install
end
it 'should support hash install options' do
expect(@slotted_provider).to receive(:emerge).with('--foo', '--bar=baz', '--baz=foo', @slotted_resource[:name])
@slotted_provider.install
end
it 'should support hash uninstall options' do
expect(@provider).to receive(:emerge).with('--rage-clean', '--foo', '--bar=baz', '--baz=foo', @resource[:name])
@provider.uninstall
end
it 'should support install of specific version' do
expect(@versioned_provider).to receive(:emerge).with(@versioned_resource[:name])
@versioned_provider.install
end
it 'should support install of specific version and slot' do
expect(@versioned_slotted_provider).to receive(:emerge).with(@versioned_slotted_resource[:name])
@versioned_slotted_provider.install
end
it 'should support uninstall of specific version' do
expect(@versioned_provider).to receive(:emerge).with('--rage-clean', @versioned_resource[:name])
@versioned_provider.uninstall
end
it 'should support uninstall of specific version and slot' do
expect(@versioned_slotted_provider).to receive(:emerge).with('--rage-clean', @versioned_slotted_resource[:name])
@versioned_slotted_provider.uninstall
end
it "uses :emerge to install packages" do
expect(@provider).to receive(:emerge)
@provider.install
end
it "uses query to find the latest package" do
expect(@provider).to receive(:query).and_return({:versions_available => "myversion"})
@provider.latest
end
it "uses eix to search the lastest version of a package" do
allow(@provider).to receive(:update_eix)
expect(@provider).to receive(:eix).and_return(StringIO.new(@match_result))
@provider.query
end
it "allows to emerge package sets" do
expect(@set_provider).to receive(:emerge).with(@set_resource[:name])
@set_provider.install
end
it "allows to emerge and update package sets" do
allow(@set_resource).to receive(:should).with(:ensure).and_return(:latest)
expect(@set_provider).to receive(:emerge).with('--update', @set_resource[:name])
@set_provider.install
end
it "eix arguments must not include --stable" do
expect(@provider.class.eix_search_arguments).not_to include("--stable")
end
it "eix arguments must not include --exact" do
expect(@provider.class.eix_search_arguments).not_to include("--exact")
end
it "query uses default arguments" do
allow(@provider).to receive(:update_eix)
expect(@provider).to receive(:eix).and_return(StringIO.new(@match_result))
expect(@provider.class).to receive(:eix_search_arguments).and_return([])
@provider.query
end
it "can handle search output with empty square brackets" do
allow(@provider).to receive(:update_eix)
expect(@provider).to receive(:eix).and_return(StringIO.new(@match_result))
expect(@provider.query[:name]).to eq("sl")
end
it "can provide the package name without slot" do
expect(@unslotted_provider.qatom[:slot]).to be_nil
end
it "can extract the slot from the package name" do
expect(@slotted_provider.qatom[:slot]).to eq('2.1')
end
it "returns nil for as the slot when no slot is specified" do
expect(@provider.qatom[:slot]).to be_nil
end
it "provides correct package atoms for unslotted packages" do
expect(@versioned_provider.qatom[:pv]).to eq('1.9.3')
end
it "provides correct package atoms for slotted packages" do
expect(@versioned_slotted_provider.qatom[:pfx]).to eq('=')
expect(@versioned_slotted_provider.qatom[:category]).to eq('dev-lang')
expect(@versioned_slotted_provider.qatom[:pn]).to eq('ruby')
expect(@versioned_slotted_provider.qatom[:pv]).to eq('1.9.3')
expect(@versioned_slotted_provider.qatom[:slot]).to eq('1.9')
end
it "can handle search output with slots for unslotted packages" do
allow(@unslotted_provider).to receive(:update_eix)
expect(@unslotted_provider).to receive(:eix).and_return(StringIO.new(@slot_match_result))
result = @unslotted_provider.query
expect(result[:name]).to eq('ruby')
expect(result[:ensure]).to eq('2.1.8')
expect(result[:version_available]).to eq('2.1.9')
end
it "can handle search output with slots" do
allow(@slotted_provider).to receive(:update_eix)
expect(@slotted_provider).to receive(:eix).and_return(StringIO.new(@slot_match_result))
result = @slotted_provider.query
expect(result[:name]).to eq('ruby')
expect(result[:ensure]).to eq('2.1.8')
expect(result[:version_available]).to eq('2.1.9')
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/package/gem_spec.rb | spec/unit/provider/package/gem_spec.rb | require 'spec_helper'
context Puppet::Type.type(:package).provider(:gem) do
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_upgradeable }
it { is_expected.to be_versionable }
it { is_expected.to be_install_options }
it { is_expected.to be_targetable }
let(:provider_gem_cmd) { '/provider/gem' }
let(:execute_options) { {:failonfail => true, :combine => true, :custom_environment => {"HOME"=>ENV["HOME"]}} }
before do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
context 'installing myresource' do
let(:resource) do
Puppet::Type.type(:package).new(
:name => 'myresource',
:ensure => :installed
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
before :each do
resource.provider = provider
allow(described_class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd)
end
context "when installing" do
before :each do
allow(provider).to receive(:rubygem_version).and_return('1.9.9')
end
context 'on windows' do
let(:path) do
"C:\\Program Files\\Puppet Labs\\Puppet\\puppet\\bin;C:\\Program Files\\Puppet Labs\\Puppet\\bin;C:\\Ruby26-x64\\bin;C:\\Windows\\system32\\bin"
end
let(:expected_path) do
"C:\\Program Files\\Puppet Labs\\Puppet\\bin;C:\\Ruby26-x64\\bin;C:\\Windows\\system32\\bin"
end
before do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with('PATH').and_return(path)
allow(described_class).to receive(:validate_command).with(provider_gem_cmd)
stub_const('::File::PATH_SEPARATOR', ';')
end
it 'removes puppet/bin from PATH' do
expect(described_class).to receive(:execute) \
.with(
anything,
hash_including(custom_environment: hash_including(PATH: expected_path))
)
.and_return("")
provider.install
end
end
it "should use the path to the gem command" do
allow(described_class).to receive(:validate_command).with(provider_gem_cmd)
expect(described_class).to receive(:execute).with(be_a(Array), execute_options) { |args| expect(args[0]).to eq(provider_gem_cmd) }.and_return("")
provider.install
end
it "should specify that the gem is being installed" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[0]).to eq("install") }.and_return("")
provider.install
end
it "should specify that --rdoc should not be included when gem version is < 2.0.0" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[1]).to eq("--no-rdoc") }.and_return("")
provider.install
end
it "should specify that --ri should not be included when gem version is < 2.0.0" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[2]).to eq("--no-ri") }.and_return("")
provider.install
end
it "should specify that --document should not be included when gem version is >= 2.0.0" do
allow(provider).to receive(:rubygem_version).and_return('2.0.0')
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[1]).to eq("--no-document") }.and_return("")
provider.install
end
it "should specify the package name" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[3]).to eq("myresource") }.and_return("")
provider.install
end
it "should not append install_options by default" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args.length).to eq(4) }.and_return("")
provider.install
end
it "should allow setting an install_options parameter" do
resource[:install_options] = [ '--force', {'--bindir' => '/usr/bin' } ]
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) do |cmd, args|
expect(args[1]).to eq('--force')
expect(args[2]).to eq('--bindir=/usr/bin')
end.and_return("")
provider.install
end
context "when a source is specified" do
context "as a normal file" do
it "should use the file name instead of the gem name" do
resource[:source] = "/my/file"
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including("/my/file")).and_return("")
provider.install
end
end
context "as a file url" do
it "should use the file name instead of the gem name" do
resource[:source] = "file:///my/file"
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including("/my/file")).and_return("")
provider.install
end
end
context "as a puppet url" do
it "should fail" do
resource[:source] = "puppet://my/file"
expect { provider.install }.to raise_error(Puppet::Error)
end
end
context "as a non-file and non-puppet url" do
it "should treat the source as a gem repository" do
resource[:source] = "http://host/my/file"
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[3..5]).to eq(["--source", "http://host/my/file", "myresource"]) }.and_return("")
provider.install
end
end
context "as a windows path on windows", :if => Puppet::Util::Platform.windows? do
it "should treat the source as a local path" do
resource[:source] = "c:/this/is/a/path/to/a/gem.gem"
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including("c:/this/is/a/path/to/a/gem.gem")).and_return("")
provider.install
end
end
context "with an invalid uri" do
it "should fail" do
expect(URI).to receive(:parse).and_raise(ArgumentError)
resource[:source] = "http:::::uppet:/:/my/file"
expect { provider.install }.to raise_error(Puppet::Error)
end
end
end
end
context "#latest" do
it "should return a single value for 'latest'" do
#gemlist is used for retrieving both local and remote version numbers, and there are cases
# (particularly local) where it makes sense for it to return an array. That doesn't make
# sense for '#latest', though.
expect(provider.class).to receive(:gemlist).with({:command => provider_gem_cmd, :justme => 'myresource'}).and_return({
:name => 'myresource',
:ensure => ["3.0"],
:provider => :gem,
})
expect(provider.latest).to eq("3.0")
end
it "should list from the specified source repository" do
resource[:source] = "http://foo.bar.baz/gems"
expect(provider.class).to receive(:gemlist).
with({:command => provider_gem_cmd, :justme => 'myresource', :source => "http://foo.bar.baz/gems"}).
and_return({
:name => 'myresource',
:ensure => ["3.0"],
:provider => :gem,
})
expect(provider.latest).to eq("3.0")
end
end
context "#instances" do
before do
allow(described_class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd)
end
it "should return an empty array when no gems installed" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return("\n")
expect(described_class.instances).to eq([])
end
it "should return ensure values as an array of installed versions" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(<<-HEREDOC.gsub(/ /, ''))
systemu (1.2.0)
vagrant (0.8.7, 0.6.9)
HEREDOC
expect(described_class.instances.map {|p| p.properties}).to eq([
{:name => "systemu", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.2.0"]},
{:name => "vagrant", :provider => :gem, :command => provider_gem_cmd, :ensure => ["0.8.7", "0.6.9"]}
])
end
it "should ignore platform specifications" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(<<-HEREDOC.gsub(/ /, ''))
systemu (1.2.0)
nokogiri (1.6.1 ruby java x86-mingw32 x86-mswin32-60, 1.4.4.1 x86-mswin32)
HEREDOC
expect(described_class.instances.map {|p| p.properties}).to eq([
{:name => "systemu", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.2.0"]},
{:name => "nokogiri", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.6.1", "1.4.4.1"]}
])
end
it "should not list 'default: ' text from rubygems''" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(<<-HEREDOC.gsub(/ /, ''))
bundler (1.16.1, default: 1.16.0, 1.15.1)
HEREDOC
expect(described_class.instances.map {|p| p.properties}).to eq([
{:name => "bundler", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.16.1", "1.16.0", "1.15.1"]}
])
end
it "should not fail when an unmatched line is returned" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(File.read(my_fixture('line-with-1.8.5-warning')))
expect(described_class.instances.map {|p| p.properties}).
to eq([{:name=>"columnize", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.3.2"]},
{:name=>"diff-lcs", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["1.1.3"]},
{:name=>"metaclass", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.0.1"]},
{:name=>"mocha", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.10.5"]},
{:name=>"rake", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.8.7"]},
{:name=>"rspec-core", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["2.9.0"]},
{:name=>"rspec-expectations", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["2.9.1"]},
{:name=>"rspec-mocks", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["2.9.0"]},
{:name=>"rubygems-bundler", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.9.0"]},
{:name=>"rvm", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["1.11.3.3"]}])
end
end
context "listing gems" do
context "searching for a single package" do
it "searches for an exact match" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including('\Abundler\z')).and_return(File.read(my_fixture('gem-list-single-package')))
expected = {:name=>"bundler", :provider=>:gem, :ensure=>["1.6.2"]}
expect(described_class.gemlist({:command => provider_gem_cmd, :justme => 'bundler'})).to eq(expected)
end
end
end
context 'insync?' do
context 'for array of versions' do
let(:is) { ['1.3.4', '3.6.1', '5.1.2'] }
it 'returns true for ~> 1.3' do
resource[:ensure] = '~> 1.3'
expect(provider).to be_insync(is)
end
it 'returns false for ~> 2' do
resource[:ensure] = '~> 2'
expect(provider).to_not be_insync(is)
end
it 'returns true for > 4' do
resource[:ensure] = '> 4'
expect(provider).to be_insync(is)
end
it 'returns true for 3.6.1' do
resource[:ensure] = '3.6.1'
expect(provider).to be_insync(is)
end
it 'returns false for 3.6.2' do
resource[:ensure] = '3.6.2'
expect(provider).to_not be_insync(is)
end
it 'returns true for >2, <4' do
resource[:ensure] = '>2, <4'
expect(provider).to be_insync(is)
end
it 'returns false for >=4, <5' do
resource[:ensure] = '>=4, <5'
expect(provider).to_not be_insync(is)
end
it 'returns true for >2 <4' do
resource[:ensure] = '>2 <4'
expect(provider).to be_insync(is)
end
it 'returns false for >=4 <5' do
resource[:ensure] = '>=4 <5'
expect(provider).to_not be_insync(is)
end
end
context 'for string version' do
let(:is) { '1.3.4' }
it 'returns true for ~> 1.3' do
resource[:ensure] = '~> 1.3'
expect(provider).to be_insync(is)
end
it 'returns false for ~> 2' do
resource[:ensure] = '~> 2'
expect(provider).to_not be_insync(is)
end
it 'returns false for > 4' do
resource[:ensure] = '> 4'
expect(provider).to_not be_insync(is)
end
it 'returns true for 1.3.4' do
resource[:ensure] = '1.3.4'
expect(provider).to be_insync(is)
end
it 'returns false for 3.6.1' do
resource[:ensure] = '3.6.1'
expect(provider).to_not be_insync(is)
end
it 'returns true for >=1.3, <2' do
resource[:ensure] = '>=1.3, <2'
expect(provider).to be_insync(is)
end
it 'returns false for >1, <=1.3' do
resource[:ensure] = '>1, <=1.3'
expect(provider).to_not be_insync(is)
end
it 'returns true for >=1.3 <2' do
resource[:ensure] = '>=1.3 <2'
expect(provider).to be_insync(is)
end
it 'returns false for >1 <=1.3' do
resource[:ensure] = '>1 <=1.3'
expect(provider).to_not be_insync(is)
end
end
it 'should return false for bad version specifiers' do
resource[:ensure] = 'not a valid gem specifier'
expect(provider).to_not be_insync('1.0')
end
it 'should return false for :absent' do
resource[:ensure] = '~> 1.0'
expect(provider).to_not be_insync(:absent)
end
end
end
context 'installing myresource with a target command' do
let(:resource_gem_cmd) { '/resource/gem' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => "myresource",
:ensure => :installed,
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
before :each do
resource.provider = provider
end
context "when installing with a target command" do
before :each do
allow(described_class).to receive(:which).with(resource_gem_cmd).and_return(resource_gem_cmd)
end
it "should use the path to the other gem" do
resource::original_parameters[:command] = resource_gem_cmd
expect(described_class).to receive(:execute_gem_command).with(resource_gem_cmd, be_a(Array)).twice.and_return("")
provider.install
end
end
end
context 'uninstalling myresource' do
let(:resource) do
Puppet::Type.type(:package).new(
:name => 'myresource',
:ensure => :absent
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
before :each do
resource.provider = provider
allow(described_class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd)
end
context "when uninstalling" do
it "should use the path to the gem command" do
allow(described_class).to receive(:validate_command).with(provider_gem_cmd)
expect(described_class).to receive(:execute).with(be_a(Array), execute_options) { |args| expect(args[0]).to eq(provider_gem_cmd) }.and_return("")
provider.uninstall
end
it "should specify that the gem is being uninstalled" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[0]).to eq("uninstall") }.and_return("")
provider.uninstall
end
it "should specify that the relevant executables should be removed without confirmation" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[1]).to eq("--executables") }.and_return("")
provider.uninstall
end
it "should specify that all the matching versions should be removed" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[2]).to eq("--all") }.and_return("")
provider.uninstall
end
it "should specify the package name" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[3]).to eq("myresource") }.and_return("")
provider.uninstall
end
it "should not append uninstall_options by default" do
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args.length).to eq(4) }.and_return("")
provider.uninstall
end
it "should allow setting an uninstall_options parameter" do
resource[:uninstall_options] = [ '--ignore-dependencies', {'--version' => '0.1.1' } ]
expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) do |cmd, args|
expect(args[4]).to eq('--ignore-dependencies')
expect(args[5]).to eq('--version=0.1.1')
end.and_return('')
provider.uninstall
end
end
end
context 'calculated specificity' do
include_context 'provider specificity'
context 'when is not defaultfor' do
subject { described_class.specificity }
it { is_expected.to eql 1 }
end
context 'when is defaultfor' do
let(:os) { Puppet.runtime[:facter].value('os.name') }
subject do
described_class.defaultfor('os.name': os)
described_class.specificity
end
it { is_expected.to be > 100 }
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/package/aptitude_spec.rb | spec/unit/provider/package/aptitude_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:aptitude) do
let :type do Puppet::Type.type(:package) end
let :pkg do
type.new(:name => 'faff', :provider => :aptitude, :source => '/tmp/faff.deb')
end
it { is_expected.to be_versionable }
context "when retrieving ensure" do
let(:dpkgquery_path) { '/bin/dpkg-query' }
before do
allow(Puppet::Util).to receive(:which).with('/usr/bin/dpkg-query').and_return(dpkgquery_path)
allow(described_class).to receive(:aptmark).with('showmanual', 'faff').and_return("")
end
{ :absent => "deinstall ok config-files faff 1.2.3-1\n",
"1.2.3-1" => "install ok installed faff 1.2.3-1\n",
}.each do |expect, output|
it "detects #{expect} packages" do
expect(Puppet::Util::Execution).to receive(:execute).with(
[dpkgquery_path, '-W', '--showformat', "'${Status} ${Package} ${Version}\\n'", 'faff'],
{:failonfail => true, :combine => true, :custom_environment => {}}
).and_return(Puppet::Util::Execution::ProcessOutput.new(output, 0))
expect(pkg.property(:ensure).retrieve).to eq(expect)
end
end
end
it "installs when asked" do
expect(pkg.provider).to receive(:aptitude).
with('-y', '-o', 'DPkg::Options::=--force-confold', :install, 'faff').
and_return(0)
expect(pkg.provider).to receive(:properties).and_return({:mark => :none})
pkg.provider.install
end
it "purges when asked" do
expect(pkg.provider).to receive(:aptitude).with('-y', 'purge', 'faff').and_return(0)
pkg.provider.purge
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/package/zypper_spec.rb | spec/unit/provider/package/zypper_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:zypper) do
before(:each) do
# Create a mock resource
@resource = double('resource')
# A catch all; no parameters set
allow(@resource).to receive(:[]).and_return(nil)
# But set name and source
allow(@resource).to receive(:[]).with(:name).and_return("mypackage")
allow(@resource).to receive(:[]).with(:ensure).and_return(:installed)
allow(@resource).to receive(:command).with(:zypper).and_return("/usr/bin/zypper")
@provider = described_class.new(@resource)
end
it "should have an install method" do
@provider = described_class.new
expect(@provider).to respond_to(:install)
end
it "should have an uninstall method" do
@provider = described_class.new
expect(@provider).to respond_to(:uninstall)
end
it "should have an update method" do
@provider = described_class.new
expect(@provider).to respond_to(:update)
end
it "should have a latest method" do
@provider = described_class.new
expect(@provider).to respond_to(:latest)
end
it "should have a install_options method" do
@provider = described_class.new
expect(@provider).to respond_to(:install_options)
end
context "when installing with zypper version >= 1.0" do
it "should use a command-line with versioned package'" do
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4.5.6")
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("1.2.8")
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage-1.2.3-4.5.6')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
it "should use a command-line without versioned package" do
allow(@resource).to receive(:should).with(:ensure).and_return(:latest)
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("1.2.8")
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--name', 'mypackage')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
end
context "when installing with zypper version = 0.6.104" do
it "should use a command-line with versioned package'" do
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4.5.6")
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("0.6.104")
expect(@provider).to receive(:zypper).with('--terse', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage-1.2.3-4.5.6')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
it "should use a command-line without versioned package" do
allow(@resource).to receive(:should).with(:ensure).and_return(:latest)
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("0.6.104")
expect(@provider).to receive(:zypper).with('--terse', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
end
context "when installing with zypper version = 0.6.13" do
it "should use a command-line with versioned package'" do
allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4.5.6")
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("0.6.13")
expect(@provider).to receive(:zypper).with('--terse', :install, '--no-confirm', 'mypackage-1.2.3-4.5.6')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
it "should use a command-line without versioned package" do
allow(@resource).to receive(:should).with(:ensure).and_return(:latest)
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("0.6.13")
expect(@provider).to receive(:zypper).with('--terse', :install, '--no-confirm', 'mypackage')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
end
context "when updating" do
it "should call install method of instance" do
expect(@provider).to receive(:install)
@provider.update
end
end
context "when getting latest version" do
after { described_class.reset! }
context "when the package has available update" do
it "should return a version string with valid list-updates data from SLES11sp1" do
fake_data = File.read(my_fixture('zypper-list-updates-SLES11sp1.out'))
allow(@resource).to receive(:[]).with(:name).and_return("at")
expect(described_class).to receive(:zypper).with("list-updates").and_return(fake_data)
expect(@provider.latest).to eq("3.1.8-1069.18.2")
end
end
context "when the package is in the latest version" do
it "should return nil with valid list-updates data from SLES11sp1" do
fake_data = File.read(my_fixture('zypper-list-updates-SLES11sp1.out'))
allow(@resource).to receive(:[]).with(:name).and_return("zypper-log")
expect(described_class).to receive(:zypper).with("list-updates").and_return(fake_data)
expect(@provider.latest).to eq(nil)
end
end
context "when there are no updates available" do
it "should return nil" do
fake_data_empty = File.read(my_fixture('zypper-list-updates-empty.out'))
allow(@resource).to receive(:[]).with(:name).and_return("at")
expect(described_class).to receive(:zypper).with("list-updates").and_return(fake_data_empty)
expect(@provider.latest).to eq(nil)
end
end
end
context "should install a virtual package" do
it "when zypper version = 0.6.13" do
allow(@resource).to receive(:should).with(:ensure).and_return(:installed)
allow(@resource).to receive(:allow_virtual?).and_return(true)
allow(@provider).to receive(:zypper_version).and_return("0.6.13")
expect(@provider).to receive(:zypper).with('--terse', :install, '--no-confirm', 'mypackage')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
it "when zypper version >= 1.0.0" do
allow(@resource).to receive(:should).with(:ensure).and_return(:installed)
allow(@resource).to receive(:allow_virtual?).and_return(true)
allow(@provider).to receive(:zypper_version).and_return("1.2.8")
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage')
expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64")
@provider.install
end
end
context "when installing with zypper install options" do
it "should install the package without checking keys" do
allow(@resource).to receive(:[]).with(:name).and_return("php5")
allow(@resource).to receive(:[]).with(:install_options).and_return(['--no-gpg-check', {'-p' => '/vagrant/files/localrepo/'}])
allow(@resource).to receive(:should).with(:ensure).and_return("5.4.10-4.5.6")
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("1.2.8")
expect(@provider).to receive(:zypper).with('--quiet', '--no-gpg-check', :install,
'--auto-agree-with-licenses', '--no-confirm', '-p=/vagrant/files/localrepo/', 'php5-5.4.10-4.5.6')
expect(@provider).to receive(:query).and_return("php5 0 5.4.10 4.5.6 x86_64")
@provider.install
end
it "should install the package with --no-gpg-checks" do
allow(@resource).to receive(:[]).with(:name).and_return("php5")
allow(@resource).to receive(:[]).with(:install_options).and_return(['--no-gpg-checks', {'-p' => '/vagrant/files/localrepo/'}])
allow(@resource).to receive(:should).with(:ensure).and_return("5.4.10-4.5.6")
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return("1.2.8")
expect(@provider).to receive(:zypper).with('--quiet', '--no-gpg-checks', :install,
'--auto-agree-with-licenses', '--no-confirm', '-p=/vagrant/files/localrepo/', 'php5-5.4.10-4.5.6')
expect(@provider).to receive(:query).and_return("php5 0 5.4.10 4.5.6 x86_64")
@provider.install
end
it "should install package with hash install options" do
allow(@resource).to receive(:[]).with(:name).and_return('vim')
allow(@resource).to receive(:[]).with(:install_options).and_return([{ '--a' => 'foo', '--b' => '"quoted bar"' }])
allow(@resource).to receive(:should).with(:ensure).and_return(:present)
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return('1.2.8')
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--a=foo', '--b="quoted bar"', '--name', 'vim')
expect(@provider).to receive(:query).and_return('package vim is not installed')
@provider.install
end
it "should install package with array install options" do
allow(@resource).to receive(:[]).with(:name).and_return('vim')
allow(@resource).to receive(:[]).with(:install_options).and_return([['--a', '--b', '--c']])
allow(@resource).to receive(:should).with(:ensure).and_return(:present)
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return('1.2.8')
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--a', '--b', '--c', '--name', 'vim')
expect(@provider).to receive(:query).and_return('package vim is not installed')
@provider.install
end
it "should install package with string install options" do
allow(@resource).to receive(:[]).with(:name).and_return('vim')
allow(@resource).to receive(:[]).with(:install_options).and_return(['--a --b --c'])
allow(@resource).to receive(:should).with(:ensure).and_return(:present)
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return('1.2.8')
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--a --b --c', '--name', 'vim')
expect(@provider).to receive(:query).and_return('package vim is not installed')
@provider.install
end
end
context 'when uninstalling' do
it 'should use remove to uninstall on zypper version 1.6 and above' do
allow(@provider).to receive(:zypper_version).and_return('1.6.308')
expect(@provider).to receive(:zypper).with(:remove, '--no-confirm', 'mypackage')
@provider.uninstall
end
it 'should use remove --force-solution to uninstall on zypper versions between 1.0 and 1.6' do
allow(@provider).to receive(:zypper_version).and_return('1.0.2')
expect(@provider).to receive(:zypper).with(:remove, '--no-confirm', '--force-resolution', 'mypackage')
@provider.uninstall
end
end
context 'when installing with VersionRange' do
let(:search_output) { File.read(my_fixture('zypper-search-uninstalled.out')) }
before(:each) do
allow(@resource).to receive(:[]).with(:name).and_return('vim')
allow(@resource).to receive(:allow_virtual?).and_return(false)
allow(@provider).to receive(:zypper_version).and_return('1.0.2')
expect(@provider).to receive(:zypper).with('search', '--match-exact', '--type', 'package', '--uninstalled-only', '-s', 'vim')
.and_return(search_output)
end
it 'does install the package if version is available' do
expect(@resource).to receive(:should).with(:ensure).and_return('>1.0')
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'vim-1.0.20040813-19.9')
expect(@provider).to receive(:query).and_return('vim 0 1.0.20040813 19.9 x86_64')
@provider.install
end
it 'does consider range as version if version in range is not available' do
allow(@resource).to receive(:should).with(:ensure).and_return('>2.0')
expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'vim->2.0')
.and_raise(Puppet::ExecutionFailure.new('My Error'))
expect { @provider.install }.to raise_error(Puppet::ExecutionFailure, 'My Error')
end
end
describe 'insync?' do
subject { @provider.insync?('1.19-2') }
context 'when versions are matching' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19-2') }
it { is_expected.to be true }
end
context 'when version are not matching' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19-3') }
it { is_expected.to be false }
end
context 'when version is in gt range' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-0') }
it { is_expected.to be true }
end
context 'when version is not in gt range' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-2') }
it { is_expected.to be false }
end
context 'when version is in min-max range' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-0 <1.19-3') }
it { is_expected.to be true }
end
context 'when version is not in min-max range' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-0 <1.19-2') }
it { is_expected.to be false }
end
context 'when using eq range' do
context 'when ensure without release' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19') }
it { is_expected.to be true }
end
context 'when ensure with release' do
before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19-2') }
it { is_expected.to be true }
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/provider/package/windows/msi_package_spec.rb | spec/unit/provider/package/windows/msi_package_spec.rb | require 'spec_helper'
require 'puppet/provider/package/windows/msi_package'
describe Puppet::Provider::Package::Windows::MsiPackage do
let (:name) { 'mysql-5.1.58-win-x64' }
let (:version) { '5.1.58' }
let (:source) { 'E:\mysql-5.1.58-win-x64.msi' }
let (:productcode) { '{E437FFB6-5C49-4DAC-ABAE-33FF065FE7CC}' }
let (:packagecode) { '{5A6FD560-763A-4BC1-9E03-B18DFFB7C72C}' }
def expect_installer
inst = double()
expect(inst).to receive(:ProductState).and_return(5)
expect(inst).to receive(:ProductInfo).with(productcode, 'PackageCode').and_return(packagecode)
expect(described_class).to receive(:installer).and_return(inst)
end
context '::installer', :if => Puppet::Util::Platform.windows? do
it 'should return an instance of the COM interface' do
expect(described_class.installer).not_to be_nil
end
end
context '::from_registry' do
it 'should return an instance of MsiPackage' do
expect(described_class).to receive(:valid?).and_return(true)
expect_installer
pkg = described_class.from_registry(productcode, {'DisplayName' => name, 'DisplayVersion' => version})
expect(pkg.name).to eq(name)
expect(pkg.version).to eq(version)
expect(pkg.productcode).to eq(productcode)
expect(pkg.packagecode).to eq(packagecode)
end
it 'should return nil if it is not a valid MSI' do
expect(described_class).to receive(:valid?).and_return(false)
expect(described_class.from_registry(productcode, {})).to be_nil
end
end
context '::valid?' do
let(:values) do { 'DisplayName' => name, 'DisplayVersion' => version, 'WindowsInstaller' => 1 } end
{
'DisplayName' => ['My App', ''],
'WindowsInstaller' => [1, nil],
}.each_pair do |k, arr|
it "should accept '#{k}' with value '#{arr[0]}'" do
values[k] = arr[0]
expect(described_class.valid?(productcode, values)).to be_truthy
end
it "should reject '#{k}' with value '#{arr[1]}'" do
values[k] = arr[1]
expect(described_class.valid?(productcode, values)).to be_falsey
end
end
it 'should reject packages whose name is not a productcode' do
expect(described_class.valid?('AddressBook', values)).to be_falsey
end
it 'should accept packages whose name is a productcode' do
expect(described_class.valid?(productcode, values)).to be_truthy
end
end
context '#match?' do
it 'should match package codes case-insensitively' do
pkg = described_class.new(name, version, productcode, packagecode.upcase)
expect(pkg.match?({:name => packagecode.downcase})).to be_truthy
end
it 'should match product codes case-insensitively' do
pkg = described_class.new(name, version, productcode.upcase, packagecode)
expect(pkg.match?({:name => productcode.downcase})).to be_truthy
end
it 'should match product name' do
pkg = described_class.new(name, version, productcode, packagecode)
expect(pkg.match?({:name => name})).to be_truthy
end
it 'should return false otherwise' do
pkg = described_class.new(name, version, productcode, packagecode)
expect(pkg.match?({:name => 'not going to find it'})).to be_falsey
end
end
context '#install_command' do
it 'should install using the source' do
cmd = described_class.install_command({:source => source})
expect(cmd).to eq(['msiexec.exe', '/qn', '/norestart', '/i', source])
end
end
context '#uninstall_command' do
it 'should uninstall using the productcode' do
pkg = described_class.new(name, version, productcode, packagecode)
expect(pkg.uninstall_command).to eq(['msiexec.exe', '/qn', '/norestart', '/x', productcode])
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/package/windows/package_spec.rb | spec/unit/provider/package/windows/package_spec.rb | require 'spec_helper'
require 'puppet/provider/package/windows/package'
describe Puppet::Provider::Package::Windows::Package do
let(:hklm) { 'HKEY_LOCAL_MACHINE' }
let(:hkcu) { 'HKEY_CURRENT_USER' }
let(:path) { 'Software\Microsoft\Windows\CurrentVersion\Uninstall' }
let(:key) { double('key', :name => "#{hklm}\\#{path}\\Google") }
let(:package) { double('package') }
context '::each' do
it 'should generate an empty enumeration' do
expect(described_class).to receive(:with_key)
expect(described_class.to_a).to be_empty
end
it 'should yield each package it finds' do
expect(described_class).to receive(:with_key).and_yield(key, {})
expect(Puppet::Provider::Package::Windows::MsiPackage).to receive(:from_registry).with('Google', {}).and_return(package)
yielded = nil
described_class.each do |pkg|
yielded = pkg
end
expect(yielded).to eq(package)
end
end
context '::with_key', :if => Puppet::Util::Platform.windows? do
it 'should search HKLM (64 & 32) and HKCU (64 & 32)' do
expect(described_class).to receive(:open).with(hklm, path, described_class::KEY64 | described_class::KEY_READ).ordered
expect(described_class).to receive(:open).with(hklm, path, described_class::KEY32 | described_class::KEY_READ).ordered
expect(described_class).to receive(:open).with(hkcu, path, described_class::KEY64 | described_class::KEY_READ).ordered
expect(described_class).to receive(:open).with(hkcu, path, described_class::KEY32 | described_class::KEY_READ).ordered
described_class.with_key { |key, values| }
end
it 'should ignore file not found exceptions' do
ex = Puppet::Util::Windows::Error.new('Failed to open registry key', Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND)
# make sure we don't stop after the first exception
expect(described_class).to receive(:open).exactly(4).times().and_raise(ex)
keys = []
described_class.with_key { |key, values| keys << key }
expect(keys).to be_empty
end
it 'should raise other types of exceptions' do
ex = Puppet::Util::Windows::Error.new('Failed to open registry key', Puppet::Util::Windows::Error::ERROR_ACCESS_DENIED)
expect(described_class).to receive(:open).and_raise(ex)
expect {
described_class.with_key{ |key, values| }
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(5) # ERROR_ACCESS_DENIED
end
end
end
context '::installer_class' do
it 'should require the source parameter' do
expect {
described_class.installer_class({})
}.to raise_error(Puppet::Error, /The source parameter is required when using the Windows provider./)
end
context 'MSI' do
let (:klass) { Puppet::Provider::Package::Windows::MsiPackage }
it 'should accept source ending in .msi' do
expect(described_class.installer_class({:source => 'foo.msi'})).to eq(klass)
end
it 'should accept quoted source ending in .msi' do
expect(described_class.installer_class({:source => '"foo.msi"'})).to eq(klass)
end
it 'should accept source case insensitively' do
expect(described_class.installer_class({:source => '"foo.MSI"'})).to eq(klass)
end
it 'should reject source containing msi in the name' do
expect {
described_class.installer_class({:source => 'mymsi.txt'})
}.to raise_error(Puppet::Error, /Don't know how to install 'mymsi.txt'/)
end
end
context 'Unknown' do
it 'should reject packages it does not know about' do
expect {
described_class.installer_class({:source => 'basram'})
}.to raise_error(Puppet::Error, /Don't know how to install 'basram'/)
end
end
end
context '::munge' do
it 'should shell quote strings with spaces and fix forward slashes' do
expect(described_class.munge('c:/windows/the thing')).to eq('"c:\windows\the thing"')
end
it 'should leave properly formatted paths alone' do
expect(described_class.munge('c:\windows\thething')).to eq('c:\windows\thething')
end
end
context '::replace_forward_slashes' do
it 'should replace forward with back slashes' do
expect(described_class.replace_forward_slashes('c:/windows/thing/stuff')).to eq('c:\windows\thing\stuff')
end
end
context '::quote' do
it 'should shell quote strings with spaces' do
expect(described_class.quote('foo bar')).to eq('"foo bar"')
end
it 'should shell quote strings with spaces and quotes' do
expect(described_class.quote('"foo bar" baz')).to eq('"\"foo bar\" baz"')
end
it 'should not shell quote strings without spaces' do
expect(described_class.quote('"foobar"')).to eq('"foobar"')
end
end
context '::get_display_name' do
it 'should return nil if values is nil' do
expect(described_class.get_display_name(nil)).to be_nil
end
it 'should return empty if values is empty' do
reg_values = {}
expect(described_class.get_display_name(reg_values)).to eq('')
end
it 'should return DisplayName when available' do
reg_values = { 'DisplayName' => 'Google' }
expect(described_class.get_display_name(reg_values)).to eq('Google')
end
it 'should return DisplayName when available, even when QuietDisplayName is also available' do
reg_values = { 'DisplayName' => 'Google', 'QuietDisplayName' => 'Google Quiet' }
expect(described_class.get_display_name(reg_values)).to eq('Google')
end
it 'should return QuietDisplayName when available if DisplayName is empty' do
reg_values = { 'DisplayName' => '', 'QuietDisplayName' =>'Google Quiet' }
expect(described_class.get_display_name(reg_values)).to eq('Google Quiet')
end
it 'should return QuietDisplayName when DisplayName is not available' do
reg_values = { 'QuietDisplayName' =>'Google Quiet' }
expect(described_class.get_display_name(reg_values)).to eq('Google Quiet')
end
it 'should return empty when DisplayName is empty and QuietDisplay name is not available' do
reg_values = { 'DisplayName' => '' }
expect(described_class.get_display_name(reg_values)).to eq('')
end
it 'should return empty when DisplayName is empty and QuietDisplay name is empty' do
reg_values = { 'DisplayName' => '', 'QuietDisplayName' =>'' }
expect(described_class.get_display_name(reg_values)).to eq('')
end
end
it 'should implement instance methods' do
pkg = described_class.new('orca', '5.0')
expect(pkg.name).to eq('orca')
expect(pkg.version).to eq('5.0')
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/package/windows/exe_package_spec.rb | spec/unit/provider/package/windows/exe_package_spec.rb | require 'spec_helper'
require 'puppet/provider/package/windows/exe_package'
require 'puppet/provider/package/windows'
describe Puppet::Provider::Package::Windows::ExePackage do
let (:name) { 'Git version 1.7.11' }
let (:version) { '1.7.11' }
let (:source) { 'E:\Git-1.7.11.exe' }
let (:uninstall) { '"C:\Program Files (x86)\Git\unins000.exe" /SP-' }
context '::from_registry' do
it 'should return an instance of ExePackage' do
expect(described_class).to receive(:valid?).and_return(true)
pkg = described_class.from_registry('', {'DisplayName' => name, 'DisplayVersion' => version, 'UninstallString' => uninstall})
expect(pkg.name).to eq(name)
expect(pkg.version).to eq(version)
expect(pkg.uninstall_string).to eq(uninstall)
end
it 'should return nil if it is not a valid executable' do
expect(described_class).to receive(:valid?).and_return(false)
expect(described_class.from_registry('', {})).to be_nil
end
end
context '::valid?' do
let(:name) { 'myproduct' }
let(:values) do { 'DisplayName' => name, 'UninstallString' => uninstall } end
{
'DisplayName' => ['My App', ''],
'UninstallString' => ['E:\uninstall.exe', ''],
'WindowsInstaller' => [nil, 1],
'ParentKeyName' => [nil, 'Uber Product'],
'Security Update' => [nil, 'KB890830'],
'Update Rollup' => [nil, 'Service Pack 42'],
'Hotfix' => [nil, 'QFE 42']
}.each_pair do |k, arr|
it "should accept '#{k}' with value '#{arr[0]}'" do
values[k] = arr[0]
expect(described_class.valid?(name, values)).to be_truthy
end
it "should reject '#{k}' with value '#{arr[1]}'" do
values[k] = arr[1]
expect(described_class.valid?(name, values)).to be_falsey
end
end
it 'should reject packages whose name starts with "KBXXXXXX"' do
expect(described_class.valid?('KB890830', values)).to be_falsey
end
it 'should accept packages whose name does not start with "KBXXXXXX"' do
expect(described_class.valid?('My Update (KB890830)', values)).to be_truthy
end
end
context '#match?' do
let(:pkg) { described_class.new(name, version, uninstall) }
it 'should match product name' do
expect(pkg.match?({:name => name})).to be_truthy
end
it 'should return false otherwise' do
expect(pkg.match?({:name => 'not going to find it'})).to be_falsey
end
end
context '#install_command' do
it 'should install using the source' do
allow(Puppet::FileSystem).to receive(:exist?).with(source).and_return(true)
cmd = described_class.install_command({:source => source})
expect(cmd).to eq(source)
end
it 'should raise error when URI is invalid' do
web_source = 'https://www.t e s t.test/test.exe'
expect do
described_class.install_command({:source => web_source, :name => name})
end.to raise_error(Puppet::Error, /Error when installing #{name}:/)
end
it 'should download package from source file before installing', if: Puppet::Util::Platform.windows? do
web_source = 'https://www.test.test/test.exe'
stub_request(:get, web_source).to_return(status: 200, body: 'package binaries')
cmd = described_class.install_command({:source => web_source})
expect(File.read(cmd)).to eq('package binaries')
end
end
context '#uninstall_command' do
['C:\uninstall.exe', 'C:\Program Files\uninstall.exe'].each do |exe|
it "should quote #{exe}" do
expect(described_class.new(name, version, exe).uninstall_command).to eq(
"\"#{exe}\""
)
end
end
['"C:\Program Files\uninstall.exe"', '"C:\Program Files (x86)\Git\unins000.exe" /SILENT"'].each do |exe|
it "should not quote #{exe}" do
expect(described_class.new(name, version, exe).uninstall_command).to eq(
exe
)
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/file_bucket/file_spec.rb | spec/unit/file_bucket/file_spec.rb | require 'spec_helper'
require 'puppet/file_bucket/file'
describe Puppet::FileBucket::File, :uses_checksums => true do
include PuppetSpec::Files
# this is the default from spec_helper, but it keeps getting reset at odd times
let(:bucketdir) { Puppet[:bucketdir] = tmpdir('bucket') }
it "defaults to serializing to `:binary`" do
expect(Puppet::FileBucket::File.default_format).to eq(:binary)
end
it "only accepts binary" do
expect(Puppet::FileBucket::File.supported_formats).to eq([:binary])
end
describe "making round trips through network formats" do
with_digest_algorithms do
it "can make a round trip through `binary`" do
file = Puppet::FileBucket::File.new(plaintext)
tripped = Puppet::FileBucket::File.convert_from(:binary, file.render)
expect(tripped.contents).to eq(plaintext)
end
end
end
it "should require contents to be a string" do
expect { Puppet::FileBucket::File.new(5) }.to raise_error(ArgumentError, /contents must be a String or Pathname, got a Integer$/)
end
it "should complain about options other than :bucket_path" do
expect {
Puppet::FileBucket::File.new('5', :crazy_option => 'should not be passed')
}.to raise_error(ArgumentError, /Unknown option\(s\): crazy_option/)
end
with_digest_algorithms do
it "it uses #{metadata[:digest_algorithm]} as the configured digest algorithm" do
file = Puppet::FileBucket::File.new(plaintext)
expect(file.contents).to eq(plaintext)
expect(file.checksum_type).to eq(digest_algorithm)
expect(file.checksum).to eq("{#{digest_algorithm}}#{checksum}")
expect(file.name).to eq("#{digest_algorithm}/#{checksum}")
end
end
describe "when using back-ends" do
it "should redirect using Puppet::Indirector" do
expect(Puppet::Indirector::Indirection.instance(:file_bucket_file).model).to equal(Puppet::FileBucket::File)
end
it "should have a :save instance method" do
expect(Puppet::FileBucket::File.indirection).to respond_to(:save)
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/file_bucket/dipper_spec.rb | spec/unit/file_bucket/dipper_spec.rb | require 'spec_helper'
require 'pathname'
require 'puppet/file_bucket/dipper'
require 'puppet/indirector/file_bucket_file/rest'
require 'puppet/indirector/file_bucket_file/file'
require 'puppet/util/checksums'
shared_examples_for "a restorable file" do
let(:dest) { tmpfile('file_bucket_dest') }
describe "restoring the file" do
with_digest_algorithms do
it "should restore the file" do
request = nil
# With the *_any_instance_of form of using a block on receive, the
# first argument to the block is which instance is currently being
# dealt with, and the remaining arguments are the arguments to the
# method, instead of the block only getting the arguments to the
# method.
expect_any_instance_of(klass).to receive(:find) { |_,r| request = r }.and_return(Puppet::FileBucket::File.new(plaintext))
expect(dipper.restore(dest, checksum)).to eq(checksum)
expect(digest(Puppet::FileSystem.binread(dest))).to eq(checksum)
expect(request.key).to eq("#{digest_algorithm}/#{checksum}")
expect(request.server).to eq(server)
expect(request.port).to eq(port)
end
it "should skip restoring if existing file has the same checksum" do
File.open(dest, 'wb') {|f| f.print(plaintext) }
expect(dipper).not_to receive(:getfile)
expect(dipper.restore(dest, checksum)).to be_nil
end
it "should overwrite existing file if it has different checksum" do
expect_any_instance_of(klass).to receive(:find).and_return(Puppet::FileBucket::File.new(plaintext))
File.open(dest, 'wb') {|f| f.print('other contents') }
expect(dipper.restore(dest, checksum)).to eq(checksum)
end
end
end
end
describe Puppet::FileBucket::Dipper, :uses_checksums => true do
include PuppetSpec::Files
def make_tmp_file(contents)
file = tmpfile("file_bucket_file")
File.open(file, 'wb') { |f| f.write(contents) }
file
end
it "should fail in an informative way when there are failures checking for the file on the server" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => make_absolute("/my/bucket"))
file = make_tmp_file('contents')
expect(Puppet::FileBucket::File.indirection).to receive(:head).and_raise(ArgumentError)
expect { @dipper.backup(file) }.to raise_error(Puppet::Error)
end
it "should fail in an informative way when there are failures backing up to the server" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => make_absolute("/my/bucket"))
file = make_tmp_file('contents')
expect(Puppet::FileBucket::File.indirection).to receive(:head).and_return(false)
expect(Puppet::FileBucket::File.indirection).to receive(:save).and_raise(ArgumentError)
expect { @dipper.backup(file) }.to raise_error(Puppet::Error)
end
describe "when diffing on a local filebucket" do
describe "in non-windows environments or JRuby", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do
with_digest_algorithms do
it "should fail in an informative way when one or more checksum doesn't exists" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => tmpdir("bucket"))
wrong_checksum = "DEADBEEF"
# First checksum fails
expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(RuntimeError, "Invalid checksum #{wrong_checksum.inspect}")
file = make_tmp_file(plaintext)
@dipper.backup(file)
#Diff_with checksum fails
expect { @dipper.diff(checksum, wrong_checksum, nil, nil) }.to raise_error(RuntimeError, "could not find diff_with #{wrong_checksum}")
end
it "should properly diff files on the filebucket" do
file1 = make_tmp_file("OriginalContent\n")
file2 = make_tmp_file("ModifiedContent\n")
@dipper = Puppet::FileBucket::Dipper.new(:Path => tmpdir("bucket"))
checksum1 = @dipper.backup(file1)
checksum2 = @dipper.backup(file2)
# Diff without the context
# Lines we need to see match 'Content' instead of trimming diff output filter out
# surrounding noise...or hard code the check values
if Puppet.runtime[:facter].value('os.family') == 'Solaris' &&
Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.full'), '11.0') >= 0
# Use gdiff on Solaris
diff12 = Puppet::Util::Execution.execute("gdiff -uN #{file1} #{file2}| grep Content")
diff21 = Puppet::Util::Execution.execute("gdiff -uN #{file2} #{file1}| grep Content")
else
diff12 = Puppet::Util::Execution.execute("diff -uN #{file1} #{file2}| grep Content")
diff21 = Puppet::Util::Execution.execute("diff -uN #{file2} #{file1}| grep Content")
end
expect(@dipper.diff(checksum1, checksum2, nil, nil)).to include(diff12)
expect(@dipper.diff(checksum1, nil, nil, file2)).to include(diff12)
expect(@dipper.diff(nil, checksum2, file1, nil)).to include(diff12)
expect(@dipper.diff(nil, nil, file1, file2)).to include(diff12)
expect(@dipper.diff(checksum2, checksum1, nil, nil)).to include(diff21)
expect(@dipper.diff(checksum2, nil, nil, file1)).to include(diff21)
expect(@dipper.diff(nil, checksum1, file2, nil)).to include(diff21)
expect(@dipper.diff(nil, nil, file2, file1)).to include(diff21)
end
end
describe "in windows environment", :if => Puppet::Util::Platform.windows? do
it "should fail in an informative way when trying to diff" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => tmpdir("bucket"))
wrong_checksum = "DEADBEEF"
# First checksum fails
expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform")
# Diff_with checksum fails
expect { @dipper.diff(checksum, wrong_checksum, nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform")
end
end
end
end
it "should fail in an informative way when there are failures listing files on the server" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => "/unexistent/bucket")
expect(Puppet::FileBucket::File.indirection).to receive(:find).and_return(nil)
expect { @dipper.list(nil, nil) }.to raise_error(Puppet::Error)
end
describe "listing files in local filebucket" do
with_digest_algorithms do
it "should list all files present" do
if Puppet::Util::Platform.windows? && digest_algorithm == "sha512"
skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names"
end
Puppet[:bucketdir] = "/my/bucket"
file_bucket = tmpdir("bucket")
@dipper = Puppet::FileBucket::Dipper.new(:Path => file_bucket)
#First File
file1 = make_tmp_file(plaintext)
real_path = Pathname.new(file1).realpath
expect(digest(plaintext)).to eq(checksum)
expect(@dipper.backup(file1)).to eq(checksum)
expected_list1_1 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/
File.open(file1, 'w') {|f| f.write("Blahhhh")}
new_checksum = digest("Blahhhh")
expect(@dipper.backup(file1)).to eq(new_checksum)
expected_list1_2 = /#{new_checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/
#Second File
content = "DummyFileWithNonSenseTextInIt"
file2 = make_tmp_file(content)
real_path = Pathname.new(file2).realpath
checksum = digest(content)
expect(@dipper.backup(file2)).to eq(checksum)
expected_list2 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/
#Third file : Same as the first one with a different path
file3 = make_tmp_file(plaintext)
real_path = Pathname.new(file3).realpath
checksum = digest(plaintext)
expect(digest(plaintext)).to eq(checksum)
expect(@dipper.backup(file3)).to eq(checksum)
expected_list3 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/
result = @dipper.list(nil, nil)
expect(result).to match(expected_list1_1)
expect(result).to match(expected_list1_2)
expect(result).to match(expected_list2)
expect(result).to match(expected_list3)
end
it "should filter with the provided dates" do
if Puppet::Util::Platform.windows? && digest_algorithm == "sha512"
skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names"
end
Puppet[:bucketdir] = "/my/bucket"
file_bucket = tmpdir("bucket")
twentyminutes=60*20
thirtyminutes=60*30
onehour=60*60
twohours=onehour*2
threehours=onehour*3
# First File created now
@dipper = Puppet::FileBucket::Dipper.new(:Path => file_bucket)
file1 = make_tmp_file(plaintext)
real_path = Pathname.new(file1).realpath
expect(digest(plaintext)).to eq(checksum)
expect(@dipper.backup(file1)).to eq(checksum)
expected_list1 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/
# Second File created an hour ago
content = "DummyFileWithNonSenseTextInIt"
file2 = make_tmp_file(content)
real_path = Pathname.new(file2).realpath
checksum = digest(content)
expect(@dipper.backup(file2)).to eq(checksum)
# Modify mtime of the second file to be an hour ago
onehourago = Time.now - onehour
bucketed_paths_file = Dir.glob("#{file_bucket}/**/#{checksum}/paths")
FileUtils.touch(bucketed_paths_file, mtime: onehourago)
expected_list2 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/
now = Time.now
#Future
expect(@dipper.list((now + threehours).strftime("%F %T"), nil )).to eq("")
#Epoch -> Future = Everything (Sorted (desc) by date)
expect(@dipper.list(nil, (now + twohours).strftime("%F %T"))).to match(expected_list1)
expect(@dipper.list(nil, (now + twohours).strftime("%F %T"))).to match(expected_list2)
#Now+1sec -> Future = Nothing
expect(@dipper.list((now + 1).strftime("%F %T"), (now + twohours).strftime("%F %T"))).to eq("")
#Now-30mins -> Now-20mins = Nothing
expect(@dipper.list((now - thirtyminutes).strftime("%F %T"), (now - twentyminutes).strftime("%F %T"))).to eq("")
#Now-2hours -> Now-30mins = Second file only
expect(@dipper.list((now - twohours).strftime("%F %T"), (now - thirtyminutes).strftime("%F %T"))).to match(expected_list2)
expect(@dipper.list((now - twohours).strftime("%F %T"), (now - thirtyminutes).strftime("%F %T"))).not_to match(expected_list1)
#Now-30minutes -> Now = First file only
expect(@dipper.list((now - thirtyminutes).strftime("%F %T"), now.strftime("%F %T"))).to match(expected_list1)
expect(@dipper.list((now - thirtyminutes).strftime("%F %T"), now.strftime("%F %T"))).not_to match(expected_list2)
end
end
end
describe "when diffing on a remote filebucket" do
describe "in non-windows environments", :unless => Puppet::Util::Platform.windows? do
with_digest_algorithms do
it "should fail in an informative way when one or more checksum doesn't exists" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337")
wrong_checksum = "DEADBEEF"
expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:find).and_return(nil)
expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(Puppet::Error, "Failed to diff files")
end
it "should properly diff files on the filebucket" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337")
expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:find).and_return("Probably valid diff")
expect(@dipper.diff("checksum1", "checksum2", nil, nil)).to eq("Probably valid diff")
end
end
end
describe "in windows environment", :if => Puppet::Util::Platform.windows? do
it "should fail in an informative way when trying to diff" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337")
wrong_checksum = "DEADBEEF"
expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform")
expect { @dipper.diff(wrong_checksum, nil, nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform")
end
end
end
describe "listing files in remote filebucket" do
it "is not allowed" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port=> "31337")
expect {
@dipper.list(nil, nil)
}.to raise_error(Puppet::Error, "Listing remote file buckets is not allowed")
end
end
describe "backing up and retrieving local files" do
with_digest_algorithms do
it "should backup files to a local bucket" do
if Puppet::Util::Platform.windows? && digest_algorithm == "sha512"
skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names"
end
Puppet[:bucketdir] = "/non/existent/directory"
file_bucket = tmpdir("bucket")
@dipper = Puppet::FileBucket::Dipper.new(:Path => file_bucket)
file = make_tmp_file(plaintext)
expect(digest(plaintext)).to eq(checksum)
expect(@dipper.backup(file)).to eq(checksum)
expect(Puppet::FileSystem.exist?("#{file_bucket}/#{bucket_dir}/contents")).to eq(true)
end
it "should not backup a file that is already in the bucket" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => "/my/bucket")
file = make_tmp_file(plaintext)
expect(Puppet::FileBucket::File.indirection).to receive(:head).with(
%r{#{digest_algorithm}/#{checksum}}, {:bucket_path => "/my/bucket"}
).and_return(true)
expect(Puppet::FileBucket::File.indirection).not_to receive(:save)
expect(@dipper.backup(file)).to eq(checksum)
end
it "should retrieve files from a local bucket" do
@dipper = Puppet::FileBucket::Dipper.new(:Path => "/my/bucket")
request = nil
expect_any_instance_of(Puppet::FileBucketFile::File).to receive(:find) { |_,r| request = r }.once.and_return(Puppet::FileBucket::File.new(plaintext))
expect(@dipper.getfile(checksum)).to eq(plaintext)
expect(request.key).to eq("#{digest_algorithm}/#{checksum}")
end
end
end
describe "backing up and retrieving remote files" do
with_digest_algorithms do
it "should backup files to a remote server" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337")
file = make_tmp_file(plaintext)
real_path = Pathname.new(file).realpath
request1 = nil
request2 = nil
expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:head) { |_,r| request1 = r }.once.and_return(nil)
expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:save) { |_,r| request2 = r }.once
expect(@dipper.backup(file)).to eq(checksum)
[request1, request2].each do |r|
expect(r.server).to eq('puppetmaster')
expect(r.port).to eq(31337)
expect(r.key).to eq("#{digest_algorithm}/#{checksum}/#{real_path}")
end
end
it "should retrieve files from a remote server" do
@dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337")
request = nil
expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:find) { |_,r| request = r }.and_return(Puppet::FileBucket::File.new(plaintext))
expect(@dipper.getfile(checksum)).to eq(plaintext)
expect(request.server).to eq('puppetmaster')
expect(request.port).to eq(31337)
expect(request.key).to eq("#{digest_algorithm}/#{checksum}")
end
end
end
describe "#restore" do
describe "when restoring from a remote server" do
let(:klass) { Puppet::FileBucketFile::Rest }
let(:server) { "puppetmaster" }
let(:port) { 31337 }
it_behaves_like "a restorable file" do
let (:dipper) { Puppet::FileBucket::Dipper.new(:Server => server, :Port => port.to_s) }
end
end
describe "when restoring from a local server" do
let(:klass) { Puppet::FileBucketFile::File }
let(:server) { nil }
let(:port) { nil }
it_behaves_like "a restorable file" do
let (:dipper) { Puppet::FileBucket::Dipper.new(:Path => "/my/bucket") }
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/ssl/certificate_request_attributes_spec.rb | spec/unit/ssl/certificate_request_attributes_spec.rb | require 'spec_helper'
require 'puppet/ssl/certificate_request_attributes'
describe Puppet::SSL::CertificateRequestAttributes do
include PuppetSpec::Files
let(:expected) do
{
"custom_attributes" => {
"1.3.6.1.4.1.34380.2.2"=>[3232235521, 3232235777], # system IPs in hex
"1.3.6.1.4.1.34380.2.0"=>"hostname.domain.com",
"1.3.6.1.4.1.34380.1.1.3"=>:node_image_name,
# 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
"1.2.840.113549.1.9.7"=>"utf8passwordA\u06FF\u16A0\u{2070E}"
}
}
end
let(:csr_attributes_hash) { expected.dup }
let(:csr_attributes_path) { tmpfile('csr_attributes.yaml') }
let(:csr_attributes) { Puppet::SSL::CertificateRequestAttributes.new(csr_attributes_path) }
it "initializes with a path" do
expect(csr_attributes.path).to eq(csr_attributes_path)
end
describe "loading" do
it "returns nil when loading from a non-existent file" do
nonexistent = Puppet::SSL::CertificateRequestAttributes.new('/does/not/exist.yaml')
expect(nonexistent.load).to be_falsey
end
context "with an available attributes file" do
before do
Puppet::Util::Yaml.dump(csr_attributes_hash, csr_attributes_path)
end
it "loads csr attributes from a file when the file is present" do
expect(csr_attributes.load).to be_truthy
end
it "exposes custom_attributes" do
csr_attributes.load
expect(csr_attributes.custom_attributes).to eq(expected['custom_attributes'])
end
it "returns an empty hash if custom_attributes points to nil" do
Puppet::Util::Yaml.dump({'custom_attributes' => nil }, csr_attributes_path)
csr_attributes.load
expect(csr_attributes.custom_attributes).to eq({})
end
it "returns an empty hash if custom_attributes key is not present" do
Puppet::Util::Yaml.dump({}, csr_attributes_path)
csr_attributes.load
expect(csr_attributes.custom_attributes).to eq({})
end
it "raises a Puppet::Error if an unexpected root key is defined" do
csr_attributes_hash['unintentional'] = 'data'
Puppet::Util::Yaml.dump(csr_attributes_hash, csr_attributes_path)
expect {
csr_attributes.load
}.to raise_error(Puppet::Error, /unexpected attributes.*unintentional/)
end
it "raises a Puppet::Util::Yaml::YamlLoadError if an unexpected ruby object is present" do
csr_attributes_hash['custom_attributes']['whoops'] = Object.new
Puppet::Util::Yaml.dump(csr_attributes_hash, csr_attributes_path)
expect {
csr_attributes.load
}.to raise_error(Puppet::Util::Yaml::YamlLoadError, /Tried to load unspecified class: Object/)
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/ssl/certificate_request_spec.rb | spec/unit/ssl/certificate_request_spec.rb | require 'spec_helper'
require 'puppet/ssl/certificate_request'
describe Puppet::SSL::CertificateRequest do
let(:request) { described_class.new("myname") }
let(:key) { OpenSSL::PKey::RSA.new(Puppet[:keylength]) }
it "should use any provided name as its name" do
expect(described_class.new("myname").name).to eq("myname")
end
it "should only support the text format" do
expect(described_class.supported_formats).to eq([:s])
end
describe "when converting from a string" do
it "should create a CSR instance with its name set to the CSR subject and its content set to the extracted CSR" do
csr = double('csr',
:subject => OpenSSL::X509::Name.parse("/CN=Foo.madstop.com"),
:is_a? => true)
expect(OpenSSL::X509::Request).to receive(:new).with("my csr").and_return(csr)
mycsr = double('sslcsr')
expect(mycsr).to receive(:content=).with(csr)
expect(described_class).to receive(:new).with("Foo.madstop.com").and_return(mycsr)
described_class.from_s("my csr")
end
end
describe "when managing instances" do
it "should have a name attribute" do
expect(request.name).to eq("myname")
end
it "should downcase its name" do
expect(described_class.new("MyName").name).to eq("myname")
end
it "should have a content attribute" do
expect(request).to respond_to(:content)
end
it "should be able to read requests from disk" do
path = "/my/path"
expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding::ASCII}).and_return("my request")
my_req = double('request')
expect(OpenSSL::X509::Request).to receive(:new).with("my request").and_return(my_req)
expect(request.read(path)).to equal(my_req)
expect(request.content).to equal(my_req)
end
it "should return an empty string when converted to a string with no request" do
expect(request.to_s).to eq("")
end
it "should convert the request to pem format when converted to a string", :unless => RUBY_PLATFORM == 'java' do
request.generate(key)
expect(request.to_s).to eq(request.content.to_pem)
end
it "should have a :to_text method that it delegates to the actual key" do
real_request = double('request')
expect(real_request).to receive(:to_text).and_return("requesttext")
request.content = real_request
expect(request.to_text).to eq("requesttext")
end
end
describe "when generating", :unless => RUBY_PLATFORM == 'java' do
it "should verify the CSR using the public key associated with the private key" do
request.generate(key)
expect(request.content.verify(key.public_key)).to be_truthy
end
it "should set the version to 0" do
request.generate(key)
expect(request.content.version).to eq(0)
end
it "should set the public key to the provided key's public key" do
request.generate(key)
# The openssl bindings do not define equality on keys so we use to_s
expect(request.content.public_key.to_s).to eq(key.public_key.to_s)
end
context "without subjectAltName / dns_alt_names" do
before :each do
Puppet[:dns_alt_names] = ""
end
["extreq", "msExtReq"].each do |name|
it "should not add any #{name} attribute" do
request.generate(key)
expect(request.content.attributes.find do |attr|
attr.oid == name
end).not_to be
end
it "should return no subjectAltNames" do
request.generate(key)
expect(request.subject_alt_names).to be_empty
end
end
end
context "with dns_alt_names" do
before :each do
Puppet[:dns_alt_names] = "one, two, three"
end
["extreq", "msExtReq"].each do |name|
it "should not add any #{name} attribute" do
request.generate(key)
expect(request.content.attributes.find do |attr|
attr.oid == name
end).not_to be
end
it "should return no subjectAltNames" do
request.generate(key)
expect(request.subject_alt_names).to be_empty
end
end
end
context "with subjectAltName to generate request" do
before :each do
Puppet[:dns_alt_names] = ""
end
it "should add an extreq attribute" do
request.generate(key, :dns_alt_names => 'one, two')
extReq = request.content.attributes.find do |attr|
attr.oid == 'extReq'
end
expect(extReq).to be
extReq.value.value.all? do |x|
x.value.all? do |y|
expect(y.value[0].value).to eq("subjectAltName")
end
end
end
it "should return the subjectAltName values" do
request.generate(key, :dns_alt_names => 'one,two')
expect(request.subject_alt_names).to match_array(["DNS:myname", "DNS:one", "DNS:two"])
end
end
context "with DNS and IP SAN specified" do
before :each do
Puppet[:dns_alt_names] = ""
end
it "should return the subjectAltName values" do
request.generate(key, :dns_alt_names => 'DNS:foo, bar, IP:172.16.254.1')
expect(request.subject_alt_names).to match_array(["DNS:bar", "DNS:foo", "DNS:myname", "IP Address:172.16.254.1"])
end
end
context "with custom CSR attributes" do
it "adds attributes with single values" do
csr_attributes = {
'1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info',
'1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info',
}
request.generate(key, :csr_attributes => csr_attributes)
attrs = request.custom_attributes
expect(attrs).to include({'oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'CSR specific info'})
expect(attrs).to include({'oid' => '1.3.6.1.4.1.34380.1.2.2', 'value' => 'more CSR specific info'})
end
['extReq', '1.2.840.113549.1.9.14'].each do |oid|
it "doesn't overwrite standard PKCS#9 CSR attribute '#{oid}'" do
expect do
request.generate(key, :csr_attributes => {oid => 'data'})
end.to raise_error ArgumentError, /Cannot specify.*#{oid}/
end
end
['msExtReq', '1.3.6.1.4.1.311.2.1.14'].each do |oid|
it "doesn't overwrite Microsoft extension request OID '#{oid}'" do
expect do
request.generate(key, :csr_attributes => {oid => 'data'})
end.to raise_error ArgumentError, /Cannot specify.*#{oid}/
end
end
it "raises an error if an attribute cannot be created" do
csr_attributes = { "thats.no.moon" => "death star" }
expect do
request.generate(key, :csr_attributes => csr_attributes)
end.to raise_error Puppet::Error, /Cannot create CSR with attribute thats\.no\.moon: /
end
it "should support old non-DER encoded extensions" do
csr = OpenSSL::X509::Request.new(File.read(my_fixture("old-style-cert-request.pem")))
wrapped_csr = Puppet::SSL::CertificateRequest.from_instance csr
exts = wrapped_csr.request_extensions()
expect(exts.find { |ext| ext['oid'] == 'pp_uuid' }['value']).to eq('I-AM-A-UUID')
expect(exts.find { |ext| ext['oid'] == 'pp_instance_id' }['value']).to eq('i_am_an_id')
expect(exts.find { |ext| ext['oid'] == 'pp_image_name' }['value']).to eq('i_am_an_image_name')
end
end
context "with extension requests" do
let(:extension_data) do
{
'1.3.6.1.4.1.34380.1.1.31415' => 'pi',
'1.3.6.1.4.1.34380.1.1.2718' => 'e',
}
end
it "adds an extreq attribute to the CSR" do
request.generate(key, :extension_requests => extension_data)
exts = request.content.attributes.select { |attr| attr.oid = 'extReq' }
expect(exts.length).to eq(1)
end
it "adds an extension for each entry in the extension request structure" do
request.generate(key, :extension_requests => extension_data)
exts = request.request_extensions
expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi')
expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e')
end
it "defines the extensions as non-critical" do
request.generate(key, :extension_requests => extension_data)
request.request_extensions.each do |ext|
expect(ext['critical']).to be_falsey
end
end
it "rejects the subjectAltNames extension" do
san_names = ['subjectAltName', '2.5.29.17']
san_field = 'DNS:first.tld, DNS:second.tld'
san_names.each do |name|
expect do
request.generate(key, :extension_requests => {name => san_field})
end.to raise_error Puppet::Error, /conflicts with internally used extension/
end
end
it "merges the extReq attribute with the subjectAltNames extension" do
request.generate(key,
:dns_alt_names => 'first.tld, second.tld',
:extension_requests => extension_data)
exts = request.request_extensions
expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi')
expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e')
expect(exts).to include('oid' => 'subjectAltName', 'value' => 'DNS:first.tld, DNS:myname, DNS:second.tld')
expect(request.subject_alt_names).to eq ['DNS:first.tld', 'DNS:myname', 'DNS:second.tld']
end
it "raises an error if the OID could not be created" do
exts = {"thats.no.moon" => "death star"}
expect do
request.generate(key, :extension_requests => exts)
end.to raise_error Puppet::Error, /Cannot create CSR with extension request thats\.no\.moon.*: /
end
end
it "should sign the csr with the provided key" do
request.generate(key)
expect(request.content.verify(key.public_key)).to be_truthy
end
it "should verify the generated request using the public key" do
# Stupid keys don't have a competent == method.
expect_any_instance_of(OpenSSL::X509::Request).to receive(:verify) do |public_key|
public_key.to_s == key.public_key.to_s
end.and_return(true)
request.generate(key)
end
it "should fail if verification fails" do
expect_any_instance_of(OpenSSL::X509::Request).to receive(:verify) do |public_key|
public_key.to_s == key.public_key.to_s
end.and_return(false)
expect do
request.generate(key)
end.to raise_error(Puppet::Error, /CSR sign verification failed/)
end
it "should log the fingerprint" do
allow_any_instance_of(Puppet::SSL::Digest).to receive(:to_hex).and_return("FINGERPRINT")
allow(Puppet).to receive(:info)
expect(Puppet).to receive(:info).with(/FINGERPRINT/)
request.generate(key)
end
it "should return the generated request" do
generated = request.generate(key)
expect(generated).to be_a(OpenSSL::X509::Request)
expect(generated).to be(request.content)
end
it "should use SHA1 to sign the csr when SHA256 isn't available" do
csr = OpenSSL::X509::Request.new
csr.public_key = key.public_key
csr.version = 0
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(true)
signer = Puppet::SSL::CertificateSigner.new
signer.sign(csr, key)
expect(csr.verify(key)).to be_truthy
end
it "should use SHA512 to sign the csr when SHA256 and SHA1 aren't available" do
key = OpenSSL::PKey::RSA.new(2048)
csr = OpenSSL::X509::Request.new
csr.public_key = key.public_key
csr.version = 0
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(true)
signer = Puppet::SSL::CertificateSigner.new
signer.sign(csr, key)
expect(csr.verify(key)).to be_truthy
end
it "should use SHA384 to sign the csr when SHA256/SHA1/SHA512 aren't available" do
key = OpenSSL::PKey::RSA.new(2048)
csr = OpenSSL::X509::Request.new
csr.public_key = key.public_key
csr.version = 0
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA384").and_return(true)
signer = Puppet::SSL::CertificateSigner.new
signer.sign(csr, key)
expect(csr.verify(key)).to be_truthy
end
it "should use SHA224 to sign the csr when SHA256/SHA1/SHA512/SHA384 aren't available" do
csr = OpenSSL::X509::Request.new
csr.public_key = key.public_key
csr.version = 0
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA384").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA224").and_return(true)
signer = Puppet::SSL::CertificateSigner.new
signer.sign(csr, key)
expect(csr.verify(key)).to be_truthy
end
it "should raise an error if neither SHA256/SHA1/SHA512/SHA384/SHA224 are available" do
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA384").and_return(false)
expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA224").and_return(false)
expect {
Puppet::SSL::CertificateSigner.new
}.to raise_error(Puppet::Error)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/ssl/state_machine_spec.rb | spec/unit/ssl/state_machine_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/ssl'
describe Puppet::SSL::StateMachine, unless: Puppet::Util::Platform.jruby? do
include PuppetSpec::Files
let(:privatekeydir) { tmpdir('privatekeydir') }
let(:certdir) { tmpdir('certdir') }
let(:requestdir) { tmpdir('requestdir') }
let(:machine) { described_class.new }
let(:cert_provider) { Puppet::X509::CertProvider.new(privatekeydir: privatekeydir, certdir: certdir, requestdir: requestdir) }
let(:ssl_provider) { Puppet::SSL::SSLProvider.new }
let(:machine) { described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider) }
let(:cacert_pem) { cacert.to_pem }
let(:cacert) { cert_fixture('ca.pem') }
let(:cacerts) { [cacert, cert_fixture('intermediate.pem')] }
let(:crl_pem) { crl.to_pem }
let(:crl) { crl_fixture('crl.pem') }
let(:crls) { [crl, crl_fixture('intermediate-crl.pem')] }
let(:private_key) { key_fixture('signed-key.pem') }
let(:client_cert) { cert_fixture('signed.pem') }
let(:refused_message) { %r{Connection refused|No connection could be made because the target machine actively refused it} }
before(:each) do
Puppet[:daemonize] = false
Puppet[:ssl_lockfile] = tmpfile('ssllock')
allow(Kernel).to receive(:sleep)
future = Time.now + (5 * 60)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:crl_last_update).and_return(future)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update).and_return(future)
end
def expected_digest(name, content)
OpenSSL::Digest.new(name).hexdigest(content)
end
def to_fingerprint(digest)
digest.scan(/../).join(':').upcase
end
context 'when passing keyword arguments' do
it "accepts digest" do
expect(described_class.new(digest: 'SHA512').digest).to eq('SHA512')
end
it "accepts ca_fingerprint" do
expect(described_class.new(ca_fingerprint: 'CAFE').ca_fingerprint).to eq('CAFE')
end
end
context 'when ensuring CA certs and CRLs' do
it 'returns an SSLContext with the loaded CA certs and CRLs' do
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
allow(cert_provider).to receive(:load_crls).and_return(crls)
ssl_context = machine.ensure_ca_certificates
expect(ssl_context[:cacerts]).to eq(cacerts)
expect(ssl_context[:crls]).to eq(crls)
expect(ssl_context[:verify_peer]).to eq(true)
end
context 'when exceptions occur' do
it 'raises in onetime mode' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca})
.to_raise(Errno::ECONNREFUSED)
machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider, onetime: true)
expect {
machine.ensure_ca_certificates
}.to raise_error(Puppet::Error, refused_message)
end
it 'retries CA cert download' do
# allow cert to be saved to disk
FileUtils.mkdir_p(Puppet[:certdir])
allow(cert_provider).to receive(:load_crls).and_return(crls)
req = stub_request(:get, %r{puppet-ca/v1/certificate/ca})
.to_raise(Errno::ECONNREFUSED).then
.to_return(status: 200, body: cacert_pem)
machine.ensure_ca_certificates
expect(req).to have_been_made.twice
expect(@logs).to include(an_object_having_attributes(message: refused_message))
end
it 'retries CRL download' do
# allow crl to be saved to disk
FileUtils.mkdir_p(Puppet[:ssldir])
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
req = stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca})
.to_raise(Errno::ECONNREFUSED).then
.to_return(status: 200, body: crl_pem)
machine.ensure_ca_certificates
expect(req).to have_been_made.twice
expect(@logs).to include(an_object_having_attributes(message: refused_message))
end
end
end
context 'when ensuring a client cert' do
it 'returns an SSLContext with the loaded CA certs, CRLs, private key and client cert' do
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
allow(cert_provider).to receive(:load_crls).and_return(crls)
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
allow(cert_provider).to receive(:load_client_cert).and_return(client_cert)
ssl_context = machine.ensure_client_certificate
expect(ssl_context[:cacerts]).to eq(cacerts)
expect(ssl_context[:crls]).to eq(crls)
expect(ssl_context[:verify_peer]).to eq(true)
expect(ssl_context[:private_key]).to eq(private_key)
expect(ssl_context[:client_cert]).to eq(client_cert)
end
it 'uses the specified digest to log the cert chain fingerprints' do
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
allow(cert_provider).to receive(:load_crls).and_return(crls)
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
allow(cert_provider).to receive(:load_client_cert).and_return(client_cert)
Puppet[:log_level] = :debug
machine = described_class.new(cert_provider: cert_provider, digest: 'SHA512')
machine.ensure_client_certificate
expect(@logs).to include(
an_object_having_attributes(message: /Verified CA certificate 'CN=Test CA' fingerprint \(SHA512\)/),
an_object_having_attributes(message: /Verified CA certificate 'CN=Test CA Subauthority' fingerprint \(SHA512\)/),
an_object_having_attributes(message: /Verified client certificate 'CN=signed' fingerprint \(SHA512\)/)
)
end
context 'when exceptions occur' do
before :each do
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
allow(cert_provider).to receive(:load_crls).and_return(crls)
end
it 'retries CSR submission' do
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
allow($stdout).to receive(:puts).with(/Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate/)
stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}})
.to_return(status: 200, body: client_cert.to_pem)
# first request raises, second succeeds
req = stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}})
.to_raise(Errno::ECONNREFUSED).then
.to_return(status: 200)
machine.ensure_client_certificate
expect(req).to have_been_made.twice
expect(@logs).to include(an_object_having_attributes(message: refused_message))
end
it 'retries client cert download' do
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
# first request raises, second succeeds
req = stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}})
.to_raise(Errno::ECONNREFUSED).then
.to_return(status: 200, body: client_cert.to_pem)
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200)
machine.ensure_client_certificate
expect(req).to have_been_made.twice
expect(@logs).to include(an_object_having_attributes(message: refused_message))
end
it 'retries when client cert and private key are mismatched' do
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
# return mismatched cert the first time, correct cert second time
req = stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}})
.to_return(status: 200, body: cert_fixture('pluto.pem').to_pem)
.to_return(status: 200, body: client_cert.to_pem)
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200)
machine.ensure_client_certificate
expect(req).to have_been_made.twice
expect(@logs).to include(an_object_having_attributes(message: %r{The certificate for 'CN=pluto' does not match its private key}))
end
it 'raises in onetime mode' do
stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}})
.to_raise(Errno::ECONNREFUSED)
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}})
.to_return(status: 200)
machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider, onetime: true)
expect {
machine.ensure_client_certificate
}.to raise_error(Puppet::Error, refused_message)
end
end
end
context 'when locking' do
let(:lockfile) { Puppet::Util::Pidlock.new(Puppet[:ssl_lockfile]) }
let(:machine) { described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider, lockfile: lockfile) }
# lockfile is deleted before `ensure_ca_certificates` returns, so
# verify lockfile contents while state machine is running
def expect_lockfile_to_contain(pid)
allow(cert_provider).to receive(:load_cacerts) do
expect(File.read(Puppet[:ssl_lockfile])).to eq(pid.to_s)
end.and_return(cacerts)
allow(cert_provider).to receive(:load_crls).and_return(crls)
end
it 'locks the file prior to running the state machine and unlocks when done' do
expect(lockfile).to receive(:lock).and_call_original.ordered
expect(cert_provider).to receive(:load_cacerts).and_return(cacerts).ordered
expect(cert_provider).to receive(:load_crls).and_return(crls).ordered
expect(lockfile).to receive(:unlock).ordered
machine.ensure_ca_certificates
end
it 'deletes the lockfile when finished' do
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
allow(cert_provider).to receive(:load_crls).and_return(crls)
machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider)
machine.ensure_ca_certificates
expect(File).to_not be_exist(Puppet[:ssl_lockfile])
end
it 'acquires an empty lockfile' do
Puppet::FileSystem.touch(Puppet[:ssl_lockfile])
expect_lockfile_to_contain(Process.pid)
machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider)
machine.ensure_ca_certificates
end
it 'acquires its own lockfile' do
File.write(Puppet[:ssl_lockfile], Process.pid.to_s)
expect_lockfile_to_contain(Process.pid)
machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider)
machine.ensure_ca_certificates
end
it 'overwrites a stale lockfile' do
# 2**31 - 1 chosen to not conflict with existing pid
File.write(Puppet[:ssl_lockfile], "2147483647")
expect_lockfile_to_contain(Process.pid)
machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider)
machine.ensure_ca_certificates
end
context 'and another puppet process is running' do
let(:now) { Time.now }
let(:future) { now + (5 * 60)} # 5 mins in the future
before :each do
allow(lockfile).to receive(:lock).and_return(false)
end
it 'raises a puppet exception' do
expect {
machine.ensure_ca_certificates
}.to raise_error(Puppet::Error, /Another puppet instance is already running and the waitforlock setting is set to 0; exiting/)
end
it 'sleeps and retries successfully' do
machine = described_class.new(lockfile: lockfile, cert_provider: cert_provider, waitforlock: 1, maxwaitforlock: 10)
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
allow(cert_provider).to receive(:load_crls).and_return(crls)
allow(Time).to receive(:now).and_return(now, future)
expect(Kernel).to receive(:sleep).with(1)
expect(Puppet).to receive(:info).with("Another puppet instance is already running; waiting for it to finish")
expect(Puppet).to receive(:info).with("Will try again in 1 seconds.")
allow(lockfile).to receive(:lock).and_return(false, true)
expect(machine.ensure_ca_certificates).to be_an_instance_of(Puppet::SSL::SSLContext)
end
it 'sleeps and retries unsuccessfully until the deadline is exceeded' do
machine = described_class.new(lockfile: lockfile, waitforlock: 1, maxwaitforlock: 10)
allow(Time).to receive(:now).and_return(now, future)
expect(Kernel).to receive(:sleep).with(1)
expect(Puppet).to receive(:info).with("Another puppet instance is already running; waiting for it to finish")
expect(Puppet).to receive(:info).with("Will try again in 1 seconds.")
allow(lockfile).to receive(:lock).and_return(false)
expect {
machine.ensure_ca_certificates
}.to raise_error(Puppet::Error, /Another puppet instance is already running and the maxwaitforlock timeout has been exceeded; exiting/)
end
it 'defaults the waitlock deadline to 60 seconds' do
allow(Time).to receive(:now).and_return(now)
machine = described_class.new
expect(machine.waitlock_deadline).to eq(now.to_i + 60)
end
end
end
context 'NeedCACerts' do
let(:state) { Puppet::SSL::StateMachine::NeedCACerts.new(machine) }
before :each do
Puppet[:localcacert] = tmpfile('needcacerts')
end
it 'transitions to NeedCRLs state' do
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
expect(state.next_state).to be_an_instance_of(Puppet::SSL::StateMachine::NeedCRLs)
end
it 'loads existing CA certs' do
allow(cert_provider).to receive(:load_cacerts).and_return(cacerts)
st = state.next_state
expect(st.ssl_context[:cacerts]).to eq(cacerts)
end
it 'fetches and saves CA certs' do
allow(cert_provider).to receive(:load_cacerts).and_return(nil)
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: cacert_pem)
st = state.next_state
expect(st.ssl_context[:cacerts].map(&:to_pem)).to eq([cacert_pem])
expect(File).to be_exist(Puppet[:localcacert])
end
it "does not verify the server's cert if there are no local CA certs" do
allow(cert_provider).to receive(:load_cacerts).and_return(nil)
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: cacert_pem)
allow(cert_provider).to receive(:save_cacerts)
receive_count = 0
allow_any_instance_of(Net::HTTP).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE) { receive_count += 1 }
state.next_state
expect(receive_count).to eq(2)
end
it 'returns an Error if the server returns 404' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 404)
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error)
expect(st.message).to eq("CA certificate is missing from the server")
end
it 'returns an Error if there is a different exception' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: [500, 'Internal Server Error'])
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error)
expect(st.message).to eq("Could not download CA certificate: Internal Server Error")
end
it 'returns an Error if CA certs are invalid' do
allow(cert_provider).to receive(:load_cacerts).and_return(nil)
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: '')
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error)
expect(st.error).to be_an_instance_of(OpenSSL::X509::CertificateError)
end
it 'does not save invalid CA certs' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: <<~END)
-----BEGIN CERTIFICATE-----
MIIBpDCCAQ2gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAfMR0wGwYDVQQDDBRUZXN0
END
state.next_state rescue OpenSSL::X509::CertificateError
expect(File).to_not exist(Puppet[:localcacert])
end
it 'skips CA refresh if it has not expired' do
Puppet[:ca_refresh_interval] = '1y'
Puppet::FileSystem.touch(Puppet[:localcacert], mtime: Time.now)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_cacerts).and_return(cacerts)
# we're expecting a net/http request to never be made
state.next_state
end
context 'when verifying CA cert bundle' do
before :each do
allow(cert_provider).to receive(:load_cacerts).and_return(nil)
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: cacert_pem)
allow(cert_provider).to receive(:save_cacerts)
end
it 'verifies CA cert bundle if a ca_fingerprint is given case-insensitively' do
Puppet[:log_level] = :info
digest = expected_digest('SHA256', cacert_pem)
fingerprint = to_fingerprint(digest)
machine = described_class.new(digest: 'SHA256', ca_fingerprint: digest.downcase)
state = Puppet::SSL::StateMachine::NeedCACerts.new(machine)
state.next_state
expect(@logs).to include(an_object_having_attributes(message: "Verified CA bundle with digest (SHA256) #{fingerprint}"))
end
it 'verifies CA cert bundle using non-default fingerprint' do
Puppet[:log_level] = :info
digest = expected_digest('SHA512', cacert_pem)
machine = described_class.new(digest: 'SHA512', ca_fingerprint: digest)
state = Puppet::SSL::StateMachine::NeedCACerts.new(machine)
state.next_state
expect(@logs).to include(an_object_having_attributes(message: "Verified CA bundle with digest (SHA512) #{to_fingerprint(digest)}"))
end
it 'returns an error if verification fails' do
machine = described_class.new(digest: 'SHA256', ca_fingerprint: 'wrong!')
state = Puppet::SSL::StateMachine::NeedCACerts.new(machine)
fingerprint = to_fingerprint(expected_digest('SHA256', cacert_pem))
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error)
expect(st.message).to eq("CA bundle with digest (SHA256) #{fingerprint} did not match expected digest WR:ON:G!")
end
end
context 'when refreshing a CA bundle' do
before :each do
Puppet[:ca_refresh_interval] = '1s'
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_cacerts).and_return(cacerts)
yesterday = Time.now - (24 * 60 * 60)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update).and_return(yesterday)
end
let(:new_ca_bundle) do
# add 'unknown' cert to the bundle
[cacert, cert_fixture('intermediate.pem'), cert_fixture('unknown-ca.pem')].map(&:to_pem)
end
it 'uses the local CA if it has not been modified' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 304)
expect(state.next_state.ssl_context.cacerts).to eq(cacerts)
end
it 'uses the local CA if refreshing fails in HTTP layer' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 503)
expect(state.next_state.ssl_context.cacerts).to eq(cacerts)
end
it 'uses the local CA if refreshing fails in TCP layer' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_raise(Errno::ECONNREFUSED)
expect(state.next_state.ssl_context.cacerts).to eq(cacerts)
end
it 'uses the updated crl for the future requests' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: new_ca_bundle.join)
expect(state.next_state.ssl_context.cacerts.map(&:to_pem)).to eq(new_ca_bundle)
end
it 'updates the `last_update` time on successful CA refresh' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: new_ca_bundle.join)
expect_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update=).with(be_within(60).of(Time.now))
state.next_state
end
it "does not update the `last_update` time when CA refresh fails" do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_raise(Errno::ECONNREFUSED)
expect_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update=).never
state.next_state
end
it 'forces the NeedCRLs to refresh' do
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: new_ca_bundle.join)
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::NeedCRLs)
expect(st.force_crl_refresh).to eq(true)
end
end
end
context 'NeedCRLs' do
let(:ssl_context) { Puppet::SSL::SSLContext.new(cacerts: cacerts)}
let(:state) { Puppet::SSL::StateMachine::NeedCRLs.new(machine, ssl_context) }
before :each do
Puppet[:hostcrl] = tmpfile('needcrls')
end
it 'transitions to NeedKey state' do
allow(cert_provider).to receive(:load_crls).and_return(crls)
expect(state.next_state).to be_an_instance_of(Puppet::SSL::StateMachine::NeedKey)
end
it 'loads existing CRLs' do
allow(cert_provider).to receive(:load_crls).and_return(crls)
st = state.next_state
expect(st.ssl_context[:crls]).to eq(crls)
end
it 'fetches and saves CRLs' do
allow(cert_provider).to receive(:load_crls).and_return(nil)
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: crl_pem)
st = state.next_state
expect(st.ssl_context[:crls].map(&:to_pem)).to eq([crl_pem])
expect(File).to be_exist(Puppet[:hostcrl])
end
it "verifies the server's certificate when fetching the CRL" do
allow(cert_provider).to receive(:load_crls).and_return(nil)
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: crl_pem)
allow(cert_provider).to receive(:save_crls)
receive_count = 0
allow_any_instance_of(Net::HTTP).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER) { receive_count += 1 }
state.next_state
expect(receive_count).to eq(2)
end
it 'returns an Error if the server returns 404' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 404)
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error)
expect(st.message).to eq("CRL is missing from the server")
end
it 'returns an Error if there is a different exception' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: [500, 'Internal Server Error'])
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error)
expect(st.message).to eq("Could not download CRLs: Internal Server Error")
end
it 'returns an Error if CRLs are invalid' do
allow(cert_provider).to receive(:load_crls).and_return(nil)
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: '')
st = state.next_state
expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error)
expect(st.error).to be_an_instance_of(OpenSSL::X509::CRLError)
end
it 'does not save invalid CRLs' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: <<~END)
-----BEGIN X509 CRL-----
MIIBCjB1AgEBMA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNVBAMMB1Rlc3QgQ0EXDTcw
END
state.next_state rescue OpenSSL::X509::CRLError
expect(File).to_not exist(Puppet[:hostcrl])
end
it 'skips CRL download when revocation is disabled' do
Puppet[:certificate_revocation] = false
expect(cert_provider).not_to receive(:load_crls)
state.next_state
expect(File).to_not exist(Puppet[:hostcrl])
end
it 'skips CRL refresh if it has not expired' do
Puppet[:crl_refresh_interval] = '1y'
Puppet::FileSystem.touch(Puppet[:hostcrl], mtime: Time.now)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_crls).and_return(crls)
# we're expecting a net/http request to never be made
state.next_state
end
context 'when refreshing a CRL' do
before :each do
Puppet[:crl_refresh_interval] = '1s'
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_crls).and_return(crls)
yesterday = Time.now - (24 * 60 * 60)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:crl_last_update).and_return(yesterday)
end
let(:new_crl_bundle) do
# add intermediate crl to the bundle
int_crl = crl_fixture('intermediate-crl.pem')
[crl, int_crl].map(&:to_pem)
end
it 'uses the local crl if it has not been modified' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 304)
expect(state.next_state.ssl_context.crls).to eq(crls)
end
it 'uses the local crl if refreshing fails in HTTP layer' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 503)
expect(state.next_state.ssl_context.crls).to eq(crls)
end
it 'uses the local crl if refreshing fails in TCP layer' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_raise(Errno::ECONNREFUSED)
expect(state.next_state.ssl_context.crls).to eq(crls)
end
it 'uses the updated crl for the future requests' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: new_crl_bundle.join)
expect(state.next_state.ssl_context.crls.map(&:to_pem)).to eq(new_crl_bundle)
end
it 'updates the `last_update` time' do
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: new_crl_bundle.join)
expect_any_instance_of(Puppet::X509::CertProvider).to receive(:crl_last_update=).with(be_within(60).of(Time.now))
state.next_state
end
end
end
context 'when ensuring a client cert' do
context 'in state NeedKey' do
let(:ssl_context) { Puppet::SSL::SSLContext.new(cacerts: cacerts, crls: crls)}
let(:state) { Puppet::SSL::StateMachine::NeedKey.new(machine, ssl_context) }
it 'loads an existing private key and passes it to the next state' do
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
st = state.next_state
expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR)
expect(st.private_key).to eq(private_key)
end
it 'loads a matching private key and cert' do
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
allow(cert_provider).to receive(:load_client_cert).and_return(client_cert)
st = state.next_state
expect(st).to be_instance_of(Puppet::SSL::StateMachine::Done)
end
it 'raises if the client cert is mismatched' do
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
allow(cert_provider).to receive(:load_client_cert).and_return(cert_fixture('tampered-cert.pem'))
ssl_context = Puppet::SSL::SSLContext.new(cacerts: [cacert], crls: [crl])
state = Puppet::SSL::StateMachine::NeedKey.new(machine, ssl_context)
expect {
state.next_state
}.to raise_error(Puppet::SSL::SSLError, %r{The certificate for 'CN=signed' does not match its private key})
end
it 'generates a new RSA private key, saves it and passes it to the next state' do
allow(cert_provider).to receive(:load_private_key).and_return(nil)
expect(cert_provider).to receive(:save_private_key)
st = state.next_state
expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR)
expect(st.private_key).to be_instance_of(OpenSSL::PKey::RSA)
expect(st.private_key).to be_private
end
it 'generates a new EC private key, saves it and passes it to the next state' do
Puppet[:key_type] = 'ec'
allow(cert_provider).to receive(:load_private_key).and_return(nil)
expect(cert_provider).to receive(:save_private_key)
st = state.next_state
expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR)
expect(st.private_key).to be_instance_of(OpenSSL::PKey::EC)
expect(st.private_key).to be_private
expect(st.private_key.group.curve_name).to eq('prime256v1')
end
it 'generates a new EC private key with curve `secp384r1`, saves it and passes it to the next state' do
Puppet[:key_type] = 'ec'
Puppet[:named_curve] = 'secp384r1'
allow(cert_provider).to receive(:load_private_key).and_return(nil)
expect(cert_provider).to receive(:save_private_key)
st = state.next_state
expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR)
expect(st.private_key).to be_instance_of(OpenSSL::PKey::EC)
expect(st.private_key).to be_private
expect(st.private_key.group.curve_name).to eq('secp384r1')
end
it 'raises if the named curve is unsupported' do
Puppet[:key_type] = 'ec'
Puppet[:named_curve] = 'infiniteloop'
allow(cert_provider).to receive(:load_private_key).and_return(nil)
expect {
state.next_state
}.to raise_error(OpenSSL::PKey::ECError, /(invalid|unknown) curve name/)
end
it 'raises an error if it fails to load the key' do
allow(cert_provider).to receive(:load_private_key).and_raise(OpenSSL::PKey::RSAError)
expect {
state.next_state
}.to raise_error(OpenSSL::PKey::RSAError)
end
it "transitions to Done if current time plus renewal interval is less than cert's \"NotAfter\" time" do
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
allow(cert_provider).to receive(:load_client_cert).and_return(client_cert)
st = state.next_state
expect(st).to be_instance_of(Puppet::SSL::StateMachine::Done)
end
it "returns NeedRenewedCert if current time plus renewal interval is greater than cert's \"NotAfter\" time" do
client_cert.not_after=(Time.now + 300)
allow(cert_provider).to receive(:load_private_key).and_return(private_key)
allow(cert_provider).to receive(:load_client_cert).and_return(client_cert)
ssl_context = Puppet::SSL::SSLContext.new(cacerts: [cacert], client_cert: client_cert, crls: [crl])
state = Puppet::SSL::StateMachine::NeedKey.new(machine, ssl_context)
st = state.next_state
expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedRenewedCert)
end
end
context 'in state NeedSubmitCSR' do
let(:ssl_context) { Puppet::SSL::SSLContext.new(cacerts: cacerts, crls: crls)}
let(:state) { Puppet::SSL::StateMachine::NeedSubmitCSR.new(machine, ssl_context, private_key) }
def write_csr_attributes(data)
file_containing('state_machine_csr', YAML.dump(data))
end
before :each do
allow(cert_provider).to receive(:save_request)
end
it 'submits the CSR and transitions to NeedCert' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200)
expect(state.next_state).to be_an_instance_of(Puppet::SSL::StateMachine::NeedCert)
end
it 'saves the CSR and transitions to NeedCert' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200)
expect(cert_provider).to receive(:save_request).with(Puppet[:certname], instance_of(OpenSSL::X509::Request))
state.next_state
end
it 'includes DNS alt names' do
Puppet[:dns_alt_names] = "one,IP:192.168.0.1,DNS:two.com"
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).with do |request|
csr = Puppet::SSL::CertificateRequest.from_instance(OpenSSL::X509::Request.new(request.body))
expect(
csr.subject_alt_names
).to contain_exactly('DNS:one', 'IP Address:192.168.0.1', 'DNS:two.com', "DNS:#{Puppet[:certname]}")
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/ssl/oids_spec.rb | spec/unit/ssl/oids_spec.rb | require 'spec_helper'
require 'puppet/ssl/oids'
describe Puppet::SSL::Oids do
describe "defining application OIDs" do
{
'puppetlabs' => '1.3.6.1.4.1.34380',
'ppCertExt' => '1.3.6.1.4.1.34380.1',
'ppRegCertExt' => '1.3.6.1.4.1.34380.1.1',
'pp_uuid' => '1.3.6.1.4.1.34380.1.1.1',
'pp_instance_id' => '1.3.6.1.4.1.34380.1.1.2',
'pp_image_name' => '1.3.6.1.4.1.34380.1.1.3',
'pp_preshared_key' => '1.3.6.1.4.1.34380.1.1.4',
'pp_cost_center' => '1.3.6.1.4.1.34380.1.1.5',
'pp_product' => '1.3.6.1.4.1.34380.1.1.6',
'pp_project' => '1.3.6.1.4.1.34380.1.1.7',
'pp_application' => '1.3.6.1.4.1.34380.1.1.8',
'pp_service' => '1.3.6.1.4.1.34380.1.1.9',
'pp_employee' => '1.3.6.1.4.1.34380.1.1.10',
'pp_created_by' => '1.3.6.1.4.1.34380.1.1.11',
'pp_environment' => '1.3.6.1.4.1.34380.1.1.12',
'pp_role' => '1.3.6.1.4.1.34380.1.1.13',
'pp_software_version' => '1.3.6.1.4.1.34380.1.1.14',
'pp_department' => '1.3.6.1.4.1.34380.1.1.15',
'pp_cluster' => '1.3.6.1.4.1.34380.1.1.16',
'pp_provisioner' => '1.3.6.1.4.1.34380.1.1.17',
'pp_region' => '1.3.6.1.4.1.34380.1.1.18',
'pp_datacenter' => '1.3.6.1.4.1.34380.1.1.19',
'pp_zone' => '1.3.6.1.4.1.34380.1.1.20',
'pp_network' => '1.3.6.1.4.1.34380.1.1.21',
'pp_securitypolicy' => '1.3.6.1.4.1.34380.1.1.22',
'pp_cloudplatform' => '1.3.6.1.4.1.34380.1.1.23',
'pp_apptier' => '1.3.6.1.4.1.34380.1.1.24',
'pp_hostname' => '1.3.6.1.4.1.34380.1.1.25',
'pp_owner' => '1.3.6.1.4.1.34380.1.1.26',
'ppPrivCertExt' => '1.3.6.1.4.1.34380.1.2',
'ppAuthCertExt' => '1.3.6.1.4.1.34380.1.3',
'pp_authorization' => '1.3.6.1.4.1.34380.1.3.1',
'pp_auth_role' => '1.3.6.1.4.1.34380.1.3.13',
}.each_pair do |sn, oid|
it "defines #{sn} as #{oid}" do
object_id = OpenSSL::ASN1::ObjectId.new(sn)
expect(object_id.oid).to eq oid
end
end
end
describe "checking if an OID is a subtree of another OID" do
it "can determine if an OID is contained in another OID" do
expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1.4.1')).to be_truthy
expect(described_class.subtree_of?('1.3.6.1.4.1', '1.3.6.1')).to be_falsey
end
it "returns true if an OID is compared against itself and exclusive is false" do
expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1', false)).to be_truthy
end
it "returns false if an OID is compared against itself and exclusive is true" do
expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1', true)).to be_falsey
end
it "can compare OIDs defined as short names" do
expect(described_class.subtree_of?('IANA', '1.3.6.1.4.1')).to be_truthy
expect(described_class.subtree_of?('1.3.6.1', 'enterprises')).to be_truthy
end
it "returns false when an invalid OID shortname is passed" do
expect(described_class.subtree_of?('IANA', 'bananas')).to be_falsey
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/ssl/digest_spec.rb | spec/unit/ssl/digest_spec.rb | require 'spec_helper'
require 'puppet/ssl/digest'
describe Puppet::SSL::Digest do
it "defaults to sha256" do
digest = described_class.new(nil, 'blah')
expect(digest.name).to eq('SHA256')
expect(digest.digest.hexdigest).to eq("8b7df143d91c716ecfa5fc1730022f6b421b05cedee8fd52b1fc65a96030ad52")
end
describe '#name' do
it "prints the hashing algorithm used by the openssl digest" do
expect(described_class.new('SHA224', 'blah').name).to eq('SHA224')
end
it "upcases the hashing algorithm" do
expect(described_class.new('sha224', 'blah').name).to eq('SHA224')
end
end
describe '#to_hex' do
it "returns ':' separated upper case hex pairs" do
described_class.new(nil, 'blah').to_hex =~ /\A([A-Z0-9]:)+[A-Z0-9]\Z/
end
end
describe '#to_s' do
it "formats the digest algorithm and the digest as a string" do
digest = described_class.new('sha512', 'some content')
expect(digest.to_s).to eq("(#{digest.name}) #{digest.to_hex}")
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/ssl/certificate_spec.rb | spec/unit/ssl/certificate_spec.rb | require 'spec_helper'
require 'puppet/certificate_factory'
require 'puppet/ssl/certificate'
describe Puppet::SSL::Certificate do
let :key do OpenSSL::PKey::RSA.new(Puppet[:keylength]) end
# Sign the provided cert so that it can be DER-decoded later
def sign_wrapped_cert(cert)
signer = Puppet::SSL::CertificateSigner.new
signer.sign(cert.content, key)
end
before do
@class = Puppet::SSL::Certificate
end
it "should only support the text format" do
expect(@class.supported_formats).to eq([:s])
end
describe "when converting from a string" do
it "should create a certificate instance with its name set to the certificate subject and its content set to the extracted certificate" do
cert = double(
'certificate',
:subject => OpenSSL::X509::Name.parse("/CN=Foo.madstop.com"),
:is_a? => true
)
expect(OpenSSL::X509::Certificate).to receive(:new).with("my certificate").and_return(cert)
mycert = double('sslcert')
expect(mycert).to receive(:content=).with(cert)
expect(@class).to receive(:new).with("Foo.madstop.com").and_return(mycert)
@class.from_s("my certificate")
end
it "should create multiple certificate instances when asked" do
cert1 = double('cert1')
expect(@class).to receive(:from_s).with("cert1").and_return(cert1)
cert2 = double('cert2')
expect(@class).to receive(:from_s).with("cert2").and_return(cert2)
expect(@class.from_multiple_s("cert1\n---\ncert2")).to eq([cert1, cert2])
end
end
describe "when converting to a string" do
before do
@certificate = @class.new("myname")
end
it "should return an empty string when it has no certificate" do
expect(@certificate.to_s).to eq("")
end
it "should convert the certificate to pem format" do
certificate = double('certificate', :to_pem => "pem")
@certificate.content = certificate
expect(@certificate.to_s).to eq("pem")
end
it "should be able to convert multiple instances to a string" do
cert2 = @class.new("foo")
expect(@certificate).to receive(:to_s).and_return("cert1")
expect(cert2).to receive(:to_s).and_return("cert2")
expect(@class.to_multiple_s([@certificate, cert2])).to eq("cert1\n---\ncert2")
end
end
describe "when managing instances" do
def build_cert(opts)
key = OpenSSL::PKey::RSA.new(Puppet[:keylength])
csr = Puppet::SSL::CertificateRequest.new('quux')
csr.generate(key, opts)
raw_cert = Puppet::CertificateFactory.build('client', csr, csr.content, 14)
@class.from_instance(raw_cert)
end
before do
@certificate = @class.new("myname")
end
it "should have a name attribute" do
expect(@certificate.name).to eq("myname")
end
it "should convert its name to a string and downcase it" do
expect(@class.new(:MyName).name).to eq("myname")
end
it "should have a content attribute" do
expect(@certificate).to respond_to(:content)
end
describe "#subject_alt_names", :unless => RUBY_PLATFORM == 'java' do
it "should list all alternate names when the extension is present" do
certificate = build_cert(:dns_alt_names => 'foo, bar,baz')
expect(certificate.subject_alt_names).
to match_array(['DNS:foo', 'DNS:bar', 'DNS:baz', 'DNS:quux'])
end
it "should return an empty list of names if the extension is absent" do
certificate = build_cert({})
expect(certificate.subject_alt_names).to be_empty
end
end
describe "custom extensions", :unless => RUBY_PLATFORM == 'java' do
it "returns extensions under the ppRegCertExt" do
exts = {'pp_uuid' => 'abcdfd'}
cert = build_cert(:extension_requests => exts)
sign_wrapped_cert(cert)
expect(cert.custom_extensions).to include('oid' => 'pp_uuid', 'value' => 'abcdfd')
end
it "returns extensions under the ppPrivCertExt" do
exts = {'1.3.6.1.4.1.34380.1.2.1' => 'x509 :('}
cert = build_cert(:extension_requests => exts)
sign_wrapped_cert(cert)
expect(cert.custom_extensions).to include('oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'x509 :(')
end
it "returns extensions under the ppAuthCertExt" do
exts = {'pp_auth_role' => 'taketwo'}
cert = build_cert(:extension_requests => exts)
sign_wrapped_cert(cert)
expect(cert.custom_extensions).to include('oid' => 'pp_auth_role', 'value' => 'taketwo')
end
it "doesn't return standard extensions" do
cert = build_cert(:dns_alt_names => 'foo')
expect(cert.custom_extensions).to be_empty
end
end
it "should return a nil expiration if there is no actual certificate" do
allow(@certificate).to receive(:content).and_return(nil)
expect(@certificate.expiration).to be_nil
end
it "should use the expiration of the certificate as its expiration date" do
cert = double('cert')
allow(@certificate).to receive(:content).and_return(cert)
expect(cert).to receive(:not_after).and_return("sometime")
expect(@certificate.expiration).to eq("sometime")
end
it "should be able to read certificates from disk" do
path = "/my/path"
expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding::ASCII}).and_return("my certificate")
certificate = double('certificate')
expect(OpenSSL::X509::Certificate).to receive(:new).with("my certificate").and_return(certificate)
expect(@certificate.read(path)).to equal(certificate)
expect(@certificate.content).to equal(certificate)
end
it "should have a :to_text method that it delegates to the actual key" do
real_certificate = double('certificate')
expect(real_certificate).to receive(:to_text).and_return("certificatetext")
@certificate.content = real_certificate
expect(@certificate.to_text).to eq("certificatetext")
end
it "should parse the old non-DER encoded extension values" do
cert = OpenSSL::X509::Certificate.new(File.read(my_fixture("old-style-cert-exts.pem")))
wrapped_cert = Puppet::SSL::Certificate.from_instance cert
exts = wrapped_cert.custom_extensions
expect(exts.find { |ext| ext['oid'] == 'pp_uuid'}['value']).to eq('I-AM-A-UUID')
expect(exts.find { |ext| ext['oid'] == 'pp_instance_id'}['value']).to eq('i_am_an_id')
expect(exts.find { |ext| ext['oid'] == 'pp_image_name'}['value']).to eq('i_am_an_image_name')
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/ssl/base_spec.rb | spec/unit/ssl/base_spec.rb | require 'spec_helper'
require 'puppet/ssl/certificate'
class TestCertificate < Puppet::SSL::Base
wraps(Puppet::SSL::Certificate)
end
describe Puppet::SSL::Certificate do
before :each do
@base = TestCertificate.new("name")
@class = TestCertificate
end
describe "when creating new instances" do
it "should fail if given an object that is not an instance of the wrapped class" do
obj = double('obj', :is_a? => false)
expect { @class.from_instance(obj) }.to raise_error(ArgumentError)
end
it "should fail if a name is not supplied and can't be determined from the object" do
obj = double('obj', :is_a? => true)
expect { @class.from_instance(obj) }.to raise_error(ArgumentError)
end
it "should determine the name from the object if it has a subject" do
obj = double('obj', :is_a? => true, :subject => '/CN=foo')
inst = double('base')
expect(inst).to receive(:content=).with(obj)
expect(@class).to receive(:new).with('foo').and_return(inst)
expect(@class).to receive(:name_from_subject).with('/CN=foo').and_return('foo')
expect(@class.from_instance(obj)).to eq(inst)
end
end
describe "when determining a name from a certificate subject" do
it "should extract only the CN and not any other components" do
name = OpenSSL::X509::Name.parse('/CN=host.domain.com/L=Portland/ST=Oregon')
expect(@class.name_from_subject(name)).to eq('host.domain.com')
end
end
describe "when initializing wrapped class from a file with #read" do
it "should open the file with ASCII encoding" do
path = '/foo/bar/cert'
expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding::ASCII}).and_return("bar")
@base.read(path)
end
end
describe "#digest_algorithm" do
let(:content) { double('content') }
let(:base) {
b = Puppet::SSL::Base.new('base')
b.content = content
b
}
# Some known signature algorithms taken from RFC 3279, 5758, and browsing
# objs_dat.h in openssl
{
'md5WithRSAEncryption' => 'md5',
'sha1WithRSAEncryption' => 'sha1',
'md4WithRSAEncryption' => 'md4',
'sha256WithRSAEncryption' => 'sha256',
'ripemd160WithRSA' => 'ripemd160',
'ecdsa-with-SHA1' => 'sha1',
'ecdsa-with-SHA224' => 'sha224',
'ecdsa-with-SHA256' => 'sha256',
'ecdsa-with-SHA384' => 'sha384',
'ecdsa-with-SHA512' => 'sha512',
'dsa_with_SHA224' => 'sha224',
'dsaWithSHA1' => 'sha1',
}.each do |signature, digest|
it "returns '#{digest}' for signature algorithm '#{signature}'" do
allow(content).to receive(:signature_algorithm).and_return(signature)
expect(base.digest_algorithm).to eq(digest)
end
end
it "raises an error on an unknown signature algorithm" do
allow(content).to receive(:signature_algorithm).and_return("nonsense")
expect {
base.digest_algorithm
}.to raise_error(Puppet::Error, "Unknown signature algorithm 'nonsense'")
end
end
describe "when getting a CN from a subject" do
def parse(dn)
OpenSSL::X509::Name.parse(dn)
end
def cn_from(subject)
@class.name_from_subject(subject)
end
it "should correctly parse a subject containing only a CN" do
subj = parse('/CN=foo')
expect(cn_from(subj)).to eq('foo')
end
it "should correctly parse a subject containing other components" do
subj = parse('/CN=Root CA/OU=Server Operations/O=Example Org')
expect(cn_from(subj)).to eq('Root CA')
end
it "should correctly parse a subject containing other components with CN not first" do
subj = parse('/emailAddress=foo@bar.com/CN=foo.bar.com/O=Example Org')
expect(cn_from(subj)).to eq('foo.bar.com')
end
it "should return nil for a subject with no CN" do
subj = parse('/OU=Server Operations/O=Example Org')
expect(cn_from(subj)).to eq(nil)
end
it "should return nil for a bare string" do
expect(cn_from("/CN=foo")).to eq(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/ssl/ssl_provider_spec.rb | spec/unit/ssl/ssl_provider_spec.rb | require 'spec_helper'
describe Puppet::SSL::SSLProvider do
include PuppetSpec::Files
let(:global_cacerts) { [ cert_fixture('ca.pem'), cert_fixture('intermediate.pem') ] }
let(:global_crls) { [ crl_fixture('crl.pem'), crl_fixture('intermediate-crl.pem') ] }
let(:wrong_key) { OpenSSL::PKey::RSA.new(512) }
context 'when creating an insecure context' do
let(:sslctx) { subject.create_insecure_context }
it 'has an empty list of trusted certs' do
expect(sslctx.cacerts).to eq([])
end
it 'has an empty list of crls' do
expect(sslctx.crls).to eq([])
end
it 'has an empty chain' do
expect(sslctx.client_chain).to eq([])
end
it 'has a nil private key and cert' do
expect(sslctx.private_key).to be_nil
expect(sslctx.client_cert).to be_nil
end
it 'does not authenticate the server' do
expect(sslctx.verify_peer).to eq(false)
end
it 'raises if the frozen context is modified' do
expect {
sslctx.cacerts = []
}.to raise_error(/can't modify frozen/)
end
end
context 'when creating an root ssl context with CA certs' do
let(:config) { { cacerts: [], crls: [], revocation: false } }
it 'accepts empty list of certs and crls' do
sslctx = subject.create_root_context(**config)
expect(sslctx.cacerts).to eq([])
expect(sslctx.crls).to eq([])
end
it 'accepts valid root certs' do
certs = [cert_fixture('ca.pem')]
sslctx = subject.create_root_context(**config.merge(cacerts: certs))
expect(sslctx.cacerts).to eq(certs)
end
it 'accepts valid intermediate certs' do
certs = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')]
sslctx = subject.create_root_context(**config.merge(cacerts: certs))
expect(sslctx.cacerts).to eq(certs)
end
it 'accepts expired CA certs' do
expired = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')]
expired.each { |x509| x509.not_after = Time.at(0) }
sslctx = subject.create_root_context(**config.merge(cacerts: expired))
expect(sslctx.cacerts).to eq(expired)
end
it 'raises if the frozen context is modified' do
sslctx = subject.create_root_context(**config)
expect {
sslctx.verify_peer = false
}.to raise_error(/can't modify frozen/)
end
it 'verifies peer' do
sslctx = subject.create_root_context(**config)
expect(sslctx.verify_peer).to eq(true)
end
end
context 'when creating a system ssl context' do
it 'accepts empty list of CA certs' do
sslctx = subject.create_system_context(cacerts: [])
expect(sslctx.cacerts).to eq([])
end
it 'accepts valid root certs' do
certs = [cert_fixture('ca.pem')]
sslctx = subject.create_system_context(cacerts: certs)
expect(sslctx.cacerts).to eq(certs)
end
it 'accepts valid intermediate certs' do
certs = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')]
sslctx = subject.create_system_context(cacerts: certs)
expect(sslctx.cacerts).to eq(certs)
end
it 'accepts expired CA certs' do
expired = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')]
expired.each { |x509| x509.not_after = Time.at(0) }
sslctx = subject.create_system_context(cacerts: expired)
expect(sslctx.cacerts).to eq(expired)
end
it 'raises if the frozen context is modified' do
sslctx = subject.create_system_context(cacerts: [])
expect {
sslctx.verify_peer = false
}.to raise_error(/can't modify frozen/)
end
it 'trusts system ca store by default' do
expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths)
subject.create_system_context(cacerts: [])
end
it 'trusts an external ca store' do
path = tmpfile('system_cacerts')
File.write(path, cert_fixture('ca.pem').to_pem)
expect_any_instance_of(OpenSSL::X509::Store).to receive(:add_file).with(path)
subject.create_system_context(cacerts: [], path: path)
end
it 'verifies peer' do
sslctx = subject.create_system_context(cacerts: [])
expect(sslctx.verify_peer).to eq(true)
end
it 'disable revocation' do
sslctx = subject.create_system_context(cacerts: [])
expect(sslctx.revocation).to eq(false)
end
it 'sets client cert and private key to nil' do
sslctx = subject.create_system_context(cacerts: [])
expect(sslctx.client_cert).to be_nil
expect(sslctx.private_key).to be_nil
end
it 'includes the client cert and private key when requested' do
Puppet[:hostcert] = fixtures('ssl/signed.pem')
Puppet[:hostprivkey] = fixtures('ssl/signed-key.pem')
sslctx = subject.create_system_context(cacerts: [], include_client_cert: true)
expect(sslctx.client_cert).to be_an(OpenSSL::X509::Certificate)
expect(sslctx.private_key).to be_an(OpenSSL::PKey::RSA)
end
it 'ignores non-existent client cert and private key when requested' do
Puppet[:certname] = 'doesnotexist'
sslctx = subject.create_system_context(cacerts: [], include_client_cert: true)
expect(sslctx.client_cert).to be_nil
expect(sslctx.private_key).to be_nil
end
it 'warns if the client cert does not exist when in non-user mode' do
Puppet[:certname] = 'missingcert'
Puppet[:hostprivkey] = fixtures('ssl/signed-key.pem')
Puppet.settings.preferred_run_mode = 'server'
expect(Puppet).to receive(:warning).with("Client certificate for 'missingcert' does not exist")
subject.create_system_context(cacerts: [], include_client_cert: true)
end
it 'warns if the private key does not exist when in non-user mode' do
Puppet[:certname] = 'missingkey'
Puppet[:hostcert] = fixtures('ssl/signed.pem')
Puppet.settings.preferred_run_mode = 'server'
expect(Puppet).to receive(:warning).with("Private key for 'missingkey' does not exist")
subject.create_system_context(cacerts: [], include_client_cert: true)
end
it 'shows info message if the client cert does not exist when in user mode' do
Puppet[:certname] = 'missingcert'
Puppet[:hostprivkey] = fixtures('ssl/signed-key.pem')
expect(Puppet).to receive(:info).with("Client certificate for 'missingcert' does not exist")
subject.create_system_context(cacerts: [], include_client_cert: true)
end
it 'shows info message if the private key does not exist when in user mode' do
Puppet[:certname] = 'missingkey'
Puppet[:hostcert] = fixtures('ssl/signed.pem')
expect(Puppet).to receive(:info).with("Private key for 'missingkey' does not exist")
subject.create_system_context(cacerts: [], include_client_cert: true)
end
it 'raises if client cert and private key are mismatched' do
Puppet[:hostcert] = fixtures('ssl/signed.pem')
Puppet[:hostprivkey] = fixtures('ssl/127.0.0.1-key.pem')
expect {
subject.create_system_context(cacerts: [], include_client_cert: true)
}.to raise_error(Puppet::SSL::SSLError,
"The certificate for 'CN=signed' does not match its private key")
end
it 'trusts additional system certs' do
path = tmpfile('system_cacerts')
File.write(path, cert_fixture('ca.pem').to_pem)
expect_any_instance_of(OpenSSL::X509::Store).to receive(:add_file).with(path)
subject.create_system_context(cacerts: [], path: path)
end
it 'ignores empty files' do
path = tmpfile('system_cacerts')
FileUtils.touch(path)
subject.create_system_context(cacerts: [], path: path)
expect(@logs).to eq([])
end
it 'prints an error if it is not a file' do
path = tmpdir('system_cacerts')
subject.create_system_context(cacerts: [], path: path)
expect(@logs).to include(an_object_having_attributes(level: :warning, message: /^The 'ssl_trust_store' setting does not refer to a file and will be ignored/))
end
end
context 'when creating an ssl context with crls' do
let(:config) { { cacerts: global_cacerts, crls: global_crls} }
it 'accepts valid CRLs' do
certs = [cert_fixture('ca.pem')]
crls = [crl_fixture('crl.pem')]
sslctx = subject.create_root_context(**config.merge(cacerts: certs, crls: crls))
expect(sslctx.crls).to eq(crls)
end
it 'accepts valid CRLs for intermediate certs' do
certs = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')]
crls = [crl_fixture('crl.pem'), crl_fixture('intermediate-crl.pem')]
sslctx = subject.create_root_context(**config.merge(cacerts: certs, crls: crls))
expect(sslctx.crls).to eq(crls)
end
it 'accepts expired CRLs' do
expired = [crl_fixture('crl.pem'), crl_fixture('intermediate-crl.pem')]
expired.each { |x509| x509.last_update = Time.at(0) }
sslctx = subject.create_root_context(**config.merge(crls: expired))
expect(sslctx.crls).to eq(expired)
end
it 'verifies peer' do
sslctx = subject.create_root_context(**config)
expect(sslctx.verify_peer).to eq(true)
end
end
context 'when creating an ssl context with client certs' do
let(:client_cert) { cert_fixture('signed.pem') }
let(:private_key) { key_fixture('signed-key.pem') }
let(:config) { { cacerts: global_cacerts, crls: global_crls, client_cert: client_cert, private_key: private_key } }
it 'raises if CA certs are missing' do
expect {
subject.create_context(**config.merge(cacerts: nil))
}.to raise_error(ArgumentError, /CA certs are missing/)
end
it 'raises if CRLs are missing' do
expect {
subject.create_context(**config.merge(crls: nil))
}.to raise_error(ArgumentError, /CRLs are missing/)
end
it 'raises if private key is missing' do
expect {
subject.create_context(**config.merge(private_key: nil))
}.to raise_error(ArgumentError, /Private key is missing/)
end
it 'raises if client cert is missing' do
expect {
subject.create_context(**config.merge(client_cert: nil))
}.to raise_error(ArgumentError, /Client cert is missing/)
end
it 'accepts RSA keys' do
sslctx = subject.create_context(**config)
expect(sslctx.private_key).to eq(private_key)
end
it 'accepts EC keys' do
ec_key = ec_key_fixture('ec-key.pem')
ec_cert = cert_fixture('ec.pem')
sslctx = subject.create_context(**config.merge(client_cert: ec_cert, private_key: ec_key))
expect(sslctx.private_key).to eq(ec_key)
end
it 'raises if private key is unsupported' do
dsa_key = OpenSSL::PKey::DSA.new
expect {
subject.create_context(**config.merge(private_key: dsa_key))
}.to raise_error(Puppet::SSL::SSLError, /Unsupported key 'OpenSSL::PKey::DSA'/)
end
it 'resolves the client chain from leaf to root' do
sslctx = subject.create_context(**config)
expect(
sslctx.client_chain.map(&:subject).map(&:to_utf8)
).to eq(['CN=signed', 'CN=Test CA Subauthority', 'CN=Test CA'])
end
it 'raises if client cert signature is invalid' do
client_cert.public_key = wrong_key.public_key
client_cert.sign(wrong_key, OpenSSL::Digest::SHA256.new)
expect {
subject.create_context(**config.merge(client_cert: client_cert))
}.to raise_error(Puppet::SSL::CertVerifyError,
"Invalid signature for certificate 'CN=signed'")
end
it 'raises if client cert and private key are mismatched' do
expect {
subject.create_context(**config.merge(private_key: wrong_key))
}.to raise_error(Puppet::SSL::SSLError,
"The certificate for 'CN=signed' does not match its private key")
end
it "raises if client cert's public key has been replaced" do
expect {
subject.create_context(**config.merge(client_cert: cert_fixture('tampered-cert.pem')))
}.to raise_error(Puppet::SSL::CertVerifyError,
"Invalid signature for certificate 'CN=signed'")
end
# This option is only available in openssl 1.1
# OpenSSL 1.1.1h no longer reports expired root CAs when using "verify".
# This regression was fixed in 1.1.1i, so only skip this test if we're on
# the affected version.
# See: https://github.com/openssl/openssl/pull/13585
if Puppet::Util::Package.versioncmp(OpenSSL::OPENSSL_LIBRARY_VERSION.split[1], '1.1.1h') != 0
it 'raises if root cert signature is invalid', if: defined?(OpenSSL::X509::V_FLAG_CHECK_SS_SIGNATURE) do
ca = global_cacerts.first
ca.sign(wrong_key, OpenSSL::Digest::SHA256.new)
expect {
subject.create_context(**config.merge(cacerts: global_cacerts))
}.to raise_error(Puppet::SSL::CertVerifyError,
"Invalid signature for certificate 'CN=Test CA'")
end
end
it 'raises if intermediate CA signature is invalid', unless: Puppet::Util::Platform.jruby? && RUBY_VERSION.to_f >= 2.6 do
int = global_cacerts.last
int.public_key = wrong_key.public_key if Puppet::Util::Platform.jruby?
int.sign(wrong_key, OpenSSL::Digest::SHA256.new)
expect {
subject.create_context(**config.merge(cacerts: global_cacerts))
}.to raise_error(Puppet::SSL::CertVerifyError,
"Invalid signature for certificate 'CN=Test CA Subauthority'")
end
it 'raises if CRL signature for root CA is invalid', unless: Puppet::Util::Platform.jruby? do
crl = global_crls.first
crl.sign(wrong_key, OpenSSL::Digest::SHA256.new)
expect {
subject.create_context(**config.merge(crls: global_crls))
}.to raise_error(Puppet::SSL::CertVerifyError,
"Invalid signature for CRL issued by 'CN=Test CA'")
end
it 'raises if CRL signature for intermediate CA is invalid', unless: Puppet::Util::Platform.jruby? do
crl = global_crls.last
crl.sign(wrong_key, OpenSSL::Digest::SHA256.new)
expect {
subject.create_context(**config.merge(crls: global_crls))
}.to raise_error(Puppet::SSL::CertVerifyError,
"Invalid signature for CRL issued by 'CN=Test CA Subauthority'")
end
it 'raises if client cert is revoked' do
expect {
subject.create_context(**config.merge(private_key: key_fixture('revoked-key.pem'), client_cert: cert_fixture('revoked.pem')))
}.to raise_error(Puppet::SSL::CertVerifyError,
"Certificate 'CN=revoked' is revoked")
end
it 'warns if intermediate issuer is missing' do
expect(Puppet).to receive(:warning).with("The issuer 'CN=Test CA Subauthority' of certificate 'CN=signed' cannot be found locally")
subject.create_context(**config.merge(cacerts: [cert_fixture('ca.pem')]))
end
it 'raises if root issuer is missing' do
expect {
subject.create_context(**config.merge(cacerts: [cert_fixture('intermediate.pem')]))
}.to raise_error(Puppet::SSL::CertVerifyError,
"The issuer 'CN=Test CA' of certificate 'CN=Test CA Subauthority' is missing")
end
it 'raises if cert is not valid yet', unless: Puppet::Util::Platform.jruby? do
client_cert.not_before = Time.now + (5 * 60 * 60)
int_key = key_fixture('intermediate-key.pem')
client_cert.sign(int_key, OpenSSL::Digest::SHA256.new)
expect {
subject.create_context(**config.merge(client_cert: client_cert))
}.to raise_error(Puppet::SSL::CertVerifyError,
"The certificate 'CN=signed' is not yet valid, verify time is synchronized")
end
it 'raises if cert is expired', unless: Puppet::Util::Platform.jruby? do
client_cert.not_after = Time.at(0)
int_key = key_fixture('intermediate-key.pem')
client_cert.sign(int_key, OpenSSL::Digest::SHA256.new)
expect {
subject.create_context(**config.merge(client_cert: client_cert))
}.to raise_error(Puppet::SSL::CertVerifyError,
"The certificate 'CN=signed' has expired, verify time is synchronized")
end
it 'raises if crl is not valid yet', unless: Puppet::Util::Platform.jruby? do
future_crls = global_crls
# invalidate the CRL issued by the root
future_crls.first.last_update = Time.now + (5 * 60 * 60)
expect {
subject.create_context(**config.merge(crls: future_crls))
}.to raise_error(Puppet::SSL::CertVerifyError,
"The CRL issued by 'CN=Test CA' is not yet valid, verify time is synchronized")
end
it 'raises if crl is expired', unless: Puppet::Util::Platform.jruby? do
past_crls = global_crls
# invalidate the CRL issued by the root
past_crls.first.next_update = Time.at(0)
expect {
subject.create_context(**config.merge(crls: past_crls))
}.to raise_error(Puppet::SSL::CertVerifyError,
"The CRL issued by 'CN=Test CA' has expired, verify time is synchronized")
end
it 'raises if the root CRL is missing' do
crls = [crl_fixture('intermediate-crl.pem')]
expect {
subject.create_context(**config.merge(crls: crls, revocation: :chain))
}.to raise_error(Puppet::SSL::CertVerifyError,
"The CRL issued by 'CN=Test CA' is missing")
end
it 'raises if the intermediate CRL is missing' do
crls = [crl_fixture('crl.pem')]
expect {
subject.create_context(**config.merge(crls: crls))
}.to raise_error(Puppet::SSL::CertVerifyError,
"The CRL issued by 'CN=Test CA Subauthority' is missing")
end
it "doesn't raise if the root CRL is missing and we're just checking the leaf" do
crls = [crl_fixture('intermediate-crl.pem')]
subject.create_context(**config.merge(crls: crls, revocation: :leaf))
end
it "doesn't raise if the intermediate CRL is missing and revocation checking is disabled" do
crls = [crl_fixture('crl.pem')]
subject.create_context(**config.merge(crls: crls, revocation: false))
end
it "doesn't raise if both CRLs are missing and revocation checking is disabled" do
subject.create_context(**config.merge(crls: [], revocation: false))
end
# OpenSSL < 1.1 does not verify basicConstraints
it "raises if root CA's isCA basic constraint is false", unless: Puppet::Util::Platform.jruby? || OpenSSL::OPENSSL_VERSION_NUMBER < 0x10100000 do
certs = [cert_fixture('bad-basic-constraints.pem'), cert_fixture('intermediate.pem')]
# openssl 3 returns 79
# define X509_V_ERR_NO_ISSUER_PUBLIC_KEY 24
# define X509_V_ERR_INVALID_CA 79
expect {
subject.create_context(**config.merge(cacerts: certs, crls: [], revocation: false))
}.to raise_error(Puppet::SSL::CertVerifyError,
/Certificate 'CN=Test CA' failed verification \((24|79)\): invalid CA certificate/)
end
# OpenSSL < 1.1 does not verify basicConstraints
it "raises if intermediate CA's isCA basic constraint is false", unless: Puppet::Util::Platform.jruby? || OpenSSL::OPENSSL_VERSION_NUMBER < 0x10100000 do
certs = [cert_fixture('ca.pem'), cert_fixture('bad-int-basic-constraints.pem')]
expect {
subject.create_context(**config.merge(cacerts: certs, crls: [], revocation: false))
}.to raise_error(Puppet::SSL::CertVerifyError,
/Certificate 'CN=Test CA Subauthority' failed verification \((24|79)\): invalid CA certificate/)
end
it 'accepts CA certs in any order' do
sslctx = subject.create_context(**config.merge(cacerts: global_cacerts.reverse))
# certs in ruby+openssl 1.0.x are not comparable, so compare subjects
expect(sslctx.client_chain.map(&:subject).map(&:to_utf8)).to contain_exactly('CN=Test CA', 'CN=Test CA Subauthority', 'CN=signed')
end
it 'accepts CRLs in any order' do
sslctx = subject.create_context(**config.merge(crls: global_crls.reverse))
# certs in ruby+openssl 1.0.x are not comparable, so compare subjects
expect(sslctx.client_chain.map(&:subject).map(&:to_utf8)).to contain_exactly('CN=Test CA', 'CN=Test CA Subauthority', 'CN=signed')
end
it 'raises if the frozen context is modified' do
sslctx = subject.create_context(**config)
expect {
sslctx.verify_peer = false
}.to raise_error(/can't modify frozen/)
end
it 'verifies peer' do
sslctx = subject.create_context(**config)
expect(sslctx.verify_peer).to eq(true)
end
it 'does not trust the system ca store by default' do
expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths).never
subject.create_context(**config)
end
it 'trusts the system ca store' do
expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths)
subject.create_context(**config.merge(include_system_store: true))
end
end
context 'when loading an ssl context' do
let(:client_cert) { cert_fixture('signed.pem') }
let(:private_key) { key_fixture('signed-key.pem') }
let(:doesnt_exist) { '/does/not/exist' }
before :each do
Puppet[:localcacert] = file_containing('global_cacerts', global_cacerts.first.to_pem)
Puppet[:hostcrl] = file_containing('global_crls', global_crls.first.to_pem)
Puppet[:certname] = 'signed'
Puppet[:privatekeydir] = tmpdir('privatekeydir')
File.write(File.join(Puppet[:privatekeydir], 'signed.pem'), private_key.to_pem)
Puppet[:certdir] = tmpdir('privatekeydir')
File.write(File.join(Puppet[:certdir], 'signed.pem'), client_cert.to_pem)
end
it 'raises if CA certs are missing' do
Puppet[:localcacert] = doesnt_exist
expect {
subject.load_context
}.to raise_error(Puppet::Error, /The CA certificates are missing from/)
end
it 'raises if the CRL is missing' do
Puppet[:hostcrl] = doesnt_exist
expect {
subject.load_context
}.to raise_error(Puppet::Error, /The CRL is missing from/)
end
it 'does not raise if the CRL is missing and revocation is disabled' do
Puppet[:hostcrl] = doesnt_exist
subject.load_context(revocation: false)
end
it 'raises if the private key is missing' do
Puppet[:privatekeydir] = doesnt_exist
expect {
subject.load_context
}.to raise_error(Puppet::Error, /The private key is missing from/)
end
it 'raises if the client cert is missing' do
Puppet[:certdir] = doesnt_exist
expect {
subject.load_context
}.to raise_error(Puppet::Error, /The client certificate is missing from/)
end
context 'loading private keys', unless: RUBY_PLATFORM == 'java' do
it 'loads the private key and client cert' do
ssl_context = subject.load_context
expect(ssl_context.private_key).to be_an(OpenSSL::PKey::RSA)
expect(ssl_context.client_cert).to be_an(OpenSSL::X509::Certificate)
end
it 'loads a password protected key and client cert' do
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), File.join(Puppet[:privatekeydir], 'signed.pem'))
ssl_context = subject.load_context(password: '74695716c8b6')
expect(ssl_context.private_key).to be_an(OpenSSL::PKey::RSA)
expect(ssl_context.client_cert).to be_an(OpenSSL::X509::Certificate)
end
it 'raises if the password is incorrect' do
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), File.join(Puppet[:privatekeydir], 'signed.pem'))
expect {
subject.load_context(password: 'wrongpassword')
}.to raise_error(Puppet::SSL::SSLError, /Failed to load private key for host 'signed': Could not parse PKey/)
end
end
it 'does not trust the system ca store by default' do
expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths).never
subject.load_context
end
it 'trusts the system ca store' do
expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths)
subject.load_context(include_system_store: true)
end
end
context 'when verifying requests' do
let(:csr) { request_fixture('request.pem') }
it 'accepts valid requests' do
private_key = key_fixture('request-key.pem')
expect(subject.verify_request(csr, private_key.public_key)).to eq(csr)
end
it "raises if the CSR was signed by a private key that doesn't match public key" do
expect {
subject.verify_request(csr, wrong_key.public_key)
}.to raise_error(Puppet::SSL::SSLError,
"The CSR for host 'CN=pending' does not match the public key")
end
it "raises if the CSR was tampered with" do
csr = request_fixture('tampered-csr.pem')
expect {
subject.verify_request(csr, csr.public_key)
}.to raise_error(Puppet::SSL::SSLError,
"The CSR for host 'CN=signed' does not match the public key")
end
end
context 'printing' do
let(:client_cert) { cert_fixture('signed.pem') }
let(:private_key) { key_fixture('signed-key.pem') }
let(:config) { { cacerts: global_cacerts, crls: global_crls, client_cert: client_cert, private_key: private_key } }
it 'prints in debug' do
Puppet[:log_level] = 'debug'
ctx = subject.create_context(**config)
subject.print(ctx)
expect(@logs.map(&:message)).to include(
/Verified CA certificate 'CN=Test CA' fingerprint/,
/Verified CA certificate 'CN=Test CA Subauthority' fingerprint/,
/Verified client certificate 'CN=signed' fingerprint/,
/Using CRL 'CN=Test CA' authorityKeyIdentifier '(keyid:)?[A-Z0-9:]{59}' crlNumber '0'/,
/Using CRL 'CN=Test CA Subauthority' authorityKeyIdentifier '(keyid:)?[A-Z0-9:]{59}' crlNumber '0'/
)
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/ssl/verifier_spec.rb | spec/unit/ssl/verifier_spec.rb | require 'spec_helper'
describe Puppet::SSL::Verifier do
let(:options) { {} }
let(:ssl_context) { Puppet::SSL::SSLContext.new(options) }
let(:host) { 'example.com' }
let(:http) { Net::HTTP.new(host) }
let(:verifier) { described_class.new(host, ssl_context) }
context '#reusable?' do
it 'Verifiers with the same ssl_context are reusable' do
expect(verifier).to be_reusable(described_class.new(host, ssl_context))
end
it 'Verifiers with different ssl_contexts are not reusable' do
expect(verifier).to_not be_reusable(described_class.new(host, Puppet::SSL::SSLContext.new))
end
end
context '#setup_connection' do
it 'copies parameters from the ssl_context to the connection' do
store = double('store')
options.merge!(store: store)
verifier.setup_connection(http)
expect(http.cert_store).to eq(store)
end
it 'defaults to VERIFY_PEER' do
expect(http).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER)
verifier.setup_connection(http)
end
it 'only uses VERIFY_NONE if explicitly disabled' do
options.merge!(verify_peer: false)
expect(http).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE)
verifier.setup_connection(http)
end
it 'registers a verify callback' do
verifier.setup_connection(http)
expect(http.verify_callback).to eq(verifier)
end
end
context '#handle_connection_error' do
let(:peer_cert) { cert_fixture('127.0.0.1.pem') }
let(:chain) { [peer_cert] }
let(:ssl_error) { OpenSSL::SSL::SSLError.new("certificate verify failed") }
it "raises a verification error for a CA cert" do
store_context = double('store_context', current_cert: peer_cert, chain: [peer_cert], error: OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, error_string: "unable to get local issuer certificate")
verifier.call(false, store_context)
expect {
verifier.handle_connection_error(http, ssl_error)
}.to raise_error(Puppet::SSL::CertVerifyError, "certificate verify failed [unable to get local issuer certificate for CN=127.0.0.1]")
end
it "raises a verification error for the server cert" do
store_context = double('store_context', current_cert: peer_cert, chain: chain, error: OpenSSL::X509::V_ERR_CERT_REJECTED, error_string: "certificate rejected")
verifier.call(false, store_context)
expect {
verifier.handle_connection_error(http, ssl_error)
}.to raise_error(Puppet::SSL::CertVerifyError, "certificate verify failed [certificate rejected for CN=127.0.0.1]")
end
it "raises cert mismatch error on ruby < 2.4" do
expect(http).to receive(:peer_cert).and_return(peer_cert)
store_context = double('store_context')
verifier.call(true, store_context)
ssl_error = OpenSSL::SSL::SSLError.new("hostname 'example'com' does not match the server certificate")
expect {
verifier.handle_connection_error(http, ssl_error)
}.to raise_error(Puppet::Error, "Server hostname 'example.com' did not match server certificate; expected one of 127.0.0.1, DNS:127.0.0.1, DNS:127.0.0.2")
end
it "raises cert mismatch error on ruby >= 2.4" do
store_context = double('store_context', current_cert: peer_cert, chain: chain, error: OpenSSL::X509::V_OK, error_string: "ok")
verifier.call(false, store_context)
expect {
verifier.handle_connection_error(http, ssl_error)
}.to raise_error(Puppet::Error, "Server hostname 'example.com' did not match server certificate; expected one of 127.0.0.1, DNS:127.0.0.1, DNS:127.0.0.2")
end
it 're-raises other ssl connection errors' do
err = OpenSSL::SSL::SSLError.new("This version of OpenSSL does not support FIPS mode")
expect {
verifier.handle_connection_error(http, err)
}.to raise_error(err)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/ssl/certificate_signer_spec.rb | spec/unit/ssl/certificate_signer_spec.rb | require 'spec_helper'
describe Puppet::SSL::CertificateSigner do
include PuppetSpec::Files
let(:wrong_key) { OpenSSL::PKey::RSA.new(512) }
let(:client_cert) { cert_fixture('signed.pem') }
# jruby-openssl >= 0.13.0 (JRuby >= 9.3.5.0) raises an error when signing a
# certificate when there is a discrepancy between the certificate and key.
it 'raises if client cert signature is invalid', if: Puppet::Util::Platform.jruby? && RUBY_VERSION.to_f >= 2.6 do
expect {
client_cert.sign(wrong_key, OpenSSL::Digest::SHA256.new)
}.to raise_error(OpenSSL::X509::CertificateError,
'invalid public key data')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/gettext/module_loading_spec.rb | spec/unit/gettext/module_loading_spec.rb | require 'spec_helper'
require 'puppet_spec/modules'
require 'puppet_spec/files'
require 'puppet/gettext/module_translations'
describe Puppet::ModuleTranslations do
include PuppetSpec::Files
describe "loading translations from the module path" do
let(:modpath) { tmpdir('modpath') }
let(:module_a) { PuppetSpec::Modules.create(
"mod_a",
modpath,
:metadata => {
:author => 'foo'
},
:environment => double("environment"))
}
let(:module_b) { PuppetSpec::Modules.create(
"mod_b",
modpath,
:metadata => {
:author => 'foo'
},
:environment => double("environment"))
}
it "should attempt to load translations only for modules that have them" do
expect(module_a).to receive(:has_translations?).and_return(false)
expect(module_b).to receive(:has_translations?).and_return(true)
expect(Puppet::GettextConfig).to receive(:load_translations).with("foo-mod_b", File.join(modpath, "mod_b", "locales"), :po).and_return(true)
Puppet::ModuleTranslations.load_from_modulepath([module_a, module_b])
end
end
describe "loading translations from $vardir" do
let(:vardir) {
dir_containing("vardir",
{ "locales" => { "ja" => { "foo-mod_a.po" => "" } } })
}
it "should attempt to load translations for the current locale" do
expect(Puppet::GettextConfig).to receive(:current_locale).and_return("ja")
expect(Puppet::GettextConfig).to receive(:load_translations).with("foo-mod_a", File.join(vardir, "locales"), :po).and_return(true)
Puppet::ModuleTranslations.load_from_vardir(vardir)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/gettext/config_spec.rb | spec/unit/gettext/config_spec.rb | require 'puppet/gettext/config'
require 'spec_helper'
describe Puppet::GettextConfig do
require 'puppet_spec/files'
include PuppetSpec::Files
include Puppet::GettextConfig
let(:local_path) do
local_path ||= Puppet::GettextConfig::LOCAL_PATH
end
let(:windows_path) do
windows_path ||= Puppet::GettextConfig::WINDOWS_PATH
end
let(:posix_path) do
windows_path ||= Puppet::GettextConfig::POSIX_PATH
end
before(:each) do
allow(Puppet::GettextConfig).to receive(:gettext_loaded?).and_return(true)
end
after(:each) do
Puppet::GettextConfig.set_locale('en')
Puppet::GettextConfig.delete_all_text_domains
end
# These tests assume gettext is enabled, but it will be disabled when the
# first time the `Puppet[:disable_i18n]` setting is resolved
around(:each) do |example|
disabled = Puppet::GettextConfig.instance_variable_get(:@gettext_disabled)
Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, false)
begin
example.run
ensure
Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, disabled)
end
end
describe 'setting and getting the locale' do
it 'should return "en" when gettext is unavailable' do
allow(Puppet::GettextConfig).to receive(:gettext_loaded?).and_return(false)
expect(Puppet::GettextConfig.current_locale).to eq('en')
end
it 'should allow the locale to be set' do
Puppet::GettextConfig.set_locale('hu')
expect(Puppet::GettextConfig.current_locale).to eq('hu')
end
end
describe 'translation mode selection' do
it 'should select PO mode when given a local config path' do
expect(Puppet::GettextConfig.translation_mode(local_path)).to eq(:po)
end
it 'should select PO mode when given a non-package config path' do
expect(Puppet::GettextConfig.translation_mode('../fake/path')).to eq(:po)
end
it 'should select MO mode when given a Windows package config path' do
expect(Puppet::GettextConfig.translation_mode(windows_path)).to eq(:mo)
end
it 'should select MO mode when given a POSIX package config path' do
expect(Puppet::GettextConfig.translation_mode(posix_path)).to eq(:mo)
end
end
describe 'loading translations' do
context 'when given a nil locale path' do
it 'should return false' do
expect(Puppet::GettextConfig.load_translations('puppet', nil, :po)).to be false
end
end
context 'when given a valid locale file location' do
it 'should return true' do
expect(Puppet::GettextConfig).to receive(:add_repository_to_domain).with('puppet', local_path, :po, anything)
expect(Puppet::GettextConfig.load_translations('puppet', local_path, :po)).to be true
end
end
context 'when given a bad file format' do
it 'should raise an exception' do
expect { Puppet::GettextConfig.load_translations('puppet', local_path, :bad_format) }.to raise_error(Puppet::Error)
end
end
end
describe "setting up text domains" do
it 'can create the default text domain after another is set' do
Puppet::GettextConfig.delete_all_text_domains
FastGettext.text_domain = 'other'
Puppet::GettextConfig.create_default_text_domain
end
it 'should add puppet translations to the default text domain' do
expect(Puppet::GettextConfig).to receive(:load_translations).with('puppet', local_path, :po, Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN).and_return(true)
Puppet::GettextConfig.create_default_text_domain
expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN)
end
it 'should copy default translations when creating a non-default text domain' do
Puppet::GettextConfig.reset_text_domain(:test)
expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test)
end
it 'should normalize domain name when creating a non-default text domain' do
Puppet::GettextConfig.reset_text_domain('test')
expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test)
end
end
describe "clearing the configured text domain" do
it 'succeeds' do
Puppet::GettextConfig.clear_text_domain
expect(FastGettext.text_domain).to eq(FastGettext.default_text_domain)
end
it 'falls back to default' do
Puppet::GettextConfig.reset_text_domain(:test)
expect(FastGettext.text_domain).to eq(:test)
Puppet::GettextConfig.clear_text_domain
expect(FastGettext.text_domain).to eq(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN)
end
end
describe "deleting text domains" do
it 'can delete a text domain by name' do
Puppet::GettextConfig.reset_text_domain(:test)
expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test)
Puppet::GettextConfig.delete_text_domain(:test)
expect(Puppet::GettextConfig.loaded_text_domains).to eq([Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN])
end
it 'can delete all non-default text domains' do
Puppet::GettextConfig.reset_text_domain(:test)
expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test)
Puppet::GettextConfig.delete_environment_text_domains
expect(Puppet::GettextConfig.loaded_text_domains).to eq([Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN])
end
it 'can delete all text domains' do
Puppet::GettextConfig.reset_text_domain(:test)
expect(Puppet::GettextConfig.loaded_text_domains).to include(Puppet::GettextConfig::DEFAULT_TEXT_DOMAIN, :test)
Puppet::GettextConfig.delete_all_text_domains
expect(Puppet::GettextConfig.loaded_text_domains).to be_empty
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/partition_spec.rb | spec/unit/functions/partition_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the partition function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'for an array' do
it 'partitions by item' do
manifest = "notify { String(partition(['', b, ab]) |$s| { $s.empty }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[[[''], ['b', 'ab']]]")
end
it 'partitions by index, item' do
manifest = "notify { String(partition(['', b, ab]) |$i, $s| { $i == 2 or $s.empty }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[[['', 'ab'], ['b']]]")
end
end
context 'for a hash' do
it 'partitions by key-value pair' do
manifest = "notify { String(partition(a => [1, 2], b => []) |$kv| { $kv[1].empty }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[[[['b', []]], [['a', [1, 2]]]]]")
end
it 'partitions by key, value' do
manifest = "notify { String(partition(a => [1, 2], b => []) |$k, $v| { $v.empty }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[[[['b', []]], [['a', [1, 2]]]]]")
end
end
context 'for a string' do
it 'fails' do
manifest = "notify { String(partition('something') |$s| { $s.empty }): }"
expect { compile_to_catalog(manifest) }.to raise_error(Puppet::PreformattedError)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/floor_spec.rb | spec/unit/functions/floor_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the floor function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'for an integer' do
[ 0, 1, -1].each do |x|
it "called as floor(#{x}) results in the same value" do
expect(compile_to_catalog("notify { String( floor(#{x}) == #{x}): }")).to have_resource("Notify[true]")
end
end
end
context 'for a float' do
{
0.0 => 0,
1.1 => 1,
-1.1 => -2,
}.each_pair do |x, expected|
it "called as floor(#{x}) results in #{expected}" do
expect(compile_to_catalog("notify { String( floor(#{x}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'for a string' do
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
{ "0" => 0,
"1" => 1,
"-1" => -1,
"0.0" => 0,
"1.1" => 1,
"-1.1" => -2,
"0777" => 777,
"-0777" => -777,
"0xFF" => 0xFF,
}.each_pair do |x, expected|
it "called as floor('#{x}') results in #{expected} and a deprecation warning" do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String( floor('#{x}') == #{expected}): }")).to have_resource("Notify[true]")
end
expect(warnings).to include(/auto conversion of .* is deprecated/)
end
end
['blue', '0.2.3'].each do |x|
it "errors as the string '#{x}' cannot be converted to a float (indirectly deprecated)" do
expect{ compile_to_catalog("floor('#{x}')") }.to raise_error(/cannot convert given value to a floating point value/)
end
end
end
[[1,2,3], {'a' => 10}].each do |x|
it "errors for a value of class #{x.class} (indirectly deprecated)" do
expect{ compile_to_catalog("floor(#{x})") }.to raise_error(/expects a value of type Numeric or String/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/step_spec.rb | spec/unit/functions/step_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'shared_behaviours/iterative_functions'
describe 'the step method' do
include PuppetSpec::Compiler
it 'raises an error when given a type that cannot be iterated' do
expect do
compile_to_catalog(<<-MANIFEST)
3.14.step(1) |$v| { }
MANIFEST
end.to raise_error(Puppet::Error, /expects an Iterable value, got Float/)
end
it 'raises an error when called with more than two arguments and a block' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].step(1,2) |$v| { }
MANIFEST
end.to raise_error(Puppet::Error, /expects 2 arguments, got 3/)
end
it 'raises an error when called with more than two arguments and without a block' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].step(1,2)
MANIFEST
end.to raise_error(Puppet::Error, /expects 2 arguments, got 3/)
end
it 'raises an error when called with a block with too many required parameters' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].step(1) |$v1, $v2| { }
MANIFEST
end.to raise_error(Puppet::Error, /block expects 1 argument, got 2/)
end
it 'raises an error when called with a block with too few parameters' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].step(1) | | { }
MANIFEST
end.to raise_error(Puppet::Error, /block expects 1 argument, got none/)
end
it 'raises an error when called with step == 0' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].step(0) |$x| { }
MANIFEST
end.to raise_error(Puppet::Error, /'step' expects an Integer\[1\] value, got Integer\[0, 0\]/)
end
it 'raises an error when step is not an integer' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].step('three') |$x| { }
MANIFEST
end.to raise_error(Puppet::Error, /'step' expects an Integer value, got String/)
end
it 'does not raise an error when called with a block with too many but optional arguments' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].step(1) |$v1, $v2=extra| { }
MANIFEST
end.to_not raise_error
end
it 'returns Undef when called with a block' do
expect do
compile_to_catalog(<<-MANIFEST)
assert_type(Undef, [1].step(2) |$x| { $x })
MANIFEST
end.not_to raise_error
end
it 'returns an Iterable when called without a block' do
expect do
compile_to_catalog(<<-MANIFEST)
assert_type(Iterable, [1].step(2))
MANIFEST
end.not_to raise_error
end
it 'should produce "times" interval of integer according to step' do
expect(eval_and_collect_notices('10.step(2) |$x| { notice($x) }')).to eq(['0', '2', '4', '6', '8'])
end
it 'should produce interval of Integer[5,20] according to step' do
expect(eval_and_collect_notices('Integer[5,20].step(4) |$x| { notice($x) }')).to eq(['5', '9', '13', '17'])
end
it 'should produce the elements of [a,b,c,d,e,f,g,h] according to step' do
expect(eval_and_collect_notices('[a,b,c,d,e,f,g,h].step(2) |$x| { notice($x) }')).to eq(%w(a c e g))
end
it 'should produce the elements {a=>1,b=>2,c=>3,d=>4,e=>5,f=>6,g=>7,h=>8} according to step' do
expect(eval_and_collect_notices('{a=>1,b=>2,c=>3,d=>4,e=>5,f=>6,g=>7,h=>8}.step(2) |$t| { notice($t[1]) }')).to eq(%w(1 3 5 7))
end
it 'should produce the choices of Enum[a,b,c,d,e,f,g,h] according to step' do
expect(eval_and_collect_notices('Enum[a,b,c,d,e,f,g,h].step(2) |$x| { notice($x) }')).to eq(%w(a c e g))
end
it 'should produce descending interval of Integer[5,20] when chained after a reverse_each' do
expect(eval_and_collect_notices('Integer[5,20].reverse_each.step(4) |$x| { notice($x) }')).to eq(['20', '16', '12', '8'])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/break_spec.rb | spec/unit/functions/break_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the break function' do
include PuppetSpec::Compiler
include Matchers::Resource
context do
it 'breaks iteration as if at end of input in a map for an array' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[1, 2]]')
function please_break() {
[1,2,3].map |$x| { if $x == 3 { break() } $x }
}
notify { String(please_break()): }
CODE
end
it 'breaks iteration as if at end of input in a map for a hash' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[1, 2]]')
function please_break() {
{'a' => 1, 'b' => 2, 'c' => 3}.map |$x, $y| { if $y == 3 { break() } $y }
}
notify { String(please_break()): }
CODE
end
it 'breaks iteration as if at end of input in a reduce for an array' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[6]')
function please_break() {
[1,2,3,4].reduce |$memo, $x| { if $x == 4 { break() } $memo + $x }
}
notify { String(please_break()): }
CODE
end
it 'breaks iteration as if at end of input in a reduce for a hash' do
expect(compile_to_catalog(<<-CODE)).to have_resource("Notify[['abc', 6]]")
function please_break() {
{'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4}.reduce |$memo, $x| {
if $x[1] == 4 { break() }
$string = "${memo[0]}${x[0]}"
$number = $memo[1] + $x[1]
[$string, $number]
}
}
notify { String(please_break()): }
CODE
end
it 'breaks iteration as if at end of input in an each for an array' do
expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]')
function please_break() {
[1,2,3].each |$x| { if $x == 3 { break() } notify { "$x": } }
}
please_break()
CODE
end
it 'breaks iteration as if at end of input in an each for a hash' do
expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]')
function please_break() {
{'a' => 1, 'b' => 2, 'c' => 3}.each |$x, $y| { if $y == 3 { break() } notify { "$y": } }
}
please_break()
CODE
end
it 'breaks iteration as if at end of input in a reverse_each' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[2]')
function please_break() {
[1,2,3].reverse_each |$x| { if $x == 1 { break() } notify { "$x": } }
}
please_break()
CODE
end
it 'breaks iteration as if at end of input in a map for a hash' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[[1, 2]]')
function please_break() {
{'a' => 1, 'b' => 2, 'c' => 3}.map |$x, $y| { if $y == 3 { break() } $y }
}
notify { String(please_break()): }
CODE
end
it 'breaks iteration as if at end of input in a reduce for an array' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[6]')
function please_break() {
[1,2,3,4].reduce |$memo, $x| { if $x == 4 { break() } $memo + $x }
}
notify { String(please_break()): }
CODE
end
it 'breaks iteration as if at end of input in a reduce for a hash' do
expect(compile_to_catalog(<<-CODE)).to have_resource("Notify[['abc', 6]]")
function please_break() {
{'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4}.reduce |$memo, $x| {
if $x[1] == 4 { break() }
$string = "${memo[0]}${x[0]}"
$number = $memo[1] + $x[1]
[$string, $number]
}
}
notify { String(please_break()): }
CODE
end
it 'breaks iteration as if at end of input in an each for an array' do
expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]')
function please_break() {
[1,2,3].each |$x| { if $x == 3 { break() } notify { "$x": } }
}
please_break()
CODE
end
it 'breaks iteration as if at end of input in an each for a hash' do
expect(compile_to_catalog(<<-CODE)).to_not have_resource('Notify[3]')
function please_break() {
{'a' => 1, 'b' => 2, 'c' => 3}.each |$x, $y| { if $y == 3 { break() } notify { "$y": } }
}
please_break()
CODE
end
it 'breaks iteration as if at end of input in a reverse_each' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[2]')
function please_break() {
[1,2,3].reverse_each |$x| { if $x == 1 { break() } notify { "$x": } }
}
please_break()
CODE
end
it 'does not provide early exit from a class' do
# A break would semantically mean that the class should not be included - as if the
# iteration over class names should stop. That is too magic and should
# be done differently by the user.
#
expect do
compile_to_catalog(<<-CODE)
class does_break {
notice 'a'
if 1 == 1 { break() } # avoid making next line statically unreachable
notice 'b'
}
include(does_break)
CODE
end.to raise_error(/break\(\) from context where this is illegal .*/)
end
it 'does not provide early exit from a define' do
# A break would semantically mean that the resource should not be created - as if the
# iteration over resource titles should stop. That is too magic and should
# be done differently by the user.
#
expect do
compile_to_catalog(<<-CODE)
define does_break {
notice 'a'
if 1 == 1 { break() } # avoid making next line statically unreachable
notice 'b'
}
does_break { 'no_you_cannot': }
CODE
end.to raise_error(/break\(\) from context where this is illegal .*/)
end
it 'can be called when nested in a function to make that function behave as a break' do
# This allows functions like break_when(...) to be implemented by calling break() conditionally
#
expect(eval_and_collect_notices(<<-CODE)).to eql(['[100]'])
function nested_break($x) {
if $x == 2 { break() } else { $x * 100 }
}
function example() {
[1,2,3].map |$x| { nested_break($x) }
}
notice example()
CODE
end
it 'can not be called nested from top scope' do
expect do
compile_to_catalog(<<-CODE)
# line 1
# line 2
$result = with(1) |$x| { with($x) |$x| {break() }}
notice $result
CODE
end.to raise_error(/break\(\) from context where this is illegal .*/)
end
it 'can not be called from top scope' do
expect do
compile_to_catalog(<<-CODE)
# line 1
# line 2
break()
CODE
end.to raise_error(/break\(\) from context where this is illegal .*/)
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/functions/min_spec.rb | spec/unit/functions/min_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the min function' do
include PuppetSpec::Compiler
include Matchers::Resource
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
it 'errors if not give at least one argument' do
expect{ compile_to_catalog("min()") }.to raise_error(/Wrong number of arguments need at least one/)
end
context 'compares numbers' do
{ [0, 1] => 0,
[-1, 0] => -1,
[-1.0, 0] => -1.0,
}.each_pair do |values, expected|
it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do
expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'compares strings that are not numbers without deprecation warning' do
it "string as number is deprecated" do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String( min('a', 'b') == 'a'): }")).to have_resource("Notify[true]")
end
expect(warnings).to_not include(/auto conversion of .* is deprecated/)
end
end
context 'compares strings as numbers if possible and outputs deprecation warning' do
{
[20, "'100'"] => 20,
["'20'", "'100'"] => "'20'",
["'20'", 100] => "'20'",
[20, "'100x'"] => "'100x'",
["20", "'100x'"] => "'100x'",
["'20x'", 100] => 100,
}.each_pair do |values, expected|
it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
expect(warnings).to include(/auto conversion of .* is deprecated/)
end
end
{
[20, "'1e2'"] => 20,
[20, "'1E2'"] => 20,
[20, "'10_0'"] => 20,
[20, "'100.0'"] => 20,
}.each_pair do |values, expected|
it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
expect(warnings).to include(/auto conversion of .* is deprecated/)
end
end
end
context 'compares semver' do
{ ["Semver('2.0.0')", "Semver('10.0.0')"] => "Semver('2.0.0')",
["Semver('5.5.5')", "Semver('5.6.7')"] => "Semver('5.5.5')",
}.each_pair do |values, expected|
it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do
expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'compares timespans' do
{ ["Timespan(2)", "Timespan(77.3)"] => "Timespan(2)",
["Timespan('1-00:00:00')", "Timespan('2-00:00:00')"] => "Timespan('1-00:00:00')",
}.each_pair do |values, expected|
it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do
expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'compares timestamps' do
{ ["Timestamp(0)", "Timestamp(298922400)"] => "Timestamp(0)",
["Timestamp('1970-01-01T12:00:00.000')", "Timestamp('1979-06-22T18:00:00.000')"] => "Timestamp('1970-01-01T12:00:00.000')",
}.each_pair do |values, expected|
it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected}" do
expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'compares all except numeric and string by conversion to string (and issues deprecation warning)' do
{
[[20], "'a'"] => [20], # before since '[' is before 'a'
["{'a' => 10}", "'|a'"] => "{'a' => 10}", # before since '{' is before '|'
[false, 'fal'] => "'fal'", # 'fal' before since shorter than 'false'
['/b/', "'(?-mix:a)'"] => "'(?-mix:a)'", # because regexp to_s is a (?-mix:b) string
["Timestamp(1)", "'1556 a.d'"] => "'1556 a.d'", # because timestamp to_s is a date-time string here starting with 1970
}.each_pair do |values, expected|
it "called as min(#{values[0]}, #{values[1]}) results in the value #{expected} and issues deprecation warning" do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String( min(#{values[0]}, #{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
expect(warnings).to include(/auto conversion of .* is deprecated/)
end
end
end
it "accepts a lambda that takes over the comparison (here avoiding the string as number conversion)" do
src = <<-SRC
$val = min("2", "10") |$a, $b| { compare($a, $b) }
notify { String( $val == "10"): }
SRC
expect(compile_to_catalog(src)).to have_resource("Notify[true]")
end
context 'compares entries in a single array argument as if they were splatted as individual args' do
{
[1,2,3] => 1,
["1", "2","3"] => "'1'",
[1,"2",3] => 1,
}.each_pair do |value, expected|
it "called as max(#{value}) results in the value #{expected}" do
src = "notify { String( min(#{value}) == #{expected}): }"
expect(compile_to_catalog(src)).to have_resource("Notify[true]")
end
end
{
[1,2,3] => 1,
["10","2","3"] => "'10'",
[1,"x",3] => "'x'",
}.each_pair do |value, expected|
it "called as max(#{value}) with a lambda using compare() results in the value #{expected}" do
src = <<-"SRC"
function n_after_s($a,$b) {
case [$a, $b] {
[String, Numeric]: { -1 }
[Numeric, String]: { 1 }
default: { compare($a, $b) }
}
}
notify { String( min(#{value}) |$a,$b| {n_after_s($a,$b) } == #{expected}): }
SRC
expect(compile_to_catalog(src)).to have_resource("Notify[true]")
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/getvar_spec.rb | spec/unit/functions/getvar_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the getvar function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'returns undef value' do
it 'when result is undef due to missing variable' do
expect( evaluate(source: "getvar('x')")).to be_nil
end
it 'when result is undef due to resolved undef variable value' do
expect( evaluate(source: "$x = undef; getvar('x')")).to be_nil
end
it 'when result is undef due to navigation into undef' do
expect( evaluate(source: "$x = undef; getvar('x.0')")).to be_nil
end
end
context 'returns default value' do
it 'when result is undef due to missing variable' do
expect( evaluate(source: "getvar('x', 'ok')")).to eql('ok')
end
it 'when result is undef due to resolved undef variable value' do
expect( evaluate(source: "$x = undef; getvar('x', 'ok')")).to eql('ok')
end
it 'when result is undef due to navigation into undef' do
expect( evaluate(source: "$x = undef; getvar('x.0', 'ok')")).to eql('ok')
end
end
it 'returns value of $variable if dotted navigation is not present' do
expect(evaluate(source: "$x = 'testing'; getvar('x')")).to eql('testing')
end
it 'returns value of fully qualified $namespace::variable if dotted navigation is not present' do
expect(evaluate(
code:
"class testing::nested { $x = ['ok'] } include 'testing::nested'",
source:
"getvar('testing::nested::x.0')"
)).to eql('ok')
end
it 'navigates into $variable if given dot syntax after variable name' do
expect(
evaluate(
variables: {'x'=> ['nope', ['ok']]},
source: "getvar('x.1.0')"
)
).to eql('ok')
end
it 'can navigate a key with . when it is quoted' do
expect(
evaluate(
variables: {'x' => {'a.b' => ['nope', ['ok']]}},
source: "getvar('x.\"a.b\".1.0')"
)
).to eql('ok')
end
it 'an error is raised when navigating with string key into an array' do
expect {
evaluate(source: "$x =['nope', ['ok']]; getvar('x.1.blue')")
}.to raise_error(/The given data requires an Integer index/)
end
['X', ':::x', 'x:::x', 'x-x', '_x::x', 'x::', '1'].each do |var_string|
it "an error pointing out that varible is invalid is raised for variable '#{var_string}'" do
expect {
evaluate(source: "getvar(\"#{var_string}.1.blue\")")
}.to raise_error(/The given string does not start with a valid variable name/)
end
end
it 'calls a given block with EXPECTED_INTEGER_INDEX if navigating into array with string' do
expect(evaluate(
source:
"$x = ['nope', ['ok']]; getvar('x.1.blue') |$error| {
if $error.issue_code =~ /^EXPECTED_INTEGER_INDEX$/ {'ok'} else { 'nope'}
}"
)).to eql('ok')
end
it 'calls a given block with EXPECTED_COLLECTION if navigating into something not Undef or Collection' do
expect(evaluate(
source:
"$x = ['nope', /nah/]; getvar('x.1.blue') |$error| {
if $error.issue_code =~ /^EXPECTED_COLLECTION$/ {'ok'} else { 'nope'}
}"
)).to eql('ok')
end
context 'it does not pick the default value when undef is returned by error handling block' do
it 'for "expected integer" case' do
expect(evaluate(
source: "$x = ['nope', ['ok']]; getvar('x.1.blue', 'nope') |$msg| { undef }"
)).to be_nil
end
it 'for "expected collection" case' do
expect(evaluate(
source: "$x = ['nope', /nah/]; getvar('x.1.blue') |$msg| { undef }"
)).to be_nil
end
end
it 'does not call a given block if navigation string has syntax error' do
expect {evaluate(
source: "$x = ['nope', /nah/]; getvar('x.1....') |$msg| { fail('so sad') }"
)}.to raise_error(/Syntax error/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/any_spec.rb | spec/unit/functions/any_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'shared_behaviours/iterative_functions'
describe 'the any method' do
include PuppetSpec::Compiler
context "should be callable as" do
it 'any on an array' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$n = $a.any |$v| { $v == 2 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'any on an array with index' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.any |$i, $v| { $i == 2 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'any on a hash selecting entries' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>'ah','b'=>'be','c'=>'ce'}
$n = $a.any |$e| { $e[1] == 'be' }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'any on a hash selecting key and value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>'ah','b'=>'be','c'=>'ce'}
$n = $a.any |$k, $v| { $v == 'be' }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
end
context 'stops iteration when result is known' do
it 'true when boolean true is found' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$n = $a.any |$v| { if $v == 1 { true } else { fail("unwanted") } }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
end
context "produces a boolean" do
it 'true when boolean true is found' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.any |$v| { true }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'true when truthy is found' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.any |$v| { 42 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'false when truthy is not found (all undef)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.any |$v| { undef }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "false")['ensure']).to eq('present')
end
it 'false when truthy is not found (all false)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.any |$v| { false }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "false")['ensure']).to eq('present')
end
end
it_should_behave_like 'all iterative functions argument checks', 'any'
it_should_behave_like 'all iterative functions hash handling', 'any'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/require_spec.rb | spec/unit/functions/require_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet/parser/functions'
require 'matchers/containment_matchers'
require 'matchers/resource'
require 'matchers/include_in_order'
require 'unit/functions/shared'
describe 'The "require" function' do
include PuppetSpec::Compiler
include ContainmentMatchers
include Matchers::Resource
before(:each) do
compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
@scope = compiler.topscope
end
it 'includes a class that is not already included' do
catalog = compile_to_catalog(<<-MANIFEST)
class required {
notify { "required": }
}
require required
MANIFEST
expect(catalog.classes).to include("required")
end
it 'sets the require attribute on the requiring resource' do
catalog = compile_to_catalog(<<-MANIFEST)
class required {
notify { "required": }
}
class requiring {
require required
}
include requiring
MANIFEST
requiring = catalog.resource("Class", "requiring")
expect(requiring["require"]).to be_instance_of(Array)
expect(requiring["require"][0]).to be_instance_of(Puppet::Resource)
expect(requiring["require"][0].to_s).to eql("Class[Required]")
end
it 'appends to the require attribute on the requiring resource if it already has requirements' do
catalog = compile_to_catalog(<<-MANIFEST)
class required { }
class also_required { }
class requiring {
require required
require also_required
}
include requiring
MANIFEST
requiring = catalog.resource("Class", "requiring")
expect(requiring["require"]).to be_instance_of(Array)
expect(requiring["require"][0]).to be_instance_of(Puppet::Resource)
expect(requiring["require"][0].to_s).to eql("Class[Required]")
expect(requiring["require"][1]).to be_instance_of(Puppet::Resource)
expect(requiring["require"][1].to_s).to eql("Class[Also_required]")
end
it "includes the class when using a fully qualified anchored name" do
catalog = compile_to_catalog(<<-MANIFEST)
class required {
notify { "required": }
}
require ::required
MANIFEST
expect(catalog.classes).to include("required")
end
it_should_behave_like 'all functions transforming relative to absolute names', :require
it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :require
it_should_behave_like 'an inclusion function, when --tasks is on,', :require
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/match_spec.rb | spec/unit/functions/match_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
describe 'the match function' do
before(:each) do
loaders = Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))
Puppet.push_context({:loaders => loaders}, "test-examples")
end
after(:each) do
Puppet.pop_context()
end
let(:func) do
Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'match')
end
let(:type_parser) { Puppet::Pops::Types::TypeParser.singleton }
it 'matches string and regular expression without captures' do
expect(func.call({}, 'abc123', /[a-z]+[1-9]+/)).to eql(['abc123'])
end
it 'matches string and regular expression with captures' do
expect(func.call({}, 'abc123', /([a-z]+)([1-9]+)/)).to eql(['abc123', 'abc', '123'])
end
it 'produces nil if match is not found' do
expect(func.call({}, 'abc123', /([x]+)([6]+)/)).to be_nil
end
[ 'Pattern[/([a-z]+)([1-9]+)/]', # regexp
'Pattern["([a-z]+)([1-9]+)"]', # string
'Regexp[/([a-z]+)([1-9]+)/]', # regexp type
'Pattern[/x9/, /([a-z]+)([1-9]+)/]', # regexp, first found matches
].each do |pattern|
it "matches string and type #{pattern} with captures" do
expect(func.call({}, 'abc123', type(pattern))).to eql(['abc123', 'abc', '123'])
end
it "matches string with an alias type for #{pattern} with captures" do
expect(func.call({}, 'abc123', alias_type("MyAlias", type(pattern)))).to eql(['abc123', 'abc', '123'])
end
it "matches string with a matching variant type for #{pattern} with captures" do
expect(func.call({}, 'abc123', variant_type(type(pattern)))).to eql(['abc123', 'abc', '123'])
end
end
it 'matches an array of strings and yields a map of the result' do
expect(func.call({}, ['abc123', '2a', 'xyz2'], /([a-z]+)[1-9]+/)).to eql([['abc123', 'abc'], nil, ['xyz2', 'xyz']])
end
it 'raises error if Regexp type without regexp is used' do
expect{func.call({}, 'abc123', type('Regexp'))}.to raise_error(ArgumentError, /Given Regexp Type has no regular expression/)
end
def variant_type(*t)
Puppet::Pops::Types::PVariantType.new(t)
end
def alias_type(name, t)
# Create an alias using a nil AST (which is never used because it is given a type as resolution)
Puppet::Pops::Types::PTypeAliasType.new(name, nil, t)
end
def type(s)
Puppet::Pops::Types::TypeParser.singleton.parse(s)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/return_spec.rb | spec/unit/functions/return_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the return function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'returns from outer function when called from nested block' do
it 'with a given value as function result' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[100]')
function please_return() {
[1,2,3].map |$x| { if $x == 1 { return(100) } 200 }
300
}
notify { String(please_return()): }
CODE
end
it 'with undef value as function result when not given an argument' do
# strict mode is off so behavior this test is trying to check isn't stubbed out
Puppet[:strict_variables] = false
Puppet[:strict] = :warning
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[xy]')
function please_return() {
[1,2,3].map |$x| { if $x == 1 { return() } 200 }
300
}
notify { "x${please_return}y": }
CODE
end
end
it 'can be called without parentheses around the argument' do
expect(compile_to_catalog(<<-CODE)).to have_resource('Notify[100]')
function please_return() {
if 1 == 1 { return 100 }
200
}
notify { String(please_return()): }
CODE
end
it 'provides early exit from a class and keeps the class' do
expect(eval_and_collect_notices(<<-CODE)).to eql(['a', 'c', 'true', 'true'])
class notices_c { notice 'c' }
class does_next {
notice 'a'
if 1 == 1 { return() } # avoid making next line statically unreachable
notice 'b'
}
# include two classes to check that next does not do an early return from
# the include function.
include(does_next, notices_c)
notice defined(does_next)
notice defined(notices_c)
CODE
end
it 'provides early exit from a user defined resource and keeps the resource' do
expect(eval_and_collect_notices(<<-CODE)).to eql(['the_doer_of_next', 'copy_cat', 'true', 'true'])
define does_next {
notice $title
if 1 == 1 { return() } # avoid making next line statically unreachable
notice 'b'
}
define checker {
notice defined(Does_next['the_doer_of_next'])
notice defined(Does_next['copy_cat'])
}
# create two instances to ensure next does not break the entire
# resource expression
does_next { ['the_doer_of_next', 'copy_cat']: }
checker { 'needed_because_evaluation_order': }
CODE
end
it 'can be called when nested in a function to make that function return' do
expect(eval_and_collect_notices(<<-CODE)).to eql(['100'])
function nested_return() {
with(1) |$x| { with($x) |$x| {return(100) }}
}
notice nested_return()
CODE
end
it 'can not be called nested from top scope' do
expect do
compile_to_catalog(<<-CODE)
# line 1
# line 2
$result = with(1) |$x| { with($x) |$x| {return(100) }}
notice $result
CODE
end.to raise_error(/return\(\) from context where this is illegal .*/)
end
it 'can not be called from top scope' do
expect do
compile_to_catalog(<<-CODE)
# line 1
# line 2
return()
CODE
end.to raise_error(/return\(\) from context where this is illegal .*/)
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/functions/downcase_spec.rb | spec/unit/functions/downcase_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the downcase function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'returns lower case version of a string' do
expect(compile_to_catalog("notify { 'ABC'.downcase: }")).to have_resource('Notify[abc]')
end
it 'returns the value if Numeric' do
expect(compile_to_catalog("notify { String(42.downcase == 42): }")).to have_resource('Notify[true]')
end
it 'performs downcase of international UTF-8 characters' do
expect(compile_to_catalog("notify { 'ÅÄÖ'.downcase: }")).to have_resource('Notify[åäö]')
end
it 'returns lower case version of each entry in an array (recursively)' do
expect(compile_to_catalog("notify { String(['A', ['B', ['C']]].downcase == ['a', ['b', ['c']]]): }")).to have_resource('Notify[true]')
end
it 'returns lower case version of keys and values in a hash (recursively)' do
expect(compile_to_catalog("notify { String({'A'=>'B','C'=>{'D'=>'E'}}.downcase == {'a'=>'b', 'c'=>{'d'=>'e'}}): }")).to have_resource('Notify[true]')
end
it 'returns lower case version of keys and values in nested hash / array structure' do
expect(compile_to_catalog("notify { String({'A'=>['B'],'C'=>[{'D'=>'E'}]}.downcase == {'a'=>['b'],'c'=>[{'d'=>'e'}]}): }")).to have_resource('Notify[true]')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/new_spec.rb | spec/unit/functions/new_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the new function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'yields converted value if given a block' do
expect(compile_to_catalog(<<-MANIFEST
$x = Integer.new('42') |$x| { $x+2 }
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 44]')
end
it 'produces undef if given an undef value and type accepts it' do
expect(compile_to_catalog(<<-MANIFEST
$x = Optional[Integer].new(undef)
notify { "one${x}word": }
MANIFEST
)).to have_resource('Notify[oneword]')
end
it 'errors if given undef and type does not accept the value' do
expect{compile_to_catalog(<<-MANIFEST
$x = Integer.new(undef)
notify { "one${x}word": }
MANIFEST
)}.to raise_error(Puppet::Error, /of type Undef cannot be converted to Integer/)
end
it 'errors if converted value is not assignable to the type' do
expect{compile_to_catalog(<<-MANIFEST
$x = Integer[1,5].new('42')
notify { "one${x}word": }
MANIFEST
)}.to raise_error(Puppet::Error, /expects an Integer\[1, 5\] value, got Integer\[42, 42\]/)
end
it 'accepts and returns a second parameter that is an instance of the first, even when the type has no backing new_function' do
expect(eval_and_collect_notices(<<-MANIFEST)).to eql(%w(true true true true true true))
notice(undef == Undef(undef))
notice(default == Default(default))
notice(Any == Type(Any))
$b = Binary('YmluYXI=')
notice($b == Binary($b))
$t = Timestamp('2012-03-04T09:10:11.001')
notice($t == Timestamp($t))
type MyObject = Object[{attributes => {'type' => String}}]
$o = MyObject('Remote')
notice($o == MyObject($o))
MANIFEST
end
context 'when invoked on NotUndef' do
it 'produces an instance of the NotUndef nested type' do
expect(compile_to_catalog(<<-MANIFEST
$x = NotUndef[Integer].new(42)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 42]')
end
it 'produces the given value when there is no type specified' do
expect(compile_to_catalog(<<-MANIFEST
$x = NotUndef.new(42)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 42]')
end
end
context 'when invoked on an Integer' do
it 'produces 42 when given the integer 42' do
expect(compile_to_catalog(<<-MANIFEST
$x = Integer.new(42)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 42]')
end
it 'produces 3 when given the float 3.1415' do
expect(compile_to_catalog(<<-MANIFEST
$x = Integer.new(3.1415)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 3]')
end
it 'produces 0 from false' do
expect(compile_to_catalog(<<-MANIFEST
$x = Integer.new(false)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 0]')
end
it 'produces 1 from true' do
expect(compile_to_catalog(<<-MANIFEST
$x = Integer.new(true)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 1]')
end
it "produces an absolute value when third argument is 'true'" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Integer.new(-42, 10, true))
MANIFEST
)).to eql(['42'])
end
it "does not produce an absolute value when third argument is 'false'" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Integer.new(-42, 10, false))
MANIFEST
)).to eql(['-42'])
end
it "produces an absolute value from hash {from => val, abs => true}" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Integer.new({from => -42, abs => true}))
MANIFEST
)).to eql(['42'])
end
it "does not produce an absolute value from hash {from => val, abs => false}" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Integer.new({from => -42, abs => false}))
MANIFEST
)).to eql(['-42'])
end
context 'when prefixed by a sign' do
{ '+1' => 1,
'-1' => -1,
'+ 1' => 1,
'- 1' => -1,
'+0x10' => 16,
'+ 0x10' => 16,
'-0x10' => -16,
'- 0x10' => -16
}.each do |str, result|
it "produces #{result} from the string '#{str}'" do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}")
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource("Notify[Integer, #{result}]")
end
end
end
context "when radix is not set it uses default and" do
{ "10" => 10,
"010" => 8,
"0x10" => 16,
"0X10" => 16,
'0B111' => 7,
'0b111' => 7
}.each do |str, result|
it "produces #{result} from the string '#{str}'" do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}")
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource("Notify[Integer, #{result}]")
end
end
{ '0x0G' => :error,
'08' => :error,
'10F' => :error,
'0B2' => :error,
}.each do |str, result|
it "errors when given a non Integer compliant string '#{str}'" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}")
MANIFEST
)}.to raise_error(Puppet::Error, /invalid value|cannot be converted to Integer/)
end
end
end
context "when radix is explicitly set to 'default' it" do
{ "10" => 10,
"010" => 8,
"0x10" => 16,
"0X10" => 16,
'0B111' => 7,
'0b111' => 7
}.each do |str, result|
it "produces #{result} from the string '#{str}'" do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", default)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource("Notify[Integer, #{result}]")
end
end
end
context "when radix is explicitly set to '2' it" do
{ "10" => 2,
"010" => 2,
"00010" => 2,
'0B111' => 7,
'0b111' => 7,
'+0B111' => 7,
'-0b111' => -7,
'+ 0B111'=> 7,
'- 0b111'=> -7
}.each do |str, result|
it "produces #{result} from the string '#{str}'" do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 2)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource("Notify[Integer, #{result}]")
end
end
{ '0x10' => :error,
'0X10' => :error,
'+0X10' => :error,
'-0X10' => :error,
'+ 0X10'=> :error,
'- 0X10'=> :error
}.each do |str, result|
it "errors when given the non binary value compliant string '#{str}'" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 2)
MANIFEST
)}.to raise_error(Puppet::Error, /invalid value/)
end
end
end
context "when radix is explicitly set to '8' it" do
{ "10" => 8,
"010" => 8,
"00010" => 8,
'+00010' => 8,
'-00010' => -8,
'+ 00010'=> 8,
'- 00010'=> -8,
}.each do |str, result|
it "produces #{result} from the string '#{str}'" do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 8)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource("Notify[Integer, #{result}]")
end
end
{ "0x10" => :error,
'0X10' => :error,
'0B10' => :error,
'0b10' => :error,
'+0b10' => :error,
'-0b10' => :error,
'+ 0b10'=> :error,
'- 0b10'=> :error,
}.each do |str, result|
it "errors when given the non octal value compliant string '#{str}'" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 8)
MANIFEST
)}.to raise_error(Puppet::Error, /invalid value/)
end
end
end
context "when radix is explicitly set to '16' it" do
{ "10" => 16,
"010" => 16,
"00010" => 16,
"0x10" => 16,
"0X10" => 16,
"0b1" => 16*11+1,
"0B1" => 16*11+1,
'+0B1' => 16*11+1,
'-0B1' => -16*11-1,
'+ 0B1' => 16*11+1,
'- 0B1' => -16*11-1,
}.each do |str, result|
it "produces #{result} from the string '#{str}'" do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 16)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource("Notify[Integer, #{result}]")
end
end
{ '0XGG' => :error,
'+0XGG' => :error,
'-0XGG' => :error,
'+ 0XGG'=> :error,
'- 0XGG'=> :error,
}.each do |str, result|
it "errors when given the non hexadecimal value compliant string '#{str}'" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 8)
MANIFEST
)}.to raise_error(Puppet::Error, /The string '#{Regexp.escape(str)}' cannot be converted to Integer/)
end
end
end
context "when radix is explicitly set to '10' it" do
{ "10" => 10,
"010" => 10,
"00010" => 10,
"08" => 8,
"0008" => 8,
}.each do |str, result|
it "produces #{result} from the string '#{str}'" do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 10)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource("Notify[Integer, #{result}]")
end
end
{ '0X10' => :error,
'0b10' => :error,
'0B10' => :error,
}.each do |str, result|
it "errors when given the non binary value compliant string '#{str}'" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new("#{str}", 10)
MANIFEST
)}.to raise_error(Puppet::Error, /invalid value/)
end
end
end
context "input can be given in long form " do
{ {'from' => "10", 'radix' => 2} => 2,
{'from' => "10", 'radix' => 8} => 8,
{'from' => "10", 'radix' => 10} => 10,
{'from' => "10", 'radix' => 16} => 16,
{'from' => "10", 'radix' => :default} => 10,
}.each do |options, result|
it "produces #{result} from the long form '#{options}'" do
src = <<-"MANIFEST"
$x = Integer.new(#{options.to_s.gsub(/:/, '')})
notify { "${type($x, generalized)}, $x": }
MANIFEST
expect(compile_to_catalog(src)).to have_resource("Notify[Integer, #{result}]")
end
end
end
context 'errors when' do
it 'radix is wrong and when given directly' do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new('10', 3)
MANIFEST
)}.to raise_error(Puppet::Error, /Illegal radix/)
end
it 'radix is wrong and when given in long form' do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new({from =>'10', radix=>3})
MANIFEST
)}.to raise_error(Puppet::Error, /Illegal radix/)
end
it 'value is not numeric and given directly' do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new('eleven', 10)
MANIFEST
)}.to raise_error(Puppet::Error, /The string 'eleven' cannot be converted to Integer/)
end
it 'value is not numeric and given in long form' do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Integer.new({from => 'eleven', radix => 10})
MANIFEST
)}.to raise_error(Puppet::Error, /The string 'eleven' cannot be converted to Integer/)
end
end
end
context 'when invoked on Numeric' do
{ 42 => "Notify[Integer, 42]",
42.3 => "Notify[Float, 42.3]",
"42.0" => "Notify[Float, 42.0]",
"+42.0" => "Notify[Float, 42.0]",
"-42.0" => "Notify[Float, -42.0]",
"+ 42.0" => "Notify[Float, 42.0]",
"- 42.0" => "Notify[Float, -42.0]",
"42.3" => "Notify[Float, 42.3]",
"0x10" => "Notify[Integer, 16]",
"010" => "Notify[Integer, 8]",
"0.10" => "Notify[Float, 0.1]",
"0b10" => "Notify[Integer, 2]",
"0" => "Notify[Integer, 0]",
false => "Notify[Integer, 0]",
true => "Notify[Integer, 1]",
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect}" do
expect(compile_to_catalog(<<-MANIFEST
$x = Numeric.new(#{input.inspect})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
it "produces a result when long from hash {from => val} is used" do
expect(compile_to_catalog(<<-MANIFEST
$x = Numeric.new({from=>'42'})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Integer, 42]')
end
it "produces an absolute value when second argument is 'true'" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Numeric.new(-42.3, true))
MANIFEST
)).to eql(['42.3'])
end
it "does not produce an absolute value when second argument is 'false'" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Numeric.new(-42.3, false))
MANIFEST
)).to eql(['-42.3'])
end
it "produces an absolute value from hash {from => val, abs => true}" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Numeric.new({from => -42.3, abs => true}))
MANIFEST
)).to eql(['42.3'])
end
it "does not produce an absolute value from hash {from => val, abs => false}" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Numeric.new({from => -42.3, abs => false}))
MANIFEST
)).to eql(['-42.3'])
end
end
context 'when invoked on Float' do
{ 42 => "Notify[Float, 42.0]",
42.3 => "Notify[Float, 42.3]",
"42.0" => "Notify[Float, 42.0]",
"+42.0" => "Notify[Float, 42.0]",
"-42.0" => "Notify[Float, -42.0]",
"+ 42.0" => "Notify[Float, 42.0]",
"- 42.0" => "Notify[Float, -42.0]",
"42.3" => "Notify[Float, 42.3]",
"0x10" => "Notify[Float, 16.0]",
"010" => "Notify[Float, 10.0]",
"0.10" => "Notify[Float, 0.1]",
false => "Notify[Float, 0.0]",
true => "Notify[Float, 1.0]",
'0b10' => "Notify[Float, 2.0]",
'0B10' => "Notify[Float, 2.0]",
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect}" do
expect(compile_to_catalog(<<-MANIFEST
$x = Float.new(#{input.inspect})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
it "produces a result when long from hash {from => val} is used" do
expect(compile_to_catalog(<<-MANIFEST
$x = Float.new({from=>42})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Float, 42.0]')
end
it "produces an absolute value when second argument is 'true'" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Float.new(-42.3, true))
MANIFEST
)).to eql(['42.3'])
end
it "does not produce an absolute value when second argument is 'false'" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Float.new(-42.3, false))
MANIFEST
)).to eql(['-42.3'])
end
it "produces an absolute value from hash {from => val, abs => true}" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Float.new({from => -42.3, abs => true}))
MANIFEST
)).to eql(['42.3'])
end
it "does not produce an absolute value from hash {from => val, abs => false}" do
expect(eval_and_collect_notices(<<-MANIFEST
notice(Float.new({from => -42.3, abs => false}))
MANIFEST
)).to eql(['-42.3'])
end
end
context 'when invoked on Boolean' do
{ true => 'Notify[Boolean, true]',
false => 'Notify[Boolean, false]',
0 => 'Notify[Boolean, false]',
1 => 'Notify[Boolean, true]',
0.0 => 'Notify[Boolean, false]',
1.0 => 'Notify[Boolean, true]',
'true' => 'Notify[Boolean, true]',
'TrUe' => 'Notify[Boolean, true]',
'yes' => 'Notify[Boolean, true]',
'YeS' => 'Notify[Boolean, true]',
'y' => 'Notify[Boolean, true]',
'Y' => 'Notify[Boolean, true]',
'false' => 'Notify[Boolean, false]',
'no' => 'Notify[Boolean, false]',
'n' => 'Notify[Boolean, false]',
'FalSE' => 'Notify[Boolean, false]',
'nO' => 'Notify[Boolean, false]',
'N' => 'Notify[Boolean, false]',
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect}" do
expect(compile_to_catalog(<<-MANIFEST
$x = Boolean.new(#{input.inspect})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
it "errors when given an non boolean representation like the string 'hello'" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Boolean.new('hello')
MANIFEST
)}.to raise_error(Puppet::Error, /The string 'hello' cannot be converted to Boolean/)
end
it "does not convert an undef (as may be expected, but is handled as every other undef)" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Boolean.new(undef)
MANIFEST
)}.to raise_error(Puppet::Error, /of type Undef cannot be converted to Boolean/)
end
end
context 'when invoked on Array' do
{ [] => 'Notify[Array[Unit], []]',
[true] => 'Notify[Array[Boolean], [true]]',
{'a'=>true, 'b' => false} => 'Notify[Array[Array[ScalarData]], [[a, true], [b, false]]]',
'abc' => 'Notify[Array[String[1, 1]], [a, b, c]]',
3 => 'Notify[Array[Integer], [0, 1, 2]]',
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect} and wrap is not given" do
expect(compile_to_catalog(<<-MANIFEST
$x = Array.new(#{input.inspect})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
{
true => /of type Boolean cannot be converted to Array/,
42.3 => /of type Float cannot be converted to Array/,
}.each do |input, error_match|
it "errors when given an non convertible #{input.inspect} when wrap is not given" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Array.new(#{input.inspect})
MANIFEST
)}.to raise_error(Puppet::Error, error_match)
end
end
{ [] => 'Notify[Array[Unit], []]',
[true] => 'Notify[Array[Boolean], [true]]',
{'a'=>true} => 'Notify[Array[Hash[String, Boolean]], [{a => true}]]',
'hello' => 'Notify[Array[String], [hello]]',
true => 'Notify[Array[Boolean], [true]]',
42 => 'Notify[Array[Integer], [42]]',
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect} and wrap is given" do
expect(compile_to_catalog(<<-MANIFEST
$x = Array.new(#{input.inspect}, true)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
it 'produces an array of byte integer values when given a Binary' do
expect(compile_to_catalog(<<-MANIFEST
$x = Array.new(Binary('ABC', '%s'))
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Array[Integer], [65, 66, 67]]')
end
it 'wraps a binary when given extra argument true' do
expect(compile_to_catalog(<<-MANIFEST
$x = Array[Any].new(Binary('ABC', '%s'), true)
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Array[Binary], [QUJD]]')
end
end
context 'when invoked on Tuple' do
{ 'abc' => 'Notify[Array[String[1, 1]], [a, b, c]]',
3 => 'Notify[Array[Integer], [0, 1, 2]]',
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect} and wrap is not given" do
expect(compile_to_catalog(<<-MANIFEST
$x = Tuple[Any,3].new(#{input.inspect})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
it "errors when tuple requirements are not met" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Tuple[Integer,6].new(3)
MANIFEST
)}.to raise_error(Puppet::Error, /expects size to be at least 6, got 3/)
end
end
context 'when invoked on Hash' do
{ {} => 'Notify[Hash[0, 0], {}]',
[] => 'Notify[Hash[0, 0], {}]',
{'a'=>true} => 'Notify[Hash[String, Boolean], {a => true}]',
[1,2,3,4] => 'Notify[Hash[Integer, Integer], {1 => 2, 3 => 4}]',
[[1,2],[3,4]] => 'Notify[Hash[Integer, Integer], {1 => 2, 3 => 4}]',
'abcd' => 'Notify[Hash[String[1, 1], String[1, 1]], {a => b, c => d}]',
4 => 'Notify[Hash[Integer, Integer], {0 => 1, 2 => 3}]',
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect}" do
expect(compile_to_catalog(<<-MANIFEST
$x = Hash.new(#{input.inspect})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
{ true => /Value of type Boolean cannot be converted to Hash/,
[1,2,3] => /odd number of arguments for Hash/,
}.each do |input, error_match|
it "errors when given an non convertible #{input.inspect}" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Hash.new(#{input.inspect})
MANIFEST
)}.to raise_error(Puppet::Error, error_match)
end
end
context 'when using the optional "tree" format' do
it 'can convert a tree in flat form to a hash' do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2,0], d]], tree)
notify { test: message => $x }
MANIFEST
)).to have_resource('Notify[test]').with_parameter(:message, { 0 => 'a', 1 => { 0 => 'b', 1=> 'c'}, 2 => {0 => 'd'} })
end
it 'preserves array in flattened tree but overwrites entries if they are present' do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2], [overwritten, kept]], [[2,0], d]], tree)
notify { test: message => $x }
MANIFEST
)).to have_resource('Notify[test]').with_parameter(:message, { 0 => 'a', 1 => { 0 => 'b', 1=> 'c'}, 2 => ['d', 'kept'] })
end
it 'preserves hash in flattened tree but overwrites entries if they are present' do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2], {0 => 0, kept => 1}], [[2,0], d]], tree)
notify { test: message => $x }
MANIFEST
)).to have_resource('Notify[test]').with_parameter(:message, { 0 => 'a', 1 => { 0 => 'b', 1=> 'c'}, 2 => {0=>'d', 'kept'=>1} })
end
end
context 'when using the optional "tree_hash" format' do
it 'turns array in flattened tree into hash' do
expect(compile_to_catalog(<<-"MANIFEST"
$x = Hash.new([[[0], a],[[1,0], b],[[1,1], c],[[2], [overwritten, kept]], [[2,0], d]], hash_tree)
notify { test: message => $x }
MANIFEST
)).to have_resource('Notify[test]').with_parameter(:message, { 0=>'a', 1=>{ 0=>'b', 1=>'c'}, 2=>{0=>'d', 1=>'kept'}})
end
end
end
context 'when invoked on Struct' do
{ {'a' => 2} => 'Notify[Struct[{\'a\' => Integer[2, 2]}], {a => 2}]',
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect}" do
expect(compile_to_catalog(<<-MANIFEST
$x = Struct[{a => Integer[2]}].new(#{input.inspect})
notify { "${type($x)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
it "errors when tuple requirements are not met" do
expect{compile_to_catalog(<<-"MANIFEST"
$x = Struct[{a => Integer[2]}].new({a => 0})
MANIFEST
)}.to raise_error(Puppet::Error, /entry 'a' expects an Integer\[2\]/)
end
end
context 'when invoked on String' do
{ {} => 'Notify[String, {}]',
[] => 'Notify[String, []]',
{'a'=>true} => "Notify[String, {'a' => true}]",
[1,2,3,4] => 'Notify[String, [1, 2, 3, 4]]',
[[1,2],[3,4]] => 'Notify[String, [[1, 2], [3, 4]]]',
'abcd' => 'Notify[String, abcd]',
4 => 'Notify[String, 4]',
}.each do |input, result|
it "produces #{result} when given the value #{input.inspect}" do
expect(compile_to_catalog(<<-MANIFEST
$x = String.new(#{input.inspect})
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource(result)
end
end
end
context 'when invoked on a type alias' do
it 'delegates the new to the aliased type' do
expect(compile_to_catalog(<<-MANIFEST
type X = Boolean
$x = X.new('yes')
notify { "${type($x, generalized)}, $x": }
MANIFEST
)).to have_resource('Notify[Boolean, true]')
end
end
context 'when invoked on a Type' do
it 'creates a Type from its string representation' do
expect(compile_to_catalog(<<-MANIFEST
$x = Type.new('Integer[3,10]')
notify { "${type($x)}": }
MANIFEST
)).to have_resource('Notify[Type[Integer[3, 10]]]')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/dig_spec.rb | spec/unit/functions/dig_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the dig function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'returns a value from an array index via integer index' do
expect(compile_to_catalog("notify { [testing].dig(0): }")).to have_resource('Notify[testing]')
end
it 'returns undef if given an undef key' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test-Undef-ing]')
notify { "test-${type([testing].dig(undef))}-ing": }
SOURCE
end
it 'returns undef if starting with undef' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test-Undef-ing]')
notify { "test-${type(undef.dig(undef))}-ing": }
SOURCE
end
it 'returns a value from an hash key via given key' do
expect(compile_to_catalog("notify { {key => testing}.dig(key): }")).to have_resource('Notify[testing]')
end
it 'continues digging if result is an array' do
expect(compile_to_catalog("notify { [nope, [testing]].dig(1, 0): }")).to have_resource('Notify[testing]')
end
it 'continues digging if result is a hash' do
expect(compile_to_catalog("notify { [nope, {yes => testing}].dig(1, yes): }")).to have_resource('Notify[testing]')
end
it 'stops digging when step is undef' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[testing]')
$result = [nope, {yes => testing}].dig(1, no, 2)
notify { "test${result}ing": }
SOURCE
end
it 'errors if step is neither Array nor Hash' do
expect { compile_to_catalog(<<-SOURCE)}.to raise_error(/The given data does not contain a Collection at \[1, "yes"\], got 'String'/)
$result = [nope, {yes => testing}].dig(1, yes, 2)
notify { "test${result}ing": }
SOURCE
end
it 'errors if not given a non Collection as the starting point' do
expect { compile_to_catalog(<<-SOURCE)}.to raise_error(/'dig' parameter 'data' expects a value of type Undef or Collection, got String/)
"hello".dig(1, yes, 2)
SOURCE
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/size_spec.rb | spec/unit/functions/size_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the size function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'for an array it' do
it 'returns 0 when empty' do
expect(compile_to_catalog("notify { String(size([])): }")).to have_resource('Notify[0]')
end
it 'returns number of elements when not empty' do
expect(compile_to_catalog("notify { String(size([1, 2, 3])): }")).to have_resource('Notify[3]')
end
end
context 'for a hash it' do
it 'returns 0 empty' do
expect(compile_to_catalog("notify { String(size({})): }")).to have_resource('Notify[0]')
end
it 'returns number of elements when not empty' do
expect(compile_to_catalog("notify { String(size({1=>1,2=>2})): }")).to have_resource('Notify[2]')
end
end
context 'for a string it' do
it 'returns 0 when empty' do
expect(compile_to_catalog("notify { String(size('')): }")).to have_resource('Notify[0]')
end
it 'returns number of characters when not empty' do
# note the multibyte characters - åäö each taking two bytes in UTF-8
expect(compile_to_catalog('notify { String(size("\u00e5\u00e4\u00f6")): }')).to have_resource('Notify[3]')
end
end
context 'for a binary it' do
it 'returns 0 when empty' do
expect(compile_to_catalog("notify { String(size(Binary(''))): }")).to have_resource('Notify[0]')
end
it 'returns number of bytes when not empty' do
expect(compile_to_catalog("notify { String(size(Binary('b25l'))): }")).to have_resource('Notify[3]')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/inline_epp_spec.rb | spec/unit/functions/inline_epp_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe "the inline_epp function" do
include PuppetSpec::Files
include PuppetSpec::Compiler
let :node do Puppet::Node.new('localhost') end
let :compiler do Puppet::Parser::Compiler.new(node) end
let :scope do Puppet::Parser::Scope.new(compiler) end
context "when accessing scope variables as $ variables" do
it "looks up the value from the scope" do
scope["what"] = "are belong"
expect(eval_template("all your base <%= $what %> to us")).to eq("all your base are belong to us")
end
it "gets error accessing a variable that does not exist" do
expect { eval_template("<%= $kryptonite == undef %>")}.to raise_error(/Evaluation Error: Unknown variable: 'kryptonite'./)
end
it "get nil accessing a variable that does not exist when strict mode is off" do
Puppet[:strict_variables] = false
Puppet[:strict] = :warning
expect(eval_template("<%= $kryptonite == undef %>")).to eq("true")
end
it "get nil accessing a variable that is undef" do
scope['undef_var'] = :undef
expect(eval_template("<%= $undef_var == undef %>")).to eq("true")
end
it "gets shadowed variable if args are given" do
scope['phantom'] = 'of the opera'
expect(eval_template_with_args("<%= $phantom == dragos %>", 'phantom' => 'dragos')).to eq("true")
end
it "gets shadowed variable if args are given and parameters are specified" do
scope['x'] = 'wrong one'
expect(eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct')).to eq("true")
end
it "raises an error if required variable is not given" do
scope['x'] = 'wrong one'
expect {
eval_template_with_args("<%-| $x |-%><%= $x == correct %>", {})
}.to raise_error(/expects a value for parameter 'x'/)
end
it 'raises an error if unexpected arguments are given' do
scope['x'] = 'wrong one'
expect {
eval_template_with_args("<%-| $x |-%><%= $x == correct %>", 'x' => 'correct', 'y' => 'surplus')
}.to raise_error(/has no parameter named 'y'/)
end
end
context "when given an empty template" do
it "allows the template file to be empty" do
expect(eval_template("")).to eq("")
end
it "allows the template to have empty body after parameters" do
expect(eval_template_with_args("<%-|$x|%>", 'x'=>1)).to eq("")
end
end
it "renders a block expression" do
expect(eval_template_with_args("<%= { $y = $x $x + 1} %>", 'x' => 2)).to eq("3")
end
# although never a problem with epp
it "is not interfered with by having a variable named 'string' (#14093)" do
scope['string'] = "this output should not be seen"
expect(eval_template("some text that is static")).to eq("some text that is static")
end
it "has access to a variable named 'string' (#14093)" do
scope['string'] = "the string value"
expect(eval_template("string was: <%= $string %>")).to eq("string was: the string value")
end
context "when using Sensitive" do
it "returns an unwrapped sensitive value as a String" do
expect(eval_and_collect_notices(<<~END)).to eq(["opensesame"])
notice(inline_epp("<%= Sensitive('opensesame').unwrap %>"))
END
end
it "rewraps a sensitive value" do
# note entire result is redacted, not just sensitive part
expect(eval_and_collect_notices(<<~END)).to eq(["Sensitive [value redacted]"])
notice(inline_epp("This is sensitive <%= Sensitive('opensesame') %>"))
END
end
it "can be double wrapped" do
catalog = compile_to_catalog(<<~END)
notify { 'title':
message => Sensitive(inline_epp("<%= Sensitive('opensesame') %>"))
}
END
expect(catalog.resource(:notify, 'title')['message']).to eq('opensesame')
end
end
def eval_template_with_args(content, args_hash)
epp_function.call(scope, content, args_hash)
end
def eval_template(content)
epp_function.call(scope, content)
end
def epp_function()
scope.compiler.loaders.public_environment_loader.load(:function, 'inline_epp')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/then_spec.rb | spec/unit/functions/then_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the then function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'calls a lambda passing one argument' do
expect(compile_to_catalog("then(testing) |$x| { notify { $x: } }")).to have_resource('Notify[testing]')
end
it 'produces what lambda returns if value is not undef' do
expect(compile_to_catalog("notify{ then(1) |$x| { testing }: }")).to have_resource('Notify[testing]')
end
it 'does not call lambda if argument is undef' do
expect(compile_to_catalog('then(undef) |$x| { notify { "failed": } }')).to_not have_resource('Notify[failed]')
end
it 'produces undef if given value is undef' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test-Undef-ing]')
notify{ "test-${type(then(undef) |$x| { testing })}-ing": }
SOURCE
end
it 'errors when lambda wants too many args' do
expect do
compile_to_catalog('then(1) |$x, $y| { }')
end.to raise_error(/'then' block expects 1 argument, got 2/m)
end
it 'errors when lambda wants too few args' do
expect do
compile_to_catalog('then(1) || { }')
end.to raise_error(/'then' block expects 1 argument, got none/m)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/camelcase_spec.rb | spec/unit/functions/camelcase_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the camelcase function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'replaces initial <char> and each _<char> with upper case version of the char' do
expect(compile_to_catalog("notify { 'abc_def'.camelcase: }")).to have_resource('Notify[AbcDef]')
end
it 'returns the value if Numeric' do
expect(compile_to_catalog("notify { String(42.camelcase == 42): }")).to have_resource('Notify[true]')
end
it 'performs camelcase of international UTF-8 characters' do
expect(compile_to_catalog("notify { 'åäö_äö'.camelcase: }")).to have_resource('Notify[ÅäöÄö]')
end
it 'returns capitalized version of each entry in an array' do
expect(compile_to_catalog("notify { String(['a_a', 'b_a', 'c_a'].camelcase == ['AA', 'BA', 'CA']): }")).to have_resource('Notify[true]')
end
it 'returns capitalized version of each entry in an Iterator' do
expect(compile_to_catalog("notify { String(['a_a', 'b_a', 'c_a'].reverse_each.camelcase == ['CA', 'BA', 'AA']): }")).to have_resource('Notify[true]')
end
it 'errors when given a a nested Array' do
expect { compile_to_catalog("['a', 'b', ['c']].camelcase")}.to raise_error(/'camelcase' parameter 'arg' expects a value of type Numeric, String, or Iterable/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/all_spec.rb | spec/unit/functions/all_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'shared_behaviours/iterative_functions'
describe 'the all method' do
include PuppetSpec::Compiler
context "should be callable as" do
it 'all on an array' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$n = $a.all |$v| { $v > 0 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'all on an array with index' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [0,2,4]
$n = $a.all |$i, $v| { $v == $i * 2 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'all on a hash selecting entries' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {0=>0,1=>2,2=>4}
$n = $a.all |$e| { $e[1] == $e[0]*2 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'all on a hash selecting key and value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {0=>0,1=>2,2=>4}
$n = $a.all |$k,$v| { $v == $k*2 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
end
context "produces a boolean" do
it 'true when boolean true is found' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.all |$v| { true }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'true when truthy is found' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.all |$v| { 42 }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "true")['ensure']).to eq('present')
end
it 'false when truthy is not found (all undef)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.all |$v| { undef }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "false")['ensure']).to eq('present')
end
it 'false when truthy is not found (all false)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [6,6,6]
$n = $a.all |$v| { false }
file { "$n": ensure => present }
MANIFEST
expect(catalog.resource(:file, "false")['ensure']).to eq('present')
end
end
it_should_behave_like 'all iterative functions argument checks', 'any'
it_should_behave_like 'all iterative functions hash handling', 'any'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/include_spec.rb | spec/unit/functions/include_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet/parser/functions'
require 'matchers/containment_matchers'
require 'matchers/resource'
require 'matchers/include_in_order'
require 'unit/functions/shared'
describe 'The "include" function' do
include PuppetSpec::Compiler
include ContainmentMatchers
include Matchers::Resource
before(:each) do
compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
@scope = Puppet::Parser::Scope.new(compiler)
end
it "includes a class" do
catalog = compile_to_catalog(<<-MANIFEST)
class included {
notify { "included": }
}
include included
MANIFEST
expect(catalog.classes).to include("included")
end
it "includes a class when using a fully qualified anchored name" do
catalog = compile_to_catalog(<<-MANIFEST)
class included {
notify { "included": }
}
include ::included
MANIFEST
expect(catalog.classes).to include("included")
end
it "includes multiple classes" do
catalog = compile_to_catalog(<<-MANIFEST)
class included {
notify { "included": }
}
class included_too {
notify { "included_too": }
}
include included, included_too
MANIFEST
expect(catalog.classes).to include("included")
expect(catalog.classes).to include("included_too")
end
it "includes multiple classes given as an array" do
catalog = compile_to_catalog(<<-MANIFEST)
class included {
notify { "included": }
}
class included_too {
notify { "included_too": }
}
include [included, included_too]
MANIFEST
expect(catalog.classes).to include("included")
expect(catalog.classes).to include("included_too")
end
it "flattens nested arrays" do
catalog = compile_to_catalog(<<-MANIFEST)
class included {
notify { "included": }
}
class included_too {
notify { "included_too": }
}
include [[[included], [[[included_too]]]]]
MANIFEST
expect(catalog.classes).to include("included")
expect(catalog.classes).to include("included_too")
end
it "raises an error if class does not exist" do
expect {
compile_to_catalog(<<-MANIFEST)
include the_god_in_your_religion
MANIFEST
}.to raise_error(Puppet::Error)
end
{ "''" => 'empty string',
'undef' => 'undef',
"['']" => 'empty string',
"[undef]" => 'undef'
}.each_pair do |value, name_kind|
it "raises an error if class is #{name_kind}" do
expect {
compile_to_catalog(<<-MANIFEST)
include #{value}
MANIFEST
}.to raise_error(/Cannot use #{name_kind}/)
end
end
it "does not contained the included class in the current class" do
catalog = compile_to_catalog(<<-MANIFEST)
class not_contained {
notify { "not_contained": }
}
class container {
include not_contained
}
include container
MANIFEST
expect(catalog).to_not contain_class("not_contained").in("container")
end
it 'produces an array with a single class references given a single argument' do
catalog = compile_to_catalog(<<-MANIFEST)
class a {
notify { "a": }
}
$x = include(a)
Array[Type[Class], 1, 1].assert_type($x)
notify { 'feedback': message => "$x" }
MANIFEST
feedback = catalog.resource("Notify", "feedback")
expect(feedback[:message]).to eql("[Class[a]]")
end
it 'produces an array with class references given multiple arguments' do
catalog = compile_to_catalog(<<-MANIFEST)
class a {
notify { "a": }
}
class b {
notify { "b": }
}
$x = include(a, b)
Array[Type[Class], 2, 2].assert_type($x)
notify { 'feedback': message => "$x" }
MANIFEST
feedback = catalog.resource("Notify", "feedback")
expect(feedback[:message]).to eql("[Class[a], Class[b]]")
end
it 'allows the result to be used in a relationship operation' do
catalog = compile_to_catalog(<<-MANIFEST)
class a {
notify { "a": }
}
class b {
notify { "b": }
}
notify { 'c': }
include(a, b) -> Notify[c]
MANIFEST
# Assert relationships are formed
expect(catalog.resource("Class", "a")[:before][0]).to eql('Notify[c]')
expect(catalog.resource("Class", "b")[:before][0]).to eql('Notify[c]')
end
it_should_behave_like 'all functions transforming relative to absolute names', :include
it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :include
it_should_behave_like 'an inclusion function, when --tasks is on,', :include
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/annotate_spec.rb | spec/unit/functions/annotate_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/compiler'
describe 'the annotate function' do
include PuppetSpec::Compiler
let(:annotation) { <<-PUPPET }
type MyAdapter = Object[{
parent => Annotation,
attributes => {
id => Integer,
value => String[1]
}
}]
PUPPET
let(:annotation2) { <<-PUPPET }
type MyAdapter2 = Object[{
parent => Annotation,
attributes => {
id => Integer,
value => String[1]
}
}]
PUPPET
context 'with object and hash arguments' do
it 'creates new annotation on object' do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
}]
$my_object = MyObject({})
MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value' })
notice(MyAdapter.annotate($my_object).value)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['annotation value'])
end
it 'forces creation of new annotation' do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
}]
$my_object = MyObject({})
MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value' })
notice(MyAdapter.annotate($my_object).value)
MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value 2' })
notice(MyAdapter.annotate($my_object).value)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['annotation value', 'annotation value 2'])
end
end
context 'with object and block arguments' do
it 'creates new annotation on object' do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
}]
$my_object = MyObject({})
MyAdapter.annotate($my_object) || { { 'id' => 2, 'value' => 'annotation value' } }
notice(MyAdapter.annotate($my_object).value)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['annotation value'])
end
it 'does not recreate annotation' do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
}]
$my_object = MyObject({})
MyAdapter.annotate($my_object) || {
notice('should call this');
{ 'id' => 2, 'value' => 'annotation value' }
}
MyAdapter.annotate($my_object) || {
notice('should not call this');
{ 'id' => 2, 'value' => 'annotation value 2' }
}
notice(MyAdapter.annotate($my_object).value)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['should call this', 'annotation value'])
end
end
it "with object and 'clear' arguments, clears and returns annotation" do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
}]
$my_object = MyObject({})
MyAdapter.annotate($my_object, { 'id' => 2, 'value' => 'annotation value' })
notice(MyAdapter.annotate($my_object, clear).value)
notice(MyAdapter.annotate($my_object) == undef)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['annotation value', 'true'])
end
context 'when object is an annotated Type' do
it 'finds annotation declared in the type' do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
annotations => {
MyAdapter => { 'id' => 2, 'value' => 'annotation value' }
}
}]
notice(MyAdapter.annotate(MyObject).value)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['annotation value'])
end
it 'fails attempts to clear a declared annotation' do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
annotations => {
MyAdapter => { 'id' => 2, 'value' => 'annotation value' }
}
}]
notice(MyAdapter.annotate(MyObject).value)
notice(MyAdapter.annotate(MyObject, clear).value)
PUPPET
expect { eval_and_collect_notices(code) }.to raise_error(/attempt to clear MyAdapter annotation declared on MyObject/)
end
it 'fails attempts to redefine a declared annotation' do
code = <<-PUPPET
#{annotation}
type MyObject = Object[{
annotations => {
MyAdapter => { 'id' => 2, 'value' => 'annotation value' }
}
}]
notice(MyAdapter.annotate(MyObject).value)
notice(MyAdapter.annotate(MyObject, { 'id' => 3, 'value' => 'some other value' }).value)
PUPPET
expect { eval_and_collect_notices(code) }.to raise_error(/attempt to redefine MyAdapter annotation declared on MyObject/)
end
it 'allows annotation that are not declared in the type' do
code = <<-PUPPET
#{annotation}
#{annotation2}
type MyObject = Object[{
annotations => {
MyAdapter => { 'id' => 2, 'value' => 'annotation value' }
}
}]
notice(MyAdapter.annotate(MyObject).value)
notice(MyAdapter2.annotate(MyObject, { 'id' => 3, 'value' => 'some other value' }).value)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['annotation value', 'some other value'])
end
end
it 'used on Pcore, can add multiple annotations an object' do
code = <<-PUPPET
#{annotation}
#{annotation2}
type MyObject = Object[{
}]
$my_object = Pcore.annotate(MyObject({}), {
MyAdapter => { 'id' => 2, 'value' => 'annotation value' },
MyAdapter2 => { 'id' => 3, 'value' => 'second annotation value' }
})
notice(MyAdapter.annotate($my_object).value)
notice(MyAdapter2.annotate($my_object).value)
PUPPET
expect(eval_and_collect_notices(code)).to eql(['annotation value', 'second annotation value'])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/binary_file_spec.rb | spec/unit/functions/binary_file_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
require 'puppet_spec/files'
describe 'the binary_file function' do
include PuppetSpec::Compiler
include Matchers::Resource
include PuppetSpec::Files
def with_file_content(content)
path = tmpfile('find-file-function')
file = File.new(path, 'wb')
file.sync = true
file.print content
yield path
end
it 'reads an existing absolute file' do
with_file_content('one') do |one|
# Note that Binary to String produced Base64 encoded version of 'one' which is 'b23l'
expect(compile_to_catalog("notify { String(binary_file('#{one}')):}")).to have_resource("Notify[b25l]")
end
end
it 'errors on non existing files' do
expect do
with_file_content('one') do |one|
compile_to_catalog("notify { binary_file('#{one}/nope'):}")
end
end.to raise_error(/The given file '.+\/nope' does not exist/)
end
it 'reads an existing file in a module' do
with_file_content('binary_data') do |name|
mod = double('module')
allow(mod).to receive(:file).with('myfile').and_return(name)
Puppet[:code] = "notify { String(binary_file('mymod/myfile')):}"
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
allow(compiler.environment).to receive(:module).with('mymod').and_return(mod)
# Note that the Binary to string produces Base64 encoded version of 'binary_data' which is 'YmluYXJ5X2RhdGE='
expect(compiler.compile().filter { |r| r.virtual? }).to have_resource("Notify[YmluYXJ5X2RhdGE=]")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/type_spec.rb | spec/unit/functions/type_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the type function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'produces the type of a given value with default detailed quality' do
expect(compile_to_catalog('notify { "${ type([2, 3.14]) }": }')).to have_resource(
'Notify[Tuple[Integer[2, 2], Float[3.14, 3.14]]]')
end
it 'produces the type of a give value with detailed quality when quality is given' do
expect(compile_to_catalog('notify { "${ type([2, 3.14], detailed) }": }')).to have_resource(
'Notify[Tuple[Integer[2, 2], Float[3.14, 3.14]]]')
end
it 'produces the type of a given value with reduced quality when quality is given' do
expect(compile_to_catalog('notify { "${ type([2, 3.14], reduced) }": }')).to have_resource(
'Notify[Array[Numeric, 2, 2]]')
end
it 'produces the type of a given value with generalized quality when quality is given' do
expect(compile_to_catalog('notify { "${ type([2, 3.14], generalized) }": }')).to have_resource(
'Notify[Array[Numeric]]')
end
it 'errors when given a fault inference quality' do
expect do
compile_to_catalog("notify { type([2, 4.14], gobbledygooked): }")
end.to raise_error(/expects a match for Enum\['detailed', 'generalized', 'reduced'\], got 'gobbledygooked'/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/with_spec.rb | spec/unit/functions/with_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the with function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'calls a lambda passing no arguments' do
expect(compile_to_catalog("with() || { notify { testing: } }")).to have_resource('Notify[testing]')
end
it 'calls a lambda passing a single argument' do
expect(compile_to_catalog('with(1) |$x| { notify { "testing$x": } }')).to have_resource('Notify[testing1]')
end
it 'calls a lambda passing more than one argument' do
expect(compile_to_catalog('with(1, 2) |*$x| { notify { "testing${x[0]}, ${x[1]}": } }')).to have_resource('Notify[testing1, 2]')
end
it 'passes a type reference to a lambda' do
expect(compile_to_catalog('notify { test: message => "data" } with(Notify[test]) |$x| { notify { "${x[message]}": } }')).to have_resource('Notify[data]')
end
it 'errors when not given enough arguments for the lambda' do
expect do
compile_to_catalog('with(1) |$x, $y| { }')
end.to raise_error(/Parameter \$y is required but no value was given/m)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/length_spec.rb | spec/unit/functions/length_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the length function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'for an array it' do
it 'returns 0 when empty' do
expect(compile_to_catalog("notify { String(length([])): }")).to have_resource('Notify[0]')
end
it 'returns number of elements when not empty' do
expect(compile_to_catalog("notify { String(length([1, 2, 3])): }")).to have_resource('Notify[3]')
end
end
context 'for a hash it' do
it 'returns 0 empty' do
expect(compile_to_catalog("notify { String(length({})): }")).to have_resource('Notify[0]')
end
it 'returns number of elements when not empty' do
expect(compile_to_catalog("notify { String(length({1=>1,2=>2})): }")).to have_resource('Notify[2]')
end
end
context 'for a string it' do
it 'returns 0 when empty' do
expect(compile_to_catalog("notify { String(length('')): }")).to have_resource('Notify[0]')
end
it 'returns number of characters when not empty' do
# note the multibyte characters - åäö each taking two bytes in UTF-8
expect(compile_to_catalog('notify { String(length("\u00e5\u00e4\u00f6")): }')).to have_resource('Notify[3]')
end
end
context 'for a binary it' do
it 'returns 0 when empty' do
expect(compile_to_catalog("notify { String(length(Binary(''))): }")).to have_resource('Notify[0]')
end
it 'returns number of bytes when not empty' do
expect(compile_to_catalog("notify { String(length(Binary('b25l'))): }")).to have_resource('Notify[3]')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/hiera_spec.rb | spec/unit/functions/hiera_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet/pops'
describe 'when calling' do
include PuppetSpec::Compiler
include PuppetSpec::Files
let(:global_dir) { tmpdir('global') }
let(:env_config) { {} }
let(:hiera_yaml) { <<-YAML.unindent }
---
:backends:
- yaml
- hieraspec
:yaml:
:datadir: #{global_dir}/hieradata
:hierarchy:
- first
- second
YAML
let(:hieradata_files) do
{
'first.yaml' => <<-YAML.unindent,
---
a: first a
class_name: "-- %{calling_class} --"
class_path: "-- %{calling_class_path} --"
module: "-- %{calling_module} --"
mod_name: "-- %{module_name} --"
database_user:
name: postgres
uid: 500
gid: 500
groups:
db: 520
b:
b1: first b1
b2: first b2
fbb:
- mod::foo
- mod::bar
- mod::baz
empty_array: []
nested_array:
first:
- 10
- 11
second:
- 21
- 22
dotted.key:
a: dotted.key a
b: dotted.key b
dotted.array:
- a
- b
YAML
'second.yaml' => <<-YAML.unindent,
---
a: second a
b:
b1: second b1
b3: second b3
YAML
'the_override.yaml' => <<-YAML.unindent
---
key: foo_result
YAML
}
end
let(:environment_files) do
{
'test' => {
'modules' => {
'mod' => {
'manifests' => {
'foo.pp' => <<-PUPPET.unindent,
class mod::foo {
notice(hiera('class_name'))
notice(hiera('class_path'))
notice(hiera('module'))
notice(hiera('mod_name'))
}
PUPPET
'bar.pp' => <<-PUPPET.unindent,
class mod::bar {}
PUPPET
'baz.pp' => <<-PUPPET.unindent
class mod::baz {}
PUPPET
},
'hiera.yaml' => <<-YAML.unindent,
---
version: 5
YAML
'data' => {
'common.yaml' => <<-YAML.unindent
mod::c: mod::c (from module)
YAML
}
}
}
}.merge(env_config)
}
end
let(:global_files) do
{
'hiera.yaml' => hiera_yaml,
'hieradata' => hieradata_files,
'environments' => environment_files
}
end
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
let(:env_dir) { File.join(global_dir, 'environments') }
let(:env) { Puppet::Node::Environment.create(:test, [File.join(env_dir, 'test', 'modules')]) }
let(:environments) { Puppet::Environments::Directories.new(env_dir, []) }
let(:node) { Puppet::Node.new('test_hiera', :environment => env) }
let(:compiler) { Puppet::Parser::Compiler.new(node) }
let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera') }
before(:all) do
$LOAD_PATH.unshift(File.join(my_fixture_dir))
end
after(:all) do
Hiera::Backend.send(:remove_const, :Hieraspec_backend) if Hiera::Backend.const_defined?(:Hieraspec_backend)
$LOAD_PATH.shift
end
before(:each) do
Puppet.settings[:codedir] = global_dir
Puppet.settings[:hiera_config] = File.join(global_dir, 'hiera.yaml')
end
around(:each) do |example|
dir_contained_in(global_dir, global_files)
Puppet.override(:environments => environments, :current_environment => env) do
example.run
end
end
def with_scope(code = 'undef')
result = nil
Puppet[:code] = 'undef'
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
compiler.compile do |catalog|
result = yield(compiler.topscope)
catalog
end
end
result
end
def func(*args, &block)
with_scope { |scope| the_func.call(scope, *args, &block) }
end
context 'hiera', :if => Puppet.features.hiera? do
it 'should require a key argument' do
expect { func([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/)
end
it 'should use the "first" merge strategy' do
expect(func('a')).to eql('first a')
end
it 'should allow lookup with quoted dotted key' do
expect(func("'dotted.key'")).to eql({'a' => 'dotted.key a', 'b' => 'dotted.key b'})
end
it 'should allow lookup with dotted key' do
expect(func('database_user.groups.db')).to eql(520)
end
it 'should not find data in module' do
expect(func('mod::c', 'default mod::c')).to eql('default mod::c')
end
it 'should propagate optional override' do
ovr = 'the_override'
expect(func('key', nil, ovr)).to eql('foo_result')
end
it 'backend data sources, including optional overrides, are propagated to custom backend' do
expect(func('datasources', nil, 'the_override')).to eql(['the_override', 'first', 'second'])
end
it 'a hiera v3 scope is used', :if => Puppet.features.hiera? do
expect(eval_and_collect_notices(<<-PUPPET, node)).to eql(['-- testing --', '-- mod::foo --', '-- mod/foo --', '-- mod --', '-- mod --'])
class testing () {
notice(hiera('class_name'))
}
include testing
include mod::foo
PUPPET
end
it 'should return default value nil when key is not found' do
expect(func('foo', nil)).to be_nil
end
it "should return default value '' when key is not found" do
expect(func('foo', '')).to eq('')
end
it 'should use default block' do
expect(func('foo') { |k| "default for key '#{k}'" }).to eql("default for key 'foo'")
end
it 'should propagate optional override when combined with default block' do
ovr = 'the_override'
with_scope do |scope|
expect(the_func.call(scope, 'key', ovr) { |k| "default for key '#{k}'" }).to eql('foo_result')
expect(the_func.call(scope, 'foo.bar', ovr) { |k| "default for key '#{k}'" }).to eql("default for key 'foo.bar'")
end
end
it 'should log deprecation errors' do
func('a')
expect(warnings).to include(/The function 'hiera' is deprecated in favor of using 'lookup'. See https:/)
end
context 'with environment with configured data provider' do
let(:env_config) {
{
'hiera.yaml' => <<-YAML.unindent,
---
version: 5
YAML
'data' => {
'common.yaml' => <<-YAML.unindent
---
a: a (from environment)
e: e (from environment)
YAML
}
}
}
it 'should find data globally' do
expect(func('a')).to eql('first a')
end
it 'should find data in the environment' do
expect(func('e')).to eql('e (from environment)')
end
it 'should find data in module' do
expect(func('mod::c')).to eql('mod::c (from module)')
end
end
it 'should not be disabled by data_binding_terminus setting' do
Puppet[:data_binding_terminus] = 'none'
expect(func('a')).to eql('first a')
end
end
context 'hiera_array', :if => Puppet.features.hiera? do
let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_array') }
it 'should require a key argument' do
expect { func([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/)
end
it 'should log deprecation errors' do
func('fbb')
expect(warnings).to include(/The function 'hiera_array' is deprecated in favor of using 'lookup'/)
end
it 'should use the array resolution_type' do
expect(func('fbb', {'fbb' => 'foo_result'})).to eql(%w[mod::foo mod::bar mod::baz])
end
it 'should allow lookup with quoted dotted key' do
expect(func("'dotted.array'")).to eql(['a', 'b'])
end
it 'should fail lookup with dotted key' do
expect{ func('nested_array.0.first') }.to raise_error(/Resolution type :array is illegal when accessing values using dotted keys. Offending key was 'nested_array.0.first'/)
end
it 'should use default block' do
expect(func('foo') { |k| ['key', k] }).to eql(%w[key foo])
end
end
context 'hiera_hash', :if => Puppet.features.hiera? do
let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_hash') }
it 'should require a key argument' do
expect { func([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/)
end
it 'should use the hash resolution_type' do
expect(func('b', {'b' => 'foo_result'})).to eql({ 'b1' => 'first b1', 'b2' => 'first b2', 'b3' => 'second b3'})
end
it 'should lookup and return a hash' do
expect(func('database_user')).to eql({ 'name' => 'postgres', 'uid' => 500, 'gid' => 500, 'groups' => { 'db' => 520 }})
end
it 'should allow lookup with quoted dotted key' do
expect(func("'dotted.key'")).to eql({'a' => 'dotted.key a', 'b' => 'dotted.key b'})
end
it 'should fail lookup with dotted key' do
expect{ func('database_user.groups') }.to raise_error(/Resolution type :hash is illegal when accessing values using dotted keys. Offending key was 'database_user.groups'/)
end
it 'should log deprecation errors' do
func('b')
expect(warnings).to include(/The function 'hiera_hash' is deprecated in favor of using 'lookup'. See https:/)
end
it 'should use default block' do
expect(func('foo') { |k| {'key' => k} }).to eql({'key' => 'foo'})
end
end
context 'hiera_include', :if => Puppet.features.hiera? do
let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_include') }
it 'should require a key argument' do
expect { func([]) }.to raise_error(ArgumentError)
end
it 'should raise a useful error when nil is returned' do
expect { func('badkey') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'badkey'/)
end
it 'should use the array resolution_type to include classes' do
expect(func('fbb').map { |c| c.class_name }).to eql(%w[mod::foo mod::bar mod::baz])
end
it 'should log deprecation errors' do
func('fbb')
expect(warnings).to include(/The function 'hiera_include' is deprecated in favor of using 'lookup'. See https:/)
end
it 'should not raise an error if the resulting hiera lookup returns an empty array' do
expect { func('empty_array') }.to_not raise_error
end
it 'should use default block array to include classes' do
expect(func('foo') { |k| ['mod::bar', "mod::#{k}"] }.map { |c| c.class_name }).to eql(%w[mod::bar mod::foo])
end
end
context 'with custom backend and merge_behavior declared in hiera.yaml', :if => Puppet.features.hiera? do
let(:merge_behavior) { 'deeper' }
let(:hiera_yaml) do
<<-YAML.unindent
---
:backends:
- yaml
- hieraspec
:yaml:
:datadir: #{global_dir}/hieradata
:hierarchy:
- common
- other
:merge_behavior: #{merge_behavior}
:deep_merge_options:
:unpack_arrays: ','
YAML
end
let(:global_files) do
{
'hiera.yaml' => hiera_yaml,
'hieradata' => {
'common.yaml' => <<-YAML.unindent,
da:
- da 0
- da 1
dm:
dm1:
dm11: value of dm11 (from common)
dm12: value of dm12 (from common)
dm2:
dm21: value of dm21 (from common)
hash:
array:
- x1,x2
array:
- x1,x2
YAML
'other.yaml' => <<-YAML.unindent,
da:
- da 2,da 3
dm:
dm1:
dm11: value of dm11 (from other)
dm13: value of dm13 (from other)
dm3:
dm31: value of dm31 (from other)
hash:
array:
- x3
- x4
array:
- x3
- x4
YAML
}
}
end
context 'hiera_hash' do
let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_hash') }
context "using 'deeper'" do
it 'declared merge_behavior is honored' do
expect(func('dm')).to eql({
'dm1' => {
'dm11' => 'value of dm11 (from common)',
'dm12' => 'value of dm12 (from common)',
'dm13' => 'value of dm13 (from other)'
},
'dm2' => {
'dm21' => 'value of dm21 (from common)'
},
'dm3' => {
'dm31' => 'value of dm31 (from other)'
}
})
end
it "merge behavior is propagated to a custom backend as 'hash'" do
expect(func('resolution_type')).to eql({ 'resolution_type' => 'hash' })
end
it 'fails on attempts to merge an array' do
expect {func('da')}.to raise_error(/expects a Hash value/)
end
it 'honors option :unpack_arrays: (unsupported by puppet)' do
expect(func('hash')).to eql({'array' => %w(x3 x4 x1 x2)})
end
end
context "using 'deep'" do
let(:merge_behavior) { 'deep' }
it 'honors option :unpack_arrays: (unsupported by puppet)' do
expect(func('hash')).to eql({'array' => %w(x1 x2 x3 x4)})
end
end
end
context 'hiera_array', :if => Puppet.features.hiera? do
let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera_array') }
it 'declared merge_behavior is ignored' do
expect(func('da')).to eql(['da 0', 'da 1', 'da 2,da 3'])
end
it "merge behavior is propagated to a custom backend as 'array'" do
expect(func('resolution_type')).to eql(['resolution_type', 'array'])
end
end
context 'hiera' do
let(:the_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'hiera') }
it 'declared merge_behavior is ignored' do
expect(func('da')).to eql(['da 0', 'da 1'])
end
it "no merge behavior is propagated to a custom backend" do
expect(func('resolution_type')).to eql('resolution_type=')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/unique_spec.rb | spec/unit/functions/unique_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the unique function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'produces the unique set of chars from a String such that' do
it 'same case is considered unique' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "abc")
notify{ 'test': message => 'abcbbcc'.unique }
SOURCE
end
it 'different case is not considered unique' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "abcABC")
notify{ 'test': message => 'abcAbbBccC'.unique }
SOURCE
end
it 'case independent matching can be performed with a lambda' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "abc")
notify{ 'test': message => 'abcAbbBccC'.unique |$x| { String($x, '%d') } }
SOURCE
end
it 'the first found value in the unique set is used' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, "AbC")
notify{ 'test': message => 'AbCAbbBccC'.unique |$x| { String($x, '%d') } }
SOURCE
end
end
context 'produces the unique set of values from an Array such that' do
it 'ruby equality is used to compute uniqueness by default' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['a', 'b', 'c', 'B', 'C'])
notify{ 'test': message => [a, b, c, a, 'B', 'C'].unique }
SOURCE
end
it 'accepts a lambda to perform the value to use for uniqueness' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['a', 'b', 'c'])
notify{ 'test': message => [a, b, c, a, 'B', 'C'].unique |$x| { String($x, '%d') }}
SOURCE
end
it 'the first found value in the unique set is used' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['A', 'b', 'C'])
notify{ 'test': message => ['A', b, 'C', a, 'B', 'c'].unique |$x| { String($x, '%d') }}
SOURCE
end
end
context 'produces the unique set of values from an Hash such that' do
it 'resulting keys and values in hash are arrays' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, {['a'] => [10], ['b']=>[20]})
notify{ 'test': message => {a => 10, b => 20}.unique }
SOURCE
end
it 'resulting keys contain all keys with same value' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, {['a', 'b'] => [10], ['c']=>[20]})
notify{ 'test': message => {a => 10, b => 10, c => 20}.unique }
SOURCE
end
it 'resulting values contain Ruby == unique set of values' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, {['a'] => [10], ['b', 'c']=>[11, 20]})
notify{ 'test': message => {a => 10, b => 11, c => 20}.unique |$x| { if $x > 10 {bigly} else { $x }}}
SOURCE
end
end
context 'produces the unique set of values from an Iterable' do
it 'such as reverse_each - in reverse order' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['B','b','a'])
notify{ 'test': message => ['a', 'b', 'B'].reverse_each.unique }
SOURCE
end
it 'such as Integer[1,5]' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, [1,2,3,4,5])
notify{ 'test': message => Integer[1,5].unique }
SOURCE
end
it 'such as the Integer 3' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, [0,1,2])
notify{ 'test': message => 3.unique }
SOURCE
end
it 'allows lambda to be used with Iterable' do
expect(compile_to_catalog(<<-SOURCE)).to have_resource('Notify[test]').with_parameter(:message, ['B','a'])
notify{ 'test': message => ['a', 'b', 'B'].reverse_each.unique |$x| { String($x, '%d') }}
SOURCE
end
end
it 'errors when given unsupported data type as input' do
expect do
compile_to_catalog(<<-SOURCE)
undef.unique
SOURCE
end.to raise_error(/expects an Iterable value, got Undef/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/capitalize_spec.rb | spec/unit/functions/capitalize_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the capitalize function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'returns initial char upper case version of a string' do
expect(compile_to_catalog("notify { 'abc'.capitalize: }")).to have_resource('Notify[Abc]')
end
it 'returns the value if Numeric' do
expect(compile_to_catalog("notify { String(42.capitalize == 42): }")).to have_resource('Notify[true]')
end
it 'performs capitalize of international UTF-8 characters' do
expect(compile_to_catalog("notify { 'åäö'.capitalize: }")).to have_resource('Notify[Åäö]')
end
it 'returns capitalized version of each entry in an array' do
expect(compile_to_catalog("notify { String(['aa', 'ba', 'ca'].capitalize == ['Aa', 'Ba', 'Ca']): }")).to have_resource('Notify[true]')
end
it 'returns capitalized version of each entry in an Iterator' do
expect(compile_to_catalog("notify { String(['aa', 'ba', 'ca'].reverse_each.capitalize == ['Ca', 'Ba', 'Aa']): }")).to have_resource('Notify[true]')
end
it 'errors when given a a nested Array' do
expect { compile_to_catalog("['a', 'b', ['c']].capitalize")}.to raise_error(/'capitalize' parameter 'arg' expects a value of type Numeric, String, or Iterable/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/chomp_spec.rb | spec/unit/functions/chomp_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the chomp function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'removes line endings CR LF from a string' do
expect(compile_to_catalog("notify { String(\"abc\r\n\".chomp == 'abc'): }")).to have_resource('Notify[true]')
end
it 'removes line ending CR from a string' do
expect(compile_to_catalog("notify { String(\"abc\r\".chomp == 'abc'): }")).to have_resource('Notify[true]')
end
it 'removes line ending LF from a string' do
expect(compile_to_catalog("notify { String(\"abc\n\".chomp == 'abc'): }")).to have_resource('Notify[true]')
end
it 'does not removes LF before CR line ending from a string' do
expect(compile_to_catalog("notify { String(\"abc\n\r\".chomp == \"abc\n\"): }")).to have_resource('Notify[true]')
end
it 'returns empty string for an empty string' do
expect(compile_to_catalog("notify { String(''.chomp == ''): }")).to have_resource('Notify[true]')
end
it 'returns the value if Numeric' do
expect(compile_to_catalog("notify { String(42.chomp == 42): }")).to have_resource('Notify[true]')
end
it 'returns chomped version of each entry in an array' do
expect(compile_to_catalog("notify { String([\"a\n\", \"b\n\", \"c\n\"].chomp == ['a', 'b', 'c']): }")).to have_resource('Notify[true]')
end
it 'returns chopped version of each entry in an Iterator' do
expect(compile_to_catalog("notify { String([\"a\n\", \"b\n\", \"c\n\"].reverse_each.chomp == ['c', 'b', 'a']): }")).to have_resource('Notify[true]')
end
it 'errors when given a a nested Array' do
expect { compile_to_catalog("['a', 'b', ['c']].chomp")}.to raise_error(/'chomp' parameter 'arg' expects a value of type Numeric, String, or Iterable/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/flatten_spec.rb | spec/unit/functions/flatten_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the flatten function' do
include PuppetSpec::Compiler
include Matchers::Resource
let(:array_fmt) { { 'format' => "%(a", 'separator'=>""} }
it 'returns flattened array of all its given arguments' do
expect(compile_to_catalog("notify { String([1,[2,[3]]].flatten, Array => #{array_fmt}): }")).to have_resource('Notify[(123)]')
end
it 'accepts a single non array value which results in it being wrapped in an array' do
expect(compile_to_catalog("notify { String(flatten(1), Array => #{array_fmt}): }")).to have_resource('Notify[(1)]')
end
it 'accepts a single array value - (which is a noop)' do
expect(compile_to_catalog("notify { String(flatten([1]), Array => #{array_fmt}): }")).to have_resource('Notify[(1)]')
end
it 'it does not flatten a hash - it is a value that gets wrapped' do
expect(compile_to_catalog("notify { String(flatten({a=>1}), Array => #{array_fmt}): }")).to have_resource("Notify[({'a' => 1})]")
end
it 'accepts mix of array and non array arguments and concatenates and flattens them' do
expect(compile_to_catalog("notify { String(flatten([1],2,[[3,4]]), Array => #{array_fmt}): }")).to have_resource('Notify[(1234)]')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/compare_spec.rb | spec/unit/functions/compare_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the compare function' do
include PuppetSpec::Compiler
include Matchers::Resource
{
[0, 1] => -1,
[1, 0] => 1,
[1, 1] => 0,
[0.0, 1.0] => -1,
[1.0, 0.0] => 1,
[1.0, 1.0] => 0,
[0.0, 1] => -1,
[1.0, 0] => 1,
[1.0, 1] => 0,
[0, 1.0] => -1,
[1, 0.0] => 1,
[1, 1.0] => 0,
}.each_pair do |values, expected|
it "compares numeric/numeric such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do
expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
{
['"a"', '"b"'] => -1,
['"b"', '"a"'] => 1,
['"b"', '"b"'] => 0,
['"A"', '"b"'] => -1,
['"B"', '"a"'] => 1,
['"B"', '"b"'] => 0,
}.each_pair do |values, expected|
it "compares String values by default such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do
expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
it "compares String values with third true arg such that compare(#{values[0]}, #{values[1]}, true) returns #{expected}" do
expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}, true) == #{expected}): }")).to have_resource("Notify[true]")
end
end
{
['"a"', '"b"'] => -1,
['"b"', '"a"'] => 1,
['"b"', '"b"'] => 0,
['"A"', '"b"'] => -1,
['"B"', '"a"'] => -1,
['"B"', '"b"'] => -1,
}.each_pair do |values, expected|
it "compares String values with third arg false such that compare(#{values[0]}, #{values[1]}, false) returns #{expected}" do
expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}, false) == #{expected}): }")).to have_resource("Notify[true]")
end
end
{
["Semver('1.0.0')", "Semver('2.0.0')"] => -1,
["Semver('2.0.0')", "Semver('1.0.0')"] => 1,
["Semver('2.0.0')", "Semver('2.0.0')"] => 0,
}.each_pair do |values, expected|
it "compares Semver values such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do
expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
{
["Timespan(1)", "Timespan(2)"] => -1,
["Timespan(2)", "Timespan(1)"] => 1,
["Timespan(1)", "Timespan(1)"] => 0,
["Timespan(1)", 2] => -1,
["Timespan(2)", 1] => 1,
["Timespan(1)", 1] => 0,
[1, "Timespan(2)"] => -1,
[2, "Timespan(1)"] => 1,
[1, "Timespan(1)"] => 0,
["Timestamp(1)", "Timestamp(2)"] => -1,
["Timestamp(2)", "Timestamp(1)"] => 1,
["Timestamp(1)", "Timestamp(1)"] => 0,
["Timestamp(1)", 2] => -1,
["Timestamp(2)", 1] => 1,
["Timestamp(1)", 1] => 0,
[1, "Timestamp(2)"] => -1,
[2, "Timestamp(1)"] => 1,
[1, "Timestamp(1)"] => 0,
}.each_pair do |values, expected|
it "compares time values such that compare(#{values[0]}, #{values[1]}) returns #{expected}" do
expect(compile_to_catalog("notify { String( compare(#{values[0]},#{values[1]}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
context "errors when" do
[ [true, false],
['/x/', '/x/'],
['undef', 'undef'],
['undef', 1],
[1, 'undef'],
[[1], [1]],
[{'a' => 1}, {'b' => 1}],
].each do |a, b|
it "given values of non comparable types #{a.class}, #{b.class}" do
expect { compile_to_catalog("compare(#{a},#{b})")}.to raise_error(/Non comparable type/)
end
end
[
[10, '"hello"'],
['"hello"', 10],
[10.0, '"hello"'],
['"hello"', 10.0],
['Timespan(1)', '"hello"'],
['Timestamp(1)', '"hello"'],
['Timespan(1)', 'Semver("1.2.3")'],
['Timestamp(1)', 'Semver("1.2.3")'],
].each do |a, b|
it "given values of comparable, but incompatible types #{a.class}, #{b.class}" do
expect { compile_to_catalog("compare(#{a},#{b})")}.to raise_error(/Can only compare values of the same type/)
end
end
[
[10, 10],
[10.0, 10],
['Timespan(1)', 'Timespan(1)'],
['Timestamp(1)', 'Timestamp(1)'],
['Semver("1.2.3")', 'Semver("1.2.3")'],
].each do |a, b|
it "given ignore case true when values are comparable, but not both being strings" do
expect { compile_to_catalog("compare(#{a},#{b}, true)")}.to raise_error(/can only be used when comparing strings/)
end
it "given ignore case false when values are comparable, but not both being strings" do
expect { compile_to_catalog("compare(#{a},#{b}, false)")}.to raise_error(/can only be used when comparing strings/)
end
end
it "given more than three arguments" do
expect { compile_to_catalog("compare('a','b', false, false)")}.to raise_error(/Accepts at most 3 arguments, got 4/)
end
end
# Error if not the same except Timestamp and Timespan that accepts Numeric on either side
# Error for non supported - Boolean, Regexp, etc
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/contain_spec.rb | spec/unit/functions/contain_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet/parser/functions'
require 'matchers/containment_matchers'
require 'matchers/resource'
require 'matchers/include_in_order'
require 'unit/functions/shared'
describe 'The "contain" function' do
include PuppetSpec::Compiler
include ContainmentMatchers
include Matchers::Resource
before(:each) do
compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("foo"))
@scope = Puppet::Parser::Scope.new(compiler)
end
it "includes the class" do
catalog = compile_to_catalog(<<-MANIFEST)
class contained {
notify { "contained": }
}
class container {
contain contained
}
include container
MANIFEST
expect(catalog.classes).to include("contained")
end
it "includes the class when using a fully qualified anchored name" do
catalog = compile_to_catalog(<<-MANIFEST)
class contained {
notify { "contained": }
}
class container {
contain ::contained
}
include container
MANIFEST
expect(catalog.classes).to include("contained")
end
it "ensures that the edge is with the correct class" do
catalog = compile_to_catalog(<<-MANIFEST)
class outer {
class named { }
contain outer::named
}
class named { }
include named
include outer
MANIFEST
expect(catalog).to have_resource("Class[Named]")
expect(catalog).to have_resource("Class[Outer]")
expect(catalog).to have_resource("Class[Outer::Named]")
expect(catalog).to contain_class("outer::named").in("outer")
end
it "makes the class contained in the current class" do
catalog = compile_to_catalog(<<-MANIFEST)
class contained {
notify { "contained": }
}
class container {
contain contained
}
include container
MANIFEST
expect(catalog).to contain_class("contained").in("container")
end
it "can contain multiple classes" do
catalog = compile_to_catalog(<<-MANIFEST)
class a {
notify { "a": }
}
class b {
notify { "b": }
}
class container {
contain a, b
}
include container
MANIFEST
expect(catalog).to contain_class("a").in("container")
expect(catalog).to contain_class("b").in("container")
end
context "when containing a class in multiple classes" do
it "creates a catalog with all containment edges" do
catalog = compile_to_catalog(<<-MANIFEST)
class contained {
notify { "contained": }
}
class container {
contain contained
}
class another {
contain contained
}
include container
include another
MANIFEST
expect(catalog).to contain_class("contained").in("container")
expect(catalog).to contain_class("contained").in("another")
end
it "and there are no dependencies applies successfully" do
manifest = <<-MANIFEST
class contained {
notify { "contained": }
}
class container {
contain contained
}
class another {
contain contained
}
include container
include another
MANIFEST
expect { apply_compiled_manifest(manifest) }.not_to raise_error
end
it "and there are explicit dependencies on the containing class causes a dependency cycle" do
manifest = <<-MANIFEST
class contained {
notify { "contained": }
}
class container {
contain contained
}
class another {
contain contained
}
include container
include another
Class["container"] -> Class["another"]
MANIFEST
expect { apply_compiled_manifest(manifest) }.to raise_error(
Puppet::Error,
/One or more resource dependency cycles detected in graph/
)
end
end
it "does not create duplicate edges" do
catalog = compile_to_catalog(<<-MANIFEST)
class contained {
notify { "contained": }
}
class container {
contain contained
contain contained
}
include container
MANIFEST
contained = catalog.resource("Class", "contained")
container = catalog.resource("Class", "container")
expect(catalog.edges_between(container, contained).count).to eq 1
end
context "when a containing class has a dependency order" do
it "the contained class is applied in that order" do
catalog = compile_to_relationship_graph(<<-MANIFEST)
class contained {
notify { "contained": }
}
class container {
contain contained
}
class first {
notify { "first": }
}
class last {
notify { "last": }
}
include container, first, last
Class["first"] -> Class["container"] -> Class["last"]
MANIFEST
expect(order_resources_traversed_in(catalog)).to include_in_order(
"Notify[first]", "Notify[contained]", "Notify[last]"
)
end
end
it 'produces an array with a single class references given a single argument' do
catalog = compile_to_catalog(<<-MANIFEST)
class a {
notify { "a": }
}
class container {
$x = contain(a)
Array[Type[Class], 1, 1].assert_type($x)
notify { 'feedback': message => "$x" }
}
include container
MANIFEST
feedback = catalog.resource("Notify", "feedback")
expect(feedback[:message]).to eql("[Class[a]]")
end
it 'produces an array with class references given multiple arguments' do
catalog = compile_to_catalog(<<-MANIFEST)
class a {
notify { "a": }
}
class b {
notify { "b": }
}
class container {
$x = contain(a, b)
Array[Type[Class], 2, 2].assert_type($x)
notify { 'feedback': message => "$x" }
}
include container
MANIFEST
feedback = catalog.resource("Notify", "feedback")
expect(feedback[:message]).to eql("[Class[a], Class[b]]")
end
it 'allows the result to be used in a relationship operation' do
catalog = compile_to_catalog(<<-MANIFEST)
class a {
notify { "a": }
}
class b {
notify { "b": }
}
notify { 'c': }
class container {
contain(a, b) -> Notify[c]
}
include container
MANIFEST
# Assert relationships are formed
expect(catalog.resource("Class", "a")[:before][0]).to eql('Notify[c]')
expect(catalog.resource("Class", "b")[:before][0]).to eql('Notify[c]')
end
it_should_behave_like 'all functions transforming relative to absolute names', :contain
it_should_behave_like 'an inclusion function, regardless of the type of class reference,', :contain
it_should_behave_like 'an inclusion function, when --tasks is on,', :contain
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/versioncmp_spec.rb | spec/unit/functions/versioncmp_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
describe "the versioncmp function" do
before(:each) do
loaders = Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))
Puppet.push_context({:loaders => loaders}, "test-examples")
end
after(:each) do
Puppet::pop_context()
end
def versioncmp(*args)
Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'versioncmp').call({}, *args)
end
let(:type_parser) { Puppet::Pops::Types::TypeParser.singleton }
it 'should raise an Error if there is less than 2 arguments' do
expect { versioncmp('a,b') }.to raise_error(/expects between 2 and 3 arguments, got 1/)
end
it 'should raise an Error if there is more than 3 arguments' do
expect { versioncmp('a,b','foo', false, 'bar') }.to raise_error(/expects between 2 and 3 arguments, got 4/)
end
it "should call Puppet::Util::Package.versioncmp (included in scope)" do
expect(Puppet::Util::Package).to receive(:versioncmp).with('1.2', '1.3', false).and_return(-1)
expect(versioncmp('1.2', '1.3')).to eq(-1)
end
context "when ignore_trailing_zeroes is true" do
it "should equate versions with 2 elements and dots but with unnecessary zero" do
expect(versioncmp("10.1.0", "10.1", true)).to eq(0)
end
it "should equate versions with 1 element and dot but with unnecessary zero" do
expect(versioncmp("11.0", "11", true)).to eq(0)
end
it "should equate versions with 1 element and dot but with unnecessary zeros" do
expect(versioncmp("11.00", "11", true)).to eq(0)
end
it "should equate versions with dots and iregular zeroes" do
expect(versioncmp("11.0.00", "11", true)).to eq(0)
end
it "should equate versions with dashes" do
expect(versioncmp("10.1-0", "10.1.0-0", true)).to eq(0)
end
it "should compare versions with dashes after normalization" do
expect(versioncmp("10.1-1", "10.1.0-0", true)).to eq(1)
end
it "should not normalize versions if zeros are not trailing" do
expect(versioncmp("1.1", "1.0.1", true)).to eq(1)
end
end
context "when ignore_trailing_zeroes is false" do
it "should not equate versions if zeros are not trailing" do
expect(versioncmp("1.1", "1.0.1")).to eq(1)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/abs_spec.rb | spec/unit/functions/abs_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the abs function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'for an integer' do
{ 0 => 0,
1 => 1,
-1 => 1 }.each_pair do |x, expected|
it "called as abs(#{x}) results in #{expected}" do
expect(compile_to_catalog("notify { String( abs(#{x}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'for an float' do
{ 0.0 => 0.0,
1.0 => 1.0,
-1.1 => 1.1 }.each_pair do |x, expected|
it "called as abs(#{x}) results in #{expected}" do
expect(compile_to_catalog("notify { String( abs(#{x}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'for a string' do
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
{ "0" => 0,
"1" => 1,
"-1" => 1,
"0.0" => 0.0,
"1.1" => 1.1,
"-1.1" => 1.1,
"0777" => 777,
"-0777" => 777,
}.each_pair do |x, expected|
it "called as abs('#{x}') results in #{expected} and deprecation warning" do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String( abs('#{x}') == #{expected}): }")).to have_resource("Notify[true]")
end
expect(warnings).to include(/auto conversion of .* is deprecated/)
end
end
['blue', '0xFF'].each do |x|
it "errors when the string is not a decimal integer '#{x}' (indirectly deprecated)" do
expect{ compile_to_catalog("abs('#{x}')") }.to raise_error(/was given non decimal string/)
end
end
['0.2.3', '1E+10'].each do |x|
it "errors when the string is not a supported decimal float '#{x}' (indirectly deprecated)" do
expect{ compile_to_catalog("abs('#{x}')") }.to raise_error(/was given non decimal string/)
end
end
end
[[1,2,3], {'a' => 10}].each do |x|
it "errors for a value of class #{x.class}" do
expect{ compile_to_catalog("abs(#{x})") }.to raise_error(/expects a value of type Numeric or String/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/logging_spec.rb | spec/unit/functions/logging_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe 'the log function' do
include PuppetSpec::Compiler
def collect_logs(code)
Puppet[:code] = code
Puppet[:environment_timeout] = 10
node = Puppet::Node.new('logtest')
compiler = Puppet::Parser::Compiler.new(node)
node.environment.check_for_reparse
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
compiler.compile
end
logs
end
def expect_log(code, log_level, message)
logs = collect_logs(code)
# There's a chance that additional messages could have been
# added during code compilation like debug messages from
# Facter. This happened on Appveyor when the Appveyor image
# failed to resolve the domain fact. Since these messages are
# not relevant to our test, and since they can (possibly) be
# injected at any location in our logs array, it is good enough
# to assert that our desired log _is_ included in the logs array
# instead of trying to figure out _where_ it is included.
expect(logs).to include(satisfy { |log| log.level == log_level && log.message == message })
end
before(:each) do
Puppet[:log_level] = 'debug'
end
Puppet::Util::Log.levels.each do |level|
context "for log level '#{level}'" do
it 'can be called' do
expect_log("#{level.to_s}('yay')", level, 'yay')
end
it 'joins multiple arguments using space' do
# Not using the evaluator would result in yay {"a"=>"b", "c"=>"d"}
expect_log("#{level.to_s}('a', 'b', 3)", level, 'a b 3')
end
it 'uses the evaluator to format output' do
# Not using the evaluator would result in yay {"a"=>"b", "c"=>"d"}
expect_log("#{level.to_s}('yay', {a => b, c => d})", level, 'yay {a => b, c => d}')
end
it 'returns undef value' do
logs = collect_logs("notice(type(#{level.to_s}('yay')))")
expect(logs.size).to eql(2)
expect(logs[1].level).to eql(:notice)
expect(logs[1].message).to eql('Undef')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/ceiling_spec.rb | spec/unit/functions/ceiling_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the ceiling function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'for an integer' do
[ 0, 1, -1].each do |x|
it "called as ceiling(#{x}) results in the same value" do
expect(compile_to_catalog("notify { String( ceiling(#{x}) == #{x}): }")).to have_resource("Notify[true]")
end
end
end
context 'for a float' do
{
0.0 => 0,
1.1 => 2,
-1.1 => -1,
}.each_pair do |x, expected|
it "called as ceiling(#{x}) results in #{expected}" do
expect(compile_to_catalog("notify { String( ceiling(#{x}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
end
context 'for a string' do
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
{ "0" => 0,
"1" => 1,
"-1" => -1,
"0.0" => 0,
"1.1" => 2,
"-1.1" => -1,
"0777" => 777,
"-0777" => -777,
"0xFF" => 0xFF,
}.each_pair do |x, expected|
it "called as ceiling('#{x}') results in #{expected} and a deprecation warning" do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String( ceiling('#{x}') == #{expected}): }")).to have_resource("Notify[true]")
end
expect(warnings).to include(/auto conversion of .* is deprecated/)
end
end
['blue', '0.2.3'].each do |x|
it "errors as the string '#{x}' cannot be converted to a float" do
expect{ compile_to_catalog("ceiling('#{x}')") }.to raise_error(/cannot convert given value to a floating point value/)
end
end
end
[[1,2,3], {'a' => 10}].each do |x|
it "errors for a value of class #{x.class}" do
expect{ compile_to_catalog("ceiling(#{x})") }.to raise_error(/expects a value of type Numeric or String/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/map_spec.rb | spec/unit/functions/map_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
require 'shared_behaviours/iterative_functions'
describe 'the map method can' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'map on an array (multiplying each value by 2)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$a.map |$x|{ $x*2}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_4]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present')
end
it 'map on an enumerable type (multiplying each value by 2)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = Integer[1,3]
$a.map |$x|{ $x*2}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_4]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present')
end
it 'map on an integer (multiply each by 3)' do
catalog = compile_to_catalog(<<-MANIFEST)
3.map |$x|{ $x*3}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_0]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present')
end
it 'map on a string' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {a=>x, b=>y}
"ab".map |$x|{$a[$x]}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_x]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_y]").with_parameter(:ensure, 'present')
end
it 'map on an array (multiplying value by 10 in even index position)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$a.map |$i, $x|{ if $i % 2 == 0 {$x} else {$x*10}}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_20]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present')
end
it 'map on a hash selecting keys' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.map |$x|{ $x[0]}.each |$k|{
file { "/file_$k": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_a]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_b]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_c]").with_parameter(:ensure, 'present')
end
it 'map on a hash selecting keys - using two block parameters' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.map |$k,$v|{ file { "/file_$k": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_a]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_b]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_c]").with_parameter(:ensure, 'present')
end
it 'map on a hash using captures-last parameter' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>present,'b'=>absent,'c'=>present}
$a.map |*$kv|{ file { "/file_${kv[0]}": ensure => $kv[1] } }
MANIFEST
expect(catalog).to have_resource("File[/file_a]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_b]").with_parameter(:ensure, 'absent')
expect(catalog).to have_resource("File[/file_c]").with_parameter(:ensure, 'present')
end
it 'each on a hash selecting value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.map |$x|{ $x[1]}.each |$k|{ file { "/file_$k": ensure => present } }
MANIFEST
expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present')
end
it 'each on a hash selecting value - using two block parameters' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'a'=>1,'b'=>2,'c'=>3}
$a.map |$k,$v|{ file { "/file_$v": ensure => present } }
MANIFEST
expect(catalog).to have_resource("File[/file_1]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_2]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present')
end
context "handles data type corner cases" do
it "map gets values that are false" do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [false,false]
$a.map |$x| { $x }.each |$i, $v| {
file { "/file_$i.$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_0.false]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_1.false]").with_parameter(:ensure, 'present')
end
it "map gets values that are nil" do
Puppet::Parser::Functions.newfunction(:nil_array, :type => :rvalue) do |args|
[nil]
end
catalog = compile_to_catalog(<<-MANIFEST)
$a = nil_array()
$a.map |$x| { $x }.each |$i, $v| {
file { "/file_$i.$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_0.]").with_parameter(:ensure, 'present')
end
end
it_should_behave_like 'all iterative functions argument checks', 'map'
it_should_behave_like 'all iterative functions hash handling', 'map'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/find_file_spec.rb | spec/unit/functions/find_file_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
require 'puppet_spec/files'
describe 'the find_file function' do
include PuppetSpec::Compiler
include Matchers::Resource
include PuppetSpec::Files
def with_file_content(content)
path = tmpfile('find-file-function')
file = File.new(path, 'wb')
file.sync = true
file.print content
yield path
end
it 'finds an existing absolute file when given arguments individually' do
with_file_content('one') do |one|
with_file_content('two') do |two|
expect(compile_to_catalog("notify { find_file('#{one}', '#{two}'):}")).to have_resource("Notify[#{one}]")
end
end
end
it 'skips non existing files' do
with_file_content('one') do |one|
with_file_content('two') do |two|
expect(compile_to_catalog("notify { find_file('#{one}/nope', '#{two}'):}")).to have_resource("Notify[#{two}]")
end
end
end
it 'accepts arguments given as an array' do
with_file_content('one') do |one|
with_file_content('two') do |two|
expect(compile_to_catalog("notify { find_file(['#{one}', '#{two}']):}")).to have_resource("Notify[#{one}]")
end
end
end
it 'finds an existing file in a module' do
with_file_content('file content') do |name|
mod = double('module')
allow(mod).to receive(:file).with('myfile').and_return(name)
Puppet[:code] = "notify { find_file('mymod/myfile'):}"
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
allow(compiler.environment).to receive(:module).with('mymod').and_return(mod)
expect(compiler.compile().filter { |r| r.virtual? }).to have_resource("Notify[#{name}]")
end
end
it 'returns undef when none of the paths were found' do
mod = double('module')
allow(mod).to receive(:file).with('myfile').and_return(nil)
Puppet[:code] = "notify { String(type(find_file('mymod/myfile', 'nomod/nofile'))):}"
node = Puppet::Node.new('localhost')
compiler = Puppet::Parser::Compiler.new(node)
# For a module that does not have the file
allow(compiler.environment).to receive(:module).with('mymod').and_return(mod)
# For a module that does not exist
allow(compiler.environment).to receive(:module).with('nomod').and_return(nil)
expect(compiler.compile().filter { |r| r.virtual? }).to have_resource("Notify[Undef]")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/sort_spec.rb | spec/unit/functions/sort_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the sort function' do
include PuppetSpec::Compiler
include Matchers::Resource
{
"'bac'" => "'abc'",
"'BaC'" => "'BCa'",
}.each_pair do |value, expected|
it "sorts characters in a string such that #{value}.sort results in #{expected}" do
expect(compile_to_catalog("notify { String( sort(#{value}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
{
"'bac'" => "'abc'",
"'BaC'" => "'aBC'",
}.each_pair do |value, expected|
it "accepts a lambda when sorting characters in a string such that #{value} results in #{expected}" do
expect(compile_to_catalog("notify { String( sort(#{value}) |$a,$b| { compare($a,$b) } == #{expected}): }")).to have_resource("Notify[true]")
end
end
{
['b', 'a', 'c'] => ['a', 'b', 'c'],
['B', 'a', 'C'] => ['B', 'C', 'a'],
}.each_pair do |value, expected|
it "sorts strings in an array such that #{value}.sort results in #{expected}" do
expect(compile_to_catalog("notify { String( sort(#{value}) == #{expected}): }")).to have_resource("Notify[true]")
end
end
{
['b', 'a', 'c'] => ['a', 'b', 'c'],
['B', 'a', 'C'] => ['a', 'B', 'C'],
}.each_pair do |value, expected|
it "accepts a lambda when sorting an array such that #{value} results in #{expected}" do
expect(compile_to_catalog("notify { String( sort(#{value}) |$a,$b| { compare($a,$b) } == #{expected}): }")).to have_resource("Notify[true]")
end
end
it 'errors if given a mix of data types' do
expect { compile_to_catalog("sort([1, 'a'])")}.to raise_error(/comparison .* failed/)
end
it 'returns empty string for empty string input' do
expect(compile_to_catalog("notify { String(sort('') == ''): }")).to have_resource("Notify[true]")
end
it 'returns empty string for empty string input' do
expect(compile_to_catalog("notify { String(sort([]) == []): }")).to have_resource("Notify[true]")
end
it 'can sort mixed data types when using a lambda' do
# source sorts Numeric before string and uses compare() for same data type
src = <<-SRC
notify{ String(sort(['b', 3, 'a', 2]) |$a, $b| {
case [$a, $b] {
[String, Numeric] : { 1 }
[Numeric, String] : { -1 }
default: { compare($a, $b) }
}
} == [2, 3,'a', 'b']):
}
SRC
expect(compile_to_catalog(src)).to have_resource("Notify[true]")
end
it 'errors if lambda does not accept 2 arguments' do
expect { compile_to_catalog("sort([1, 'a']) || { }")}.to raise_error(/block expects 2 arguments/)
expect { compile_to_catalog("sort([1, 'a']) |$x| { }")}.to raise_error(/block expects 2 arguments/)
expect { compile_to_catalog("sort([1, 'a']) |$x,$y, $z| { }")}.to raise_error(/block expects 2 arguments/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/reverse_each_spec.rb | spec/unit/functions/reverse_each_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'shared_behaviours/iterative_functions'
describe 'the reverse_each function' do
include PuppetSpec::Compiler
it 'raises an error when given a type that cannot be iterated' do
expect do
compile_to_catalog(<<-MANIFEST)
3.14.reverse_each |$v| { }
MANIFEST
end.to raise_error(Puppet::Error, /expects an Iterable value, got Float/)
end
it 'raises an error when called with more than one argument and without a block' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].reverse_each(1)
MANIFEST
end.to raise_error(Puppet::Error, /expects 1 argument, got 2/)
end
it 'raises an error when called with more than one argument and a block' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].reverse_each(1) |$v| { }
MANIFEST
end.to raise_error(Puppet::Error, /expects 1 argument, got 2/)
end
it 'raises an error when called with a block with too many required parameters' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].reverse_each() |$v1, $v2| { }
MANIFEST
end.to raise_error(Puppet::Error, /block expects 1 argument, got 2/)
end
it 'raises an error when called with a block with too few parameters' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].reverse_each() | | { }
MANIFEST
end.to raise_error(Puppet::Error, /block expects 1 argument, got none/)
end
it 'does not raise an error when called with a block with too many but optional arguments' do
expect do
compile_to_catalog(<<-MANIFEST)
[1].reverse_each() |$v1, $v2=extra| { }
MANIFEST
end.to_not raise_error
end
it 'returns an Undef when called with a block' do
expect do
compile_to_catalog(<<-MANIFEST)
assert_type(Undef, [1].reverse_each |$x| { $x })
MANIFEST
end.not_to raise_error
end
it 'returns an Iterable when called without a block' do
expect do
compile_to_catalog(<<-MANIFEST)
assert_type(Iterable, [1].reverse_each)
MANIFEST
end.not_to raise_error
end
it 'should produce "times" interval of integer in reverse' do
expect(eval_and_collect_notices('5.reverse_each |$x| { notice($x) }')).to eq(['4', '3', '2', '1', '0'])
end
it 'should produce range Integer[5,8] in reverse' do
expect(eval_and_collect_notices('Integer[5,8].reverse_each |$x| { notice($x) }')).to eq(['8', '7', '6', '5'])
end
it 'should produce the choices of [first,second,third] in reverse' do
expect(eval_and_collect_notices('[first,second,third].reverse_each |$x| { notice($x) }')).to eq(%w(third second first))
end
it 'should produce the choices of {first => 1,second => 2,third => 3} in reverse' do
expect(eval_and_collect_notices('{first => 1,second => 2,third => 3}.reverse_each |$t| { notice($t[0]) }')).to eq(%w(third second first))
end
it 'should produce the choices of Enum[first,second,third] in reverse' do
expect(eval_and_collect_notices('Enum[first,second,third].reverse_each |$x| { notice($x) }')).to eq(%w(third second first))
end
it 'should produce nth element in reverse of range Integer[5,20] when chained after a step' do
expect(eval_and_collect_notices('Integer[5,20].step(4).reverse_each |$x| { notice($x) }')
).to eq(['17', '13', '9', '5'])
end
it 'should produce nth element in reverse of times 5 when chained after a step' do
expect(eval_and_collect_notices('5.step(2).reverse_each |$x| { notice($x) }')).to eq(['4', '2', '0'])
end
it 'should produce nth element in reverse of range Integer[5,20] when chained after a step' do
expect(eval_and_collect_notices(
'[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20].step(4).reverse_each |$x| { notice($x) }')
).to eq(['17', '13', '9', '5'])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/scanf_spec.rb | spec/unit/functions/scanf_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the scanf function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'scans a value and returns an array' do
expect(compile_to_catalog("$x = '42'.scanf('%i')[0] + 1; notify { \"test$x\": }")).to have_resource('Notify[test43]')
end
it 'scans a value and returns result of a code block' do
expect(compile_to_catalog("$x = '42'.scanf('%i')|$x|{$x[0]} + 1; notify { \"test$x\": }")).to have_resource('Notify[test43]')
end
it 'returns empty array if nothing was scanned' do
expect(compile_to_catalog("$x = 'no'.scanf('%i')[0]; notify { \"test${x}test\": }")).to have_resource('Notify[testtest]')
end
it 'produces result up to first unsuccessful scan' do
expect(compile_to_catalog("$x = '42 no'.scanf('%i'); notify { \"test${x[0]}${x[1]}test\": }")).to have_resource('Notify[test42test]')
end
it 'errors when not given enough arguments' do
expect do
compile_to_catalog("'42'.scanf()")
end.to raise_error(/'scanf' expects 2 arguments, got 1/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/rstrip_spec.rb | spec/unit/functions/rstrip_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the rstrip function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'removes trailing whitepsace' do
expect(compile_to_catalog("notify { String(\" abc\t\n \".rstrip == ' abc'): }")).to have_resource('Notify[true]')
end
it 'returns the value if Numeric' do
expect(compile_to_catalog("notify { String(42.rstrip == 42): }")).to have_resource('Notify[true]')
end
it 'returns rstripped version of each entry in an array' do
expect(compile_to_catalog("notify { String([' a ', ' b ', ' c '].rstrip == [' a', ' b', ' c']): }")).to have_resource('Notify[true]')
end
it 'returns rstripped version of each entry in an Iterator' do
expect(compile_to_catalog("notify { String(['a ', 'b ', 'c '].reverse_each.lstrip == ['c ', 'b ', 'a ']): }")).to have_resource('Notify[true]')
end
it 'errors when given a a nested Array' do
expect { compile_to_catalog("['a', 'b', ['c']].lstrip")}.to raise_error(/'lstrip' parameter 'arg' expects a value of type Numeric, String, or Iterable/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/group_by_spec.rb | spec/unit/functions/group_by_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the group_by function' do
include PuppetSpec::Compiler
include Matchers::Resource
context 'for an array' do
it 'groups by item' do
manifest = "notify { String(group_by([a, b, ab]) |$s| { $s.length }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[{1 => ['a', 'b'], 2 => ['ab']}]")
end
it 'groups by index, item' do
manifest = "notify { String(group_by([a, b, ab]) |$i, $s| { $i%2 + $s.length }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[{1 => ['a'], 2 => ['b', 'ab']}]")
end
end
context 'for a hash' do
it 'groups by key-value pair' do
manifest = "notify { String(group_by(a => [1, 2], b => [1]) |$kv| { $kv[1].length }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[{2 => [['a', [1, 2]]], 1 => [['b', [1]]]}]")
end
it 'groups by key, value' do
manifest = "notify { String(group_by(a => [1, 2], b => [1]) |$k, $v| { $v.length }): }"
expect(compile_to_catalog(manifest)).to have_resource("Notify[{2 => [['a', [1, 2]]], 1 => [['b', [1]]]}]")
end
end
context 'for a string' do
it 'fails' do
manifest = "notify { String(group_by('something') |$s| { $s.length }): }"
expect { compile_to_catalog(manifest) }.to raise_error(Puppet::PreformattedError)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/chop_spec.rb | spec/unit/functions/chop_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the chop function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'removes last character in a string' do
expect(compile_to_catalog("notify { String('abc'.chop == 'ab'): }")).to have_resource('Notify[true]')
end
it 'returns empty string for an empty string' do
expect(compile_to_catalog("notify { String(''.chop == ''): }")).to have_resource('Notify[true]')
end
it 'removes both CR LF if both are the last characters in a string' do
expect(compile_to_catalog("notify { String(\"abc\r\n\".chop == 'abc'): }")).to have_resource('Notify[true]')
end
it 'returns the value if Numeric' do
expect(compile_to_catalog("notify { String(42.chop == 42): }")).to have_resource('Notify[true]')
end
it 'returns chopped version of each entry in an array' do
expect(compile_to_catalog("notify { String(['aa', 'ba', 'ca'].chop == ['a', 'b', 'c']): }")).to have_resource('Notify[true]')
end
it 'returns chopped version of each entry in an Iterator' do
expect(compile_to_catalog("notify { String(['aa', 'bb', 'cc'].reverse_each.chop == ['c', 'b', 'a']): }")).to have_resource('Notify[true]')
end
it 'errors when given a a nested Array' do
expect { compile_to_catalog("['a', 'b', ['c']].chop")}.to raise_error(/'chop' parameter 'arg' expects a value of type Numeric, String, or Iterable/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/assert_type_spec.rb | spec/unit/functions/assert_type_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
require 'puppet_spec/compiler'
describe 'the assert_type function' do
include PuppetSpec::Compiler
after(:all) { Puppet::Pops::Loaders.clear }
let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) }
let(:func) { loaders.puppet_system_loader.load(:function, 'assert_type') }
it 'asserts compliant type by returning the value' do
expect(func.call({}, type(String), 'hello world')).to eql('hello world')
end
it 'accepts type given as a String' do
expect(func.call({}, 'String', 'hello world')).to eql('hello world')
end
it 'asserts non compliant type by raising an error' do
expect do
func.call({}, type(Integer), 'hello world')
end.to raise_error(Puppet::Pops::Types::TypeAssertionError, /expects an Integer value, got String/)
end
it 'checks that first argument is a type' do
expect do
func.call({}, 10, 10)
end.to raise_error(ArgumentError, "The function 'assert_type' was called with arguments it does not accept. It expects one of:
(Type type, Any value, Callable[Type, Type] block?)
rejected: parameter 'type' expects a Type value, got Integer
(String type_string, Any value, Callable[Type, Type] block?)
rejected: parameter 'type_string' expects a String value, got Integer")
end
it 'allows the second arg to be undef/nil)' do
expect do
func.call({}, optional(String), nil)
end.to_not raise_error
end
it 'can be called with a callable that receives a specific type' do
expected, actual, actual2 = func.call({}, 'Optional[String]', 1) { |expctd, actul| [expctd, actul, actul] }
expect(expected.to_s).to eql('Optional[String]')
expect(actual.to_s).to eql('Integer[1, 1]')
expect(actual2.to_s).to eql('Integer[1, 1]')
end
def optional(type_ref)
Puppet::Pops::Types::TypeFactory.optional(type(type_ref))
end
def type(type_ref)
Puppet::Pops::Types::TypeFactory.type_of(type_ref)
end
it 'can validate a resource type' do
expect(eval_and_collect_notices("assert_type(Type[Resource], File['/tmp/test']) notice('ok')")).to eq(['ok'])
end
it 'can validate a type alias' do
code = <<-CODE
type UnprivilegedPort = Integer[1024,65537]
assert_type(UnprivilegedPort, 5432)
notice('ok')
CODE
expect(eval_and_collect_notices(code)).to eq(['ok'])
end
it 'can validate a type alias passed as a String' do
code = <<-CODE
type UnprivilegedPort = Integer[1024,65537]
assert_type('UnprivilegedPort', 5432)
notice('ok')
CODE
expect(eval_and_collect_notices(code)).to eq(['ok'])
end
it 'can validate and fail using a type alias' do
code = <<-CODE
type UnprivilegedPort = Integer[1024,65537]
assert_type(UnprivilegedPort, 345)
notice('ok')
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error, /expects an UnprivilegedPort = Integer\[1024, 65537\] value, got Integer\[345, 345\]/)
end
it 'will use infer_set to report detailed information about complex mismatches' do
code = <<-CODE
assert_type(Struct[{a=>Integer,b=>Boolean}], {a=>hej,x=>s})
CODE
expect { eval_and_collect_notices(code) }.to raise_error(Puppet::Error,
/entry 'a' expects an Integer value, got String.*expects a value for key 'b'.*unrecognized key 'x'/m)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/defined_spec.rb | spec/unit/functions/defined_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
describe "the 'defined' function" do
after(:all) { Puppet::Pops::Loaders.clear }
# This loads the function once and makes it easy to call it
# It does not matter that it is not bound to the env used later since the function
# looks up everything via the scope that is given to it.
# The individual tests needs to have a fresh env/catalog set up
#
let(:loaders) { Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, [])) }
let(:func) { loaders.puppet_system_loader.load(:function, 'defined') }
before :each do
# A fresh environment is needed for each test since tests creates types and resources
environment = Puppet::Node::Environment.create(:testing, [])
@node = Puppet::Node.new('yaynode', :environment => environment)
@known_resource_types = environment.known_resource_types
@compiler = Puppet::Parser::Compiler.new(@node)
@scope = Puppet::Parser::Scope.new(@compiler)
end
def newclass(name)
@known_resource_types.add Puppet::Resource::Type.new(:hostclass, name)
end
def newdefine(name)
@known_resource_types.add Puppet::Resource::Type.new(:definition, name)
end
def newresource(type, title)
resource = Puppet::Resource.new(type, title)
@compiler.add_resource(@scope, resource)
resource
end
#--- CLASS
#
context 'can determine if a class' do
context 'is defined' do
it 'by using the class name in string form' do
newclass 'yayness'
expect(func.call(@scope, 'yayness')).to be_truthy
end
it 'by using a Type[Class[name]] type reference' do
name = 'yayness'
newclass name
class_type = Puppet::Pops::Types::TypeFactory.host_class(name)
type_type = Puppet::Pops::Types::TypeFactory.type_type(class_type)
expect(func.call(@scope, type_type)).to be_truthy
end
end
context 'is not defined' do
it 'by using the class name in string form' do
expect(func.call(@scope, 'yayness')).to be_falsey
end
it 'even if there is a define, by using a Type[Class[name]] type reference' do
name = 'yayness'
newdefine name
class_type = Puppet::Pops::Types::TypeFactory.host_class(name)
type_type = Puppet::Pops::Types::TypeFactory.type_type(class_type)
expect(func.call(@scope, type_type)).to be_falsey
end
end
context 'is defined and realized' do
it 'by using a Class[name] reference' do
name = 'cowabunga'
newclass name
newresource(:class, name)
class_type = Puppet::Pops::Types::TypeFactory.host_class(name)
expect(func.call(@scope, class_type)).to be_truthy
end
end
context 'is not realized' do
it '(although defined) by using a Class[name] reference' do
name = 'cowabunga'
newclass name
class_type = Puppet::Pops::Types::TypeFactory.host_class(name)
expect(func.call(@scope, class_type)).to be_falsey
end
it '(and not defined) by using a Class[name] reference' do
name = 'cowabunga'
class_type = Puppet::Pops::Types::TypeFactory.host_class(name)
expect(func.call(@scope, class_type)).to be_falsey
end
end
end
#---RESOURCE TYPE
#
context 'can determine if a resource type' do
context 'is defined' do
it 'by using the type name (of a built in type) in string form' do
expect(func.call(@scope, 'file')).to be_truthy
end
it 'by using the type name (of a resource type) in string form' do
newdefine 'yayness'
expect(func.call(@scope, 'yayness')).to be_truthy
end
it 'by using a File type reference (built in type)' do
resource_type = Puppet::Pops::Types::TypeFactory.resource('file')
type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type)
expect(func.call(@scope, type_type)).to be_truthy
end
it 'by using a Type[File] type reference' do
resource_type = Puppet::Pops::Types::TypeFactory.resource('file')
type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type)
expect(func.call(@scope, type_type)).to be_truthy
end
it 'by using a Resource[T] type reference (defined type)' do
name = 'yayness'
newdefine name
resource_type = Puppet::Pops::Types::TypeFactory.resource(name)
expect(func.call(@scope, resource_type)).to be_truthy
end
it 'by using a Type[Resource[T]] type reference (defined type)' do
name = 'yayness'
newdefine name
resource_type = Puppet::Pops::Types::TypeFactory.resource(name)
type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type)
expect(func.call(@scope, type_type)).to be_truthy
end
end
context 'is not defined' do
it 'by using the resource name in string form' do
expect(func.call(@scope, 'notatype')).to be_falsey
end
it 'even if there is a class with the same name, by using a Type[Resource[T]] type reference' do
name = 'yayness'
newclass name
resource_type = Puppet::Pops::Types::TypeFactory.resource(name)
type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type)
expect(func.call(@scope, type_type)).to be_falsey
end
end
context 'is defined and instance realized' do
it 'by using a Resource[T, title] reference for a built in type' do
type_name = 'file'
title = '/tmp/myfile'
newdefine type_name
newresource(type_name, title)
class_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title)
expect(func.call(@scope, class_type)).to be_truthy
end
it 'by using a Resource[T, title] reference for a defined type' do
type_name = 'meme'
title = 'cowabunga'
newdefine type_name
newresource(type_name, title)
class_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title)
expect(func.call(@scope, class_type)).to be_truthy
end
end
context 'is not realized' do
it '(although defined) by using a Resource[T, title] reference or Type[Resource[T, title]] reference' do
type_name = 'meme'
title = 'cowabunga'
newdefine type_name
resource_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title)
expect(func.call(@scope, resource_type)).to be_falsey
type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type)
expect(func.call(@scope, type_type)).to be_falsey
end
it '(and not defined) by using a Resource[T, title] reference or Type[Resource[T, title]] reference' do
type_name = 'meme'
title = 'cowabunga'
resource_type = Puppet::Pops::Types::TypeFactory.resource(type_name, title)
expect(func.call(@scope, resource_type)).to be_falsey
type_type = Puppet::Pops::Types::TypeFactory.type_type(resource_type)
expect(func.call(@scope, type_type)).to be_falsey
end
end
end
#---VARIABLES
#
context 'can determine if a variable' do
context 'is defined' do
it 'by giving the variable in string form' do
@scope['x'] = 'something'
expect(func.call(@scope, '$x')).to be_truthy
end
it 'by giving a :: prefixed variable in string form' do
@compiler.topscope['x'] = 'something'
expect(func.call(@scope, '$::x')).to be_truthy
end
it 'by giving a numeric variable in string form (when there is a match scope)' do
# with no match scope, there are no numeric variables defined
expect(func.call(@scope, '$0')).to be_falsey
expect(func.call(@scope, '$42')).to be_falsey
pattern = Regexp.new('.*')
@scope.new_match_scope(pattern.match('anything'))
# with a match scope, all numeric variables are set (the match defines if they have a value or not, but they are defined)
# even if their value is undef.
expect(func.call(@scope, '$0')).to be_truthy
expect(func.call(@scope, '$42')).to be_truthy
end
end
context 'is undefined' do
it 'by giving a :: prefixed or regular variable in string form' do
expect(func.call(@scope, '$x')).to be_falsey
expect(func.call(@scope, '$::x')).to be_falsey
end
end
end
context 'has any? semantics when given multiple arguments' do
it 'and one of the names is a defined user defined type' do
newdefine 'yayness'
expect(func.call(@scope, 'meh', 'yayness', 'booness')).to be_truthy
end
it 'and one of the names is a built type' do
expect(func.call(@scope, 'meh', 'file', 'booness')).to be_truthy
end
it 'and one of the names is a defined class' do
newclass 'yayness'
expect(func.call(@scope, 'meh', 'yayness', 'booness')).to be_truthy
end
it 'is true when at least one variable exists in scope' do
@scope['x'] = 'something'
expect(func.call(@scope, '$y', '$x', '$z')).to be_truthy
end
it 'is false when none of the names are defined' do
expect(func.call(@scope, 'meh', 'yayness', 'booness')).to be_falsey
end
end
it 'raises an argument error when asking if Resource type is defined' do
resource_type = Puppet::Pops::Types::TypeFactory.resource
expect { func.call(@scope, resource_type)}.to raise_error(ArgumentError, /reference to all.*type/)
end
it 'raises an argument error if you ask if Class is defined' do
class_type = Puppet::Pops::Types::TypeFactory.host_class
expect { func.call(@scope, class_type) }.to raise_error(ArgumentError, /reference to all.*class/)
end
it 'raises error if referencing undef' do
expect{func.call(@scope, nil)}.to raise_error(ArgumentError, /'defined' parameter 'vals' expects a value of type String, Type\[CatalogEntry\], or Type\[Type\], got Undef/)
end
it 'raises error if referencing a number' do
expect{func.call(@scope, 42)}.to raise_error(ArgumentError, /'defined' parameter 'vals' expects a value of type String, Type\[CatalogEntry\], or Type\[Type\], got Integer/)
end
it 'is false if referencing empty string' do
expect(func.call(@scope, '')).to be_falsey
end
it "is true if referencing 'main'" do
# mimic what compiler does with "main" in intial import
newclass ''
newresource :class, ''
expect(func.call(@scope, 'main')).to be_truthy
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/filter_spec.rb | spec/unit/functions/filter_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
require 'shared_behaviours/iterative_functions'
describe 'the filter method' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'should filter on an array (all berries)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = ['strawberry','blueberry','orange']
$a.filter |$x|{ $x =~ /berry$/}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_blueberry]").with_parameter(:ensure, 'present')
end
it 'should filter on enumerable type (Integer)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = Integer[1,10]
$a.filter |$x|{ $x % 3 == 0}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_3]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_9]").with_parameter(:ensure, 'present')
end
it 'should filter on enumerable type (Integer) using two args index/value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = Integer[10,18]
$a.filter |$i, $x|{ $i % 3 == 0}.each |$v|{
file { "/file_$v": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_10]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_13]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_16]").with_parameter(:ensure, 'present')
end
it 'should produce an array when acting on an array' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = ['strawberry','blueberry','orange']
$b = $a.filter |$x|{ $x =~ /berry$/}
file { "/file_${b[0]}": ensure => present }
file { "/file_${b[1]}": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_blueberry]").with_parameter(:ensure, 'present')
end
it 'can filter array using index and value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = ['strawberry','blueberry','orange']
$b = $a.filter |$index, $x|{ $index == 0 or $index ==2}
file { "/file_${b[0]}": ensure => present }
file { "/file_${b[1]}": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_orange]").with_parameter(:ensure, 'present')
end
it 'can filter array using index and value (using captures-rest)' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = ['strawberry','blueberry','orange']
$b = $a.filter |*$ix|{ $ix[0] == 0 or $ix[0] ==2}
file { "/file_${b[0]}": ensure => present }
file { "/file_${b[1]}": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_orange]").with_parameter(:ensure, 'present')
end
it 'filters on a hash (all berries) by key' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'strawberry'=>'red','blueberry'=>'blue','orange'=>'orange'}
$a.filter |$x|{ $x[0] =~ /berry$/}.each |$v|{
file { "/file_${v[0]}": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_strawberry]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_blueberry]").with_parameter(:ensure, 'present')
end
it 'should produce a hash when acting on a hash' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'strawberry'=>'red','blueberry'=>'blue','orange'=>'orange'}
$b = $a.filter |$x|{ $x[0] =~ /berry$/}
file { "/file_${b['strawberry']}": ensure => present }
file { "/file_${b['blueberry']}": ensure => present }
file { "/file_${b['orange']}": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_red]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_blue]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_]").with_parameter(:ensure, 'present')
end
it 'filters on a hash (all berries) by value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {'strawb'=>'red berry','blueb'=>'blue berry','orange'=>'orange fruit'}
$a.filter |$x|{ $x[1] =~ /berry$/}.each |$v|{
file { "/file_${v[0]}": ensure => present }
}
MANIFEST
expect(catalog).to have_resource("File[/file_strawb]").with_parameter(:ensure, 'present')
expect(catalog).to have_resource("File[/file_blueb]").with_parameter(:ensure, 'present')
end
it 'filters on an array will include elements for which the block returns truthy' do
catalog = compile_to_catalog(<<-MANIFEST)
$r = [1, 2, false, undef].filter |$v| { $v } == [1, 2]
notify { "eval_${$r}": }
MANIFEST
expect(catalog).to have_resource('Notify[eval_true]')
end
it 'filters on a hash will not include elements for which the block returns truthy' do
catalog = compile_to_catalog(<<-MANIFEST)
$r = {a => 1, b => 2, c => false, d=> undef}.filter |$k, $v| { $v } == {a => 1, b => 2}
notify { "eval_${$r}": }
MANIFEST
expect(catalog).to have_resource('Notify[eval_true]')
end
it_should_behave_like 'all iterative functions argument checks', 'filter'
it_should_behave_like 'all iterative functions hash handling', 'filter'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/reduce_spec.rb | spec/unit/functions/reduce_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
require 'shared_behaviours/iterative_functions'
describe 'the reduce method' do
include PuppetSpec::Compiler
include Matchers::Resource
before :each do
node = Puppet::Node.new("floppy", :environment => 'production')
@compiler = Puppet::Parser::Compiler.new(node)
@scope = Puppet::Parser::Scope.new(@compiler)
@topscope = @scope.compiler.topscope
@scope.parent = @topscope
end
context "should be callable as" do
it 'reduce on an array' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$b = $a.reduce |$memo, $x| { $memo + $x }
file { "/file_$b": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present')
end
it 'reduce on an array with captures rest in lambda' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$b = $a.reduce |*$mx| { $mx[0] + $mx[1] }
file { "/file_$b": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present')
end
it 'reduce on enumerable type' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = Integer[1,3]
$b = $a.reduce |$memo, $x| { $memo + $x }
file { "/file_$b": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_6]").with_parameter(:ensure, 'present')
end
it 'reduce on an array with start value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = [1,2,3]
$b = $a.reduce(4) |$memo, $x| { $memo + $x }
file { "/file_$b": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_10]").with_parameter(:ensure, 'present')
end
it 'reduce on a hash' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {a=>1, b=>2, c=>3}
$start = [ignored, 4]
$b = $a.reduce |$memo, $x| {['sum', $memo[1] + $x[1]] }
file { "/file_${$b[0]}_${$b[1]}": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_sum_6]").with_parameter(:ensure, 'present')
end
it 'reduce on a hash with start value' do
catalog = compile_to_catalog(<<-MANIFEST)
$a = {a=>1, b=>2, c=>3}
$start = ['ignored', 4]
$b = $a.reduce($start) |$memo, $x| { ['sum', $memo[1] + $x[1]] }
file { "/file_${$b[0]}_${$b[1]}": ensure => present }
MANIFEST
expect(catalog).to have_resource("File[/file_sum_10]").with_parameter(:ensure, 'present')
end
end
it_should_behave_like 'all iterative functions argument checks', 'reduce'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/empty_spec.rb | spec/unit/functions/empty_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the empty function' do
include PuppetSpec::Compiler
include Matchers::Resource
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
context 'for an array it' do
it 'returns true when empty' do
expect(compile_to_catalog("notify { String(empty([])): }")).to have_resource('Notify[true]')
end
it 'returns false when not empty' do
expect(compile_to_catalog("notify { String(empty([1])): }")).to have_resource('Notify[false]')
end
end
context 'for a hash it' do
it 'returns true when empty' do
expect(compile_to_catalog("notify { String(empty({})): }")).to have_resource('Notify[true]')
end
it 'returns false when not empty' do
expect(compile_to_catalog("notify { String(empty({1=>1})): }")).to have_resource('Notify[false]')
end
end
context 'for numeric values it' do
it 'always returns false for integer values (including 0)' do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String(empty(0)): }")).to have_resource('Notify[false]')
end
expect(warnings).to include(/Calling function empty\(\) with Numeric value is deprecated/)
end
it 'always returns false for float values (including 0.0)' do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String(empty(0.0)): }")).to have_resource('Notify[false]')
end
expect(warnings).to include(/Calling function empty\(\) with Numeric value is deprecated/)
end
end
context 'for a string it' do
it 'returns true when empty' do
expect(compile_to_catalog("notify { String(empty('')): }")).to have_resource('Notify[true]')
end
it 'returns false when not empty' do
expect(compile_to_catalog("notify { String(empty(' ')): }")).to have_resource('Notify[false]')
end
end
context 'for a sensitive string it' do
it 'returns true when empty' do
expect(compile_to_catalog("notify { String(empty(Sensitive(''))): }")).to have_resource('Notify[true]')
end
it 'returns false when not empty' do
expect(compile_to_catalog("notify { String(empty(Sensitive(' '))): }")).to have_resource('Notify[false]')
end
end
context 'for a binary it' do
it 'returns true when empty' do
expect(compile_to_catalog("notify { String(empty(Binary(''))): }")).to have_resource('Notify[true]')
end
it 'returns false when not empty' do
expect(compile_to_catalog("notify { String(empty(Binary('b25l'))): }")).to have_resource('Notify[false]')
end
end
context 'for undef it' do
it 'returns true without deprecation warning' do
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(compile_to_catalog("notify { String(empty(undef)): }")).to have_resource('Notify[true]')
end
expect(warnings).to_not include(/Calling function empty\(\) with Undef value is deprecated/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/split_spec.rb | spec/unit/functions/split_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
describe 'the split function' do
before(:each) do
loaders = Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))
Puppet.push_context({:loaders => loaders}, "test-examples")
end
after(:each) do
Puppet.pop_context()
end
def split(*args)
Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'split').call({}, *args)
end
let(:type_parser) { Puppet::Pops::Types::TypeParser.singleton }
it 'should raise an Error if there is less than 2 arguments' do
expect { split('a,b') }.to raise_error(/'split' expects 2 arguments, got 1/)
end
it 'should raise an Error if there is more than 2 arguments' do
expect { split('a,b','foo', 'bar') }.to raise_error(/'split' expects 2 arguments, got 3/)
end
it 'should raise a RegexpError if the regexp is malformed' do
expect { split('a,b',')') }.to raise_error(/unmatched close parenthesis/)
end
it 'should handle pattern in string form' do
expect(split('a,b',',')).to eql(['a', 'b'])
end
it 'should handle pattern in Regexp form' do
expect(split('a,b',/,/)).to eql(['a', 'b'])
end
it 'should handle pattern in Regexp Type form' do
expect(split('a,b',type_parser.parse('Regexp[/,/]'))).to eql(['a', 'b'])
end
it 'should handle pattern in Regexp Type form with empty regular expression' do
expect(split('ab',type_parser.parse('Regexp[//]'))).to eql(['a', 'b'])
end
it 'should handle pattern in Regexp Type form with missing regular expression' do
expect(split('ab',type_parser.parse('Regexp'))).to eql(['a', 'b'])
end
it 'should handle sensitive String' do
expect(split(Puppet::Pops::Types::PSensitiveType::Sensitive.new('a,b'), ',')).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive)
expect(split(Puppet::Pops::Types::PSensitiveType::Sensitive.new('a,b'), /,/)).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive)
expect(split(Puppet::Pops::Types::PSensitiveType::Sensitive.new('a,b'), type_parser.parse('Regexp[/,/]'))).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/values_spec.rb | spec/unit/functions/values_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the values function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'returns the values in the hash in the order they appear in a hash iteration' do
expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[1 & 2]')
$k = {'apples' => 1, 'oranges' => 2}.values
notify { "${k[0]} & ${k[1]}": }
SRC
end
it 'returns an empty array for an empty hash' do
expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[0]')
$v = {}.values.reduce(0) |$m, $v| { $m+1 }
notify { "${v}": }
SRC
end
it 'includes an undef value if one is present in the hash' do
expect(compile_to_catalog(<<-'SRC'.unindent)).to have_resource('Notify[Undef]')
$types = {a => undef}.values.map |$v| { $v.type }
notify { "${types[0]}": }
SRC
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/functions/upcase_spec.rb | spec/unit/functions/upcase_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'matchers/resource'
describe 'the upcase function' do
include PuppetSpec::Compiler
include Matchers::Resource
it 'returns upper case version of a string' do
expect(compile_to_catalog("notify { 'abc'.upcase: }")).to have_resource('Notify[ABC]')
end
it 'returns the value if Numeric' do
expect(compile_to_catalog("notify { String(42.upcase == 42): }")).to have_resource('Notify[true]')
end
it 'performs upcase of international UTF-8 characters' do
expect(compile_to_catalog("notify { 'åäö'.upcase: }")).to have_resource('Notify[ÅÄÖ]')
end
it 'returns upper case version of each entry in an array (recursively)' do
expect(compile_to_catalog("notify { String(['a', ['b', ['c']]].upcase == ['A', ['B', ['C']]]): }")).to have_resource('Notify[true]')
end
it 'returns upper case version of keys and values in a hash (recursively)' do
expect(compile_to_catalog("notify { String({'a'=>'b','c'=>{'d'=>'e'}}.upcase == {'A'=>'B', 'C'=>{'D'=>'E'}}): }")).to have_resource('Notify[true]')
end
it 'returns upper case version of keys and values in nested hash / array structure' do
expect(compile_to_catalog("notify { String({'a'=>['b'],'c'=>[{'d'=>'e'}]}.upcase == {'A'=>['B'],'C'=>[{'D'=>'E'}]}): }")).to have_resource('Notify[true]')
end
end
| ruby | Apache-2.0 | 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.